text
stringlengths
10
2.72M
/* * 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 algo; import jdk.nashorn.internal.objects.Global; import model.Location; import model.Vehicle; /** * * @author Team Foufou */ public class IntraTourInfos { private Vehicle vehicle; protected final int positionFrom; protected final int positionTo; /** * DeltaCost between the previous cost and the new one, it must be positive to do the change */ protected double deltaCost; protected Location bestLocation; /** * Data Constructor * * @param vehicle * @param positionFrom * @param positionTo */ public IntraTourInfos(Vehicle vehicle, int positionFrom, int positionTo) { this.vehicle = vehicle; this.positionFrom = positionFrom; this.positionTo = positionTo; this.deltaCost = Global.Infinity; this.bestLocation = null; } /** * * @return vehicle */ public Vehicle getVehicle() { return vehicle; } /** * * @return positionFrom */ public int getPositionFrom() { return positionFrom; } /** * * @return positionTo */ public int getPositionTo() { return positionTo; } /** * * @return deltaCost */ public double getDeltaCost() { return deltaCost; } /** * * @return bestLocation */ public Location getBestLocation() { return bestLocation; } /** * Launch the calcul of the cost for the bestLocation */ public void calculateDeltaCost() { this.deltaCost = this.vehicle.calculateDeltaMovementCost(positionFrom, positionTo, bestLocation); if (this.deltaCost == Double.NEGATIVE_INFINITY) this.deltaCost = 0.0; } /** * * @param location */ public void checkMovementTime(Location location) { this.bestLocation = this.vehicle.checkMovementLocation(positionFrom, positionTo, location); } /** * Execute the deplacement from the previous position to the new one * @return true */ public boolean doDeplacementIntraTournee() { if (!this.vehicle.moveLocation(positionFrom, positionTo, bestLocation)) return false; return true; } @Override public String toString() { return "IntraTourInfos{" + "Location=" + bestLocation + ", positionFrom=" + positionFrom + ", positionTo=" + positionTo + ", delta=" + deltaCost + '}'; } }
/* * Merge HRIS API * The unified API for building rich integrations with multiple HR Information System platforms. * * The version of the OpenAPI document: 1.0 * Contact: hello@merge.dev * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package merge_hris_client.api; import merge_hris_client.ApiException; import merge_hris_client.model.DataPassthroughRequest; import merge_hris_client.model.RemoteResponse; import org.junit.Test; import org.junit.Ignore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for PassthroughApi */ @Ignore public class PassthroughApiTest { private final PassthroughApi api = new PassthroughApi(); /** * * * Pull data from an endpoint not currently supported by Merge. * * @throws ApiException * if the Api call fails */ @Test public void passthroughCreateTest() throws ApiException { String xAccountToken = null; DataPassthroughRequest dataPassthroughRequest = null; RemoteResponse response = api.passthroughCreate(xAccountToken, dataPassthroughRequest); // TODO: test validations } }
package pushMessage; import lombok.Data; /** * @program: left-box * @description: * @author: Payton Wang * @date: 2019-10-03 14:17 **/ @Data public class Content { private String value; public Content() { } public Content(String value) { this.value = value; } }
package com.example.pfweather.ui; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; import android.view.animation.AlphaAnimation; public class LoginActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //设置为无标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); //设置为全屏模式 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.login); //获取组件 //背景透明度变化3秒内从0.3变到1.0 AlphaAnimation aa = new AlphaAnimation(0.3f, 1.0f); aa.setDuration(3000); //创建Timer对象 Timer timer = new Timer(); //创建TimerTask对象 TimerTask timerTask = new TimerTask() { @Override public void run() { Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); finish(); } }; //使用timer.schedule()方法调用timerTask,定时3秒后执行run timer.schedule(timerTask, 3000); } }
//https://leetcode.com/problems/largest-number-at-least-twice-of-others/ public class LargestTwice{ public int dominantIndex(int[] nums) { int maxIndex = 0 ; //In this pass find the pos where the max element is present in the array for(int i=0;i<nums.length;i++) if(nums[i]>nums[maxIndex]) maxIndex = i; //After finding maxIndex, Now see whether this condition is met MaxEle > Twice(every element) for(int i=0;i<nums.length;i++) if(maxIndex != i && nums[maxIndex] < 2*nums[i]) return -1; return maxIndex; } }
package tp.rest; import javax.xml.ws.Endpoint; import tp.model.City; import tp.model.CityManager; public class MyServiceTP{ public MyServiceTP() { CityManager cityManager = new CityManager(); cityManager.addCity(new City("Rouen",0,0,"France")); Endpoint.publish("http://127.0.0.1:8084/citymanager", cityManager); } public static void main(String args[]) throws InterruptedException { new MyServiceTP(); Thread.sleep(15*60*1000); System.exit(0); } }
package us.team7pro.EventTicketsApp.Models; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.format.annotation.DateTimeFormat; import lombok.Data; import java.util.Date; @Entity @Data @Table(name="events") public class Event { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int eventID; private long organizerID; private String eventName; private String eventCategory; // Concerts, Sports, Festivals @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm") private Date date; private String location; private String description; private float price; private String imgUrl; private boolean status; // approved or not public Event() {} public Event(long organizerID, String eventName, String eventCategory, String location, Date date, String description, float price, String imgUrl, boolean status) { this.organizerID = organizerID; this.eventName = eventName; this.eventCategory = eventCategory; this.location = location; this.date = date; this.description = description; this.price = price; this.imgUrl = imgUrl; this.status = status; } }
package at.ac.tuwien.sepm.groupphase.backend.unittests; import at.ac.tuwien.sepm.groupphase.backend.basetest.TestData; import at.ac.tuwien.sepm.groupphase.backend.entity.Cart; import at.ac.tuwien.sepm.groupphase.backend.entity.CartItem; import at.ac.tuwien.sepm.groupphase.backend.repository.CartItemRepository; import at.ac.tuwien.sepm.groupphase.backend.repository.CartRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.time.LocalDateTime; import java.util.HashSet; import java.util.Set; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertFalse; @ExtendWith(SpringExtension.class) @DataJpaTest @ActiveProfiles("test") class CartRepositoryTest implements TestData { private final Cart cart = new Cart(); private final CartItem cartItem = new CartItem(); @Autowired private CartRepository cartRepository; @Autowired private CartItemRepository cartItemRepository; @BeforeEach void beforeEach() { this.cartItemRepository.deleteAll(); this.cartRepository.deleteAll(); cart.setCreatedAt(LocalDateTime.now()); Set<CartItem> itemSet = new HashSet<>(); cartItem.setId(1L); cartItem.setProductId(1L); cartItem.setQuantity(5); itemSet.add(cartItemRepository.save(cartItem)); cart.setItems(itemSet); } @Test void givenAllProperties_whenSaveCart_thenFindWithCartBySessionIdCheckIfCarExistsDeleteCarByDate() { UUID sessionId = UUID.randomUUID(); cart.setSessionId(sessionId); cartRepository.save(cart); assertTrue(cartRepository.findBySessionId(sessionId).isPresent()); assertEquals(cart, cartRepository.findBySessionId(sessionId).get()); assertTrue(cartRepository.existsCartBySessionId(sessionId)); assertTrue(cartRepository.findCartItemInCartUsingSessionId(sessionId, 1L).isPresent()); assertEquals(cartItem, cartRepository.findCartItemInCartUsingSessionId(sessionId, 1L).get()); assertTrue(cartRepository.countCartItemInCartUsingSessionId(sessionId).isPresent()); assertEquals(1 ,cartRepository.countCartItemInCartUsingSessionId(sessionId).get()); cartRepository.deleteCartByCreatedAtIsBefore(LocalDateTime.now()); assertFalse(cartRepository.existsCartBySessionId(sessionId)); } }
package com.hopu.bigdata.controller; import com.hopu.bigdata.model.Userinfo; import com.hopu.bigdata.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; @Controller public class LoginController { @Autowired private PasswordEncoder passwordEncoder; @Autowired private UserService userService; @GetMapping("/login") public String login() { return "login"; } @GetMapping("/login-error") public String loginError() { return "login-error"; } @GetMapping("/registry") public String registry(Model model) { Userinfo user = new Userinfo(); user.setSex("男"); model.addAttribute("user", user); return "registry"; } @PostMapping("/registry") public String registry(@ModelAttribute("user") Userinfo user, Model model, @RequestParam(required=false) boolean modify) { model.addAttribute("modify", modify); // 用户已存在 if (!modify && userService.getUserByName(user.getLoginname()) != null) { model.addAttribute("error", true); model.addAttribute("error_msg", "用户 '" + user.getLoginname() + "'已存在!"); return "registry"; } user.setPassword(passwordEncoder.encode(user.getPassword())); if (!modify) { userService.save(user); } else { userService.updateById(user); model.addAttribute("result", "用户修改成功!"); return "registry"; } return "login"; } }
package com.lenovohit.hwe.pay.support.acctpay.balance.transfer; public class RestEntityResponse<T> extends RestResponse { public RestEntityResponse(){ super(); } public RestEntityResponse(RestResponse reponse){ super(); if(null == reponse){ return; } this.setSuccess(reponse.getSuccess()); this.setMsg(reponse.getMsg()); this.setResult(reponse.getResult()); this.setEntity(null); } public RestEntityResponse(RestResponse reponse, T entity){ super(); if(null == reponse){ return; } this.setSuccess(reponse.getSuccess()); this.setMsg(reponse.getMsg()); this.setResult(reponse.getResult()); this.setEntity(entity); } private T entity; public T getEntity() { return entity; } public void setEntity(T entity) { this.entity = entity; } }
/* * Maze.java∑≠“Ž * * Created on __DATE__, __TIME__ */ package maze; import java.awt.Color; import java.awt.Window; import javax.swing.JPanel; /** * * @author __USER__ */ public class Maze extends javax.swing.JFrame { /** Creates new form Maze */ public Maze() { initComponents(); } //GEN-BEGIN:initComponents // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPanel1 = new MyPanel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jRadioButton3 = new javax.swing.JRadioButton(); jButton5 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setMaximumSize(new java.awt.Dimension(300, 300)); jPanel1.setMinimumSize(new java.awt.Dimension(300, 300)); jPanel1.setPreferredSize(new java.awt.Dimension(300, 300)); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout( jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 399, Short.MAX_VALUE)); jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 300, Short.MAX_VALUE)); jButton1.setText("Start"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Reset"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("Hint"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setText("Close"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jRadioButton1.setText("Normal"); jRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton1ActionPerformed(evt); } }); jRadioButton2.setText("Nightmare"); jRadioButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton2ActionPerformed(evt); } }); jRadioButton3.setText("Hell"); jRadioButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton3ActionPerformed(evt); } }); jButton5.setText("Clear"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout( getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE) .addGroup( javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addComponent( jButton1) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( jButton2)) .addGroup( layout.createSequentialGroup() .addComponent( jRadioButton1) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( jRadioButton2) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( jRadioButton3))) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup( layout.createSequentialGroup() .addComponent( jButton5) .addContainerGap( javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup( javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent( jButton3) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( jButton4) .addContainerGap())))); layout.setVerticalGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup( javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton1) .addComponent(jRadioButton2) .addComponent(jRadioButton3) .addComponent(jButton5)) .addGap(18, 18, 18) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2) .addComponent(jButton4) .addComponent(jButton3)) .addContainerGap())); pack(); }// </editor-fold> //GEN-END:initComponents private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: jPanel1.clearHint(); } private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) { System.out.println(jRadioButton3.isSelected()); // TODO add your handling code here: if (jRadioButton3.isSelected()) { jRadioButton2.setSelected(false); jRadioButton1.setSelected(false); jPanel1.init(6); } } private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: if (jRadioButton2.isSelected()) { jRadioButton3.setSelected(false); jRadioButton1.setSelected(false); jPanel1.init(12); } } private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: if (jRadioButton1.isSelected()) { jRadioButton2.setSelected(false); jRadioButton3.setSelected(false); jPanel1.init(15); } } // private void jCheckBox3ActionPerformed(java.awt.event.ActionEvent evt) { // // TODO add your handling code here: // System.out.println(jCheckBox3.isSelected()); // // } // // private void jCheckBox2ActionPerformed(java.awt.event.ActionEvent evt) { // // TODO add your handling code here: // if (jCheckBox2.isSelected()) { // jPanel1.init(12); // } // } // // private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) { // // TODO add your handling code here: // if (jCheckBox1.isSelected()) { // jPanel1.init(15); // } // } private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: jPanel1.path(); } private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: dispose(); } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: jPanel1.init(jPanel1.getCellSize()); } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: jPanel1.init(24); } /** * @param args * the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Maze().setVisible(true); } }); } //GEN-BEGIN:variables // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private MyPanel jPanel1; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JRadioButton jRadioButton3; // End of variables declaration//GEN-END:variables }
package com.app.eslamhossam23.testceihm; import android.animation.AnimatorSet; import android.animation.ValueAnimator; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; /** * Created by Eslam on 0016 16/12/2016. */ public class GameActivity extends AppCompatActivity { //Periode entre deux affichages successifs de hints public static final int PERIOD = 20000; public static final int INACTIVITY_DELAY = 20000; public static final String HINT_TEXT = "Appuyez sur un thème pour le sélectionner."; // List<Theme> themes = new ArrayList<>(); public static Timer timer; public static int imageID; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { imageID = getIntent().getIntExtra("image", R.drawable.accueil); // themes.add(new Theme(imageID, "Moi")); // themes.add(new Theme(R.drawable.mariage, "Mariage")); // themes.add(new Theme(R.drawable.family, "Famille")); // themes.add(new Theme(R.drawable.children_1, "Enfants")); super.onCreate(savedInstanceState); setContentView(R.layout.game_layout); ImageView moi = (ImageView)findViewById(R.id.moi); moi.setImageResource(imageID); moi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(GameActivity.this, AccueilActivity.class); startActivity(intent); } }); ImageView famille = (ImageView)findViewById(R.id.family); famille.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(GameActivity.this, PuzzleActivity.class); startActivity(intent); } }); // String prenom = getIntent().getExtras().getString("prenom"); // Toast.makeText(this, prenom, Toast.LENGTH_SHORT).show(); // GridView gridView = (GridView) findViewById(R.id.listCategories); // ArrayAdapter arrayAdapter = new ListAdapter(); // gridView.setAdapter(arrayAdapter); // timer = new Timer(); // timer.schedule(new TimerTask() { // @Override // public void run() { //// final ImageView cursor = (ImageView) findViewById(R.id.cursor); // runOnUiThread(new Runnable() { // @Override // public void run() { // showHint(HINT_TEXT); // } // }); // // } // }, 0, PERIOD); } @Override protected void onResume() { super.onResume(); ImageView moi = (ImageView)findViewById(R.id.moi); moi.setImageResource(imageID); } public void showHint(final String hint) { // final AnimatorSet animatorSet = new AnimatorSet(); final View guideView = findViewById(R.id.guide); guideView.setAlpha(0); guideView.setVisibility(View.VISIBLE); final ValueAnimator valueAnimator = ValueAnimator.ofFloat(guideView.getAlpha(), guideView.getAlpha() + 1f); valueAnimator.setDuration(2000); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { guideView.setAlpha((Float) animation.getAnimatedValue()); if((Float)animation.getAnimatedValue() == 1f){ hideHint(); } } }); // final ImageView cursor = (ImageView) findViewById(R.id.cursor); // final float oldCursorLocationX = cursor.getX(); // final ImageView imageHolder = (ImageView) findViewById(R.id.image_placeholder); // final ValueAnimator valueAnimator2 = ValueAnimator.ofFloat(cursor.getX(), imageHolder.getX() + 30f); // valueAnimator2.setDuration(2000); // valueAnimator2.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { // @Override // public void onAnimationUpdate(ValueAnimator animation) { // cursor.setX((Float) animation.getAnimatedValue()); // if((float) animation.getAnimatedValue() == imageHolder.getX() + 30f){ // cursor.setImageResource(R.drawable.cursor_click); // hideHint(oldCursorLocationX); // } // } // }); // animatorSet.play(valueAnimator).before(valueAnimator2); // animatorSet.start(); valueAnimator.start(); TextView hintTextView = (TextView) guideView.findViewById(R.id.hint); hintTextView.setText(hint); findViewById(R.id.listCategories).setVisibility(View.INVISIBLE); } public void hideHint() { final View guideView = findViewById(R.id.guide); ValueAnimator valueAnimator = ValueAnimator.ofFloat(guideView.getAlpha(), 0f); valueAnimator.setDuration(2000); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { guideView.setAlpha((Float) animation.getAnimatedValue()); if((float) animation.getAnimatedValue() == 0f){ // ImageView cursor = (ImageView) findViewById(R.id.cursor); // cursor.setImageResource(R.drawable.cursor); // cursor.setX(oldCursorLocationX); guideView.setVisibility(View.INVISIBLE); findViewById(R.id.listCategories).setVisibility(View.VISIBLE); } } }); valueAnimator.start(); } private void startTimer() { timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { // final ImageView cursor = (ImageView) findViewById(R.id.cursor); showHint(HINT_TEXT); } }); } }, INACTIVITY_DELAY, PERIOD); } @Override public boolean onTouchEvent(MotionEvent event) { // pauseTimer(); // startTimer(); return super.onTouchEvent(event); } private void pauseTimer() { timer.cancel(); } // private class ListAdapter extends ArrayAdapter { // public ListAdapter() { // super(GameActivity.this, R.layout.simple_list_item_2, themes); // } // // @NonNull // @Override // public View getView(int position, View convertView, @NonNull ViewGroup parent) { // View itemView = convertView; // if (itemView == null) { // itemView = getLayoutInflater().inflate(R.layout.simple_list_item_2, parent, false); // } // final Theme theme = themes.get(position); // ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView2); // TextView textView = (TextView) itemView.findViewById(R.id.textView2); // textView.setText(theme.getName()); // imageView.setImageResource(theme.getIdImage()); // imageView.setTag(theme.getIdImage()); // itemView.setOnClickListener(new View.OnClickListener() { //// String nom = theme.getName(); // @Override // public void onClick(final View v) { //// ValueAnimator valueAnimator = ValueAnimator.ofFloat(v.getY(), v.getY() + 50f); //// valueAnimator.setDuration(1000); //// valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { //// @Override //// public void onAnimationUpdate(ValueAnimator animation) { //// v.setY((Float) animation.getAnimatedValue()); //// } //// }); //// valueAnimator.start(); //// Toast.makeText(getContext(), "Vous avez selectionné " + nom, Toast.LENGTH_SHORT).show(); // if((int) v.findViewById(R.id.imageView2).getTag() == imageID){ // Intent intent = new Intent(GameActivity.this, AccueilActivity.class); // startActivity(intent); // }else if((int) v.findViewById(R.id.imageView2).getTag() == R.drawable.family) { // Intent intent = new Intent(GameActivity.this, PuzzleActivity.class); // startActivity(intent); // }else if((int) v.findViewById(R.id.imageView2).getTag() == R.drawable.children_1) { // Intent intent = new Intent(GameActivity.this,Nb_enfant.class); // startActivity(intent); // } // } // }); // return itemView; //// return super.getView(position, convertView, parent); // } // } }
package Problem_14494; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String buf = br.readLine(); int N = Integer.parseInt(buf.split(" ")[0]); int M = Integer.parseInt(buf.split(" ")[1]); long[][] dp = new long[N+1][M+1]; for(int i = 1; i<=N; i++) dp[i][1] = 1; for(int j = 1; j<=M; j++) dp[1][j] = 1; for(int i = 2; i<=N; i++) { for(int j =2; j<=M;j++) { dp[i][j] = (dp[i][j-1] + dp[i-1][j] + dp[i-1][j-1]); dp[i][j] %= 1000000007; } } System.out.println(dp[N][M]); } }
package entities; import graphics.Sprite; import java.util.ArrayList; public class Bomber extends GameCharacter { public static final double BOMBER_SPEED = 2.8; private static int BOMB_AMOUNT = 1; public static int FLAME_SIZE = 1; private int availableBomb = BOMB_AMOUNT; public Bomber(double x, double y, ArrayList<Sprite> sprites) { super(x, y, sprites); this.moveSpeed = BOMBER_SPEED; } @Override public void update(){ if (!this.isDoomed) { this.xLeft += this.rightVelocity * this.moveSpeed; this.yTop += this.downVelocity * this.moveSpeed; } else { this.getNextImg(); } } @Override public void getDirection(Bomber player, ArrayList<Entity> blocks, ArrayList<Bomb> bombs) { /* Bomber will not automatically move. */ } public boolean haveBomb() { return availableBomb > 0; } public boolean dropBomb(ArrayList<Bomb> bombs) { if (availableBomb > 0) { for (Bomb b : bombs) { if (b.getXUnit() == this.getXUnit() && b.getYUnit() == this.getYUnit()) { return false; } } System.out.println(availableBomb); availableBomb --; return true; } return false; } public void addBomb() { availableBomb ++; } public void control(String action, ArrayList<Bomb> bombs, long timer) { switch (action) { case "LEFT": this.velocityUpdate(-1, 0); this.getNextImg(Sprite.bomber_left, 1); break; case "RIGHT": this.velocityUpdate(1, 0); this.getNextImg(Sprite.bomber_right, 0); break; case "UP": this.velocityUpdate(0, -1); this.getNextImg(Sprite.bomber_up, 3); break; case "DOWN": this.velocityUpdate(0, 1); this.getNextImg(Sprite.bomber_down, 2); break; case "SPACE": if (this.haveBomb()) { if (this.dropBomb(bombs)) { bombs.add(new Bomb(this.getXUnit(), this.getYUnit(), Sprite.bomb, timer)); } } default: break; } } public void bombsPowerup() { this.availableBomb ++; BOMB_AMOUNT ++; } }
package com.pim.controller; import com.pim.model.SkuModel; import com.pim.repository.domain.SkuInfo; import com.pim.service.CatalogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.List; /** * Created by pkulkar4 on 8/1/18. */ @RestController public class SkuController { @Autowired private CatalogService catalogService; @RequestMapping(method = RequestMethod.GET, value = "/sku/load", produces = "application/json") public ResponseEntity loadSkuData(){ HashMap<String, String> attributes = new HashMap<>(); attributes.put("color","Black"); attributes.put("size", "8"); catalogService.load(SkuModel .builder().id("11223344556") .displayName("NikeBlackShoes").dynamicAttributes(attributes).build()); return null; } @RequestMapping(method = RequestMethod.GET, value = "/sku/save", produces = "application/json") public ResponseEntity saveSku(@RequestBody SkuModel model){ catalogService.load(model); return new ResponseEntity(true, HttpStatus.OK); } @RequestMapping(method = RequestMethod.GET, value = "/sku/top", produces = "application/json") public ResponseEntity<List<SkuModel>> getTopSku(){ return new ResponseEntity<List<SkuModel>>(catalogService.getSkus(10), HttpStatus.OK) ; } }
package com.energytrade.app.model; import java.io.Serializable; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; /** * The persistent class for the all_forecasts database table. * */ @Entity @Table(name="all_forecasts") @NamedQuery(name="AllForecast.findAll", query="SELECT a FROM AllForecast a") public class AllForecast implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="forecast_id") private int forecastId; @Column(name="active_status") private byte activeStatus; @Column(name="created_by") private String createdBy; @Temporal(TemporalType.TIMESTAMP) @Column(name="created_ts") private Date createdTs; @Column(name="ev_power") private BigDecimal evPower; @Temporal(TemporalType.TIMESTAMP) @Column(name="forecast_date") private Date forecastDate; @Column(name="generator_power") private BigDecimal generatorPower; private byte softdeleteflag; @Column(name="solar_power") private BigDecimal solarPower; @Temporal(TemporalType.TIMESTAMP) @Column(name="sync_ts") private Date syncTs; @ManyToOne @JoinColumn(name="timeslot_id") private AllTimeslot timeslot; @Column(name="updated_by") private String updatedBy; @Temporal(TemporalType.TIMESTAMP) @Column(name="updated_ts") private Date updatedTs; @Column(name="user_load") private BigDecimal userLoad; //bi-directional many-to-one association to AllUser @ManyToOne @JoinColumn(name="user_id") private AllUser allUser; public AllForecast() { } public int getForecastId() { return this.forecastId; } public void setForecastId(int forecastId) { this.forecastId = forecastId; } public byte getActiveStatus() { return this.activeStatus; } public void setActiveStatus(byte activeStatus) { this.activeStatus = activeStatus; } public String getCreatedBy() { return this.createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Date getCreatedTs() { return this.createdTs; } public void setCreatedTs(Date createdTs) { this.createdTs = createdTs; } public BigDecimal getEvPower() { return this.evPower; } public void setEvPower(BigDecimal evPower) { this.evPower = evPower; } public Date getForecastDate() { return this.forecastDate; } public void setForecastDate(Date forecastDate) { this.forecastDate = forecastDate; } public BigDecimal getGeneratorPower() { return this.generatorPower; } public void setGeneratorPower(BigDecimal generatorPower) { this.generatorPower = generatorPower; } public byte getSoftdeleteflag() { return this.softdeleteflag; } public void setSoftdeleteflag(byte softdeleteflag) { this.softdeleteflag = softdeleteflag; } public BigDecimal getSolarPower() { return this.solarPower; } public void setSolarPower(BigDecimal solarPower) { this.solarPower = solarPower; } public Date getSyncTs() { return this.syncTs; } public void setSyncTs(Date syncTs) { this.syncTs = syncTs; } public AllTimeslot getTimeslotId() { return this.timeslot; } public void setTimeslotId(AllTimeslot timeslot) { this.timeslot = timeslot; } public String getUpdatedBy() { return this.updatedBy; } public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } public Date getUpdatedTs() { return this.updatedTs; } public void setUpdatedTs(Date updatedTs) { this.updatedTs = updatedTs; } public BigDecimal getUserLoad() { return this.userLoad; } public void setUserLoad(BigDecimal userLoad) { this.userLoad = userLoad; } public AllUser getAllUser() { return this.allUser; } public void setAllUser(AllUser allUser) { this.allUser = allUser; } }
package hangers; import edu.wpi.first.wpilibj.CANTalon; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.hal.PDPJNI; import utilities.Controllers; import utilities.RobotDashboard; public class HangerIO { private static HangerIO hangerIO; private Solenoid hangerSolenoid; private CANTalon hangerMotor; private int prevPOV; private boolean prevX, cylinderState; private String state = ""; private HangerIO(){ //initialize hanger outputs hangerSolenoid = new Solenoid(3); hangerMotor = new CANTalon(7); } public static HangerIO getInstance(){ //get singleton instance if(hangerIO == null) hangerIO = new HangerIO(); return hangerIO; } public void update(){ double speed = 1; if(getPOV() == 0 || getPOV() == 315 || getPOV() == 45){ //pull hanger up hangerMotor.set(-speed); state = "up"; } else if(getPOV() == 180 || getPOV() == 135 || getPOV() == 225){ //unspool hanger if(getDriverY()){ //only unspool if driver is holding Y hangerMotor.set(speed); state = "down"; } } else{ hangerMotor.set(0); state = "not moving"; } //when operator presses X and driver holds Y, put the hanger up/down if(getOpX() && !prevX){ if(getDriverY()){ //change cylinder state cylinderState = !cylinderState; hangerSolenoid.set(cylinderState); state = "change Solenoid"; } } prevPOV = getPOV(); prevX = getOpX(); RobotDashboard.putString("HangState", state); } private int getPOV(){ return Controllers.getOperatorJoystick().getPOV(0); } private boolean getOpX(){ return Controllers.getOperatorJoystick().getRawButton(3); } private boolean getDriverY(){ return Controllers.getDriverJoystick().getRawButton(4); } }
package com.capgemini.Resource_Management.service; import java.util.List; import com.capgemini.Resource_Management.model.UserRegistration; //@Service(name="UserService") public interface UserService { public void register(UserRegistration registration); public List<UserRegistration> getAllUser(); public UserRegistration getUser(String user_id); }
package com.example.user15.batteryapp; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; public class MainActivity extends Activity { private ImageView mBatteryView; private TextView mBatteryPercentageView; private TextView mBatteryTechnology; private TextView mBatteryStatus; private BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int maxCapacity = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0); int currCapacity = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0); String technology = intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY); int batteryPercentage = Math.round(currCapacity * 100.0f / maxCapacity); mBatteryView.getDrawable().setLevel(batteryPercentage * 100); mBatteryPercentageView.setText(getString(R.string.battery_percent_format, batteryPercentage)); mBatteryTechnology.setText(technology); mBatteryStatus.setText(getResources().getStringArray(R.array.battery_states)[getBatteryState(intent)]); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBatteryView = (ImageView) findViewById(R.id.iv_battery); mBatteryPercentageView = (TextView) findViewById(R.id.tv_battery_percentage); mBatteryTechnology = (TextView) findViewById(R.id.tv_battery_technology); mBatteryStatus = (TextView) findViewById(R.id.tv_battery_status); } @Override protected void onStart() { super.onStart(); IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); registerReceiver(mBatteryReceiver, filter); } @Override protected void onStop() { super.onStop(); unregisterReceiver(mBatteryReceiver); } @Override protected void onDestroy() { super.onDestroy(); } private boolean isBatteryPresent(Intent intent) { return intent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true); } private int getBatteryState(Intent intent) { int state = 0; if (isBatteryPresent(intent)) { state = intent.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN); } return state; } }
package com.legaoyi.protocol.messagebody.decoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Component; import com.legaoyi.protocol.exception.IllegalMessageException; import com.legaoyi.protocol.message.MessageBody; import com.legaoyi.protocol.message.decoder.MessageBodyDecoder; import com.legaoyi.protocol.up.messagebody.Tjsatl_2017_0200_MessageBody; import com.legaoyi.protocol.util.ByteUtils; import com.legaoyi.protocol.util.DateUtils; /** * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2015-01-30 */ @Component(MessageBodyDecoder.MESSAGE_BODY_DECODER_BEAN_PREFIX + "0200_tjsatl" + MessageBodyDecoder.MESSAGE_BODY_DECODER_BEAN_SUFFIX) public class Tjsatl_2017_0200_MessageBodyDecoder implements MessageBodyDecoder { @Override public MessageBody decode(byte[] messageBody) throws IllegalMessageException { Tjsatl_2017_0200_MessageBody message = new Tjsatl_2017_0200_MessageBody(); try { int offset = 0; byte[] arr = new byte[4]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.setAlarm(ByteUtils.dword2long(arr)); offset += arr.length; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.setState(ByteUtils.dword2long(arr)); offset += arr.length; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.setLat(String.valueOf(Double.valueOf(Double.valueOf(ByteUtils.dword2long(arr)).doubleValue() / 1000000.0D))); offset += arr.length; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.setLng(String.valueOf(Double.valueOf(Double.valueOf(ByteUtils.dword2long(arr)).doubleValue() / 1000000.0D))); offset += arr.length; arr = new byte[2]; System.arraycopy(messageBody, offset, arr, 0, arr.length); int altitude = ByteUtils.word2int(arr); if (altitude > 32767) { altitude -= 65536; } message.setAltitude(altitude); offset += arr.length; System.arraycopy(messageBody, offset, arr, 0, arr.length); double speed = ByteUtils.word2int(arr); if (speed > 0) { speed = speed / 10.0d; } message.setSpeed(speed); offset += arr.length; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.setDirection(ByteUtils.word2int(arr)); offset += arr.length; arr = new byte[6]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.setGpsTime(DateUtils.bcd2Timestamp(ByteUtils.bytes2bcd(arr))); offset += arr.length; while (offset < messageBody.length) { int param = ByteUtils.byte2int(messageBody[offset++]); int length = ByteUtils.byte2int(messageBody[offset++]); if (param == 0x01) { arr = new byte[4]; System.arraycopy(messageBody, offset, arr, 0, arr.length); double mileage = ByteUtils.dword2long(arr); if (mileage > 0) { mileage = mileage / 10.0d; } message.setMileage(mileage); offset += arr.length; } else if (param == 0x02) { arr = new byte[2]; System.arraycopy(messageBody, offset, arr, 0, arr.length); double oilmass = ByteUtils.word2int(arr); if (oilmass > 0) { oilmass = oilmass / 10.0d; } message.setOilmass(oilmass); offset += arr.length; } else if (param == 0x03) { arr = new byte[2]; System.arraycopy(messageBody, offset, arr, 0, arr.length); double dvrSpeed = ByteUtils.word2int(arr); if (dvrSpeed > 0) { dvrSpeed = dvrSpeed / 10.0d; } message.setDvrSpeed(dvrSpeed); offset += arr.length; } else if (param == 0x04) { arr = new byte[2]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.setAlarmEventId(ByteUtils.word2int(arr)); offset += arr.length; } else if (param == 0x11) { Map<String, Object> overSpeedAlarmExt = new HashMap<String, Object>(); arr = new byte[1]; System.arraycopy(messageBody, offset, arr, 0, arr.length); overSpeedAlarmExt.put("type", ByteUtils.byte2int(arr[0])); offset += arr.length; if (length > 1) { arr = new byte[4]; System.arraycopy(messageBody, offset, arr, 0, arr.length); overSpeedAlarmExt.put("id", ByteUtils.dword2long(arr)); offset += arr.length; } message.setOverSpeedAlarmExt(overSpeedAlarmExt); } else if (param == 0x12) { Map<String, Object> inOutAlarmExt = new HashMap<String, Object>(); arr = new byte[1]; System.arraycopy(messageBody, offset, arr, 0, arr.length); inOutAlarmExt.put("type", ByteUtils.byte2int(arr[0])); offset += arr.length; arr = new byte[4]; System.arraycopy(messageBody, offset, arr, 0, arr.length); inOutAlarmExt.put("id", ByteUtils.dword2long(arr)); offset += arr.length; arr = new byte[1]; System.arraycopy(messageBody, offset, arr, 0, arr.length); inOutAlarmExt.put("direction", ByteUtils.byte2int(arr[0])); message.setInOutAlarmExt(inOutAlarmExt); offset += arr.length; } else if (param == 0x13) { Map<String, Object> runningTimeAlarmExt = new HashMap<String, Object>(); arr = new byte[4]; System.arraycopy(messageBody, offset, arr, 0, arr.length); runningTimeAlarmExt.put("id", ByteUtils.dword2long(arr)); offset += arr.length; arr = new byte[2]; System.arraycopy(messageBody, offset, arr, 0, arr.length); runningTimeAlarmExt.put("runTime", ByteUtils.word2int(arr)); offset += arr.length; arr = new byte[1]; System.arraycopy(messageBody, offset, arr, 0, arr.length); runningTimeAlarmExt.put("result", ByteUtils.byte2int(arr[0])); message.setRunningTimeAlarmExt(runningTimeAlarmExt); offset += arr.length; } // *******tjsatl协议 start********// else if (param == 0x64) {// 高级驾驶辅助系统报警信息 arr = new byte[4]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addAdasAlarm("alarmId", ByteUtils.dword2long(arr)); offset += arr.length; message.addAdasAlarm("flag", ByteUtils.byte2int(messageBody[offset++])); int type = ByteUtils.byte2int(messageBody[offset++]); message.addAdasAlarm("type", type); message.addAdasAlarm("level", ByteUtils.byte2int(messageBody[offset++])); if (type < 0x03) { message.addAdasAlarm("frontSpeed", ByteUtils.byte2int(messageBody[offset++])); } else { offset++; } if (type < 0x03 || type == 0x04) { message.addAdasAlarm("frontDistance", ByteUtils.byte2int(messageBody[offset++])); } else { offset++; } if (type == 0x02) { message.addAdasAlarm("deviationType", ByteUtils.byte2int(messageBody[offset++])); } else { offset++; } if (type == 0x06 || type == 0x10) { message.addAdasAlarm("roadSignType", ByteUtils.byte2int(messageBody[offset++])); message.addAdasAlarm("roadSignData", ByteUtils.byte2int(messageBody[offset++])); } else { offset++; offset++; } message.addAdasAlarm("speed", ByteUtils.byte2int(messageBody[offset++])); arr = new byte[2]; System.arraycopy(messageBody, offset, arr, 0, arr.length); altitude = ByteUtils.word2int(arr); if (altitude > 32767) { altitude -= 65536; } message.addAdasAlarm("altitude", altitude); offset += arr.length; arr = new byte[4]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addAdasAlarm("lat", String.valueOf(Double.valueOf(Double.valueOf(ByteUtils.dword2long(arr)).doubleValue() / 1000000.0D))); offset += arr.length; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addAdasAlarm("lng", String.valueOf(Double.valueOf(Double.valueOf(ByteUtils.dword2long(arr)).doubleValue() / 1000000.0D))); offset += arr.length; arr = new byte[6]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addAdasAlarm("time", DateUtils.bcd2dateTime(ByteUtils.bytes2bcd(arr))); offset += arr.length; arr = new byte[2]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addAdasAlarm("state", ByteUtils.word2int(arr)); offset += arr.length; arr = new byte[7]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addAdasAlarm("terminalId", ByteUtils.bytes2ascii(arr)); offset += arr.length; arr = new byte[6]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addAdasAlarm("alarmTime", DateUtils.bcd2dateTime(ByteUtils.bytes2bcd(arr))); offset += arr.length; message.addAdasAlarm("alarmSeq", ByteUtils.byte2int(messageBody[offset++])); message.addAdasAlarm("totalFile", ByteUtils.byte2int(messageBody[offset++])); message.addAdasAlarm("alarmExt", ByteUtils.byte2int(messageBody[offset++])); } else if (param == 0x65) {// 驾驶员状态监测系统报警信息 arr = new byte[4]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addDsmAlarm("alarmId", ByteUtils.dword2long(arr)); offset += arr.length; message.addDsmAlarm("flag", ByteUtils.byte2int(messageBody[offset++])); int type = ByteUtils.byte2int(messageBody[offset++]); message.addDsmAlarm("type", type); message.addDsmAlarm("level", ByteUtils.byte2int(messageBody[offset++])); if (type == 0x01) { message.addDsmAlarm("fatigueDegree", ByteUtils.byte2int(messageBody[offset++])); } else { offset++; } System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addDsmAlarm("ext", ByteUtils.dword2long(arr)); offset += arr.length; message.addDsmAlarm("speed", ByteUtils.byte2int(messageBody[offset++])); arr = new byte[2]; System.arraycopy(messageBody, offset, arr, 0, arr.length); altitude = ByteUtils.word2int(arr); if (altitude > 32767) { altitude -= 65536; } message.addDsmAlarm("altitude", altitude); offset += arr.length; arr = new byte[4]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addDsmAlarm("lat", String.valueOf(Double.valueOf(Double.valueOf(ByteUtils.dword2long(arr)).doubleValue() / 1000000.0D))); offset += arr.length; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addDsmAlarm("lng", String.valueOf(Double.valueOf(Double.valueOf(ByteUtils.dword2long(arr)).doubleValue() / 1000000.0D))); offset += arr.length; arr = new byte[6]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addDsmAlarm("time", DateUtils.bcd2dateTime(ByteUtils.bytes2bcd(arr))); offset += arr.length; arr = new byte[2]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addDsmAlarm("state", ByteUtils.word2int(arr)); offset += arr.length; arr = new byte[7]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addDsmAlarm("terminalId", ByteUtils.bytes2ascii(arr)); offset += arr.length; arr = new byte[6]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addDsmAlarm("alarmTime", DateUtils.bcd2dateTime(ByteUtils.bytes2bcd(arr))); offset += arr.length; message.addDsmAlarm("alarmSeq", ByteUtils.byte2int(messageBody[offset++])); message.addDsmAlarm("totalFile", ByteUtils.byte2int(messageBody[offset++])); message.addDsmAlarm("alarmExt", ByteUtils.byte2int(messageBody[offset++])); } else if (param == 0x66) {// 胎压监测系统报警信息 arr = new byte[4]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addTpmAlarm("alarmId", ByteUtils.dword2long(arr)); offset += arr.length; message.addTpmAlarm("flag", ByteUtils.byte2int(messageBody[offset++])); message.addTpmAlarm("speed", ByteUtils.byte2int(messageBody[offset++])); arr = new byte[2]; System.arraycopy(messageBody, offset, arr, 0, arr.length); altitude = ByteUtils.word2int(arr); if (altitude > 32767) { altitude -= 65536; } message.addTpmAlarm("altitude", altitude); offset += arr.length; arr = new byte[4]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addTpmAlarm("lat", String.valueOf(Double.valueOf(Double.valueOf(ByteUtils.dword2long(arr)).doubleValue() / 1000000.0D))); offset += arr.length; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addTpmAlarm("lng", String.valueOf(Double.valueOf(Double.valueOf(ByteUtils.dword2long(arr)).doubleValue() / 1000000.0D))); offset += arr.length; arr = new byte[6]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addTpmAlarm("time", DateUtils.bcd2dateTime(ByteUtils.bytes2bcd(arr))); offset += arr.length; arr = new byte[2]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addTpmAlarm("state", ByteUtils.word2int(arr)); offset += arr.length; arr = new byte[7]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addTpmAlarm("terminalId", ByteUtils.bytes2ascii(arr)); offset += arr.length; arr = new byte[6]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addTpmAlarm("alarmTime", DateUtils.bcd2dateTime(ByteUtils.bytes2bcd(arr))); offset += arr.length; message.addTpmAlarm("alarmSeq", ByteUtils.byte2int(messageBody[offset++])); message.addTpmAlarm("totalFile", ByteUtils.byte2int(messageBody[offset++])); message.addTpmAlarm("alarmExt", ByteUtils.byte2int(messageBody[offset++])); int totalAlarm = ByteUtils.byte2int(messageBody[offset++]); List<Map<String, Object>> alarmList = new ArrayList<Map<String, Object>>(); Map<String, Object> map; for (int i = 0; i < totalAlarm; i++) { map = new HashMap<String, Object>(); map.put("seq", ByteUtils.byte2int(messageBody[offset++])); arr = new byte[2]; System.arraycopy(messageBody, offset, arr, 0, arr.length); map.put("type", ByteUtils.word2int(arr)); offset += arr.length; System.arraycopy(messageBody, offset, arr, 0, arr.length); map.put("pressure", ByteUtils.word2int(arr)); offset += arr.length; System.arraycopy(messageBody, offset, arr, 0, arr.length); map.put("temperature", ByteUtils.word2int(arr)); offset += arr.length; System.arraycopy(messageBody, offset, arr, 0, arr.length); map.put("electricity", ByteUtils.word2int(arr)); offset += arr.length; alarmList.add(map); } message.addTpmAlarm("alarmList", alarmList); } else if (param == 0x67) {// 盲区监测系统报警信息, arr = new byte[4]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addBsdAlarm("alarmId", ByteUtils.dword2long(arr)); offset += arr.length; message.addBsdAlarm("flag", ByteUtils.byte2int(messageBody[offset++])); message.addDsmAlarm("type", ByteUtils.byte2int(messageBody[offset++])); message.addBsdAlarm("speed", ByteUtils.byte2int(messageBody[offset++])); arr = new byte[2]; System.arraycopy(messageBody, offset, arr, 0, arr.length); altitude = ByteUtils.word2int(arr); if (altitude > 32767) { altitude -= 65536; } message.addBsdAlarm("altitude", altitude); offset += arr.length; arr = new byte[4]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addBsdAlarm("lat", String.valueOf(Double.valueOf(Double.valueOf(ByteUtils.dword2long(arr)).doubleValue() / 1000000.0D))); offset += arr.length; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addBsdAlarm("lng", String.valueOf(Double.valueOf(Double.valueOf(ByteUtils.dword2long(arr)).doubleValue() / 1000000.0D))); offset += arr.length; arr = new byte[6]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addBsdAlarm("time", DateUtils.bcd2dateTime(ByteUtils.bytes2bcd(arr))); offset += arr.length; arr = new byte[2]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addBsdAlarm("state", ByteUtils.word2int(arr)); offset += arr.length; arr = new byte[7]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addBsdAlarm("terminalId", ByteUtils.bytes2ascii(arr)); offset += arr.length; arr = new byte[6]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.addBsdAlarm("alarmTime", DateUtils.bcd2dateTime(ByteUtils.bytes2bcd(arr))); offset += arr.length; message.addBsdAlarm("alarmSeq", ByteUtils.byte2int(messageBody[offset++])); message.addBsdAlarm("totalFile", ByteUtils.byte2int(messageBody[offset++])); message.addBsdAlarm("alarmExt", ByteUtils.byte2int(messageBody[offset++])); } // *******tjsatl协议 end********// else if (param == 0x25) { arr = new byte[4]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.setExtSignal(ByteUtils.dword2long(arr)); offset += arr.length; } else if (param == 0x2A) { arr = new byte[2]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.setIo(ByteUtils.word2int(arr)); offset += arr.length; } else if (param == 0x2B) { arr = new byte[4]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.setAd(ByteUtils.dword2long(arr)); offset += arr.length; } else if (param == 0x30) { arr = new byte[1]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.setRssi(ByteUtils.byte2int(arr[0])); offset += arr.length; } else if (param == 0x31) { arr = new byte[1]; System.arraycopy(messageBody, offset, arr, 0, arr.length); message.setGnss(ByteUtils.byte2int(arr[0])); offset += arr.length; } else { offset += length; } } return message; } catch (Exception e) { throw new IllegalMessageException(e); } } }
package org.aksw.autosparql.client.controller; import org.aksw.autosparql.client.AppEvents; import org.aksw.autosparql.client.view.ApplicationView; import org.aksw.autosparql.client.view.LoadedQueryView; import com.extjs.gxt.ui.client.Registry; import com.extjs.gxt.ui.client.event.EventType; import com.extjs.gxt.ui.client.mvc.AppEvent; import com.extjs.gxt.ui.client.mvc.Controller; public class LoadedQueryController extends Controller { private LoadedQueryView view; public LoadedQueryController(){ registerEventTypes(AppEvents.NavLoadedQuery); } @Override protected void initialize() { view = new LoadedQueryView(this); } @Override public void handleEvent(AppEvent event) { EventType type = event.getType(); if (type == AppEvents.NavLoadedQuery) { ((ApplicationView)Registry.get("View")).updateHeader(); forwardToView(view, event); } } }
package com.gaoshin.cloud.web.vm.bean; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Pod { private Long id; private Long dataCenterId; private String name; private String gateway; private String description; private AllocationState allocationState; private Boolean externalDhcp; private Long removedDate; private String uuid; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getDataCenterId() { return dataCenterId; } public void setDataCenterId(Long dataCenterId) { this.dataCenterId = dataCenterId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGateway() { return gateway; } public void setGateway(String gateway) { this.gateway = gateway; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public AllocationState getAllocationState() { return allocationState; } public void setAllocationState(AllocationState allocationState) { this.allocationState = allocationState; } public Boolean getExternalDhcp() { return externalDhcp; } public void setExternalDhcp(Boolean externalDhcp) { this.externalDhcp = externalDhcp; } public Long getRemovedDate() { return removedDate; } public void setRemovedDate(Long removedDate) { this.removedDate = removedDate; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } }
package com.example.suigeneris; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; public class Spy { public static void PersonCount(){ SimpleDateFormat sdf = new SimpleDateFormat("EEEE"); Date d = new Date(); String dayOfTheWeek = sdf.format(d); //DocumentReference mDocRef = FirebaseFirestore.getInstance().document("Faculty/Cybernetic/Department/Program/Group/4Pr/"+dayOfTheWeek+"/"+LocalDate.now()); DocumentReference mDocRef = FirebaseFirestore.getInstance().document("Faculty/Cybernetic/Department/Program/Group/Cource4/4Pr/RomantsovVV/"+dayOfTheWeek+"/"+LocalDate.now()); LocalTime now = LocalTime.now(); LocalTime now1 = LocalTime.now(); DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("hh:mm:ss"); DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern("hh:mm"); Map<String, Object> user = new HashMap<>(); String time = LocalTime.now().toString(); user.put("In University "+now.format(dtf3), LocalTime.now().format(dtf2)); mDocRef.update(user); } }
package com.tch.test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolStopTest { public static void main(String[] args) throws InterruptedException { ExecutorService threadPool = Executors.newFixedThreadPool(1); threadPool.execute(new Runnable() { @Override public void run() { System.out.println("start"); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("finish"); } }); threadPool.shutdown(); } }
package com.liziyi.exam224; /** * @version 1.0 * @Description * @Author liziyi * @CreateDate 2021/1/17 10:32 * @UpdateUser * @UpdateDate * @UpdateRemark */ public class Solution5653 { public int countGoodRectangles(int[][] rectangles) { //正方形最长边 int longRec = 0; //当前正方形的边 int nowRec; //最大正方形的个数 int num = 1; for (int i = 0; i < rectangles.length; i++) { nowRec = Math.min(rectangles[i][0],rectangles[i][1]); if (longRec < nowRec) { longRec = nowRec; num = 1; } else if (longRec == nowRec){ num ++; } } return num; } public static void main(String[] args) { Solution5653 solution5653 = new Solution5653(); int[][] rectangles = new int[5][2]; rectangles[0][0]= 4; // rectangles[0]= {4,2} // rectangles[1] = [4][2]; // { // } [4][2]; [[2, 3],[3, 7],[4, 3],[3, 7]]; // solution5653.countGoodRectangles(); } }
package com.ryancobbproductions.vault; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.UnsupportedEncodingException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; public class SetupAccountActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setup_account); Button submitButton = (Button) findViewById(R.id.passphraseButton); submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Crypto.getInstance().createVault(((EditText) findViewById(R.id.editText)).getText().toString()); finish(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_setup_account, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package apiAlquilerVideoJuegos.basedatos; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import apiAlquilerVideoJuegos.modelos.Ciudad; @Repository public interface CiudadBD extends CrudRepository<Ciudad, Long>{ }
package com.gaoshin.coupon.dao; import com.gaoshin.coupon.bean.CategoryList; public interface CategoryDao extends GenericDao { CategoryList listTopCategories(); }
package com.intel.realsense.librealsense; import android.hardware.usb.UsbDeviceConnection; class UsbDesc { public UsbDesc(String n, int d, UsbDeviceConnection c) { name = n; descriptor = d; connection = c; } String name; int descriptor; UsbDeviceConnection connection; }
package br.com.douglastuiuiu.biometricengine.integration.creddefense.dto.request.entity.viewdata; import java.io.Serializable; /** * @author douglas * @since 20/03/2017 */ public class ViewDataRequestDTO implements Serializable { private static final long serialVersionUID = -6002594667423536871L; private ViewDataCreditDTO creditrequest; private ViewDataAuthenticationDTO authentication; public ViewDataRequestDTO() { } public ViewDataRequestDTO(ViewDataCreditDTO creditrequest, ViewDataAuthenticationDTO authentication) { super(); this.creditrequest = creditrequest; this.authentication = authentication; } public ViewDataCreditDTO getCreditrequest() { return creditrequest; } public void setCreditrequest(ViewDataCreditDTO creditrequest) { this.creditrequest = creditrequest; } public ViewDataAuthenticationDTO getAuthentication() { return authentication; } public void setAuthentication(ViewDataAuthenticationDTO authentication) { this.authentication = authentication; } }
package com.shilong.jysgl.pojo.vo; import java.util.Date; import java.util.List; import com.shilong.jysgl.pojo.po.Project; import com.shilong.jysgl.utils.MyUtil; public class ProjectCustom extends Project { private List<TeacherCustom> teachers; private String lxsjstr; private String jxsjstr; private String xmjbmc; private String xmlxmc; private String shztmc; private Date lxsj_start; private Date lxsj_end; private Date jxsj_start; private Date jxsj_end; private String grp_by; public List<TeacherCustom> getTeachers() { return teachers; } public void setTeachers(List<TeacherCustom> teachers) { this.teachers = teachers; } public String getLxsjstr() { return MyUtil.dateToString2(getLxsj()); } public void setLxsjstr(String lxsjstr) { this.lxsjstr = lxsjstr; } public String getJxsjstr() { return MyUtil.dateToString2(getJxsj()); } public void setJxsjstr(String jxsjstr) { this.jxsjstr = jxsjstr; } public String getXmjbmc() { return xmjbmc; } public void setXmjbmc(String xmjbmc) { this.xmjbmc = xmjbmc; } public String getXmlxmc() { return xmlxmc; } public void setXmlxmc(String xmlxmc) { this.xmlxmc = xmlxmc; } public String getShztmc() { return shztmc; } public void setShztmc(String shztmc) { this.shztmc = shztmc; } public Date getLxsj_start() { return lxsj_start; } public void setLxsj_start(Date lxsj_start) { this.lxsj_start = lxsj_start; } public Date getLxsj_end() { return lxsj_end; } public void setLxsj_end(Date lxsj_end) { this.lxsj_end = lxsj_end; } public Date getJxsj_start() { return jxsj_start; } public void setJxsj_start(Date jxsj_start) { this.jxsj_start = jxsj_start; } public Date getJxsj_end() { return jxsj_end; } public void setJxsj_end(Date jxsj_end) { this.jxsj_end = jxsj_end; } public String getGrp_by() { return grp_by; } public void setGrp_by(String grp_by) { this.grp_by = grp_by; } }
package com.krc.cloud.serevice; import com.krc.cloud.entity.Student; /** * @Author Rongcai Kang * @Time 2018/12/9 * @Description */ public interface StudentService { public Student findById(Integer id); }
package edu.nmsu.agents.MGM; import edu.nmsu.Home.Home; import edu.nmsu.Home.LocalSolver.CPSolver; import edu.nmsu.Home.LocalSolver.RuleSchedulerSolver; import edu.nmsu.Home.LocalSolver.RulesSchedule; import edu.nmsu.kernel.AgentActions; import edu.nmsu.kernel.AgentState; import edu.nmsu.problem.Pair; import edu.nmsu.problem.Parameters; import edu.nmsu.problem.Utilities; import java.io.OutputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * Created by nandofioretto on 11/6/16. */ public class MGMAgentActions extends AgentActions { CPSolver solver; Map<Pair<Long, Integer>, Double> receivedGains = new HashMap<>(); Map<Pair<Long, Integer>, Double[]> receivedEnergyProfiles = new HashMap<>(); // For each cycle private static class NullOutputStream extends OutputStream { @Override public void write(int b){ return; } @Override public void write(byte[] b){ return; } @Override public void write(byte[] b, int off, int len){ return; } public NullOutputStream(){ } }; private PrintStream nullStream = new PrintStream(new NullOutputStream()); private PrintStream outStream = System.out; Pair<Long, Integer> agtIdCycle_pair = new Pair(0,0); public MGMAgentActions(MGMAgentState agentState, long solver_timout, double w_price, double w_power) { super(agentState); Home home = agentState.getHome(); assert (home != null); solver = new RuleSchedulerSolver( home.getName(), home.getSchedulingRules(), agentState.getBackgroundLoads()); solver.setTimeoutMs(solver_timout); ((RuleSchedulerSolver)solver).setWeights((int)w_price, (int)w_power); } public void computeGain() { MGMAgentState state = (MGMAgentState)getAgentState(); state.setGain( Math.max(0, state.getBestSchedule().getCost() - state.getCurrSchedule().getCost()) ); } public boolean isBestGain(int curr_cycle) { MGMAgentState state = ((MGMAgentState)getAgentState()); agtIdCycle_pair.setSecond(curr_cycle); double gain = state.getGain(); for (AgentState n : state.getNeighbors()) { agtIdCycle_pair.setFirst(n.getID()); double neighborGain = receivedGains.get(agtIdCycle_pair); if ( gain < neighborGain) { return false; } else if (gain == neighborGain && state.getID() > n.getID()) { return false; } } return true; } public void updateBestSchedule(RulesSchedule schedule) { MGMAgentState mgmAgentState = ((MGMAgentState)getAgentState()); mgmAgentState.setBestSchedule(schedule); } public boolean computeSchedule(int cycleNo) { MGMAgentState mgmAgentState = ((MGMAgentState)getAgentState()); agtIdCycle_pair.setSecond(cycleNo); long T1, T2; T1 = System.currentTimeMillis(); // Sum neighbors loads double[] neighborLoads = new double[Parameters.getHorizon()]; Arrays.fill(neighborLoads, 0); for (AgentState n : mgmAgentState.getNeighbors()) { agtIdCycle_pair.setFirst(n.getID()); Double[] nLoads = receivedEnergyProfiles.get(agtIdCycle_pair); neighborLoads = Utilities.sum(neighborLoads, nLoads); } System.setOut(nullStream); System.setErr(nullStream); RulesSchedule rs = solver.getSchedule(neighborLoads); mgmAgentState.setCurrSchedule(rs); System.setOut(outStream); System.setErr(outStream); T2 = System.currentTimeMillis(); mgmAgentState.setSolvingTimeMs(T2 - T1); return (rs.getCost() != Double.MAX_VALUE); } public boolean computeFirstSchedule() { MGMAgentState mgmAgentState = ((MGMAgentState)getAgentState()); long T1, T2; T1 = System.currentTimeMillis(); System.setOut(nullStream); RulesSchedule rs = solver.getFirstSchedule(); mgmAgentState.setCurrSchedule(rs); System.setOut(outStream); T2 = System.currentTimeMillis(); mgmAgentState.setSolvingTimeMs(T2 - T1); return (rs.getCost() != Double.MAX_VALUE); } public boolean computeBaselineSchedule(int cycleNo) { MGMAgentState mgmAgentState = ((MGMAgentState)getAgentState()); agtIdCycle_pair.setSecond(cycleNo); long T1, T2; T1 = System.currentTimeMillis(); // Sum neighbors loads double[] neighborLoads = new double[Parameters.getHorizon()]; Arrays.fill(neighborLoads, 0); for (AgentState n : mgmAgentState.getNeighbors()) { agtIdCycle_pair.setFirst(n.getID()); Double[] nLoads = receivedEnergyProfiles.get(n.getID()); neighborLoads = Utilities.sum(neighborLoads, nLoads); } System.setOut(nullStream); RulesSchedule rs = solver.getBaselineSchedule(neighborLoads); mgmAgentState.setCurrSchedule(rs); System.setOut(outStream); T2 = System.currentTimeMillis(); mgmAgentState.setSolvingTimeMs(T2 - T1); return (rs.getCost() != Double.MAX_VALUE); } public void storeMessage(long id, MGMAgent.GainMessage msg) { Pair p = new Pair(id, msg.getCycle()); receivedGains.put(p, msg.getGain()); } public void storeMessage(long id, MGMAgent.EnergyProfileMessage msg) { Pair p = new Pair(id, msg.getCycle()); receivedEnergyProfiles.put(p, msg.getEnergyProfile()); } /** Check if the agent received gains from all neighbors at iteration \p iter */ public boolean receivedAllGains(int iter) { MGMAgentState mgmAgentState = ((MGMAgentState)getAgentState()); agtIdCycle_pair.setSecond(iter); for (AgentState n : mgmAgentState.getNeighbors()) { agtIdCycle_pair.setFirst(n.getID()); if (!receivedGains.containsKey(agtIdCycle_pair)) return false; } return true; } /** Check if the agent received energey profiles from all neighbors at iteration \p iter */ public boolean receivedAllEnergyProfiles(int iter) { MGMAgentState mgmAgentState = ((MGMAgentState)getAgentState()); agtIdCycle_pair.setSecond(iter); for (AgentState n : mgmAgentState.getNeighbors()) { agtIdCycle_pair.setFirst(n.getID()); if (!receivedEnergyProfiles.containsKey(agtIdCycle_pair)) return false; } return true; } }
package com.alibaba.druid.bvt.filter.wall; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.druid.wall.WallConfig; import com.alibaba.druid.wall.WallUtils; public class StrictSyntaxCheckTest extends TestCase { public void test_syntax() throws Exception { Assert.assertFalse(WallUtils.isValidateMySql(// "SELECT SELECT")); // 部分永真 } public void test_syntax_1() throws Exception { WallConfig config = new WallConfig(); config.setStrictSyntaxCheck(false); Assert.assertTrue(WallUtils.isValidateMySql(// "SELECT SELECT", config)); // 部分永真 } }
package com.algo; import org.junit.Test; import java.util.Map; import java.util.TreeMap; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class KComplementaryTest { private final Solution solution = new Solution(); @Test public void name() throws Exception { assertResult(6, new int[]{1, 8, -3, 0, 1, 3, -2, 4, 5}, 7); assertResult(10, new int[]{1, 5, 9}, 3); } class Solution { public int solution(int K, int[] A) { // int count = 0; // for (int i = 0; i < A.length; i++) { // for (int j = i; j < A.length; j++) { // if (A[i] + A[j] == K) { // if (i != j) count += 2; // else count++; // } // } // } // return count; // obviously this solution is O(nˆ2) // to be O(n*log(n) it needs some "sort of sorting" :) // what I was trying to do, but didn't finished // get all the values in a unique way, already sorted // with their occurrencies, the occurrencies are needed // to calculate the combination of couples // to do that I would loop the structure just getting // the values by being value = A[i] - K // the solution is the following. Map<Integer, Integer> occurencies = new TreeMap<>(); for (int i = 0; i < A.length; i++) { if (occurencies.get(A[i]) == null) { occurencies.put(A[i], 1); } else { Integer value = occurencies.get(A[i]); occurencies.put(A[i], value + 1); } } int counter = 0; for (Integer current : occurencies.keySet()) { int valueNeeded = K - current; if (occurencies.get(valueNeeded) != null) { counter += occurencies.get(current) * occurencies.get(valueNeeded); } } return counter; } } private void assertResult(int K, int[] A, int expected) { assertThat(solution.solution(K, A), is(expected)); } }
package nl.hva.ict.ds; import org.junit.Before; import org.junit.Test; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * This class contains some unit tests. They by no means ensure that all the requirements are implemented * correctly. */ public class HighScoreListTest { private static final int MAX_HIGH_SCORE = 100000; private Random randomizer = new SecureRandom(); private HighScoreList highScores; private Player nearlyHeadlessNick; private Player dumbledore; @Before public void setup() { // Here you should select your implementation to be tested. // highScores = new DummyHighScores(); // highScores = new InsertionSortHighScores(); // highScores = new BucketSortHighScores(); highScores = new PriorityQueueHighScores(); nearlyHeadlessNick = new Player("Nicholas", "de Mimsy-Porpington", getHighScore() % 200); dumbledore = new Player("Albus", "Dumbledore", nearlyHeadlessNick.getHighScore() * 1000); } @Test public void noPlayerNoHighScore() { assertTrue("There are high-score while there should be no high-scores!", highScores.getHighScores(1).isEmpty()); } @Test public void whenNoHighScoreIsAskedForNonShouldBeGiven() { highScores.add(dumbledore); assertEquals(0, highScores.getHighScores(0).size()); } @Test public void noMoreHighScoresCanBeGivenThenPresent() { highScores.add(nearlyHeadlessNick); highScores.add(dumbledore); assertEquals(2, highScores.getHighScores(10).size()); } @Test public void keepAllHighScores() { highScores.add(nearlyHeadlessNick); highScores.add(dumbledore); assertEquals(2, highScores.getHighScores(2).size()); } @Test public void singlePlayerHasHighScore() { highScores.add(dumbledore); assertEquals(dumbledore, highScores.getHighScores(1).get(0)); } @Test public void harryBeatsDumbledore() { highScores.add(dumbledore); Player harry = new Player("Harry", "Potter", dumbledore.getHighScore() + 1); highScores.add(harry); assertEquals(harry, highScores.getHighScores(1).get(0)); } // Extra unit tests go here @Test public void makeSortedListOfTenPersons() { Player eerste = new Player("Eerste", "Plaats", 10); Player tweede = new Player("tweede", "Plaats", 9); Player derde = new Player("derde", "Plaats", 8); Player vierde = new Player("vierde", "Plaats", 7); Player vijfde = new Player("vijfde", "Plaats", 6); Player zesde = new Player("zesde", "Plaats", 5); Player zevende = new Player("zevende", "Plaats", 4); Player achtste = new Player("achtste", "Plaats", 3); Player negende = new Player("negende", "Plaats", 2); Player tiende = new Player("tiende", "Plaats", 1); highScores.add(zesde); highScores.add(achtste); highScores.add(tweede); highScores.add(zevende); highScores.add(vierde); highScores.add(derde); highScores.add(tiende); highScores.add(eerste); highScores.add(vijfde); highScores.add(negende); List<Long> expected = Arrays.asList( eerste.getHighScore(), tweede.getHighScore(), derde.getHighScore(), vierde.getHighScore(), vijfde.getHighScore(), zesde.getHighScore(), zevende.getHighScore(), achtste.getHighScore(), negende.getHighScore(), tiende.getHighScore()); List<Player> temp = highScores.getHighScores(10); List<Long> result = new ArrayList<>(); for (int i = 0; i < temp.size(); i++) { result.add(temp.get(i).getHighScore()); } assertEquals(expected, result); } private long getHighScore() { return randomizer.nextInt(MAX_HIGH_SCORE); } }
package com.sky.design.strategy.base; //抽象方法类 定义所有算法支持的公共接口 public abstract class Strategy { //算法方法 public abstract void AlgorithmInterface(); }
package com.wenyuankeji.spring.service; import java.util.List; import com.wenyuankeji.spring.model.BaseBusinessareaModel; import com.wenyuankeji.spring.model.BaseCityModel; import com.wenyuankeji.spring.model.BaseConfigModel; import com.wenyuankeji.spring.model.BaseProvinceModel; import com.wenyuankeji.spring.util.BaseException; public interface IBaseConfigService { /** * 查找省份 * @return * @throws BaseException */ public List<BaseProvinceModel> searchBaseProvince()throws BaseException; /** * 根据省份id查找城市信息 * @param provinceId 省份ID * @return * @throws BaseException */ public List<BaseCityModel> searchBaseCityByProvinceId(int provinceId)throws BaseException; /** * 查询所有的商圈 * @return * @throws BaseException */ public List<BaseBusinessareaModel> searchBaseBusinessarea() throws BaseException; /** * 添加商圈 * @return * @throws BaseException */ public boolean addBaseBusinessarea(BaseBusinessareaModel o) throws BaseException; /** * 设置配置表 * @return * @throws BaseException */ public boolean addBaseConfig(BaseConfigModel o) throws BaseException; /** * 查询基础设置表 * @param configcode 配置编码 * @return * @throws BaseException */ public List<BaseConfigModel> searchBaseConfigList(String configcode)throws BaseException; /** * 查询首页图片 * @param configcode 配置编码 * @param cofigvalue 值 * @return */ public BaseConfigModel searchBaseConfigByCode(String configcode, String configvalue)throws BaseException; /** * 修改首页图片 * @param configcode 配置编码 * @param cofigvalue 值 * @param value1 picid值 * @return */ public boolean updateBaseConfig(String configcode, String configvalue, String value1)throws BaseException; public List<BaseConfigModel> searchBaseConfig(String configcode)throws BaseException; /** * 查询基础设置表 * @param configcode 配置编码 * @return * @throws BaseException */ public BaseConfigModel searchBaseConfigByCode(String configcode)throws BaseException; /** * 根据编码更新配置信息 * @param configcode * @param configvalue * @return * @throws BaseException */ public boolean updateBaseConfigByConfigCode(String configcode, String configvalue)throws BaseException; }
package com.example.widgettest4; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; public class MainActivity extends AppCompatActivity { final static String TAG = "MainActivity"; EditText mInputEditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mInputEditText = findViewById(R.id.inputEditText); } public void onButtonClick(View view) { String inputString = mInputEditText.getText().toString(); if (!inputString.isEmpty()) Log.i(TAG, inputString); } }
package com.mingrisoft; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.LayoutManager; public class CircleLayout implements LayoutManager { @Override public void addLayoutComponent(String name, Component comp) { } @Override public void layoutContainer(Container parent) { double centerX = parent.getBounds().getCenterX(); double centerY = parent.getBounds().getCenterY(); Insets insets = parent.getInsets(); double horizon = centerX - insets.left; double vertical = centerY - insets.top; double radius = horizon > vertical ? vertical : horizon; int count = parent.getComponentCount(); for (int i = 0; i < count; i++) { Component component = parent.getComponent(i); if (component.isVisible()) { Dimension size = component.getPreferredSize(); double angle = 2 * Math.PI * i / count; double x = centerX + radius * Math.sin(angle); double y = centerY - radius * Math.cos(angle); component.setBounds((int) x - size.width / 2, (int) y - size.height / 2, size.width, size.height); } } } @Override public Dimension minimumLayoutSize(Container parent) { return parent.getMinimumSize(); } @Override public Dimension preferredLayoutSize(Container parent) { return parent.getPreferredSize(); } @Override public void removeLayoutComponent(Component comp) { } }
package com.techboon.repository; import com.techboon.domain.CaseItem; import com.techboon.domain.PersistentAuditEvent; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; import org.springframework.data.jpa.repository.*; import java.time.Instant; import java.time.LocalDate; /** * Spring Data JPA repository for the CaseItem entity. */ @SuppressWarnings("unused") @Repository public interface CaseItemRepository extends JpaRepository<CaseItem, Long>,JpaSpecificationExecutor<CaseItem> { CaseItem findDistinctBySampleFlowNumberEquals(String sampleFlowNumber); Page<CaseItem> findAllBySampleDateBetween(LocalDate fromDate, LocalDate toDate, Pageable pageable); }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public * * License as published by the Free Software Foundation; either * * version 3 of the License, or any later version. * * * * Data Crow 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 General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this program. If not, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.console.windows.enhancers; import java.awt.GridBagConstraints; import java.awt.Insets; import java.util.ArrayList; import java.util.Collection; import javax.swing.DefaultCellEditor; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JViewport; import javax.swing.table.TableColumn; import net.datacrow.console.ComponentFactory; import net.datacrow.console.Layout; import net.datacrow.console.components.renderers.CheckBoxTableCellRenderer; import net.datacrow.console.components.tables.DcTable; import net.datacrow.core.DcRepository; import net.datacrow.core.modules.DcModule; import net.datacrow.core.modules.DcModules; import net.datacrow.core.objects.DcField; import net.datacrow.core.objects.DcMediaObject; import net.datacrow.core.resources.DcResources; import net.datacrow.enhancers.AutoIncrementer; import net.datacrow.enhancers.ValueEnhancers; import net.datacrow.settings.DcSettings; import net.datacrow.settings.definitions.DcFieldDefinition; public class AutoIncrementSettingsPanel extends JPanel { private DcModule module; private final DcTable table; public AutoIncrementSettingsPanel() { super(); table = ComponentFactory.getDCTable(false, false); setModule(DcSettings.getInt(DcRepository.Settings.stModule)); buildComponent(); } public void save() { Collection<AutoIncrementer> enhancers = getEnhancers(); module.removeEnhancers(); for (AutoIncrementer incrementer : enhancers) { if (incrementer.isEnabled()) { for (DcFieldDefinition definition : module.getFieldDefinitions().getDefinitions()) { if (definition.getIndex() == incrementer.getField()) definition.isEnabled(true); } } if (module.hasSearchView()) module.getSearchView().applySettings(); if (module.hasInsertView()) module.getInsertView().applySettings(); ValueEnhancers.registerEnhancer(module.getField(incrementer.getField()), incrementer); } ValueEnhancers.save(); } public void setModule(int index) { module = DcModules.get(index); } public void setEnhancers(Collection<AutoIncrementer> enhancers) { table.clear(); if (enhancers.size() == 0) { enhancers.add(new AutoIncrementer(DcMediaObject._U4_USER_NUMERIC1)); enhancers.add(new AutoIncrementer(DcMediaObject._U5_USER_NUMERIC2)); } int field; Object[] row; for (AutoIncrementer incrementer : enhancers) { field = incrementer.getField(); row = new Object[] { module.getField(field), incrementer.isEnabled(), incrementer.isFillGaps(), incrementer.getStep()}; table.addRow(row); } table.applyHeaders(); } public Collection<AutoIncrementer> getEnhancers() { Collection<AutoIncrementer> enhancers = new ArrayList<AutoIncrementer>(); DcField field; boolean enabled; boolean fillGaps; int step; for (int i = 0; i < table.getRowCount(); i++) { field = (DcField) table.getValueAt(i, 0, true); if (field != null) { enabled = ((Boolean) table.getValueAt(i, 1, true)).booleanValue(); fillGaps = ((Boolean) table.getValueAt(i, 2, true)).booleanValue(); step = ((Integer) table.getValueAt(i, 3, true)).intValue(); enhancers.add(new AutoIncrementer(field.getIndex(), enabled, fillGaps, step)); } } return enhancers; } @SuppressWarnings("unchecked") private void buildComponent() { setLayout(Layout.getGBL()); JPanel panel = new JPanel(); panel.setLayout(Layout.getGBL()); table.setColumnCount(4); TableColumn cField = table.getColumnModel().getColumn(0); JTextField textField = new JTextField(); textField.setEditable(false); textField.setEnabled(false); textField.setFont(ComponentFactory.getSystemFont()); textField.setForeground(ComponentFactory.getDisabledColor()); cField.setCellEditor(new DefaultCellEditor(textField)); TableColumn columnEnabled = table.getColumnModel().getColumn(1); columnEnabled.setCellEditor(new DefaultCellEditor(new JCheckBox())); columnEnabled.setCellRenderer(CheckBoxTableCellRenderer.getInstance()); TableColumn cFillGaps = table.getColumnModel().getColumn(2); cFillGaps.setCellEditor(new DefaultCellEditor(new JCheckBox())); cFillGaps.setCellRenderer(CheckBoxTableCellRenderer.getInstance()); TableColumn cStep = table.getColumnModel().getColumn(3); JComboBox comboWeight = ComponentFactory.getComboBox(); for (int i = 1; i < 101; i++) comboWeight.addItem(i); cStep.setCellEditor(new DefaultCellEditor(comboWeight)); cField.setHeaderValue(DcResources.getText("lblField")); columnEnabled.setHeaderValue(DcResources.getText("lblEnabled")); cFillGaps.setHeaderValue(DcResources.getText("lblFillGaps")); cStep.setHeaderValue(DcResources.getText("lblStep")); Collection<AutoIncrementer> enhancers = (Collection<AutoIncrementer>) ValueEnhancers.getEnhancers(module.getIndex(), ValueEnhancers._AUTOINCREMENT); setEnhancers(enhancers); JScrollPane scroller = new JScrollPane(table); scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scroller.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE); add(scroller, Layout.getGBC( 0, 0, 1, 4, 50.0, 50.0 ,GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets( 5, 5, 5, 5), 0, 0)); } }
/* * Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.engine; import java.util.Collection; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import pl.edu.icm.unity.db.generic.realm.RealmDB; import pl.edu.icm.unity.engine.authz.AuthorizationManager; import pl.edu.icm.unity.engine.authz.AuthzCapability; import pl.edu.icm.unity.engine.events.InvocationEventProducer; import pl.edu.icm.unity.engine.transactions.SqlSessionTL; import pl.edu.icm.unity.engine.transactions.Transactional; import pl.edu.icm.unity.exceptions.EngineException; import pl.edu.icm.unity.server.api.RealmsManagement; import pl.edu.icm.unity.types.authn.AuthenticationRealm; /** * Implementation of {@link RealmsManagement}. * @author K. Benedyczak */ @Component @InvocationEventProducer @Transactional public class RealmsManagementImpl implements RealmsManagement { private RealmDB realmDB; private AuthorizationManager authz; @Autowired public RealmsManagementImpl(RealmDB realmDB, AuthorizationManager authz) { super(); this.realmDB = realmDB; this.authz = authz; } @Override public void addRealm(AuthenticationRealm realm) throws EngineException { authz.checkAuthorization(AuthzCapability.maintenance); SqlSession sql = SqlSessionTL.get(); try { realmDB.insert(realm.getName(), realm, sql); } catch (Exception e) { throw new EngineException("Unable to create a realm: " + e.getMessage(), e); } } @Override public AuthenticationRealm getRealm(String name) throws EngineException { authz.checkAuthorization(AuthzCapability.maintenance); SqlSession sql = SqlSessionTL.get(); try { return realmDB.get(name, sql); } catch (Exception e) { throw new EngineException("Unable to retrieve a realm: " + e.getMessage(), e); } } @Override public Collection<AuthenticationRealm> getRealms() throws EngineException { authz.checkAuthorization(AuthzCapability.maintenance); SqlSession sql = SqlSessionTL.get(); try { return realmDB.getAll(sql); } catch (Exception e) { throw new EngineException("Unable to retrieve realms: " + e.getMessage(), e); } } @Override public void updateRealm(AuthenticationRealm realm) throws EngineException { authz.checkAuthorization(AuthzCapability.maintenance); SqlSession sql = SqlSessionTL.get(); try { realmDB.update(realm.getName(), realm, sql); } catch (Exception e) { throw new EngineException("Unable to update a realm: " + e.getMessage(), e); } } @Override public void removeRealm(String name) throws EngineException { authz.checkAuthorization(AuthzCapability.maintenance); SqlSession sql = SqlSessionTL.get(); try { realmDB.remove(name, sql); } catch (Exception e) { throw new EngineException("Unable to remove a realm: " + e.getMessage(), e); } } }
package cn.novelweb.tool.upload.fastdfs.protocol.storage.response; import cn.novelweb.tool.upload.fastdfs.model.MateData; import cn.novelweb.tool.upload.fastdfs.protocol.BaseResponse; import cn.novelweb.tool.upload.fastdfs.utils.MetadataMapperUtils; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.Set; /** * <p></p> * <p>2020-02-03 17:01</p> * * @author Dai Yuanchuan **/ public class GetMetadataResponse extends BaseResponse<Set<MateData>> { /** * 解析反馈内容 */ @Override public Set<MateData> decodeContent(InputStream in, Charset charset) throws IOException { // 解析报文内容 byte[] bytes = new byte[(int) getContentLength()]; int contentSize = in.read(bytes); if (contentSize != getContentLength()) { throw new IOException("读取到的数据长度与协议长度不符"); } return MetadataMapperUtils.fromByte(bytes, charset); } }
package exam.iz0_803; public class Exam_066 { } /* The catch clause argument is always of type __________. A. Exception B. Exception but NOT including RuntimeException C. Throwable D. RuntimeException E. CheckedException F. Error Answer: C */
package kr.co.flyingturtle.repository.vo; import java.util.Date; public class VideoCom { private int comNo; private int videoNo; private int memberNo; private Date regDate; private String comContent; private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } public int getComNo() { return comNo; } public void setComNo(int comNo) { this.comNo = comNo; } public int getVideoNo() { return videoNo; } public void setVideoNo(int videoNo) { this.videoNo = videoNo; } public int getMemberNo() { return memberNo; } public void setMemberNo(int memberNo) { this.memberNo = memberNo; } public Date getRegDate() { return regDate; } public void setRegDate(Date regDate) { this.regDate = regDate; } public String getComContent() { return comContent; } public void setComContent(String comContent) { this.comContent = comContent; } }
/** Start of LinkedList Cycle (medium) 计算入环节点 */ class ListNode { int value = 0; ListNode next; ListNode(int value) { this.value = value; } } public class LinkedListCycleStart { public static ListNode findCycleStart(ListNode head) { ListNode nodeInCycle = findOneNodeInCycle(head); int length = findCycleLength(nodeInCycle); return findCycleStart(head, length); } /** * 从链表的环中获取一一个节点。 * @param * head 列表头结点 * @return * Node or null if hasn't cycle */ private static ListNode findOneNodeInCycle(ListNode head){ ListNode slow = head; ListNode fast = head; while(fast!=null && fast.next!=null){ fast = fast.next.next; slow = slow.next; if(fast == slow){ return fast; } } return null; } /** * 获取有环链表 环的长度 */ private static int findCycleLength(ListNode node){ int length = 0; ListNode current = node; do{ length++; current = current.next; }while(current != node); return length; } private static ListNode findCycleStart(ListNode head, int cycleLength){ ListNode fastPoint = head; ListNode slowPoint = head; while(cycleLength > 0){ fastPoint = fastPoint.next; cycleLength--; } while(fastPoint != slowPoint){ fastPoint = fastPoint.next; slowPoint = slowPoint.next; } return fastPoint; } public static void main(String[] args) { ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); head.next.next.next = new ListNode(4); head.next.next.next.next = new ListNode(5); head.next.next.next.next.next = new ListNode(6); head.next.next.next.next.next.next = head.next.next; System.out.println("LinkedList cycle start: " + LinkedListCycleStart.findCycleStart(head).value); head.next.next.next.next.next.next = head.next.next.next; System.out.println("LinkedList cycle start: " + LinkedListCycleStart.findCycleStart(head).value); head.next.next.next.next.next.next = head; System.out.println("LinkedList cycle start: " + LinkedListCycleStart.findCycleStart(head).value); } }
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.sdk.metrics.data; /** An {@link ExemplarData} with {@code long} measurements. */ public interface LongExemplarData extends ExemplarData { /** Numerical value of the measurement that was recorded. */ long getValue(); }
package com.amundi.tech.onsite.db; import com.amundi.tech.onsite.db.model.RestaurantDefinition; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface RestaurantDefinitionRepository extends JpaRepository<RestaurantDefinition, Long> { List<RestaurantDefinition> findAllByName(String name); }
package br.com.mixfiscal.prodspedxnfe.domain.nfe; import java.io.Serializable; import java.util.Objects; public abstract class ICMS implements Serializable{ private static final long serialVersionUID = -7327132501215844194L; private int CST; private String origem; public int getCST() { return CST; } public void setCST(int cst) { this.CST = cst; } public String getOrigem() { return origem; } public void setOrigem(String origem) { this.origem = origem; } @Override public int hashCode() { int hash = 7; hash = 83 * hash + this.CST; hash = 83 * hash + Objects.hashCode(this.origem); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ICMS other = (ICMS) obj; if (this.CST != other.CST) { return false; } if (!Objects.equals(this.origem, other.origem)) { return false; } return true; } }
package com.designpattern.dp11decoratorpattern.Demo; /** * 装饰器类的抽象类 * 继承于被装饰类的抽象类 * 是可有可无的,具体可以根据业务模型来选择。 */ public abstract class BattercakeDecorator extends Battercake{ // 静态代理 委派 private Battercake battercake; // 持有一个被装饰类的引用 public BattercakeDecorator(Battercake battercake){ this.battercake = battercake; } // 装饰器类扩展被装饰类的方法 protected abstract void doSomething(); @Override protected String getMsg() { return this.battercake.getMsg(); } @Override protected int getPrice() { return this.battercake.getPrice(); } }
/** * com.swordfish.net.SpiderFactory.java@com.tax.splider */ package com.rednovo.tools.web; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; /** * * @author Yongchao.Yang@2013年10月29日 * */ public class SpiderFactory { private static PoolingHttpClientConnectionManager pool; private static CloseableHttpClient splider; static { pool = new PoolingHttpClientConnectionManager(); pool.setDefaultMaxPerRoute(20); pool.setMaxTotal(2000); splider = HttpClients.custom().setConnectionManager(pool).build(); } public static CloseableHttpClient getSplider() { return splider; } }
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.transaction.reactive; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.springframework.lang.Nullable; /** * Mutable transaction context that encapsulates transactional synchronizations and * resources in the scope of a single transaction. Transaction context is typically * held by an outer {@link TransactionContextHolder} or referenced directly within * from the subscriber context. * * @author Mark Paluch * @author Juergen Hoeller * @since 5.2 * @see TransactionContextManager * @see reactor.util.context.Context */ public class TransactionContext { private final @Nullable TransactionContext parent; private final Map<Object, Object> resources = new LinkedHashMap<>(); @Nullable private Set<TransactionSynchronization> synchronizations; private volatile @Nullable String currentTransactionName; private volatile boolean currentTransactionReadOnly; private volatile @Nullable Integer currentTransactionIsolationLevel; private volatile boolean actualTransactionActive; TransactionContext() { this(null); } TransactionContext(@Nullable TransactionContext parent) { this.parent = parent; } @Nullable public TransactionContext getParent() { return this.parent; } public Map<Object, Object> getResources() { return this.resources; } public void setSynchronizations(@Nullable Set<TransactionSynchronization> synchronizations) { this.synchronizations = synchronizations; } @Nullable public Set<TransactionSynchronization> getSynchronizations() { return this.synchronizations; } public void setCurrentTransactionName(@Nullable String currentTransactionName) { this.currentTransactionName = currentTransactionName; } @Nullable public String getCurrentTransactionName() { return this.currentTransactionName; } public void setCurrentTransactionReadOnly(boolean currentTransactionReadOnly) { this.currentTransactionReadOnly = currentTransactionReadOnly; } public boolean isCurrentTransactionReadOnly() { return this.currentTransactionReadOnly; } public void setCurrentTransactionIsolationLevel(@Nullable Integer currentTransactionIsolationLevel) { this.currentTransactionIsolationLevel = currentTransactionIsolationLevel; } @Nullable public Integer getCurrentTransactionIsolationLevel() { return this.currentTransactionIsolationLevel; } public void setActualTransactionActive(boolean actualTransactionActive) { this.actualTransactionActive = actualTransactionActive; } public boolean isActualTransactionActive() { return this.actualTransactionActive; } public void clear() { this.synchronizations = null; this.currentTransactionName = null; this.currentTransactionReadOnly = false; this.currentTransactionIsolationLevel = null; this.actualTransactionActive = false; } }
package com.metoo.manage.admin.action; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Field; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.metoo.core.annotation.SecurityMapping; import com.metoo.core.beans.BeanUtils; import com.metoo.core.beans.BeanWrapper; import com.metoo.core.domain.virtual.SysMap; import com.metoo.core.mv.JModelAndView; import com.metoo.core.qrcode.QRCodeUtil; import com.metoo.core.query.support.IPageList; import com.metoo.core.tools.CommUtil; import com.metoo.core.tools.WebForm; import com.metoo.core.tools.database.DatabaseTools; import com.metoo.foundation.domain.GoodsSku; import com.metoo.foundation.domain.Evaluate; import com.metoo.foundation.domain.Goods; import com.metoo.foundation.domain.GoodsBrand; import com.metoo.foundation.domain.GoodsClass; import com.metoo.foundation.domain.Message; import com.metoo.foundation.domain.SysConfig; import com.metoo.foundation.domain.Template; import com.metoo.foundation.domain.User; import com.metoo.foundation.domain.ZTCGoldLog; import com.metoo.foundation.domain.query.GoodsQueryObject; import com.metoo.foundation.service.IAccessoryService; import com.metoo.foundation.service.IAlbumService; import com.metoo.foundation.service.IEvaluateService; import com.metoo.foundation.service.IGoodsBrandService; import com.metoo.foundation.service.IGoodsCartService; import com.metoo.foundation.service.IGoodsClassService; import com.metoo.foundation.service.IGoodsService; import com.metoo.foundation.service.IGoodsSkuService; import com.metoo.foundation.service.IGoodsSpecPropertyService; import com.metoo.foundation.service.IGoodsTypePropertyService; import com.metoo.foundation.service.IMessageService; import com.metoo.foundation.service.IOrderFormLogService; import com.metoo.foundation.service.IOrderFormService; import com.metoo.foundation.service.IPaymentService; import com.metoo.foundation.service.ISysConfigService; import com.metoo.foundation.service.ITemplateService; import com.metoo.foundation.service.ITransportService; import com.metoo.foundation.service.IUserConfigService; import com.metoo.foundation.service.IUserGoodsClassService; import com.metoo.foundation.service.IUserService; import com.metoo.foundation.service.IWaterMarkService; import com.metoo.foundation.service.IZTCGoldLogService; import com.metoo.lucene.LuceneUtil; import com.metoo.lucene.LuceneVo; import com.metoo.lucene.tools.LuceneVoTools; import com.metoo.manage.admin.tools.StoreTools; import com.metoo.manage.seller.tools.TransportTools; import com.metoo.msg.MsgTools; import com.metoo.msg.email.SpelTemplate; import com.metoo.view.web.tools.GoodsViewTools; import com.metoo.view.web.tools.StoreViewTools; /** * * <p> * Title: GoodsManageAction.java * </p> * * <p> * Description: 商品管理类 * </p> * * <p> * Copyright: Copyright (c) 2015 * </p> * * <p> * Company: 湖南觅通科技有限公司 www.metoo.com * </p> * * @author erikzhang * * @date 2014年5月27日 * * @version metoo_b2b2c 2.0 */ @Controller public class GoodsManageAction { @Autowired private ISysConfigService configService; @Autowired private IUserConfigService userConfigService; @Autowired private IGoodsService goodsService; @Autowired private IGoodsBrandService goodsBrandService; @Autowired private IGoodsClassService goodsClassService; @Autowired private ITemplateService templateService; @Autowired private IUserService userService; @Autowired private IMessageService messageService; @Autowired private MsgTools msgTools; @Autowired private DatabaseTools databaseTools; @Autowired private IEvaluateService evaluateService; @Autowired private IGoodsCartService goodsCartService; @Autowired private IOrderFormService orderFormService; @Autowired private IOrderFormLogService orderFormLogService; @Autowired private IAccessoryService accessoryService; @Autowired private IUserGoodsClassService userGoodsClassService; @Autowired private IGoodsSpecPropertyService specPropertyService; @Autowired private IGoodsTypePropertyService goodsTypePropertyService; @Autowired private IWaterMarkService waterMarkService; @Autowired private IAlbumService albumService; @Autowired private ITransportService transportService; @Autowired private IPaymentService paymentService; @Autowired private TransportTools transportTools; @Autowired private StoreTools storeTools; @Autowired private StoreViewTools storeViewTools; @Autowired private GoodsViewTools goodsViewTools; @Autowired private IZTCGoldLogService ztcglService; @Autowired private LuceneVoTools luceneVoTools; @Autowired private IGoodsSkuService goodsSkuService; /** * Goods列表页 * * @param currentPage * @param orderBy * @param orderType * @param request * @return */ @SecurityMapping(title = "商品列表", value = "/admin/goods_list.htm*", rtype = "admin", rname = "商品管理", rcode = "admin_goods", rgroup = "商品") @RequestMapping("/admin/goods_list.htm") public ModelAndView goods_list(HttpServletRequest request, HttpServletResponse response, String currentPage, String orderBy, String orderType, String store_name, String brand_id, String gc_id, String goods_type, String goods_name, String store_recommend, String status,String goods_global, String goods_serial) { ModelAndView mv = new JModelAndView("admin/blue/goods_list.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); if(CommUtil.null2String(goods_serial).equals("")){ GoodsQueryObject qo = new GoodsQueryObject(currentPage, mv, orderBy, orderType); qo.setOrderBy("addTime"); qo.setOrderType("desc"); WebForm wf = new WebForm(); wf.toQueryPo(request, qo, Goods.class, mv); if (store_name != null && !store_name.equals("")) { qo.addQuery("obj.goods_store.store_name", new SysMap("store_name", "%" + CommUtil.null2String(store_name) + "%"), "like"); mv.addObject("store_name", store_name); } if (brand_id != null && !brand_id.equals("")) { qo.addQuery("obj.goods_brand.id", new SysMap("goods_brand_id", CommUtil.null2Long(brand_id)), "="); mv.addObject("brand_id", brand_id); } if (gc_id != null && !gc_id.equals("")) { qo.addQuery("obj.gc.id", new SysMap("goods_gc_id", CommUtil.null2Long(gc_id)), "="); mv.addObject("gc_id", gc_id); } if (goods_type != null && !goods_type.equals("")) { qo.addQuery("obj.goods_type", new SysMap("goods_goods_type", CommUtil.null2Int(goods_type)), "="); mv.addObject("goods_type", goods_type); } if (goods_global != null && !goods_global.equals("")) { qo.addQuery("obj.goods_global", new SysMap("goods_goods_global", CommUtil.null2Int(goods_global)), "="); mv.addObject("goods_global", goods_global); } if (goods_name != null && !goods_name.equals("")) { qo.addQuery("obj.goods_name", new SysMap("goods_goods_name", "%" + goods_name + "%"), "like"); mv.addObject("goods_name", goods_name); } if (store_recommend != null && !store_recommend.equals("")) { qo.addQuery( "obj.store_recommend", new SysMap("goods_store_recommend", CommUtil .null2Boolean(store_recommend)), "="); mv.addObject("store_recommend", store_recommend); } if (status != null && !status.equals("")) { qo.addQuery("obj.goods_status", new SysMap("goods_status", CommUtil.null2Int(status)), "="); mv.addObject("status", status); } else { qo.addQuery("obj.goods_status", new SysMap("goods_status", -2), ">"); } IPageList pList = this.goodsService.list(qo); CommUtil.saveIPageList2ModelAndView("", "", "", pList, mv); }else{ Set<Goods> objs = new HashSet<Goods>(); Map params = new HashMap(); params.put("goods_serial", goods_serial); List<Goods> list = this.goodsService.query("select obj from Goods obj where obj.goods_serial=:goods_serial", params, -1, -1); for(Goods goods : list){ objs.add(goods); } List<GoodsSku> clist = this.goodsSkuService.query("select obj from GoodsSku obj where obj.goods_serial=:goods_serial", params, -1, -1); if(!clist.isEmpty()){ for(GoodsSku cg : clist){ objs.add(cg.getGoods()); } } mv.addObject("objs", objs); mv.addObject("goods_serial", goods_serial); } List<GoodsBrand> gbs = this.goodsBrandService .query("select new GoodsBrand(id,addTime,name) from GoodsBrand obj order by obj.sequence asc", null, -1, -1); List<GoodsClass> gcs = this.goodsClassService .query("select new GoodsClass(id,className) from GoodsClass obj where obj.parent.id is null order by obj.sequence asc", null, -1, -1); mv.addObject("gcs", gcs); mv.addObject("gbs", gbs); return mv; } @SecurityMapping(title = "违规商品列表", value = "/admin/goods_outline.htm*", rtype = "admin", rname = "商品管理", rcode = "admin_goods", rgroup = "商品") @RequestMapping("/admin/goods_outline.htm") public ModelAndView goods_outline(HttpServletRequest request, HttpServletResponse response, String currentPage, String orderBy, String orderType,String goods_name,String gb_id ,String gc_id) { ModelAndView mv = new JModelAndView("admin/blue/goods_outline.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); String url = this.configService.getSysConfig().getAddress(); if (url == null || url.equals("")) { url = CommUtil.getURL(request); } String params = ""; GoodsQueryObject qo = new GoodsQueryObject(currentPage, mv, orderBy, orderType); if (goods_name != null && !goods_name.equals("")) { qo.addQuery("obj.goods_name", new SysMap("goods_goods_name", "%" + goods_name + "%"), "like"); mv.addObject("goods_name", goods_name); } if (gb_id != null && !gb_id.equals("")) { qo.addQuery("obj.goods_brand.id", new SysMap("goods_brand_id", CommUtil.null2Long(gb_id)), "="); mv.addObject("gb_id", gb_id); } if (gb_id != null && !gc_id.equals("")) { qo.addQuery("obj.gc.id", new SysMap("goods_class_id", CommUtil.null2Long(gc_id)), "="); mv.addObject("gc_id", gc_id); } qo.addQuery("obj.goods_status", new SysMap("goods_status", -2), "="); IPageList pList = this.goodsService.list(qo); CommUtil.saveIPageList2ModelAndView(url + "/admin/goods_list.htm", "", params, pList, mv); List<GoodsBrand> gbs = this.goodsBrandService .query("select new GoodsBrand(id,addTime,name) from GoodsBrand obj order by obj.sequence asc", null, -1, -1); List<GoodsClass> gcs = this.goodsClassService .query("select obj from GoodsClass obj where obj.level=1 order by obj.sequence asc", null, -1, -1); mv.addObject("gcs", gcs); mv.addObject("gbs", gbs); return mv; } @SecurityMapping(title = "商品删除", value = "/admin/goods_del.htm*", rtype = "admin", rname = "商品管理", rcode = "admin_goods", rgroup = "商品") @RequestMapping("/admin/goods_del.htm") public String goods_del(HttpServletRequest request, String mulitId) throws Exception { String[] ids = mulitId.split(","); for (String id : ids) { if (!id.equals("")) { Goods goods = this.goodsService.getObjById(CommUtil .null2Long(id)); List<Evaluate> evaluates = goods.getEvaluates(); for (Evaluate e : evaluates) { this.evaluateService.delete(e.getId()); } goods.getGoods_photos().clear(); goods.getGoods_ugcs().clear(); goods.getGoods_specs().clear(); Map params = new HashMap(); params.clear();// 直通车商品记录 params.put("gid", goods.getId()); List<ZTCGoldLog> ztcgls = this.ztcglService .query("select obj from ZTCGoldLog obj where obj.zgl_goods_id=:gid", params, -1, -1); for (ZTCGoldLog ztc : ztcgls) { this.ztcglService.delete(ztc.getId()); } goods.setGoods_main_photo(null); this.goodsService.delete(goods.getId()); // 删除索引 String goods_lucene_path = System.getProperty("metoob2b2c.root") + File.separator + "luence" + File.separator + "goods"; File file = new File(goods_lucene_path); if (!file.exists()) { CommUtil.createFolder(goods_lucene_path); } LuceneUtil lucene = LuceneUtil.instance(); lucene.setIndex_path(goods_lucene_path); lucene.delete_index(CommUtil.null2String(id)); // 发送站内短信提醒卖家 if (goods.getGoods_type() == 1) { this.send_site_msg(request, "msg_toseller_goods_delete_by_admin_notify", goods .getGoods_store().getUser(), goods, "商城存在违规"); } } } return "redirect:goods_list.htm"; } private void send_site_msg(HttpServletRequest request, String mark, User user, Goods goods, String reason) throws Exception { Template template = this.templateService.getObjByProperty(null, "mark", mark); if (template.isOpen()) { ExpressionParser exp = new SpelExpressionParser(); EvaluationContext context = new StandardEvaluationContext(); context.setVariable("reason", reason); context.setVariable("user", user); context.setVariable("config", this.configService.getSysConfig()); context.setVariable("send_time", CommUtil.formatLongDate(new Date())); Expression ex = exp.parseExpression(template.getContent(), new SpelTemplate()); String content = ex.getValue(context, String.class); User fromUser = this.userService.getObjByProperty(null, "userName", "admin"); Message msg = new Message(); msg.setAddTime(new Date()); msg.setContent(content); msg.setFromUser(fromUser); msg.setTitle(template.getTitle()); msg.setToUser(user); msg.setType(0); this.messageService.save(msg); } } @SecurityMapping(title = "商品AJAX更新", value = "/admin/goods_ajax.htm*", rtype = "admin", rname = "商品管理", rcode = "admin_goods", rgroup = "商品") @RequestMapping("/admin/goods_ajax.htm") public void goods_ajax(HttpServletRequest request, HttpServletResponse response, String id, String fieldName, String value) throws ClassNotFoundException { Goods obj = this.goodsService.getObjById(Long.parseLong(id)); Field[] fields = Goods.class.getDeclaredFields(); BeanWrapper wrapper = new BeanWrapper(obj); Object val = null; for (Field field : fields) { if (field.getName().equals(fieldName)) { Class clz = Class.forName("java.lang.String"); if (field.getType().getName().equals("int")) { clz = Class.forName("java.lang.Integer"); } if (field.getType().getName().equals("boolean")) { clz = Class.forName("java.lang.Boolean"); } if (!value.equals("")) { val = BeanUtils.convertType(value, clz); } else { val = !CommUtil.null2Boolean(wrapper .getPropertyValue(fieldName)); } wrapper.setPropertyValue(fieldName, val); } } if (fieldName.equals("store_recommend")) { if (obj.isStore_recommend()) { obj.setStore_recommend_time(new Date()); } else obj.setStore_recommend_time(null); } if (fieldName.equals("store_creativity")) { if (obj.isStore_creativity()) { obj.setStore_creativity_time(new Date()); } else obj.setStore_creativity_time(null); } if (fieldName.equals("store_deals")) { if (obj.isStore_deals()) { obj.setStore_deals_time(new Date()); } else obj.setStore_deals_time(null); } if (fieldName.equals("store_china")) { if (obj.isStore_china()) { obj.setStore_china_time(new Date()); } else obj.setStore_china_time(null); } this.goodsService.update(obj); if (obj.getGoods_status() == 0) { // 更新lucene索引 String goods_lucene_path = System.getProperty("metoob2b2c.root") + File.separator + "luence" + File.separator + "goods"; File file = new File(goods_lucene_path); if (!file.exists()) { CommUtil.createFolder(goods_lucene_path); } LuceneVo vo = new LuceneVo(); vo.setVo_id(obj.getId()); vo.setVo_title(obj.getGoods_name()); vo.setVo_content(obj.getGoods_details()); vo.setVo_type("goods"); vo.setVo_store_price(CommUtil.null2Double(obj .getGoods_current_price())); vo.setVo_add_time(obj.getAddTime().getTime()); vo.setVo_goods_salenum(obj.getGoods_salenum()); vo.setVo_goods_serial(obj.getGoods_serial()); LuceneUtil lucene = LuceneUtil.instance(); lucene.setConfig(this.configService.getSysConfig()); lucene.setIndex_path(goods_lucene_path); lucene.update(CommUtil.null2String(obj.getId()), vo); } else { String goods_lucene_path = System.getProperty("metoob2b2c.root") + File.separator + "luence" + File.separator + "goods"; File file = new File(goods_lucene_path); if (!file.exists()) { CommUtil.createFolder(goods_lucene_path); } LuceneUtil lucene = LuceneUtil.instance(); lucene.setConfig(this.configService.getSysConfig()); lucene.setIndex_path(goods_lucene_path); lucene.delete_index(CommUtil.null2String(id)); } response.setContentType("text/plain"); response.setHeader("Cache-Control", "no-cache"); response.setCharacterEncoding("UTF-8"); PrintWriter writer; try { writer = response.getWriter(); writer.print(val.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @SecurityMapping(title = "商品审核", value = "/admin/goods_audit.htm*", rtype = "admin", rname = "商品管理", rcode = "admin_goods", rgroup = "商品") @RequestMapping("/admin/goods_audit.htm") public String goods_audit(HttpServletRequest request, HttpServletResponse response, String mulitId, String status) throws ClassNotFoundException { String ids[] = mulitId.split(","); for (String id : ids) { if (id != null) { Goods obj = this.goodsService .getObjById(CommUtil.null2Long(id)); obj.setGoods_status(obj.getPublish_goods_status());// 设置商品发布审核后状态 obj.setGoods_msg(null); this.goodsService.update(obj); String goods_lucene_path = System.getProperty("metoob2b2c.root") + File.separator + "luence" + File.separator + "goods"; File file = new File(goods_lucene_path); if (!file.exists()) { CommUtil.createFolder(goods_lucene_path); } LuceneVo vo = this.luceneVoTools.updateGoodsIndex(obj); SysConfig config = this.configService.getSysConfig(); LuceneUtil lucene = LuceneUtil.instance(); lucene.setConfig(config); lucene.setIndex_path(goods_lucene_path); lucene.writeIndex(vo); } } return "redirect:goods_list.htm?status=" + status; } @SecurityMapping(title = "商品二维码生成", value = "/admin/goods_qr.htm*", rtype = "admin", rname = "商品管理", rcode = "admin_goods", rgroup = "商品") @RequestMapping("/admin/goods_qr.htm") public String goods_self_qr(HttpServletRequest request, HttpServletResponse response, String mulitId, String currentPage) throws ClassNotFoundException { String ids[] = mulitId.split(","); for (String id : ids) { if (id != null) { Goods obj = this.goodsService .getObjById(CommUtil.null2Long(id)); String uploadFilePath = this.configService.getSysConfig() .getUploadFilePath(); String destPath = request.getSession().getServletContext() .getRealPath("/") + uploadFilePath + File.separator + "goods_qr"; if (!CommUtil.fileExist(destPath)) { CommUtil.createFolder(destPath); } destPath = destPath + File.separator + obj.getId() + "_qr.jpg"; // Map goods_qr = new HashMap(); // goods_qr.put("id", CommUtil.null2String(obj.getId())); // goods_qr.put("type", "goods"); String logoPath = ""; if (obj.getGoods_main_photo() != null) { logoPath = request.getSession().getServletContext() .getRealPath("/") + File.separator + obj.getGoods_main_photo().getPath() + File.separator + obj.getGoods_main_photo().getName(); } else { logoPath = request.getSession().getServletContext() .getRealPath("/") + File.separator + this.configService.getSysConfig().getGoodsImage() .getPath() + File.separator + File.separator + this.configService.getSysConfig().getGoodsImage() .getName(); } String goods_url = CommUtil.getURL(request) + "/goods_" + id + ".htm"; if (obj.getGoods_type() == 1) {// 商家商品 if (this.configService.getSysConfig() .isSecond_domain_open() && !CommUtil.null2String( obj.getGoods_store() .getStore_second_domain()).equals( "")) { goods_url = "http://" + obj.getGoods_store().getStore_second_domain() + "." + CommUtil.generic_domain(request) + "/goods_" + id + ".htm"; } } QRCodeUtil.encode(goods_url, logoPath, destPath, true); obj.setQr_img_path(CommUtil.getURL(request) + "/" + uploadFilePath + "/" + "goods_qr" + "/" + obj.getId() + "_qr.jpg"); this.goodsService.update(obj); } } return "redirect:goods_list.htm?currentPage=" + currentPage; } }
/** * MIT License * <p> * Copyright (c) 2019-2022 nerve.network * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package network.nerve.converter.tx.v1.proposal; import io.nuls.base.data.NulsHash; import io.nuls.base.data.Transaction; import io.nuls.core.basic.InitializingBean; import io.nuls.core.core.annotation.Autowired; import io.nuls.core.core.annotation.Component; import io.nuls.core.exception.NulsException; import network.nerve.converter.constant.ConverterErrorCode; import network.nerve.converter.core.heterogeneous.docking.management.HeterogeneousDockingManager; import network.nerve.converter.enums.ProposalTypeEnum; import network.nerve.converter.helper.ConfirmProposalHelper; import network.nerve.converter.model.bo.Chain; import network.nerve.converter.model.po.ProposalPO; import network.nerve.converter.model.txdata.ConfirmProposalTxData; import network.nerve.converter.model.txdata.ProposalExeBusinessData; import network.nerve.converter.storage.ProposalStorageService; import network.nerve.converter.storage.RechargeStorageService; import network.nerve.converter.tx.v1.proposal.interfaces.IConfirmProposal; import network.nerve.converter.utils.ConverterUtil; /** * @author: Loki * @date: 2020/5/21 */ @Component("ConfirmTransferProposal") public class ConfirmTransferProposal implements IConfirmProposal, InitializingBean { @Autowired private ConfirmProposalHelper confirmProposalHelper; @Autowired private HeterogeneousDockingManager heterogeneousDockingManager; @Autowired private ProposalStorageService proposalStorageService; @Autowired private RechargeStorageService rechargeStorageService; @Override public void afterPropertiesSet() throws NulsException { confirmProposalHelper.register(proposalType(), this); } @Override public Byte proposalType() { return ProposalTypeEnum.TRANSFER.value(); } @Override public void validate(Chain chain, Transaction tx, ConfirmProposalTxData txData) throws NulsException { ProposalExeBusinessData businessData = ConverterUtil.getInstance(txData.getBusinessData(), ProposalExeBusinessData.class); // 获取提案信息 ProposalPO proposalPO = proposalStorageService.find(chain, businessData.getProposalTxHash()); if(null == proposalPO){ chain.getLogger().error("[ConfirmTransferProposal] 提案不存在 proposalHash:{}", businessData.getProposalTxHash().toHex()); throw new NulsException(ConverterErrorCode.PROPOSAL_NOT_EXIST); } // 根据填hash 获取已确认充值交易的hash NulsHash rechargeTxHash = rechargeStorageService.find(chain, proposalPO.getHash().toHex()); if(null == rechargeTxHash){ chain.getLogger().error("[ConfirmTransferProposal] 该提案已执的充值交易不存在 proposalHash:{}, ", businessData.getProposalTxHash().toHex()); throw new NulsException(ConverterErrorCode.PROPOSAL_EXECUTIVE_FAILED); } if(!rechargeTxHash.equals(businessData.getProposalExeHash())){ chain.getLogger().error("[ConfirmTransferProposal] 确认充值交易中充值交易hash,与已确认数据不一致, 该提案已执行过充值. ProposalExeHash:{}, DB-RechargeTxHash:{} ", businessData.getProposalExeHash().toHex(), rechargeTxHash.toHex()); throw new NulsException(ConverterErrorCode.PROPOSAL_EXECUTIVE_FAILED); } } }
package com.yc.cinema.util; import static org.junit.Assert.*; import java.sql.Connection; import org.junit.Test; public class MyBatisUtilTest { @Test public void testGetSession() { Connection conn = MyBatisUtil.getSession().getConnection(); assertNotNull("数据库连接失败!",conn); } }
package com.bwie.juan_mao.jingdong_kanglijuan.widget; import android.content.Context; import android.graphics.Color; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.bwie.juan_mao.jingdong_kanglijuan.R; /** * Created by 卷猫~ on 2018/10/26. */ public class AddDecreaseWidget extends LinearLayout implements View.OnClickListener { private Button txtDecrease; private Button txtAdd; private TextView txtNum; private int num = 1; public int getNum() { return num; } public void setNum(int num) { this.num = num; txtNum.setText(num + ""); setColor(); } public interface OnAddDecreaseClickListener { void onAddClick(int num); void onDecreaseClick(int num); } private OnAddDecreaseClickListener addDecreaseClickListener; public void setOnAddDecreaseClickListener(OnAddDecreaseClickListener onAddDecreaseClickListener) { this.addDecreaseClickListener = onAddDecreaseClickListener; } public AddDecreaseWidget(Context context) { this(context, null); } public AddDecreaseWidget(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public AddDecreaseWidget(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } private void init(Context context) { View.inflate(context, R.layout.widget_add_decrease, this); txtDecrease = findViewById(R.id.txt_decrease); txtAdd = findViewById(R.id.txt_add); txtNum = findViewById(R.id.txt_num); txtDecrease.setOnClickListener(this); txtAdd.setOnClickListener(this); } private void setColor() { if (Integer.parseInt(txtNum.getText().toString()) == 1) { txtDecrease.setTextColor(Color.rgb(121, 120, 120)); } else { txtDecrease.setTextColor(Color.BLACK); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.txt_decrease: if (num > 1) { num--; } txtNum.setText(num + ""); if (addDecreaseClickListener != null) { addDecreaseClickListener.onDecreaseClick(num); } setColor(); break; case R.id.txt_add: num++; txtNum.setText(num + ""); if (addDecreaseClickListener != null) { addDecreaseClickListener.onAddClick(num); } setColor(); break; } } }
package com.getkhaki.api.bff.web.models; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; @Setter @Getter @Accessors(chain = true) public class UserProfileResponseDto extends PersonDto { private String companyName; private String department; }
package nightgames.skills; import nightgames.characters.Attribute; import nightgames.characters.Character; import nightgames.characters.Emotion; import nightgames.characters.Trait; import nightgames.combat.Combat; import nightgames.combat.Result; import nightgames.global.Global; import nightgames.stance.Behind; import nightgames.stance.Position; import nightgames.status.Primed; public class CheapShot extends Skill { public CheapShot(Character self) { super("Cheap Shot", self); } @Override public boolean requirements(Combat c, Character user, Character target) { return user.getPure(Attribute.Temporal) >= 2; } @Override public boolean usable(Combat c, Character target) { Position s = c.getStance(); return s.mobile(getSelf()) && !s.prone(getSelf()) && !s.prone(target) && !s.behind(getSelf()) && getSelf().canAct() && !s.penetrated(target) && !s.penetrated(getSelf()) && Primed.isPrimed(getSelf(), 3); } @Override public String describe(Combat c) { return "Stop time long enough to get in an unsportsmanlike attack from behind: 3 charges"; } @Override public boolean resolve(Combat c, Character target) { getSelf().add(new Primed(getSelf(), -3)); if (getSelf().human()) { c.write(getSelf(), deal(c, 0, Result.normal, target)); } else if (target.human()) { c.write(getSelf(), receive(c, 0, Result.normal, target)); if (Global.random(5) >= 3) { c.write(getSelf(), getSelf().bbLiner(c)); } } c.setStance(new Behind(getSelf(), target)); target.pain(c, 8 + Global.random(16) + getSelf().get(Attribute.Power)); if (getSelf().has(Trait.wrassler)) { target.calm(c, Global.random(6)); } else { target.calm(c, Global.random(10)); } getSelf().buildMojo(c, 10); getSelf().emote(Emotion.confident, 15); getSelf().emote(Emotion.dominant, 15); target.emote(Emotion.nervous, 10); target.emote(Emotion.angry, 20); return true; } @Override public Skill copy(Character user) { return new CheapShot(user); } @Override public Tactics type(Combat c) { return Tactics.damage; } @Override public String deal(Combat c, int damage, Result modifier, Character target) { if (target.mostlyNude()) { if (target.hasBalls()) { return String.format( "You freeze time briefly, giving you a chance to circle around %s. When time resumes, %s looks around in " + "confusion, completely unguarded. You capitalize on your advantage by crouching behind %s and delivering a decisive " + "uppercut to %s dangling balls.", target.name(), target.pronoun(), target.directObject(), target.possessivePronoun()); } else { return String.format( "You freeze time briefly, giving you a chance to circle around %s. When time resumes, %s looks around in " + "confusion, completely unguarded. You capitalize on your advantage by crouching behind %s and delivering a swift, but " + "painful cunt punt.", target.name(), target.pronoun(), target.directObject()); } } else { return String.format( "You freeze time briefly, giving you a chance to circle around %s. When time resumes, %s looks around in " + "confusion, completely unguarded. You capitalize on your advantage by crouching behind %s and delivering a decisive " + "uppercut to the groin.", target.name(), target.pronoun(), target.directObject()); } } @Override public String receive(Combat c, int damage, Result modifier, Character target) { if (target.mostlyNude()) { return String.format( "%s suddenly vanishes right in front of your eyes. That wasn't just fast, %s completely disappeared. Before " + "you can react, you're hit from behind with a devastating punch to your unprotected balls.", getSelf().name(), getSelf().pronoun()); } else { return String.format( "%s suddenly vanishes right in front of your eyes. That wasn't just fast, %s completely disappeared. You hear something " + "that sounds like 'Za Warudo' before you suffer a painful groin hit from behind.", getSelf().name(), getSelf().pronoun()); } } }
package jp.ac.kyushu_u.csce.modeltool.dictionary.dialog; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import jp.ac.kyushu_u.csce.modeltool.base.ModelToolBasePlugin; import jp.ac.kyushu_u.csce.modeltool.base.constant.BasePreferenceConstants; import jp.ac.kyushu_u.csce.modeltool.base.dialog.CInputDialog; import jp.ac.kyushu_u.csce.modeltool.base.utility.ColorName; import jp.ac.kyushu_u.csce.modeltool.base.utility.PluginHelper; import jp.ac.kyushu_u.csce.modeltool.dictionary.Messages; import jp.ac.kyushu_u.csce.modeltool.dictionary.ModelToolDictionaryPlugin; import jp.ac.kyushu_u.csce.modeltool.dictionary.constant.DictionaryConstants; import jp.ac.kyushu_u.csce.modeltool.dictionary.dict.DictionaryClass; import jp.ac.kyushu_u.csce.modeltool.dictionary.dict.DictionarySetting; import jp.ac.kyushu_u.csce.modeltool.dictionary.dict.DictionarySetting.Category; import jp.ac.kyushu_u.csce.modeltool.dictionary.dict.Entry; import jp.ac.kyushu_u.csce.modeltool.dictionary.dict.HandlerUpdater; import jp.ac.kyushu_u.csce.modeltool.dictionary.dict.TableTab; import jp.ac.kyushu_u.csce.modeltool.dictionary.dict.model.ModelManager; import jp.ac.kyushu_u.csce.modeltool.dictionary.utility.LanguageUtil; import org.apache.commons.lang.StringUtils; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IInputValidator; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.ColorSelector; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.window.IShellProvider; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; /** * 辞書情報を表示するダイアログ * * @author KBK yoshimura */ public class DictionaryInformationDialog extends Dialog { private Text txtDomain; private Text txtProject; private Text txtLanguage; // private Text txtModel; private Combo cmbModel; private Table tblSubtotal; private int total; private String bkLanguage; Button chkSpecificCategory; TableViewer tvCategory; Button btnDefaultCategory; // ColorSelector csPrimary; // ColorSelector csSecondary; /** タブフォルダー */ private TabFolder folder; /** 最後に開いたタブのインデックス */ private static int lastTabIndex = 0; /** タブフォルダーのセレクションリスナー */ SelectionListener tabListener; // /** 種別デフォルトフラグ */ // private boolean isDefaultCategory; /** */ private static final int NUM_COLUMNS = 2; /** 言語情報タブのタブインデックス */ private static final int TAB_IDX_LANGUAGE = 3; /** 辞書タブ */ private TableTab tab; /** プリファレンスストア(base) */ private IPreferenceStore storeBase; /** * 種別設定 */ List<CategoryItem> catItems; Map<CategoryItem, Image[]> colorImageMap; /** 変更可能フラグ */ private boolean canEdit; /** * コンストラクタ * @param parentShell */ private DictionaryInformationDialog(Shell parentShell) { super(parentShell); } /** * コンストラクタ * @param parentShell */ private DictionaryInformationDialog(IShellProvider parentShell) { super(parentShell); } /** * コンストラクタ * @param parentShell * @param tab */ public DictionaryInformationDialog(Shell parentShell, TableTab tab) { super(parentShell); Assert.isNotNull(tab); this.tab = tab; canEdit = ModelManager.getInstance().isResisteredModel( tab.getDictionary().getDictionaryClass().model); storeBase = ModelToolBasePlugin.getDefault().getPreferenceStore(); catItems = new ArrayList<CategoryItem>(); colorImageMap = new LinkedHashMap<CategoryItem, Image[]>(); } @Override protected Control createDialogArea(Composite parent) { Composite composite = (Composite)super.createDialogArea(parent); GridLayout compLayout = (GridLayout)composite.getLayout(); compLayout.numColumns = 2; compLayout.verticalSpacing = 4; // 辞書名 Label lblDicName = new Label(composite, SWT.NONE); lblDicName.setText(Messages.DictionaryInformationDialog_0); GridData data = new GridData(SWT.NONE); lblDicName.setLayoutData(data); Text txtDicName = new Text(composite, SWT.READ_ONLY | SWT.WRAP); data = new GridData(GridData.GRAB_HORIZONTAL); txtDicName.setLayoutData(data); txtDicName.setText(tab.getDictionaryName()); // ファイル名 Label lblFileName = new Label(composite, SWT.NONE); lblFileName.setText(Messages.DictionaryInformationDialog_1); data = new GridData(SWT.NONE); lblFileName.setLayoutData(data); Text txtFileName = new Text(composite, SWT.READ_ONLY | SWT.WRAP); data = new GridData(GridData.GRAB_HORIZONTAL); txtFileName.setLayoutData(data); if (tab.getFile() != null) { txtFileName.setText(tab.getFile().getName()); } // パス Label lblPath = new Label(composite, SWT.NONE); lblPath.setText(Messages.DictionaryInformationDialog_2); data = new GridData(SWT.NONE); lblPath.setLayoutData(data); Text txtPath = new Text(composite, SWT.READ_ONLY | SWT.WRAP); data = new GridData(GridData.GRAB_HORIZONTAL); txtPath.setLayoutData(data); if (tab.getFile() != null) { txtPath.setText(PluginHelper.getRelativePath(tab.getFile())); } // 空行 Label lblEmpty = new Label(composite, SWT.NONE); lblEmpty.setText(""); //$NON-NLS-1$ data = new GridData(SWT.NONE); data.horizontalSpan = 2; data.heightHint = 5; lblEmpty.setLayoutData(data); // タブフォルダ folder = new TabFolder(composite, SWT.NONE); data = new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL); data.horizontalSpan = 2; folder.setLayoutData(data); // 登録件数タブ /*TabItem itmTotal =*/ createTotalTab(folder); // 種別情報タブ createCategoryTab(folder); // 辞書情報タブ /*TabItem itmInfo =*/ createInfoTab(folder); // 入力言語タブ createLanguageTab(folder); // 最後に開いたタブを開く folder.setSelection(lastTabIndex); // リスナーの追加 tabListener = new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { // 選択されたタブインデックスを退避 lastTabIndex = folder.getSelectionIndex(); } }; folder.addSelectionListener(tabListener); // タブをフォーカス folder.setFocus(); return composite; } /** * 登録件数タブの作成 * @param folder */ protected TabItem createTotalTab(TabFolder folder) { // 登録件数タブ TabItem item = new TabItem(folder, SWT.BORDER); Composite cmpTotal = new Composite(folder, SWT.NONE); GridLayout cmpTotalLayout = new GridLayout(2, false); cmpTotal.setLayout(cmpTotalLayout); item.setControl(cmpTotal); item.setText(Messages.DictionaryInformationDialog_4); Composite composite = cmpTotal; // 登録件数 Label lblTotal = new Label(composite, SWT.NONE); lblTotal.setText(Messages.DictionaryInformationDialog_5); GridData data = new GridData(SWT.NONE); lblTotal.setLayoutData(data); Text txtTotal = new Text(composite, SWT.READ_ONLY | SWT.WRAP); data = new GridData(GridData.GRAB_HORIZONTAL); txtTotal.setLayoutData(data); // 種別内訳 Label lblSubtotal = new Label(composite, SWT.NONE); lblSubtotal.setText(Messages.DictionaryInformationDialog_6); data = new GridData(SWT.NONE); lblSubtotal.setLayoutData(data); Button btnCopy = new Button(composite, SWT.NONE); data = new GridData(SWT.END, SWT.CENTER, true, false); btnCopy.setLayoutData(data); btnCopy.setText(Messages.DictionaryInformationDialog_7); btnCopy.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { copy(); } }); // 登録件数の集計 Map<Object, Integer> map = tab.getCategorySubtotal(); int subtotalNone = map.containsKey(DictionaryConstants.CATEGORY_NO_NONE)? map.get(DictionaryConstants.CATEGORY_NO_NONE) : 0; int subtotalNoun = map.containsKey(DictionaryConstants.CATEGORY_NO_NOUN)? map.get(DictionaryConstants.CATEGORY_NO_NOUN) : 0; int subtotalVerb = map.containsKey(DictionaryConstants.CATEGORY_NO_VERB)? map.get(DictionaryConstants.CATEGORY_NO_VERB) : 0; int subtotalState = map.containsKey(DictionaryConstants.CATEGORY_NO_STATE)? map.get(DictionaryConstants.CATEGORY_NO_STATE) : 0; total = subtotalNone + subtotalNoun + subtotalVerb + subtotalState; tblSubtotal = new Table(composite, SWT.BORDER | SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); // data = new GridData(GridData.GRAB_HORIZONTAL // | GridData.HORIZONTAL_ALIGN_FILL // | GridData.GRAB_VERTICAL // | GridData.VERTICAL_ALIGN_FILL); // data.horizontalSpan = 2; data = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1); tblSubtotal.setLayoutData(data); TableLayout tblLayout = new TableLayout(); tblSubtotal.setLayout(tblLayout); tblSubtotal.setHeaderVisible(true); tblSubtotal.setLinesVisible(true); TableColumn col1 = new TableColumn(tblSubtotal, SWT.NONE); col1.setText(Messages.DictionaryInformationDialog_8); col1.setWidth(100); TableColumn col2 = new TableColumn(tblSubtotal, SWT.RIGHT); col2.setText(Messages.DictionaryInformationDialog_9); col2.setWidth(100); TableItem itemNone = new TableItem(tblSubtotal, SWT.NONE); itemNone.setText(new String[]{DictionaryConstants.CATEGORY_NONE2, String.valueOf(subtotalNone)}); // TableItem itemNoun = new TableItem(tblSubtotal, SWT.NONE); // itemNoun.setText(new String[]{DictionaryConstants.CATEGORY_NOUN, String.valueOf(subtotalNoun)}); // TableItem itemVerb = new TableItem(tblSubtotal, SWT.NONE); // itemVerb.setText(new String[]{DictionaryConstants.CATEGORY_VERB, String.valueOf(subtotalVerb)}); // TableItem itemState = new TableItem(tblSubtotal, SWT.NONE); // itemState.setText(new String[]{DictionaryConstants.CATEGORY_STATE, String.valueOf(subtotalState)}); // 個別設定分の表示 for (int i=1; i <= DictionaryConstants.MAX_CATEGORY_NO; i++) { Category category = tab.getDictionary().getSetting().getCategory(i); if (category != null) { TableItem itemCat = new TableItem(tblSubtotal, SWT.NONE); int count = PluginHelper.nullToZero(map.get(category.getNo())); itemCat.setText(new String[]{category.getName(), String.valueOf(count)}); total += count; } } txtTotal.setText(String.valueOf(total) + Messages.DictionaryInformationDialog_10); return item; } /** * 種別内訳をクリップボードにコピー */ private void copy() { Clipboard clipboard = new Clipboard(getShell().getDisplay()); StringBuffer sb = new StringBuffer(); TableItem[] items = tblSubtotal.getItems(); for (int i=0; i<items.length; i++) { TableItem item = items[i]; for (int j=0; j<NUM_COLUMNS; j++) { sb.append(item.getText(j)); if (j != NUM_COLUMNS - 1) { sb.append("\t"); //$NON-NLS-1$ } } sb.append("\n"); //$NON-NLS-1$ } sb.append(Messages.DictionaryInformationDialog_13).append("\t").append(total); //$NON-NLS-1$ String[] data = new String[]{sb.toString()}; Transfer[] dataTypes = new Transfer[]{TextTransfer.getInstance()}; clipboard.setContents(data, dataTypes); clipboard.dispose(); } /** * 種別情報タブの作成 * @param folder * @return */ protected TabItem createCategoryTab(final TabFolder folder) { // ボタン配列 final Button[] buttons = new Button[3]; final int ADD = 0; // 追加 final int EDIT = 1; // 編集 final int REMOVE = 2; // 除去 // 変更可能フラグ final boolean isEditable = isCategoryEditable(); // コントロールマネージャー final ControlUsageManager cuManager = new ControlUsageManager(); // タブ作成 TabItem item = new TabItem(folder, SWT.BORDER); Composite composite = new Composite(folder, SWT.NONE); GridLayout cmpInfoLayout = new GridLayout(1, false); composite.setLayout(cmpInfoLayout); item.setControl(composite); item.setText(Messages.DictionaryInformationDialog_48); // 固有設定有無チェックボックス chkSpecificCategory = new Button(composite, SWT.CHECK); chkSpecificCategory.setText(Messages.DictionaryInformationDialog_57); chkSpecificCategory.setSelection(!tab.getDictionary().getSetting().isDefaultCategory()); // セパレーター Label separator = new Label(composite, SWT.SEPARATOR | SWT.SHADOW_OUT | SWT.HORIZONTAL | SWT.NO_FOCUS | SWT.LEFT_TO_RIGHT); separator.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL)); // 種別設定グループ final Group grpCategory = new Group(composite, SWT.NONE); grpCategory.setText(Messages.DictionaryInformationDialog_21); GridData data = new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_VERTICAL | GridData.VERTICAL_ALIGN_FILL); grpCategory.setLayoutData(data); GridLayout grpLayout = new GridLayout(2, false); grpCategory.setLayout(grpLayout); // テーブル tvCategory = new TableViewer(grpCategory, SWT.BORDER | SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); Table tblCategory = tvCategory.getTable(); // tblCategory = new Table(grpCategory, SWT.BORDER | SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); data = new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_VERTICAL | GridData.VERTICAL_ALIGN_FILL); data.horizontalSpan = 1; tblCategory.setLayoutData(data); TableLayout layout = new TableLayout(); tblCategory.setLayout(layout); tblCategory.setHeaderVisible(true); tblCategory.setLinesVisible(true); // tblCategory.addListener(SWT.MeasureItem, new Listener() { // public void handleEvent(Event event) { // event.height = 25; // } // }); // カラム設定 // 1列目の表示位置が不正となる不具合対応(Windowsのみ?) // 1列目に非表示行を追加 TableColumn col0 = new TableColumn(tblCategory, SWT.NONE); col0.setWidth(0); col0.setResizable(false); // No final TableColumn col1 = new TableColumn(tblCategory, SWT.NONE); col1.setText(Messages.DictionaryInformationDialog_22); // col1.setWidth(30); col1.setAlignment(SWT.RIGHT); col1.setResizable(false); // col1.pack(); // 種別名 TableColumn col2 = new TableColumn(tblCategory, SWT.NONE); col2.setText(Messages.DictionaryInformationDialog_23); col2.setWidth(100); // 初回色 TableColumn col3 = new TableColumn(tblCategory, SWT.NONE); col3.setText(Messages.DictionaryInformationDialog_24); col3.setResizable(false); col3.setWidth(60); col3.setAlignment(SWT.CENTER); // 2回目以降色 TableColumn col4 = new TableColumn(tblCategory, SWT.NONE); col4.setText(Messages.DictionaryInformationDialog_25); col4.setResizable(false); col4.setWidth(60); col4.setAlignment(SWT.CENTER); // コンテンツプロバイダー tvCategory.setContentProvider(new ArrayContentProvider()); // ラベルプロバイダー tvCategory.setLabelProvider(new TableLabelProvider()); // // カラムプロパティー // tvCategory.setColumnProperties(new String[]{ // "blank", // "no", //$NON-NLS-1$ // "name", //$NON-NLS-1$ // "primary", //$NON-NLS-1$ // "secondary", //$NON-NLS-1$ // }); // // // セルエディター // tvCategory.setCellEditors(new CellEditor[]{ // null, // null, //// new TextCellEditor(tblCategory, SWT.READ_ONLY), // TODO:ダイアログでの編集に切り替え // null, // セルエディターは使わない // null, // null, // }); // // // セルモディファイアー // tvCategory.setCellModifier(new ICellModifier() { // // @Override // public void modify(Object element, String property, Object value) { // CategoryItem item = (CategoryItem)((TableItem)element).getData(); // if (property.equals("name")) { //$NON-NLS-1$ // item.name = (String)value; // } // tvCategory.update(item, new String[]{property}); // } // // @Override // public Object getValue(Object element, String property) { // if (property.equals("name")) { //$NON-NLS-1$ // return ((CategoryItem)element).name; // } // return null; // } // // @Override // public boolean canModify(Object element, String property) { // if (property.equals("name")) { //$NON-NLS-1$ // return true; // } else { // return false; // } // } // }); // セレクションリスナーの追加 tvCategory.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (isEditable) { IStructuredSelection selection = (IStructuredSelection)event.getSelection(); if (!selection.isEmpty()) { // 編集ボタン 使用可 buttons[EDIT].setEnabled(true); // 選択されたインデックスの取得 buttons[REMOVE].setEnabled(true); } else { buttons[EDIT].setEnabled(false); buttons[REMOVE].setEnabled(false); } if (tvCategory.getTable().getItemCount() >= DictionaryConstants.MAX_CATEGORY_NO) { buttons[ADD].setEnabled(false); } else { buttons[ADD].setEnabled(true); } } } }); // XXX:ダイアログでの編集に切り替えるためコメントアウト // tblCategory.addMouseListener(new MouseAdapter() { // public void mouseDown(MouseEvent e) { // TableItem[] selection = tblCategory.getSelection(); // if (selection.length != 1) { // return; // } // IStructuredSelection sSelection = (IStructuredSelection)tvCategory.getSelection(); // CategoryItem cItem = (CategoryItem)sSelection.getFirstElement(); //// csPrimary.setColorValue(cItem.primary); //// csSecondary.setColorValue(cItem.secondary); //// setEnabledColorSelector(true); // // TableItem item = selection[0]; // for (int i = 0; i < tblCategory.getColumnCount(); i++) { // if (item.getBounds(i).contains(e.x, e.y)) { // if (i == 2) { // ColorDialog dialog = new ColorDialog(tblCategory.getShell()); // dialog.setRGB(cItem.primary); // RGB rgb = dialog.open(); // if (rgb != null) { // cItem.primary = rgb; // isDefaultCategory = false; // tvCategory.update(cItem, null); // } // } // if (i == 3) { // ColorDialog dialog = new ColorDialog(tblCategory.getShell()); // dialog.setRGB(cItem.secondary); // RGB rgb = dialog.open(); // if (rgb != null) { // cItem.secondary = rgb; // isDefaultCategory = false; // tvCategory.update(cItem, null); // } // } // break; // } // } // } // }); // データの追加 DictionarySetting setting = tab.getDictionary().getSetting(); // isDefaultCategory = setting.isDefaultCategory(); boolean isDefaultCategory = setting.isDefaultCategory(); if (isDefaultCategory) { CategoryItem itmNoun = new CategoryItem(); itmNoun.no = DictionaryConstants.CATEGORY_NO_NOUN; itmNoun.name = DictionaryConstants.CATEGORY_NOUN; itmNoun.primary = PreferenceConverter.getColor( storeBase, BasePreferenceConstants.PK_COLOR_NOUN_FIRST); itmNoun.secondary = PreferenceConverter.getColor( storeBase, BasePreferenceConstants.PK_COLOR_NOUN); catItems.add(itmNoun); CategoryItem itmVerb = new CategoryItem(); itmVerb.no = DictionaryConstants.CATEGORY_NO_VERB; itmVerb.name = DictionaryConstants.CATEGORY_VERB; itmVerb.primary = PreferenceConverter.getColor( storeBase, BasePreferenceConstants.PK_COLOR_VERB_FIRST); itmVerb.secondary = PreferenceConverter.getColor( storeBase, BasePreferenceConstants.PK_COLOR_VERB); catItems.add(itmVerb); CategoryItem itmState = new CategoryItem(); itmState.no = DictionaryConstants.CATEGORY_NO_STATE; itmState.name = DictionaryConstants.CATEGORY_STATE; itmState.primary = PreferenceConverter.getColor( storeBase, BasePreferenceConstants.PK_COLOR_STATE_FIRST); itmState.secondary = PreferenceConverter.getColor( storeBase, BasePreferenceConstants.PK_COLOR_STATE); catItems.add(itmState); } else { // for (int i=0; i<=DictionarySetting.CATEGORY_COUNT; i++) { for (int i=0; i<=DictionaryConstants.MAX_CATEGORY_NO; i++) { DictionarySetting.Category category = setting.getCategory(i); if (category == null) { continue; } CategoryItem cItem = new CategoryItem(); cItem.no = category.getNo(); cItem.name = category.getName(); cItem.primary = category.getPrimary(); cItem.secondary = category.getSecondary(); catItems.add(cItem); } } // データを設定 tvCategory.setInput(catItems); // Noカラム幅調整 col1.pack(); // ボタンエリア Composite buttonArea = new Composite(grpCategory, SWT.NONE); data = new GridData(SWT.BEGINNING, SWT.BEGINNING, false, true); buttonArea.setLayoutData(data); buttonArea.setLayout(new GridLayout(1, false)); // 追加ボタン Button btnAdd = new Button(buttonArea, SWT.PUSH); data = new GridData(SWT.FILL, SWT.CENTER, true, false); btnAdd.setLayoutData(data); btnAdd.setText(Messages.DictionaryInformationDialog_49); buttons[ADD] = btnAdd; // 編集ボタン Button btnEdit = new Button(buttonArea, SWT.PUSH); data = new GridData(SWT.FILL, SWT.CENTER, true, false); btnEdit.setLayoutData(data); btnEdit.setText(Messages.DictionaryInformationDialog_50); buttons[EDIT] = btnEdit; // 除去ボタン Button btnRemove = new Button(buttonArea, SWT.PUSH); data = new GridData(SWT.FILL, SWT.CENTER, true, false); btnRemove.setLayoutData(data); btnRemove.setText(Messages.DictionaryInformationDialog_51); buttons[REMOVE] = btnRemove; // 追加ボタン押下時の処理 buttons[ADD].addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { // ダイアログを開いて追加する CategoryDialog dialog = new CategoryDialog(getShell(), null); int ret = dialog.open(); if (ret == Dialog.OK) { CategoryItem retItem = dialog.getData(); catItems.add(retItem); Collections.sort(catItems, new Comparator<CategoryItem>() { public int compare(CategoryItem o1, CategoryItem o2) { return (o1.no - o2.no); } }); tvCategory.refresh(); tvCategory.setSelection(new StructuredSelection(retItem), true); col1.pack(); // 最大数に達した場合ボタン押下不可 if (catItems.size() >= DictionaryConstants.MAX_CATEGORY_NO) { buttons[ADD].setEnabled(false); } } } }); // 編集ボタン押下時の処理 buttons[EDIT].addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { int index = tvCategory.getTable().getSelectionIndex(); if (index >= 0) { // ダイアログを開いて編集する CategoryItem item = (CategoryItem)tvCategory.getElementAt(index); CategoryDialog dialog = new CategoryDialog(getShell(), item); int ret = dialog.open(); if (ret == Dialog.OK) { CategoryItem retItem = dialog.getData(); tvCategory.update(retItem, null); tvCategory.setSelection(new StructuredSelection(retItem), true); col1.pack(); } } } }); // 除去ボタン押下時の処理 buttons[REMOVE].addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { int index = tvCategory.getTable().getSelectionIndex(); if (index >= 0) { catItems.remove(index); tvCategory.refresh(); if (tvCategory.getTable().getItemCount() > 0) { if (index >= tvCategory.getTable().getItemCount()) { index = tvCategory.getTable().getItemCount() - 1; } tvCategory.setSelection(new StructuredSelection( tvCategory.getElementAt(index)), true); col1.pack(); } // 追加ボタン押下可能 buttons[ADD].setEnabled(true); } } }); // デフォルトボタン btnDefaultCategory = new Button(grpCategory, SWT.PUSH); data = new GridData(SWT.END, SWT.CENTER, true, false);//GridData.GRAB_VERTICAL | GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_END); data.verticalAlignment = SWT.END; // data.grabExcessVerticalSpace = true; data.horizontalSpan = 2; btnDefaultCategory.setLayoutData(data); btnDefaultCategory.setText(Messages.DictionaryInformationDialog_33); btnDefaultCategory.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { setDefaultColor(); // isDefaultCategory = true; } }); // 初期状態では未選択のため、編集・除去ボタン使用不可 buttons[EDIT].setEnabled(false); buttons[REMOVE].setEnabled(false); // 最大数に達した場合ボタン押下不可 if (catItems.size() >= DictionaryConstants.MAX_CATEGORY_NO) { buttons[ADD].setEnabled(false); } // 固有の設定チェックボックスによる活性・非活性の設定 cuManager.setControlEnabled(grpCategory, chkSpecificCategory.getSelection()); // 種別設定変更不可の場合 if (!isEditable) { chkSpecificCategory.setEnabled(false); if (chkSpecificCategory.getSelection()) { tblCategory.setEnabled(true); // テーブルまでdisabledにすると見にくいためここだけenabled } for (Button button : buttons) button.setEnabled(false); btnDefaultCategory.setEnabled(false); } // 固有の設定チェックボックスのリスナー追加 chkSpecificCategory.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // 活性・非活性の設定 cuManager.setControlEnabled(grpCategory, chkSpecificCategory.getSelection()); } }); return item; } /** * コントロールの活性・非活性を管理するクラス */ private class ControlUsageManager { /** * 活性・非活性の状態をバックアップするリスト */ private List<Boolean> list = new ArrayList<Boolean>(); /** * 子コントロールを含むコントロールの活性・非活性を設定する * @param control 対象コントロール * @param enabled trueの場合活性、falseの場合非活性 */ void setControlEnabled(Control control, boolean enabled) { if (enabled) { // 使用可能にする場合 loadEnabled(list.iterator(), control); } else { // 使用不可にする場合 list.clear(); saveEnabled(list, control); } } /** * 活性・非活性の状態をバックアップリストに格納する * @param list バックアップリスト * @param control 対象コントロール */ private void saveEnabled(List<Boolean> list, Control control) { // 自身の状態を退避 list.add(control.getEnabled()); // Compositeであれば子の状態も退避(再帰) if (control instanceof Composite) { for (Control child : ((Composite)control).getChildren()) { saveEnabled(list, child); } } // 状態を非活性にする control.setEnabled(false); } /** * 活性・非活性の状態をバックアップリストから復元する * @param iterator バックアップリストのイテレータ * @param control 対象コントロール */ private void loadEnabled(Iterator<Boolean> iterator, Control control) { if (!iterator.hasNext()) return; // 自身の状態を復元 control.setEnabled(iterator.next()); // Compositeであれば子の状態も復元(再帰) if (control instanceof Composite) { for (Control child : ((Composite)control).getChildren()) { loadEnabled(iterator, child); } } } } /** * 辞書情報タブの作成 * @param folder * @return */ protected TabItem createInfoTab(final TabFolder folder) { TabItem item = new TabItem(folder, SWT.BORDER); Composite composite = new Composite(folder, SWT.NONE); GridLayout cmpInfoLayout = new GridLayout(1, false); composite.setLayout(cmpInfoLayout); item.setControl(composite); item.setText(Messages.DictionaryInformationDialog_15); DictionaryClass dicClass = tab.getDictionary().getDictionaryClass(); // クラスグループ Group grpClass = new Group(composite, SWT.NONE); grpClass.setText(Messages.DictionaryInformationDialog_16); GridData data = new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL); grpClass.setLayoutData(data); GridLayout grpLayout = new GridLayout(3, false); grpClass.setLayout(grpLayout); // 問題領域 Label lblDomain = new Label(grpClass, SWT.NONE); lblDomain.setText(Messages.DictionaryInformationDialog_17); data = new GridData(); lblDomain.setLayoutData(data); txtDomain = new Text(grpClass, SWT.BORDER | SWT.SINGLE); data = new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL); data.horizontalSpan = 2; txtDomain.setLayoutData(data); txtDomain.setText(dicClass.domain); // プロジェクト名 Label lblProject = new Label(grpClass, SWT.NONE); lblProject.setText(Messages.DictionaryInformationDialog_18); data = new GridData(); lblProject.setLayoutData(data); txtProject = new Text(grpClass, SWT.BORDER | SWT.SINGLE); data = new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL); data.horizontalSpan = 2; txtProject.setLayoutData(data); txtProject.setText(dicClass.project); // 入力言語 Label lblLanguage = new Label(grpClass, SWT.NONE); lblLanguage.setText(Messages.DictionaryInformationDialog_19); data = new GridData(); lblLanguage.setLayoutData(data); txtLanguage = new Text(grpClass, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY); data = new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL); txtLanguage.setLayoutData(data); // txtLanguage.setText(dicClass.language); txtLanguage.setText(getCommaSeparatedString(dicClass.languages)); bkLanguage = txtLanguage.getText(); // 初期値を退避しておく Button btnLanguage = new Button(grpClass, SWT.PUSH); data = new GridData(); btnLanguage.setData(data); btnLanguage.setText(Messages.DictionaryInformationDialog_35); btnLanguage.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { folder.setSelection(TAB_IDX_LANGUAGE); } }); // 出力モデル Label lblModel = new Label(grpClass, SWT.NONE); lblModel.setText(Messages.DictionaryInformationDialog_20); data = new GridData(); lblModel.setLayoutData(data); // txtModel = new Text(grpClass, SWT.BORDER | SWT.SINGLE); // data = new GridData(GridData.GRAB_HORIZONTAL // | GridData.HORIZONTAL_ALIGN_FILL); // data.horizontalSpan = 2; // txtModel.setLayoutData(data); // txtModel.setText(dicClass.model); cmbModel = new Combo(grpClass, SWT.READ_ONLY); data = new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL); data.horizontalSpan = 2; cmbModel.setLayoutData(data); ModelManager modelManager = ModelManager.getInstance(); // 未登録モデルの場合、先頭に表示 if (!canEdit) { String unregModel = tab.getDictionary().getDictionaryClass().model; String unregModelName = Messages.DictionaryInformationDialog_46 + tab.getDictionary().getDictionaryClass().model; cmbModel.add(unregModelName); cmbModel.setData(unregModelName, unregModel); cmbModel.setText(unregModelName); } for (String modelKey : modelManager.getKeyList()) { cmbModel.add(modelManager.getModelName(modelKey)); cmbModel.setData(modelManager.getModelName(modelKey), modelKey); } if (!PluginHelper.isEmpty(dicClass.model) && canEdit) { cmbModel.setText(modelManager.getModelName(dicClass.model)); } cmbModel.setEnabled(isModelEditable()); return item; } // /** // * // */ // private class ColorChangeListener implements IPropertyChangeListener { // // private int row; // private int col; // // public ColorChangeListener(int row, int col) { // this.row = row; // this.col = col; // } // // public void propertyChange(PropertyChangeEvent event) { // // if (event.getNewValue().equals(event.getOldValue())) { // return; // } // // isDefaultCategory = false; // // if (col == 2) { // catItems.get(row).primary = (RGB)event.getNewValue(); // } // if (col == 3) { // catItems.get(row).secondary = (RGB)event.getNewValue(); // } // } // } /** * 種別設定ダイアログ・クラス */ private class CategoryDialog extends Dialog { /** No */ Text txtNo; /** 辞書名 */ Text txtName; /** マーキング色 初回 */ ColorSelector csPrimary; /** マーキング色 2回目以降 */ ColorSelector csSecondary; /** 編集対象アイテム */ CategoryItem item; /** * コンストラクタ * @param shell シェル * @param item アイテム */ public CategoryDialog(Shell shell, CategoryItem item) { super(shell); this.item = item; } /* * (non-Javadoc) * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) */ protected Control createDialogArea(Composite parent) { // スーパークラスのメソッド呼び出し Composite composite = (Composite)super.createDialogArea(parent); // ダイアログエリアの作成 Composite area = new Composite(composite, SWT.NONE); GridLayout layout = new GridLayout(3, false); area.setLayout(layout); area.setLayoutData(new GridData(GridData.FILL_BOTH)); // No Label lblNo = new Label(area, SWT.NONE); lblNo.setText(Messages.DictionaryInformationDialog_52); txtNo = new Text(area, SWT.BORDER | SWT.RIGHT); GridData gdNo = new GridData(); gdNo.widthHint = 50; txtNo.setLayoutData(gdNo); txtNo.setTextLimit(String.valueOf(DictionaryConstants.MAX_CATEGORY_NO).length()); new Label(area, SWT.NONE).setText(MessageFormat.format(Messages.DictionaryInformationDialog_58, String.valueOf(DictionaryConstants.MAX_CATEGORY_NO))); // 種別名 Label lblName = new Label(area, SWT.NONE); lblName.setText(Messages.DictionaryInformationDialog_53); txtName = new Text(area, SWT.BORDER); GridData gdName = new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL); gdName.horizontalSpan = 2; txtName.setLayoutData(gdName); txtName.setTextLimit(50); // セパレーター Label separator = new Label(area, SWT.SEPARATOR | SWT.SHADOW_OUT | SWT.HORIZONTAL | SWT.NO_FOCUS | SWT.LEFT_TO_RIGHT); GridData gdSeparator = new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL); gdSeparator.horizontalSpan = 3; separator.setLayoutData(gdSeparator); // マーキング色設定 Label lblMarking = new Label(area, SWT.NONE); lblMarking.setText(Messages.DictionaryInformationDialog_54); GridData gdMarking = new GridData(); gdMarking.horizontalSpan = 3; lblMarking.setLayoutData(gdMarking); Composite color = new Composite(area, SWT.NONE); GridLayout glColor = new GridLayout(); glColor.numColumns = 4; color.setLayout(glColor); GridData gdColor = new GridData(); gdColor.horizontalSpan = 3; color.setLayoutData(gdColor); Label lblPrimary = new Label(color, SWT.NONE); lblPrimary.setText(Messages.DictionaryInformationDialog_55); csPrimary = new ColorSelector(color); Label lblSecondary = new Label(color, SWT.NONE); lblSecondary.setText(Messages.DictionaryInformationDialog_56); csSecondary = new ColorSelector(color); txtNo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { validateInput(); } }); txtName.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { validateInput(); } }); return composite; } protected Control createContents(Composite parent) { Composite composite = (Composite)super.createContents(parent); if (item != null) { txtNo.setText(String.valueOf(item.no)); txtName.setText(item.name); csPrimary.setColorValue(item.primary); csSecondary.setColorValue(item.secondary); txtNo.setEditable(false); // Noは変更不可 txtName.setEditable(true); // 名前は変更可 txtName.setFocus(); // 種別名にフォーカス txtName.setSelection(0, item.name.length()); } else { csPrimary.setColorValue(ColorName.RGB_BLACK); csSecondary.setColorValue(ColorName.RGB_BLACK); txtNo.setFocus(); // Noにフォーカス } validateInput(); return composite; } protected void validateInput() { // No if (StringUtils.isBlank(txtNo.getText()) || !StringUtils.isNumeric(txtNo.getText())) { // 数字でない場合エラー getButton(Dialog.OK).setEnabled(false); return; } else { int no = Integer.parseInt(txtNo.getText()); // 0以下、MAXを超える場合エラー if (no <= 0 || no > DictionaryConstants.MAX_CATEGORY_NO) { getButton(Dialog.OK).setEnabled(false); return; } // 追加の場合、または編集でNo変更した場合 if (item == null || (item != null && item.no != no)) { int itmCnt = tvCategory.getTable().getItemCount(); for (int i = 0; i< itmCnt; i++) { CategoryItem catItm = (CategoryItem)tvCategory.getElementAt(i); if (no == catItm.no) { // 登録済みの数字の場合エラー getButton(Dialog.OK).setEnabled(false); return; } } } } // 種別名 if (PluginHelper.isEmpty(txtName.getText())) { // 未入力の場合エラー getButton(Dialog.OK).setEnabled(false); return; } getButton(Dialog.OK).setEnabled(true); } protected void okPressed() { if (item == null) { item = new CategoryItem(); } item.no = Integer.parseInt(txtNo.getText()); item.name = txtName.getText(); item.primary = csPrimary.getColorValue(); item.secondary = csSecondary.getColorValue(); super.okPressed(); } public CategoryItem getData() { return this.item; } } /** * */ class CategoryItem { int no; String name; RGB primary; RGB secondary; } /** * 色選択ボタンのデフォルト色設定 */ private void setDefaultColor() { catItems.clear(); CategoryItem itmNoun = new CategoryItem(); itmNoun.no = DictionaryConstants.CATEGORY_NO_NOUN; itmNoun.name = DictionaryConstants.CATEGORY_NOUN; itmNoun.primary = PreferenceConverter.getColor( storeBase, BasePreferenceConstants.PK_COLOR_NOUN_FIRST); itmNoun.secondary = PreferenceConverter.getColor( storeBase, BasePreferenceConstants.PK_COLOR_NOUN); catItems.add(itmNoun); CategoryItem itmVerb = new CategoryItem(); itmVerb.no = DictionaryConstants.CATEGORY_NO_VERB; itmVerb.name = DictionaryConstants.CATEGORY_VERB; itmVerb.primary = PreferenceConverter.getColor( storeBase, BasePreferenceConstants.PK_COLOR_VERB_FIRST); itmVerb.secondary = PreferenceConverter.getColor( storeBase, BasePreferenceConstants.PK_COLOR_VERB); catItems.add(itmVerb); CategoryItem itmState = new CategoryItem(); itmState.no = DictionaryConstants.CATEGORY_NO_STATE; itmState.name = DictionaryConstants.CATEGORY_STATE; itmState.primary = PreferenceConverter.getColor( storeBase, BasePreferenceConstants.PK_COLOR_STATE_FIRST); itmState.secondary = PreferenceConverter.getColor( storeBase, BasePreferenceConstants.PK_COLOR_STATE); catItems.add(itmState); tvCategory.setInput(catItems); // setEnabledColorSelector(false); } // private void setEnabledColorSelector(boolean enabled) { // csPrimary.setEnabled(enabled); // csSecondary.setEnabled(enabled); // } /** * 言語設定タブの作成 * @param folder */ protected TabItem createLanguageTab(final TabFolder folder) { DictionaryClass dicClass = tab.getDictionary().getDictionaryClass(); LanguageUtil util = ModelToolDictionaryPlugin.getLanguageUtil(); Map<String, String> map = util.getLanguageMap(); boolean isEditable = isLanguagesEditable(); // 言語設定タブ TabItem item = new TabItem(folder, SWT.BORDER); Composite cmpLang = new Composite(folder, SWT.NONE); GridLayout cmpLangLayout = new GridLayout(3, false); cmpLang.setLayout(cmpLangLayout); item.setControl(cmpLang); item.setText(Messages.DictionaryInformationDialog_36); Composite composite = cmpLang; final Table tblLanguage = new Table(composite, SWT.BORDER | SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); GridData data = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1); tblLanguage.setLayoutData(data); TableLayout tblLayout = new TableLayout(); tblLanguage.setLayout(tblLayout); tblLanguage.setHeaderVisible(true); tblLanguage.setLinesVisible(true); TableColumn col1 = new TableColumn(tblLanguage, SWT.NONE); col1.setText(Messages.DictionaryInformationDialog_37); TableColumn col2 = new TableColumn(tblLanguage, SWT.NONE); col2.setText(Messages.DictionaryInformationDialog_38); // 入力言語テーブルにデータを追加 int langcnt = 0; for (String cd : dicClass.languages) { String name = map.get(cd); new TableItem(tblLanguage, SWT.NONE).setText(new String[]{cd, name}); langcnt++; if (langcnt >= DictionaryConstants.MAX_COL_INFORMAL) { break; } } col1.pack(); col2.pack(); int col1Width = col1.getWidth(); int col2Width = col2.getWidth(); tblLayout.addColumnData(new ColumnWeightData(20, col1Width)); tblLayout.addColumnData(new ColumnWeightData(80, col2Width)); Label lblEmpty = new Label(composite, SWT.NONE); data = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1); lblEmpty.setLayoutData(data); final Button btnLangDel = new Button(cmpLang, SWT.NONE); btnLangDel.setText(Messages.DictionaryInformationDialog_39); data = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); data.widthHint = 100; btnLangDel.setLayoutData(data); btnLangDel.setEnabled(tblLanguage.getItemCount() > 0); btnLangDel.setEnabled(isEditable); Label lblLang = new Label(cmpLang, SWT.NONE); lblLang.setText(Messages.DictionaryInformationDialog_40); lblLang.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1)); final Combo cmbLang = new Combo(cmpLang, SWT.READ_ONLY); cmbLang.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1)); LanguageUtil languageUtil = ModelToolDictionaryPlugin.getLanguageUtil(); // コンボボックスにセット for (Map.Entry<String, String> p : languageUtil.getReverseMap().entrySet()) { // 既に選択済みの言語は除外する if (!dicClass.languages.contains(p.getValue())) { cmbLang.add(p.getKey()); } cmbLang.setData(p.getKey(), p.getValue()); } if (cmbLang.getItemCount() > 0) { cmbLang.select(0); } final Button btnLangAdd = new Button(cmpLang, SWT.NONE); btnLangAdd.setText(Messages.DictionaryInformationDialog_41); data = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); data.widthHint = 100; btnLangAdd.setLayoutData(data); btnLangAdd.setEnabled(isEditable); // 削除ボタン押下処理 btnLangDel.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { int index = tblLanguage.getSelectionIndex(); if (index > -1) { TableItem item =tblLanguage.getItem(index); String name = item.getText(1); tblLanguage.remove(index); if (tblLanguage.getItemCount() == 0) { btnLangDel.setEnabled(false); } else if (index == tblLanguage.getItemCount()) { tblLanguage.setSelection(index - 1); } else { tblLanguage.setSelection(index); } // コンボボックスへの追加位置を探す // TODO:とりあえず線形探索 時間があれば二分探索に変更する int cmbCnt = cmbLang.getItemCount(); for (int i=0; i< cmbCnt; i++) { if (name.compareToIgnoreCase(cmbLang.getItem(i)) < 0) { cmbLang.add(name, i); break; } } if (cmbCnt == cmbLang.getItemCount()) { cmbLang.add(name); } // 追加ボタンの有効化 if (tblLanguage.getItemCount() < DictionaryConstants.MAX_LANGUAGES_COUNT) { btnLangAdd.setEnabled(true); } // 辞書情報タブの入力言語TextBox更新 txtLanguage.setText(getCommaSeparatedString(tblLanguage.getItems())); } } }); // 追加ボタン押下処理 btnLangAdd.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { int index = cmbLang.getSelectionIndex(); if (index > -1) { String name = cmbLang.getItem(index); String cd = (String)cmbLang.getData(name); new TableItem(tblLanguage, SWT.NONE).setText(new String[]{cd, name}); cmbLang.remove(index); if (index != cmbLang.getItemCount()) { cmbLang.select(index); } else { cmbLang.select(index - 1); } tblLanguage.select(tblLanguage.getItemCount() - 1); tblLanguage.showItem(tblLanguage.getItem(tblLanguage.getItemCount() - 1)); btnLangDel.setEnabled(true); // 最大数を超えた入力は不可 if (tblLanguage.getItemCount() >= DictionaryConstants.MAX_LANGUAGES_COUNT) { btnLangAdd.setEnabled(false); } // 辞書情報タブの入力言語TextBox更新 txtLanguage.setText(getCommaSeparatedString(tblLanguage.getItems())); } } }); return item; } @Override protected Control createButtonBar(Composite parent) { Control control = super.createButtonBar(parent); // OKボタン制御 getButton(IDialogConstants.OK_ID).setEnabled(canEdit); return control; } @Override protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText(Messages.DictionaryInformationDialog_34); } @Override protected boolean isResizable() { return true; } @Override protected Point getInitialSize() { Point point = super.getInitialSize(); point.x = 500; return point; } @Override protected void okPressed() { // 編集不可の場合、処理なし if (!canEdit) return; // 入力チェック if (!validate()) return; // 形式モデルが変更された場合 if (!tab.getDictionary().getDictionaryClass().model.equals((String)cmbModel.getData(cmbModel.getText()))) { if (tab.isFileExist()) { boolean saveFlg = MessageDialog.openConfirm(getShell(), Messages.DictionaryInformationDialog_42, Messages.DictionaryInformationDialog_43); if (!saveFlg) return; // 辞書名設定 CInputDialog ciDlg = new CInputDialog(getShell(), Messages.DictionaryInformationDialog_44, MessageFormat.format(Messages.DictionaryInformationDialog_45, tab.getDictionaryName()), tab.getDictionaryName(), new IInputValidator() { @Override public String isValid(String newText) { if (newText.equals(tab.getDictionaryName())) { return Messages.DictionaryInformationDialog_47; } IWorkspace workspace = ResourcesPlugin.getWorkspace(); IStatus status = workspace.validateName(newText, IResource.FILE); if (status.isOK() == false) { return status.getMessage(); } return null; } }); if (ciDlg.open() == CANCEL) return; // 辞書の保存 if (tab.isDirty()) { tab.save(false); } // 辞書ファイルとの紐づけを解除 tab.clearFile(); // 辞書名設定 tab.setText(ciDlg.getValue()); tab.setToolTipText(ciDlg.getValue()); } // Undoヒストリのクリア tab.getHistoryHelper().clear(); // 辞書情報の更新 updateClassInfo(); // 種別設定の更新 updateCategorySetting(); // 辞書モデルの更新 ModelManager.getInstance().updateModel(tab.getDictionary()); // 形式的種別・定義のクリア tab.getDictionary().clearFormalDefinition(); // 編集フラグのクリア tab.setDirty(true); // 再描画 tab.getTableViewer().refresh(); new HandlerUpdater().update(tab); // モデルが変更されていない場合 } else { boolean classDirtyFlg = isClassDirty(); boolean categoryDirtyFlg = isCategoryDirty(); // クラス情報または種別設定が変更された場合 if (classDirtyFlg || categoryDirtyFlg) { // 不必要にメモリを使いたくないんで変更があったほうだけ履歴に残す // クラス情報 DictionaryClass oldClass = null; Object informalList = null; if (classDirtyFlg) { // 変更前のクラスの退避 oldClass = tab.getDictionary().getDictionaryClass().deepCopy(); // 変更前の非形式的定義の退避 informalList = getInformalsList(); } // 種別設定 DictionarySetting oldSetting = null; if (categoryDirtyFlg) { // 変更前の設定の退避 oldSetting = tab.getDictionary().getSetting().deepCopy(); } // 辞書情報の更新 updateClassInfo(); // 種別設定の更新 updateCategorySetting(); // 変更後のクラスの取得 DictionaryClass newClass = tab.getDictionary().getDictionaryClass(); // 変更後の設定の退避 DictionarySetting newSetting = tab.getDictionary().getSetting(); // Undoヒストリの追加 tab.getHistoryHelper().addInformationHistory(oldClass, newClass, oldSetting, newSetting, informalList); // 辞書モデルの更新 ModelManager.getInstance().updateModel(tab.getDictionary()); tab.setDirty(true); tab.getTableViewer().refresh(); new HandlerUpdater().update(tab); } } super.okPressed(); } /** * クラス情報が変更されたか判定する * @return */ protected boolean isClassDirty() { boolean isClassDirty = false; DictionaryClass dicClass = tab.getDictionary().getDictionaryClass(); if (dicClass.domain.equals(txtDomain.getText()) == false) { isClassDirty = true; } if (dicClass.project.equals(txtProject.getText()) == false) { isClassDirty = true; } if (bkLanguage.equals(txtLanguage.getText()) == false) { isClassDirty = true; } // if (dicClass.model.equals(txtModel.getText()) == false) { // isClassDirty = true; // } String newModel = StringUtils.defaultString((String)cmbModel.getData(cmbModel.getText())); if (dicClass.model.equals(newModel) == false) { isClassDirty = true; } return isClassDirty; } /** * クラス情報の変更内容を辞書オブジェクトへ反映する */ protected void updateClassInfo() { DictionaryClass dicClass = tab.getDictionary().getDictionaryClass(); if (dicClass.domain.equals(txtDomain.getText()) == false) { dicClass.domain = txtDomain.getText(); } if (dicClass.project.equals(txtProject.getText()) == false) { dicClass.project = txtProject.getText(); } if (bkLanguage.equals(txtLanguage.getText()) == false) { // 入力言語変更内容の反映 updateLangeuages(); } // if (dicClass.model.equals(txtModel.getText()) == false) { // dicClass.model = txtModel.getText(); // } String newModel = StringUtils.defaultString((String)cmbModel.getData(cmbModel.getText())); if (dicClass.model.equals(newModel) == false) { dicClass.model = newModel; } } /** * 種別設定が変更されたか判定する * @return */ protected boolean isCategoryDirty() { boolean ret = false; // 種別設定 DictionarySetting setting = tab.getDictionary().getSetting(); // 固有設定の有無が変更された場合 if (setting.isDefaultCategory() == chkSpecificCategory.getSelection()) { return true; } // 固有設定ありの場合 if (chkSpecificCategory.getSelection()) { // 種別数が異なる場合 if (catItems.size() != setting.categorySize()) { return true; } for (CategoryItem item : catItems) { // 設定済みの種別を取得 Category category = setting.getCategory(item.no); // 種別Noが存在しない場合 if (category == null) { return true; } // 設定内容が異なる場合 if (!item.name.equals(category.getName()) || !item.primary.equals(category.getPrimary()) || !item.secondary.equals(category.getSecondary())) { return true; } } } return ret; } /** * 種別設定の変更内容を辞書オブジェクトへ反映する */ protected void updateCategorySetting() { // 種別設定 DictionarySetting setting = tab.getDictionary().getSetting(); setting.clearCategory(); // 固有設定ありの場合 if (chkSpecificCategory.getSelection()) { setting.setDefaultCategory(false); for (int i=0; i<catItems.size(); i++) { CategoryItem catItem = catItems.get(i); setting.setCategory(catItem.no, catItem.name, catItem.primary, catItem.secondary); } // 固有設定なしの場合 } else { setting.setDefaultCategory(true); } } /** * 入力チェック * @return チェック結果(true = OK/false = NG) */ protected boolean validate() { if (StringUtils.isBlank(txtLanguage.getText())) { MessageDialog.openWarning(getShell(), Messages.DictionaryInformationDialog_3, Messages.DictionaryInformationDialog_11); return false; } return true; } /** * 非形式的定義のリストを取得する * @return 非形式的定義リスト */ private List<List<String>> getInformalsList() { List<List<String>> list = new ArrayList<List<String>>(tab.getDictionary().size()); for (Entry entry : tab.getDictionary().getEntries()) { list.add(entry.copyInformals()); } return list; } /** * 入力言語の変更内容を辞書オブジェクトに反映する */ private void updateLangeuages() { // 変更後の内容を反映 String[] after = txtLanguage.getText().split(","); //$NON-NLS-1$ List<String> newLanguages = new ArrayList<String>(after.length); for (String lang : after) { newLanguages.add(lang.trim()); } tab.getDictionary().updateLangeuages(newLanguages); // カラムの表示/非表示制御 tab.showColumns(DictionaryConstants.DIC_COL_ID_INFORMAL); } @Override public boolean close() { folder.removeSelectionListener(tabListener); boolean ret = super.close(); if (ret) { for (CategoryItem item : colorImageMap.keySet()) { Image[] images = colorImageMap.get(item); for (Image image : images) { if (image != null && !image.isDisposed()) { image.dispose(); } } } } return ret; } /** * ラベルプロバイダー */ private class TableLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object element, int columnIndex) { if (columnIndex < 3) { return null; } CategoryItem item = (CategoryItem)element; int mapIndex = columnIndex - 3; int x = 0; int y = 0; int width = 47; int height = 20; Image image = null; Image[] images = null; if (colorImageMap.containsKey(item)) { images = colorImageMap.get(item); image = images[mapIndex]; if (image != null && !image.isDisposed()) { image.dispose(); } } else { images = new Image[]{null, null}; colorImageMap.put(item, images); } image = new Image(tvCategory.getTable().getDisplay(), new Rectangle(x, y, width, height)); images[mapIndex] = image; GC gc = new GC(image); if (columnIndex == 3) { gc.setBackground(ModelToolDictionaryPlugin.getColorManager().getColor(item.primary)); } else { gc.setBackground(ModelToolDictionaryPlugin.getColorManager().getColor(item.secondary)); } gc.fillRectangle(2, 1, width-3, height-2); gc.setForeground(tvCategory.getTable().getDisplay().getSystemColor(SWT.COLOR_BLACK)); gc.drawRectangle(1, 0, width-2, height-1); gc.dispose(); return image; } public String getColumnText(Object element, int columnIndex) { switch (columnIndex) { case 1: return String.valueOf(((CategoryItem)element).no); case 2: return ((CategoryItem)element).name; // case 2: // return ((CategoryItem)element).primary.toString(); // case 3: // return ((CategoryItem)element).secondary.toString(); } return null; } } /** List⇒カンマ区切り文字列変換 */ private String getCommaSeparatedString(List<String> list) { if (list == null || list.isEmpty()) { return ""; //$NON-NLS-1$ } StringBuilder sb = new StringBuilder(); for (int i=0; i<list.size()-1; i++) { String str = list.get(i); sb.append(str).append(","); //$NON-NLS-1$ } return sb.append(list.get(list.size() - 1)).toString(); } /** TableItem[]⇒カンマ区切り文字列変換 */ private String getCommaSeparatedString(TableItem[] items) { if (items == null || items.length == 0) { return ""; //$NON-NLS-1$ } StringBuilder sb = new StringBuilder(); for (int i=0; i<items.length-1; i++) { String str = items[i].getText(0); sb.append(str).append(","); //$NON-NLS-1$ } return sb.append(items[items.length - 1].getText(0)).toString(); } /** * 種別設定が変更可能かを判定する * @return エントリを辞書編集ビューで開いている場合は変更不可 */ private boolean isCategoryEditable() { return isLanguagesEditable(); } /** * 入力言語が変更可能かを判定する * @return エントリを辞書編集ビューで開いている場合は変更不可 */ private boolean isLanguagesEditable() { for (Entry entry : tab.getDictionary().getEntries()) { if (entry.isEdit()) { return false; } } return true; } /** * 出力モデルが変更可能かを判定する * @return 入力言語と同条件 */ private boolean isModelEditable() { return isLanguagesEditable(); } }
package com.senac.millanches.Modelos; import java.sql.SQLClientInfoException; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class Gerador { private String cliente; private int quantidade; private List<Lista> fakes; public Gerador (String cliente, int quantidade) { this.cliente = cliente; this.quantidade = quantidade; } public List<Lista> geraFakes(){ Faker faker = new Faker (new Locale("pt-BR")); fakes = new ArrayList<>(); for (int = 0, i< quantidade; i++){ switch (cliente){ case: "Clientes": fakes.add(new Lista(faker.name().fullName(), "Cliente")); break; case: "Comidas": fakes.add(new Lista(faker.name().name(), "Comida")); break; } } return fakes; } public String getCliente() { return cliente; } public int getQuantidade() { return quantidade; } public List<Lista> getFakes() { return fakes; } }
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jdbc.datasource.embedded; import javax.sql.DataSource; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.jdbc.datasource.init.DatabasePopulator; import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils; import org.springframework.lang.Nullable; /** * A subclass of {@link EmbeddedDatabaseFactory} that implements {@link FactoryBean} * for registration as a Spring bean. Returns the actual {@link DataSource} that * provides connectivity to the embedded database to Spring. * * <p>The target {@link DataSource} is returned instead of an {@link EmbeddedDatabase} * proxy since the {@link FactoryBean} will manage the initialization and destruction * lifecycle of the embedded database instance. * * <p>Implements {@link DisposableBean} to shut down the embedded database when the * managing Spring container is being closed. * * @author Keith Donald * @author Juergen Hoeller * @since 3.0 */ public class EmbeddedDatabaseFactoryBean extends EmbeddedDatabaseFactory implements FactoryBean<DataSource>, InitializingBean, DisposableBean { @Nullable private DatabasePopulator databaseCleaner; /** * Set a script execution to be run in the bean destruction callback, * cleaning up the database and leaving it in a known state for others. * @param databaseCleaner the database script executor to run on destroy * @see #setDatabasePopulator * @see org.springframework.jdbc.datasource.init.DataSourceInitializer#setDatabaseCleaner */ public void setDatabaseCleaner(DatabasePopulator databaseCleaner) { this.databaseCleaner = databaseCleaner; } @Override public void afterPropertiesSet() { initDatabase(); } @Override @Nullable public DataSource getObject() { return getDataSource(); } @Override public Class<? extends DataSource> getObjectType() { return DataSource.class; } @Override public boolean isSingleton() { return true; } @Override public void destroy() { if (this.databaseCleaner != null && getDataSource() != null) { DatabasePopulatorUtils.execute(this.databaseCleaner, getDataSource()); } shutdownDatabase(); } }
package com.zc.pivas.drugDamage.service; import com.zc.base.orm.mybatis.paging.JqueryStylePaging; import com.zc.base.orm.mybatis.paging.JqueryStylePagingResults; import com.zc.base.sys.modules.user.entity.User; import com.zc.pivas.drugDamage.bean.DrugDamageBean; import com.zc.pivas.drugDamage.bean.DrugDamageProblemOrLink; import com.zc.pivas.medicaments.entity.Medicaments; import java.lang.reflect.InvocationTargetException; import java.util.List; /** * * @author Jack.M * @version 1.0 */ public interface DrugDamageService { /** * 分页查询所有破损药品 * * @param bean * @param paging * @return * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException */ public JqueryStylePagingResults<DrugDamageBean> getAllDrugDamage(DrugDamageBean bean, JqueryStylePaging paging) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException; /** * 添加破损药品 * * @param bean */ public void addDrugDamage(DrugDamageBean bean); /** * 修改破损药品 * * @param bean */ public void updateDrugDamage(DrugDamageBean bean); /** * 删除破损药品 * * @param gid */ public void deleteDrugDamage(Long gid); /** * 根据破损药品ID查询药品详情 * * @param gid * @return */ public DrugDamageBean displayDrugDamage(Long gid); /** * 查询所有药师 * * @return */ public List<User> getAllUsers(); /** * 获取药品 * * @param condition * @return */ public List<Medicaments> queryMedicByCondition(Medicaments condition); /** * 获取质量问题和破损环节 * * @param type * @return */ public List<DrugDamageProblemOrLink> getAlldamageProblemOrLink(String type); }
package com.estsoft.mysite.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.estsoft.mysite.annotation.Auth; import com.estsoft.mysite.annotation.AuthUser; import com.estsoft.mysite.service.BoardService; import com.estsoft.mysite.vo.BoardVo; import com.estsoft.mysite.vo.UserVo; @Controller @RequestMapping("/board") public class BoardController { @Autowired private BoardService boardService; @RequestMapping("") public String list(@RequestParam(value = "kwd", required = true, defaultValue = "") String kwd, @RequestParam(value = "page", required = true, defaultValue = "1") Long page, Model model) { Map<String, Object> map = boardService.SearchList(kwd, page); model.addAttribute("pageinfo", map.get("pageinfo")); model.addAttribute("boardno",map.get("boardno")); model.addAttribute("list",map.get("list")); return "board/list"; } // BoardVo vo =boardService.getView(no, true); // isview @RequestMapping("/view") public String view(@RequestParam(value = "no", required = true, defaultValue = "-1") Long no, Model model,HttpSession session) { BoardVo vo=boardService.getView(no, true); vo.setNo(no); model.addAttribute("vo",vo); return "board/view"; } @RequestMapping("/boardmodifyform") public String boardModifyForm(@ModelAttribute BoardVo vo,Model model) { model.addAttribute("vo", vo); return "board/modify"; } @RequestMapping("/boardmodify") public String boardModify(@ModelAttribute BoardVo vo,HttpSession session) { UserVo userVo = (UserVo)session.getAttribute("authUser"); vo.setUser_no(userVo.getNo()); System.out.println("BC: VO"+vo); BoardVo boardVo=boardService.getView(vo.getNo(), false); boardVo.setNo(vo.getNo()); boardVo.setTitle(vo.getTitle()); boardVo.setContent(vo.getContent()); System.out.println("BC : boardVo"+boardVo); boardService.ModifyUpdate(boardVo); return "redirect:/board"; } @RequestMapping("/writeform") public String writeForm(@ModelAttribute BoardVo vo,Model model) { model.addAttribute("vo",vo); return "board/write"; } @Auth @RequestMapping("/write") //@AuthUser로 받는 parameter는 반드시 인증된 사용자가 넘어오게된다 public String write(@AuthUser UserVo authUser,HttpSession session, @ModelAttribute BoardVo vo) { /*UserVo userVo = (UserVo)session.getAttribute("authUser");*/ System.out.println("write:::::::::::::::::::::::::::::auth::::::::"+authUser); System.out.println("write:::::::::::::::::::::::::::::vo::::::::"+vo); vo.setUser_no(authUser.getNo()); vo.setUser_name(authUser.getName()); if(vo.getNo()!= null){ BoardVo superVo=boardService.getView(vo.getNo(), false); vo.setOrder_no(superVo.getOrder_no()); vo.setDepth(superVo.getDepth()); vo.setGroup_no(superVo.getGroup_no()); } boardService.insert(vo); return "redirect:/board"; } @RequestMapping("/delete") public String delete(@ModelAttribute BoardVo vo) { boardService.delete(vo); return "redirect:/board"; } }
package com.memory.platform.modules.system.base.datalink; import java.util.HashMap; import java.util.Map; import com.memory.platform.modules.system.base.model.SystemDept; import com.memory.platform.modules.system.base.model.SystemRole; import com.memory.platform.modules.system.base.model.SystemUser; public class BasedataLinkHelper { public enum DATATYPE { SYSTEM_USER,SYSTEM_ROLE,SYSTEM_DEPT } private static Map<Class<?>,String> dataTypeMap = new HashMap<Class<?>,String>(); static { dataTypeMap.put(SystemUser.class, DATATYPE.SYSTEM_USER.name()); dataTypeMap.put(SystemRole.class, DATATYPE.SYSTEM_ROLE.name()); dataTypeMap.put(SystemDept.class, DATATYPE.SYSTEM_DEPT.name()); } public static String getDbTypeFlag(Class<?> model) { String flag = dataTypeMap.get(model); return flag; } }
/* * Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.jet.beam.transforms; import org.apache.beam.sdk.PipelineResult; import org.apache.beam.sdk.coders.SerializableCoder; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.junit.Test; import static junit.framework.TestCase.assertEquals; import static org.apache.beam.sdk.TestUtils.LINES; import static org.apache.beam.sdk.TestUtils.LINES_ARRAY; import static org.apache.beam.sdk.TestUtils.NO_LINES_ARRAY; /* "Inspired" by org.apache.beam.sdk.transforms.CreateTest */ @SuppressWarnings("ALL") public class CreateTest extends AbstractTransformTest { @Test public void testCreate() { PCollection<String> output = pipeline.apply(Create.of(LINES)); PAssert.that(output).containsInAnyOrder(LINES_ARRAY); PipelineResult.State state = pipeline.run().waitUntilFinish(); assertEquals(PipelineResult.State.DONE, state); } @Test public void testCreateEmpty() { PCollection<String> output = pipeline.apply(Create.empty(StringUtf8Coder.of())); PAssert.that(output).containsInAnyOrder(NO_LINES_ARRAY); assertEquals(StringUtf8Coder.of(), output.getCoder()); PipelineResult.State state = pipeline.run().waitUntilFinish(); assertEquals(PipelineResult.State.DONE, state); } @Test public void testCreateWithNullsAndValues() throws Exception { PCollection<String> output = pipeline.apply( Create.of(null, "test1", null, "test2", null) .withCoder(SerializableCoder.of(String.class))); PAssert.that(output).containsInAnyOrder(null, "test1", null, "test2", null); PipelineResult.State state = pipeline.run().waitUntilFinish(); assertEquals(PipelineResult.State.DONE, state); } @Test public void testCreateWithVoidType() throws Exception { PCollection<Void> output = pipeline.apply(Create.of(null, (Void) null)); PAssert.that(output).containsInAnyOrder(null, null); PipelineResult.State state = pipeline.run().waitUntilFinish(); assertEquals(PipelineResult.State.DONE, state); } @Test public void testCreateWithKVVoidType() throws Exception { PCollection<KV<Void, Void>> output = pipeline.apply(Create.of(KV.of(null, null), KV.of(null, null))); PAssert.that(output) .containsInAnyOrder(KV.of(null, null), KV.of(null, null)); PipelineResult.State state = pipeline.run().waitUntilFinish(); assertEquals(PipelineResult.State.DONE, state); } }
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.server.vcn; import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED; import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED; import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING; import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED; import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR; import static android.net.NetworkCapabilities.TRANSPORT_WIFI; import static com.android.server.VcnManagementService.VDBG; import android.annotation.NonNull; import android.annotation.Nullable; import android.net.InetAddresses; import android.net.IpPrefix; import android.net.IpSecManager; import android.net.IpSecManager.IpSecTunnelInterface; import android.net.IpSecManager.ResourceUnavailableException; import android.net.IpSecTransform; import android.net.LinkAddress; import android.net.LinkProperties; import android.net.Network; import android.net.NetworkAgent; import android.net.NetworkAgentConfig; import android.net.NetworkCapabilities; import android.net.RouteInfo; import android.net.TelephonyNetworkSpecifier; import android.net.annotations.PolicyDirection; import android.net.ipsec.ike.ChildSessionCallback; import android.net.ipsec.ike.ChildSessionConfiguration; import android.net.ipsec.ike.ChildSessionParams; import android.net.ipsec.ike.IkeSession; import android.net.ipsec.ike.IkeSessionCallback; import android.net.ipsec.ike.IkeSessionConfiguration; import android.net.ipsec.ike.IkeSessionParams; import android.net.ipsec.ike.exceptions.IkeException; import android.net.ipsec.ike.exceptions.IkeProtocolException; import android.net.vcn.VcnGatewayConnectionConfig; import android.net.vcn.VcnTransportInfo; import android.net.wifi.WifiInfo; import android.os.Handler; import android.os.HandlerExecutor; import android.os.Message; import android.os.ParcelUuid; import android.util.ArraySet; import android.util.Slog; import com.android.internal.annotations.VisibleForTesting; import com.android.internal.annotations.VisibleForTesting.Visibility; import com.android.internal.util.State; import com.android.internal.util.StateMachine; import com.android.server.vcn.TelephonySubscriptionTracker.TelephonySubscriptionSnapshot; import com.android.server.vcn.UnderlyingNetworkTracker.UnderlyingNetworkRecord; import com.android.server.vcn.UnderlyingNetworkTracker.UnderlyingNetworkTrackerCallback; import com.android.server.vcn.Vcn.VcnGatewayStatusCallback; import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; /** * A single VCN Gateway Connection, providing a single public-facing VCN network. * * <p>This class handles mobility events, performs retries, and tracks safe-mode conditions. * * <pre>Internal state transitions are as follows: * * +----------------------------+ +------------------------------+ * | DisconnectedState | Teardown or | DisconnectingState | * | |<--no available--| | * | Initial state. | underlying | Transitive state for tearing | * +----------------------------+ networks | tearing down an IKE session. | * | +------------------------------+ * | ^ | * Underlying Network Teardown requested | Not tearing down * changed +--or retriable error--+ and has available * | | occurred underlying network * | ^ | * v | v * +----------------------------+ | +------------------------------+ * | ConnectingState |<----------------| RetryTimeoutState | * | | | | | * | Transitive state for | | | Transitive state for | * | starting IKE negotiation. |---+ | handling retriable errors. | * +----------------------------+ | +------------------------------+ * | | * IKE session | * negotiated | * | | * v | * +----------------------------+ ^ * | ConnectedState | | * | | | * | Stable state where | | * | gateway connection is set | | * | up, and Android Network is | | * | connected. |---+ * +----------------------------+ * </pre> * * @hide */ public class VcnGatewayConnection extends StateMachine { private static final String TAG = VcnGatewayConnection.class.getSimpleName(); private static final int[] MERGED_CAPABILITIES = new int[] {NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_NOT_ROAMING}; private static final InetAddress DUMMY_ADDR = InetAddresses.parseNumericAddress("192.0.2.0"); private static final int ARG_NOT_PRESENT = Integer.MIN_VALUE; private static final String DISCONNECT_REASON_INTERNAL_ERROR = "Uncaught exception: "; private static final String DISCONNECT_REASON_UNDERLYING_NETWORK_LOST = "Underlying Network lost"; private static final String DISCONNECT_REASON_TEARDOWN = "teardown() called on VcnTunnel"; private static final int TOKEN_ALL = Integer.MIN_VALUE; private static final int NETWORK_LOSS_DISCONNECT_TIMEOUT_SECONDS = 30; @VisibleForTesting(visibility = Visibility.PRIVATE) static final int TEARDOWN_TIMEOUT_SECONDS = 5; private interface EventInfo {} /** * Sent when there are changes to the underlying network (per the UnderlyingNetworkTracker). * * <p>May indicate an entirely new underlying network, OR a change in network properties. * * <p>Relevant in ALL states. * * <p>In the Connected state, this MAY indicate a mobility even occurred. * * @param arg1 The "all" token; this event is always applicable. * @param obj @NonNull An EventUnderlyingNetworkChangedInfo instance with relevant data. */ private static final int EVENT_UNDERLYING_NETWORK_CHANGED = 1; private static class EventUnderlyingNetworkChangedInfo implements EventInfo { @Nullable public final UnderlyingNetworkRecord newUnderlying; EventUnderlyingNetworkChangedInfo(@Nullable UnderlyingNetworkRecord newUnderlying) { this.newUnderlying = newUnderlying; } @Override public int hashCode() { return Objects.hash(newUnderlying); } @Override public boolean equals(@Nullable Object other) { if (!(other instanceof EventUnderlyingNetworkChangedInfo)) { return false; } final EventUnderlyingNetworkChangedInfo rhs = (EventUnderlyingNetworkChangedInfo) other; return Objects.equals(newUnderlying, rhs.newUnderlying); } } /** * Sent (delayed) to trigger an attempt to reestablish the tunnel. * * <p>Only relevant in the Retry-timeout state, discarded in all other states. * * <p>Upon receipt of this signal, the state machine will transition from the Retry-timeout * state to the Connecting state. * * @param arg1 The "all" token; no sessions are active in the RetryTimeoutState. */ private static final int EVENT_RETRY_TIMEOUT_EXPIRED = 2; /** * Sent when a gateway connection has been lost, either due to a IKE or child failure. * * <p>Relevant in all states that have an IKE session. * * <p>Upon receipt of this signal, the state machine will (unless loss of the session is * expected) transition to the Disconnecting state, to ensure IKE session closure before * retrying, or fully shutting down. * * @param arg1 The session token for the IKE Session that was lost, used to prevent out-of-date * signals from propagating. * @param obj @NonNull An EventSessionLostInfo instance with relevant data. */ private static final int EVENT_SESSION_LOST = 3; private static class EventSessionLostInfo implements EventInfo { @Nullable public final Exception exception; EventSessionLostInfo(@NonNull Exception exception) { this.exception = exception; } @Override public int hashCode() { return Objects.hash(exception); } @Override public boolean equals(@Nullable Object other) { if (!(other instanceof EventSessionLostInfo)) { return false; } final EventSessionLostInfo rhs = (EventSessionLostInfo) other; return Objects.equals(exception, rhs.exception); } } /** * Sent when an IKE session has completely closed. * * <p>Relevant only in the Disconnecting State, used to identify that a session being torn down * was fully closed. If this event is not fired within a timely fashion, the IKE session will be * forcibly terminated. * * <p>Upon receipt of this signal, the state machine will (unless closure of the session is * expected) transition to the Disconnected or RetryTimeout states, depending on whether the * GatewayConnection is being fully torn down. * * @param arg1 The session token for the IKE Session that was lost, used to prevent out-of-date * signals from propagating. * @param obj @NonNull An EventSessionLostInfo instance with relevant data. */ private static final int EVENT_SESSION_CLOSED = 4; /** * Sent when an IKE Child Transform was created, and should be applied to the tunnel. * * <p>Only relevant in the Connecting, Connected and Migrating states. This callback MUST be * handled in the Connected or Migrating states, and should be deferred if necessary. * * @param arg1 The session token for the IKE Session that had a new child created, used to * prevent out-of-date signals from propagating. * @param obj @NonNull An EventTransformCreatedInfo instance with relevant data. */ private static final int EVENT_TRANSFORM_CREATED = 5; private static class EventTransformCreatedInfo implements EventInfo { @PolicyDirection public final int direction; @NonNull public final IpSecTransform transform; EventTransformCreatedInfo( @PolicyDirection int direction, @NonNull IpSecTransform transform) { this.direction = direction; this.transform = Objects.requireNonNull(transform); } @Override public int hashCode() { return Objects.hash(direction, transform); } @Override public boolean equals(@Nullable Object other) { if (!(other instanceof EventTransformCreatedInfo)) { return false; } final EventTransformCreatedInfo rhs = (EventTransformCreatedInfo) other; return direction == rhs.direction && Objects.equals(transform, rhs.transform); } } /** * Sent when an IKE Child Session was completely opened and configured successfully. * * <p>Only relevant in the Connected and Migrating states. * * @param arg1 The session token for the IKE Session for which a child was opened and configured * successfully, used to prevent out-of-date signals from propagating. * @param obj @NonNull An EventSetupCompletedInfo instance with relevant data. */ private static final int EVENT_SETUP_COMPLETED = 6; private static class EventSetupCompletedInfo implements EventInfo { @NonNull public final VcnChildSessionConfiguration childSessionConfig; EventSetupCompletedInfo(@NonNull VcnChildSessionConfiguration childSessionConfig) { this.childSessionConfig = Objects.requireNonNull(childSessionConfig); } @Override public int hashCode() { return Objects.hash(childSessionConfig); } @Override public boolean equals(@Nullable Object other) { if (!(other instanceof EventSetupCompletedInfo)) { return false; } final EventSetupCompletedInfo rhs = (EventSetupCompletedInfo) other; return Objects.equals(childSessionConfig, rhs.childSessionConfig); } } /** * Sent when conditions (internal or external) require a disconnect. * * <p>Relevant in all states except the Disconnected state. * * <p>This signal is often fired with a timeout in order to prevent disconnecting during * transient conditions, such as network switches. Upon the transient passing, the signal is * canceled based on the disconnect reason. * * <p>Upon receipt of this signal, the state machine MUST tear down all active sessions, cancel * any pending work items, and move to the Disconnected state. * * @param arg1 The "all" token; this signal is always honored. * @param obj @NonNull An EventDisconnectRequestedInfo instance with relevant data. */ private static final int EVENT_DISCONNECT_REQUESTED = 7; private static class EventDisconnectRequestedInfo implements EventInfo { /** The reason why the disconnect was requested. */ @NonNull public final String reason; EventDisconnectRequestedInfo(@NonNull String reason) { this.reason = Objects.requireNonNull(reason); } @Override public int hashCode() { return Objects.hash(reason); } @Override public boolean equals(@Nullable Object other) { if (!(other instanceof EventDisconnectRequestedInfo)) { return false; } final EventDisconnectRequestedInfo rhs = (EventDisconnectRequestedInfo) other; return reason.equals(rhs.reason); } } /** * Sent (delayed) to trigger a forcible close of an IKE session. * * <p>Only relevant in the Disconnecting state, discarded in all other states. * * <p>Upon receipt of this signal, the state machine will transition from the Disconnecting * state to the Disconnected state. * * @param arg1 The session token for the IKE Session that is being torn down, used to prevent * out-of-date signals from propagating. */ private static final int EVENT_TEARDOWN_TIMEOUT_EXPIRED = 8; /** * Sent when this VcnGatewayConnection is notified of a change in TelephonySubscriptions. * * <p>Relevant in all states. * * @param arg1 The "all" token; this signal is always honored. */ // TODO(b/178426520): implement handling of this event private static final int EVENT_SUBSCRIPTIONS_CHANGED = 9; @VisibleForTesting(visibility = Visibility.PRIVATE) @NonNull final DisconnectedState mDisconnectedState = new DisconnectedState(); @VisibleForTesting(visibility = Visibility.PRIVATE) @NonNull final DisconnectingState mDisconnectingState = new DisconnectingState(); @VisibleForTesting(visibility = Visibility.PRIVATE) @NonNull final ConnectingState mConnectingState = new ConnectingState(); @VisibleForTesting(visibility = Visibility.PRIVATE) @NonNull final ConnectedState mConnectedState = new ConnectedState(); @VisibleForTesting(visibility = Visibility.PRIVATE) @NonNull final RetryTimeoutState mRetryTimeoutState = new RetryTimeoutState(); @NonNull private TelephonySubscriptionSnapshot mLastSnapshot; @NonNull private final VcnContext mVcnContext; @NonNull private final ParcelUuid mSubscriptionGroup; @NonNull private final UnderlyingNetworkTracker mUnderlyingNetworkTracker; @NonNull private final VcnGatewayConnectionConfig mConnectionConfig; @NonNull private final VcnGatewayStatusCallback mGatewayStatusCallback; @NonNull private final Dependencies mDeps; @NonNull private final VcnUnderlyingNetworkTrackerCallback mUnderlyingNetworkTrackerCallback; @NonNull private final IpSecManager mIpSecManager; @NonNull private final IpSecTunnelInterface mTunnelIface; /** Running state of this VcnGatewayConnection. */ private boolean mIsRunning = true; /** * The token used by the primary/current/active session. * * <p>This token MUST be updated when a new stateful/async session becomes the * primary/current/active session. Example cases where the session changes are: * * <ul> * <li>Switching to an IKE session as the primary session * </ul> * * <p>In the migrating state, where two sessions may be active, this value MUST represent the * primary session. This is USUALLY the existing session, and is only switched to the new * session when: * * <ul> * <li>The new session connects successfully, and becomes the primary session * <li>The existing session is lost, and the remaining (new) session becomes the primary * session * </ul> */ private int mCurrentToken = -1; /** * The number of unsuccessful attempts since the last successful connection. * * <p>This number MUST be incremented each time the RetryTimeout state is entered, and cleared * each time the Connected state is entered. */ private int mFailedAttempts = 0; /** * The current underlying network. * * <p>Set in any states, always @NonNull in all states except Disconnected, null otherwise. */ private UnderlyingNetworkRecord mUnderlying; /** * The active IKE session. * * <p>Set in Connecting or Migrating States, always @NonNull in Connecting, Connected, and * Migrating states, null otherwise. */ private VcnIkeSession mIkeSession; /** * The last known child configuration. * * <p>Set in Connected and Migrating states, always @NonNull in Connected, Migrating * states, @Nullable otherwise. */ private VcnChildSessionConfiguration mChildConfig; /** * The active network agent. * * <p>Set in Connected state, always @NonNull in Connected, Migrating states, @Nullable * otherwise. */ private NetworkAgent mNetworkAgent; public VcnGatewayConnection( @NonNull VcnContext vcnContext, @NonNull ParcelUuid subscriptionGroup, @NonNull TelephonySubscriptionSnapshot snapshot, @NonNull VcnGatewayConnectionConfig connectionConfig, @NonNull VcnGatewayStatusCallback gatewayStatusCallback) { this( vcnContext, subscriptionGroup, snapshot, connectionConfig, gatewayStatusCallback, new Dependencies()); } @VisibleForTesting(visibility = Visibility.PRIVATE) VcnGatewayConnection( @NonNull VcnContext vcnContext, @NonNull ParcelUuid subscriptionGroup, @NonNull TelephonySubscriptionSnapshot snapshot, @NonNull VcnGatewayConnectionConfig connectionConfig, @NonNull VcnGatewayStatusCallback gatewayStatusCallback, @NonNull Dependencies deps) { super(TAG, Objects.requireNonNull(vcnContext, "Missing vcnContext").getLooper()); mVcnContext = vcnContext; mSubscriptionGroup = Objects.requireNonNull(subscriptionGroup, "Missing subscriptionGroup"); mConnectionConfig = Objects.requireNonNull(connectionConfig, "Missing connectionConfig"); mGatewayStatusCallback = Objects.requireNonNull(gatewayStatusCallback, "Missing gatewayStatusCallback"); mDeps = Objects.requireNonNull(deps, "Missing deps"); mLastSnapshot = Objects.requireNonNull(snapshot, "Missing snapshot"); mUnderlyingNetworkTrackerCallback = new VcnUnderlyingNetworkTrackerCallback(); mUnderlyingNetworkTracker = mDeps.newUnderlyingNetworkTracker( mVcnContext, subscriptionGroup, mLastSnapshot, mConnectionConfig.getAllUnderlyingCapabilities(), mUnderlyingNetworkTrackerCallback); mIpSecManager = mVcnContext.getContext().getSystemService(IpSecManager.class); IpSecTunnelInterface iface; try { iface = mIpSecManager.createIpSecTunnelInterface( DUMMY_ADDR, DUMMY_ADDR, new Network(-1)); } catch (IOException | ResourceUnavailableException e) { teardownAsynchronously(); mTunnelIface = null; return; } mTunnelIface = iface; addState(mDisconnectedState); addState(mDisconnectingState); addState(mConnectingState); addState(mConnectedState); addState(mRetryTimeoutState); setInitialState(mDisconnectedState); setDbg(VDBG); start(); } /** * Asynchronously tears down this GatewayConnection, and any resources used. * * <p>Once torn down, this VcnTunnel CANNOT be started again. */ public void teardownAsynchronously() { sendMessage( EVENT_DISCONNECT_REQUESTED, TOKEN_ALL, new EventDisconnectRequestedInfo(DISCONNECT_REASON_TEARDOWN)); // TODO: Notify VcnInstance (via callbacks) of permanent teardown of this tunnel, since this // is also called asynchronously when a NetworkAgent becomes unwanted } @Override protected void onQuitting() { // No need to call setInterfaceDown(); the IpSecInterface is being fully torn down. if (mTunnelIface != null) { mTunnelIface.close(); } mUnderlyingNetworkTracker.teardown(); } /** * Notify this Gateway that subscriptions have changed. * * <p>This snapshot should be used to update any keepalive requests necessary for potential * underlying Networks in this Gateway's subscription group. */ public void updateSubscriptionSnapshot(@NonNull TelephonySubscriptionSnapshot snapshot) { Objects.requireNonNull(snapshot, "Missing snapshot"); mVcnContext.ensureRunningOnLooperThread(); mLastSnapshot = snapshot; mUnderlyingNetworkTracker.updateSubscriptionSnapshot(mLastSnapshot); sendMessage(EVENT_SUBSCRIPTIONS_CHANGED, TOKEN_ALL); } private class VcnUnderlyingNetworkTrackerCallback implements UnderlyingNetworkTrackerCallback { @Override public void onSelectedUnderlyingNetworkChanged( @Nullable UnderlyingNetworkRecord underlying) { // TODO(b/179091925): Move the delayed-message handling to BaseState // If underlying is null, all underlying networks have been lost. Disconnect VCN after a // timeout. if (underlying == null) { sendMessageDelayed( EVENT_DISCONNECT_REQUESTED, TOKEN_ALL, new EventDisconnectRequestedInfo(DISCONNECT_REASON_UNDERLYING_NETWORK_LOST), TimeUnit.SECONDS.toMillis(NETWORK_LOSS_DISCONNECT_TIMEOUT_SECONDS)); } else if (getHandler() != null) { // Cancel any existing disconnect due to loss of underlying network // getHandler() can return null if the state machine has already quit. Since this is // called from other classes, this condition must be verified. getHandler() .removeEqualMessages( EVENT_DISCONNECT_REQUESTED, new EventDisconnectRequestedInfo( DISCONNECT_REASON_UNDERLYING_NETWORK_LOST)); } sendMessage( EVENT_UNDERLYING_NETWORK_CHANGED, TOKEN_ALL, new EventUnderlyingNetworkChangedInfo(underlying)); } } private void sendMessage(int what, int token, EventInfo data) { super.sendMessage(what, token, ARG_NOT_PRESENT, data); } private void sendMessage(int what, int token, int arg2, EventInfo data) { super.sendMessage(what, token, arg2, data); } private void sendMessageDelayed(int what, int token, EventInfo data, long timeout) { super.sendMessageDelayed(what, token, ARG_NOT_PRESENT, data, timeout); } private void sendMessageDelayed(int what, int token, int arg2, EventInfo data, long timeout) { super.sendMessageDelayed(what, token, arg2, data, timeout); } private void sessionLost(int token, @Nullable Exception exception) { sendMessage(EVENT_SESSION_LOST, token, new EventSessionLostInfo(exception)); } private void sessionClosed(int token, @Nullable Exception exception) { // SESSION_LOST MUST be sent before SESSION_CLOSED to ensure that the SM moves to the // Disconnecting state. sessionLost(token, exception); sendMessage(EVENT_SESSION_CLOSED, token); } private void childTransformCreated( int token, @NonNull IpSecTransform transform, int direction) { sendMessage( EVENT_TRANSFORM_CREATED, token, new EventTransformCreatedInfo(direction, transform)); } private void childOpened(int token, @NonNull VcnChildSessionConfiguration childConfig) { sendMessage(EVENT_SETUP_COMPLETED, token, new EventSetupCompletedInfo(childConfig)); } private abstract class BaseState extends State { @Override public void enter() { try { enterState(); } catch (Exception e) { Slog.wtf(TAG, "Uncaught exception", e); sendMessage( EVENT_DISCONNECT_REQUESTED, TOKEN_ALL, new EventDisconnectRequestedInfo( DISCONNECT_REASON_INTERNAL_ERROR + e.toString())); } } protected void enterState() throws Exception {} /** * Top-level processMessage with safeguards to prevent crashing the System Server on non-eng * builds. */ @Override public boolean processMessage(Message msg) { try { processStateMsg(msg); } catch (Exception e) { Slog.wtf(TAG, "Uncaught exception", e); sendMessage( EVENT_DISCONNECT_REQUESTED, TOKEN_ALL, new EventDisconnectRequestedInfo( DISCONNECT_REASON_INTERNAL_ERROR + e.toString())); } return HANDLED; } protected abstract void processStateMsg(Message msg) throws Exception; @Override public void exit() { try { exitState(); } catch (Exception e) { Slog.wtf(TAG, "Uncaught exception", e); sendMessage( EVENT_DISCONNECT_REQUESTED, TOKEN_ALL, new EventDisconnectRequestedInfo( DISCONNECT_REASON_INTERNAL_ERROR + e.toString())); } } protected void exitState() throws Exception {} protected void logUnhandledMessage(Message msg) { // Log as unexpected all known messages, and log all else as unknown. switch (msg.what) { case EVENT_UNDERLYING_NETWORK_CHANGED: // Fallthrough case EVENT_RETRY_TIMEOUT_EXPIRED: // Fallthrough case EVENT_SESSION_LOST: // Fallthrough case EVENT_SESSION_CLOSED: // Fallthrough case EVENT_TRANSFORM_CREATED: // Fallthrough case EVENT_SETUP_COMPLETED: // Fallthrough case EVENT_DISCONNECT_REQUESTED: // Fallthrough case EVENT_TEARDOWN_TIMEOUT_EXPIRED: // Fallthrough case EVENT_SUBSCRIPTIONS_CHANGED: logUnexpectedEvent(msg.what); break; default: logWtfUnknownEvent(msg.what); break; } } protected void teardownNetwork() { if (mNetworkAgent != null) { mNetworkAgent.unregister(); mNetworkAgent = null; } } protected void handleDisconnectRequested(String msg) { Slog.v(TAG, "Tearing down. Cause: " + msg); mIsRunning = false; teardownNetwork(); if (mIkeSession == null) { // Already disconnected, go straight to DisconnectedState transitionTo(mDisconnectedState); } else { // Still need to wait for full closure transitionTo(mDisconnectingState); } } protected void logUnexpectedEvent(int what) { Slog.d(TAG, String.format( "Unexpected event code %d in state %s", what, this.getClass().getSimpleName())); } protected void logWtfUnknownEvent(int what) { Slog.wtf(TAG, String.format( "Unknown event code %d in state %s", what, this.getClass().getSimpleName())); } } /** * State representing the a disconnected VCN tunnel. * * <p>This is also is the initial state. */ private class DisconnectedState extends BaseState { @Override protected void enterState() { if (!mIsRunning) { quitNow(); // Ignore all queued events; cleanup is complete. } if (mIkeSession != null || mNetworkAgent != null) { Slog.wtf(TAG, "Active IKE Session or NetworkAgent in DisconnectedState"); } } @Override protected void processStateMsg(Message msg) { switch (msg.what) { case EVENT_UNDERLYING_NETWORK_CHANGED: // First network found; start tunnel mUnderlying = ((EventUnderlyingNetworkChangedInfo) msg.obj).newUnderlying; if (mUnderlying != null) { transitionTo(mConnectingState); } break; case EVENT_DISCONNECT_REQUESTED: mIsRunning = false; quitNow(); break; default: logUnhandledMessage(msg); break; } } } private abstract class ActiveBaseState extends BaseState { /** * Handles all incoming messages, discarding messages for previous networks. * * <p>States that handle mobility events may need to override this method to receive * messages for all underlying networks. */ @Override public boolean processMessage(Message msg) { final int token = msg.arg1; // Only process if a valid token is presented. if (isValidToken(token)) { return super.processMessage(msg); } Slog.v(TAG, "Message called with obsolete token: " + token + "; what: " + msg.what); return HANDLED; } protected boolean isValidToken(int token) { return (token == TOKEN_ALL || token == mCurrentToken); } } /** * Transitive state representing a VCN that is tearing down an IKE session. * * <p>In this state, the IKE session is in the process of being torn down. If the IKE session * does not complete teardown in a timely fashion, it will be killed (forcibly closed). */ private class DisconnectingState extends ActiveBaseState { /** * Whether to skip the RetryTimeoutState and go straight to the ConnectingState. * * <p>This is used when an underlying network change triggered a restart on a new network. * * <p>Reset (to false) upon exit of the DisconnectingState. */ private boolean mSkipRetryTimeout = false; // TODO(b/178441390): Remove this in favor of resetting retry timers on UND_NET change. public void setSkipRetryTimeout(boolean shouldSkip) { mSkipRetryTimeout = shouldSkip; } @Override protected void enterState() throws Exception { if (mIkeSession == null) { Slog.wtf(TAG, "IKE session was already closed when entering Disconnecting state."); sendMessage(EVENT_SESSION_CLOSED, mCurrentToken); return; } // If underlying network has already been lost, save some time and just kill the session if (mUnderlying == null) { // Will trigger a EVENT_SESSION_CLOSED as IkeSession shuts down. mIkeSession.kill(); return; } mIkeSession.close(); sendMessageDelayed( EVENT_TEARDOWN_TIMEOUT_EXPIRED, mCurrentToken, TimeUnit.SECONDS.toMillis(TEARDOWN_TIMEOUT_SECONDS)); } @Override protected void processStateMsg(Message msg) { switch (msg.what) { case EVENT_UNDERLYING_NETWORK_CHANGED: // Fallthrough mUnderlying = ((EventUnderlyingNetworkChangedInfo) msg.obj).newUnderlying; // If we received a new underlying network, continue. if (mUnderlying != null) { break; } // Fallthrough; no network exists to send IKE close session requests. case EVENT_TEARDOWN_TIMEOUT_EXPIRED: // Grace period ended. Kill session, triggering EVENT_SESSION_CLOSED mIkeSession.kill(); break; case EVENT_DISCONNECT_REQUESTED: teardownNetwork(); String reason = ((EventDisconnectRequestedInfo) msg.obj).reason; if (reason.equals(DISCONNECT_REASON_UNDERLYING_NETWORK_LOST)) { // Will trigger EVENT_SESSION_CLOSED immediately. mIkeSession.kill(); break; } // Otherwise we are already in the process of shutting down. break; case EVENT_SESSION_CLOSED: mIkeSession = null; if (mIsRunning && mUnderlying != null) { transitionTo(mSkipRetryTimeout ? mConnectingState : mRetryTimeoutState); } else { teardownNetwork(); transitionTo(mDisconnectedState); } break; default: logUnhandledMessage(msg); break; } } @Override protected void exitState() throws Exception { mSkipRetryTimeout = false; } } /** * Transitive state representing a VCN that is making an primary (non-handover) connection. * * <p>This state starts IKE negotiation, but defers transform application & network setup to the * Connected state. */ private class ConnectingState extends ActiveBaseState { @Override protected void enterState() { if (mIkeSession != null) { Slog.wtf(TAG, "ConnectingState entered with active session"); // Attempt to recover. mIkeSession.kill(); mIkeSession = null; } mIkeSession = buildIkeSession(); } @Override protected void processStateMsg(Message msg) { switch (msg.what) { case EVENT_UNDERLYING_NETWORK_CHANGED: final UnderlyingNetworkRecord oldUnderlying = mUnderlying; mUnderlying = ((EventUnderlyingNetworkChangedInfo) msg.obj).newUnderlying; if (oldUnderlying == null) { // This should never happen, but if it does, there's likely a nasty bug. Slog.wtf(TAG, "Old underlying network was null in connected state. Bug?"); } // If new underlying is null, all underlying networks have been lost; disconnect if (mUnderlying == null) { transitionTo(mDisconnectingState); break; } if (oldUnderlying != null && mUnderlying.network.equals(oldUnderlying.network)) { break; // Only network properties have changed; continue connecting. } // Else, retry on the new network. // Immediately come back to the ConnectingState (skip RetryTimeout, since this // isn't a failure) mDisconnectingState.setSkipRetryTimeout(true); // fallthrough - disconnect, and retry on new network. case EVENT_SESSION_LOST: transitionTo(mDisconnectingState); break; case EVENT_SESSION_CLOSED: // Disconnecting state waits for EVENT_SESSION_CLOSED to shutdown, and this // message may not be posted again. Defer to ensure immediate shutdown. deferMessage(msg); transitionTo(mDisconnectingState); break; case EVENT_SETUP_COMPLETED: // fallthrough case EVENT_TRANSFORM_CREATED: // Child setup complete; move to ConnectedState for NetworkAgent registration deferMessage(msg); transitionTo(mConnectedState); break; case EVENT_DISCONNECT_REQUESTED: handleDisconnectRequested(((EventDisconnectRequestedInfo) msg.obj).reason); break; default: logUnhandledMessage(msg); break; } } } private abstract class ConnectedStateBase extends ActiveBaseState { protected void updateNetworkAgent( @NonNull IpSecTunnelInterface tunnelIface, @NonNull NetworkAgent agent, @NonNull VcnChildSessionConfiguration childConfig) { final NetworkCapabilities caps = buildNetworkCapabilities(mConnectionConfig, mUnderlying); final LinkProperties lp = buildConnectedLinkProperties(mConnectionConfig, tunnelIface, childConfig); agent.sendNetworkCapabilities(caps); agent.sendLinkProperties(lp); } protected NetworkAgent buildNetworkAgent( @NonNull IpSecTunnelInterface tunnelIface, @NonNull VcnChildSessionConfiguration childConfig) { final NetworkCapabilities caps = buildNetworkCapabilities(mConnectionConfig, mUnderlying); final LinkProperties lp = buildConnectedLinkProperties(mConnectionConfig, tunnelIface, childConfig); final NetworkAgent agent = new NetworkAgent( mVcnContext.getContext(), mVcnContext.getLooper(), TAG, caps, lp, Vcn.getNetworkScore(), new NetworkAgentConfig(), mVcnContext.getVcnNetworkProvider()) { @Override public void unwanted() { teardownAsynchronously(); } }; agent.register(); agent.markConnected(); return agent; } protected void applyTransform( int token, @NonNull IpSecTunnelInterface tunnelIface, @NonNull Network underlyingNetwork, @NonNull IpSecTransform transform, int direction) { try { // TODO: Set underlying network of tunnel interface // Transforms do not need to be persisted; the IkeSession will keep them alive mIpSecManager.applyTunnelModeTransform(tunnelIface, direction, transform); } catch (IOException e) { Slog.d(TAG, "Transform application failed for network " + token, e); sessionLost(token, e); } } protected void setupInterface( int token, @NonNull IpSecTunnelInterface tunnelIface, @NonNull VcnChildSessionConfiguration childConfig) { setupInterface(token, tunnelIface, childConfig, null); } protected void setupInterface( int token, @NonNull IpSecTunnelInterface tunnelIface, @NonNull VcnChildSessionConfiguration childConfig, @Nullable VcnChildSessionConfiguration oldChildConfig) { try { final Set<LinkAddress> newAddrs = new ArraySet<>(childConfig.getInternalAddresses()); final Set<LinkAddress> existingAddrs = new ArraySet<>(); if (oldChildConfig != null) { existingAddrs.addAll(oldChildConfig.getInternalAddresses()); } final Set<LinkAddress> toAdd = new ArraySet<>(); toAdd.addAll(newAddrs); toAdd.removeAll(existingAddrs); final Set<LinkAddress> toRemove = new ArraySet<>(); toRemove.addAll(existingAddrs); toRemove.removeAll(newAddrs); for (LinkAddress address : toAdd) { tunnelIface.addAddress(address.getAddress(), address.getPrefixLength()); } for (LinkAddress address : toRemove) { tunnelIface.removeAddress(address.getAddress(), address.getPrefixLength()); } } catch (IOException e) { Slog.d(TAG, "Adding address to tunnel failed for token " + token, e); sessionLost(token, e); } } } /** * Stable state representing a VCN that has a functioning connection to the mobility anchor. * * <p>This state handles IPsec transform application (initial and rekey), NetworkAgent setup, * and monitors for mobility events. */ class ConnectedState extends ConnectedStateBase { @Override protected void enterState() throws Exception { // Successful connection, clear failed attempt counter mFailedAttempts = 0; } @Override protected void processStateMsg(Message msg) { switch (msg.what) { case EVENT_UNDERLYING_NETWORK_CHANGED: handleUnderlyingNetworkChanged(msg); break; case EVENT_SESSION_CLOSED: // Disconnecting state waits for EVENT_SESSION_CLOSED to shutdown, and this // message may not be posted again. Defer to ensure immediate shutdown. deferMessage(msg); transitionTo(mDisconnectingState); break; case EVENT_SESSION_LOST: transitionTo(mDisconnectingState); break; case EVENT_TRANSFORM_CREATED: final EventTransformCreatedInfo transformCreatedInfo = (EventTransformCreatedInfo) msg.obj; applyTransform( mCurrentToken, mTunnelIface, mUnderlying.network, transformCreatedInfo.transform, transformCreatedInfo.direction); break; case EVENT_SETUP_COMPLETED: mChildConfig = ((EventSetupCompletedInfo) msg.obj).childSessionConfig; setupInterfaceAndNetworkAgent(mCurrentToken, mTunnelIface, mChildConfig); break; case EVENT_DISCONNECT_REQUESTED: handleDisconnectRequested(((EventDisconnectRequestedInfo) msg.obj).reason); break; default: logUnhandledMessage(msg); break; } } private void handleUnderlyingNetworkChanged(@NonNull Message msg) { final UnderlyingNetworkRecord oldUnderlying = mUnderlying; mUnderlying = ((EventUnderlyingNetworkChangedInfo) msg.obj).newUnderlying; if (mUnderlying == null) { // Ignored for now; a new network may be coming up. If none does, the delayed // NETWORK_LOST disconnect will be fired, and tear down the session + network. return; } // mUnderlying assumed non-null, given check above. // If network changed, migrate. Otherwise, update any existing networkAgent. if (oldUnderlying == null || !oldUnderlying.network.equals(mUnderlying.network)) { mIkeSession.setNetwork(mUnderlying.network); } else { // oldUnderlying is non-null & underlying network itself has not changed // (only network properties were changed). // Network not yet set up, or child not yet connected. if (mNetworkAgent != null && mChildConfig != null) { // If only network properties changed and agent is active, update properties updateNetworkAgent(mTunnelIface, mNetworkAgent, mChildConfig); } } } protected void setupInterfaceAndNetworkAgent( int token, @NonNull IpSecTunnelInterface tunnelIface, @NonNull VcnChildSessionConfiguration childConfig) { setupInterface(token, tunnelIface, childConfig); if (mNetworkAgent == null) { mNetworkAgent = buildNetworkAgent(tunnelIface, childConfig); } else { updateNetworkAgent(tunnelIface, mNetworkAgent, childConfig); } } } /** * Transitive state representing a VCN that failed to establish a connection, and will retry. * * <p>This state will be exited upon a new underlying network being found, or timeout expiry. */ class RetryTimeoutState extends ActiveBaseState { @Override protected void enterState() throws Exception { // Reset upon entry to ConnectedState mFailedAttempts++; if (mUnderlying == null) { Slog.wtf(TAG, "Underlying network was null in retry state"); transitionTo(mDisconnectedState); } else { sendMessageDelayed( EVENT_RETRY_TIMEOUT_EXPIRED, mCurrentToken, getNextRetryIntervalsMs()); } } @Override protected void processStateMsg(Message msg) { switch (msg.what) { case EVENT_UNDERLYING_NETWORK_CHANGED: final UnderlyingNetworkRecord oldUnderlying = mUnderlying; mUnderlying = ((EventUnderlyingNetworkChangedInfo) msg.obj).newUnderlying; // If new underlying is null, all networks were lost; go back to disconnected. if (mUnderlying == null) { removeMessages(EVENT_RETRY_TIMEOUT_EXPIRED); transitionTo(mDisconnectedState); return; } else if (oldUnderlying != null && mUnderlying.network.equals(oldUnderlying.network)) { // If the network has not changed, do nothing. return; } // Fallthrough case EVENT_RETRY_TIMEOUT_EXPIRED: removeMessages(EVENT_RETRY_TIMEOUT_EXPIRED); transitionTo(mConnectingState); break; case EVENT_DISCONNECT_REQUESTED: handleDisconnectRequested(((EventDisconnectRequestedInfo) msg.obj).reason); break; default: logUnhandledMessage(msg); break; } } private long getNextRetryIntervalsMs() { final int retryDelayIndex = mFailedAttempts - 1; final long[] retryIntervalsMs = mConnectionConfig.getRetryIntervalsMs(); // Repeatedly use last item in retry timeout list. if (retryDelayIndex >= retryIntervalsMs.length) { return retryIntervalsMs[retryIntervalsMs.length - 1]; } return retryIntervalsMs[retryDelayIndex]; } } @VisibleForTesting(visibility = Visibility.PRIVATE) static NetworkCapabilities buildNetworkCapabilities( @NonNull VcnGatewayConnectionConfig gatewayConnectionConfig, @Nullable UnderlyingNetworkRecord underlying) { final NetworkCapabilities.Builder builder = new NetworkCapabilities.Builder(); builder.addTransportType(TRANSPORT_CELLULAR); builder.addCapability(NET_CAPABILITY_NOT_CONGESTED); builder.addCapability(NET_CAPABILITY_NOT_SUSPENDED); // Add exposed capabilities for (int cap : gatewayConnectionConfig.getAllExposedCapabilities()) { builder.addCapability(cap); } if (underlying != null) { final NetworkCapabilities underlyingCaps = underlying.networkCapabilities; // Mirror merged capabilities. for (int cap : MERGED_CAPABILITIES) { if (underlyingCaps.hasCapability(cap)) { builder.addCapability(cap); } } // Set admin UIDs for ConnectivityDiagnostics use. final int[] underlyingAdminUids = underlyingCaps.getAdministratorUids(); Arrays.sort(underlyingAdminUids); // Sort to allow contains check below. final int[] adminUids; if (underlyingCaps.getOwnerUid() > 0 // No owner UID specified && 0 > Arrays.binarySearch(// Owner UID not found in admin UID list. underlyingAdminUids, underlyingCaps.getOwnerUid())) { adminUids = Arrays.copyOf(underlyingAdminUids, underlyingAdminUids.length + 1); adminUids[adminUids.length - 1] = underlyingCaps.getOwnerUid(); Arrays.sort(adminUids); } else { adminUids = underlyingAdminUids; } builder.setAdministratorUids(adminUids); // Set TransportInfo for SysUI use (never parcelled out of SystemServer). if (underlyingCaps.hasTransport(TRANSPORT_WIFI) && underlyingCaps.getTransportInfo() instanceof WifiInfo) { final WifiInfo wifiInfo = (WifiInfo) underlyingCaps.getTransportInfo(); builder.setTransportInfo(new VcnTransportInfo(wifiInfo)); } else if (underlyingCaps.hasTransport(TRANSPORT_CELLULAR) && underlyingCaps.getNetworkSpecifier() instanceof TelephonyNetworkSpecifier) { final TelephonyNetworkSpecifier telNetSpecifier = (TelephonyNetworkSpecifier) underlyingCaps.getNetworkSpecifier(); builder.setTransportInfo(new VcnTransportInfo(telNetSpecifier.getSubscriptionId())); } else { Slog.wtf( TAG, "Unknown transport type or missing TransportInfo/NetworkSpecifier for" + " non-null underlying network"); } } // TODO: Make a VcnNetworkSpecifier, and match all underlying subscription IDs. return builder.build(); } private static LinkProperties buildConnectedLinkProperties( @NonNull VcnGatewayConnectionConfig gatewayConnectionConfig, @NonNull IpSecTunnelInterface tunnelIface, @NonNull VcnChildSessionConfiguration childConfig) { final LinkProperties lp = new LinkProperties(); lp.setInterfaceName(tunnelIface.getInterfaceName()); for (LinkAddress addr : childConfig.getInternalAddresses()) { lp.addLinkAddress(addr); } for (InetAddress addr : childConfig.getInternalDnsServers()) { lp.addDnsServer(addr); } lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), null)); lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), null)); lp.setMtu(gatewayConnectionConfig.getMaxMtu()); return lp; } private class IkeSessionCallbackImpl implements IkeSessionCallback { private final int mToken; IkeSessionCallbackImpl(int token) { mToken = token; } @Override public void onOpened(@NonNull IkeSessionConfiguration ikeSessionConfig) { Slog.v(TAG, "IkeOpened for token " + mToken); // Nothing to do here. } @Override public void onClosed() { Slog.v(TAG, "IkeClosed for token " + mToken); sessionClosed(mToken, null); } @Override public void onClosedExceptionally(@NonNull IkeException exception) { Slog.v(TAG, "IkeClosedExceptionally for token " + mToken, exception); sessionClosed(mToken, exception); } @Override public void onError(@NonNull IkeProtocolException exception) { Slog.v(TAG, "IkeError for token " + mToken, exception); // Non-fatal, log and continue. } } /** Implementation of ChildSessionCallback, exposed for testing. */ @VisibleForTesting(visibility = Visibility.PRIVATE) public class VcnChildSessionCallback implements ChildSessionCallback { private final int mToken; VcnChildSessionCallback(int token) { mToken = token; } /** Internal proxy method for injecting of mocked ChildSessionConfiguration */ @VisibleForTesting(visibility = Visibility.PRIVATE) void onOpened(@NonNull VcnChildSessionConfiguration childConfig) { Slog.v(TAG, "ChildOpened for token " + mToken); childOpened(mToken, childConfig); } @Override public void onOpened(@NonNull ChildSessionConfiguration childConfig) { onOpened(new VcnChildSessionConfiguration(childConfig)); } @Override public void onClosed() { Slog.v(TAG, "ChildClosed for token " + mToken); sessionLost(mToken, null); } @Override public void onClosedExceptionally(@NonNull IkeException exception) { Slog.v(TAG, "ChildClosedExceptionally for token " + mToken, exception); sessionLost(mToken, exception); } @Override public void onIpSecTransformCreated(@NonNull IpSecTransform transform, int direction) { Slog.v(TAG, "ChildTransformCreated; Direction: " + direction + "; token " + mToken); childTransformCreated(mToken, transform, direction); } @Override public void onIpSecTransformDeleted(@NonNull IpSecTransform transform, int direction) { // Nothing to be done; no references to the IpSecTransform are held, and this transform // will be closed by the IKE library. Slog.v(TAG, "ChildTransformDeleted; Direction: " + direction + "; for token " + mToken); } } @VisibleForTesting(visibility = Visibility.PRIVATE) UnderlyingNetworkTrackerCallback getUnderlyingNetworkTrackerCallback() { return mUnderlyingNetworkTrackerCallback; } @VisibleForTesting(visibility = Visibility.PRIVATE) UnderlyingNetworkRecord getUnderlyingNetwork() { return mUnderlying; } @VisibleForTesting(visibility = Visibility.PRIVATE) void setUnderlyingNetwork(@Nullable UnderlyingNetworkRecord record) { mUnderlying = record; } @VisibleForTesting(visibility = Visibility.PRIVATE) boolean isRunning() { return mIsRunning; } @VisibleForTesting(visibility = Visibility.PRIVATE) void setIsRunning(boolean isRunning) { mIsRunning = isRunning; } @VisibleForTesting(visibility = Visibility.PRIVATE) VcnIkeSession getIkeSession() { return mIkeSession; } @VisibleForTesting(visibility = Visibility.PRIVATE) void setIkeSession(@Nullable VcnIkeSession session) { mIkeSession = session; } private IkeSessionParams buildIkeParams() { // TODO: Implement this once IkeSessionParams is persisted return null; } private ChildSessionParams buildChildParams() { // TODO: Implement this once IkeSessionParams is persisted return null; } @VisibleForTesting(visibility = Visibility.PRIVATE) VcnIkeSession buildIkeSession() { final int token = ++mCurrentToken; return mDeps.newIkeSession( mVcnContext, buildIkeParams(), buildChildParams(), new IkeSessionCallbackImpl(token), new VcnChildSessionCallback(token)); } /** External dependencies used by VcnGatewayConnection, for injection in tests */ @VisibleForTesting(visibility = Visibility.PRIVATE) public static class Dependencies { /** Builds a new UnderlyingNetworkTracker. */ public UnderlyingNetworkTracker newUnderlyingNetworkTracker( VcnContext vcnContext, ParcelUuid subscriptionGroup, TelephonySubscriptionSnapshot snapshot, Set<Integer> requiredUnderlyingNetworkCapabilities, UnderlyingNetworkTrackerCallback callback) { return new UnderlyingNetworkTracker( vcnContext, subscriptionGroup, snapshot, requiredUnderlyingNetworkCapabilities, callback); } /** Builds a new IkeSession. */ public VcnIkeSession newIkeSession( VcnContext vcnContext, IkeSessionParams ikeSessionParams, ChildSessionParams childSessionParams, IkeSessionCallback ikeSessionCallback, ChildSessionCallback childSessionCallback) { return new VcnIkeSession( vcnContext, ikeSessionParams, childSessionParams, ikeSessionCallback, childSessionCallback); } } /** * Proxy implementation of Child Session Configuration, used for testing. * * <p>This wrapper allows mocking of the final, parcelable ChildSessionConfiguration object for * testing purposes. This is the unfortunate result of mockito-inline (for mocking final * classes) not working properly with system services & associated classes. * * <p>This class MUST EXCLUSIVELY be a passthrough, proxying calls directly to the actual * ChildSessionConfiguration. */ @VisibleForTesting(visibility = Visibility.PRIVATE) public static class VcnChildSessionConfiguration { private final ChildSessionConfiguration mChildConfig; public VcnChildSessionConfiguration(ChildSessionConfiguration childConfig) { mChildConfig = childConfig; } /** Retrieves the addresses to be used inside the tunnel. */ public List<LinkAddress> getInternalAddresses() { return mChildConfig.getInternalAddresses(); } /** Retrieves the DNS servers to be used inside the tunnel. */ public List<InetAddress> getInternalDnsServers() { return mChildConfig.getInternalDnsServers(); } } /** Proxy implementation of IKE session, used for testing. */ @VisibleForTesting(visibility = Visibility.PRIVATE) public static class VcnIkeSession { private final IkeSession mImpl; public VcnIkeSession( VcnContext vcnContext, IkeSessionParams ikeSessionParams, ChildSessionParams childSessionParams, IkeSessionCallback ikeSessionCallback, ChildSessionCallback childSessionCallback) { mImpl = new IkeSession( vcnContext.getContext(), ikeSessionParams, childSessionParams, new HandlerExecutor(new Handler(vcnContext.getLooper())), ikeSessionCallback, childSessionCallback); } /** Creates a new IKE Child session. */ public void openChildSession( @NonNull ChildSessionParams childSessionParams, @NonNull ChildSessionCallback childSessionCallback) { mImpl.openChildSession(childSessionParams, childSessionCallback); } /** Closes an IKE session as identified by the ChildSessionCallback. */ public void closeChildSession(@NonNull ChildSessionCallback childSessionCallback) { mImpl.closeChildSession(childSessionCallback); } /** Gracefully closes this IKE Session, waiting for remote acknowledgement. */ public void close() { mImpl.close(); } /** Forcibly kills this IKE Session, without waiting for a closure confirmation. */ public void kill() { mImpl.kill(); } /** Sets the underlying network used by the IkeSession. */ public void setNetwork(@NonNull Network network) { mImpl.setNetwork(network); } } }
package cl.sportapp.evaluation.entitie; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; @Data @Entity(name = "detalle_metodo_fraccionamiento") public class DetalleMetodoFraccionamiento { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "DETALLE_METODO_FRACCIONAMIENTO_SEQ") @SequenceGenerator(name = "DETALLE_METODO_FRACCIONAMIENTO_SEQ", sequenceName = "SEQ_DETALLE_METODO_FRACCIONAMIENTO", allocationSize = 1) @Column(name = "id") private Long id; @Column private int kilogramo; @Column private int porcentaje; @Column(name = "score_z") private int scoreZ; @Column(name = "dif_peso") private int difPeso; @ManyToOne @JoinColumn(name="tipo_metodo_fraccionamiento") @JsonIgnore private TipoMetodoFraccionamiento tipoMetodoFraccionamiento; @ManyToOne @JoinColumn(name="paciente") @JsonIgnore private Paciente paciente; }
package pos.hurrybunny.appsmatic.com.hurrybunnypos.FCM; /** * Created by Eng Ali on 9/9/2018. */ public class Notification_activity { }
package at.ac.tuwien.infosys; /** * Created by lenaskarlat on 4/18/17. */ public class ModelAttributes { public static final String RECEIVED_DATA_TIMESTAMPS_FORM = "receivedDataTimeStampsForm"; public static final String OBJECT_LIST = "objectList"; private ModelAttributes() { } }
package com.gxtc.huchuan.ui.deal.liuliang.dispatchOrder; import com.gxtc.commlibrary.BasePresenter; import com.gxtc.commlibrary.BaseUserView; import com.gxtc.commlibrary.data.BaseSource; import com.gxtc.huchuan.bean.CopywritingBean; import com.gxtc.huchuan.http.ApiCallBack; import java.util.List; /** * Created by Steven on 17/3/2. */ public interface CopywritingContract { interface View extends BaseUserView<CopywritingContract.Presenter>{ void showData(List<CopywritingBean> datas); } interface Presenter extends BasePresenter{ void getData(); } interface Source extends BaseSource{ void getData(ApiCallBack<List<CopywritingBean>> callBack); } }
package bspq21_e4.ParkingManagement.Server; import static org.junit.Assert.*; import java.awt.HeadlessException; import org.apache.log4j.Logger; import org.junit.Before; import org.junit.Test; import bspq21_e4.ParkingManagement.Windows.AuthWindowTest; import bspq21_e4.ParkingManagement.client.gui.AuthWindow; import bspq21_e4.ParkingManagement.server.main.Server; public class ServerTest { static Logger logger = Logger.getLogger(AuthWindowTest.class.getName()); Server server; @Before public void setUp() throws Exception { try { logger.info("Entering setUp"); server = new Server(); logger.info("Leaving setUp"); } catch (HeadlessException e) { // TODO: handle exception } } @Test public void testServer() throws Exception { try { logger.info("Starting testServer"); assertEquals(server.getClass(), Server.class); logger.info("Finishing testServer"); } catch (HeadlessException e) { // TODO: handle exception } } }
package com.fruit.crawler.task.config; /** * Created by vincent * Created on 16/2/2 13:54. */ public class ProxyConfig { private String type ; public String getType() { return type; } public void setType(String type) { this.type = type; } }
package br.com.alura.gerenciador.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; //@WebServlet(urlPatterns="/oi") public class OiMundoServlet extends HttpServlet{ @Override public void service(ServletRequest req, ServletResponse res) throws IOException { PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<h2>"); out.println("Olá mundo é o c******"); out.println("</h2>"); out.println("</body>"); out.println("</html>"); System.out.println("O servlet foi chamado"); } }
//designpatterns.adapter.AmbulanceSound.java package designpatterns.adapter; //救护车声音类,充当适配者 public class AmbulanceSound { public void alarmSound() { System.out.println("发出救护车声音!"); } }
package com.qa.util; import com.qa.base.Testbase; public class TestUtil extends Testbase { public static long PAGE_LOAD_TIMEOUT=40; public static long IMPLICIT_WAIT=40; public void switchToframe() { driver.switchTo().frame(""); } }
package net.ckj46.springdataapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.data.domain.AuditorAware; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import java.util.LinkedList; import java.util.List; @EnableJpaAuditing (auditorAwareRef = "auditorAware") @SpringBootApplication public class SpringDataAppApplication { public static void main(String[] args) { SpringApplication.run(SpringDataAppApplication.class, args); } @Bean public AuditorAware<String> auditorAware() { return new AuditorAwareImpl(); } }
package modul.systemu.asi.frontend.model; import javax.persistence.*; import java.util.ArrayList; import java.util.Date; import java.util.List; @Entity @Table(name = "Task") public class Task { @Id @Column(unique = true, nullable = false) @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String name; @Column(name = "description", columnDefinition = "MEDIUMTEXT") private String description; @ManyToOne @JoinColumn(name = "fk_assigned_person") private User assignedPerson; @ManyToOne @JoinColumn(name = "fk_type") private Type type; @ManyToOne @JoinColumn(name = "fk_status") private Status status; @ManyToOne @JoinColumn(name = "fk_priority") private Priority priority; @ManyToOne @JoinColumn(name = "fk_related_notification") private Notification relatedNotification; private Date deadline; private boolean archived; @OneToMany(mappedBy = "task") private List<Comment> comments = new ArrayList<Comment>(); @OneToMany(mappedBy = "task") private List<TaskHistory> taskHistories = new ArrayList<TaskHistory>(); public Task(){ super(); } public Task(String name, String description, User assignedPerson, Type type, Status status, Priority priority, Notification relatedNotification, Date deadline, boolean archived){ super(); this.name = name; this.description = description; this.assignedPerson = assignedPerson; this.type = type; this.status = status; this.priority = priority; this.relatedNotification = relatedNotification; this.deadline = deadline; this.archived = archived; } public void setId(long id) { this.id = id; } public List<Comment> getComments() { return comments; } public void setComments(List<Comment> comments) { this.comments = comments; } public List<TaskHistory> getTaskHistories() { return taskHistories; } public void setTaskHistories(List<TaskHistory> taskHistories) { this.taskHistories = taskHistories; } public boolean isArchived() { return archived; } public void setArchived(boolean archived) { this.archived = archived; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public User getAssignedPerson() { return assignedPerson; } public void setAssignedPerson(User assignedPerson) { this.assignedPerson = assignedPerson; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public Priority getPriority() { return priority; } public void setPriority(Priority priority) { this.priority = priority; } public Notification getRelatedNotification() { return relatedNotification; } public void setRelatedNotification(Notification relatedNotification) { this.relatedNotification = relatedNotification; } public Date getDeadline() { return deadline; } public void setDeadline(Date deadline) { this.deadline = deadline; } }
package classes; import interfaces.Command; import interfaces.Invoker; /** * @author dylan * */ public class CreateTableCommand implements Command { private Invoker invoker; /** * @param invoker */ public CreateTableCommand(Invoker invoker) { super(); this.invoker = invoker; } /* * (non-Javadoc) * * @see interfaces.Command#invokeCommand() */ @Override public void invokeCommand() { invoker.createTable(); } }
package com.zhangdxchn.web.api; import com.zhangdxchn.dao.UserDaoImpl; import com.zhangdxchn.web.test.TestController; import org.apache.commons.collections.map.HashedMap; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpSession; import java.util.Map; /** * Created by zhangdx on 2016/11/20. */ public class TestControllerTest { @Mock private UserDaoImpl userDaoImpl; @InjectMocks private TestController testController; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } @Test public void weather() throws Exception { Map<String, Object> newsMap = new HashedMap(); newsMap.put("name", "张大"); Mockito.when(userDaoImpl.fetch(1)).thenReturn(newsMap); //assertEquals(userDaoImpl.fetch(39), newsMap); //test: add request and response MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); MockHttpSession mockHttpSession = new MockHttpSession(); // mockHttpSession.setAttribute("username", "user"); mockHttpServletRequest.setSession(mockHttpSession); MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse(); String resultJSON = testController.testUser(mockHttpServletRequest, mockHttpServletResponse); System.out.println("===================result==================="); System.out.println(resultJSON); } }
package com.bongda.model; public class SanDau { }
package buttley.nyc.esteban.magicbeans.model.boards.beanography; /** * Created by Tara on 12/30/2014. */ public class BeanographyPost { private int mName; private int mType; private int mHome; private int mLikes; private int mDislikes; private int mQuotes; private int mSnapshot; public BeanographyPost(int mName, int mType, int mHome, int mLikes, int mDislikes, int mQuotes, int mSnapshot) { this.mName = mName; this.mType = mType; this.mHome = mHome; this.mLikes = mLikes; this.mDislikes = mDislikes; this.mQuotes = mQuotes; this.mSnapshot = mSnapshot; } public int getmName() { return mName; } public void setmName(int mName) { this.mName = mName; } public int getmLikes() { return mLikes; } public void setmLikes(int mLikes) { this.mLikes = mLikes; } public int getmDislikes() { return mDislikes; } public void setmDislikes(int mDislikes) { this.mDislikes = mDislikes; } public int getmHome() { return mHome; } public void setmHome(int mHome) { this.mHome = mHome; } public int getmType() { return mType; } public void setmType(int mType) { this.mType = mType; } public int getmQuotes() { return mQuotes; } public void setmQuotes(int mQuotes) { this.mQuotes = mQuotes; } public int getmSnapshot() { return mSnapshot; } public void setmSnapshot(int mSnapshot) { this.mSnapshot = mSnapshot; } }
package com.rt.video.decode.glcustom; import android.graphics.SurfaceTexture; import android.opengl.GLES11Ext; import android.opengl.GLES20; import com.gensee.utils.GenseeLog; import com.rt.video.decode.GlRender; import javax.microedition.khronos.egl.EGLContext; import static javax.microedition.khronos.egl.EGL10.EGL_HEIGHT; import static javax.microedition.khronos.egl.EGL10.EGL_NONE; import static javax.microedition.khronos.egl.EGL10.EGL_WIDTH; public class OffScreenGlRender extends CustomGLRender{ private static final String TAG = "OffScreenGlRender"; private int mWidth; private int mHeight; private int mTexId; private SurfaceTexture decodeSurfaceTexture = null; private OnGlTextrueListener onGlTextrueListener; public void setOnGlTextrueListener(OnGlTextrueListener listener) { onGlTextrueListener = listener; } public void onSurfaceCreated(SurfaceTexture surfaceTexture, int mWidth, int mHeight) { GenseeLog.i(TAG, "onSurfaceCreated mWidth = " + mWidth + " mHeight = " + mHeight); this.mWidth = mWidth; this.mHeight = mHeight; super.onSurfaceCreated(surfaceTexture, mWidth, mHeight); } @Override protected void createSurface() { int[] attribList = new int[] { EGL_WIDTH, mWidth, EGL_HEIGHT, mHeight, EGL_NONE }; mEGLSurface = mEGL.eglCreatePbufferSurface(mEGLDisplay, mEGLConfig, attribList); } protected void setRender(GlRender render) { if(!Thread.currentThread().getName().equals(mThreadOwner)) { GenseeLog.e(TAG, "setGlRener: this thread does not own the Opengles Context"); return; } int[] textures = new int[1]; GLES20.glGenTextures(1, textures, 0); mTexId = textures[0]; GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTexId); GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); decodeSurfaceTexture = new SurfaceTexture(mTexId); decodeSurfaceTexture.setOnFrameAvailableListener(onFrameAvailableListener); if (null != onGlTextrueListener) { onGlTextrueListener.onGlSurfaceTexture(decodeSurfaceTexture); } GenseeLog.i(TAG, "mTexId = " + mTexId); if(null != onGlTextrueListener) { onGlTextrueListener.onGlContext(mEGLContext, mTexId); } if(null != glRender) { glRender.onSurfaceCreated(mGL, mEGLConfig); glRender.onSurfaceChanged(mGL, mWidth, mHeight); } } public void getTextureRes() { if(null != onGlTextrueListener) { onGlTextrueListener.onGlContext(mEGLContext, mTexId); } } private SurfaceTexture.OnFrameAvailableListener onFrameAvailableListener = new SurfaceTexture.OnFrameAvailableListener() { @Override public void onFrameAvailable(SurfaceTexture surfaceTexture) { GenseeLog.i(TAG, "onFrameAvailable threadid = " + Thread.currentThread().getName() + ":" + Thread.currentThread().getId()); // requestRender(); if(null != onGlTextrueListener) { onGlTextrueListener.onRequestRender(); } } }; @Override protected void onDrawFrame() { // if(null != decodeSurfaceTexture) // { // decodeSurfaceTexture.updateTexImage(); // } } public interface OnGlTextrueListener{ void onGlSurfaceTexture(SurfaceTexture surfaceTexture); void onGlContext(EGLContext eglContext, int mTextId); void onRequestRender(); } }
package com.oaec.control; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class Login extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = "root"; String password = "root"; if("root".equals(username) && "root".equals(password)){ HttpSession s = request.getSession(); s.setAttribute("aaa", "bbb"); request.setAttribute("ccc", "dddddddd"); this.getServletContext().setAttribute("ggggggg", "ffffffffff"); request.getRequestDispatcher("loginOk.jsp").forward(request, response); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
public class SignIn{ private int id; private String name; private String saveTime; public void sign(){ System.out.println(saveTime); } }
package cyfixusBot.gui; import java.awt.Color; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.font.TextAttribute; import java.util.Map; import javax.swing.JPanel; import cyfixusBot.gui.components.CyLabel; public class AlertPanel extends JPanel { protected Font messageFont; protected Font alertFont; protected Map attributes; protected String message; protected String alert; protected CyLabel messageLabel; protected CyLabel alertLabel; protected CyLabel alertLabel2; public AlertPanel(String message, String alert) { super(); setFocusable(false); this.message = message; this.alert = alert; setBackground(new Color(3)); setLayout(new GridBagLayout()); setLabel(); GridBagConstraints gc = new GridBagConstraints(); gc.gridx = 0; gc.gridy = 0; gc.fill = GridBagConstraints.NONE; add(alertLabel, gc); gc.weighty = 1; gc.gridx = 0; gc.gridy = 1; gc.fill = GridBagConstraints.NONE; add(messageLabel, gc); gc.weighty = 0; gc.gridx = 0; gc.gridy = 2; gc.fill = GridBagConstraints.NONE; add(alertLabel2, gc); } public void setLabel(){ setMessageFont(); messageLabel = new CyLabel(message); messageLabel.setFont(messageFont); setAlertFont(); alertLabel = new CyLabel("-\t-\t" + alert + "\t-\t-"); alertLabel.setFont(alertFont); alertLabel2 = new CyLabel("-\t-\t" + alert + "\t-\t-"); alertLabel2.setFont(alertFont); } public void setMessageFont(){ messageFont = this.getFont(); attributes = messageFont.getAttributes(); attributes.put(TextAttribute.FOREGROUND, new Color(0xffff00ff)); attributes.put(TextAttribute.SIZE, 48); attributes.put(TextAttribute.WIDTH, TextAttribute.WIDTH_REGULAR); attributes.put(TextAttribute.FAMILY, "Nimbus Mono L"); attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD); messageFont = messageFont.deriveFont(attributes); } public void setAlertFont(){ alertFont = this.getFont(); attributes = alertFont.getAttributes(); attributes.put(TextAttribute.FOREGROUND, new Color(0xff00ffff)); attributes.put(TextAttribute.SIZE, 24); attributes.put(TextAttribute.WIDTH, TextAttribute.WIDTH_REGULAR); attributes.put(TextAttribute.FAMILY, "Nimbus Mono L"); attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD); alertFont = alertFont.deriveFont(attributes); } }
package structural.composition.my.nodedemo; public class ElementNode implements Node{ private String name; public ElementNode(String name) { this.name = name; } @Override public void print() { System.out.println("元素节点: " + name); } @Override public void add(Node node) { } @Override public void remove(Node node) { } }
package com.sky.design.strategy; public class CashContext { private CashSuper cashSuper; //策略 public CashContext(CashSuper cashSuper){ this.cashSuper=cashSuper; } //策略与简单工厂结合 public CashContext(String type){ switch (type) { case "正常收费": cashSuper=new CashNormal(); break; case "满300返100": cashSuper=new CashReturn(300, 100); break; case "打8折": cashSuper=new CashRebate(0.8); break; default:cashSuper=new CashNormal();break; } } public double GetResult(double money){ return cashSuper.acceptCash(money); } }
package com.example; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Simple class that provides jokes */ public class Joker implements JokeProvider { /** * Return random joke from jokes base * @return Joke */ @Override public synchronized String getJoke() { final int jokesCount = jokes.size(); final Random randomGenerator = new Random(); final int jokeNumber = randomGenerator.nextInt(jokesCount); return jokes.get(jokeNumber); } private static final List<String> jokes = new ArrayList<>(); static { jokes.add("Can a kangaroo jump higher than a house? Of course, a house doesn’t jump at all"); jokes.add("It is so cold outside I saw a politician with his hands in his own pockets."); jokes.add("My dog used to chase people on a bike a lot. It got so bad, finally I had to take his bike away."); jokes.add("I wanted to grow my own food but I couldn’t get bacon seeds anywhere"); jokes.add("I'd like to buy a new boomerang please. Also, can you tell me how to throw the old one away?"); jokes.add("You can train a cat to do anything the cat wants to do at the moment it wants to do it"); } }
package com.db.server.security; import org.apache.log4j.Logger; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.stereotype.Component; import java.util.Collections; @Component public class ServerAuthProvider implements AuthenticationProvider { private final static Logger LOGGER = Logger.getLogger(ServerAuthProvider.class); @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { LOGGER.debug("Try to authenticate '" + authentication.getName() + "'"); String name = authentication.getName(); if (name.equals("tester1") || name.equals("tester2")){ LOGGER.debug("Authenticated ->" + authentication); String password = authentication.getCredentials().toString(); UsernamePasswordAuthenticationToken userAuth = new UsernamePasswordAuthenticationToken(name, password, Collections.emptyList()); return userAuth; } LOGGER.debug("Not Authenticated"); throw new BadCredentialsException("Illegal user"); } @Override public boolean supports(Class<?> authenticationClz) { LOGGER.debug("Check class " + authenticationClz); return authenticationClz.equals(UsernamePasswordAuthenticationToken.class); } }
package dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TExecutor { public <T> T execQuery(Connection connection, String query, TResultHandler<T> handler) throws SQLException { Statement stmt = connection.createStatement(); stmt.execute(query); ResultSet resultSet = stmt.getResultSet(); T value = handler.handle(resultSet); resultSet.close(); stmt.close(); return value; } }
package de.fraunhofer.iese.ids.odrl.policy.library.model.enums; public enum PolicyType { OFFER("ids:ContractOffer"), REQUEST("ids:ContractRequest"), AGREEMENT("ids:ContractAgreement"); String stringRepresentation; PolicyType(String s) { this.stringRepresentation = s; } public String getStringRepresentation() { return this.stringRepresentation; } public static PolicyType getFromIdsString(String stringRepresentation) { for( PolicyType policyType : values()) { if(policyType.getStringRepresentation().equals(stringRepresentation)) { return policyType; } } return null; } }
package com.zxt.compplatform.workflow.service.impl; import java.util.Calendar; import java.util.List; import com.zxt.compplatform.workflow.dao.LogWorkFlowDao; import com.zxt.compplatform.workflow.entity.WorkFlowDataStauts; import com.zxt.compplatform.workflow.service.LogWorkFlowService; public class LogWorkFlowServiceImpl implements LogWorkFlowService { //dao层注入 private LogWorkFlowDao logWorkFlowDao; public void addWorkFlowLog(String userId,String app_id,WorkFlowDataStauts workflowDataStauts, String processDefId, String workitemId) { //获取当前时间 Calendar ca = Calendar.getInstance(); int year = ca.get(Calendar.YEAR); int month=ca.get(Calendar.MONTH); int day=ca.get(Calendar.DATE); int minute=ca.get(Calendar.MINUTE); int hour=ca.get(Calendar.HOUR); int second=ca.get(Calendar.SECOND); String currentTime = year +"年"+ month +"月"+ day + "日"+hour +"时"+ minute +"分"+ second +"秒"; logWorkFlowDao.addWorkFlowLog(userId,currentTime,app_id,workflowDataStauts,processDefId,workitemId); } /** * 流程日志添加ETC */ public void addWorkFlowLogETC(String mid,String userId,String pioneer_status,String pioneer_operate,String app_id,String processDefId,String workitemId){ //获取当前时间 Calendar ca = Calendar.getInstance(); int year = ca.get(Calendar.YEAR); int month=ca.get(Calendar.MONTH); int day=ca.get(Calendar.DATE); int minute=ca.get(Calendar.MINUTE); int hour=ca.get(Calendar.HOUR); int second=ca.get(Calendar.SECOND); String currentTime = year +"年"+ month +"月"+ day + "日"+hour +"时"+ minute +"分"+ second +"秒"; logWorkFlowDao.addWorkFlowLogETC(mid,userId,currentTime,pioneer_status,pioneer_operate,app_id,processDefId,workitemId); } /** * 查询流程日志详情 */ public List findWorkFlowLogByAppID(String app_id){ return logWorkFlowDao.findWorkFlowLogByAppID(app_id); } public LogWorkFlowDao getLogWorkFlowDao() { return logWorkFlowDao; } public void setLogWorkFlowDao(LogWorkFlowDao logWorkFlowDao) { this.logWorkFlowDao = logWorkFlowDao; } }
package com.sapl.retailerorderingmsdpharma.activities; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.SwitchCompat; import android.text.TextUtils; import android.view.View; import android.widget.ImageView; import android.widget.Switch; import android.widget.Toast; import com.sapl.retailerorderingmsdpharma.R; import com.sapl.retailerorderingmsdpharma.confiq.GPSTracker; import com.sapl.retailerorderingmsdpharma.customView.CircularTextView; import com.sapl.retailerorderingmsdpharma.customView.CustomButtonRegular; import com.sapl.retailerorderingmsdpharma.customView.CustomEditTextMedium; import com.sapl.retailerorderingmsdpharma.customView.CustomTextViewMedium; import com.sapl.retailerorderingmsdpharma.customView.CustomTextViewRegular; public class ActivityRegisterTwo extends AppCompatActivity { public static String LOG_TAG = "ActivityRegisterTwo"; CircularTextView txt_lable1, txt_lable2, txt_lable3,txt_no_of_product_taken; CustomTextViewRegular txt_sign_up_link; CustomEditTextMedium edt_retailer_area, edt_retailer_location, edt_pin_code; //edt_retailer_address edt_retailer_city, edt_retailer_district, edt_retailer_state'' CustomButtonRegular btn_next; final Context context = this; SwitchCompat actionbar_switch; GPSTracker gps; ImageView img_menu,img_cart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register_two); initComponants(); initComponantListner(); } public void initComponants() { img_cart = findViewById(R.id.img_cart); img_cart.setVisibility(View.GONE); img_menu = findViewById(R.id.img_menu); img_menu.setVisibility(View.GONE); txt_no_of_product_taken = findViewById(R.id.txt_no_of_product_taken); txt_no_of_product_taken.setVisibility(View.GONE); CustomTextViewMedium txt_title = findViewById(R.id.txt_title); txt_title.setText(getResources().getString(R.string.sign_up)); txt_title.setTextColor((Color.parseColor(MyApplication.get_session(MyApplication.SESSION_PRIMARY_TEXT_COLOR)))); CustomTextViewMedium txt_cmpl_area = findViewById(R.id.txt_cmpl_area); txt_cmpl_area.setTextColor(getResources().getColor(R.color.red)); CustomTextViewMedium txt_cmpl_pin_code = findViewById(R.id.txt_cmpl_pin_code); txt_cmpl_pin_code.setTextColor(getResources().getColor(R.color.red)); CustomTextViewMedium txt_cmpl_loc = findViewById(R.id.txt_cmpl_loc); txt_cmpl_loc.setTextColor(getResources().getColor(R.color.red)); edt_retailer_area = findViewById(R.id.edt_retailer_area); edt_pin_code = findViewById(R.id.edt_pin_code); edt_retailer_location = findViewById(R.id.edt_retailer_location); edt_retailer_location.setClickable(false); edt_retailer_location.setActivated(false); txt_sign_up_link = findViewById(R.id.txt_sign_up_link); txt_lable1 = findViewById(R.id.txt_lable1); txt_lable2 = findViewById(R.id.txt_lable2); txt_lable3 = findViewById(R.id.txt_lable3); txt_lable1.setStrokeColor("#006e6e"); txt_lable1.setTextColor(getResources().getColor(R.color.white)); txt_lable2.setStrokeColor("#006e6e"); txt_lable2.setTextColor(getResources().getColor(R.color.white)); txt_lable3.setStrokeColor("#C0C0C0"); txt_lable3.setTextColor(getResources().getColor(R.color.white)); btn_next = findViewById(R.id.btn_next); // actionbar_switch = findViewById(R.id.actionbar_switch); /* if (!TextUtils.isEmpty(MyApplication.get_session(MyApplication.SESSION_AREA))) { edt_retailer_area.setText(MyApplication.get_session(MyApplication.SESSION_AREA)); } if (!TextUtils.isEmpty(MyApplication.get_session(MyApplication.SESSION_PIN))) { edt_pin_code.setText(MyApplication.get_session(MyApplication.SESSION_PIN)); } if (!TextUtils.isEmpty(MyApplication.get_session(MyApplication.SESSION_LOCATION))) { // edt_retailer_location.setText(MyApplication.get_session(MyApplication.SESSION_LOCATION)); }*/ } public void initComponantListner() { btn_next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String pinCode = edt_pin_code.getText() + ""; String area = edt_retailer_area.getText() + ""; String shop_location = edt_retailer_location.getText().toString().trim(); gps = new GPSTracker(ActivityRegisterTwo.this); if (gps.canGetLocation()) { double latitude = gps.getLatitude(); double longitude = gps.getLongitude(); MyApplication.logi(LOG_TAG, "lattt is-->" + latitude); MyApplication.logi(LOG_TAG, "longitute---->" + longitude); String location = latitude + "," + longitude; MyApplication.set_session(MyApplication.SESSION_LOCATION, location); MyApplication.logi(LOG_TAG, "GEO TAGGINF IS--->" + MyApplication.get_session(MyApplication.SESSION_LOCATION)); // \n is for new line // Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); } else { // can't get location // GPS or Network is not enabled // Ask user to enable GPS/network in settings gps.showSettingsAlert(); } if (TextUtils.isEmpty(shop_location)) { edt_retailer_location.setError("Enter shop location"); return; } if (TextUtils.isEmpty(pinCode)) { edt_pin_code.setError("Enter pin code"); return; } if (TextUtils.isEmpty(area)) { edt_retailer_area.setError("Enter area"); return; } if (!TextUtils.isEmpty(area)) { if (!TextUtils.isEmpty(pinCode) && pinCode.length() == 6) { MyApplication.set_session(MyApplication.SESSION_AREA, area); MyApplication.set_session(MyApplication.SESSION_PIN, pinCode); // MyApplication.set_session(MyApplication.SESSION_LOCATION, "23.56, 72.767" ); Intent i = new Intent(getApplicationContext(), ActivityRegisterThree.class); // finish(); overridePendingTransition(R.anim.fade_in_call, R.anim.fade_out_call); startActivity(i); } else edt_pin_code.setError("Enter valid pin code."); } else edt_retailer_area.setError("Enter area"); } }); txt_sign_up_link.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(getApplicationContext(), ActivityLogin.class); finish(); overridePendingTransition(R.anim.fade_in_call, R.anim.fade_out_call); startActivity(i); } }); } }
package com.medic.medicapp; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.ValueEventListener; import com.medic.medicapp.data.MedicContract; import java.text.SimpleDateFormat; import java.util.Calendar; import static com.medic.medicapp.MainActivity.ADMINS; import static com.medic.medicapp.MainActivity.ADMISSIONS_PERSONAL; import static com.medic.medicapp.MainActivity.NURSES; import static com.medic.medicapp.MainActivity.PATIENTS; import static com.medic.medicapp.MainActivity.RC_SIGN_IN; import static com.medic.medicapp.MainActivity.USERS; import static com.medic.medicapp.MainActivity.admPersMainPage; import static com.medic.medicapp.MainActivity.adminsMainPage; import static com.medic.medicapp.MainActivity.id; import static com.medic.medicapp.MainActivity.mAdminsReference; import static com.medic.medicapp.MainActivity.mAdmissionsPersonalReference; import static com.medic.medicapp.MainActivity.mDb; import static com.medic.medicapp.MainActivity.mEmailToTypeReference; import static com.medic.medicapp.MainActivity.mFirebaseAuth; import static com.medic.medicapp.MainActivity.mNursesReference; import static com.medic.medicapp.MainActivity.mUsernameToEmailReference; import static com.medic.medicapp.MainActivity.mUsersReference; import static com.medic.medicapp.MainActivity.nursesMainPage; import static com.medic.medicapp.MainActivity.patientsMainPage; import static com.medic.medicapp.MainActivity.usersMainPage; public class LogInActivity extends AppCompatActivity { private EditText mUserNameEditText; private EditText mPasswordEditText; private final String lastAccess = "lastAccess"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_in); mUserNameEditText = (EditText) findViewById(R.id.et_user_name); mPasswordEditText = (EditText) findViewById(R.id.et_user_password); } //Este es el método que se llama al pulsar el botón de ACCEDER public void logInUser(View view) { if (mUserNameEditText.getText().length() == 0 || mPasswordEditText.getText().length() == 0) { return; }else if(mPasswordEditText.getText().length() < 6){ Toast.makeText(getBaseContext(), R.string.password6Caracteres, Toast.LENGTH_LONG).show(); mPasswordEditText.getText().clear(); return; }else if(mUserNameEditText.getText().toString().contains("@")){ //email entered logInWithEmail(mUserNameEditText.getText().toString(), mPasswordEditText.getText().toString(), true); }else{ //username entered logInWithUsername(mUserNameEditText.getText().toString(), mPasswordEditText.getText().toString(), false); } } private void logInWithUsername(final String username, final String password, boolean emailInserted) { mUsernameToEmailReference.child(username).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ String email = dataSnapshot.child("email").getValue().toString(); //since Firebase does not accept dots in the name of a node, //we store them with * instead email = email.replace("*", "."); logInWithEmail(email, password,false); }else{ Toast.makeText(LogInActivity.this, R.string.login_error , Toast.LENGTH_SHORT).show(); mUserNameEditText.getText().clear(); mPasswordEditText.getText().clear(); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void logInWithEmail(final String email, String password, final boolean emailInserted) { mFirebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { Toast.makeText(LogInActivity.this, "Email: " + email, Toast.LENGTH_SHORT).show(); if (task.isSuccessful()) { Toast.makeText(LogInActivity.this, R.string.login_ok, Toast.LENGTH_SHORT).show(); initializeMainPage(email, emailInserted); } else { Toast.makeText(LogInActivity.this, "An error occurred: " + task.getResult().toString(), Toast.LENGTH_SHORT).show(); } } }); } public void initializeMainPage(String email, final boolean emailInserted){ final String emailToFirebase = email.replace(".", "*"); mEmailToTypeReference.child(emailToFirebase).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if(dataSnapshot.exists()){ String type = dataSnapshot.child("type").getValue().toString(); //The first time the user logs in, we are going to give him/her the opportunity to //create a username boolean hasUsername; switch (dataSnapshot.child("username").getValue(String.class)){ case "true": hasUsername = true; break; case "false": case "---": hasUsername = false; break; default: hasUsername = false; break; } if(emailInserted && !hasUsername){ //If he/she entered an email account it is most likely that he/she does not have a username //We are going to check it in the database //The username is not created. //Open the activity to create a new username that doesn't already exists startActivityForResult((new Intent(LogInActivity.this, CreateUsernameActivity.class)).putExtra(Intent.EXTRA_TEXT, type), 1); }else{ Toast.makeText(getBaseContext(), R.string.login_ok, Toast.LENGTH_LONG).show(); //The user can finally access his/her account SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); String currentTime = dateFormat.format(Calendar.getInstance().getTime()); switch (type){ case USERS: mUsersReference.child(emailToFirebase).child(lastAccess).setValue(currentTime); startActivityForResult((new Intent(getBaseContext(), usersMainPage).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP )), RC_SIGN_IN); finish(); break; case ADMINS: startActivityForResult((new Intent(getBaseContext(), adminsMainPage).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP )), RC_SIGN_IN); finish(); break; case ADMISSIONS_PERSONAL: mAdmissionsPersonalReference.child(emailToFirebase).child(lastAccess).setValue(currentTime); startActivityForResult((new Intent(getBaseContext(), admPersMainPage).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP )), RC_SIGN_IN); break; case NURSES: mNursesReference.child(emailToFirebase).child(lastAccess).setValue(currentTime); startActivityForResult( (new Intent(getBaseContext(), nursesMainPage).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP )) .putExtra(Intent.EXTRA_TEXT, NURSES), RC_SIGN_IN); break; case PATIENTS: String patientDni = dataSnapshot.child("dni").getValue().toString(); startActivityForResult( (new Intent(getBaseContext(), patientsMainPage).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP )) .putExtra(Intent.EXTRA_TEXT, patientDni).putExtra("isPatient", true), RC_SIGN_IN); break; default: Toast.makeText(getBaseContext(), R.string.error_not_defined_type, Toast.LENGTH_LONG).show(); break; } } } else { Toast.makeText(getBaseContext(), R.string.login_firebase_error, Toast.LENGTH_LONG).show(); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode==1){ String email = mFirebaseAuth.getCurrentUser().getEmail().replace(".", "*"); initializeMainPage(email,false); } } @Override public boolean onCreateOptionsMenu(Menu menu) { /* Use AppCompatActivity's method getMenuInflater to get a handle on the menu inflater */ MenuInflater inflater = getMenuInflater(); /* Use the inflater's inflate method to inflate our menu layout to this menu */ /////////////////inflater.inflate(R.menu.menu_help, menu); /* Return true so that the menu is displayed in the Toolbar */ return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id){ /////////////////case R.id.action_help: /////////////////startActivity(new Intent(this, RegisterHelpActivity.class)); //// return true; } return super.onOptionsItemSelected(item); } }
package com.beike.wap.service.impl; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.beike.wap.dao.MTagDao; import com.beike.wap.entity.MTag; import com.beike.wap.service.MTagService; /** * Title : MTagServiceImpl * <p/> * Description :分类信息服务实现类 * <p/> * CopyRight : CopyRight (c) 2011 * </P> * Company : qianpin.com </P> JDK Version Used : JDK 5.0 + * <p/> * Modification History : * <p/> * * <pre> * NO. Date Modified By Why & What is modified * </pre> * * <pre>1 2011-10-17 lvjx Created * * <pre> * <p/> * * @author lvjx * @version 1.0.0.2011-10-17 */ @Service("wapTagService") public class MTagServiceImpl implements MTagService { /* * @see com.beike.wap.service.tag.MTagService#queryTagByParendId(int) */ @Override public List<MTag> queryTagByParendId(int parentId) throws Exception { List<MTag> tagList = null; tagList = tagDao.queryTagByParendId(parentId); return tagList; } /* * @see com.beike.wap.service.tag.MTagService#queryTagByParentIdInfo(int) */ @Override public Map<String, String> queryTagByParentIdInfo(int parentId) throws Exception { Map<String,String> tagMap = null; tagMap = tagDao.queryTagByParentIdInfo(parentId); return tagMap; } /* * @see com.beike.service.GenericService#findById(java.io.Serializable) */ @Override public MTag findById(Long id) { // TODO Auto-generated method stub return null; } @Resource(name = "wapTagDao") private MTagDao tagDao; }
package jianzhioffer; import jianzhioffer.utils.TreeNode; /** * @ClassName : Solution28 * @Description : 判断俩二叉树是否对称 * @Date : 2019/9/16 14:38 */ public class Solution28 { public boolean isSymmetrical(TreeNode root1, TreeNode root2){ if (root1==null && root2==null) return true; if (root1==null || root2==null) return false; if (root1.val!=root2.val) return false; return isSymmetrical(root1.left,root2.right) && isSymmetrical(root1.right,root2.left); } }
package com.legaoyi.file.message.handler; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import java.util.List; import org.springframework.stereotype.Component; import com.legaoyi.file.message.codec.MessageEncoder; import com.legaoyi.file.server.util.Constants; import com.legaoyi.protocol.exception.MessageDeliveryException; import com.legaoyi.protocol.exception.UnsupportedMessageException; import com.legaoyi.protocol.message.Message; import com.legaoyi.protocol.message.encoder.MessageBodyEncoder; import com.legaoyi.protocol.util.SpringBeanUtil; /** * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2015-01-30 */ @Component("deviceDownMessageDeliverer") public class DeviceDownMessageDeliverer { public void deliver(ChannelHandlerContext ctx, Message message) throws Exception { Channel channel = ctx.channel(); if (channel == null || !channel.isActive()) { throw new MessageDeliveryException("device offline,simCode=".concat(message.getMessageHeader().getSimCode())); } MessageBodyEncoder messageBodyEncoder = null; String messageId = message.getMessageHeader().getMessageId(); try { messageBodyEncoder = SpringBeanUtil.getMessageBodyEncoder(messageId, Constants.PROTOCOL_VERSION); } catch (Exception e) { throw new UnsupportedMessageException(e); } List<byte[]> byteList = new MessageEncoder().encode(message, messageBodyEncoder); ctx.writeAndFlush(byteList); } }
package com.limefriends.molde.menu_magazine; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.limefriends.molde.MoldeMainActivity; import com.limefriends.molde.R; import com.limefriends.molde.menu_magazine.cardnews.MagazineCardNewsAdapter; import com.limefriends.molde.menu_magazine.entity.CardNewsEntity; import com.limefriends.molde.menu_magazine.magazineReport.MagazineReportLocationDetailActivity; import com.limefriends.molde.menu_magazine.magazineReport.MagazineReportMolcaDetailActivity; import com.limefriends.molde.menu_magazine.magazineReport.MagazineReportSpreadDetailActivity; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class MoldeMagazineFragment extends Fragment implements MoldeMainActivity.onKeyBackPressedListener{ @BindView(R.id.cardnews_recyclerView) RecyclerView cardnews_recyclerView; @BindView(R.id.manual_new_molca) LinearLayout manual_new_molca; @BindView(R.id.manual_by_location) LinearLayout manual_by_location; @BindView(R.id.manual_for_spreading) LinearLayout manual_for_spreading; public MoldeMagazineFragment(){} public static MoldeMagazineFragment newInstance() { MoldeMagazineFragment fragment = new MoldeMagazineFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.magazine_fragment, container, false); ButterKnife.bind(this, rootView); manual_new_molca.setElevation(8); manual_for_spreading.setElevation(8); manual_by_location.setElevation(8); manual_new_molca.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(getActivity(), MagazineReportMolcaDetailActivity.class); intent.putExtra("title", "최신 몰카 정보"); startActivity(intent); } }); manual_by_location.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(getActivity(), MagazineReportLocationDetailActivity.class); intent.putExtra("title", "장소별 대처법"); startActivity(intent); } }); manual_for_spreading.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(getActivity(), MagazineReportSpreadDetailActivity.class); intent.putExtra("title", "몰카유포 대처"); startActivity(intent); } }); List<CardNewsEntity> cardnewsDataList = new ArrayList<CardNewsEntity>(); cardnewsDataList.add(new CardNewsEntity(R.drawable.img_cardnews_dummy, "카드뉴스1")); cardnewsDataList.add(new CardNewsEntity(R.drawable.img_cardnews_dummy, "카드뉴스2")); cardnewsDataList.add(new CardNewsEntity(R.drawable.img_cardnews_dummy, "카드뉴스3")); cardnewsDataList.add(new CardNewsEntity(R.drawable.img_cardnews_dummy, "카드뉴스4")); cardnewsDataList.add(new CardNewsEntity(R.drawable.img_cardnews_dummy, "카드뉴스5")); cardnewsDataList.add(new CardNewsEntity(R.drawable.img_cardnews_dummy, "카드뉴스6")); cardnewsDataList.add(new CardNewsEntity(R.drawable.img_cardnews_dummy, "카드뉴스7")); cardnewsDataList.add(new CardNewsEntity(R.drawable.img_cardnews_dummy, "카드뉴스8")); cardnewsDataList.add(new CardNewsEntity(R.drawable.img_cardnews_dummy, "카드뉴스9")); cardnewsDataList.add(new CardNewsEntity(R.drawable.img_cardnews_dummy, "카드뉴스10")); MagazineCardNewsAdapter magazineCardNewsAdapter = new MagazineCardNewsAdapter(getContext(), cardnewsDataList); cardnews_recyclerView.setAdapter(magazineCardNewsAdapter); return rootView; } @Override public void onBackKey() { } }
package ru.yurima.customthreadlocal; import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; /** * Я не являюсь крупным специалистом в concurrency. Но в чем проблема использовать такую простую реализацию? * Заранее благодарен за разъяснения. * */ public class CustomThreadLocal<T> implements IThreadLocal<T>{ private final Map<Thread, T> store = Collections.synchronizedMap(new WeakHashMap<>()); @Override public void set(T value) { Thread thread = Thread.currentThread(); store.put(thread, value); } @Override public T get() { Thread thread = Thread.currentThread(); return store.get(thread); } @Override public void remove() { Thread thread = Thread.currentThread(); store.remove(thread); } }