text
stringlengths 10
2.72M
|
|---|
package com.aditya.project.hateoas.controller;
import com.aditya.project.hateoas.model.Customer;
import com.aditya.project.hateoas.model.Order;
import com.aditya.project.hateoas.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.Link;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
@RestController
@RequestMapping(value = "/customers")
public class CustomerController {
@Autowired
private CustomerService customerService;
@GetMapping
public CollectionModel<Customer> findAll() {
List<Customer> customers = customerService.findAll();
for (Customer customer : customers) {
Link link = linkTo(CustomerController.class).slash(customer.getId()).withSelfRel();
customer.add(link);
if (customer.getOrders().size() > 0) {
customer.getOrders().forEach(order -> {
Link orderLink = linkTo(methodOn(OrderController.class).findById(order.getId())).withSelfRel();
order.add(orderLink);
});
}
}
Link link = linkTo(CustomerController.class).withSelfRel();
return CollectionModel.of(customers, link);
}
@GetMapping("/{id}")
public Customer findById(@PathVariable int id) {
Customer customer = customerService.findById(id);
if (customer.getOrders().size() > 0) {
customer.getOrders().forEach(order -> {
Link orderLink = linkTo(methodOn(OrderController.class).findById(order.getId())).withSelfRel();
order.add(orderLink);
});
}
Link link = linkTo(CustomerController.class).slash(customer.getId()).withSelfRel();
customer.add(link);
return customer;
}
@GetMapping("/{id}/orders")
public CollectionModel<Order> findOrdersByCustomerId(@PathVariable int id) {
List<Order> orders = customerService.findOrdersByCustomerId(id);
for (Order order : orders) {
Link link = linkTo(methodOn(OrderController.class).findById(order.getId())).withSelfRel();
order.add(link);
}
Link link = linkTo(methodOn(CustomerController.class).findOrdersByCustomerId(id)).withSelfRel();
return CollectionModel.of(orders, link);
}
@GetMapping("/{id}/orders/{orderId}")
public Order findOrderByCustomerIdAndOrderId(@PathVariable int id, @PathVariable int orderId) {
Order order = customerService.findOrderByCustomerIdAndOrderId(id, orderId);
Link link = linkTo(methodOn(OrderController.class).findById(orderId)).withSelfRel();
order.add(link);
return order;
}
}
|
package com.isystk.sample.common.dto;
import java.io.Serializable;
import org.apache.commons.lang3.StringUtils;
import org.seasar.doma.Domain;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.val;
@Domain(valueType = String.class, factoryMethod = "of")
@NoArgsConstructor
public class CommaSeparatedString implements Serializable {
private static final long serialVersionUID = -6864852815920199569L;
@Getter
String data;
/**
* ファクトリメソッド
*
* @param data
* @return
*/
public static CommaSeparatedString of(String data) {
val css = new CommaSeparatedString();
css.data = StringUtils.join(data, ",");
return css;
}
// ResultSet.getBytes(int)で取得された値がこのコンストラクタで設定される
CommaSeparatedString(String data) {
this.data = StringUtils.join(data, ",");
}
// PreparedStatement.setBytes(int, bytes)へ設定する値がこのメソッドから取得される
String getValue() {
return this.data;
}
}
|
package com.sudipatcp.string;
import java.util.HashMap;
import java.util.Set;
public class IntegerToRoman {
public String intToRoman(int A) {
HashMap<Integer, String> RomanDecimalVal = new HashMap<Integer, String>();
RomanDecimalVal.put(1, "I");
RomanDecimalVal.put(4, "IV");
RomanDecimalVal.put(5, "V");
RomanDecimalVal.put(9, "IX");
RomanDecimalVal.put(10, "X");
RomanDecimalVal.put(40, "XL");
RomanDecimalVal.put(50, "L");
RomanDecimalVal.put(90, "XC");
RomanDecimalVal.put(100, "C");
RomanDecimalVal.put(400,"CD");
RomanDecimalVal.put(500,"D");
RomanDecimalVal.put(900, "CM");
RomanDecimalVal.put(1000, "M");
StringBuilder sbd = new StringBuilder();
Set<Integer> list = RomanDecimalVal.keySet();
while(A > 0){
}
return null;
}
}
|
package com.sds.chocomuffin.molly.domain.surveyaggregate;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
public interface SurveyAggregateRepository extends ReactiveCrudRepository<SurveyAggregate, String> {
}
|
package fundamentos;
import java.util.Scanner;
public class Class12Bucles {
public static void main(String[] args) {
//DECLARAMOS UN BUCLE DE 1 a 5
for (int i = 1; i <= 5; i++) {
//INSTRUCCIONES
System.out.println("Contador: " + i);
}
//Podemos realizar el bucle para que
//tenga otro incremento si lo deseamos
// i+=NUMERO
for (int i = 1; i <= 20; i += 2) {
//IMPARES
System.out.println(i);
}
//DEBEMOS CAMBIAR LA CONDICION EN ALGUNO MOMENTO
//HACEMOS UN BUCLE DE 1 a 5 CON WHILE
//LA VARIABLE SE DECLARA FUERA DEL BUCLE
int numero = 1;
while (numero <= 5) {
//ACCIONES
//DEBEMOS HACER ALGUN CODIGO PARA SALIR DEL
//BUCLE, EN ESTE EJEMPLO, SUMAR VALOR AL NUMERO
System.out.println("While: " + numero);
numero += 1;
}
String dato = "hola";
if (dato == "hola") {
//NUNCA ENTRA AQUI
}
//PEDIREMOS AL USUARIO TEXTOS
//HASTA QUE ESCRIBA LA PALABRA STOP
Scanner teclado = new Scanner(System.in);
String respuesta = "";
System.out.println("Escriba stop para salir");
//while (respuesta.equals("stop") == false) {
while (!respuesta.equals("stop")) {
//INDICAMOS QUE ESCRIBA ALGO...
System.out.println("Introduzca una palabra: ");
//ALMACENAMOS LO QUE HA ESCRITO EL USUARIO
respuesta = teclado.nextLine();
System.out.println("Su respuesta es..." + respuesta);
}
System.out.println("Fin de programa");
}
}
|
package core;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import org.lwjgl.glfw.GLFWKeyCallback;
import events.Event;
import events.KeyEvent;
import events.Listener;
import events.KeyEvent.Priority;
import static org.lwjgl.glfw.GLFW.*;
public class KeyboardHandler extends GLFWKeyCallback{
public static boolean[] keys = new boolean[65536];
private static HashMap<Integer,HashMap<Integer,ArrayList<Listener>>> listeners = new HashMap<Integer,HashMap<Integer,ArrayList<Listener>>>();// HashMap<key, HashMap<Priority, Listener> >
@Override
public void invoke(long window, int key, int scancode, int action, int mods) {
if (keys[key] != (action!=GLFW_RELEASE)){//if key changed
new KeyEvent(key,action != GLFW_RELEASE).trigger();
}
keys[key] = action != GLFW_RELEASE;
}
public static boolean isKeyDown(int keycode) {
return keys[keycode];
}
public static void registerKeyListener(int keyNum, Listener l){
try{
Method m = l.getClass().getMethod("listen", Event.class);
ArrayList<Listener> existing = new ArrayList<Listener>();
int val;
if (m.isAnnotationPresent(Priority.class)){
val = m.getAnnotation(Priority.class).value().getPriority();
}else{
val = 0;
}
if (listeners.containsKey(keyNum)){
if (listeners.get(keyNum).containsKey(val)){
existing = listeners.get(keyNum).get(val);
}
}
existing.add(l);
if (!listeners.containsKey(keyNum)){
listeners.put(keyNum, new HashMap<Integer,ArrayList<Listener>>());
}
listeners.get(keyNum).put(val, existing);
}catch(NoSuchMethodException | SecurityException e){e.printStackTrace();}//not possible?
}
public static void unregisterKeyListener(int keyNum, Listener l){
try{
Method m = l.getClass().getMethod("listen", Event.class);
ArrayList<Listener> existing = new ArrayList<Listener>();
int val;
if (m.isAnnotationPresent(Priority.class)){
val = m.getAnnotation(Priority.class).value().getPriority();
}else{
val = 0;
}
if (listeners.containsKey(keyNum)){
if (listeners.get(keyNum).containsKey(val)){
existing = listeners.get(keyNum).get(val);
existing.remove(l);
listeners.get(keyNum).put(val, existing);
}
}
}catch(NoSuchMethodException | SecurityException e){e.printStackTrace();}//also not possible?
}
public static HashMap<Integer,HashMap<Integer,ArrayList<Listener>>> getKeyListeners(){
return listeners;
}
public static HashMap<Integer,ArrayList<Listener>> getKeyListeners(int key){
return listeners.get(key);
}
}
|
package com.sopra.rest;
public class FunkoPop
{
private int id;
private String name;
private String universe;
private boolean waterproof;
private double latitude;
private double longitude;
public FunkoPop()
{
}
public FunkoPop( int id, String name, String universe, boolean waterproof, double latitude, double longitude )
{
this.id = id;
this.name = name;
this.universe = universe;
this.waterproof = waterproof;
this.latitude = latitude;
this.longitude = longitude;
}
public String getName()
{
return name;
}
public void setName( String name )
{
this.name = name;
}
public String getUniverse()
{
return universe;
}
public void setUniverse( String universe )
{
this.universe = universe;
}
public boolean isWaterproof()
{
return waterproof;
}
public void setWaterproof( boolean waterproof )
{
this.waterproof = waterproof;
}
public int getId()
{
return id;
}
public void setId( int id )
{
this.id = id;
}
public double getLatitude()
{
return latitude;
}
public void setLatitude( double latitude )
{
this.latitude = latitude;
}
public double getLongitude()
{
return longitude;
}
public void setLongitude( double longitude )
{
this.longitude = longitude;
}
}
|
package ch02.ex02_07;
import static org.junit.Assert.*;
import org.junit.Test;
public class VehicleTest {
public long idNum;
public static long nextID = 0;
//idNumTest
@Test
public void testId() {
Vehicle car = new Vehicle();
assertEquals(0, (int)car.idNum);
Vehicle train = new Vehicle();
assertEquals(1, (int)train.idNum);
Vehicle airplane = new Vehicle();
assertEquals(2, (int)airplane.idNum);
}
//constructorTest
@Test
public void testConstructor() {
Vehicle car = new Vehicle("Mike");
assertEquals("Mike", car.owner);
Vehicle train = new Vehicle("Joe");
assertEquals("Joe", train.owner);
Vehicle airplane = new Vehicle("Nick");
assertEquals("Nick", airplane.owner);
}
}
|
package ithome.am.ithomenotsss.Adapters;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
import ithome.am.ithomenotsss.Activitys.ProfileActivity;
import ithome.am.ithomenotsss.Engine.Engine;
import ithome.am.ithomenotsss.Engine.Model;
import ithome.am.ithomenotsss.R;
public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.ViewHolder> {
Engine engine;
private List<Model> mPeopleList;
private Context mContext;
private RecyclerView mRecyclerV;
public RecycleViewAdapter(List<Model> myDataset, Context context, RecyclerView recyclerView) {
mPeopleList = myDataset;
mContext = context;
mRecyclerV = recyclerView;
}
@NonNull
@Override
public RecycleViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(
parent.getContext());
View v =
inflater.inflate(R.layout.single_row, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
final Model person = mPeopleList.get(position);
holder.personNameTxtV.setText("Name: " + person.getName());
holder.personOccupationTxtV.setText("Occupation: " + person.getOccupation());
Picasso.with(mContext).load(person.getImage()).placeholder(R.mipmap.ic_launcher).into(holder.personImageImgV);
//listen to single view layout click
holder.layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Choose option");
builder.setMessage("Update or delete user?");
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//go to update activity
goToUpdateActivity(person.getId());
}
});
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// PersonDBHelper dbHelper = new PersonDBHelper(mContext);
// dbHelper.deletePersonRecord(person.getId(), mContext);
engine=Engine.getInstance();
engine.getDbServices(mContext).deletePersonRecord(person.getId(),mContext);
mPeopleList.remove(position);
mRecyclerV.removeViewAt(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mPeopleList.size());
notifyDataSetChanged();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
});
}
private void goToUpdateActivity(long personId){
Intent goToUpdate = new Intent(mContext, ProfileActivity.class);
goToUpdate.putExtra("USER_ID", personId);
mContext.startActivity(goToUpdate);
}
@Override
public int getItemCount() {
return mPeopleList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView personNameTxtV;
//public TextView personAgeTxtV;
public TextView personOccupationTxtV;
public ImageView personImageImgV;
public View layout;
public ViewHolder(View v) {
super(v);
layout = v;
personNameTxtV = v.findViewById(R.id.name);
// personAgeTxtV = (TextView) v.findViewById(R.id.age);
personOccupationTxtV = v.findViewById(R.id.occupation);
personImageImgV = (ImageView) v.findViewById(R.id.image);
}
}
}
|
package com.relsulla.sample_data.driver;
import com.relsulla.sample_data.util.Util;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import com.relsulla.sample_data.mapreduce.CalculateMeasureMapper;
import com.relsulla.sample_data.mapreduce.CalculateMeasureReducer;
import java.net.URI;
/**
* Created by Bob on 2/9/2017.
*/
public class CalculateMeasure extends Configured implements Tool {
public static final String DIAGNOSIS_CODES_CACHE = "CalculateMeasure.diagnosisCodesTable";
public static final String COMORBIDITY_COLUMNS_CACHE = "CalculateMeasure.comorbidityColumnsTable";
public static final String MEASURE_COMORBIDITY_CACHE = "CalculateMeasure.measureComorbidity";
public static final String SELECTED_MEASURE = "CalculateMeasure.selectedMeasure";
public static void main(String[] args) throws Exception {
int rc = ToolRunner.run(new CalculateMeasure(), args);
System.exit(rc);
}
public int run(String[] args) throws Exception {
int rc = 0;
Configuration conf;
conf = getConf();
rc = runJob(conf,args[0],args[1],args[2],args[3],args[4], args[5],1);
return (rc);
}
private int runJob(Configuration conf
,String measure
,String inputPaths
,String diagnosisCodesTablePath
,String comorbidityColumnsTablePath
,String measureComorbidityPath
,String outPath
,int numReducers) {
int rc = 0;
Job job;
Path outputPath;
FileSystem fs;
Path diagnosisCodesTableCache;
Path comorbidityColumnsTableCache;
Path measureComorbidityCache;
String[] inputPathsParts;
try {
inputPathsParts = inputPaths.split(",");
conf.set(SELECTED_MEASURE,measure);
diagnosisCodesTableCache = new Path(diagnosisCodesTablePath);
conf.set(DIAGNOSIS_CODES_CACHE,diagnosisCodesTableCache.getName());
comorbidityColumnsTableCache = new Path(comorbidityColumnsTablePath);
conf.set(COMORBIDITY_COLUMNS_CACHE,comorbidityColumnsTableCache.getName());
measureComorbidityCache = new Path(measureComorbidityPath);
conf.set(MEASURE_COMORBIDITY_CACHE,measureComorbidityCache.getName());
job = Job.getInstance(conf, "Sample Data by Measure (" + measure + ")");
job.setJarByClass(getClass());
job.setMapperClass(CalculateMeasureMapper.class);
job.setReducerClass(CalculateMeasureReducer.class);
job.setNumReduceTasks(numReducers);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Text.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
for ( int idxInputFiles=0; idxInputFiles < inputPathsParts.length; idxInputFiles++ ) {
FileInputFormat.addInputPath(job,new Path(inputPathsParts[idxInputFiles]));
}
job.setInputFormatClass(TextInputFormat.class);
job.addCacheFile(new URI(diagnosisCodesTableCache.toString() + "#" + diagnosisCodesTableCache.getName()));
job.addCacheFile(new URI(comorbidityColumnsTableCache.toString() + "#" + comorbidityColumnsTableCache.getName()));
job.addCacheFile(new URI(measureComorbidityCache.toString() + "#" + measureComorbidityCache.getName()));
outputPath = new Path(outPath);
fs = Util.getFileSystem(outputPath,conf);
Util.removeDirIfExists(fs,outPath);
FileOutputFormat.setOutputPath(job, outputPath);
if (job.waitForCompletion(true)) {
rc = 0;
} else {
rc = 8;
}
} catch (Exception ex) {
ex.printStackTrace(System.err);
rc = 8;
}
return(rc);
}
}
|
/*
* 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 Entities;
/**
*
* @author Ziyin
*/
public class Administrator extends User{
public Administrator(){super();}
public Administrator(String username,String password,String userid){
super(username,password,userid);
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import java.io.IOException;
import java.util.Collection;
import org.apache.hadoop.mapred.FairScheduler.JobInfo;
import org.apache.hadoop.mapreduce.TaskType;
public class JobSchedulable extends Schedulable {
private FairScheduler scheduler;
private JobInProgress job;
private TaskType taskType;
private int demand = 0;
public JobSchedulable(FairScheduler scheduler, JobInProgress job,
TaskType taskType) {
this.scheduler = scheduler;
this.job = job;
this.taskType = taskType;
}
@Override
public String getName() {
return job.getJobID().toString();
}
public JobInProgress getJob() {
return job;
}
@Override
public void updateDemand() {
demand = 0;
if (isRunnable()) {
// For reduces, make sure enough maps are done that reduces can launch
if (taskType == TaskType.REDUCE && !job.scheduleReduces())
return;
// Add up demand from each TaskInProgress; each TIP can either
// - have no attempts running, in which case it demands 1 slot
// - have N attempts running, in which case it demands N slots, and may
// potentially demand one more slot if it needs to be speculated
TaskInProgress[] tips = (taskType == TaskType.MAP ?
job.getTasks(TaskType.MAP) : job.getTasks(TaskType.REDUCE));
boolean speculationEnabled = (taskType == TaskType.MAP ?
job.hasSpeculativeMaps() : job.hasSpeculativeReduces());
long time = scheduler.getClock().getTime();
for (TaskInProgress tip: tips) {
if (!tip.isComplete()) {
if (tip.isRunning()) {
// Count active tasks and any speculative task we want to launch
demand += tip.getActiveTasks().size();
if (speculationEnabled && tip.canBeSpeculated(time))
demand += 1;
} else {
// Need to launch 1 task
demand += 1;
}
}
}
}
}
private boolean isRunnable() {
JobInfo info = scheduler.getJobInfo(job);
int runState = job.getStatus().getRunState();
return (info != null && info.runnable && runState == JobStatus.RUNNING);
}
@Override
public int getDemand() {
return demand;
}
@Override
public void redistributeShare() {}
@Override
public JobPriority getPriority() {
return job.getPriority();
}
@Override
public int getRunningTasks() {
if (!job.inited()) {
return 0;
}
return taskType == TaskType.MAP ? job.runningMaps() : job.runningReduces();
}
@Override
public long getStartTime() {
return job.startTime;
}
@Override
public double getWeight() {
return scheduler.getJobWeight(job, taskType);
}
@Override
public int getMinShare() {
return 0;
}
@Override
public Task assignTask(TaskTrackerStatus tts, long currentTime,
Collection<JobInProgress> visited) throws IOException {
if (isRunnable()) {
visited.add(job);
TaskTrackerManager ttm = scheduler.taskTrackerManager;
ClusterStatus clusterStatus = ttm.getClusterStatus();
int numTaskTrackers = clusterStatus.getTaskTrackers();
// check with the load manager whether it is safe to
// launch this task on this taskTracker.
LoadManager loadMgr = scheduler.getLoadManager();
if (!loadMgr.canLaunchTask(tts, job, taskType)) {
return null;
}
if (taskType == TaskType.MAP) {
LocalityLevel localityLevel = scheduler.getAllowedLocalityLevel(
job, currentTime);
scheduler.getEventLog().log(
"ALLOWED_LOC_LEVEL", job.getJobID(), localityLevel);
// obtainNewMapTask needs to be passed 1 + the desired locality level
return job.obtainNewMapTask(tts, numTaskTrackers,
ttm.getNumberOfUniqueHosts(), localityLevel.toCacheLevelCap());
} else {
return job.obtainNewReduceTask(tts, numTaskTrackers,
ttm.getNumberOfUniqueHosts());
}
} else {
return null;
}
}
}
|
package kimmyeonghoe.cloth.web.user;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import kimmyeonghoe.cloth.common.Log;
import kimmyeonghoe.cloth.domain.user.LoginDTO;
import kimmyeonghoe.cloth.domain.user.User;
import kimmyeonghoe.cloth.domain.user.ValiCode;
import kimmyeonghoe.cloth.service.user.UserService;
@Controller("kimmyeonghoe.cloth.web.user")
@RequestMapping("/user")
public class UserController{
@Autowired private UserService userService;
@RequestMapping("/login")
public String login(LoginDTO loginDTO, @CookieValue(required=false) Cookie loginCookie) {
if(loginCookie != null) loginDTO.setUserId(loginCookie.getValue());
return "user/login";
}
@PostMapping("/login")
public void loginchk(@Valid @RequestParam("userId") String userId, @RequestParam("userPw") String userPw, Model model, HttpServletRequest request){
HttpSession session = request.getSession();
User user = userService.chkUser(userId, userPw);
session.setAttribute("userId", user.getUserId());
if(user.getUserId().equals("admin")) {
model.addAttribute("admin",user);
}else {
model.addAttribute("user",user);
}
}
@ResponseBody
@RequestMapping("/idChk")
public String idChk(@RequestParam("userId") String userId, HttpServletRequest request, HttpServletResponse response) {
String result = userService.getId(userId);
if(result == null) result = "";
return result;
}
@RequestMapping("/join")
public String join(User user) {
return "user/join";
}
@PostMapping("/join")
public void joinUser(@RequestBody User user, Model model, HttpServletRequest request, HttpServletResponse response){
String email = user.getEmail();
HttpSession session = request.getSession();
session.setAttribute("user", user);
Cookie joinCookie = new Cookie("joinCookie", email);
joinCookie.setPath(request.getContextPath()+"/user/joinEmail");
joinCookie.setMaxAge(200);
response.addCookie(joinCookie);
}
@RequestMapping("/joinEmail")
public String joinEmailAddr() {
return "user/joinEmail";
}
@PostMapping("/joinEmail")
public void joinEmail(@RequestBody ValiCode valiCode, @CookieValue(required=false) Cookie joinCookie, HttpServletRequest request, HttpServletResponse response) {
String to = joinCookie.getValue();
valiCode.setTo(to);
userService.sendValiCode(valiCode, request, response);
}
@RequestMapping("/joinSuccess")
public String joinSuccessAddr() {
return "uset/joinSuccess";
}
@GetMapping("/joinSuccess")
public void joinSuccess(HttpServletRequest request) {
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
userService.addUser(user);
}
@RequestMapping("/joinFail")
public String joinFailAddr() {
return "uset/joinSuccess";
}
@GetMapping("/joinFail")
public void joinFail() {
}
@GetMapping("/logout")
@Log
public String logout(HttpSession session) {
session.invalidate();
return "redirect:/user/login";
}
@RequestMapping("/findId")
public String findIdAddr() {
return "user/findId";
}
@ResponseBody
@PostMapping("/findId")
public String getIdWithEmail(@RequestBody ValiCode valiCode,HttpServletRequest request, HttpServletResponse response) {
String email = valiCode.getTo();
String result = userService.getIdWithEmail(email);
if(result != null) {
Cookie loginCookie = new Cookie("loginCookie", result);
loginCookie.setPath(request.getContextPath()+"/user/login");
loginCookie.setMaxAge(300);
response.addCookie(loginCookie);
}
return result;
}
@ResponseBody
@PostMapping("/compareCode")
public String compareCode(@RequestBody ValiCode valiCode, HttpServletRequest request, HttpServletResponse response) {
String result = "";
int code = valiCode.getCode();
HttpSession session = request.getSession();
int sessionCode = (int) session.getAttribute("valicode");
if(code == sessionCode) result="success";
return result;
}
@ResponseBody
@PostMapping("/compareEmail")
public String compareEmail(@RequestBody User user, HttpServletRequest request, HttpServletResponse response) {
String result = "";
String email = user.getEmail();
String dbEmail = userService.getEmail(email);
if(!email.equals(dbEmail)) result="success";
return result;
}
@PostMapping("/sendMail")
public void findId(@RequestBody ValiCode valiCode,HttpServletRequest request, HttpServletResponse response) {
userService.sendValiCode(valiCode, request, response);
}
@RequestMapping("/findPw")
public String findPwAddr() {
return "user/findPw";
}
@RequestMapping("/changePw")
public String changePwAddr() {
return "user/changePw";
}
@PostMapping("/changePw")
public void saveId(@RequestBody User user, HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
session.getAttribute("userId");
if(user.getUserId() != null) {
session.setAttribute("userId", user.getUserId());
}
}
@PostMapping("/changePw2")
public void changePw(@RequestParam("userPw") String userPw, HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
String userId = (String) session.getAttribute("userId");
if(userId != null) {
userService.fixPw(userId, userPw);
}
}
@ResponseBody
@PostMapping("/changeEmail")
public void changeEmail(HttpServletRequest request, @RequestBody User user) {
String email = user.getEmail();
HttpSession session = request.getSession();
String userId = (String) session.getAttribute("userId");
userService.fixEmail(email, userId);
}
@ResponseBody
@PostMapping("/changeContact")
public void changeContact(HttpServletRequest request, @RequestBody User user) {
String contact = user.getContact();
HttpSession session = request.getSession();
String userId = (String) session.getAttribute("userId");
userService.fixContact(contact, userId);
}
@ResponseBody
@PostMapping("/changeAddress")
public void changeAddr(HttpServletRequest request, @RequestBody User user) {
String postcode = user.getPostcode();
String address = user.getAddress();
String addressDetail = user.getAddressDetail();
HttpSession session = request.getSession();
String userId = (String) session.getAttribute("userId");
userService.fixAddress(postcode, address, addressDetail, userId);
}
@RequestMapping("/userDetail")
public String getUserDetailAddr() {
return "user/userDetail";
}
@ResponseBody
@PostMapping("/userDetail")
public User getDetail(HttpServletRequest request, @CookieValue(required=false) Cookie loginState){
HttpSession session = request.getSession();
String userId = (String) session.getAttribute("userId");
return userService.getUser(userId);
}
}
|
/*
* 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 algorithmlab;
import java.util.Arrays;
/**
*
* @author pigrick
*/
public class Bubblesort1 {
public static void swap(int[] arr, int first, int second){
int temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
public static void bubblesort(int[] arr){
int n;
for(n = 0; n < arr.length-1; n++){
if(arr[n] > arr[n+1]){
break;
}
}
if(n == arr.length-1 ){
System.out.println("Already sorted");
return;
}
for(int i = 0 ; i < arr.length;i++){
for(int j = 0; j < arr.length - 1; j++){
if(arr[j] > arr[j+1]){
swap(arr, j, j+1);
}
}
}
}
public static void main(String[] args) {
int[] a = {3,6,4,1,2,5, 8 , -9, 9,7 ,4 ,1};
int[] b = {3,4,5,6};
bubblesort(a);
System.out.println(Arrays.toString(a));
bubblesort(a);
}
}
|
/*
* 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 cacpheptinh;
/**
*
* @author nguye
*/
public class Jpheptinh extends javax.swing.JFrame {
/**
* Creates new form Jpheptinh
*/
public Jpheptinh() {
initComponents();
}
/**
* 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();
cong = new javax.swing.JButton();
tru = new javax.swing.JButton();
nhan = new javax.swing.JButton();
chia = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
KQua = new javax.swing.JTextField();
NumA = new javax.swing.JTextField();
NumB = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Số a :");
jLabel2.setText("Số b :");
cong.setText("+");
cong.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
congActionPerformed(evt);
}
});
tru.setText("-");
tru.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
truActionPerformed(evt);
}
});
nhan.setText("*");
nhan.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nhanActionPerformed(evt);
}
});
chia.setText("/");
chia.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chiaActionPerformed(evt);
}
});
jLabel3.setText("Kết quả :");
jLabel4.setText("CÁC PHÉP TÍNH ");
jButton1.setText("Đóng");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(42, 42, 42)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3)
.addComponent(cong))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(tru)
.addGap(33, 33, 33)
.addComponent(nhan)
.addGap(41, 41, 41)
.addComponent(chia))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(KQua, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(NumA, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(NumB, javax.swing.GroupLayout.Alignment.LEADING))
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(jLabel4))))
.addGroup(layout.createSequentialGroup()
.addGap(108, 108, 108)
.addComponent(jButton1)))
.addContainerGap(38, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(NumA, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(NumB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cong)
.addComponent(tru)
.addComponent(nhan)
.addComponent(chia))
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(KQua, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(12, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void congActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_congActionPerformed
// TODO add your handling code here:
int a = Integer.parseInt(NumA.getText());
int b = Integer.parseInt(NumB.getText());
int ketqua = a+b;
KQua.setText(String.valueOf(ketqua));
}//GEN-LAST:event_congActionPerformed
private void truActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_truActionPerformed
// TODO add your handling code here:
int a = Integer.parseInt(NumA.getText());
int b = Integer.parseInt(NumB.getText());
int ketqua = a-b;
KQua.setText(String.valueOf(ketqua));
}//GEN-LAST:event_truActionPerformed
private void nhanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nhanActionPerformed
// TODO add your handling code here:
int a = Integer.parseInt(NumA.getText());
int b = Integer.parseInt(NumB.getText());
int ketqua = a*b;
KQua.setText(String.valueOf(ketqua));
}//GEN-LAST:event_nhanActionPerformed
private void chiaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chiaActionPerformed
// TODO add your handling code here:
float a = Float.parseFloat(NumA.getText());
float b = Float.parseFloat(NumB.getText());
float ketqua = a/b;
KQua.setText(String.valueOf(ketqua));
}//GEN-LAST:event_chiaActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
System.exit(0);
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Jpheptinh.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Jpheptinh.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Jpheptinh.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Jpheptinh.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Jpheptinh().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField KQua;
private javax.swing.JTextField NumA;
private javax.swing.JTextField NumB;
private javax.swing.JButton chia;
private javax.swing.JButton cong;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JButton nhan;
private javax.swing.JButton tru;
// End of variables declaration//GEN-END:variables
}
|
/*
* Copyright 2005-2010 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
*
* 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 sdloader.javaee.webxml;
import java.util.HashSet;
import java.util.Set;
import sdloader.constants.JavaEEConstants;
import sdloader.exception.NotImplementedYetException;
import sdloader.util.CollectionsUtil;
/**
* filter-mappingタグ
*
* @author c9katayama
* @author shot
*/
public class FilterMappingTag implements WebXmlTagElement {
private static final Set<String> SUPPORT_DISPATCHERS = new HashSet<String>();
static {
SUPPORT_DISPATCHERS.add(JavaEEConstants.DISPATCHER_TYPE_REQUEST);
SUPPORT_DISPATCHERS.add(JavaEEConstants.DISPATCHER_TYPE_FORWARD);
SUPPORT_DISPATCHERS.add(JavaEEConstants.DISPATCHER_TYPE_INCLUDE);
SUPPORT_DISPATCHERS.add(JavaEEConstants.DISPATCHER_TYPE_ERROR);
}
private String filterName;
private String urlPattern;
private String servletName;
private Set<String> dispatchers = CollectionsUtil.newHashSet();
public FilterMappingTag() {
super();
}
public String getFilterName() {
return filterName;
}
public FilterMappingTag setFilterName(String filterName) {
this.filterName = filterName;
return this;
}
public String getServletName() {
return servletName;
}
public FilterMappingTag setServletName(String servletName) {
this.servletName = servletName;
return this;
}
public String getUrlPattern() {
return urlPattern;
}
public FilterMappingTag setUrlPattern(String urlPattern) {
this.urlPattern = urlPattern;
return this;
}
public Set<String> getDispatchers() {
return dispatchers;
}
public FilterMappingTag addDispatcher(String dispatcher) {
if (!SUPPORT_DISPATCHERS.contains(dispatcher)) {
throw new NotImplementedYetException("dispatcher value ["
+ dispatcher + "] not support.");
}
this.dispatchers.add(dispatcher);
return this;
}
public void accept(WebXmlVisitor visitor) {
visitor.visit(this);
}
}
|
package data;
/**
* @Author weimin
* @Date 2020/10/9 0009 15:18
*/
public class Main2 {
public static void main(String[] args) {
String hexString = Integer.toHexString(16);
System.out.println(hexString);
String s = Integer.toBinaryString(16);
System.out.println(s);
String octalString = Integer.toOctalString(16);
System.out.println(octalString);
}
}
|
package railroad;
import java.util.Observer;
public class Facade
{
static private Facade _facade;
private Controller _controller;
private Facade()
{
_controller = Controller.getInstance();
}
static public Facade getInstance()
{
if(_facade == null)
{
_facade = new Facade();
}
return _facade;
}
public void AddRight(int speed)
{
_controller.AddRight(speed);
}
public void AddLeft(int speed)
{
_controller.AddLeft(speed);
}
public void setObserver(Observer observer)
{
_controller.setObserver(observer);
}
}
|
package com.hpg.demo.controller;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
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 org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.hpg.demo.bean.User;
import com.hpg.demo.service.UserService;
import com.hpg.demo.util.JSONUtil;
import com.hpg.demo.util.TimeUtils;
@Controller
@RequestMapping("User")
public class UserController extends BaseController {
/** 账号不存在 */
private static final String ERROR_USERNAME_NOT_EXISTS_RESPONSE = "{\"success\":0,\"message\":\"账号不存在\"}";
/** 密码错误 */
private static final String ERROR_USERNAME_MATCH_PASSWORD_RESPONSE = "{\"success\":0,\"message\":\"密码错误\"}";
/** 账号已存在 */
private static final String ERROR_USERNAME_IS_EXIST_RESPONSE = "{\"success\":0,\"message\":\"账号已经存在\"}";
/** 注册成功 */
private static final String SUCCESS_REGIST_RESPONSE = "{\"success\":1,\"message\":\"注册成功\"}";
/** 注册成功 */
private static final String SUCCESS_RESPONSE = "{\"success\":1,\"message\":\"操作成功\"}";
@Resource(name = "userServiceImpl")
private UserService userService;
/**
* 用户注册
*
* @param req
* @param rep
* @throws IOException
*/
@RequestMapping(value = "/regist.do", method = RequestMethod.POST)
@ResponseBody
public void regist(HttpServletRequest req, HttpServletResponse rep)
throws IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username + " " + password);
if (!username.equals("") && !password.equals("")) {// 先判断是否为空
User user = userService.isUserNameExists(username);
if (user == null) {// 用户为空就可以进行注册了
User registUser = new User();
registUser.setUsername(username);// 用户名
registUser.setPassword(password);// 密码
registUser.setCreatetime(TimeUtils.getCurrentTime());// 注册时间
userService.insertUser(registUser);
// sendResponse(rep,JSONUtil.convertBeanToStandardJSON(registUser));
sendSuccessMessage(rep, "注册成功");
} else {
sendErrorMessage(rep, "账号已经存在");
}
}
}
/**
* 登陆验证
*
* @param req
* @param rep
* @throws IOException
*/
@RequestMapping(value = "/login.do", method = RequestMethod.POST)
@ResponseBody
public void login(HttpServletRequest req, HttpServletResponse rep)
throws IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
if (username != null && password != null) {
if (!username.equals("") && !password.equals("")) {// 先判断是否为空
User user = userService.isUserNameExists(username);
if (user != null) {// 用户存在
if (user.getPassword().equals(password)) {// 验证密码
user.setPassword("");
sendResponse(rep,
JSONUtil.convertBeanToStandardJSON(user));
} else {// 密码不正确
sendErrorMessage(rep, "密码错误");
}
} else {// 用户不存在
sendErrorMessage(rep, "用户不存在");
}
} else {
sendErrorMessage(rep, "请输入正确账号密码");
}
} else {
sendErrorMessage(rep, "请输入账号");
}
}
/**
* 更新个人信息
*
* @param req
* @param rep
* @throws IOException
*/
@RequestMapping(value = "/update.do", method = RequestMethod.POST)
@ResponseBody
public void updateUserInfo(HttpServletRequest req, HttpServletResponse rep)
throws IOException {
String userName = req.getParameter("username");
int userSex = Integer.parseInt(req.getParameter("sex"));
String userProfiles = req.getParameter("profiles");
userService.updateUserInfo(userName, userSex, userProfiles);
sendSuccessMessage(rep, "更新成功");
}
/**
* 文件上传
*
* @param file
* @return
* @throws IOException
*/
@RequestMapping(value = "/upload.do", method = RequestMethod.POST)
public void fileUpload(@RequestParam("file") MultipartFile file,
HttpServletRequest request, HttpServletResponse response)
throws IOException {// 此处参数与表单参数一致
String username = request.getParameter("username");
if (!username.equals("") && username != null) {// 先判断是否为空
User user = userService.isUserNameExists(username);
if (user != null) {// 用户存在
if (!file.isEmpty()) {
try {
String fileName = System.currentTimeMillis() + ".jpg";
// file.getOriginalFilename()
String filePath = request.getSession()
.getServletContext().getRealPath("/")
+ "portrait/" + fileName;
String filePathString = request.getContextPath()
+ "/portrait/" + fileName;
System.out.println(filePathString);
File destFile = new File(filePath);
FileUtils.copyInputStreamToFile(file.getInputStream(),
destFile);
userService.updatePortrait(username, filePathString);
sendSuccessMessage(response, "上传成功");
} catch (Exception e) {
sendErrorMessage(response, "存储失败");
}
} else {
sendErrorMessage(response, "文件为空");
}
} else {
sendErrorMessage(response, "账户不存在");
}
} else {
sendErrorMessage(response, "必须参数username");
}
}
/**
* 多文件上传
*
* @param file
* @return
*/
@RequestMapping(value = "/mulitiFilesUpload.do", method = RequestMethod.POST)
public String filesUpload(@RequestParam("files") MultipartFile[] files,
HttpServletRequest request) {// 此处参数与表单参数一致
// 判断file数组不能为空并且长度大于0
if (files != null && files.length > 0) {
// 循环获取file数组中得文件
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
// 保存文件
// 判断文件是否为空
if (!file.isEmpty()) {
try {
// 文件保存路径
String filePath = request.getSession()
.getServletContext().getRealPath("/")
+ "upload/" + file.getOriginalFilename();
// 转存文件
File destFile = new File(filePath);
FileUtils.copyInputStreamToFile(file.getInputStream(),
destFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return "index";
}
/**
* 上传头像 客户端传递格式 String BOUNDARY= UUID.randomUUID().toString();//边界标识 String
* PREFIX="--";//分隔符 String LINE_END="\r\n"; //换行符,用于服务器readLine标识
* StringBuffer sb = new StringBuffer(); sb.append(PREFIX);
* sb.append(BOUNDARY); sb.append(LINE_END);
* sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" +
* mFile.getName() + "\"" + LINE_END);
* sb.append("Content-Type: application/octet-stream; charset=" + CHARSET +
* LINE_END); sb.append("userid"+LINE_END);
* dos.write(sb.toString().getBytes()); sb.setLength(0);
*
* @param request
* @param response
* @throws IOException
*/
@RequestMapping(value = "/uploadPortrait", method = RequestMethod.POST)
@ResponseBody
public void uploadPortrait(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// 根目录
String path = request.getSession().getServletContext().getRealPath("/");
// 获得输入流
ServletInputStream inputStream = request.getInputStream();
// 获得数据输入流
DataInputStream in = new DataInputStream(inputStream);
// 读取客户端传递过来的文字
System.out.println(in.readLine());// 分隔符
System.out.println(in.readLine());// content-disposition
System.out.println(in.readLine());// content-type
String userName = in.readLine(); // 读取用户名
FileOutputStream file = new FileOutputStream(path + "image/portrait_"
+ userName + ".jpg");
// 读文件
DataOutputStream out = new DataOutputStream(file);
byte[] buffer = new byte[4096];
int count = 0;
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
// 写返回码
PrintWriter writer = response.getWriter();
writer.println(SUCCESS_RESPONSE);
writer.flush();
writer.close();
out.close();
in.close();
file.close();
}
//
// @RequestMapping(value = "/upload.do", method = RequestMethod.POST)
// public void upload(@RequestParam("file") CommonsMultipartFile[] files,
// HttpServletRequest request,HttpServletResponse response) throws
// IOException {
//
// for (int i = 0; i < files.length; i++) {
// System.out.println("fileName---------->"
// + files[i].getOriginalFilename());
//
// if (!files[i].isEmpty()) {
// int pre = (int) System.currentTimeMillis();
// try {
// // 拿到输出流,同时重命名上传的文件
// FileOutputStream os = new FileOutputStream(
// "/usr/local/tomcat/webapps/eat/images/"
// + new Date().getTime()
// + files[i].getOriginalFilename());
// // 拿到上传文件的输入流
// FileInputStream in = (FileInputStream) files[i]
// .getInputStream();
//
// // 以写字节的方式写文件
// int b = 0;
// while ((b = in.read()) != -1) {
// os.write(b);
// }
// os.flush();
// os.close();
// in.close();
// int finaltime = (int) System.currentTimeMillis();
// System.out.println(finaltime - pre);
// sendResponse(response, SUCCESS_RESPONSE);
// } catch (Exception e) {
// e.printStackTrace();
// sendResponse(response, SUCCESS_RESPONSE);
// }
// }
// }
// }
/**
* 下载头像
*
* @param req
* @param rep
* @throws IOException
*/
@RequestMapping(value = "/downloadPortrait", method = RequestMethod.GET)
@ResponseBody
public void downloadPortrait(HttpServletRequest req, HttpServletResponse rep)
throws IOException {
// 图片传输
rep.setContentType("image/jpeg");
String userName = req.getParameter("username");
File file = new File(req.getSession().getServletContext()
.getRealPath("/")
+ "image/portrait_" + userName + ".jpg");
FileInputStream is = new FileInputStream(file);
ServletOutputStream out = rep.getOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
// 写返回码
PrintWriter writer = rep.getWriter();
writer.println(SUCCESS_RESPONSE);
writer.flush();
writer.close();
// 图片传输
out.flush();
out.close();
}
}
|
/**
*
*/
package org.rebioma.server.services;
import java.util.List;
import java.util.Set;
import org.rebioma.client.OccurrenceQuery;
import org.rebioma.client.bean.Occurrence;
import org.rebioma.client.bean.SearchFieldNameValuePair;
import org.rebioma.client.bean.User;
import org.rebioma.server.services.OccurrenceDbImpl.OccurrenceFilter;
/**
* @author Mikajy
*
*/
public interface IOccurrenceSearchDb {
public List<Occurrence> find(OccurrenceQuery query, Set<OccurrenceFilter> filters, User user,
int tryCount) throws Exception;
}
|
//
// GCALDaemon is an OS-independent Java program that offers two-way
// synchronization between Google Calendar and various iCalalendar (RFC 2445)
// compatible calendar applications (Sunbird, Rainlendar, iCal, Lightning, etc).
//
// Apache License
// Version 2.0, January 2004
// http://www.apache.org/licenses/
//
// Project home:
// http://gcaldaemon.sourceforge.net
//
package org.gcaldaemon.api;
import java.net.URL;
/**
* Container of a private iCal URL and a Google Calendar name pair.
*
* Created: Jan 22, 2008 12:50:56 PM
*
* @author Andras Berkes
*/
public final class RemoteCalendar {
// --- VARIABLES ---
/**
* Name of the calendar (eg. "Work", "Business")
*/
private final String name;
/**
* Private iCal URL of the calendar (eg.
* "https://www.google.com/calendar/ical/.../basic.ics")
*/
private final URL url;
// --- CONSTRUCTOR ---
/**
* Construct a name/URL pair.
*
* @param name
* name
* @param url
* private URL
*/
RemoteCalendar(String name, URL url) {
this.name = name;
this.url = url;
}
// --- PROPERTY GETTERS ---
/**
* Returns the calendar's name (eg. "Work", "Business").
*
* @return name
*/
public final String getName() {
return name;
}
/**
* Returns the private iCal URL (eg.
* "https://www.google.com/calendar/ical/.../basic.ics").
*
* @return private URL
*/
public final URL getURL() {
return url;
}
// --- TO STRING ---
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public final String toString() {
return "org.gcaldaemon.api.RemoteCalendar[name=" + name + ", URL="
+ url + ']';
}
}
|
/**
*
*/
package com.atanu.java.spring.offersvc.resource;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.atanu.java.spring.offersvc.bo.AncillaryMgmtBO;
import com.atanu.java.spring.offersvc.constant.Constants;
import com.atanu.java.spring.offersvc.exception.OfferSvcException;
import com.atanu.java.spring.offersvc.logger.ApplicationLogger;
import com.atanu.java.spring.offersvc.model.FaultDO;
import com.atanu.java.spring.offersvc.model.service.Ancillary;
import com.atanu.java.spring.offersvc.model.service.AncillarySvcResponse;
import com.atanu.java.spring.offersvc.util.StringUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/**
* @author Atanu Bhowmick
*
*/
@RestController
@RequestMapping(value = "/ancillary")
public class AncillaryService {
@Autowired
private AncillaryMgmtBO ancillaryMgmtBO;
private static final ApplicationLogger logger = new ApplicationLogger(AncillaryService.class);
@ApiOperation(value = "Get ancilarry by Id", response = Ancillary.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved the ancillary"),
@ApiResponse(code = 404, message = "No Data Found", response = FaultDO.class),
@ApiResponse(code = 500, message = Constants.ERROR_MSG_5004, response = FaultDO.class)
})
@RequestMapping(value = "/{ancillaryId}", method = RequestMethod.GET, produces = {
MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<Ancillary> getAncillary(
@ApiParam(value = "Ancillary Id in path param", required = true)
@PathVariable("ancillaryId") String ancillaryId)
throws OfferSvcException {
logger.debug("Inside getAncillary()");
Ancillary ancillaryDetails = ancillaryMgmtBO.getAncillaryById(ancillaryId);
return new ResponseEntity<>(ancillaryDetails, HttpStatus.OK);
}
@ApiOperation(value = "Get all ancilarries", response = List.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved the ancillary"),
@ApiResponse(code = 404, message = "No Data Found", response = FaultDO.class),
@ApiResponse(code = 500, message = Constants.ERROR_MSG_5004, response = FaultDO.class)
})
@RequestMapping(value = Constants.PATH_GET_ALL_ANCILLARY, method = RequestMethod.GET, produces = {
MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<List<Ancillary>> getAllAncillaries() throws OfferSvcException {
logger.debug("Inside getAllAncillaries()");
List<Ancillary> ancillaries = ancillaryMgmtBO.getAllAncillaries();
return new ResponseEntity<>(ancillaries, HttpStatus.OK);
}
@ApiOperation(value = "Get list of the avaliable ancilarries between two airports", response = AncillarySvcResponse.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully retrieved ancillary list"),
@ApiResponse(code = 400, message = Constants.ERROR_MSG_5001, response = FaultDO.class),
@ApiResponse(code = 404, message = "No Data Found", response = FaultDO.class),
@ApiResponse(code = 500, message = Constants.ERROR_MSG_5004, response = FaultDO.class) })
@RequestMapping(value = Constants.PATH_GET_ANCILLARY, method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<AncillarySvcResponse> getAllAncillary(
@ApiParam(value = "Send origin airport code in the query param", required = true) @RequestParam(required = true) String originAirportCode,
@ApiParam(value = "Send destination airport code in the query param", required = true) @RequestParam(required = true) String destAirporCode)
throws OfferSvcException {
logger.debug("Inside getAllAncillary()");
logger.debug("originAirportCode : {} , destAirporCode : {}", originAirportCode, destAirporCode);
AncillarySvcResponse response = null;
if (StringUtils.isEmpty(originAirportCode) || StringUtils.isEmpty(destAirporCode)) {
logger.debug("Invalid request. Origin/Destination airport code is empty");
throw new OfferSvcException(Constants.ERROR_CODE_5001, Constants.ERROR_MSG_5001, HttpStatus.BAD_REQUEST);
} else {
response = ancillaryMgmtBO.getAncillariesByAirorts(originAirportCode, destAirporCode);
response.setOriginAirportCode(originAirportCode);
response.setDestAirportCode(originAirportCode);
}
return new ResponseEntity<AncillarySvcResponse>(response, HttpStatus.OK);
}
@RequestMapping(value = "/hazelcast/save", method = RequestMethod.POST, produces = { MediaType.TEXT_PLAIN_VALUE })
public ResponseEntity<String> getHazelCastData() {
return new ResponseEntity<>(ancillaryMgmtBO.putInHazelastMap(), HttpStatus.OK);
}
@RequestMapping(value = "/hazelcast/get", method = RequestMethod.GET, produces = { MediaType.TEXT_PLAIN_VALUE })
public ResponseEntity<String> getFromHazelcastMap() {
return new ResponseEntity<>(ancillaryMgmtBO.getFromHazelcastMap(), HttpStatus.OK);
}
}
|
package com.designpatter.withflyweight;
public class PaintAppTestCase {
public static void render(int noofShapes)
{
Ishape shape=null;
for(int i=0; i<noofShapes;i++)
{
if(i<=50)
{
shape=ShapFactory.getShape("circle");
shape.draw(i, "Weight", "Red");
System.out.println(shape);
}
else{
shape=ShapFactory.getShape("rectangle");
shape.draw(i+1,i*i,"Green");
System.out.println(shape);
}
}
}
public static void main(String[] args) {
render(100);
}
}
|
package ro.redeul.google.go.ide;
import com.intellij.ide.structureView.StructureViewBuilder;
import com.intellij.ide.structureView.StructureViewModel;
import com.intellij.ide.structureView.TreeBasedStructureViewBuilder;
import com.intellij.lang.PsiStructureViewFactory;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import ro.redeul.google.go.ide.structureview.GoStructureViewModel;
/**
* User: jhonny
* Date: 06/07/11
*/
public class GoStructureView implements PsiStructureViewFactory {
@Override
public StructureViewBuilder getStructureViewBuilder(final PsiFile psiFile) {
return new TreeBasedStructureViewBuilder() {
@NotNull
public StructureViewModel createStructureViewModel() {
return new GoStructureViewModel(psiFile);
}
public boolean isRootNodeShown() {
return false;
}
};
}
}
|
package com.jack.jkbase.service.impl;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jack.jkbase.entity.SysFunction;
import com.jack.jkbase.entity.SysRoleModule;
import com.jack.jkbase.entity.ViewSysFunction;
import com.jack.jkbase.entity.ViewSysModule;
import com.jack.jkbase.mapper.SysFunctionMapper;
import com.jack.jkbase.mapper.SysRoleModuleMapper;
import com.jack.jkbase.mapper.ViewSysFunctionMapper;
import com.jack.jkbase.mapper.ViewSysModuleMapper;
import com.jack.jkbase.service.ISysFunctionService;
import com.jack.jkbase.util.Helper;
/**
* <p>
* 服务实现类
* </p>
*
* @author LIBO
* @since 2020-09-23
*/
@Service
public class SysFunctionServiceImpl extends ServiceImpl<SysFunctionMapper, SysFunction> implements ISysFunctionService {
@Autowired private ViewSysFunctionMapper viewMapper;
@Autowired private SysRoleModuleMapper roleModuleMapper;
@Autowired ViewSysModuleMapper viewMduleMapper;
public ViewSysFunctionMapper getViewMapper() {
return viewMapper;
}
//order by M_AppID,M_OrderLevel
public List<ViewSysFunction> selectAll(){
return viewMapper.selectList(Wrappers.lambdaQuery(ViewSysFunction.class)
.orderByAsc(ViewSysFunction::getmAppid,ViewSysFunction::getmOrderlevel));
}
public ViewSysFunction selectById(int id) {
return viewMapper.selectById(id);
}
public List<ViewSysFunction> selectByModuleid(int moduleId){
return viewMapper.selectList(Wrappers.lambdaQuery(ViewSysFunction.class)
.eq(ViewSysFunction::getfModuleid, moduleId)
.orderByAsc(ViewSysFunction::getfValue));
}
public List<ViewSysFunction> selectByAppid(int appid){
return viewMapper.selectList(Wrappers.lambdaQuery(ViewSysFunction.class)
.eq(ViewSysFunction::getmAppid, appid)
.orderByAsc(ViewSysFunction::getmOrderlevel,ViewSysFunction::getfValue));
}
@Transactional
@Override
public boolean save(SysFunction entity) {
Integer maxValue = getBaseMapper().selectMaxValue(entity.getfModuleid());
entity.setfValue(maxValue==null?1:maxValue*2);
return super.save(entity);
}
public JSONArray selectByApp(int appId,int roleId){
List<ViewSysFunction> list = selectByAppid(appId);
List<ViewSysModule> mSet = viewMduleMapper.selectList(Wrappers.lambdaQuery(ViewSysModule.class)
.eq(ViewSysModule::getmAppid, appId));
//Set<ViewSysModule> mSet = new LinkedHashSet<ViewSysModule>();
Map<Integer, String> parentMap= new LinkedHashMap<Integer, String>();
//先获取模块的集合
for(ViewSysModule v : mSet){
int parentId = v.getmParentid();
parentMap.put(parentId,parentId==0?"":v.getmParentname());
}
//获取权限列表
List<SysRoleModule> pList = roleModuleMapper.selectList(Wrappers.lambdaQuery(SysRoleModule.class)
.eq(SysRoleModule::getpRoleid, roleId)
);
JSONArray rootJa = new JSONArray();
for(Entry<Integer, String> parent : parentMap.entrySet()){
JSONObject joParent = new JSONObject();
joParent.put("parent",parent.getValue());
//解析,按模块分组
JSONArray jaModule = new JSONArray();
for(ViewSysModule m : mSet){
if(parent.getKey().equals(m.getmParentid())){
JSONObject jo = (JSONObject) JSONObject.toJSON(m);
JSONArray jaFunction = new JSONArray();
for(ViewSysFunction func : list){
if(func.getfModuleid()==m.getModuleid()){
//判断是否具有权限,如果设置的模块权限值小于0表示无限制
for(SysRoleModule p : pList){
if(p.getpModuleid()==m.getModuleid()){
int pValue = p.getpValue();
func.setAccess((pValue&func.getfValue())==func.getfValue());
}
}
jaFunction.add(func);
}
}
//如果该模块没有功能,则不显示该模块的权限设置
if(jaFunction.size()>0){
jo.put(Helper.KEY_FUNCTIONS,jaFunction);
jaModule.add(jo);
}
}
}
joParent.put("modules",jaModule);
rootJa.add(joParent);
}
return rootJa;
}
}
|
package com.itsdf07.okhttp3;
import android.text.TextUtils;
import com.itsdf07.alog.ALog;
import com.itsdf07.okhttp3.callback.HttpBaseCallback;
import com.itsdf07.okhttp3.callback.HttpProgressCallback;
import com.itsdf07.okhttp3.impl.OkHttp3CallbackImpl;
import com.itsdf07.okhttp3.progress.ProgressRequestBody;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* @Description :
* @Author itsdf07
* @Time 2018/07/18
*/
class OkHttp3Request {
public static final String TAG_HTTP = "tag_okhttp3";
private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");//JSON数据格式
private static final MediaType MEDIA_TYPE_STREAM = MediaType.parse("application/octet-stream");//二进制流数据
private static Platform mPlatform;
/**
* @Description 请求方式
*/
enum HttpMethodType {
GET,
POST,
}
private static OkHttpClient getOkHttpClient() {
if (null == mPlatform) {
mPlatform = Platform.get();
}
return OkHttp3Utils.getInstance().getOkHttpClient();
}
/**
* 数据请求成功
* 将http请求成功结果转至主线程
*
* @param tag
* @param result
* @param callback
* @param isDecode
*/
public static void sendSuccessResultCallback(final String tag, final String result, final OkHttp3CallbackImpl callback, final boolean isDecode) {
mPlatform.execute(new Runnable() {
@Override
public void run() {
if (callback != null) {
ALog.dTag(TAG_HTTP, "\nisDecode:%s\ntag:%s\nresult:%s", isDecode, tag, result);
callback.onSuccess(result, isDecode);
callback.onFinish();
}
}
});
}
/**
* 数据请求失败
* 将http请求失败结果转至主线程
*
* @param netCode
* @param callback
*/
public static void sendFailResultCallback(final NetCode netCode, final OkHttp3CallbackImpl callback) {
mPlatform.execute(new Runnable() {
@Override
public void run() {
ALog.eTag(TAG_HTTP, "NetCode:%s,\ndesc:%s,\ninfo:%s", netCode.getCode(), netCode.getDesc(), netCode.getInfo());
if (callback != null) {
callback.onFailure(netCode.getCode(), netCode.getDesc());
callback.onFinish();
}
}
});
}
/**
* 默认不需要对返回的数据解密
*
* @param request Request对象
* @param callback 请求回调
* @param isDecode 是否需要解密
* @Description 异步请求
*/
public static Call doEnqueue(final Request request, final OkHttp3CallbackImpl callback, final boolean isDecode) {
Call call = getOkHttpClient().newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
NetCode netCode = NetCode.UNKNOW;
if (e instanceof UnknownHostException) {
netCode = NetCode.CODE_6904;
} else if (e instanceof SocketTimeoutException) {
// if (null != e.getMessage()) {
// if (e.getMessage().contains("failed to connect to")) {
// //TODO 连接超时
// }
// if (e.getMessage().equals("timeout")) {
// //TODO 读写超时
// }
// }
netCode = NetCode.CODE_6905;
}
sendFailResultCallback(netCode.setInfo("\n\t\ttag:" + call.request().url().toString() + "\n\t\terr->:" + e.getMessage()), callback);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (null == response) {
sendFailResultCallback(NetCode.CODE_6010.setInfo("\n\t\ttag:" + call.request().url().toString() + "\n\t\terr->null == response"), callback);
return;
}
if (null == response.body()) {
sendFailResultCallback(NetCode.CODE_6020.setInfo("\n\t\ttag:" + call.request().url().toString() + "\n\t\terr->null == response.body()"), callback);
return;
}
String result = response.body().string();
if (TextUtils.isEmpty(result)) {
sendFailResultCallback(NetCode.CODE_6021.setInfo("\n\t\ttag:" + call.request().url().toString() + "\n\t\terr->body is empty"), callback);
return;
}
try {
if (response.isSuccessful()) {
sendSuccessResultCallback(call.request().url().toString(), result, callback, isDecode);
} else {
sendFailResultCallback(NetCode.CODE_6011.setInfo("\n\t\ttag:" + call.request().url().toString() + "\n\t\tcode:" + response.code() + ",\n\t\terr->:" + response.message()), callback);
}
} catch (Exception e) {
sendFailResultCallback(NetCode.CODE_6900.setInfo("\n\t\ttag:" + call.request().url().toString() + "\n\t\terr->" + e.getMessage()), callback);
}
}
});
return call;
}
/****************************************************** V 2 ********************************************************/
/**
* 数据请求成功
* 将http请求成功结果转至主线程
*
* @param result
* @param callback
*/
public static void sendSuccessResultCallback(final String tag, final String result, final HttpBaseCallback callback) {
mPlatform.execute(new Runnable() {
@Override
public void run() {
ALog.dTag(TAG_HTTP, "\ntag:%s\nresult:%s", tag, result);
if (null != callback) {
callback.onSuccess(result);
}
}
});
}
/**
* 数据请求失败
* 将http请求失败结果转至主线程
*
* @param netCode
* @param callback
*/
public static void sendFailResultCallback(final NetCode netCode, final HttpBaseCallback callback) {
mPlatform.execute(new Runnable() {
@Override
public void run() {
ALog.eTag(TAG_HTTP, "NetCode:%s,\ndesc:%s,\ninfo:%s", netCode.getCode(), netCode.getDesc(), netCode.getInfo());
if (null != callback) {
callback.onFailure(netCode, netCode.getDesc());
}
}
});
}
/**
* 文件下载进度
* 线程转为主线程
*
* @param currentLen
* @param totalLen
* @param callback
* @param isFinish 是否下载完成
*/
public static void sendProgressResultCallback(final long currentLen, final long totalLen, final HttpProgressCallback callback, final boolean isFinish) {
mPlatform.execute(new Runnable() {
@Override
public void run() {
if (isFinish) {
ALog.dTag(TAG_HTTP, "下载完成");
callback.onSuccess("下载完成");
} else {
ALog.dTag(TAG_HTTP, "下载中,totalLen:%s,currentLen:%s", totalLen, currentLen);
callback.onProgress(currentLen, totalLen);
}
}
});
}
/**
* @param params 请求参数
* @Description RequestBody对象
*/
private static RequestBody builderFormMapData(Map<String, String> params) {
FormBody.Builder builder = new FormBody.Builder();
if (params != null && !params.isEmpty()) {
for (String key : params.keySet()) {
String value = params.get(key);
builder.add(key, value);
}
}
return builder.build();
}
/**
* 获取存放上传文件的请求载体RequestBody,并实现进度数据透传
*
* @param file
* @param callback
* @return RequestBody对象
*/
private static RequestBody builderFormFileData(File file, final HttpProgressCallback callback) {
ProgressRequestBody progressRequestBody = null;
if (null != file) {
RequestBody requestBody = RequestBody.create(MEDIA_TYPE_STREAM, file);
progressRequestBody = new ProgressRequestBody(requestBody, new ProgressRequestBody.Listener() {
@Override
public void onRequestProgress(final long byteWrited, final long contentLength) {
mPlatform.execute(new Runnable() {
@Override
public void run() {
callback.onProgress(byteWrited, contentLength);
}
});
}
});
}
return progressRequestBody;
}
/*************************** builder request *****************************************************/
/**
* builder json/map 格式的data数据请求体:Request
* <br/>V2
*
* @param methodType 请求方式
* @param url 请求地址
* @param params 请求参数
* @param json json数据格式
* @Description Request对象
*/
public static Request builderDataRequest(HttpMethodType methodType, String url, Map<String, String> params, String json) {
Request request;
Request.Builder builder = new Request.Builder().url(url);
String bodyLog = "";
if (methodType == HttpMethodType.POST) {
if (json != null) {
bodyLog = json;
RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
builder.post(body);
} else {
RequestBody body = builderFormMapData(params);
builder.post(body);
bodyLog = buildBodyLog4Map(params);
}
} else if (methodType == HttpMethodType.GET) {
builder.get();
bodyLog = "这是get提交方式,没有body内容";
}
request = builder.build();
ALog.dTag(TAG_HTTP, "\nURL:%s\nMethod:%s\nheader:[\n%s]\nbody:%s",
request.url().toString(), request.method().toString(), request.headers().toString(), bodyLog);
return request;
}
/**
* builder map 格式的文件数据请求体:Request
* <br/>内涵上传进度
* <br/>V2
*
* @param url 请求地址
* @param file 上传文件
* @param params header参数
* @param callback 请求回调
* @Description Request对象
*/
public static Request builderFileMapRequest(String url, File file, Map<String, String> params, HttpProgressCallback callback) {
Request request;
String filePath = "";
Request.Builder builder = new Request.Builder().url(url);
if (null != params && !params.isEmpty()) {
for (String key : params.keySet()) {
builder.addHeader(key, params.get(key));
}
}
if (null != file) {
RequestBody body = builderFormFileData(file, callback);
builder.post(body);
filePath = file.getPath();
}
request = builder.build();
ALog.dTag(TAG_HTTP, "\nURL:%s\nMethod:%s\nheader:[\n%s]\nbody:%s",
request.url().toString(), request.method().toString(), request.headers().toString(), filePath);
return request;
}
/*************************************************** do enqueue ***************************************/
/**
* Post数据请求
* <br/>V2
*
* @param request Request对象
* @param callback 请求回调
* @Description 异步请求
*/
public static Call doEnqueue(final Request request, final HttpBaseCallback callback) {
Call call = getOkHttpClient().newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
NetCode netCode = NetCode.UNKNOW;
if (e instanceof UnknownHostException) {
netCode = NetCode.CODE_6904;
} else if (e instanceof SocketTimeoutException) {
// if (null != e.getMessage()) {
// if (e.getMessage().contains("failed to connect to")) {
// //TODO 连接超时
// }
// if (e.getMessage().equals("timeout")) {
// //TODO 读写超时
// }
// }
netCode = NetCode.CODE_6905;
}
sendFailResultCallback(netCode.setInfo("\n\t\ttag:" + request.url().toString() + "\n\t\terr->" + e.getMessage()), callback);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (null == response) {
sendFailResultCallback(NetCode.CODE_6010.setInfo("\n\t\ttag:" + call.request().url().toString() + "\n\t\terr->null == response"), callback);
return;
}
if (null == response.body()) {
sendFailResultCallback(NetCode.CODE_6020.setInfo("\n\t\ttag:" + call.request().url().toString() + "\n\t\terr->null == response.body()"), callback);
return;
}
String result = response.body().string();
if (TextUtils.isEmpty(result)) {
sendFailResultCallback(NetCode.CODE_6021.setInfo("\n\t\ttag:" + call.request().url().toString() + "\n\t\terr->body is empty"), callback);
return;
}
try {
if (response.isSuccessful()) {
sendSuccessResultCallback(request.url().toString(), result, callback);
} else {
sendFailResultCallback(NetCode.CODE_6011.setInfo("\n\t\ttag:" + call.request().url().toString() + "\n\t\tcode:" + response.code() + ",\n\t\terr->:" + response.message()), callback);
}
} catch (Exception e) {
sendFailResultCallback(NetCode.CODE_6900.setInfo("\n\t\ttag:" + call.request().url().toString() + "\n\t\terr->" + e.getMessage()), callback);
}
}
});
return call;
}
/**-------------------- 异步文件下载 --------------------**/
/**
* 文件下载
* <br/>V2
*
* @param request Request对象
* @param destFileDir 目标文件存储的文件目录
* @param destFileName 目标文件存储的文件名
* @param callback 请求回调
* @Description 异步下载请求
*/
public static Call doDownloadEnqueue(final Request request, final String destFileDir, final String destFileName, final HttpProgressCallback callback) {
Call call = getOkHttpClient().newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
NetCode netCode = NetCode.UNKNOW;
if (e instanceof UnknownHostException) {
netCode = NetCode.CODE_6904;
} else if (e instanceof SocketTimeoutException) {
// if (null != e.getMessage()) {
// if (e.getMessage().contains("failed to connect to")) {
// //TODO 连接超时
// }
// if (e.getMessage().equals("timeout")) {
// //TODO 读写超时
// }
// }
netCode = NetCode.CODE_6905;
}
sendFailResultCallback(netCode.setInfo("\n\t\ttag:" + request.url().toString() + "\n\t\terr->" + e.getMessage()), callback);
}
@Override
public void onResponse(Call call, Response response) {
if (null == response) {
sendFailResultCallback(NetCode.CODE_6010.setInfo("\n\t\ttag:" + call.request().url().toString() + "\n\t\terr->null == response"), callback);
return;
}
if (null == response.body()) {
sendFailResultCallback(NetCode.CODE_6020.setInfo("\n\t\ttag:" + call.request().url().toString() + "\n\t\terr->null == response.body()"), callback);
return;
}
InputStream inputStream = response.body().byteStream();
FileOutputStream fileOutputStream = null;
try {
byte[] buffer = new byte[2048];
int len;
long currentTotalLen = 0L;
long totalLen = response.body().contentLength();
File dir = new File(destFileDir);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, destFileName);
if (file.exists()) {
//如果文件存在则删除
file.delete();
}
fileOutputStream = new FileOutputStream(file);
while ((len = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
currentTotalLen += len;
sendProgressResultCallback(currentTotalLen, totalLen, callback, false);
}
fileOutputStream.flush();
sendProgressResultCallback(currentTotalLen, totalLen, callback, true);
} catch (IOException e) {
if (e instanceof SocketException) {
sendFailResultCallback(NetCode.CODE_6901.setInfo("\n\t\ttag:" + call.request().url().toString() + "\n\t\terr->" + e.getMessage()), callback);
} else {
sendFailResultCallback(NetCode.CODE_6903.setInfo("\n\t\ttag:" + call.request().url().toString() + "\n\t\terr->" + e.getMessage()), callback);
}
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
return call;
}
/**
* body log
*
* @param params
* @return
*/
private static String buildBodyLog4Map(Map<String, String> params) {
String log = "";
if (params != null && !params.isEmpty()) {
for (String key : params.keySet()) {
String value = params.get(key);
log += key + ":" + value + ",";
}
}
return log;
}
}
|
package codesum.lm.topicsum;
import java.io.File;
import java.io.Serializable;
import org.apache.commons.lang.ArrayUtils;
import com.esotericsoftware.kryo.DefaultSerializer;
import com.esotericsoftware.kryo.serializers.CompatibleFieldSerializer;
@DefaultSerializer(CompatibleFieldSerializer.class)
public class Corpus implements Serializable {
private static final long serialVersionUID = -7132625481659554609L;
private final Tokens alphabet;
private final String corpusFolder;
private final String[] projects;
private final Cluster[] clusters;
private final int nclusters;
public Corpus(final String corpusFolder, final String[] projects) {
this.alphabet = new Tokens();
this.corpusFolder = corpusFolder;
this.projects = projects.clone();
this.nclusters = projects.length;
this.clusters = new Cluster[nclusters];
getClusters(alphabet);
}
private void getClusters(final Tokens alphabet) {
for (int ci = 0; ci < nclusters; ci++) {
System.out.println("+++++ At project " + projects[ci] + " ("
+ (ci + 1) + " of " + nclusters + ")");
clusters[ci] = new Cluster(new File(corpusFolder + projects[ci]),
alphabet);
}
}
public int nclusters() {
return nclusters;
}
public Cluster getCluster(final int c) {
return clusters[c];
}
public String getProject(final int c) {
return projects[c];
}
public String[] getProjects() {
return projects;
}
public String getCorpusFolder() {
return corpusFolder;
}
public Tokens getAlphabet() {
return alphabet;
}
public int getIndexProject(final String project) {
return ArrayUtils.indexOf(projects, project);
}
}
|
/**
*
*/
package com.cnk.travelogix.common.facades.product.provider.impl;
import com.cnk.travelogix.common.facades.product.data.flight.FlightResultData;
import com.cnk.travelogix.common.facades.product.facet.impl.AccesserFactory;
import com.cnk.travelogix.common.facades.product.facet.impl.IAccess;
import com.cnk.travelogix.common.facades.product.provider.CnkFacetValueProvider;
/**
* @author i323616
*
*/
public class DefaultCnkMulticityIntlFacetValueProvider implements CnkFacetValueProvider<FlightResultData>
{
private AccesserFactory accessFactory;
/*
* (non-Javadoc)
*
* @see
* com.cnk.travelogix.common.facades.product.provider.CnkFacetValueProvider#getFacetValue(com.cnk.travelogix.common.
* facades.product.data.BaseProductData, java.lang.String)
*/
@Override
public Object getFacetValue(final FlightResultData bean, final String propertyName)
{
// YTODO Auto-generated method stub
if (bean.getListOfFlights().isEmpty())
{
return null;
}
final IAccess accessor = accessFactory.getAccessor(bean.getListOfFlights().get(0).getClass().getName(), propertyName);
return accessor.getValue(bean.getListOfFlights().get(0));
}
/**
* @return the accessFactory
*/
public AccesserFactory getAccessFactory()
{
return accessFactory;
}
/**
* @param accessFactory
* the accessFactory to set
*/
public void setAccessFactory(final AccesserFactory accessFactory)
{
this.accessFactory = accessFactory;
}
}
|
package jp.co.aforce.test;
public class PracticeTest2 {
public static void main(String[] args) {
// TODO 自動生成されたメソッド・スタブ
int x = 10;
int y = 28;
double z = 3.14;
//問題1
System.out.println("x*y= "+x*y);
//問題2
System.out.println("y/x= "+y/x+"余り"+y%x);
//問題3
double a = y*z;
System.out.println(a);
//問題4
a++;
System.out.println(a);
//問題5
int age = 22;
int randomNumber = new java.util.Random().nextInt(100);
System.out.println(randomNumber);
if(age>randomNumber) {
System.out.println("私の方が年上です");
}
else if(age<randomNumber) {
System.out.println("私の方が年下です");
}
else {
System.out.println("私と同い年です");
}
}
}
|
package sailpoint.plugin.iiqmdmplugin;
/**
*/
public class MasterDataManagementDTO {
private String _data = new String();
public String get_message() {
return _data;
}
public void set_message(String _data) {
this._data = _data;
}
}
|
package eg.edu.guc.parkei.exceptions;
public class NotEligiblePlayer extends ParkeiException {
/**
*
*/
private static final long serialVersionUID = 1L;
public NotEligiblePlayer() {
super();
}
public NotEligiblePlayer(String x) {
super(x);
}
}
|
/*
* 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 unalcol.search.single;
import unalcol.search.Goal;
import unalcol.search.Search;
import unalcol.search.Solution;
import unalcol.search.space.Space;
/**
* @author Jonatan
*/
public abstract class SinglePointSearch<T> implements Search<T> {
public SinglePointSearch() {
}
public abstract Solution<T> apply(Solution<T> solution, Space<T> space, Goal<T> goal);
@Override
public Solution<T> apply(Space<T> space, Goal<T> goal) {
return apply(new Solution<T>(space.get(), goal), space, goal);
}
}
|
package com.pineapple.mobilecraft.utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
public abstract class SyncHTTPCaller<T> {
String mURL;
String mToken = "";
String mEntity = "";
List mParamsList = new ArrayList();
public SyncHTTPCaller(String URL)
{
mURL = URL;
}
public SyncHTTPCaller(String URL, String token)
{
mURL = URL;
mToken = token;
}
public SyncHTTPCaller(String URL, String cookie, String entity)
{
mURL = URL;
mToken = cookie;
mEntity = entity;
}
public SyncHTTPCaller(String URL, String cookie, List params)
{
mURL = URL;
mToken = cookie;
mParamsList = params;
}
public abstract T postExcute(String result);
//public abstract T postExcute(int code, String result);
public T execute()
{
return null;
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with SAP Hybris.
*/
package com.cnk.travelogix.services.paymentgateways.response.decorators;
import java.util.Map;
import com.cnk.travelogix.integrations.payment.response.beans.ResponseAttribute;
/**
*
*/
@FunctionalInterface
public interface PaymentGatewayResponseData
{
public ResponseAttribute processResponseAttibuteValue(final ResponseAttribute responseAttribute,
final Map<String, ResponseAttribute> valueMap) throws Exception;
}
|
package com.tencent.mm.plugin.sns.model.a;
import android.os.Build.VERSION;
import android.text.TextUtils;
import com.tencent.mm.compatible.e.n;
import com.tencent.mm.compatible.e.q;
import com.tencent.mm.k.g;
import com.tencent.mm.platformtools.af;
import com.tencent.mm.plugin.sns.lucky.a.b;
import com.tencent.mm.plugin.sns.model.a.c.a;
import com.tencent.mm.protocal.c.ate;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
public abstract class f extends c {
protected boolean ntm = false;
protected boolean ntn = false;
protected boolean nto = false;
protected boolean ntp = false;
public f(a aVar, a aVar2) {
super(aVar, aVar2);
}
public final String MJ(String str) {
Exception e;
int i = 2;
Object obj = null;
String str2;
try {
int i2;
Object obj2;
Object obj3;
int obj4;
String value = g.AT().getValue("SnsCloseDownloadWebp");
if (bi.oW(value)) {
i2 = 0;
} else {
i2 = bi.WU(value);
}
if (i2 != 0) {
obj2 = null;
} else if (VERSION.SDK_INT < 14) {
obj2 = null;
} else if (q.deW.der == 2) {
obj2 = null;
} else if (bi.oW(af.exZ)) {
int obj22 = 1;
} else {
obj22 = null;
}
if (!n.zq()) {
obj3 = null;
} else if (!com.tencent.mm.plugin.sns.model.af.byz()) {
obj3 = null;
} else if (bi.oW(af.exZ)) {
i2 = 1;
} else {
obj3 = null;
}
if (n.zq() && com.tencent.mm.plugin.sns.model.af.byy() && bi.oW(af.exZ)) {
obj4 = 1;
}
if (!bi.oW(af.exY) || !bi.oW(af.exZ)) {
if (!bi.oW(af.exY)) {
String[] split = str.split("(//?)");
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(split[0]).append("//").append(af.exY);
while (i < split.length) {
stringBuilder.append("/").append(split[i]);
i++;
}
str = stringBuilder.toString();
x.i("MicroMsg.SnsDownloadImageBase", "new url " + str);
}
if (!bi.oW(af.exZ)) {
str = k(str, "tp=" + af.exZ);
x.i("MicroMsg.SnsDownloadImageBase", "(dbg) new url " + str);
}
} else if (obj3 != null) {
str = k(str, "tp=wxpc");
x.i("MicroMsg.SnsDownloadImageBase", "new url " + str);
} else if (obj4 != null) {
str = k(str, "tp=hevc");
x.i("MicroMsg.SnsDownloadImageBase", "new url " + str);
} else if (obj22 != null) {
str = k(str, "tp=webp");
x.i("MicroMsg.SnsDownloadImageBase", "new url " + str);
}
if (!(this.nsN == null || this.nsN.noc.rVQ == 0)) {
str = k(str, "enc=1");
x.i("MicroMsg.SnsDownloadImageBase", "test for enckey " + this.nsN.noc.rVR + " " + this.nsN.noc.rVQ + " " + str);
b.kB(136);
this.ntp = true;
}
str2 = str;
try {
if (this.nsN == null || this.nsN.noc == null) {
return str2;
}
Object obj5;
ate ate = this.nsN.noc;
if (this.nsN.nsG) {
obj5 = ate.rVW;
} else {
String obj52 = ate.rVT;
}
obj4 = this.nsN.nsG ? ate.rVX : ate.rVU;
if (TextUtils.isEmpty(obj52)) {
return str2;
}
return k(str2, "token=" + obj52, "idx=" + obj4);
} catch (Exception e2) {
e = e2;
x.e("MicroMsg.SnsDownloadImageBase", "error get dyna by webp " + e.getMessage());
return str2;
}
} catch (Exception e3) {
e = e3;
str2 = str;
}
}
private static String k(String str, String... strArr) {
StringBuilder stringBuilder = new StringBuilder(str);
stringBuilder.append(str.contains("?") ? "&" : "?");
Object obj = 1;
for (String str2 : strArr) {
if (obj != null) {
obj = null;
} else {
stringBuilder.append("&");
}
stringBuilder.append(str2);
}
return stringBuilder.toString();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ivadam.subnetcalculator;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import org.netbeans.microedition.lcdui.SimpleTableModel;
import org.netbeans.microedition.lcdui.TableItem;
/**
* @author damir
*/
public class ConvertedMain extends MIDlet implements CommandListener {
// HINT - Uncomment for accessing new MIDlet Started/Resumed logic.
private boolean midletPaused = false;
//<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
private Form mainForm;
private TextField textIP;
private StringItem stringClass;
private ChoiceGroup choiceSubnetCount;
private StringItem stringBits;
private StringItem stringMask;
private Form tableForm;
private TableItem tableItem2;
private Command exitCommand;
private Command calcCommand;
private Command tableCommand;
private Command backCommand1;
private SimpleTableModel simpleTableModel;
//</editor-fold>//GEN-END:|fields|0|
// HINT - Uncomment for accessing new MIDlet Started/Resumed logic.
// NOTE - Be aware of resolving conflicts of the constructor.
/**
* The ConvertedMain constructor.
*/
public ConvertedMain() {
}
//<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
//</editor-fold>//GEN-END:|methods|0|
//<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
/**
* Initilizes the application.
* It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
*/
private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
// write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
// write post-initialize user code here
}//GEN-BEGIN:|0-initialize|2|
//</editor-fold>//GEN-END:|0-initialize|2|
//<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
/**
* Performs an action assigned to the Mobile Device - MIDlet Started point.
*/
public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
// write pre-action user code here
switchDisplayable(null, getMainForm());//GEN-LINE:|3-startMIDlet|1|3-postAction
// write post-action user code here
}//GEN-BEGIN:|3-startMIDlet|2|
//</editor-fold>//GEN-END:|3-startMIDlet|2|
//<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
/**
* Performs an action assigned to the Mobile Device - MIDlet Resumed point.
*/
public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
// write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
// write post-action user code here
}//GEN-BEGIN:|4-resumeMIDlet|2|
//</editor-fold>//GEN-END:|4-resumeMIDlet|2|
//<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
/**
* Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
* @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
* @param nextDisplayable the Displayable to be set
*/
public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
// write pre-switch user code here
Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
if (alert == null) {
display.setCurrent(nextDisplayable);
} else {
display.setCurrent(alert, nextDisplayable);
}//GEN-END:|5-switchDisplayable|1|5-postSwitch
// write post-switch user code here
}//GEN-BEGIN:|5-switchDisplayable|2|
//</editor-fold>//GEN-END:|5-switchDisplayable|2|
//<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
/**
* Called by a system to indicated that a command has been invoked on a particular displayable.
* @param command the Command that was invoked
* @param displayable the Displayable where the command was invoked
*/
public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
// Insert global pre-action code here
if (displayable == mainForm) {//GEN-BEGIN:|7-commandAction|1|18-preAction
if (command == calcCommand) {//GEN-END:|7-commandAction|1|18-preAction
// Insert pre-action code here
//GEN-LINE:|7-commandAction|2|18-postAction
// Insert post-action code here
//simpleTableModel1.
//this.choiceSubnets.deleteAll();
String[] ipStr = Utils.split(textIP.getString(), ".");
this.stringClass.setText(Utils.getAddressClass(textIP.getString()));
this.stringBits.setText(String.valueOf(this.choiceSubnetCount.getSelectedIndex()));
this.stringMask.setText(Utils.getMask(this.choiceSubnetCount.getSelectedIndex() + Utils.getDefaultMaskPreffix(this.stringClass.getText())));
long maxHostsPerSub = Utils.pow(2, 32 - this.choiceSubnetCount.getSelectedIndex() - Utils.getDefaultMaskPreffix(this.stringClass.getText()));
//System.out.println(String.valueOf(maxHostsPerSub));
Integer[] ipInt = new Integer[4];
for (int i = 0; i < 4; i++) {
ipInt[i] = Integer.valueOf(ipStr[i]);
}
long ipDec = ipInt[0].longValue() * Utils.pow(256, 3) + ipInt[1].longValue() * Utils.pow(256, 2) + ipInt[2].longValue() * Utils.pow(256, 1) + ipInt[3].longValue() * Utils.pow(256, 0);
long maxHosts = 0;
if (stringClass.getText().equals("A")) {
maxHosts = Utils.pow(256, 3);
} else if (stringClass.getText().equals("B")) {
maxHosts = Utils.pow(256, 2);
} else if (stringClass.getText().equals("C")) {
maxHosts = Utils.pow(256, 1);
}
int subnetCount = Integer.parseInt(this.choiceSubnetCount.getString(this.choiceSubnetCount.getSelectedIndex()));
String[][] tableValues = new String[subnetCount][5];
//this.stringOsztaly.setText(String.valueOf(ipDec));
for (int i = 0; i < subnetCount; i++) {
long ipDec1 = ipDec + i * (maxHosts / subnetCount);
String ipv4 = String.valueOf(ipDec1 / 16777216l % 256l) + "." + String.valueOf(ipDec1 / 65536l % 256l) + "." + String.valueOf(ipDec1 / 256l % 256l) + "." + String.valueOf(ipDec1 / 1l % 256l);
tableValues[i][0] = ipv4;
// host start
ipDec1 = ipDec + i * (maxHosts / subnetCount) + 1;
ipv4 = String.valueOf(ipDec1 / 16777216l % 256l) + "." + String.valueOf(ipDec1 / 65536l % 256l) + "." + String.valueOf(ipDec1 / 256l % 256l) + "." + String.valueOf(ipDec1 / 1l % 256l);
tableValues[i][1] = ipv4;
// host end
ipDec1 = ipDec + i * (maxHosts / subnetCount) + maxHostsPerSub - 2;
ipv4 = String.valueOf(ipDec1 / 16777216l % 256l) + "." + String.valueOf(ipDec1 / 65536l % 256l) + "." + String.valueOf(ipDec1 / 256l % 256l) + "." + String.valueOf(ipDec1 / 1l % 256l);
tableValues[i][2] = ipv4;
// broadcast
ipDec1 = ipDec + i * (maxHosts / subnetCount) + maxHostsPerSub - 1;
ipv4 = String.valueOf(ipDec1 / 16777216l % 256l) + "." + String.valueOf(ipDec1 / 65536l % 256l) + "." + String.valueOf(ipDec1 / 256l % 256l) + "." + String.valueOf(ipDec1 / 1l % 256l);
tableValues[i][3] = ipv4;
}
getSimpleTableModel().setValues(tableValues);
} else if (command == exitCommand) {//GEN-LINE:|7-commandAction|3|15-preAction
// Insert pre-action code here
exitMIDlet();//GEN-LINE:|7-commandAction|4|15-postAction
// Insert post-action code here
} else if (command == tableCommand) {//GEN-LINE:|7-commandAction|5|20-preAction
// Insert pre-action code here
switchDisplayable(null, getTableForm());//GEN-LINE:|7-commandAction|6|20-postAction
// Insert post-action code here
}//GEN-BEGIN:|7-commandAction|7|23-preAction
} else if (displayable == tableForm) {
if (command == backCommand1) {//GEN-END:|7-commandAction|7|23-preAction
// Insert pre-action code here
switchDisplayable(null, getMainForm());//GEN-LINE:|7-commandAction|8|23-postAction
// Insert post-action code here
}//GEN-BEGIN:|7-commandAction|9|7-postCommandAction
}//GEN-END:|7-commandAction|9|7-postCommandAction
// Insert global post-action code here
}//GEN-BEGIN:|7-commandAction|10|
//</editor-fold>//GEN-END:|7-commandAction|10|
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: mainForm ">//GEN-BEGIN:|14-getter|0|14-preInit
/**
* Returns an initiliazed instance of mainForm component.
* @return the initialized component instance
*/
public Form getMainForm() {
if (mainForm == null) {//GEN-END:|14-getter|0|14-preInit
// Insert pre-init code here
mainForm = new Form("Damir\'s SubnetCalculator 1.0", new Item[] { getTextIP(), getChoiceSubnetCount(), getStringClass(), getStringBits(), getStringMask() });//GEN-BEGIN:|14-getter|1|14-postInit
mainForm.addCommand(getExitCommand());
mainForm.addCommand(getCalcCommand());
mainForm.addCommand(getTableCommand());
mainForm.setCommandListener(this);//GEN-END:|14-getter|1|14-postInit
// Insert post-init code here
}//GEN-BEGIN:|14-getter|2|
return mainForm;
}
//</editor-fold>//GEN-END:|14-getter|2|
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: textIP ">//GEN-BEGIN:|29-getter|0|29-preInit
/**
* Returns an initiliazed instance of textIP component.
* @return the initialized component instance
*/
public TextField getTextIP() {
if (textIP == null) {//GEN-END:|29-getter|0|29-preInit
// Insert pre-init code here
textIP = new TextField("IP address:", "129.250.0.0", 32, TextField.ANY);//GEN-BEGIN:|29-getter|1|29-postInit
textIP.setInitialInputMode("UCB_BASIC_LATIN");//GEN-END:|29-getter|1|29-postInit
// Insert post-init code here
}//GEN-BEGIN:|29-getter|2|
return textIP;
}
//</editor-fold>//GEN-END:|29-getter|2|
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: choiceSubnetCount ">//GEN-BEGIN:|30-getter|0|30-preInit
/**
* Returns an initiliazed instance of choiceSubnetCount component.
* @return the initialized component instance
*/
public ChoiceGroup getChoiceSubnetCount() {
if (choiceSubnetCount == null) {//GEN-END:|30-getter|0|30-preInit
// Insert pre-init code here
choiceSubnetCount = new ChoiceGroup("Subnet count:", Choice.POPUP);//GEN-BEGIN:|30-getter|1|30-postInit
choiceSubnetCount.setFitPolicy(Choice.TEXT_WRAP_DEFAULT);//GEN-END:|30-getter|1|30-postInit
// Insert post-init code here
for (int i = 0; i < 24; i++) {
choiceSubnetCount.append(String.valueOf(Utils.pow(2, i)), null);
}
}//GEN-BEGIN:|30-getter|2|
return choiceSubnetCount;
}
//</editor-fold>//GEN-END:|30-getter|2|
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: stringClass ">//GEN-BEGIN:|31-getter|0|31-preInit
/**
* Returns an initiliazed instance of stringClass component.
* @return the initialized component instance
*/
public StringItem getStringClass() {
if (stringClass == null) {//GEN-END:|31-getter|0|31-preInit
// Insert pre-init code here
stringClass = new StringItem("Network class:", "", Item.PLAIN);//GEN-BEGIN:|31-getter|1|31-postInit
stringClass.setLayout(ImageItem.LAYOUT_DEFAULT);//GEN-END:|31-getter|1|31-postInit
// Insert post-init code here
}//GEN-BEGIN:|31-getter|2|
return stringClass;
}
//</editor-fold>//GEN-END:|31-getter|2|
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: stringBits ">//GEN-BEGIN:|32-getter|0|32-preInit
/**
* Returns an initiliazed instance of stringBits component.
* @return the initialized component instance
*/
public StringItem getStringBits() {
if (stringBits == null) {//GEN-END:|32-getter|0|32-preInit
// Insert pre-init code here
stringBits = new StringItem("Required bits:", "");//GEN-LINE:|32-getter|1|32-postInit
// Insert post-init code here
}//GEN-BEGIN:|32-getter|2|
return stringBits;
}
//</editor-fold>//GEN-END:|32-getter|2|
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: stringMask ">//GEN-BEGIN:|33-getter|0|33-preInit
/**
* Returns an initiliazed instance of stringMask component.
* @return the initialized component instance
*/
public StringItem getStringMask() {
if (stringMask == null) {//GEN-END:|33-getter|0|33-preInit
// Insert pre-init code here
stringMask = new StringItem("Network mask:", "");//GEN-LINE:|33-getter|1|33-postInit
// Insert post-init code here
}//GEN-BEGIN:|33-getter|2|
return stringMask;
}
//</editor-fold>//GEN-END:|33-getter|2|
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: tableForm ">//GEN-BEGIN:|22-getter|0|22-preInit
/**
* Returns an initiliazed instance of tableForm component.
* @return the initialized component instance
*/
public Form getTableForm() {
if (tableForm == null) {//GEN-END:|22-getter|0|22-preInit
// Insert pre-init code here
tableForm = new Form("Damir\'s SubnetCalculator 1.0", new Item[] { getTableItem2() });//GEN-BEGIN:|22-getter|1|22-postInit
tableForm.addCommand(getBackCommand1());
tableForm.setCommandListener(this);//GEN-END:|22-getter|1|22-postInit
// Insert post-init code here
}//GEN-BEGIN:|22-getter|2|
return tableForm;
}
//</editor-fold>//GEN-END:|22-getter|2|
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: tableItem2 ">//GEN-BEGIN:|26-getter|0|26-preInit
/**
* Returns an initiliazed instance of tableItem2 component.
* @return the initialized component instance
*/
public TableItem getTableItem2() {
if (tableItem2 == null) {//GEN-END:|26-getter|0|26-preInit
// Insert pre-init code here
tableItem2 = new TableItem(getDisplay(), "");//GEN-BEGIN:|26-getter|1|26-postInit
tableItem2.setTitle("Subnets");
tableItem2.setModel(getSimpleTableModel());//GEN-END:|26-getter|1|26-postInit
// Insert post-init code here
}//GEN-BEGIN:|26-getter|2|
return tableItem2;
}
//</editor-fold>//GEN-END:|26-getter|2|
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">//GEN-BEGIN:|16-getter|0|16-preInit
/**
* Returns an initiliazed instance of exitCommand component.
* @return the initialized component instance
*/
public Command getExitCommand() {
if (exitCommand == null) {//GEN-END:|16-getter|0|16-preInit
// Insert pre-init code here
exitCommand = new Command("Exit", Command.EXIT, 1);//GEN-LINE:|16-getter|1|16-postInit
// Insert post-init code here
}//GEN-BEGIN:|16-getter|2|
return exitCommand;
}
//</editor-fold>//GEN-END:|16-getter|2|
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: calcCommand ">//GEN-BEGIN:|19-getter|0|19-preInit
/**
* Returns an initiliazed instance of calcCommand component.
* @return the initialized component instance
*/
public Command getCalcCommand() {
if (calcCommand == null) {//GEN-END:|19-getter|0|19-preInit
// Insert pre-init code here
calcCommand = new Command("Calc", Command.ITEM, 1);//GEN-LINE:|19-getter|1|19-postInit
// Insert post-init code here
}//GEN-BEGIN:|19-getter|2|
return calcCommand;
}
//</editor-fold>//GEN-END:|19-getter|2|
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: tableCommand ">//GEN-BEGIN:|21-getter|0|21-preInit
/**
* Returns an initiliazed instance of tableCommand component.
* @return the initialized component instance
*/
public Command getTableCommand() {
if (tableCommand == null) {//GEN-END:|21-getter|0|21-preInit
// Insert pre-init code here
tableCommand = new Command("Show subnets", Command.SCREEN, 2);//GEN-LINE:|21-getter|1|21-postInit
// Insert post-init code here
}//GEN-BEGIN:|21-getter|2|
return tableCommand;
}
//</editor-fold>//GEN-END:|21-getter|2|
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand1 ">//GEN-BEGIN:|24-getter|0|24-preInit
/**
* Returns an initiliazed instance of backCommand1 component.
* @return the initialized component instance
*/
public Command getBackCommand1() {
if (backCommand1 == null) {//GEN-END:|24-getter|0|24-preInit
// Insert pre-init code here
backCommand1 = new Command("Back", Command.BACK, 1);//GEN-LINE:|24-getter|1|24-postInit
// Insert post-init code here
}//GEN-BEGIN:|24-getter|2|
return backCommand1;
}
//</editor-fold>//GEN-END:|24-getter|2|
//<editor-fold defaultstate="collapsed" desc=" Generated Getter: simpleTableModel ">//GEN-BEGIN:|27-getter|0|27-preInit
/**
* Returns an initiliazed instance of simpleTableModel component.
* @return the initialized component instance
*/
public SimpleTableModel getSimpleTableModel() {
if (simpleTableModel == null) {//GEN-END:|27-getter|0|27-preInit
// Insert pre-init code here
simpleTableModel = new SimpleTableModel(new java.lang.String[][] {//GEN-BEGIN:|27-getter|1|27-postInit
new java.lang.String[] { "", "", "", "", "" }}, new java.lang.String[] { "Subnet", "Host1", "Host2", "Broadcast", "Usable" });//GEN-END:|27-getter|1|27-postInit
// Insert post-init code here
}//GEN-BEGIN:|27-getter|2|
return simpleTableModel;
}
//</editor-fold>//GEN-END:|27-getter|2|
/**
* This method should return an instance of the display.
*/
/**
* Returns a display instance.
* @return the display instance.
*/
public Display getDisplay() {
return Display.getDisplay(this);
// return Display.getDisplay (this);
}
/**
* This method should exit the midlet.
*/
/**
* Exits MIDlet.
*/
public void exitMIDlet() {
getDisplay().setCurrent(null);
destroyApp(true);
notifyDestroyed();
// switchDisplayable (null, null);
// destroyApp(true);
// notifyDestroyed();
}
// /** Creates a new instance of MainForm */
// public ConvertedMain() {
// initialize();
// for (int i = 0; i < 24; i++) {
// choiceSubnetCount.append(String.valueOf(Utils.pow(2, i)), null);
// }
// }
// public void startApp() {
// }
//
// public void pauseApp() {
// }
//
// public void destroyApp(boolean unconditional) {
// }
// HINT - Uncomment for accessing new MIDlet Started/Resumed logic.
// NOTE - Be aware of resolving conflicts of following methods.
/**
* Called when MIDlet is started.
* Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
*/
public void startApp() {
if (midletPaused) {
resumeMIDlet();
} else {
initialize();
startMIDlet();
}
midletPaused = false;
}
/**
* Called when MIDlet is paused.
*/
public void pauseApp() {
midletPaused = true;
}
/**
* Called to signal the MIDlet to terminate.
* @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
*/
public void destroyApp(boolean unconditional) {
}
}
|
package it.unical.asd.group6.computerSparePartsCompany.core.exception;
public class UserAlreadyInDBException extends UserException {
public UserAlreadyInDBException() {
super(String.format("Username or email are already in use"));
}
}
|
package ru.javabegin.training.flight.database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import ru.javabegin.training.flight.spr.objects.Company;
public class CompanyDB {
private CompanyDB() {
}
private static CompanyDB instance;
public static CompanyDB getInstance() {
if (instance == null) {
instance = new CompanyDB();
}
return instance;
}
public Company getCompany(long id) {
try {
return getCompany(getCompanyStmt(id));
} catch (SQLException ex) {
Logger.getLogger(CompanyDB.class.getName()).log(Level.SEVERE, null, ex);
} finally {
AviaDB.getInstance().closeConnection();
}
return null;
}
private Company getCompany(PreparedStatement stmt) throws SQLException {
Company company = null;
ResultSet rs = null;
try {
rs = stmt.executeQuery();
rs.next();
if (rs.isFirst()) {
company = new Company();
company.setId(rs.getLong("id"));
company.setName(rs.getString("name"));
company.setDesc(rs.getString("desc"));
}
} finally {
rs.close();
stmt.close();
}
return company;
}
private PreparedStatement getCompanyStmt(long id) throws SQLException {
Connection conn = AviaDB.getInstance().getConnection();
PreparedStatement stmt = conn.prepareStatement("select * from spr_company where id=?");
stmt.setLong(1, id);
return stmt;
}
}
|
/*
* 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 tutorscheduler;
/**
* Represents a tutor, supervisor, or a room.
*
* @author Stephanie Deen
*/
public class Component {
private String name;
private int maxHours;
private int status;
public static int SUPERVISOR = 0;
public static int TUTOR = 1;
public static int ROOM = 2;
public Component(String name, int status) {
this.name = name;
this.status = status;
}
public Component(String name, int status, int maxHours) {
this.name = name;
this.maxHours = maxHours;
this.status = status;
}
public int getMaxHours() {
return maxHours;
}
public String getName() {
return name;
}
public int getStatus() {
return status;
}
public void setName(String name) {
this.name = name;
}
public void setMaxHours(int maxHours) {
this.maxHours = maxHours;
}
public void setStatus(int status) {
this.status = status;
}
@Override
public String toString() {
String statement;
statement = this.name;
if (this.status == SUPERVISOR) {
statement += " Max Hours: " + this.maxHours;
statement += " Status: Supervisor"; }
else if (this.status == TUTOR) {
statement += " Max Hours: " + this.maxHours;
statement += " Status: Tutor";
} else {
statement += " Status: Room";
}
return statement;
}
}
|
package com.dbs.spring.capstoneproject.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dbs.spring.capstoneproject.model.Client;
import com.dbs.spring.capstoneproject.model.Clientstocks;
import com.dbs.spring.capstoneproject.repository.ClientRepository;
import com.dbs.spring.capstoneproject.repository.ClientstocksRepository;
@Service
public class ClientstocksService {
public ClientstocksService()
{}
@Autowired
private ClientstocksRepository repo;
public List<Clientstocks> findclientstocksbyid(String id)
{
List<Clientstocks> clients = new ArrayList<Clientstocks>();
this.repo.findAllByClientClientid(id).forEach(tt->clients.add(tt));
return clients;
}
public Integer findquanbyid(String id) {
return this.repo.findById(id).get().getQuantity();
}
public Clientstocks findclientstockid(String id)
{
try {
Optional<Clientstocks> c=this.repo.findById(id);
return c.orElseThrow(()->{
return new EntityNotFoundException("Client with id "+id + " does not exist");
});
}
catch(IllegalArgumentException iae) {
return null;
}
}
}
|
package me.hipoplar.demo.srv.user.impl;
import me.hipoplar.demo.api.user.UserService;
import me.hipoplar.demo.api.user.model.User;
import me.hipoplar.demo.srv.user.dao.UserDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
public class UserServiceImpl implements UserService {
@Autowired
private UserDaoImpl userDao;
@Transactional
public User getUser(Long id) {
return userDao.getUser(id);
}
}
|
execute(src, registers, memory) throws Exception {
int size = Memory.MAX_ADDRESS_SIZE; // 32
String stackPointer = registers.getStackPointer();
BigInteger stackAddress = new BigInteger(stackPointer, 16);
BigInteger offset = new BigInteger(size + "");
offset = offset.divide(new BigInteger("8"));
stackAddress = stackAddress.add(offset);
// add src to stackAddress to pop it
if ( src.isHex() ) {
String extraPopped = src.getValue();
stackAddress = stackAddress.add(new BigInteger(extraPopped, 16));
}
if ( stackAddress.compareTo(new BigInteger("FFFE", 16)) == 1 ) {
throw new StackPopException(offset.intValue());
} else {
String previousInstructionAddress = memory.read(stackPointer, size);
registers.setStackPointer(stackAddress.toString(16));
// set EIP to the next instruction
BigInteger nextInstruction = new BigInteger(previousInstructionAddress, 16);
nextInstruction = nextInstruction.add(new BigInteger("1"));
registers.setInstructionPointer(nextInstruction.toString(16));
}
}
execute(registers, memory) throws Exception {
int size = Memory.MAX_ADDRESS_SIZE; // 32
String stackPointer = registers.getStackPointer();
BigInteger stackAddress = new BigInteger(stackPointer, 16);
BigInteger offset = new BigInteger(size + "");
offset = offset.divide(new BigInteger("8"));
stackAddress = stackAddress.add(offset);
if ( stackAddress.compareTo(new BigInteger("FFFE", 16)) == 1 ) {
throw new StackPopException(offset.intValue());
} else {
String previousInstructionAddress = memory.read(stackPointer, size);
registers.setStackPointer(stackAddress.toString(16));
// set EIP to the next instruction
BigInteger nextInstruction = new BigInteger(previousInstructionAddress, 16);
nextInstruction = nextInstruction.add(new BigInteger("1"));
registers.setInstructionPointer(nextInstruction.toString(16));
}
}
|
package Project2;
public abstract class DessertItem implements Comparable<DessertItem>{
private String name;
private int quantity;
protected String heat;
protected double pas_price;
protected double coo_price_dozen;
protected double mac_price;
protected double mac_price_three;
/**
* default constructor for dessertItem
*/
public DessertItem() {
}
/**
* DessertItem constuctor
* @param name is the pastry's name
* @param quantity is the amount of dessert item
*/
public DessertItem(String name, int quantity) {
this.name = name;
this.quantity = quantity;
}
/**
* set the pastries price
* @param pas_price is the pastries price
*/
public void set_pas_price(int pas_price) {
this.pas_price = pas_price;
}
/**
* gets the pastry's price
* @return the pastry's price
*/
public double get_pas_price() {
return pas_price;
}
/**
* set the cookie price for a dozen
* @param coo_price_dozen is the price for a dozen of cookie
*/
public void set_coo_price_dozen(int coo_price_dozen) {
this.coo_price_dozen = coo_price_dozen;
}
/**
* get the cookie's price per dozen
* @return the price per dozen
*/
public double get_coo_price_dozen() {
return coo_price_dozen;
}
/**
* sets the price of the macaroon
* @param mac_price is the price of the macaroon
*/
public void set_mac_price(double mac_price) {
this.mac_price = mac_price;
}
/**
* gets the price of the macaroon
* @return the price of the macaroon
*/
public double get_mac_price() {
return mac_price;
}
/**
* sets the price for three macaroons
* @param mac_price_three is the price for 3 macaroons
*/
public void set_mac_price_three(double mac_price_three) {
this.mac_price_three = mac_price_three;
}
/**
* gets the price for three macaroons
* @return the price for three macaroons
*/
public double get_mac_price_three() {
return mac_price_three;
}
/**
* sets the name of the dessert item
* @param name is the name of the dessert item
*/
public void setName(String name) {
this.name = name;
}
/**
* gets the name of the dessert item
* @return the name of the dessert item
*/
public String getName() {
return name;
}
/**
* sets the quantity of the dessert item
* @param quantity is the quantity of the dessert item
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
/**
* gets the quantity of the dessert item
* @param quantity is the quantity of the dessert item
*/
public int getQuantity() {
return quantity;
}
/**
* sets the heat of the pastry
* @param heat is the heat of the pastry
*/
public void setHeat(String heat) {
this.heat = heat;
}
/**
* gets the heat of the pastry
* @return the heat of the pastry
*/
public String getHeat() {
return heat;
}
/**
* display the object in a receipt form
*/
public abstract void display();
/**
* calculates the cost of the drink
* @return the cost of the drink
*/
public abstract double getCost();
/**
* compares the object dessert items with each other
*/
public abstract int compareTo(DessertItem other);
}
|
package fileHandlers;
import dataStructures.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class OutputGenerator
{
private String outfile = "";
public OutputGenerator(String outfile)
{
this.outfile = outfile;
}
public void generate(ArrayList<Car> cars)
{
File file = new File(outfile);
try
{
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
String line;
for(Car c : cars)
{
List<Route> routes = c.getRoutes();
line = "" + routes.size();
for(Route r : routes)
{
line += " " + r.getIndex();
}
writer.write(line);
writer.newLine();
}
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.ashoksm.thiraseela.ui;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.ashoksm.thiraseela.R;
import com.ashoksm.thiraseela.adapter.ArtistListAdapter;
import com.ashoksm.thiraseela.dto.ArtistListDTO;
import com.ashoksm.thiraseela.utils.ImageDownloader;
import com.ashoksm.thiraseela.utils.RecyclerItemClickListener;
import com.ashoksm.thiraseela.wsclient.WSClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ArtistListActivity extends AppCompatActivity {
public static final String EXTRA_PERFORMER_NAME = "EXTRA_PERFORMER_NAME";
public static final List<ArtistListDTO> ARTIST_LIST_VOS = new ArrayList<>();
private ArtistListAdapter adapter = null;
private boolean networkAvailable = true;
private static final String URL = "http://thiraseela.com/thiraandroidapp/images/inner_bg.png";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_artist_list);
final Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
toolbar.setNavigationIcon(R.drawable.ic_navigation_arrow_back);
setSupportActionBar(toolbar);
ImageView innerBG = (ImageView) findViewById(R.id.inner_bg);
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ImageDownloader downloader = ImageDownloader.getInstance(am.getMemoryClass());
Bitmap bitmap = downloader.getBitmapFromMemCache(URL);
if (bitmap != null) {
innerBG.setImageBitmap(bitmap);
} else {
downloader.download(URL, innerBG, null, null);
}
TextView info = (TextView) findViewById(R.id.info);
info.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", "info@thiraseela.com", null));
startActivity(Intent.createChooser(intent, "Complete action using"));
}
});
EditText searchText = (EditText) findViewById(R.id.search_bar);
final RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.artist_list_view);
final TextView emptyView = (TextView) findViewById(R.id.empty_view);
Button retryButton = (Button) findViewById(R.id.retryButton);
retryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadDetails(mRecyclerView, emptyView);
}
});
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
loadDetails(mRecyclerView, emptyView);
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(getApplicationContext(),
new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(getApplicationContext(), ArtistDetailActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ArtistListDTO artistListDTO = adapter.getFilteredArtistListDTOs().get(position);
int i = ARTIST_LIST_VOS.indexOf(artistListDTO);
intent.putExtra(EXTRA_PERFORMER_NAME, String.valueOf(i));
startActivity(intent);
overridePendingTransition(R.anim.slide_out_left, 0);
}
})
);
searchText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (adapter != null) {
adapter.getFilter().filter(s.toString());
}
}
});
}
private void loadDetails(final RecyclerView mRecyclerView, final TextView emptyView) {
new AsyncTask<Void, Void, Void>() {
LinearLayout progressLayout = (LinearLayout) findViewById(R.id.progressView);
RelativeLayout contentLayout = (RelativeLayout) findViewById(R.id.contentLayout);
LinearLayout timeoutLayout = (LinearLayout) findViewById(R.id.timeoutLayout);
@Override
protected void onPreExecute() {
// SHOW THE SPINNER WHILE LOADING FEEDS
progressLayout.setVisibility(View.VISIBLE);
contentLayout.setVisibility(View.GONE);
timeoutLayout.setVisibility(View.GONE);
networkAvailable = true;
}
@Override
protected Void doInBackground(Void... params) {
if (ARTIST_LIST_VOS.size() == 0) {
ARTIST_LIST_VOS.clear();
ObjectMapper mapper = new ObjectMapper();
try {
String response =
WSClient.execute("", "http://thiraseela.com/thiraandroidapp/performerlistservice.php");
Log.d("response", response);
List<ArtistListDTO> temp = mapper.readValue(response,
TypeFactory.defaultInstance().constructCollectionType(List.class, ArtistListDTO.class));
ARTIST_LIST_VOS.addAll(temp);
} catch (IOException e) {
Log.e("ArtistListActivity", e.getLocalizedMessage());
networkAvailable = false;
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (networkAvailable) {
adapter = new ArtistListAdapter(ARTIST_LIST_VOS, ArtistListActivity.this, mRecyclerView, emptyView);
mRecyclerView.setAdapter(adapter);
// HIDE THE SPINNER WHILE LOADING FEEDS
progressLayout.setVisibility(View.GONE);
contentLayout.setVisibility(View.VISIBLE);
timeoutLayout.setVisibility(View.GONE);
} else {
timeoutLayout.setVisibility(View.VISIBLE);
progressLayout.setVisibility(View.GONE);
contentLayout.setVisibility(View.GONE);
}
}
}.execute();
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.slide_in_left, 0);
}
@Override
protected void onResume() {
super.onResume();
overridePendingTransition(R.anim.slide_in_left, 0);
}
}
|
package testk;
public class OverloadingExample {
int x=10;
int y=20;
OverloadingExample() {
System.out.println("hey");
}
OverloadingExample(int x) {
this();
}
public void sum() {
int sum=x+y;
System.out.println(sum);
}
public void s() {
int sum=x+y;
System.out.println(sum);
this.sum();
}
public int sum(int x) {
this.x=x;
int s=10;
return s;
}
public static void main(String[] args) {
}
}
|
package com.tencent.mm.pluginsdk.ui.tools;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
class AppChooserUI$5 implements OnDismissListener {
final /* synthetic */ AppChooserUI qRB;
AppChooserUI$5(AppChooserUI appChooserUI) {
this.qRB = appChooserUI;
}
public final void onDismiss(DialogInterface dialogInterface) {
this.qRB.finish();
}
}
|
package com.tencent.mm.g.a;
import com.tencent.mm.sdk.b.b;
public final class qg extends b {
public a caP;
public qg() {
this((byte) 0);
}
private qg(byte b) {
this.caP = new a();
this.sFm = false;
this.bJX = null;
}
}
|
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class FCITgradeBook {
public static void main(String[] args) throws FileNotFoundException {
File inputFile = new File("FCITgradeBook.in.txt");
File outputFile = new File("FCITgradeBook.out.txt");
PrintWriter write = new PrintWriter(outputFile);
if (!inputFile.exists()) {
write.println("Input file, " + inputFile + ", does not exist.");
write.flush();
write.close();
System.exit(0);
}
Scanner read = new Scanner(inputFile);
String command;
int numCourses = read.nextInt();
FCITcourseRoster[] courses = new FCITcourseRoster[numCourses];
write.println("Welcome to the FCIT Grade Book. ");
write.println("The following course(s) have been added to the database:");
for (int i = 0; i < numCourses; i++) {
courses[i] = new FCITcourseRoster();
String name = read.next();
courses[i].setCourseNumber(name);
write.println(" " + name);
}
write.println("");
while (read.hasNext()) {
command = read.next();
if (command.equals("ADDRECORD")) {
write.println("Command: ADDRECORD");
String courseNumber = read.next();
boolean found = false;
for (int i = 0; i < courses.length; i++) {
if (courses[i].getCourseNumber().equals(courseNumber)) {
found = true;
break;
}
}
if (!found) {
write.println(" ERROR: cannot add student. Course " + courseNumber + " does not exist.");
} else {
//int courseInd = getCourseInd(courseNumber);
int id = read.nextInt();
String firstName = read.next();
String lastName = read.next();
int exam_1 = read.nextInt();
int exam_2 = read.nextInt();
int exam_3 = read.nextInt();
double final_grade = exam_1 * (0.3) + exam_2 * (0.3) + exam_3 * (0.4);
char letter = getLetterGrade(final_grade);
Student std = new Student();
std.setCourseNumber(courseNumber);
std.setFirstName(firstName);
std.setLastName(lastName);
std.setID(id);
std.setLetterGrade(letter);
std.getExamGrades()[0] = exam_1;
std.getExamGrades()[1] = exam_2;
std.getExamGrades()[2] = exam_3;
std.setFinalGrade(final_grade);
for (int i = 0; i < courses.length; i++) {
if (std.getCourseNumber().equals(courses[i].getCourseNumber())) {
courses[i].insert(std);
}
}
write.print(" " + firstName + " " + lastName + " (ID# " + id
+ ") has been added to " + courseNumber + ".\n");
write.printf(" Final Grade: %.2f (%s)\n", final_grade, letter);
Student.setNumStudents(Student.getNumStudents() + 1);
write.println("");
}
} else if (command.equals("DELETERECORD")) {
write.println("Command: DELETERECORD");
int id = read.nextInt();
int counter = 0;
boolean there = true;
for (int i = 0; i < courses.length; i++) {
Student s = courses[i].findNode(id);
if (s != null) {
courses[i].delete(id);
Student.setNumStudents(Student.getNumStudents()-1);
write.println(" " + s.getFirstName()
+ " " + s.getLastName() + " (ID# " + s.getID()
+ ") has been deleted from " + s.getCourseNumber() + ".\n");
} else {
counter++;
}
}
if (counter == courses.length) {
write.println("student is not in the database!\n");
}
} else if (command.equals("SEARCHBYID")) {
write.println("Command: SEARCHBYID");
int id = read.nextInt();
Student s = null;
//find the student
int counter = 0;
for (int i = 0; i < courses.length; i++) {
s = courses[i].findNode(id);
if (s != null) {
break;
} else {
counter++;
}
}
if (counter == courses.length) {
write.println(" ERROR: there is no record for student ID# " + id + ".\n");
} else {
write.println("Student Record for "
+ s.getFirstName() + " " + s.getLastName()
+ " (ID# " + s.getID() + "):");
for (int i = 0; i < courses.length; i++) {
Student std = courses[i].findNode(id);
if (std != null) {
write.println(" Course: " + courses[i].getCourseNumber());
write.println(" Exam 1: " + std.getExamGrades()[0] + "\n"
+ " Exam 2: " + std.getExamGrades()[1] + "\n"
+ " Final Exam: " + std.getExamGrades()[2] + "");
write.printf(" \tFinal Grade: %.2f\n", std.getFinalGrade());
write.println(" Letter Grade: " + std.getLetterGrade());
}
}
}
write.println("");
} else if (command.equals("SEARCHBYNAME")) {
write.println("Command: SEARCHBYNAME");
String firstName = read.next();
String lastName = read.next();
Student s = null;
int counter = 0;
for (int i = 0; i < courses.length; i++) {
s = courses[i].findNodeByName(firstName, lastName);
if (s != null) {
break;
} else {
counter++;
}
}
if (counter == courses.length) {
write.println(" ERROR: there is no record for student \"" + firstName + " " + lastName + "\".");
} else {
write.println("Student Record for "
+ s.getFirstName() + " " + s.getLastName()
+ " (ID# " + s.getID() + "):");
for (int i = 0; i < courses.length; i++) {
Student std = courses[i].findNodeByName(firstName, lastName);
if (std != null) {
write.println(" Course: " + courses[i].getCourseNumber());
write.println(" Exam 1: " + std.getExamGrades()[0] + "\n"
+ " Exam 2: " + std.getExamGrades()[1] + "\n"
+ " Final Exam: " + std.getExamGrades()[2] + "");
write.printf(" \tFinal Grade: %.2f\n", std.getFinalGrade());
write.println(" Letter Grade: " + std.getLetterGrade());
}
}
}
write.println("");
} else if (command.equals("DISPLAYSTATS")) {
String all = read.next();
if (all.equals("ALL")) {
write.println("Command: DISPLAYSTATS (ALL)\n"
+ "Statistical Results of all courses:\n"
+ "Total number of student records: " + Student.getNumStudents());
courses[0].calculate_All_course(courses, write);
} else {
for (int i = 0; i < courses.length; i++) {
if (all.equals(courses[i].getCourseNumber())) {
write.println("Command: DISPLAYSTATS (" + all + ")\n"
+ "Statistical Results of " + all + ":\n"
+ "Total number of student records: " + courses[i].countStudents());
courses[i].calculate_course( write);
}
}
}
write.println("");
} else if (command.equals("DISPLAYSTUDENTS")) {
String str = read.next();
write.println("Command: DISPLAYSTUDENTS " + str);
if (Student.getNumStudents() < 1) {
write.println("\t\tERROR: there are no students currently in the system.");
} else {
write.println("");
if (str.equals("ALL")) {
for (int i = 0; i < courses.length; i++) {
write.println("Course Roster for " + courses[i].getCourseNumber() + ":");
courses[i].displayStudents(write);
}
} else {
for (int i = 0; i < courses.length; i++) {
if (str.equals("" + courses[i].getCourseNumber() + "")) {
if (courses[i].getHead() == null) {
write.println(" ERROR: there are no student records for " + str + ".");
continue;
} else {
write.println("Course Roster for " + str + ":");
courses[i].displayStudents(write);
}
}
}
}
}
write.println("");
} else if (command.equals("QUIT")) {
write.println("Thank you for using the the FCIT Grade Book.\n"
+ "\n"
+ "Goodbye.");
write.flush();
write.close();
System.exit(0);
}
}
}
public static char getLetterGrade(double final_grade) {
if (final_grade < 60) {
return 'F';
} else if (final_grade >= 70 && final_grade < 80) {
return 'C';
} else if (final_grade >= 80 && final_grade < 90) {
return 'B';
} else if (final_grade >= 90) {
return 'A';
} else if (final_grade >= 60 && final_grade < 70) {
return 'D';
}
return 'Z';
}
}
|
package com.yoyuapp.sqlbuilder;
public class UpdateSetSegment extends UpdateSql{
public UpdateSetSegment set(SqlColumn column, Object value){
UpdateSetSegment up = new UpdateSetSegment();
up.sb = this.sb;
up.params = this.params;
up.sb.append(", ");
sb.append(column.sb).append(" = ?");
up.params.add(value);
return up;
}
public UpdateSql where(WhereSegment conj){
this.sb.append(" WHERE ").append(conj.toString());
this.params.addAll(conj.params);
return this;
}
}
|
package br.com.sistemamedico.config;
import br.com.sistemamedico.controllers.PacienteController;
import br.com.sistemamedico.daos.PacienteDao;
import br.com.sistemamedico.services.PacienteService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.datetime.DateFormatterRegistrar;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@EnableWebMvc
@ComponentScan(basePackageClasses = {PacienteController.class, PacienteDao.class, PacienteService.class})
public class ConfiguracaoDaAplicacao extends WebMvcConfigurerAdapter {
@Bean//Avisa que esse método vai retornar uma classe gerenciada pelo Spring
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");//Evita de ficar mostrando a extensão do arquivo
return resolver;
}
@Bean
public FormattingConversionService mvcConversionService() {//O Spring espera que o nome do método seja esse, então não use outro nome
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
DateFormatterRegistrar registrador = new DateFormatterRegistrar();
registrador.setFormatter(new DateFormatter("dd/MM/yyyy"));
registrador.registerFormatters(conversionService);
return conversionService;
}
//Método sobrescrido da classe extendida que permite o uso do CSS,..., pois libera o acesso a pasta resources
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
|
package de.jmda.app.xstaffr.common.domain;
import javax.annotation.Generated;
import javax.persistence.metamodel.SetAttribute;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="Dali", date="2018-03-15T10:57:07.385+0100")
@StaticMetamodel(Customer.class)
public class Customer_ {
public static volatile SingularAttribute<Customer, Long> id;
public static volatile SetAttribute<Customer, Project> projects;
public static volatile SingularAttribute<Customer, String> name;
}
|
package yao.servlet.languageServlet;
import yao.bean.Language;
import yao.service.LanguageService;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
public class ListLanguagesServlet extends HttpServlet {
private static final String LIST_LANGUAGES = "listLanguage.jsp";
private LanguageService languageService;
private List<Language> languageList;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
languageService = new LanguageService();
HttpSession session = request.getSession();
languageList = languageService.getAllLanguage();
session.setAttribute("languageList",languageList);
request.getRequestDispatcher(LIST_LANGUAGES).forward(request,response);
}
}
|
package com.ge.smartparking.entity;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
/**
* The persistent class for the SEARCH_COUNT database table.
*
*/
@Entity
@Table(name="SEARCH_COUNT")
@NamedQuery(name="SearchCount.findAll", query="SELECT s FROM SearchCount s")
public class SearchCount implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name="cid_GENERATOR", sequenceName="NEW_PARK_SEQ")
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="cid_GENERATOR")
@Column(name="cid")
private long cid;
@Column(name="LOC_ID")
private BigDecimal locId;
@Column(name="SEARCH_STATUS")
private String searchStatus;
public SearchCount() {
}
/**
* @return the cid
*/
public long getCid() {
return this.cid;
}
/**
* @param cid the cid to set
*/
public void setCid(long cid) {
this.cid = cid;
}
public BigDecimal getLocId() {
return this.locId;
}
public void setLocId(BigDecimal locId) {
this.locId = locId;
}
public String getSearchStatus() {
return this.searchStatus;
}
public void setSearchStatus(String searchStatus) {
this.searchStatus = searchStatus;
}
}
|
package com.geekhelp.service.comment.exception;
/**
* Created by V.Odahovskiy.
* Date 10.02.2015
* Time 7:45
* Package com.geekhelp.service.comment.exception
*/
public class CommentNotFoundException extends Exception{
public CommentNotFoundException() {
super("Comment not found");
}
public CommentNotFoundException(String msg){
super(msg);
}
public CommentNotFoundException(Long id) {
super("Comment with id " + id + " not found");
}
}
|
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.form.onboarding.service.impl;
import com.liferay.form.onboarding.constants.OnboardingFormConstants;
import com.liferay.form.onboarding.model.OBFormEntry;
import com.liferay.form.onboarding.service.base.OBFormEntryServiceBaseImpl;
import com.liferay.portal.aop.AopService;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.security.permission.ActionKeys;
import com.liferay.portal.kernel.security.permission.resource.ModelResourcePermission;
import com.liferay.portal.kernel.security.permission.resource.PortletResourcePermission;
import com.liferay.portal.kernel.service.ServiceContext;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
/**
* The implementation of the ob form entry remote service.
*
* <p>
* All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the <code>com.liferay.form.onboarding.service.OBFormEntryService</code> interface.
*
* <p>
* This is a remote service. Methods of this service are expected to have security checks based on the propagated JAAS credentials because this service can be accessed remotely.
* </p>
*
* @author Brian Wing Shun Chan
* @see OBFormEntryServiceBaseImpl
*/
@Component(
property = {
"json.web.service.context.name=obform",
"json.web.service.context.path=OBFormEntry"
},
service = AopService.class
)
public class OBFormEntryServiceImpl extends OBFormEntryServiceBaseImpl {
/**
* NOTE FOR DEVELOPERS:
*
* Never reference this class directly. Always use <code>com.liferay.form.onboarding.service.OBFormEntryServiceUtil</code> to access the ob form entry remote service.
*/
@Override
public OBFormEntry addOBFormEntry(
long userId, String name, long formId,
ServiceContext serviceContext)
throws PortalException {
_portletResourcePermission.check(
getPermissionChecker(), serviceContext.getScopeGroupId(),
ActionKeys.ADD_ENTRY);
return obFormEntryLocalService.addOBFormEntry(
userId, name, formId, serviceContext);
}
@Override
public OBFormEntry deleteOBFormEntry(long obFormEntryId)
throws PortalException {
_obFormEntryModelResourcePermission.check(
getPermissionChecker(), obFormEntryId, ActionKeys.DELETE);
return obFormEntryLocalService.deleteOBFormEntry(obFormEntryId);
}
@Override
public OBFormEntry updateOBFormEntry(
long userId, long obFormEntryId, String name,
long[] organizationIds, long[] roleIds, long[] siteIds,
long[] userGroupIds, boolean sendEmail, boolean active,
ServiceContext serviceContext)
throws PortalException {
_obFormEntryModelResourcePermission.check(
getPermissionChecker(), obFormEntryId, ActionKeys.UPDATE);
return obFormEntryLocalService.updateOBFormEntry(
userId, obFormEntryId, name, organizationIds, roleIds, siteIds,
userGroupIds, sendEmail, active, serviceContext);
}
@Reference(
policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY,
target = "(model.class.name=com.liferay.form.onboarding.model.OBFormEntry)"
)
private volatile ModelResourcePermission<OBFormEntry>
_obFormEntryModelResourcePermission;
@Reference(
policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY,
target = "(resource.name=" + OnboardingFormConstants.RESOURCE_NAME + ")"
)
private volatile PortletResourcePermission _portletResourcePermission;
}
|
package co.jjsolarte.climaapp;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
import co.jjsolarte.climaapp.controller.ListaActivity;
import co.jjsolarte.climaapp.model.City;
import co.jjsolarte.climaapp.services.PostServices;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
EditText edtCity;
Button btnBuscar;
// AdapterLista adapterLista;
public static List<City> cityList;
RecyclerView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtCity = findViewById(R.id.mainEdtCity);
btnBuscar = findViewById(R.id.mainBtnBuscar);
// listView = findViewById(R.id.mainList);
cityList = new ArrayList<>();
//
// adapterLista = new AdapterLista(cityList, R.layout.item_lista, this);
// listView.setHasFixedSize(true);
// listView.setAdapter((RecyclerView.Adapter) adapterLista);
// listView.setLayoutManager(new LinearLayoutManager(this));
// adapterLista.notifyDataSetChanged();
btnBuscar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Vamos a hacer la petición
//Mostramos resultados
getPosts();
}
});
}
private void getPosts() {
//Definir la url base
String url = "https://www.metaweather.com";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
//Interface que creamos
PostServices postService = retrofit.create(PostServices.class);
Call<List<City>> call = postService.getPost();
call.enqueue(new Callback<List<City>>() {
@Override
public void onResponse(Call<List<City>> call, Response<List<City>> response) {
for (City city : response.body()) {
// Toast.makeText(MainActivity.this, city.getTitle(), Toast.LENGTH_SHORT).show();
cityList.add(city);
}
// adapterLista.notifyDataSetChanged();
// arrayAdapter.notifyDataSetChanged();
mostrarLista();
}
@Override
public void onFailure(Call<List<City>> call, Throwable t) {
Toast.makeText(MainActivity.this, "Petición Fallida" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void mostrarLista() {
Intent intent = new Intent(this, ListaActivity.class);
startActivity(intent);
}
}
|
package sab.ifunpas.org;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
EditText editTextUsername, editTextPassword;
Button buttonLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
buttonLogin = (Button) findViewById(R.id.buttonLogin);
buttonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = editTextUsername.getText().toString();
String password = editTextPassword.getText().toString();
if (username.trim().equalsIgnoreCase("")) {
editTextUsername.setError("Username tidak boleh kosong");
editTextUsername.requestFocus();
} else if (password.trim().equalsIgnoreCase("")) {
editTextPassword.setError("Password tidak boleh kosong");
editTextPassword.requestFocus();
} else {
//disini kita akan melakukan 2 user yg bisa login yaitu
// (u:173040107, p:admin) untuk mahasiswa dan
// (u:admin, p:admin) untuk administrator
if (username.equalsIgnoreCase("admin") && password.equalsIgnoreCase("admin")) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("name", "Mahasiswa");
startActivity(intent);
LoginActivity.this.finish();
} else {
Toast.makeText(LoginActivity.this, "Username dan Password tidak sesuai", Toast.LENGTH_LONG).show();
}
}
}
});
}
}
|
package com.olfu.meis.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.olfu.meis.R;
import com.olfu.meis.adapter.MainPagerAdapter;
import com.olfu.meis.sliding.SlidingTabLayout;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* A simple {@link Fragment} subclass.
*/
public class MainFragment extends Fragment {
MainPagerAdapter adapter;
CharSequence titles[] = {"Latest" , "Forecast", "Aftershock"};
@Bind(R.id.tabs)
SlidingTabLayout tabs;
@Bind(R.id.pager)
ViewPager pager;
public MainFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main, container, false);
ButterKnife.bind(this, view);
setupPager();
return view;
}
private void setupPager() {
adapter = new MainPagerAdapter(getChildFragmentManager(), titles);
pager.setAdapter(adapter);
tabs.setDistributeEvenly(false);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
@Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.colorAccent);
}
});
tabs.setViewPager(pager);
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
}
|
//
// GCALDaemon is an OS-independent Java program that offers two-way
// synchronization between Google Calendar and various iCalalendar (RFC 2445)
// compatible calendar applications (Sunbird, Rainlendar, iCal, Lightning, etc).
//
// Apache License
// Version 2.0, January 2004
// http://www.apache.org/licenses/
//
// Project home:
// http://gcaldaemon.sourceforge.net
//
package org.gcaldaemon.core.ldap;
import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.StringTokenizer;
import net.fortuna.ical4j.model.DateTime;
import org.apache.commons.codec.net.QuotedPrintableCodec;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.gcaldaemon.core.Configurator;
import org.gcaldaemon.core.FilterMask;
import org.gcaldaemon.core.GmailContact;
import org.gcaldaemon.core.GmailEntry;
import org.gcaldaemon.core.GmailPool;
import org.gcaldaemon.core.StringUtils;
import org.gcaldaemon.logger.QuickWriter;
/**
* Periodic Gmail contact loader thread.
*
* Created: Jan 03, 2007 12:50:56 PM
*
* @author Andras Berkes
*/
public final class ContactLoader extends Thread {
// --- CONSTANTS ---
private static final String NATIVE_CHARSET = Charset.defaultCharset()
.name();
private static final String VCARD_EXTENSION = ".vcf";
private static final byte VCARD_UTF8_ENCODING = 0;
private static final byte VCARD_NATIVE_ENCODING = 1;
private static final byte VCARD_QUOTED_ENCODING = 2;
private static final int MAX_INDEX_GAP = 100;
// --- LOGGER ---
private static final Log log = LogFactory.getLog(ContactLoader.class);
// --- VARIABLES ---
private final Configurator configurator;
private final LDAPListener ldapListener;
private final long pollingTimeout;
private final File vcardDirectory;
private final byte vcardEncoding;
private final String vcardVersion;
private final String[] usernames;
private final String[] passwords;
private volatile GmailContact[] contacts;
// --- CONSTRUCTOR ---
public ContactLoader(ThreadGroup mainGroup, Configurator configurator)
throws Exception {
super(mainGroup, "Contact loader");
this.configurator = configurator;
this.vcardDirectory = new File(configurator.getWorkDirectory(), "vcard");
if (!vcardDirectory.isDirectory()) {
vcardDirectory.mkdirs();
}
// Acceptable hostnames
FilterMask[] hosts = configurator
.getFilterProperty(Configurator.LDAP_ALLOWED_HOSTNAMES);
// Acceptable TCP/IP addresses
FilterMask[] addresses = configurator
.getFilterProperty(Configurator.LDAP_ALLOWED_ADDRESSES);
// Get contact list cache timeout
long timeout = configurator.getConfigProperty(
Configurator.LDAP_CACHE_TIMEOUT, 3600000L);
if (timeout < 180000L) {
log.warn("The fastest contact list polling period is '3 min'!");
timeout = 180000L;
}
pollingTimeout = timeout;
// Get username/password pairs
LinkedList usernameList = new LinkedList();
LinkedList passwordList = new LinkedList();
String parameterPostfix;
int gapCounter = 0;
for (int i = 1;; i++) {
// Create parameter postfix [..n]
if (i == 1) {
parameterPostfix = "";
} else {
parameterPostfix = Integer.toString(i);
}
if (configurator.getConfigProperty(
Configurator.LDAP_GOOGLE_USERNAME + parameterPostfix, null) == null) {
if (gapCounter < MAX_INDEX_GAP) {
gapCounter++;
continue;
}
break;
}
gapCounter = 0;
// Get username
String username = configurator.getConfigProperty(
Configurator.LDAP_GOOGLE_USERNAME + parameterPostfix, null);
// Get password
String password = null;
if (configurator.getConfigProperty(
Configurator.LDAP_GOOGLE_PASSWORD + parameterPostfix, null) != null) {
password = configurator
.getPasswordProperty(Configurator.LDAP_GOOGLE_PASSWORD
+ parameterPostfix);
}
// Verify parameters
if (username == null) {
throw new NullPointerException("Missing username ("
+ Configurator.LDAP_GOOGLE_USERNAME + parameterPostfix
+ ")!");
}
if (password == null) {
throw new NullPointerException("Missing password ("
+ Configurator.LDAP_GOOGLE_PASSWORD + parameterPostfix
+ ")!");
}
// Add parameters to lists
usernameList.addLast(username);
passwordList.addLast(password);
}
// Create object arrays
usernames = new String[usernameList.size()];
passwords = new String[passwordList.size()];
usernameList.toArray(usernames);
passwordList.toArray(passwords);
if (hosts == null && addresses == null) {
// Security warning
log.warn("Set the '" + Configurator.LDAP_ALLOWED_HOSTNAMES
+ "' parameter to limit remote access.");
} else {
// Debug filters
if (log.isDebugEnabled()) {
log.debug("Allowed LDAP hosts: "
+ configurator.getConfigProperty(
Configurator.LDAP_ALLOWED_HOSTNAMES, "*"));
log.debug("Allowed LDAP addresses: "
+ configurator.getConfigProperty(
Configurator.LDAP_ALLOWED_ADDRESSES, "*"));
}
}
// Get vCard properties
String value = configurator.getConfigProperty(
Configurator.LDAP_VCARD_ENCODING, "quoted");
if (value.equals("quoted")) {
vcardEncoding = VCARD_QUOTED_ENCODING;
} else {
if (value.equals("native")) {
vcardEncoding = VCARD_NATIVE_ENCODING;
} else {
vcardEncoding = VCARD_UTF8_ENCODING;
}
}
value = configurator.getConfigProperty(Configurator.LDAP_VCARD_VERSION,
"3.0");
try {
double num = Double.parseDouble(value);
vcardVersion = Double.toString(num);
} catch (Exception formatError) {
log.fatal("Invalid vCard version: " + value);
throw formatError;
}
// Create and start LDAP listener
int port = (int) configurator.getConfigProperty(Configurator.LDAP_PORT,
9080);
ldapListener = new LDAPListener(this, hosts, addresses, port);
// Start listener
start();
}
// --- CONTACT LOADER LOOP ---
public final void run() {
for (;;) {
try {
// Load contact list
for (int tries = 0;; tries++) {
try {
loadContacts();
break;
} catch (Exception loadError) {
if (tries == 5) {
throw loadError;
}
log.debug("Connection refused, reconnecting...");
Thread.sleep(500);
}
}
// Wait
sleep(pollingTimeout);
} catch (InterruptedException interrupt) {
// Service stopped
return;
} catch (Exception loadError) {
log.error("Unable to load contact list!", loadError);
try {
sleep(pollingTimeout);
} catch (Exception interrupt) {
return;
}
}
}
}
// --- CONTACT LIST LOADER ---
private final void loadContacts() throws Exception {
// Loading contact list
log.debug("Loading Gmail contact list...");
GmailPool pool = configurator.getGmailPool();
LinkedList contactList = new LinkedList();
HashSet processedEntries = new HashSet();
String rev = new DateTime().toString();
HashSet cardFiles = new HashSet();
GmailEntry entry = null;
GmailContact contact;
String key, csv;
boolean found;
char[] chars;
int i, m, n;
char c;
// Loop on accounts
QuickWriter buffer = new QuickWriter();
for (n = 0; n < usernames.length; n++) {
try {
// Download CSV from Gmail
entry = pool.borrow(usernames[n], passwords[n]);
csv = entry.downloadCSV();
if (csv == null) {
continue;
}
// Remove header
chars = csv.toCharArray();
found = false;
i = -1;
for (m = 0; m < chars.length; m++) {
c = chars[m];
if (c == '\r' || c == '\n') {
found = true;
continue;
}
if (found) {
i = m;
break;
}
}
if (i != -1) {
buffer.write(chars, i, chars.length - i);
}
} finally {
pool.recycle(entry);
}
if (n < usernames.length - 1) {
Thread.sleep(1000);
}
}
// Parse CSV to GmailContact array
csv = buffer.toString();
GmailContact[] contactArray = parseCSV(csv);
// Save 'contacts.csv' in UTF8 into the 'work/vcard' dir
File file = new File(vcardDirectory, "contacts.csv");
byte[] bytes = StringUtils.encodeString(csv, StringUtils.UTF_8);
saveFile(file, bytes);
// Process contacts
if (contactArray == null) {
contactArray = new GmailContact[0];
}
for (i = 0; i < contactArray.length; i++) {
// Verify email address and name field
contact = contactArray[i];
if (contact.email.length() == 0) {
// Use the secondary email address
contact.email = contact.mail;
}
if (contact.name.length() == 0) {
// Create name from the email address
contact.name = contact.email;
m = contact.name.indexOf('@');
if (m != -1) {
contact.name = contact.name.substring(0, m);
}
}
// Fix MS Address Book bug
if (contact.email.indexOf('@') == -1) {
continue;
}
key = contact.email + '\t' + contact.name;
if (processedEntries.contains(key)) {
continue;
}
processedEntries.add(key);
if (contact.email.length() != 0) {
// Save vcard with name and email address
contactList.addLast(contact);
} else {
if (contact.name.length() != 0) {
// Save vcard without email address
cardFiles.add(saveVCard(contact, rev));
}
}
}
GmailContact[] array = new GmailContact[contactList.size()];
contactList.toArray(array);
// Save contacts withall email addresses
for (i = 0; i < array.length; i++) {
cardFiles.add(saveVCard(array[i], rev));
}
// Save contact in other formats (eg. HTML)
saveContacts(vcardDirectory, array, buffer);
// Remove deleted contacts
String[] currentFiles = vcardDirectory.list();
String fileName;
for (i = 0; i < currentFiles.length; i++) {
fileName = currentFiles[i];
if (fileName.endsWith(VCARD_EXTENSION)
&& !cardFiles.contains(fileName)) {
(new File(vcardDirectory, fileName)).delete();
}
}
// Contact list loaded
synchronized (this) {
contacts = array;
}
log.debug(array.length + " contacts loaded successfully.");
}
private static final void saveContacts(File vcardDirectory,
GmailContact[] array, QuickWriter buffer) throws Exception {
GmailContact contact;
byte[] bytes;
File file;
int i;
// Save HTML
buffer.flush();
buffer.write("<html>\r\n");
buffer.write("<head>\r\n");
buffer.write("<title>Contacts</title>\r\n");
buffer.write("<meta http-equiv=\"content-type\" ");
buffer.write("content=\"text/html; charset=UTF-8\"/>\r\n");
buffer.write("<style type=\"text/css\">\r\n");
buffer.write("td {font-size: 11px; font-family: Arial,Helvetica;}\r\n");
buffer.write("th {font-size: 11px; font-family: Arial,Helvetica;}\r\n");
buffer.write("</style>\r\n");
buffer.write("</head>\r\n");
buffer.write("<body>\r\n");
buffer.write("<table border=\"0\" cellspacing=\"0\" ");
buffer.write("cellpadding=\"5\">\r\n");
buffer.write("<tr bgcolor=\"lightgray\">");
buffer.write("<th>NAME</th>");
buffer.write("<th>MAIL</th>");
buffer.write("<th>NOTES</th>");
buffer.write("<th>DESCR</th>");
buffer.write("<th>MAIL2</th>");
buffer.write("<th>IM</th>");
buffer.write("<th>PHONE</th>");
buffer.write("<th>MOBILE</th>");
buffer.write("<th>PAGER</th>");
buffer.write("<th>FAX</th>");
buffer.write("<th>COMPANY</th>");
buffer.write("<th>TITLE</th>");
buffer.write("<th>OTHER</th>");
buffer.write("<th>ADDRESS</th>");
buffer.write("</tr>\r\n");
for (i = 0; i < array.length; i++) {
contact = array[i];
if (i % 2 != 1) {
buffer.write("<tr>");
} else {
buffer.write("<tr bgcolor=\"lightgray\">");
}
buffer.write("<td>");
buffer.write(contact.name);
buffer.write(" </td>");
buffer.write("<td>");
buffer.write(contact.email.replace(",", ", "));
buffer.write(" </td>");
buffer.write("<td>");
buffer.write(contact.notes);
buffer.write(" </td>");
buffer.write("<td>");
buffer.write(contact.description);
buffer.write(" </td>");
buffer.write("<td>");
buffer.write(contact.mail);
buffer.write(" </td>");
buffer.write("<td>");
buffer.write(contact.im);
buffer.write(" </td>");
buffer.write("<td>");
buffer.write(contact.phone);
buffer.write(" </td>");
buffer.write("<td>");
buffer.write(contact.mobile);
buffer.write(" </td>");
buffer.write("<td>");
buffer.write(contact.pager);
buffer.write(" </td>");
buffer.write("<td>");
buffer.write(contact.fax);
buffer.write(" </td>");
buffer.write("<td>");
buffer.write(contact.company);
buffer.write(" </td>");
buffer.write("<td>");
buffer.write(contact.title);
buffer.write(" </td>");
buffer.write("<td>");
buffer.write(contact.other);
buffer.write(" </td>");
buffer.write("<td>");
buffer.write(contact.address);
buffer.write(" </td>");
buffer.write("</tr>\r\n");
}
buffer.write("</table>\r\n");
buffer.write("</body>\r\n");
buffer.write("</html>");
file = new File(vcardDirectory, "contacts.html");
bytes = StringUtils.encodeString(buffer.toString(), StringUtils.UTF_8);
saveFile(file, bytes);
// Save XML
buffer.flush();
buffer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
buffer.write("<address-book>\r\n");
for (i = 0; i < array.length; i++) {
contact = array[i];
buffer.write("\t<contact>\r\n");
buffer.write("\t\t<name>");
buffer.write(contact.name);
buffer.write("</name>\r\n");
buffer.write("\t\t<email>");
buffer.write(contact.email.replace(",", ", "));
buffer.write("</email>\r\n");
buffer.write("\t\t<notes>");
buffer.write(contact.notes);
buffer.write("</notes>\r\n");
buffer.write("\t\t<description>");
buffer.write(contact.description);
buffer.write("</description>\r\n");
buffer.write("\t\t<mail>");
buffer.write(contact.mail);
buffer.write("</mail>\r\n");
buffer.write("\t\t<im>");
buffer.write(contact.im);
buffer.write("</im>\r\n");
buffer.write("\t\t<phone>");
buffer.write(contact.phone);
buffer.write("</phone>\r\n");
buffer.write("\t\t<mobile>");
buffer.write(contact.mobile);
buffer.write("</mobile>\r\n");
buffer.write("\t\t<pager>");
buffer.write(contact.pager);
buffer.write("</pager>\r\n");
buffer.write("\t\t<fax>");
buffer.write(contact.fax);
buffer.write("</fax>\r\n");
buffer.write("\t\t<company>");
buffer.write(contact.company);
buffer.write("</company>\r\n");
buffer.write("\t\t<title>");
buffer.write(contact.title);
buffer.write("</title>\r\n");
buffer.write("\t\t<other>");
buffer.write(contact.other);
buffer.write("</other>\r\n");
buffer.write("\t\t<address>");
buffer.write(contact.address);
buffer.write("</address>\r\n");
buffer.write("\t</contact>\r\n");
}
buffer.write("</address-book>");
file = new File(vcardDirectory, "contacts.xml");
bytes = StringUtils.encodeString(buffer.toString(), StringUtils.UTF_8);
saveFile(file, bytes);
}
private static final void saveFile(File file, byte[] bytes)
throws Exception {
FileOutputStream out = null;
for (int retries = 0;; retries++) {
try {
out = new FileOutputStream(file);
out.write(bytes);
out.flush();
out.close();
out = null;
break;
} catch (Exception lockedError) {
if (out != null) {
try {
out.close();
} catch (Exception ignored) {
}
out = null;
}
if (retries == 5) {
throw lockedError;
}
Thread.sleep(500);
}
}
}
private static final GmailContact[] parseCSV(String csv) {
// Parse lines
if (csv == null) {
return null;
}
LinkedList contactList = new LinkedList();
StringTokenizer st = new StringTokenizer(csv, "\r\n");
while (st.hasMoreTokens()) {
GmailContact contact = parseLine(st.nextToken());
if (contact != null) {
if (contact.name.length() == 0 && contact.email.length() == 0) {
continue;
}
contactList.addLast(contact);
}
}
// Convert list to array
GmailContact[] array = new GmailContact[contactList.size()];
contactList.toArray(array);
// Return contact array
return array;
}
private static final GmailContact parseLine(String line) {
if (line.length() == 0) {
return null;
}
// Create contact container (GmailContact)
GmailContact contact = new GmailContact();
StringBuffer buffer = new StringBuffer();
int offset = 0;
int index = 0;
String value;
do {
buffer.setLength(0);
if (offset < line.length() && line.charAt(offset) == '"') {
// Parse quoted value (e.g. "Tom McCain", "xy@foo.com")
offset = parseSeparatedValue(line, buffer, ++offset);
} else {
// Parse simple value (e.g. Tom, xy@foo.com, etc)
offset = parsePlainValue(line, buffer, offset);
}
value = buffer.toString();
switch (index) {
case 0:
// Set the 'name' field
contact.name = value;
break;
case 1:
// Set the 'email' field
contact.email = value;
break;
case 2:
// Set the 'notes' field
contact.notes = value;
break;
case 3:
// Set the 'description' field
contact.description = value;
break;
case 4:
// Set the 'mail' field
contact.mail = value;
break;
case 5:
// Set the 'im' field
contact.im = value;
break;
case 6:
// Set the 'phone' field
contact.phone = value;
break;
case 7:
// Set the 'mobile' field
contact.mobile = value;
break;
case 8:
// Set the 'pager' field
contact.pager = value;
break;
case 9:
// Set the 'fax' field
contact.fax = value;
break;
case 10:
// Set the 'company' field
contact.company = value;
break;
case 11:
// Set the 'title' field
contact.title = value;
break;
case 12:
// Set the 'other' field
contact.other = value;
break;
case 13:
// Set the 'address' field
contact.address = value;
break;
}
offset++;
index++;
if (index == 14) {
break;
}
} while (offset < line.length());
return contact;
}
private final String saveVCard(GmailContact contact, String rev) {
String name = contact.email.toLowerCase();
if (name.length() == 0) {
name = contact.name.toLowerCase();
}
name = name.trim();
if (name.length() == 0 || name.indexOf('=') != -1) {
return VCARD_EXTENSION;
}
char[] chars = name.toCharArray();
QuickWriter writer = new QuickWriter(chars.length);
boolean writeMinus = true;
char c;
int i;
for (i = 0; i < chars.length; i++) {
c = chars[i];
if (c != '_' && Character.isJavaIdentifierPart(c)) {
writer.write(c);
writeMinus = true;
continue;
}
if (c == ',') {
break;
}
if (writeMinus) {
writer.write('-');
writeMinus = false;
}
}
name = writer.toString() + VCARD_EXTENSION;
File file = new File(vcardDirectory, name);
FileOutputStream out = null;
try {
writer = new QuickWriter(500);
String encoding = StringUtils.UTF_8;
String displayName = contact.name;
if (displayName.length() == 0) {
return VCARD_EXTENSION;
}
String firstName = null;
String lastName = null;
i = displayName.indexOf(' ');
if (i != -1) {
firstName = displayName.substring(0, i);
lastName = displayName.substring(i + 1);
}
// Write vCard
writer.write("BEGIN:VCARD\r\n");
if (vcardVersion.charAt(0) == '3') {
writer.write("VERSION:");
writer.write(vcardVersion);
writer.write("\r\nPRODID:");
writer.write(Configurator.VERSION);
writer.write("\r\n");
} else {
writer.write("VERSION:2.1\r\n");
}
switch (vcardEncoding) {
case VCARD_UTF8_ENCODING:
// Pure UTF8 vCard format
writer.write("X-LOTUS-CHARSET:UTF-8\r\n");
writer.write("FN;CHARSET=UTF-8:");
writer.write(displayName);
if (firstName != null) {
// Name
writer.write("\r\nN;CHARSET=UTF-8:");
writer.write(firstName);
writer.write(';');
writer.write(lastName);
writer.write(";;;");
}
if (contact.notes.length() != 0) {
// Notes
writer.write("\r\nNOTE;CHARSET=UTF-8:");
writer.write(contact.notes);
}
if (contact.address.length() != 0) {
// Address
if (vcardVersion.charAt(0) == '3') {
writer.write("\r\nADR;TYPE=HOME;CHARSET=UTF-8:");
} else {
writer.write("\r\nADR;HOME;CHARSET=UTF-8:");
}
writer.write(contact.address);
}
break;
case VCARD_NATIVE_ENCODING:
// Native vCard format
encoding = NATIVE_CHARSET;
writer.write("X-LOTUS-CHARSET:");
writer.write(NATIVE_CHARSET);
writer.write("\r\nFN:");
writer.write(displayName);
i = displayName.indexOf(' ');
if (firstName != null) {
// Name
writer.write("\r\nN:");
writer.write(firstName);
writer.write(';');
writer.write(lastName);
}
if (contact.notes.length() != 0) {
// Notes
writer.write("\r\nNOTE:");
writer.write(contact.notes);
}
if (contact.address.length() != 0) {
// Address
if (vcardVersion.charAt(0) == '3') {
writer.write("\r\nADR;TYPE=HOME:");
} else {
writer.write("\r\nADR;HOME:");
}
writer.write(contact.address);
}
break;
default:
// Quoted-printable vCard format
encoding = StringUtils.US_ASCII;
writer.write("X-LOTUS-CHARSET:UTF-8\r\n");
writer.write("FN;QUOTED-PRINTABLE:");
writer.write(encodeQuotedPrintable(displayName));
i = displayName.indexOf(' ');
if (firstName != null) {
// Name
writer.write("\r\nN;QUOTED-PRINTABLE:");
writer.write(encodeQuotedPrintable(firstName));
writer.write(';');
writer.write(encodeQuotedPrintable(lastName));
}
if (contact.notes.length() != 0) {
// Notes
writer.write("\r\nNOTE;QUOTED-PRINTABLE:");
writer.write(encodeQuotedPrintable(contact.notes));
}
if (contact.address.length() != 0) {
// Address
if (vcardVersion.charAt(0) == '3') {
writer.write("\r\nADR;TYPE=HOME;QUOTED-PRINTABLE:");
} else {
writer.write("\r\nADR;HOME;QUOTED-PRINTABLE:");
}
writer.write(encodeQuotedPrintable(contact.address));
}
}
if (contact.email.length() != 0) {
// Default email
if (vcardVersion.charAt(0) == '3') {
writer.write("\r\nEMAIL;TYPE=PREF;TYPE=INTERNET:");
} else {
writer.write("\r\nEMAIL;PREF;INTERNET:");
}
writer.write(contact.email);
}
if (contact.mail.length() != 0) {
// Additional email
if (vcardVersion.charAt(0) == '3') {
writer.write("\r\nEMAIL;TYPE=INTERNET:");
} else {
writer.write("\r\nEMAIL;INTERNET:");
}
writer.write(contact.mail);
}
if (contact.phone.length() != 0) {
// Phone number
if (vcardVersion.charAt(0) == '3') {
writer.write("\r\nTEL;TYPE=HOME:");
} else {
writer.write("\r\nTEL;HOME:");
}
writer.write(contact.phone);
}
writer.write("\r\nREV:");
writer.write(rev);
writer.write("\r\nEND:VCARD\r\n");
byte[] bytes;
if (encoding.equals(StringUtils.US_ASCII)) {
bytes = writer.getBytes();
} else {
bytes = StringUtils.encodeString(writer.toString(), encoding);
}
for (int retries = 0;; retries++) {
try {
out = new FileOutputStream(file);
out.write(bytes);
out.flush();
out.close();
out = null;
break;
} catch (Exception lockedError) {
if (out != null) {
try {
out.close();
} catch (Exception ignored) {
}
out = null;
}
if (retries == 5) {
throw lockedError;
}
Thread.sleep(500);
}
}
} catch (Exception ioError) {
log.warn(ioError);
if (file != null) {
if (out != null) {
try {
out.close();
} catch (Exception ignored) {
}
}
file.delete();
}
}
return name;
}
private static final String encodeQuotedPrintable(String string)
throws Exception {
byte[] bytes = StringUtils.encodeString(string, StringUtils.UTF_8);
bytes = QuotedPrintableCodec.encodeQuotedPrintable(null, bytes);
return StringUtils.decodeToString(bytes, StringUtils.US_ASCII);
}
private static final int parsePlainValue(String line, StringBuffer buffer,
int offset) {
// Parse the next plain value (e.g. Tom, xy@foo.com, etc)
int nextOffset = line.indexOf(',', offset);
if (nextOffset == -1) {
buffer.append(line.substring(offset));
return line.length();
}
buffer.append(line.substring(offset, nextOffset));
return nextOffset;
}
private static final int parseSeparatedValue(String line,
StringBuffer buffer, int offset) {
int nextOffset;
int len = line.length();
// Loop on the quoted value (e.g. "xy@foo.com")
for (nextOffset = offset; nextOffset < len; nextOffset++) {
if (line.charAt(nextOffset) == '"' && nextOffset + 1 < len) {
if (line.charAt(nextOffset + 1) == '"') {
nextOffset++;
} else if (line.charAt(nextOffset + 1) == ',') {
nextOffset++;
break;
}
} else {
if (line.charAt(nextOffset) == '"' && nextOffset + 1 == len) {
break;
}
}
buffer.append(line.charAt(nextOffset));
}
return nextOffset;
}
// --- STOP SERVICE ---
public final void interrupt() {
// Close server socket and stop listener
if (ldapListener != null) {
try {
ldapListener.interrupt();
} catch (Exception closeError) {
log.debug(closeError);
}
}
// Interrupt thread
super.interrupt();
}
// --- GMAIL CONTACT GETTER ---
public final synchronized GmailContact[] getContacts() {
if (contacts == null) {
try {
// Network down - load contacts from vcards
File file = new File(vcardDirectory, "contacts.csv");
if (!file.isFile()) {
return new GmailContact[0];
}
RandomAccessFile raf = new RandomAccessFile(file, "r");
byte[] bytes = new byte[(int) raf.length()];
raf.readFully(bytes);
raf.close();
String csv = StringUtils.decodeToString(bytes,
StringUtils.UTF_8);
contacts = parseCSV(csv);
log.debug(contacts.length + " contacts loaded successfully.");
} catch (Exception ioError) {
log.warn(ioError);
}
}
return contacts;
}
}
|
package com.home;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class MessageGenerator implements Runnable {
private QueueWriter queueWriter = QueueWriter.getInstance();
private int maxPriority;
private int delay;
private int duration;
private int msgLength;
private static final String ALPHA_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private Random random = new Random();
private StringBuilder builder = new StringBuilder();
public MessageGenerator(int msgLength, int maxPriority, int duration, int delay) {
if (msgLength <= 0 || maxPriority <= 0
|| duration <= 0 || delay <= 0) {
throw new IllegalArgumentException("Input parameters are not valid! Need to be bigger zero");
}
this.msgLength = msgLength;
this.maxPriority = maxPriority;
this.delay = delay;
this.duration = duration;
}
@Override
public void run() {
long start;
long durationMillis = TimeUnit.SECONDS.toMillis(duration);
ArrayList<Message> batch;
while (true) {
start = System.currentTimeMillis();
batch = new ArrayList<>();
while (System.currentTimeMillis() - start <= durationMillis) {
Message msg = generateMessage();
batch.add(msg);
}
queueWriter.write(batch);
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
System.out.print(e.getMessage());
Thread.currentThread().interrupt();
}
}
}
Message generateMessage() {
int priority = random.nextInt(maxPriority) + 1;
return new Message(generateRandomString(), priority);
}
private String generateRandomString() {
builder.setLength(0);
int length = msgLength;
while (length-- != 0) {
int character = (int) (Math.random() * ALPHA_STRING.length());
builder.append(ALPHA_STRING.charAt(character));
}
return builder.toString();
}
}
|
package interviews.amazon.oa1.tree;
import common.TreeNode;
public class MaximumPath {
public int minPath(TreeNode root) {
if (root == null) return 0;
int left = minPath(root.left);
int right = minPath(root.right);
return Math.max(left, right) + root.val;
}
}
|
package com.facebook.react.modules.network;
import okhttp3.m;
public interface CookieJarContainer extends m {
void removeCookieJar();
void setCookieJar(m paramm);
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\modules\network\CookieJarContainer.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.petersoft.mgl.leltar;
import com.petersoft.mgl.model.Alkatresz;
public class Keszlet {
private Integer id;
private Alkatresz alkatresz;
private RaktarHely raktarHely;
private Integer darabszam;
}
|
package com.tencent.mm.ui.i;
import android.os.Bundle;
public interface b$a {
void cAp();
void m(Bundle bundle);
void onCancel();
}
|
package com.tencent.mm.plugin.wenote.model.nativenote.b;
import android.support.v7.widget.RecyclerView;
import com.tencent.mm.plugin.wenote.model.nativenote.manager.WXRTEditText;
public interface a {
void Bo(int i);
void Bp(int i);
void Bq(int i);
void Br(int i);
void Q(int i, long j);
void a(WXRTEditText wXRTEditText);
void a(WXRTEditText wXRTEditText, boolean z, int i);
void bZl();
void bZm();
void bZn();
void bZo();
void bZp();
void bZq();
void bZr();
void bZs();
int bZt();
int bZu();
boolean bZv();
RecyclerView bZw();
void bZx();
void bZy();
void e(boolean z, long j);
void en(int i, int i2);
void eo(int i, int i2);
void ep(int i, int i2);
void kr(boolean z);
void m(Object obj, boolean z);
}
|
package com.hesoyam.pharmacy.user.exceptions;
public class UserPenalizedException extends RuntimeException{
public UserPenalizedException(Long id){
super(String.format("User with ID '%s' has 3 or more penalty points", id));
}
}
|
package com.research.runtime;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
/**
* @fileName: ErrorRestartStrategy.java
* @description: 错误重启设置
* @author: by echo huang
* @date: 2020-03-10 14:31
*/
public class ErrorRestartStrategy {
public static void main(String[] args) {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
//task重启策略配置
env.setRestartStrategy(RestartStrategies.fallBackRestart());
}
}
|
package com.komaxx.komaxx_gl;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLDisplay;
import android.opengl.GLSurfaceView;
import com.komaxx.komaxx_gl.util.KoLog;
import com.komaxx.komaxx_gl.util.RenderUtil;
/**
* This class essentially handles the GL
*
* @author Matthias Schicker
*/
public class GlConfigChooser implements GLSurfaceView.EGLConfigChooser {
private final GlConfig glConfig;
public GlConfigChooser(GlConfig glConfig) {
this.glConfig = glConfig;
}
@Override
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
mValue = new int[1];
int[] configSpec = null;
int numConfigs = 0;
if (glConfig.multisampling){
// Try to find a normal multisample configuration first.
configSpec = new int[]{
EGL10.EGL_RED_SIZE, glConfig.colorDepth.getR(),
EGL10.EGL_GREEN_SIZE, glConfig.colorDepth.getG(),
EGL10.EGL_BLUE_SIZE, glConfig.colorDepth.getB(),
EGL10.EGL_ALPHA_SIZE, glConfig.colorDepth.getA(),
EGL10.EGL_DEPTH_SIZE, glConfig.depthBufferBits.toValue(),
// Requires that setEGLContextClientVersion(2) is called on the view.
EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */,
EGL10.EGL_SAMPLE_BUFFERS, 1 /* true */,
EGL10.EGL_SAMPLES, 4,
EGL10.EGL_NONE
};
if (!egl.eglChooseConfig(display, configSpec, null, 0, mValue)) {
throw new IllegalArgumentException("eglChooseConfig failed");
}
numConfigs = mValue[0];
}
if (numConfigs <= 0) {
if (glConfig.multisampling){
// No normal multisampling config was found. Try to create a
// converage multisampling configuration, for the nVidia Tegra2.
// See the EGL_NV_coverage_sample documentation.
final int EGL_COVERAGE_BUFFERS_NV = 0x30E0;
final int EGL_COVERAGE_SAMPLES_NV = 0x30E1;
configSpec = new int[]{
EGL10.EGL_RED_SIZE, glConfig.colorDepth.getR(),
EGL10.EGL_GREEN_SIZE, glConfig.colorDepth.getG(),
EGL10.EGL_BLUE_SIZE, glConfig.colorDepth.getB(),
EGL10.EGL_ALPHA_SIZE, glConfig.colorDepth.getA(),
EGL10.EGL_DEPTH_SIZE, glConfig.depthBufferBits.toValue(),
EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */,
EGL_COVERAGE_BUFFERS_NV, 1 /* true */,
EGL_COVERAGE_SAMPLES_NV, 2, // always 5 in practice on tegra 2
EGL10.EGL_NONE
};
if (!egl.eglChooseConfig(display, configSpec, null, 0,
mValue)) {
throw new IllegalArgumentException("2nd eglChooseConfig failed");
}
numConfigs = mValue[0];
}
if (numConfigs <= 0) {
// Give up, try without multisampling.
configSpec = new int[]{
EGL10.EGL_RED_SIZE, glConfig.colorDepth.getR(),
EGL10.EGL_GREEN_SIZE, glConfig.colorDepth.getG(),
EGL10.EGL_BLUE_SIZE, glConfig.colorDepth.getB(),
EGL10.EGL_ALPHA_SIZE, glConfig.colorDepth.getA(),
EGL10.EGL_DEPTH_SIZE, glConfig.depthBufferBits.toValue(),
EGL10.EGL_RENDERABLE_TYPE, 4 /* EGL_OPENGL_ES2_BIT */,
EGL10.EGL_NONE
};
if (!egl.eglChooseConfig(display, configSpec, null, 0,
mValue)) {
throw new IllegalArgumentException("3rd eglChooseConfig failed");
}
numConfigs = mValue[0];
if (numConfigs <= 0) {
throw new IllegalArgumentException("No configs match configSpec");
}
} else {
mUsesCoverageAa = true;
}
}
// Get all matching configurations.
EGLConfig[] configs = new EGLConfig[numConfigs];
if (!egl.eglChooseConfig(display, configSpec, configs, numConfigs,
mValue)) {
throw new IllegalArgumentException("data eglChooseConfig failed");
}
// CAUTION! eglChooseConfigs returns configs with higher bit depth
// first: Even though we asked for rgb565 configurations, rgb888
// configurations are considered to be "better" and returned first.
// You need to explicitly filter the data returned by eglChooseConfig!
int index = -1;
for (int i = 0; i < configs.length; ++i) {
if (findConfigAttrib(egl, display, configs[i], EGL10.EGL_RED_SIZE, 0) == glConfig.colorDepth.getR()) {
index = i;
break;
}
}
if (index == -1) {
KoLog.w(this, "Did not find sane config, using first");
index = 0;
}
EGLConfig config = configs.length > 0 ? configs[index] : null;
if (config == null) {
throw new IllegalArgumentException("No config chosen");
}
if (RenderConfig.GL_DEBUG) RenderUtil.checkGlError("choosing config");
return config;
}
private int findConfigAttrib(EGL10 egl, EGLDisplay display, EGLConfig config, int attribute, int defaultValue) {
if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) {
return mValue[0];
}
return defaultValue;
}
public boolean usesCoverageAa() {
return mUsesCoverageAa;
}
private int[] mValue;
private boolean mUsesCoverageAa;
}
|
package com.cszjkj.aisc.cm_user;
public class CmUserApplication {
}
|
package com.Java8特性.StreamAPI;
/*
* SteamAPI , 用于数据的计算操作,比如对非关系型数据库,提取全部数据,在java层面上对数据进行
* 筛选等操作。本身不存储数据。
*
* */
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Demo {
@Test
public void getStream_1(){
//通过集合获得Stream
Collection collection = new HashSet();
//获得串行的stream
Stream stream = collection.stream();
//获得并行处理的stream
Stream parallelStream = collection.parallelStream();
}
@Test
public void getStream_2(){
//通过数组获得
IntStream intStream = Arrays.stream(new int[]{1, 2, 3});
//通过自定义类型的数组获取
Stream<MyType> myTypeStream = Arrays.stream(new MyType[]{new MyType(), new MyType()});
//通过泛型指定类型
}
@Test
public void getStream_3(){
//通过自身方法获得,stream 的的对像是容器
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4);
}
@Test
public void getStream_4(){
//通过无限流获得
Stream.iterate(0,t -> t+1).limit(10).forEach(System.out :: println);
//方法引用
Stream<Double> generate = Stream.generate(Math::random);
}
}
class MyType{
private String name;
private int age;
}
|
package boj1436;
import java.util.Scanner;
public class Main1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int count = 0;
int value = 665;
while(count < n) {
value++;
if(String.valueOf(value).contains("666")) {
count++;
}
}
System.out.println(value);
}
}
|
package com.tencent.mm.plugin.game.ui;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.plugin.game.model.an;
import com.tencent.mm.plugin.game.model.be;
import com.tencent.mm.plugin.game.model.be.a;
import com.tencent.mm.plugin.game.model.d;
import com.tencent.mm.plugin.game.model.f;
import com.tencent.mm.pluginsdk.model.app.g;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
public final class u implements OnClickListener {
private d jNE;
int jNv = 0;
String jTR = null;
private int kcO;
private Context mContext;
public u(Context context) {
this.mContext = context;
}
public final void onClick(View view) {
if (view.getTag() instanceof d) {
this.jNE = (d) view.getTag();
x.i("MicroMsg.GameTMAssistClickListener", "Clicked appid = " + this.jNE.field_appId);
if (g.r(this.mContext, this.jNE.field_appId)) {
x.d("MicroMsg.GameTMAssistClickListener", "launchFromWX, appId = " + this.jNE.field_appId + ", pkg = " + this.jNE.field_packageName + ", openId = " + this.jNE.field_openId);
an.a(this.mContext, this.jNE.scene, this.jNE.bYq, this.jNE.position, 3, this.jNE.field_appId, this.jNv, this.jTR);
f.ah(this.mContext, this.jNE.field_appId);
return;
}
int i;
be.aUD();
String str = this.jNE.cmP;
if (bi.oW(str)) {
x.e("MicroMsg.QQDownloaderSDKWrapper", "queryQQDownloadTaskStatus, params is null or nil");
i = -1;
} else {
i = be.a(new a((byte) 0).Dz(str));
}
this.kcO = i;
str = this.jNE.cmP;
if (!bi.oW(str)) {
str = str.replace("ANDROIDWX.GAMECENTER", "ANDROIDWX.YYB.GAMECENTER");
}
if (this.jNE.status == 3) {
be.aUD();
be.startToAuthorized(this.mContext, str);
} else {
be.aUD();
be.am(this.mContext, str);
}
i = 5;
if (this.jNE.status == 3) {
i = 10;
}
an.a(this.mContext, this.jNE.scene, this.jNE.bYq, this.jNE.position, this.kcO == 4 ? 8 : i, this.jNE.field_appId, this.jNv, this.jNE.bHF, this.jTR);
return;
}
x.e("MicroMsg.GameTMAssistClickListener", "No GameAppInfo");
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* SDeptRole generated by hbm2java
*/
public class SDeptRole implements java.io.Serializable {
private String drid;
private String deptid;
private String roleid;
public SDeptRole() {
}
public SDeptRole(String drid, String deptid, String roleid) {
this.drid = drid;
this.deptid = deptid;
this.roleid = roleid;
}
public String getDrid() {
return this.drid;
}
public void setDrid(String drid) {
this.drid = drid;
}
public String getDeptid() {
return this.deptid;
}
public void setDeptid(String deptid) {
this.deptid = deptid;
}
public String getRoleid() {
return this.roleid;
}
public void setRoleid(String roleid) {
this.roleid = roleid;
}
}
|
package pl.cwanix.opensun.agentserver.packets.s2c.character;
import pl.cwanix.opensun.agentserver.packets.AgentServerPacketOPCode;
import pl.cwanix.opensun.commonserver.packets.Packet;
import pl.cwanix.opensun.commonserver.packets.annotations.OutgoingPacket;
@SuppressWarnings("checkstyle:MagicNumber")
@OutgoingPacket(category = AgentServerPacketOPCode.Character.CATEGORY, operation = AgentServerPacketOPCode.Character.Ans.DELETE_CHAR)
public class S2CAnsDeleteCharPacket implements Packet {
@Override
public Object[] getOrderedFields() {
return null;
}
}
|
package com.mideas.rpg.v2.hud.social.discussion;
import java.util.ArrayList;
import org.lwjgl.input.Mouse;
import com.mideas.rpg.v2.FontManager;
import com.mideas.rpg.v2.Mideas;
import com.mideas.rpg.v2.chat.ChatFrame;
import com.mideas.rpg.v2.chat.channel.ChannelMember;
import com.mideas.rpg.v2.chat.channel.ChatChannel;
import com.mideas.rpg.v2.command.chat.CommandChannel;
import com.mideas.rpg.v2.render.Draw;
import com.mideas.rpg.v2.render.Sprites;
import com.mideas.rpg.v2.render.TTF;
import com.mideas.rpg.v2.utils.Color;
import com.mideas.rpg.v2.utils.TextMenu;
import com.mideas.rpg.v2.utils.TooltipMenu;
public class DiscussionFrameUI {
private final ArrayList<ChatChannelCategoryButton> categoryList = new ArrayList<ChatChannelCategoryButton>();
private static ChatChannelButton selectedChannel;
protected float x;
private float y;
private static float yDraw;
private static float yShift;
private static float buttonXOffset;
private static float buttonYOffset;
private static float xSize;
private static float ySize;
private static float memberBorderWidth;
private static float memberX;
private static float memberY;
private static int hoveredMember = -1;
private static int rightClickDownMember = -1;
private static float memberYShift;
private final static TTF memberListFont = FontManager.get("FRIZQT", 12);
public final static TTF channelFont = FontManager.get("FRIZQT", 12);
private final static int BUTTON_X_OFFSET = 20;
private final static int BUTTON_Y_OFFSET = 79;
private final static int MEMBER_X_OFFSET = 225;
private final static int MEMBER_Y_OFFSET = 78;
private final static int MEMBER_Y_SHIFT = 15;
private final static int MEMBER_BORDER_WIDTH_SCROLLBAR = 160;
private final static int MEMBER_BORDER_WIDTH_NOSCROLLBAR = 180;
private final static int Y_SHIFT = Sprites.chat_channel_button.getImageHeight()+1;
private final static int X_SIZE = 176;
private final static int Y_SIZE = Sprites.chat_channel_button.getImageHeight();
final static TooltipMenu tooltipMenu = new TooltipMenu(0, 0, 0);
static ChatChannel tooltipChannel;
static ChannelMember tooltipMember;
private final static TextMenu leaveChannelMenu = new TextMenu(0, 0, 0, "Leave", 12, 1, 0) {
@Override
public void eventButtonClick() {
CommandChannel.leaveChannel(tooltipChannel.getID());
tooltipMenu.setActive(false);
}
};
private final static TextMenu cancelMenu = new TextMenu(0, 0, 0, "Cancel", 12, 1, 0) {
@Override
public void eventButtonClick() {
tooltipMenu.setActive(false);
}
};
private final static TextMenu whisperPlayerMenu = new TextMenu(0, 0, 0, "Whisper", 12, 1, 0) {
@Override
public void eventButtonClick() {
ChatFrame.setWhisper(tooltipMember.getName());
ChatFrame.setChatActive(true);
tooltipMenu.setActive(false);
}
};
private final static TextMenu targetPlayerMenu = new TextMenu(0, 0, 0, "Target", 12, 1, 0) {
@Override
public void eventButtonClick() {
tooltipMenu.setActive(false);
}
};
public DiscussionFrameUI(float x, float y) {
this.x = (int)x;
this.y = (int)y;
buttonXOffset = BUTTON_X_OFFSET*Mideas.getDisplayXFactor();
buttonYOffset = BUTTON_Y_OFFSET*Mideas.getDisplayYFactor();
yShift = Y_SHIFT*Mideas.getDisplayYFactor();
xSize = X_SIZE*Mideas.getDisplayXFactor();
ySize = Y_SIZE*Mideas.getDisplayYFactor();
memberYShift = MEMBER_Y_SHIFT*Mideas.getDisplayYFactor();
memberBorderWidth = MEMBER_BORDER_WIDTH_NOSCROLLBAR*Mideas.getDisplayXFactor();
memberX = this.x+MEMBER_X_OFFSET*Mideas.getDisplayXFactor();
memberY = this.y+MEMBER_Y_OFFSET*Mideas.getDisplayYFactor();
addCategory("Group");
addCategory("World");
addCategory("Custom");
}
public DiscussionFrameUI() {}
public void draw() {
int i = 0;
yDraw = this.y+buttonYOffset;
Draw.drawQuad(Sprites.discussion_frame, this.x, this.y);
while(i < this.categoryList.size()) {
this.categoryList.get(i).draw();
i++;
}
tooltipMenu.draw();
}
public boolean mouseEvent() {
int i = 0;
yDraw = this.y+buttonYOffset;
if(tooltipMenu.event()) return true;
while(i < this.categoryList.size()) {
if(this.categoryList.get(i).event()) {
return true;
}
i++;
}
return false;
}
protected void drawMemberList(ChatChannelButton channel) {
ArrayList<ChannelMember> list = channel.getChannel().getPlayerList();
int i = -1;
float y = memberY;
memberListFont.drawBegin();
while(++i < list.size()) {
memberListFont.drawStringShadow(memberX, y, list.get(i).getName(), Color.WHITE, Color.BLACK, 1, 0, 0);
y+= memberYShift;
}
memberListFont.drawEnd();
if(hoveredMember != -1) {
y = memberY;
Draw.drawQuadBlend(Sprites.friend_border, memberX-20*Mideas.getDisplayXFactor(), y+hoveredMember*memberYShift+1, memberBorderWidth, memberYShift);
}
}
protected boolean memberListEvent(ChatChannelButton channel) {
int length = channel.getChannel().getPlayerList().size();
int i = -1;
float y = memberY;
float x = memberX-20*Mideas.getDisplayXFactor();
hoveredMember = -1;
while(++i < length) {
if(Mideas.getHover() && Mideas.mouseX() >= x && Mideas.mouseX() <= x+memberBorderWidth &&
Mideas.mouseY() >= y && Mideas.mouseY() <= y+memberYShift)
{
Mideas.setHover(false);
hoveredMember = i;
break;
}
y+= memberYShift;
}
if(hoveredMember != -1) {
Draw.drawQuad(Sprites.friend_border, x, y, memberBorderWidth, memberYShift);
if(Mouse.getEventButtonState()) {
rightClickDownMember = hoveredMember;
}
else {
if(Mouse.getEventButton() == 1) {
if(rightClickDownMember == hoveredMember) {
enableMemberTooltip(channel.getChannel().getPlayerList().get(hoveredMember), Mideas.mouseX(), Mideas.mouseY());
return true;
}
}
}
}
return false;
}
protected static float getYDraw() {
return yDraw;
}
protected static void incrementYDraw() {
yDraw+= yShift;
}
protected static float getYShift() {
return yShift;
}
protected static void incrementYDraw(float value) {
yDraw+= value;
}
protected static float getXSize() {
return xSize;
}
protected static float getYSize() {
return ySize;
}
public void addCategory(String name) {
this.categoryList.add(new ChatChannelCategoryButton(name, this.x+buttonXOffset));
}
public void addChannel(ChatChannel channel) {
if(isWorldChannel(channel.getName())) {
this.categoryList.get(1).addChannel(channel);
}
else {
this.categoryList.get(2).addChannel(channel);
}
}
public void removeChannel(ChatChannel channel) {
if(isWorldChannel(channel.getName())) {
this.categoryList.get(1).removeChannel(channel);
}
else {
this.categoryList.get(2).removeChannel(channel);
}
}
protected static ChatChannelButton getSelectedChannel() {
return selectedChannel;
}
protected static void setSelectedChannel(ChatChannelButton channel) {
selectedChannel = channel;
}
protected static void enableChannelTooltip(ChatChannel channel, float x, float y) {
tooltipMenu.clearMenu();
tooltipMenu.setName(channel.getName());
tooltipMenu.addMenu(leaveChannelMenu);
tooltipMenu.addMenu(cancelMenu);
tooltipMenu.updateSize(x, y, true);
tooltipMenu.setActive(true);
tooltipMember = null;
tooltipChannel = channel;
}
protected static void enableMemberTooltip(ChannelMember member, float x, float y) {
tooltipMenu.clearMenu();
tooltipMenu.setName(member.getName());
tooltipMenu.addMenu(whisperPlayerMenu);
tooltipMenu.addMenu(targetPlayerMenu);
tooltipMenu.addMenu(cancelMenu);
tooltipMenu.updateSize(x, y, true);
tooltipMenu.setActive(true);
tooltipMember = member;
tooltipChannel = null;
}
public void updateSize(float x, float y) {
this.x = (int)x;
this.y = (int)y;
buttonXOffset = BUTTON_X_OFFSET*Mideas.getDisplayXFactor();
buttonYOffset = BUTTON_Y_OFFSET*Mideas.getDisplayYFactor();
yShift = Y_SHIFT*Mideas.getDisplayYFactor();
xSize = X_SIZE*Mideas.getDisplayXFactor();
ySize = Y_SIZE*Mideas.getDisplayYFactor();
memberX = this.x+MEMBER_X_OFFSET*Mideas.getDisplayXFactor();
memberY = this.y+MEMBER_Y_OFFSET*Mideas.getDisplayYFactor();
memberYShift = MEMBER_Y_SHIFT*Mideas.getDisplayYFactor();
memberBorderWidth = MEMBER_BORDER_WIDTH_NOSCROLLBAR*Mideas.getDisplayXFactor();
memberYShift = MEMBER_Y_SHIFT*Mideas.getDisplayYFactor();
tooltipMenu.updateSize();
int i = 0;
while(i < this.categoryList.size()) {
this.categoryList.get(i).updateSize(this.x+buttonXOffset);
i++;
}
}
private static boolean isWorldChannel(String name) {
return name.equals("General") || name.equals("Commerce");
}
}
|
package com.java.abs_fact.factory;
import com.java.abs_fact.AnimalEnum;
import com.java.abs_fact.IAnimal;
public class AnimalFactory {
public IAnimal getAnimal(FactoryEnumType factoryEnumType, AnimalEnum name) {
switch (factoryEnumType) {
case LANDANIMALFACTORY:
LandAnimalFactory factory = new LandAnimalFactory();
return factory.getAnimalByNmae(name);
case SEEANIMALFACTORY:
SeeAnimalFactory seeAnimalFactory = new SeeAnimalFactory();
return seeAnimalFactory.getAnimalByNmae(name);
}return null;
}
}
|
package com.syla;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Color;
import android.location.Location;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
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.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import com.syla.adapter.LogAdapter;
import com.syla.application.AppConstants;
import com.syla.application.MyApp;
import com.syla.models.Users;
import com.syla.utils.LocationProvider;
import com.syla.utils.ObservableScrollView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends CustomActivity implements OnMapReadyCallback,
ObservableScrollView.OnScrollChangedListener, LocationProvider.LocationCallback, LocationProvider.PermissionCallback {
private static final String TAG = "mapScreen";
private GoogleMap mMap;
private FrameLayout imgContainer;
private LocationProvider locationProvider;
private static final int REQUEST_CHECK_SETTINGS = 100;
private RecyclerView rv_list;
private ObservableScrollView mScrollView;
private LinearLayout ll_bottom;
private Toolbar toolbar;
private RelativeLayout rl_location;
private String currentRoomId;
private boolean isNewRoom = false;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private List<Users> users = new ArrayList<>();
private boolean isMine = false;
private Button txt_delete_group;
private Switch switch_location_on_off;
private UpdateCallbacks updateCallbacks;
private Users admin;
private TextView txt_group_info;
private TextView txt_copy_code;
private ImageButton btn_share_room;
private TextView txt_roomName;
private Map<String, String> joinMap = new HashMap<>();
private boolean isFirstDataSetupDone = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentRoomId = MyApp.getSharedPrefString(AppConstants.CURRENT_ROOM_ID);
isNewRoom = getIntent().getBooleanExtra("isNew", false);
isMine = getIntent().getBooleanExtra("isMine", false);
setContentView(R.layout.activity_main);
txt_group_info = findViewById(R.id.txt_group_info);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
txt_group_info.setVisibility(View.GONE);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setTitle("Room Name");
}
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
MyApp.setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true);
}
if (Build.VERSION.SDK_INT >= 19) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
if (Build.VERSION.SDK_INT >= 21) {
MyApp.setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
locationProvider = new LocationProvider(getContext(), this, this);
locationProvider.connect();
// restore the values from saved instance state
// restoreValuesFromBundle(savedInstanceState);
mScrollView = findViewById(R.id.scroll_view);
mScrollView.setOnScrollChangedListener(this);
setupViews();
// if (isNewRoom) {
// AlertDialog.Builder b = new AlertDialog.Builder(getContext());
// b.setTitle("Invite People").setMessage("You have created a new room, you can share the room id to" +
// " other people to join you.")
// .setPositiveButton("Share Now", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// String link_val = currentRoomId;
// String body = "Hi, I have created a room to share our location, so that we can track each other anytime" +
// "\n'" + link_val
// + "' is the room id you have to enter to join it.";
//// String shareBody = "Hi, I have created a room to share our location, so that we can track each other anytime" +
//// "\n'" + currentRoomId + "' is the room id you have to enter to join it.";
// Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
// sharingIntent.setType("text/plain");
// sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Join Room");
// sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);
// startActivity(Intent.createChooser(sharingIntent, "Share Via"));
// }
// }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
//
// }
// }).create().show();
// }
// get all data for the room
db.collection("allRooms").document(currentRoomId).addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(final DocumentSnapshot snapshot, FirebaseFirestoreException e) {
if (e != null) {
Log.w("Firestore Demo", "Listen failed.", e);
return;
}
if (snapshot != null && snapshot.exists()) {
Log.d("Firestore Demo", "Current data: " + snapshot.getData());
String roomName1 = snapshot.getString("roomName");
toolbar.setTitle(roomName1);
txt_roomName.setText("Room : " + roomName1);
if (isMine) {
} else {
if (snapshot.getBoolean("isLeft")) {
return;
}
admin = new Users();
admin.setActive(snapshot.getBoolean("isActive"));
try {
admin.setLat(snapshot.getDouble("lat"));
admin.setLng(snapshot.getDouble("lng"));
} catch (Exception ee) {
}
admin.setUserId(snapshot.getString("userId"));
admin.setAdmin(true);
admin.setName(snapshot.getString("userName"));
}
snapshot.getReference().collection("Users").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot userSnapshots, FirebaseFirestoreException e) {
if (e != null) {
Log.w("Firestore Demo", "Listen failed for users.", e);
txt_group_info.setVisibility(View.VISIBLE);
return;
}
users.clear();
if (!isMine)
users.add(admin);
if (userSnapshots != null && !userSnapshots.isEmpty()) {
for (DocumentSnapshot documentSnapshot : userSnapshots) {
if (documentSnapshot.exists()) {
Log.d(TAG, "onSuccess: DOCUMENT" + documentSnapshot.getId()
+ " ; " + documentSnapshot.getData());
Users u = documentSnapshot.toObject(Users.class);
try {
if (u.getLng() == 0) {
u.setLat(sourceLocation.getLatitude());
u.setLng(sourceLocation.getLongitude());
}
} catch (Exception ef) {
}
if (!u.getUserId().equals(MyApp.getSharedPrefString(AppConstants.USER_ID))) {
if (!u.isRemoved()) {
users.add(u);
} else {
if (users.size() > 1) {
MyApp.popMessage("Alert", u.getName() + " has been left the room", getContext());
db.collection("allRooms").document(currentRoomId).collection("Users")
.document(u.getUserId())
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "You have been removed ");
}
});
}
}
} else if (u.isDeleted()) {
db.collection("allRooms").document(currentRoomId).collection("Users")
.document(u.getUserId())
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
MyApp.popFinishableMessage("Alert!",
"You have been removed by the admin.", MainActivity.this);
}
});
}
}
}
if (users.size() == 0)
txt_group_info.setVisibility(View.VISIBLE);
else
txt_group_info.setVisibility(View.GONE);
rv_list.setAdapter(new LogAdapter(getContext(), users, isMine));
if (sourceLocation != null && isVisible) {
areMarkersSet = false;
setupUsersMarker(sourceLocation, users);
}
} else {
// No users found yet
isFirstDataSetupDone = true;
txt_group_info.setVisibility(View.VISIBLE);
}
}
});
} else {
Log.d("Firestore Demo", "Current data: null");
MyApp.popFinishableMessage("Alert!"
, "This room has been deleted by your admin, you cannot" +
" access it anymore.\nThank you", MainActivity.this);
}
}
});
if (isMine) {
txt_delete_group.setVisibility(View.VISIBLE);
}
updateCallbacks = new UpdateCallbacks() {
@Override
public void updateInvisible(final boolean isVisible) {
if (isMine) {
db.collection("allRooms").document(currentRoomId).update("isActive", isVisible).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
} else {
db.collection("allRooms").document(currentRoomId).collection("Users")
.document(MyApp.getSharedPrefString(AppConstants.USER_ID))
.update("isActive", isVisible)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "location updated with value " + isVisible);
}
});
}
}
@Override
public void updateSave(boolean isSaved) {
}
@Override
public void updateRemoved(boolean isRemoved) {
}
};
}
@Override
public void onClick(View v) {
super.onClick(v);
if (v.getId() == R.id.txt_leave_group) {
if (isMine) {
AlertDialog.Builder b = new AlertDialog.Builder(getContext());
b.setTitle("Leaving Group?").setMessage("Are you sure that you want to leave the group. You cannot " +
"get any update with the group and you will be removed.")
.setPositiveButton("Leave", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
MyApp.showMassage(getContext(), "Removing you.");
db.collection("allRooms").document(currentRoomId).update("isLeft", true)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
finish();
}
});
}
}).setNegativeButton("Stay", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
} else {
AlertDialog.Builder b = new AlertDialog.Builder(getContext());
b.setTitle("Leaving Group?").setMessage("Are you sure that you want to leave the group. You cannot " +
"get any update with the group and you will be removed.")
.setPositiveButton("Leave", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
MyApp.showMassage(getContext(), "Removing you.");
db.collection("allRooms").document(currentRoomId).collection("Users")
.document(MyApp.getSharedPrefString(AppConstants.USER_ID))
.update("isRemoved", true)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "You have been removed ");
finish();
}
});
}
}).setNegativeButton("Stay", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
} else if (v == txt_delete_group) {
AlertDialog.Builder b = new AlertDialog.Builder(getContext());
b.setTitle("Delete Room?").setMessage("Are you sure that you want to delete this room permanently?")
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
db.collection("allRooms").document(currentRoomId).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
if (isMine) {
finish();
} else {
db.collection("allRooms").document(currentRoomId).addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(final DocumentSnapshot snapshot, FirebaseFirestoreException e) {
if (e != null) {
Log.w("Firestore Demo", "Listen failed.", e);
MyApp.popFinishableMessage("Alert!"
, "This room has been deleted by your admin, you cannot" +
" access it anymore.\nThank you", MainActivity.this);
return;
}
if (snapshot != null && snapshot.exists()) {
Log.d("Firestore Demo", "Current data: " + snapshot.getData());
String roomName1 = snapshot.getString("roomName");
toolbar.setTitle(roomName1);
txt_roomName.setText("Room : " + toolbar.getTitle().toString());
Log.d("debugName", toolbar.getTitle().toString());
if (isMine) {
} else {
if (snapshot.getBoolean("isLeft")) {
return;
}
admin = new Users();
admin.setActive(true);
try {
admin.setLat(snapshot.getDouble("lat"));
admin.setLng(snapshot.getDouble("lng"));
} catch (Exception ee) {
}
admin.setUserId(snapshot.getString("userId"));
admin.setAdmin(true);
admin.setName(snapshot.getString("userName"));
}
snapshot.getReference().collection("Users").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot userSnapshots, FirebaseFirestoreException e) {
if (e != null) {
Log.w("Firestore Demo", "Listen failed for users.", e);
return;
}
users.clear();
if (!isMine)
users.add(admin);
if (userSnapshots != null && !userSnapshots.isEmpty()) {
for (DocumentSnapshot documentSnapshot : userSnapshots) {
if (documentSnapshot.exists()) {
Log.d(TAG, "onSuccess: DOCUMENT" + documentSnapshot.getId()
+ " ; " + documentSnapshot.getData());
Users u = documentSnapshot.toObject(Users.class);
if (!u.getUserId().equals(MyApp.getSharedPrefString(AppConstants.USER_ID))) {
if (!u.isRemoved()) {
users.add(u);
} else {
MyApp.popMessage("Alert", u.getName() + " has been left the room", getContext());
db.collection("allRooms").document(currentRoomId).collection("Users")
.document(u.getUserId())
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "You have been removed ");
}
});
}
} else if (u.isDeleted()) {
db.collection("allRooms").document(currentRoomId).collection("Users")
.document(u.getUserId())
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
MyApp.popFinishableMessage("Alert!",
"You have been removed by the admin.", MainActivity.this);
}
});
}
}
}
if (users.size() == 0) {
MyApp.popFinishableMessage("Alert!"
, "This room has been deleted by your admin, you cannot" +
" access it anymore.\nThank you", MainActivity.this);
return;
}
rv_list.setAdapter(new LogAdapter(getContext(), users, isMine));
if (sourceLocation != null && isVisible) {
areMarkersSet = false;
setupUsersMarker(sourceLocation, users);
}
} else {
MyApp.popFinishableMessage("Alert!"
, "This room has been deleted by your admin, you cannot" +
" access it anymore.\nThank you", MainActivity.this);
}
}
});
} else {
Log.d("Firestore Demo", "Current data: null");
MyApp.popFinishableMessage("Alert!"
, "This room has been deleted by your admin, you cannot" +
" access it anymore.\nThank you", MainActivity.this);
}
}
});
}
}
});
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
} else if (v.getId() == R.id.btn_share_room) {
if (isMine) {
String link_val = currentRoomId;
String body = "Hi, I have created a room to share our location, so that we can track each other anytime" +
"\n'" + link_val
+ "' is the room id you have to enter to join it.";
// String shareBody = "Hi, I have created a room to share our location, so that we can track each other anytime" +
// "\n'" + currentRoomId + "' is the room id you have to enter to join it.";
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Join Room");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);
startActivity(Intent.createChooser(sharingIntent, "Share Via"));
} else {
AlertDialog.Builder b = new AlertDialog.Builder(getContext());
b.setTitle("Save Group?").setMessage("Save a group will track a record for Saved Room section, where you can" +
" access your saved room anytime.\nThank you.")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
MyApp.showMassage(getContext(), "Saving...");
db.collection("allRooms").document(currentRoomId).collection("Users")
.document(MyApp.getSharedPrefString(AppConstants.USER_ID))
.update("isSaved", true)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "Room has been saved. ");
MyApp.showMassage(getContext(), "This room has been Saved");
db.collection("users")
.document(MyApp.getSharedPrefString(AppConstants.USER_ID))
.collection("savedRooms")
.document(currentRoomId)
.set(new HashMap<String, Object>())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
// finish();
}
});
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
} else if (v == txt_copy_code) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copy Code", currentRoomId);
clipboard.setPrimaryClip(clip);
MyApp.showMassage(getContext(), "Copied...");
}
}
private MapFragment getMapFragment() {
FragmentManager fm = getFragmentManager();
return (MapFragment) fm.findFragmentById(R.id.map);
}
private void setupViews() {
txt_roomName = findViewById(R.id.txt_roomName);
txt_copy_code = findViewById(R.id.txt_copy_code);
setTouchNClick(R.id.txt_copy_code);
txt_copy_code.setText(currentRoomId);
if (isMine) {
txt_copy_code.setVisibility(View.VISIBLE);
}
switch_location_on_off = findViewById(R.id.switch_location_on_off);
txt_delete_group = findViewById(R.id.txt_delete_group);
rl_location = findViewById(R.id.rl_location);
imgContainer = findViewById(R.id.img_container);
ll_bottom = findViewById(R.id.ll_bottom);
imgContainer.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
(int) (MyApp.getDisplayHeight() * 0.88)));
ll_bottom.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
MyApp.getDisplayHeight()));
ImageView transparentImageView = findViewById(R.id.transparent_image);
setTouchNClick(R.id.txt_leave_group);
btn_share_room = findViewById(R.id.btn_share_room);
if (isMine)
btn_share_room.setImageResource(R.drawable.ic_menu_share);
else {
if (MyApp.getStatus(AppConstants.IS_GUEST)) {
btn_share_room.setVisibility(View.GONE);
}
btn_share_room.setImageResource(R.drawable.ic_bookmark);
}
setTouchNClick(R.id.btn_share_room);
rv_list = findViewById(R.id.rv_list);
rv_list.setLayoutManager(new LinearLayoutManager(getContext()));
setTouchNClick(R.id.txt_delete_group);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
getMapFragment().getMapAsync(this);
transparentImageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
mScrollView.requestDisallowInterceptTouchEvent(true);
// Disable touch on transparent view
return false;
case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
mScrollView.requestDisallowInterceptTouchEvent(false);
return true;
case MotionEvent.ACTION_MOVE:
mScrollView.requestDisallowInterceptTouchEvent(true);
return false;
default:
return true;
}
}
});
mScrollView.post(new Runnable() {
@Override
public void run() {
mScrollView.smoothScrollTo(0, MyApp.getDisplayHeight() / 3);
}
});
switch_location_on_off.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
isVisible = true;
} else {
isVisible = false;
}
updateCallbacks.updateInvisible(isVisible);
}
});
}
private boolean isVisible = true;
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
if (areMarkersSet) {
return;
}
Log.d("Current map location ", location.getLatitude() + " , " + location.getLongitude());
if (myMarker != null) {
myMarker.remove();
}
sourceLocation = location;
setupUsersMarker(location, users);
areMarkersSet = true;
if (isMine) {
db.collection("allRooms").document(currentRoomId)
.update("lat", location.getLatitude())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
db.collection("allRooms").document(currentRoomId)
.update("lng", location.getLongitude())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
} else {
db.collection("allRooms").document(currentRoomId).collection("Users")
.document(MyApp.getSharedPrefString(AppConstants.USER_ID))
.update("lat", location.getLatitude())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
db.collection("allRooms").document(currentRoomId).collection("Users")
.document(MyApp.getSharedPrefString(AppConstants.USER_ID))
.update("lng", location.getLongitude())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
}
}
});
// Add a marker in Sydney and move the camera
}
/**
* Restoring values from saved instance state
*/
// private void restoreValuesFromBundle(Bundle savedInstanceState) {
// if (savedInstanceState != null) {
// if (savedInstanceState.containsKey("is_requesting_updates")) {
//// mRequestingLocationUpdates = savedInstanceState.getBoolean("is_requesting_updates");
// }
//
// if (savedInstanceState.containsKey("last_known_location")) {
// mCurrentLocation = savedInstanceState.getParcelable("last_known_location");
// }
//
// if (savedInstanceState.containsKey("last_updated_on")) {
// mLastUpdateTime = savedInstanceState.getString("last_updated_on");
// }
// }
//
// }
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// outState.putBoolean("is_requesting_updates", mRequestingLocationUpdates);
// outState.putParcelable("last_known_location", mCurrentLocation);
// outState.putString("last_updated_on", mLastUpdateTime);
}
@Override
protected void onResume() {
super.onResume();
if (!MyApp.isLocationEnabled(getContext())) {
displayLocationSettingsRequest(getContext());
}
}
private void displayLocationSettingsRequest(Context context) {
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(10000 / 2);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.i(TAG, "All location settings are satisfied.");
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the result
// in onActivityResult().
status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
break;
}
}
});
}
private boolean areMarkersSet = false;
private Runnable updateTask = new Runnable() {
@Override
public void run() {
areMarkersSet = false;
h.postDelayed(updateTask, 5000);
}
};
private Handler h = new Handler();
private Marker myMarker = null;
private List<Marker> markers = new ArrayList<>();
private Map<String, Marker> markerMap = new HashMap<>();
private boolean isMapCentered = false;
public void setupUsersMarker(Location myLocation, List<Users> users) {
if (areMarkersSet) {
return;
}
if (lastUserPath != null) {
String url = getMapsApiDirectionsUrl(new LatLng(sourceLocation.getLatitude(), sourceLocation.getLongitude()),
new LatLng(lastUserPath.getLat(), lastUserPath.getLng()));
new ReadTask().execute(new String[]{url});
}
// mMap.clear();
// myMarker = mMap.addMarker(new MarkerOptions().position(new LatLng(
// myLocation.getLatitude(),
// myLocation.getLongitude()))
// .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_user_marker)));
if (this.mMap != null && !isMapCentered) {
this.mMap.getUiSettings().setZoomControlsEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(myLocation.getLatitude(),
myLocation.getLongitude())).zoom(15.5f).tilt(0.0f).build();
if (ContextCompat.checkSelfPermission(this, "android.permission.ACCESS_FINE_LOCATION") == 0 || ContextCompat.checkSelfPermission(this, "android.permission.ACCESS_COARSE_LOCATION") == 0) {
this.mMap.setMyLocationEnabled(true);
} else {
ActivityCompat.requestPermissions(this, new String[]{"android.permission.ACCESS_FINE_LOCATION", "android.permission.ACCESS_COARSE_LOCATION"}, 1010);
}
this.mMap.getUiSettings().setMyLocationButtonEnabled(false);
this.mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(new LatLng(this.sourceLocation.getLatitude(), this.sourceLocation.getLongitude()));
//This is to generate 10 random points
for (int i = 0; i < users.size(); i++) {
// double x0 = myLocation.getLatitude();
// double y0 = myLocation.getLongitude();
// Random random = new Random();
//
// // Convert radius from meters to degrees
// double radiusInDegrees = 50 / 111000f;
//
// double u = random.nextDouble();
// double v = random.nextDouble();
// double w = radiusInDegrees * Math.sqrt(u);
// double t = 2 * Math.PI * v;
// double x = w * Math.cos(t);
// double y = w * Math.sin(t);
// // Adjust the x-coordinate for the shrinking of the east-west distances
// double new_x = x / Math.cos(y0);
//
// double foundLatitude = new_x + users.get(i).getLat();
// double foundLongitude = y + users.get(i).getLng();
Log.d(TAG, users.get(i).getLat() + " & " + users.get(i).getLng());
if (!markerMap.containsKey(users.get(i).getUserId())) {
markerMap.put(users.get(i).getUserId(), mMap.addMarker(new MarkerOptions().position(new LatLng(
users.get(i).getLat(),
users.get(i).getLng())).title(users.get(i).getName())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker))));
} else {
Marker m = markerMap.get(users.get(i).getUserId());
m.setPosition(new LatLng(users.get(i).getLat(), users.get(i).getLng()));
}
// markers.add(mMap.addMarker(new MarkerOptions().position(new LatLng(
// users.get(i).getLat(),
// users.get(i).getLng())).title(users.get(i).getName())
// .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker))));
builder.include(new LatLng(users.get(i).getLat(), users.get(i).getLng()));
}
if (!isMapCentered) {
isMapCentered = true;
CameraUpdateFactory.newLatLngBounds(adjustBoundsForMaxZoomLevel(builder.build()), 150);
h.postDelayed(updateTask, 5000);
}
//Get nearest point to the centre
}
private Context getContext() {
return MainActivity.this;
}
@Override
public void onScrollChanged(int deltaX, int deltaY) {
int scrollY = mScrollView.getScrollY();
// Add parallax effect
imgContainer.setTranslationY(scrollY * 0.5f);
int toolbarOffset = MyApp.getDisplayHeight() - mScrollView.getScrollY();
Log.d("scrolling", toolbarOffset + "");
if (toolbarOffset <= 240) {
rl_location.setVisibility(View.GONE);
toolbar.setVisibility(View.VISIBLE);
// slideUp(toolbar);
// slideDown(rl_location);
} else {
toolbar.setVisibility(View.GONE);
rl_location.setVisibility(View.VISIBLE);
// slideUp(rl_location);
// slideDown(toolbar);
}
}
@Override
public void onBackPressed() {
// super.onBackPressed();
AlertDialog.Builder b = new AlertDialog.Builder(getContext());
b.setTitle("Choose option").setMessage("What do you want to do?")
.setPositiveButton("Continue in background", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
// startActivity(new Intent(getContext(), DrawerActivity.class));
}
}).setNegativeButton("Leave group", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (isMine) {
MyApp.showMassage(getContext(), "Removing you.");
db.collection("allRooms").document(currentRoomId).update("isLeft", true)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
finish();
}
});
} else {
MyApp.showMassage(getContext(), "Removing you.");
db.collection("allRooms").document(currentRoomId).collection("Users")
.document(MyApp.getSharedPrefString(AppConstants.USER_ID))
.update("isRemoved", true)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "You have been removed ");
finish();
}
});
}
}
}).create().show();
}
private Location sourceLocation = null;
@Override
public void handleNewLocation(Location location) {
if (myMarker != null) {
myMarker.remove();
}
Log.d("Current location ", location.getLatitude() + " , " + location.getLongitude());
sourceLocation = location;
setupUsersMarker(location, users);
areMarkersSet = true;
if (isMine) {
db.collection("allRooms").document(currentRoomId)
.update("lat", sourceLocation.getLatitude())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
db.collection("allRooms").document(currentRoomId)
.update("lng", sourceLocation.getLongitude())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
} else {
db.collection("allRooms").document(currentRoomId).collection("Users")
.document(MyApp.getSharedPrefString(AppConstants.USER_ID))
.update("lat", sourceLocation.getLatitude())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
db.collection("allRooms").document(currentRoomId).collection("Users")
.document(MyApp.getSharedPrefString(AppConstants.USER_ID))
.update("lng", sourceLocation.getLongitude())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
}
}
@Override
public void handleManualPermission() {
ActivityCompat.requestPermissions(this, new String[]{"android.permission.ACCESS_FINE_LOCATION", "android.permission.ACCESS_COARSE_LOCATION"}, 1010);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
locationProvider = new LocationProvider(getContext(), this, this);
}
private LatLngBounds adjustBoundsForMaxZoomLevel(LatLngBounds bounds) {
LatLng sw = bounds.southwest;
LatLng ne = bounds.northeast;
double deltaLat = Math.abs((sw.latitude - this.sourceLocation.getLatitude())
- (ne.latitude - this.sourceLocation.getLatitude()));
double deltaLon = Math.abs((sw.longitude - this.sourceLocation.getLongitude())
- (ne.longitude - this.sourceLocation.getLongitude()));
LatLng latLng;
LatLng ne2;
LatLngBounds latLngBounds;
if (deltaLat < 0.005d) {
latLng = new LatLng(sw.latitude - (0.005d - (deltaLat / 2.0d)), sw.longitude);
ne2 = new LatLng(ne.latitude + (0.005d - (deltaLat / 2.0d)), ne.longitude);
latLngBounds = new LatLngBounds(latLng, ne2);
ne = ne2;
sw = latLng;
} else if (deltaLon < 0.005d) {
latLng = new LatLng(sw.latitude, sw.longitude - (0.005d - (deltaLon / 2.0d)));
ne2 = new LatLng(ne.latitude, ne.longitude + (0.005d - (deltaLon / 2.0d)));
latLngBounds = new LatLngBounds(latLng, ne2);
ne = ne2;
sw = latLng;
}
LatLngBounds.Builder displayBuilder = new LatLngBounds.Builder();
displayBuilder.include(new LatLng(this.sourceLocation.getLatitude(), this.sourceLocation.getLongitude()));
displayBuilder.include(new LatLng(this.sourceLocation.getLatitude()
+ deltaLat, this.sourceLocation.getLongitude() + deltaLon));
displayBuilder.include(new LatLng(this.sourceLocation.getLatitude()
- deltaLat, this.sourceLocation.getLongitude() - deltaLon));
this.mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(displayBuilder.build(), 100));
// this.mMap.setMaxZoomPreference(15.5f);
return bounds;
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static void setTranslucentStatusBarLollipop(Window window) {
window.setStatusBarColor(
window.getContext()
.getResources()
.getColor(R.color.transparent));
}
public void slideUp(View view) {
view.setVisibility(View.VISIBLE);
TranslateAnimation animate = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
view.getHeight(), // fromYDelta
0); // toYDelta
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
}
public void slideDown(View view) {
TranslateAnimation animate = new TranslateAnimation(
0, // fromXDelta
0, // toXDelta
0, // fromYDelta
view.getHeight()); // toYDelta
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
}
private Users lastUserPath = null;
public void goToUser(Users users) {
MyApp.showMassage(getContext(), "Drawing route");
lastUserPath = users;
String url = getMapsApiDirectionsUrl(new LatLng(sourceLocation.getLatitude(), sourceLocation.getLongitude()),
new LatLng(users.getLat(), users.getLng()));
new ReadTask().execute(new String[]{url});
// Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
// Uri.parse("geo:0,0?q=" + users.getLat() + "," + users.getLng() + " (" + users.getName() + ")"));
// startActivity(intent);
}
public void goToGoogleMap(Users users) {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("geo:0,0?q=" + users.getLat() + "," + users.getLng() + " (" + users.getName() + ")"));
startActivity(intent);
}
public void deleteUser(final Users users) {
AlertDialog.Builder b = new AlertDialog.Builder(getContext());
b.setTitle("Alert!").setMessage("Are you sure to remove '" + users.getName() + "' ?\n")
.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
db.collection("allRooms").document(currentRoomId).collection("Users")
.document(users.getUserId())
.update("isDeleted", true)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "You have been removed ");
}
});
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
private interface UpdateCallbacks {
void updateInvisible(boolean isVisible);
void updateSave(boolean isSaved);
void updateRemoved(boolean isRemoved);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (MyApp.getStatus(AppConstants.IS_GUEST)) {
db.collection("allRooms").document(currentRoomId).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
} else {
}
}
private String getMapsApiDirectionsUrl(LatLng origin, LatLng dest) {
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
return "https://maps.googleapis.com/maps/api/directions/" + "json" + "?" +
(str_origin + "&" + ("destination=" + dest.latitude + "," + dest.longitude) + "&" + "sensor=false");
}
private class ReadTask extends AsyncTask<String, Void, String> {
private ReadTask() {
}
protected String doInBackground(String... url) {
String data = "";
try {
data = new MapHttpConnection().readUr(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(new String[]{result});
}
}
public class MapHttpConnection {
public String readUr(String mapsApiDirectionsUrl) throws IOException {
String data = "";
InputStream istream = null;
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(mapsApiDirectionsUrl).openConnection();
urlConnection.connect();
istream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istream));
StringBuffer sb = new StringBuffer();
String str = "";
while (true) {
str = br.readLine();
if (str == null) {
break;
}
sb.append(str);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception url", e.toString());
} finally {
istream.close();
urlConnection.disconnect();
}
return data;
}
}
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
private ParserTask() {
}
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
List<List<HashMap<String, String>>> routes = null;
try {
routes = new PathJSONParser().parse(new JSONObject(jsonData[0]));
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
if (polyline != null) {
polyline.remove();
}
PolylineOptions polyLineOptions = null;
for (int i = 0; i < routes.size(); i++) {
ArrayList<LatLng> points = new ArrayList();
polyLineOptions = new PolylineOptions();
List<HashMap<String, String>> path = (List) routes.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = (HashMap) path.get(j);
if (j == 0) {
} else if (j == 1) {
} else {
points.add(new LatLng(Double.parseDouble(point.get("lat")), Double.parseDouble((String) point.get("lng"))));
}
}
polyLineOptions.addAll(points);
polyLineOptions.width(10.0f);
polyLineOptions.color(Color.parseColor("#156CB3"));
}
if (removedLine != null) {
removedLine.remove();
}
try {
polyline = mMap.addPolyline(polyLineOptions);
removedPolyLine = polyLineOptions;
} catch (Exception e) {
if (removedPolyLine != null) {
removedLine = mMap.addPolyline(removedPolyLine);
}
// MyApp.showMassage(getContext(), "Path is too short to draw");
}
}
}
private PolylineOptions removedPolyLine = null;
private Polyline polyline = null;
private Polyline removedLine = null;
public class PathJSONParser {
public List<List<HashMap<String, String>>> parse(JSONObject jObject) {
List<List<HashMap<String, String>>> routes = new ArrayList();
try {
JSONArray jRoutes = jObject.getJSONArray("routes");
for (int i = 0; i < jRoutes.length(); i++) {
JSONArray jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List<HashMap<String, String>> path = new ArrayList();
for (int j = 0; j < jLegs.length(); j++) {
JSONObject jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
HashMap<String, String> hmDistance = new HashMap();
hmDistance.put("distance", jDistance.getString("text"));
JSONObject jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
HashMap<String, String> hmDuration = new HashMap();
hmDuration.put("duration", jDuration.getString("text"));
path.add(hmDistance);
path.add(hmDuration);
JSONArray jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
List<LatLng> list = decodePoly((String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points"));
for (int l = 0; l < list.size(); l++) {
HashMap<String, String> hm = new HashMap();
hm.put("lat", Double.toString((list.get(l)).latitude));
hm.put("lng", Double.toString((list.get(l)).longitude));
path.add(hm);
}
}
routes.add(path);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList();
int index = 0;
int len = encoded.length();
int lat = 0;
int lng = 0;
while (index < len) {
int index2;
int shift = 0;
int result = 0;
int b = 0;
while (true) {
index2 = index + 1;
b = encoded.charAt(index) - 63;
result |= (b & 31) << shift;
shift += 5;
if (b < 32) {
break;
}
index = index2;
}
lat += (result & 1) != 0 ? (result >> 1) ^ -1 : result >> 1;
shift = 0;
result = 0;
index = index2;
while (true) {
index2 = index + 1;
b = encoded.charAt(index) - 63;
result |= (b & 31) << shift;
shift += 5;
if (b < 32) {
break;
}
index = index2;
}
lng += (result & 1) != 0 ? (result >> 1) ^ -1 : result >> 1;
poly.add(new LatLng(((double) lat) / 100000.0d, ((double) lng) / 100000.0d));
index = index2;
}
return poly;
}
}
private void playJoiningSound() {
MediaPlayer mPlayer = MediaPlayer.create(getContext(), R.raw.room_join);
mPlayer.start();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
mp.release();
}
});
}
}
|
package com.ejsfbu.app_main.Fragments;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.ejsfbu.app_main.Activities.LoginActivity;
import com.ejsfbu.app_main.Activities.ParentActivity;
import com.ejsfbu.app_main.DialogFragments.EditEmailDialogFragment;
import com.ejsfbu.app_main.DialogFragments.EditNameDialogFragment;
import com.ejsfbu.app_main.DialogFragments.EditPasswordDialogFragment;
import com.ejsfbu.app_main.DialogFragments.EditProfileImageDialogFragment;
import com.ejsfbu.app_main.DialogFragments.EditUsernameDialogFragment;
import com.ejsfbu.app_main.Models.User;
import com.ejsfbu.app_main.R;
import com.parse.ParseFile;
import com.parse.ParseUser;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
public class ParentProfileFragment extends Fragment
implements EditNameDialogFragment.EditNameDialogListener,
EditUsernameDialogFragment.EditUsernameDialogListener,
EditEmailDialogFragment.EditEmailDialogListener,
EditProfileImageDialogFragment.EditProfileImageDialogListener {
public static final String TAG = "ParentProfileFragment";
@BindView(R.id.tvParentProfileName)
TextView tvParentProfileName;
@BindView(R.id.tvParentProfileEmail)
TextView tvParentProfileEmail;
@BindView(R.id.tvParentProfileUsername)
TextView tvParentProfileUsername;
@BindView(R.id.tvParentProfilePassword)
TextView tvParentProfilePassword;
@BindView(R.id.tvParentProfileAccountCode)
TextView tvParentProfileAccountCode;
@BindView(R.id.tvParentProfileEdit)
TextView tvParentProfileEdit;
@BindView(R.id.ibParentProfileEditName)
ImageButton ibParentProfileEditName;
@BindView(R.id.ibParentProfileEditEmail)
ImageButton ibParentProfileEditEmail;
@BindView(R.id.ibParentProfileEditUsername)
ImageButton ibParentProfileEditUsername;
@BindView(R.id.ibParentProfileEditPassword)
ImageButton ibParentProfileEditPassword;
@BindView(R.id.ivParentProfileProfilePic)
ImageView ivParentProfileProfilePic;
@BindView(R.id.bParentProfileLogout)
Button bParentProfileLogout;
@BindView(R.id.bParentProfileBankInfo)
Button bParentProfileBankInfo;
@BindView(R.id.bParentProfileAddChild)
Button bParentProfileAddChild;
private User user;
private Unbinder unbinder;
private Context context;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
context = container.getContext();
user = (User) ParseUser.getCurrentUser();
return inflater.inflate(R.layout.fragment_parent_profile, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
unbinder = ButterKnife.bind(this, view);
ParentActivity.ibParentProfileBack.setVisibility(View.VISIBLE);
ParentActivity.ibChildDetailBack.setVisibility(View.GONE);
ParentActivity.ibParentBanksListBack.setVisibility(View.GONE);
ParentActivity.ibParentBankDetailsBack.setVisibility(View.GONE);
ParentActivity.ivParentProfilePic.setVisibility(View.GONE);
ParentActivity.cvParentProfilePic.setVisibility(View.GONE);
loadProfileData();
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
public void loadProfileData() {
tvParentProfileName.setText(user.getName());
tvParentProfileEmail.setText(user.getEmail());
tvParentProfileUsername.setText(user.getUsername());
tvParentProfileAccountCode.setText(user.getObjectId());
ParseFile image = user.getProfilePic();
if (image != null) {
String imageUrl = image.getUrl();
imageUrl = imageUrl.substring(4);
imageUrl = "https" + imageUrl;
RequestOptions options = new RequestOptions();
Glide.with(this)
.load(imageUrl)
.apply(options.placeholder(R.drawable.icon_user)
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.error(R.drawable.icon_user)
.transform(new CenterCrop())
.transform(new CircleCrop()))
.into(ivParentProfileProfilePic);
}
}
@OnClick(R.id.ibParentProfileEditName)
public void onClickEditParentName() {
showEditNameDialog();
}
private void showEditNameDialog() {
EditNameDialogFragment editNameDialogFragment
= EditNameDialogFragment.newInstance("Edit Name");
editNameDialogFragment.show(ParentActivity.fragmentManager,
"fragment_edit_name");
}
@OnClick(R.id.ibParentProfileEditUsername)
public void onClickEditParentUsername() {
showEditUsernameDialog();
}
private void showEditUsernameDialog() {
EditUsernameDialogFragment editUsernameDialogFragment
= EditUsernameDialogFragment.newInstance("Edit Username");
editUsernameDialogFragment.show(ParentActivity.fragmentManager,
"fragment_edit_username");
}
@OnClick(R.id.ibParentProfileEditEmail)
public void onClickEditParentEmail() {
showEditEmailDialog();
}
private void showEditEmailDialog() {
EditEmailDialogFragment editEmailDialogFragment
= EditEmailDialogFragment.newInstance("Edit Email");
editEmailDialogFragment.show(ParentActivity.fragmentManager,
"fragment_edit_email");
}
@OnClick(R.id.ibParentProfileEditPassword)
public void onClickEditParentPassword() {
showEditPasswordDialog();
}
private void showEditPasswordDialog() {
EditPasswordDialogFragment editPasswordDialogFragment
= EditPasswordDialogFragment.newInstance("Edit Password");
editPasswordDialogFragment.show(ParentActivity.fragmentManager,
"fragment_edit_password");
}
@OnClick(R.id.ivParentProfileProfilePic)
public void onClickParentProfilePic() {
showEditImageDialog();
}
@OnClick(R.id.tvParentProfileEdit)
public void onClickEdit() {
showEditImageDialog();
}
private void showEditImageDialog() {
EditProfileImageDialogFragment editProfileImageDialogFragment
= EditProfileImageDialogFragment.newInstance("Edit Password");
editProfileImageDialogFragment.show(ParentActivity.fragmentManager,
"fragment_edit_profile_pic");
}
@OnClick(R.id.bParentProfileLogout)
public void onClickParentLogout() {
ParseUser.logOut();
Intent intent = new Intent(context, LoginActivity.class);
startActivity(intent);
getActivity().finish();
}
@OnClick(R.id.bParentProfileBankInfo)
public void onClickParentProfileBankInfo() {
Fragment bankFragment = new BanksListFragment();
ParentActivity.fragmentManager.beginTransaction()
.replace(R.id.flParentContainer, bankFragment)
.commit();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onFinishEditDialog() {
loadProfileData();
}
}
|
package com.hxzy.controller.portal;
import com.hxzy.common.vo.ResponseMessage;
import com.hxzy.service.api.HomeJobTableService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/api")
public class DetaileController {
@Autowired
HomeJobTableService homeJobTableService;
@ResponseBody
@GetMapping(value = "/detail/{id}")
public ResponseMessage detail(@PathVariable(value = "id") int id){
return this.homeJobTableService.searchById(id);
}
}
|
package com.tencent.mm.plugin.appbrand.launching;
import android.content.Intent;
import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.tencent.mm.plugin.appbrand.ui.banner.AppBrandStickyBannerLogic.b;
final class AppBrandLaunchErrorAction$a implements Creator<AppBrandLaunchErrorAction> {
AppBrandLaunchErrorAction$a() {
}
public final /* bridge */ /* synthetic */ Object[] newArray(int i) {
return new AppBrandLaunchErrorAction[i];
}
private static AppBrandLaunchErrorAction j(Parcel parcel) {
String readString = parcel.readString();
if (readString == null) {
return null;
}
try {
return (AppBrandLaunchErrorAction) Class.forName(readString).getDeclaredConstructor(new Class[]{Parcel.class}).newInstance(new Object[]{parcel});
} catch (Exception e) {
return null;
}
}
static AppBrandLaunchErrorAction a(String str, int i, t tVar) {
AppBrandLaunchErrorAction appBrandLaunchErrorAction = null;
if (!(tVar == null || tVar.field_launchAction == null)) {
switch (tVar.field_launchAction.qZk) {
case 2:
Intent intent = new Intent();
intent.putExtra("rawUrl", tVar.field_launchAction.rSK);
intent.putExtra("forceHideShare", true);
appBrandLaunchErrorAction = new AppBrandLaunchErrorActionStartActivity(str, i, "webview", ".ui.tools.WebViewUI", intent);
break;
case 3:
appBrandLaunchErrorAction = new AppBrandLaunchErrorActionAlert(str, i, tVar.field_launchAction.rMD, tVar.field_launchAction.rSM);
break;
}
if (appBrandLaunchErrorAction != null) {
b.anX();
}
}
return appBrandLaunchErrorAction;
}
}
|
package misc;
import java.util.*;
public class TicketCounter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int k = sc.nextInt();
// sc.close();
Deque<Integer> q = new ArrayDeque<>();
for (int i = 1; i <= n; i++) {
q.addLast(i);
}
while (q.size() != 1) {
int i = k;
while (i-- > 0 && q.size() != 1) {
q.pollFirst();
}
if(q.size() == 1) {
break;
}
i = k;
while(i-- > 0 && q.size() != 1) {
q.pollLast();
}
if(q.size() == 1) {
break;
}
}
System.out.println(q.peekFirst());
q.pollFirst();
}
sc.close();
}
}
|
package me.itsmas.minigames.game.games.test;
import me.itsmas.minigames.game.Game;
import me.itsmas.minigames.game.phase.phases.game.LastStandingPhase;
import me.itsmas.minigames.util.C;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
class TestFightPhase extends LastStandingPhase
{
TestFightPhase(Game game)
{
super(game);
}
@Override
public void onStart()
{
game.forEachPlayer(player -> player.getInventory().setItem(0, new ItemStack(Material.WOOD_SWORD)));
}
@Override
public String getActionBar(Player player)
{
return C.GOLD + "Players left standing: " + C.BOLD + game.getPlayersSize();
}
@Override
public List<String> getSidebar(Player player)
{
List<String> sidebar = new ArrayList<>();
sidebar.add(C.GOLD + C.BOLD + "Alive");
sidebar.add(String.valueOf(game.getPlayersSize()));
return sidebar;
}
}
|
package nl.rug.oop.flaps.simulation.model.cargo;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.swing.*;
import java.awt.*;
import java.util.Objects;
/**
* Represents a type of cargo. Note that this does not represent a unit of cargo; it only represents the type itself and
* the base properties of this type. These properties are the same for all classes that have this type.
*
* @author T.O.W.E.R.
*/
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class CargoType implements Comparable<CargoType> {
/**
* The name of the cargo type
*/
private String name;
/**
* The price per kg in euros
*/
private float basePricePerKg;
/**
* The sprite of this type
*/
@Setter
private Image image;
public ImageIcon getIcon() {
ImageIcon icon;
try {
icon = new ImageIcon(this.getImage().getScaledInstance(28, 28,Image.SCALE_DEFAULT));
} catch (Exception e) {
icon = null;
}
return icon;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CargoType cargoType = (CargoType) o;
return getName().equals(cargoType.getName());
}
@Override
public int hashCode() {
return Objects.hash(getName());
}
@Override
public String toString() {
return "CargoType{" +
"name='" + name + '\'' +
", basePricePerKg=" + basePricePerKg +
'}';
}
@Override
public int compareTo(CargoType o) {
return this.getName().compareTo(o.getName());
}
}
|
package pl.codeworld.jenkinsspringexample;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
@SpringBootTest
@AutoConfigureMockMvc
class JenkinsSpringExampleApplicationTests {
@Autowired
private MockMvc mockMvc;
@Test
void shouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string("Cześć przyjacielu"));
}
}
|
package com.shiro.pojo;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
public class UserInfo extends BasePojo
{
private String userInfoId;// 用户信息表id,这个id值和use_p的id是一样的,值是一致的
private String name;// 用户的真姓名
private String cardNo;// 身份证号
private String managerId;// 领导id(相当于部门的父部门,做自关联查询的时候要用的)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date joinDate;// 入职时间
private Double salary;// 薪资
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birthday;// 生日
private String gender;// 性别
private String station;// 级别
private String telephone;// 电话
private String userLevel;// 用户级别
private String remark;// 标注
private String orderNo;// 排序号
// 表示自关联查询的领导信息
private UserInfo manager;
public String getUserInfoId()
{
return userInfoId;
}
public void setUserInfoId(String userInfoId)
{
this.userInfoId = userInfoId;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getCardNo()
{
return cardNo;
}
public void setCardNo(String cardNo)
{
this.cardNo = cardNo;
}
public String getManagerId()
{
return managerId;
}
public void setManagerId(String managerId)
{
this.managerId = managerId;
}
public Date getJoinDate()
{
return joinDate;
}
public void setJoinDate(Date joinDate)
{
this.joinDate = joinDate;
}
public Double getSalary()
{
return salary;
}
public void setSalary(Double salary)
{
this.salary = salary;
}
public Date getBirthday()
{
return birthday;
}
public void setBirthday(Date birthday)
{
this.birthday = birthday;
}
public String getGender()
{
return gender;
}
public void setGender(String gender)
{
this.gender = gender;
}
public String getStation()
{
return station;
}
public void setStation(String station)
{
this.station = station;
}
public String getTelephone()
{
return telephone;
}
public void setTelephone(String telephone)
{
this.telephone = telephone;
}
public String getUserLevel()
{
return userLevel;
}
public void setUserLevel(String userLevel)
{
this.userLevel = userLevel;
}
public String getRemark()
{
return remark;
}
public void setRemark(String remark)
{
this.remark = remark;
}
public String getOrderNo()
{
return orderNo;
}
public void setOrderNo(String orderNo)
{
this.orderNo = orderNo;
}
public UserInfo getManager()
{
return manager;
}
public void setManager(UserInfo manager)
{
this.manager = manager;
}
}
|
package pucrs.java.maven.pets.model;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import pucrs.java.maven.pets.Pet;
import pucrs.java.maven.pets.model.Cat;
public class CatTest {
Pet garfield;
@Before
public void setup() {
garfield = new Cat("Garfield", Pet.Gender.MALE);
}
@Test
public void testCatHasAName() {
assertEquals("Garfield Meow!",garfield.talk());
}
@Test
public void testCatSex() {
assertEquals(Pet.Gender.MALE,garfield.getSex());
}
}
|
package daar;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class NDFARemoveEpsilon {
private int nLignes;
private int nColonnes;
public List<Integer>[][] ndfaMatrix;
public List<Integer>[][] nouveauNdfaMatrix;
private int indiceEpsilon = 256;
private int indiceInitiale = 257;
private int indiceFinale = 258;
static int numeroEtat = 0;
public NDFARemoveEpsilon(List<Integer>[][] ndfaMatrix, int nLignes, int nColonnes, int numeroEtat){
this.nLignes = nLignes;
this.nColonnes = nColonnes;
this.ndfaMatrix = ndfaMatrix;
this.numeroEtat = numeroEtat;
ArrayList[][] arrayLists = new ArrayList[this.nLignes][this.nColonnes];
this.nouveauNdfaMatrix = arrayLists;
}
public void supression() {
HashSet nonEtatPuit = new HashSet();
// ajout de l'etat intiale
nonEtatPuit.add(0);
for(int i=0; i<this.nLignes; i++) {
if (this.ndfaMatrix[i][this.indiceEpsilon] == null) {
this.nouveauNdfaMatrix[i] = this.ndfaMatrix[i];
for(int j=0; j<(this.nColonnes-3); j++) {
if ((this.ndfaMatrix[i][j] != null) && (j != this.indiceEpsilon)) {
for(int x=0; x<this.ndfaMatrix[i][j].size(); x++) {
nonEtatPuit.add(this.ndfaMatrix[i][j].get(x));
}
}
}
} else {
/*for (int x=0; x<this.ndfaMatrix[i][this.indiceEpsilon].size(); x++) {
if (this.ndfaMatrix[i][this.indiceEpsilon].get(x) == 1) {
// nouvel etat final
if (this.ndfaMatrix[i][this.indiceFinale] == null) {
ArrayList list = new ArrayList();
list.add(1);
this.ndfaMatrix[i][this.indiceFinale] = list;
} else {
this.ndfaMatrix[i][this.indiceFinale].add(1);
}
}
}*/
ArrayList lEtatsMemeGroupe = new ArrayList();
for(int x = 0; x<this.ndfaMatrix[i][this.indiceEpsilon].size(); x++) {
lEtatsMemeGroupe.add(this.ndfaMatrix[i][this.indiceEpsilon].get(x));
// traitement epsilon ==> epsilon ==> etat //nv//
int etat_pointe_epsilon = this.ndfaMatrix[i][this.indiceEpsilon].get(x);
if (this.ndfaMatrix[etat_pointe_epsilon][this.indiceEpsilon] != null) {
for(int z = 0; z<this.ndfaMatrix[etat_pointe_epsilon][this.indiceEpsilon].size(); z++) {
if (!(this.ndfaMatrix[i][this.indiceEpsilon].contains(this.ndfaMatrix[etat_pointe_epsilon][this.indiceEpsilon].get(z)))) {
this.ndfaMatrix[i][this.indiceEpsilon].add(this.ndfaMatrix[etat_pointe_epsilon][this.indiceEpsilon].get(z));
}
}
}
}
int tailleGroupe = lEtatsMemeGroupe.size();
for(int j=0; j<this.nColonnes; j++) {
ArrayList lEtatsCibles = new ArrayList();
for(int k=0; k<tailleGroupe; k++) {
if (lEtatsMemeGroupe.get(k) != null) {
if (this.ndfaMatrix[(int) lEtatsMemeGroupe.get(k)][j] != null) {
for(int x = 0; x<this.ndfaMatrix[(int) lEtatsMemeGroupe.get(k)][j].size(); x++) {
lEtatsCibles.add(this.ndfaMatrix[(int) lEtatsMemeGroupe.get(k)][j].get(x));
if (j < (this.nColonnes-3)) {
nonEtatPuit.add(this.ndfaMatrix[(int) lEtatsMemeGroupe.get(k)][j].get(x));
}
}
}
}
}
if (this.ndfaMatrix[i][j] != null) {
for(int x = 0; x<this.ndfaMatrix[i][j].size(); x++) {
lEtatsCibles.add(this.ndfaMatrix[i][j].get(x));
if (j < (this.nColonnes-3)) {
nonEtatPuit.add(this.ndfaMatrix[i][j].get(x));
}
}
}
if (lEtatsCibles.size() > 0) {
this.nouveauNdfaMatrix[i][j] = lEtatsCibles;
} else {
this.nouveauNdfaMatrix[i][j] = null;
}
this.nouveauNdfaMatrix[i][this.indiceEpsilon] = null;
}
}
}
for(int i=0; i<this.nLignes; i++) {
ArrayList[] listPleineDeNull = new ArrayList[this.nColonnes];
if (!(nonEtatPuit.contains(i))) {
this.nouveauNdfaMatrix[i] = listPleineDeNull;
}
}
}
}
|
package com.github.manage.repository.manage;
import com.github.manage.common.mapper.MyMapper;
import com.github.manage.entity.manage.SysUserRole;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface SysUserRoleMapper extends MyMapper<SysUserRole> {
}
|
package com.lhlp.pages.service.impl;
import com.lhlp.pages.entity.Manager;
import com.lhlp.pages.mapper.ManagerMapper;
import com.lhlp.pages.service.ManagerService;
import com.lhlp.pages.util.MyBatisUtil;
public class ManagerServiceImpl implements ManagerService {
private ManagerMapper managerMapper;
public ManagerServiceImpl(){
managerMapper = MyBatisUtil.getSession(true).getMapper(ManagerMapper.class);
}
@Override
public Manager login(Manager manager) {
return managerMapper.login(manager);
}
}
|
package JavaEgzersiz.Operatorler;
public class Operatorler {
public static void main(String[] args) {
// toplam();
// stringVeIntıgerDegerleriToplama();
// atamaVeToplamaOperatoru();
durumOperatorleri();
}
public static void toplam() {
Integer sayi1 = 15;
Integer toplam = sayi1 + 5;
System.out.println(toplam);
Integer sayi2 = 22;
toplam = toplam + sayi2;
System.out.println("burak" + toplam);
}
public static void stringVeIntıgerDegerleriToplama() {
Integer deger = 4;
String deger2 = "16";
String sonuc = deger + deger2;/*
deger atama yapmak icin atamak istediğimiz yapinin sonuna noktalivirgul koyulduktan sonra alt+enter komutuyla girilir ikinci secenek secilip deger atanir
*/
System.out.println(sonuc);
}
public static void atamaVeToplamaOperatoru() {
Integer deger = 17;
Integer degerCikarma = 20;
deger = deger + 7;
deger += 7;//toplama islemi bu sekilde de yapılabilir.
degerCikarma -= 2;
System.out.println(deger);
System.out.println(degerCikarma);
}
public static void durumOperatorleri() {
int x = 17;
Integer y = 30;
System.out.println(x == y);
System.out.println(x != y);
System.out.println(x > y);
System.out.println(x < y);
}
}
|
package com.spring.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="sme_dealer_payment_collected_file")
public class DealerPaymentCollected implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 833259063356396249L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "dealer_id")
private int dealer_id;
@Column(name = "seller_id")
private int sellerId;
@Column(name = "payment_clearance_date")
private String paymentClearanceDate;
@Column(name = "sap_dealer_code")
private String sapDealerCode;
@Column(name = "firm_name")
private String firmName;
@Column(name = "city")
private String city;
@Column(name = "invoice_number")
private String invoiceNo;
@Column(name = "invoice_date")
private String invoiceDate;
@Column(name = "invoice_value")
private Double invoiceValue;
@Column(name = "invoice_due_date")
private String invoiceDueDate;
@Column(name = "payment_mode")
private String paymentMode;
@Column(name = "payment_amount")
private Double paymentAmount;
@Column(name= "payment_entry_date")
private String paymentEntryDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPaymentClearanceDate() {
return paymentClearanceDate;
}
public void setPaymentClearanceDate(String paymentClearanceDate) {
this.paymentClearanceDate = paymentClearanceDate;
}
public String getSapDealerCode() {
return sapDealerCode;
}
public void setSapDealerCode(String sapDealerCode) {
this.sapDealerCode = sapDealerCode;
}
public String getFirmName() {
return firmName;
}
public void setFirmName(String firmName) {
this.firmName = firmName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getInvoiceNo() {
return invoiceNo;
}
public void setInvoiceNo(String invoiceNo) {
this.invoiceNo = invoiceNo;
}
public String getInvoiceDate() {
return invoiceDate;
}
public void setInvoiceDate(String invoiceDate) {
this.invoiceDate = invoiceDate;
}
public Double getInvoiceValue() {
return invoiceValue;
}
public void setInvoiceValue(Double invoiceValue) {
this.invoiceValue = invoiceValue;
}
public String getInvoiceDueDate() {
return invoiceDueDate;
}
public void setInvoiceDueDate(String invoiceDueDate) {
this.invoiceDueDate = invoiceDueDate;
}
public String getPaymentMode() {
return paymentMode;
}
public void setPaymentMode(String paymentMode) {
this.paymentMode = paymentMode;
}
public Double getPaymentAmount() {
return paymentAmount;
}
public void setPaymentAmount(Double paymentAmount) {
this.paymentAmount = paymentAmount;
}
public String getPaymentEntryDate() {
return paymentEntryDate;
}
public void setPaymentEntryDate(String paymentEntryDate) {
this.paymentEntryDate = paymentEntryDate;
}
public int getDealer_id() {
return dealer_id;
}
public void setDealer_id(int dealer_id) {
this.dealer_id = dealer_id;
}
public void setSellerId(int sellerId) {
this.sellerId = sellerId;
}
public int getSellerId() {
return sellerId;
}
}
|
package akademia.ox.exceptions;
public class NotEmptyFieldException extends RuntimeException {
}
|
package cn.edu.zucc.music.controller;
import cn.edu.zucc.music.Until.Result;
import cn.edu.zucc.music.Until.ResultStatus;
import cn.edu.zucc.music.model.*;
import cn.edu.zucc.music.service.*;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Controller
public class SheetController {
@Autowired
private SheetService sheetService;
@Autowired
private UserService userService;
@Autowired
private SongService songService;
@Autowired
private SheetSongService sheetSongService;
@Autowired
private ArtistService artistService;
@Autowired
private AlbumService albumService;
@CrossOrigin
@GetMapping(value = "/api/createSheet")
@ResponseBody
public JSONObject createSheet(String user_id, String sheetname){
JSONObject jsonObject = new JSONObject();
User user = userService.findById(user_id);
Sheet sheet = new Sheet();
String id = sheetService.findMaxSheetId();
String sheet_id = String.valueOf(Integer.parseInt(id)+1);
Date date = new Date();
sheet.setSheetId(sheet_id);
sheet.setSheetName(sheetname);
sheet.setSheetPicUrl(null);
sheet.setPlayCount(0);
sheet.setSheetType(1);
sheet.setCreateTime(date);
sheet.setUserId(user_id);
sheet.setUserName(user.getUserName());
sheetService.addSheet(sheet);
jsonObject.put("code", 200);
JSONObject data = PackerController.transformCreateSheetToJson(user, sheet);
jsonObject.put("data", data);
return jsonObject;
}
@CrossOrigin
@GetMapping(value = "/api/deleteSheet")
@ResponseBody
public JSONObject deleteSheet(String sheet_id) {
JSONObject jsonObject = new JSONObject();
Sheet sheet = sheetService.findById(sheet_id);
if(sheet == null) {
jsonObject.put("code", 666);
jsonObject.put("data", 0);
} else {
sheetService.deleteSheet(sheet_id);
jsonObject.put("code", 200);
jsonObject.put("data", 1);
}
return jsonObject;
}
@CrossOrigin
@GetMapping(value = "/api/recommandSheet")
@ResponseBody
public JSONObject recommandSheet() {
JSONObject jsonObject = new JSONObject();
List<Sheet> list = new ArrayList<Sheet>();
try {
list = sheetService.selectTenSheets();
jsonObject.put("code", 200);
List<JSONObject> data = new ArrayList<JSONObject>();
for(Sheet sheet : list) {
User user = userService.findById(sheet.getUserId());
JSONObject tmp = PackerController.transformSheetToJson(sheet,user);
data.add(tmp);
}
jsonObject.put("data", data);
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
@CrossOrigin
@GetMapping(value = "/api/getSheetDetails")
@ResponseBody
public JSONObject getSheetDetails(String sheet_id){
JSONObject jsonObject = new JSONObject();
Sheet sheet = sheetService.findById(sheet_id);
if(sheet.getSheetName().equals("") || sheet.getSheetName()==null) {
jsonObject.put("code", 666);
jsonObject.put("data", null);
} else {
List<SheetSong> sheet_songs = sheetSongService.getSongsBySheetId(sheet_id);
List<Song> old_songs = new ArrayList<Song>();
for(SheetSong sheet_song : sheet_songs) {
Song tmp = songService.findById(sheet_song.getSongId());
old_songs.add(tmp);
}
List<Song> songs = new ArrayList<Song>();
List<Album> albums = new ArrayList<Album>();
User user = userService.findById(sheet.getUserId());
for(Song song : old_songs) {
Artist artist = artistService.findById(song.getArtistId());
song.setArtistId(artist.getArtistName());
Album album = albumService.findById(song.getAlbumId());
songs.add(song);
albums.add(album);
}
jsonObject.put("code", 200);
JSONObject tmp = PackerController.transformSheetDetailsToJson(sheet, user, songs, albums);
jsonObject.put("data", tmp);
}
return jsonObject;
}
@CrossOrigin
@GetMapping(value = "/api/getPersonalSheet")
@ResponseBody
public JSONObject getPersonalSheet(String user_id) {
JSONObject jsonObject = new JSONObject();
User user = userService.findById(user_id);
List<Sheet> list = sheetService.findByUserID(user_id);
if(user.getUserId().equals("") || user.getUserId()==null || list.size()==0) {
jsonObject.put("code", 666);
jsonObject.put("data", null);
} else {
List<JSONObject> data = PackerController.transformPersonalSheetToJson(list, user);
jsonObject.put("code", 200);
jsonObject.put("data", data);
}
return jsonObject;
}
}
|
package com.FCI.SWE.Models;
import static org.testng.Assert.assertEquals;
import java.util.ArrayList;
import org.testng.annotations.Test;
public class UserTimelineTest {
/*** Failed ***/
@Test
public void getUserTimeline() {
boolean found = false;
if(UserTimeline.getUserTimeline(2) != null)
found = true;
assertEquals( found , true);
assertEquals( UserTimeline.getUserTimeline(11) , null);
}
/*** Passed ***/
@Test
public void saveUserTimeline() {
Post post = new Post(6, "a", "sadFa45", "Private" , "4elt SW xD rabna yastor",
5, "a");
ArrayList<Post> posts = new ArrayList<>();
posts.add(post);
UserTimeline userTimeline = new UserTimeline(3, "osama" , posts, "osama ");
assertEquals( userTimeline.saveUserTimeline() , true);
}
}
|
import java.util.Scanner;
import java.lang.*;
public class CountOfBits1 {
//Write a program to calculate the count of bits 1 in the binary representation
//of given integer number 'n'.
public static void main(String[] args) {
// Read input from the console
Scanner reader = new Scanner(System.in);
System.out.println("Enter number n: ");
int number = reader.nextInt();
//Invoke the method "bitCounter"
bitCounter(number);
//Using the build-in method bitCounnt (Java.lang.Integer.bitCount() Method)
System.out.println(Integer.bitCount(number));
}
//A method for counting the 1 bits in a binary representation of an integer number
public static void bitCounter(int num){
String binaryNumber = Integer.toBinaryString(num);
int counter = 0;
for (int i = 0; i < binaryNumber.length(); i++) {
if (binaryNumber.charAt(i) =='1') {
counter ++;
}
}
System.out.println(counter);
}
}
|
package com.example.jbarrientos.bilbapp.Model;
/**
* Created by jbarrientos on 14/01/17.
*/
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class RestClient {
private final String baseUrl;
public RestClient(String baseUrl) {
this.baseUrl = baseUrl;
}
private HttpURLConnection getConnection(String path) throws IOException {
URL url = new URL(String.format("%s/%s", baseUrl, path));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Connection","Keep-Alive");
return conn;
}
public String getString(String path) throws IOException {
HttpURLConnection conn = null;
try {
conn = getConnection(path);
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String volcado = br.readLine();
br.close();
return volcado;
} finally {
if (conn != null)
conn.disconnect();
}
}
public JSONObject getJson(String path) throws IOException, JSONException {
return new JSONObject(getString(path));
}
public int postJson(final JSONObject json, String path) throws IOException {
HttpURLConnection conn = null;
try {
conn = getConnection(path);
System.out.println("conexión recuperada");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
PrintWriter pw = new PrintWriter(conn.getOutputStream());
pw.print(json.toString());
pw.close();
return conn.getResponseCode();
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}
|
/**
*/
package sdo.impl;
import java.util.Collection;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EObjectResolvingEList;
import sdo.ConfigurationProfile;
import sdo.ConfigurationSet;
import sdo.Parameter;
import sdo.SdoPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Configuration Profile</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link sdo.impl.ConfigurationProfileImpl#getParameterList <em>Parameter List</em>}</li>
* <li>{@link sdo.impl.ConfigurationProfileImpl#getConfigurationSetList <em>Configuration Set List</em>}</li>
* </ul>
*
* @generated
*/
public class ConfigurationProfileImpl extends MinimalEObjectImpl.Container implements ConfigurationProfile {
/**
* The cached value of the '{@link #getParameterList() <em>Parameter List</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getParameterList()
* @generated
* @ordered
*/
protected EList<Parameter> parameterList;
/**
* The cached value of the '{@link #getConfigurationSetList() <em>Configuration Set List</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getConfigurationSetList()
* @generated
* @ordered
*/
protected EList<ConfigurationSet> configurationSetList;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ConfigurationProfileImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return SdoPackage.Literals.CONFIGURATION_PROFILE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Parameter> getParameterList() {
if (parameterList == null) {
parameterList = new EObjectResolvingEList<Parameter>(Parameter.class, this, SdoPackage.CONFIGURATION_PROFILE__PARAMETER_LIST);
}
return parameterList;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ConfigurationSet> getConfigurationSetList() {
if (configurationSetList == null) {
configurationSetList = new EObjectResolvingEList<ConfigurationSet>(ConfigurationSet.class, this, SdoPackage.CONFIGURATION_PROFILE__CONFIGURATION_SET_LIST);
}
return configurationSetList;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case SdoPackage.CONFIGURATION_PROFILE__PARAMETER_LIST:
return getParameterList();
case SdoPackage.CONFIGURATION_PROFILE__CONFIGURATION_SET_LIST:
return getConfigurationSetList();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case SdoPackage.CONFIGURATION_PROFILE__PARAMETER_LIST:
getParameterList().clear();
getParameterList().addAll((Collection<? extends Parameter>)newValue);
return;
case SdoPackage.CONFIGURATION_PROFILE__CONFIGURATION_SET_LIST:
getConfigurationSetList().clear();
getConfigurationSetList().addAll((Collection<? extends ConfigurationSet>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case SdoPackage.CONFIGURATION_PROFILE__PARAMETER_LIST:
getParameterList().clear();
return;
case SdoPackage.CONFIGURATION_PROFILE__CONFIGURATION_SET_LIST:
getConfigurationSetList().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case SdoPackage.CONFIGURATION_PROFILE__PARAMETER_LIST:
return parameterList != null && !parameterList.isEmpty();
case SdoPackage.CONFIGURATION_PROFILE__CONFIGURATION_SET_LIST:
return configurationSetList != null && !configurationSetList.isEmpty();
}
return super.eIsSet(featureID);
}
} //ConfigurationProfileImpl
|
package com.example.albertusk95.simpleloginapp;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class user extends AppCompatActivity {
final Context context = this;
private Button logout_btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
logout_btn = (Button) findViewById(R.id.button_logout);
}
public void LogoutButton() {
// add button listener
logout_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("Logout confirmation");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to log out?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, go back to the login screen
Intent intent = new Intent("com.example.albertusk95.simpleloginapp.login");
startActivity(intent);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
}
|
package io.flexio.services.api.documentation.ResourcesManager;
import io.flexio.services.api.documentation.Exceptions.ResourceNotFoundException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import java.io.InputStream;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
public class FileSystemResourcesManagerTest {
private FileSystemResourcesManager fs;
@Rule
public TemporaryFolder tmpFolderStorage = new TemporaryFolder();
@Rule
public TemporaryFolder tmpFolderManifest = new TemporaryFolder();
@Rule
public TemporaryFolder tmpFolderInputStream = new TemporaryFolder();
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setUp() {
this.fs = new FileSystemResourcesManager(
tmpFolderStorage.getRoot().getAbsolutePath(),
tmpFolderManifest.getRoot().getAbsolutePath(),
tmpFolderInputStream.getRoot().getAbsolutePath());
}
@Test
public void given1Zip__thenMDMatches() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
assertNotNull(classLoader);
InputStream is = classLoader.getResourceAsStream("html.zip");
assertNotNull(is);
assertThat(fs.getmd5(is), is("c67e46795eca063e483f16c6fba5fab6"));
is = classLoader.getResourceAsStream("html2Files.zip");
assertThat(fs.getmd5(is), is("2121b2df6f35eab1599a5a29d9ec9f25"));
}
@Test
public void given1Zip__whenCalledTwice__then1FileExtractedOnlyTheFirstTime() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
InputStream is = classLoader.getResourceAsStream("html.zip");
assertNotNull(is);
String pathBase = ResourcesManager.buildPath("g1", "m1", "1.0.0", "c");
ExtractZipResult result = fs.addZipResource(is, "g1", "m1", "1.0.0", "c");
assertThat(result.isExtracted(), is(true));
assertThat(result.getPath(), is(pathBase));
int nbResources = fs.getResources("g1", "m1", "1.0.0", "c").size();
assertThat(nbResources, is(1));
is = classLoader.getResourceAsStream("html.zip");
result = fs.addZipResource(is, "g1", "m1", "1.0.0", "c");
assertThat(result.isExtracted(), is(false));
}
@Test
public void givenSend3Files__then3Groups() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
assertNotNull(classLoader);
InputStream is;
assertThat(fs.getGroups().size(), is(0));
is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, "g1", "m", "1", "c");
is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, "g2", "m", "1", "c");
is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, "g3", "m", "1", "c");
assertThat(fs.getGroups().size(), is(3));
}
@Test
public void givenVersion1__thenGetVersion1_0_0() throws Exception{
ClassLoader classLoader = getClass().getClassLoader();
assertNotNull(classLoader);
InputStream is;
assertThat(fs.getGroups().size(), is(0));
is = classLoader.getResourceAsStream("html.zip");
ExtractZipResult result = fs.addZipResource(is, "g1", "m1", "1", "c");
assertThat(result.getPath(), is("g1/m1/1.0.0/c"));
}
@Test
public void whenNoDir__thenThrowResourceNotFound0Group() throws Exception {
String group = "group1";
thrown.expect(ResourceNotFoundException.class);
assertThat(fs.getModules(group).size(), is(0));
}
@Test
public void givenSend3Files__then3Modules() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
assertNotNull(classLoader);
InputStream is;
String group = "group1";
is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, group, "m1", "1", "c");
is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, group, "m2", "1", "c");
is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, group, "m3", "1", "c");
assertThat(fs.getModules(group).size(), is(3));
}
@Test
public void whenNoDir__thenThrowResourceNotFound0Version() throws Exception {
String group = "group1";
String module = "module1";
thrown.expect(ResourceNotFoundException.class);
assertThat(fs.getVersions(group, module).size(), is(0));
}
@Test
public void givenSend3Files__then3Versions() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
assertNotNull(classLoader);
InputStream is;
String group = "group1";
String module = "module1";
is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, group, module, "1", "c");
is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, group, module, "2", "c");
is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, group, module, "3", "c");
assertThat(fs.getVersions(group, module).size(), is(4)); // 3 + Latest
}
@Test
public void givenSend3FilesSnapshoot__then3Versions() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
assertNotNull(classLoader);
InputStream is;
String group = "group1";
String module = "module1";
is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, group, module, "1", "c");
is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, group, module, "2-snapshot", "c");
is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, group, module, "3", "c");
assertThat(fs.getVersions(group, module).size(), is(5)); // 3 + Latest + snapshot
}
@Test
public void whenNoDir__thenThrowResourceNotFound0Classifier() throws Exception {
String group = "group1";
String module = "module1";
String version = "1";
thrown.expect(ResourceNotFoundException.class);
assertThat(fs.getClassifiers(group, module, version).size(), is(0));
}
@Test
public void givenSend3Files__then3Classifiers() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
InputStream is;
String group = "group1";
String module = "module1";
String version = "1.0.0";
is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, group, module, version, "c1");
is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, group, module, version, "c2");
is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, group, module, version, "c3");
assertThat(fs.getClassifiers(group, module, version).size(), is(3));
}
@Test
public void givenNoDir__whenGetResources__thenThrowResourceNotFound() throws Exception {
thrown.expect(ResourceNotFoundException.class);
fs.getResources("g", "m", "v", "c2");
}
@Test
public void givenNoDir__whenGetClassifiers__thenThrowResourceNotFound() throws Exception {
thrown.expect(ResourceNotFoundException.class);
fs.getClassifiers("g", "m", "2");
}
@Test
public void givenNoDir__whenGetVersions__thenThrowResourceNotFound() throws Exception {
thrown.expect(ResourceNotFoundException.class);
fs.getVersions("g", "m2");
}
@Test
public void givenNoDir__whenGetModules__thenThrowResourceNotFound() throws Exception {
thrown.expect(ResourceNotFoundException.class);
fs.getModules("g2");
}
@Test
public void givenZip2Files__then2Files() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
InputStream is;
String group = "group1";
String module = "module1";
String version = "2.4.51";
String classifier = "c";
is = classLoader.getResourceAsStream("html2Files.zip");
fs.addZipResource(is, group, module, version, classifier);
assertThat(fs.getResources(group, module, version, classifier).size(), is(2));
}
@Test
public void givenEmptyZip__then0Files() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
InputStream is = classLoader.getResourceAsStream("empty.zip");
fs.addZipResource(is, "g", "m", "3.14.15", "c");
assertThat(fs.getResources("g", "m", "3.14.15", "c").size(), is(0));
}
@Test
public void givenZipWithManifestFile__then1Files() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
InputStream is = classLoader.getResourceAsStream("Manifest.zip");
fs.addZipResource(is, "g", "m", "0.5.1", "c");
assertThat(fs.getResources("g", "m", "0.5.1", "c").size(), is(1));
}
@Test
public void givenTwoVersions__whenCallLatest__thenLatestIsTheHigher() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
InputStream is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, "g", "m", "1", "c");
assertThat(fs.getResources("g", "m", "LATEST", "c").size(), is(1));
is = classLoader.getResourceAsStream("html2Files.zip");
fs.addZipResource(is, "g", "m", "2", "c");
assertThat(fs.getResources("g", "m", "LATEST", "c").size(), is(2));
}
@Test
public void givenMultipleVersions__whenCallLatest__thenLatestIsTheHigher() throws Exception{
ClassLoader classLoader = getClass().getClassLoader();
InputStream is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, "g", "m", "1.0.0", "c");
}
@Test
public void givenSameVersion__whenCallLatest__thenLatestIsTheLast() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
InputStream is = classLoader.getResourceAsStream("html.zip");
fs.addZipResource(is, "g", "m", "1", "c");
assertThat(fs.getResources("g", "m", "LATEST", "c").size(), is(1));
is = classLoader.getResourceAsStream("html2Files.zip");
fs.addZipResource(is, "g", "m", "1", "c");
assertThat(fs.getResources("g", "m", "LATEST", "c").size(), is(2));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.