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 gt.com.atel.logger;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.Dependent;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.inject.Named;
/**
*
* @author victor
*/
@Named("loggerEmployees")
@Dependent
public class LoggerEmployees implements Serializable {
@Produces
public Logger getEmployeeLogger(InjectionPoint injectionPoint){
Logger logger = Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
logger.setLevel(Level.ALL);
return logger;
}
}
|
package behavioral.interpreter;
public class ExpressionA implements IExpression{
public void interpret(Context context) {
System.out.println("ExpressionA");
}
}
|
package lesson7.homeWork.exceptions;
public class NegativeEatCountException extends RuntimeException{
public NegativeEatCountException(String message) {
super(message);
}
}
|
package com.mec.datareceiver.service;
import java.util.List;
import com.mec.datareceiver.model.dao.UserDao;
import com.mec.datareceiver.model.domain.User;
public class SimpleUserManager implements UserManager {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public List<User> getUser(String screenName) {
return userDao.findByUserScreenName(screenName);
}
@Override
public List<User> getAllUsers() {
return userDao.getUserList();
}
@Override
public void addUser(User user) {
userDao.insert(user);
}
@Override
public void deleteUser(User user) {
userDao.delete(user);
}
@Override
public int getNumberOfUsers() {
return userDao.getNumOfUsers();
}
@Override
public void deleteAllUsers() {
userDao.deleteAll();
}
// Added a comment here 20190119
}
|
package com.sl.app.notice.notice.controller;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sl.app.notice.notice.service.AppNoticeService;
import com.sl.app.notice.notice.vo.AppNoticeVO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@Controller
public class AppNoticeController {
private static final Logger logger = LoggerFactory.getLogger(AppNoticeController.class);
@Autowired
AppNoticeService service;
@RequestMapping(value = "/app/notice/notice", method = RequestMethod.POST)
@ResponseBody
public JSONArray selectUserNotice(AppNoticeVO vo,Locale locale){
return service.selectUserNotice(vo);
}
@RequestMapping(value = "/app/notice/response",method = RequestMethod.POST)
@ResponseBody
public JSONObject responseUserNotice(AppNoticeVO vo,Locale locale){
return service.responseUserNotice(vo);
}
}
|
package com.example.sensortest;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private TextView textview1;
private TextView textview2;
private TextView textview3;
private SensorManager sensorManager;
private Sensor mOrientation;
private LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//github commit test
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mOrientation = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
sensorManager.registerListener(this,mOrientation,SensorManager.SENSOR_DELAY_UI);
bindViews();
}
private void bindViews(){
textview1 = findViewById(R.id.textView3);
textview2 = findViewById(R.id.textView4);
textview3 = findViewById(R.id.textView5);
}
@Override
public void onSensorChanged(SensorEvent event) {
textview1.setText("方位角:" + (float) (Math.round(event.values[0] * 100)) / 100);
textview2.setText("倾斜角:" + (float) (Math.round(event.values[1] * 100)) / 100);
textview3.setText("滚动角:" + (float) (Math.round(event.values[2] * 100)) / 100);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
} |
package nova;
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.Test;
public class Testne2 {
@Test
public void mainTestInput(){
String input = "1\n";
ByteArrayInputStream in = new ByteArrayInputStream(input.getBytes());
System.setIn(in);
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
String[] args = {};
ne2.main(args);
String consoleOutput = "Enter the radius" +System.getProperty("line.separator");
consoleOutput += "For the circle with radius1.0 ,"+System.getProperty("line.separator");
consoleOutput += "the circumference is 6.283185307179586"+System.getProperty("line.separator");
consoleOutput += "and the area is3.141592653589793."+System.getProperty("line.separator");
assertEquals(consoleOutput, out.toString());
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import com.dthebus.designpatterns.behavioral.mediator.AmericanSeller;
import com.dthebus.designpatterns.behavioral.mediator.Buyer;
import com.dthebus.designpatterns.behavioral.mediator.DollarConverter;
import com.dthebus.designpatterns.behavioral.mediator.FrenchBuyer;
import com.dthebus.designpatterns.behavioral.mediator.Mediator;
import com.dthebus.designpatterns.behavioral.mediator.SwedishBuyer;
import static org.testng.Assert.*;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
*
* @author darren
*/
public class mediatorTest {
public mediatorTest() {
}
// TODO add test methods here.
// The methods must be annotated with annotation @Test. For example:
//
@Test
public void testMediator() {
Mediator m = new Mediator();
Buyer swedish = new SwedishBuyer(m);
Buyer french = new FrenchBuyer(m);
float sellingPriceInDollars = 10.0f;
AmericanSeller americanSeller = new AmericanSeller(m, sellingPriceInDollars);
DollarConverter dollarConverter = new DollarConverter(m);
float swedishBidInKronor = 55.0f;
float frenchBidInEuro = 70.0f;
// assertTrue(swedish.attemptToPurchase(swedishBidInKronor));
// assertTrue(french.attemptToPurchase(frenchBidInEuro));
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@BeforeMethod
public void setUpMethod() throws Exception {
}
@AfterMethod
public void tearDownMethod() throws Exception {
}
}
|
/*
* 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 at.ac.tuwien.dsg.controllerunit;
/**
*
* @author Anindita
*/
//// This class is used to design the structure of Desicion Node to Deciion Tree
public class DecisionNode {
public int nodeID;
public String value=null;
public EventNode decisionbranch=null;
public DecisionNode rootNode=null;
public DecisionNode()
{
}
public DecisionNode(int newNodeID, String decisionValue)
{
nodeID=newNodeID;
value=decisionValue;
}
}
|
package com.feng.genericClass;
public class SubOrder3<T> extends Order<T> {
//这个是泛型类
//这个和SubOrder2差不多
}
|
package com.javawebtutor.Controllers.EmployeeControllers;
import com.javawebtutor.Controllers.Controller;
import com.javawebtutor.Models.Users;
import com.javawebtutor.Models.Classes.UsersCheck;
import com.javawebtutor.Utilities.HibernateUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
public class EmployeeCheckUsersController extends Controller implements Initializable {
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.getCurrentSession();
public static int userId;
@FXML
private TableView<UsersCheck> tv1;
@FXML
private TableColumn<UsersCheck, String> name;
@FXML
private TableColumn<UsersCheck, String> surname;
@FXML
private TableColumn<UsersCheck, String> button1;
@FXML
private TableColumn<UsersCheck, String> button2;
@FXML
private TableColumn<UsersCheck, String> button3;
private ObservableList<UsersCheck> personData = FXCollections.observableArrayList();
@Override
public void initialize(URL location, ResourceBundle resources) {
checkUsers();
}
public void checkUsers(){
List<Users> users = loadAllData(Users.class, session);
tv1.setItems(personData);
for(Users u : users) {
Button b1 = new Button("Samochody");
Button b2 = new Button("Dodaj samochod");
Button b3 = new Button("Faktury");
b1.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
userId = u.getUserId();
changeScene(event, "/EmployeeCheckUserCarsScene.fxml");
} catch (IOException e) {
e.printStackTrace();
}
}
});
b2.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
userId = u.getUserId();
changeScene(event, "/EmployeeAddUserCarScene.fxml");
} catch (IOException e) {
e.printStackTrace();
}
}
});
b3.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
try {
userId = u.getUserId();
changeScene(event, "/EmployeeAddInvoiceScene.fxml");
} catch (IOException e) {
e.printStackTrace();
}
}
});
UsersCheck uc = new UsersCheck(u.getName(), u.getSurname(), b1, b2, b3);
name.setCellValueFactory(new PropertyValueFactory<>("name"));
surname.setCellValueFactory(new PropertyValueFactory<>("surname"));
button1.setCellValueFactory(new PropertyValueFactory<>("button1"));
button2.setCellValueFactory(new PropertyValueFactory<>("button2"));
button3.setCellValueFactory(new PropertyValueFactory<>("button3"));
personData.add(uc);
}
}
public void addUser(ActionEvent event) throws IOException {
changeScene(event, "/EmployeeAddUserScene.fxml");
}
public void backButton(ActionEvent event) throws IOException {
this.changeScene(event, "/EmployeeMainScene.fxml");
}
}
|
package algorithms.graph.process;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.List;
import algorithms.graph.Edge;
import algorithms.graph.EdgeWeightedGraph;
import algorithms.graph.MST;
import algorithms.sorting.heap.IndexMinPQ;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope(scopeName = "prototype")
public class PrimMST implements MST {
private BitSet marked;
private Edge[] edgeTo;
private Double[] distanceTo;
private IndexMinPQ<Double> queue;
//
private List<Edge> edgeList;
private Double totalWeight;
@Override
public void init(EdgeWeightedGraph graph) {
int vCount = graph.verticesCount();
marked = new BitSet(vCount);
edgeTo = new Edge[vCount];
distanceTo = new Double[vCount];
queue = new IndexMinPQ<>(vCount);
//
for (int i = 0; i < vCount; i++) {
distanceTo[i] = Double.POSITIVE_INFINITY;
}
distanceTo[0] = 0.0;
queue.insert(0, 0.0);
while (!queue.isEmpty()) {
visit(graph, queue.delMin());
}
}
private void visit(EdgeWeightedGraph graph, Integer v) {
marked.set(v);
for (Edge edge : graph.adjacent(v)) {
Integer w = edge.theOther(v);
if (marked.get(w)) {
continue;
}
if (edge.weight() < distanceTo[w]) {
edgeTo[w] = edge;
distanceTo[w] = edge.weight();
if (queue.contains(w)) {
queue.changeKey(w, edge.weight());
} else {
queue.insert(w, edge.weight());
}
}
}
}
@Override
public Collection<Edge> edges() {
if (edgeList == null) {
edgeList = new ArrayList<>();
for (Edge edge : edgeTo) {
if (edge != null) {
edgeList.add(edge);
}
}
}
return edgeList;
}
@Override
public Double weight() {
if (totalWeight == null) {
for (Edge edge : edgeTo) {
totalWeight += edge.weight();
}
}
return totalWeight;
}
}
|
package com.smyc.kaftanis.lookingfortable;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ThirdScreen extends AppCompatActivity {
Button next;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third_screen);
next = (Button) findViewById(R.id.button9);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ThirdScreen.this, FourthScreen.class);
startActivity(intent);
finish();
}
});
}
}
|
public class sixth {
public static void find_occur_one(int[] arr){
int len=arr.length;
for (int i=0;i<len;i++){
int count=1;
for(int j=i+1;j<len;j++){
if(arr[i]==arr[j]){
count++;
arr[j]=0;
}
}
if(count==1 && arr[i]!=0){
System.out.println(arr[i]);
}
}
}
public static void main(String[] args) {
int[] arr={2,1,3,2,1};
find_occur_one(arr);
}
}
|
/**
* Copyright (C) 2014-2017 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* 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.helger.commons.scope;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.helger.commons.annotation.Nonempty;
import com.helger.commons.collection.ext.ICommonsList;
import com.helger.commons.equals.EqualsHelper;
/**
* Interface for a single request scope object.
*
* @author Philip Helger
*/
public interface IRequestScope extends IScope
{
/**
* Shortcut for <code>getSessionID(true)</code>
*
* @return The session ID associated with this request. May be
* <code>null</code> if no session ID is present and no session should
* be created.
*/
@Nonnull
@Nonempty
default String getSessionID ()
{
return getSessionID (true);
}
/**
* @param bCreateIfNotExisting
* if <code>true</code> a session ID is created if needed
* @return The session ID associated with this request. May be
* <code>null</code> if no session ID is present and no session should
* be created.
*/
@Nullable
String getSessionID (boolean bCreateIfNotExisting);
/**
* Get a list of all attribute values with the same name.
*
* @param sName
* The name of the attribute to query.
* @return <code>null</code> if no such attribute value exists
*/
@Nullable
default ICommonsList <String> getAttributeAsList (@Nullable final String sName)
{
return getAttributeAsList (sName, null);
}
/**
* Get a list of all attribute values with the same name.
*
* @param sName
* The name of the attribute to query.
* @param aDefault
* The default value to be returned, if no such attribute is present.
* @return <code>aDefault</code> if no such attribute value exists
*/
@Nullable
ICommonsList <String> getAttributeAsList (@Nullable String sName, @Nullable ICommonsList <String> aDefault);
/**
* Check if a attribute with the given name is present in the request and has
* the specified value.
*
* @param sName
* The name of the attribute to check
* @param sDesiredValue
* The value to be matched
* @return <code>true</code> if an attribute with the given name is present
* and has the desired value
*/
default boolean hasAttributeValue (@Nullable final String sName, @Nullable final String sDesiredValue)
{
return EqualsHelper.equals (getAttributeAsString (sName), sDesiredValue);
}
/**
* Check if a attribute with the given name is present in the request and has
* the specified value. If no such attribute is present, the passed default
* value is returned.
*
* @param sName
* The name of the attribute to check
* @param sDesiredValue
* The value to be matched
* @param bDefault
* the default value to be returned, if the specified attribute is not
* present
* @return <code>true</code> if an attribute with the given name is present
* and has the desired value, <code>false</code> if the attribute is
* present but has a different value. If the attribute is not present,
* the default value is returned.
*/
default boolean hasAttributeValue (@Nullable final String sName,
@Nullable final String sDesiredValue,
final boolean bDefault)
{
final String sValue = getAttributeAsString (sName);
return sValue == null ? bDefault : EqualsHelper.equals (sValue, sDesiredValue);
}
}
|
import javax.swing.*;
import java.awt.*;
public class Cell {
boolean isMark = false;
byte value = 0;
JLabel label;
private Color color;
Cell(byte value){
this.value = value;
}
void setMark(boolean isMark){
this.isMark = isMark;
}
boolean getMark(){
return this.isMark;
}
void setValue(byte value){
this.value = value;
}
byte getValue(){
return this.value;
}
void addPutnik(Putnik putnik){
label.setIcon(new ImageIcon(putnik.getIconPath()));
}
void deletePutnik(){
label.setIcon(null);
}
}
|
package com.romitus;
import java.util.Calendar;
public class Pedido {
private Calendar momento;
private Pizzas pizza;
Pedido(){
Ingredientes i1 = new Ingredientes("Jamon",150);
Ingredientes i2 = new Ingredientes();
Ingredientes[] ingredientes = new Ingredientes[2];
ingredientes[0] = i1;
ingredientes[1] = i2;
pizza = new Pizzas(Pizzas.Size.FAMILIAR,ingredientes);
momento = Calendar.getInstance();
}
Pedido(Pizzas pizza){
momento = Calendar.getInstance();
this.pizza = pizza;
}
}
|
package com.mercadolibre.android.ui.legacy.widgets.image;
import androidx.annotation.NonNull;
import android.view.MotionEvent;
/**
* Component that detects translation, scale and rotation based on touch events.
* <p>
* This class notifies its listeners whenever a gesture begins, updates or ends.
* The instance of this detector is passed to the listeners, so it can be queried
* for pivot, translation, scale or rotation.
*/
@Deprecated
class TransformGestureDetector implements Detector, Detector.Gesture<Detector> {
/**
* Internal values for default transformations
*/
private static final int DEFAULT_ROTATION = 0;
private static final int DEFAULT_SCALE = 1;
/**
* Parent detector (we just hook on him and receive his callbacks)
*/
private final MultiPointerGestureDetector parentDetector;
/**
* Callback in case someone wants to hook on us and receive our callbacks
*/
private Detector.Gesture<Detector> listener = null;
/**
* Constructor
* @param multiPointerGestureDetector the detector from which we hook to receive gesture events
*/
public TransformGestureDetector(@NonNull MultiPointerGestureDetector multiPointerGestureDetector) {
parentDetector = multiPointerGestureDetector;
parentDetector.setGestureListener(this);
}
/**
* Factory method that creates a new instance of TransformGestureDetector
*/
public static @NonNull TransformGestureDetector newInstance() {
return new TransformGestureDetector(MultiPointerGestureDetector.newInstance());
}
/**
* Sets the listener.
* @param listener listener to set
*/
@Override
public void setGestureListener(@NonNull Detector.Gesture<Detector> listener) {
this.listener = listener;
}
/**
* Resets the component to the initial state.
*/
public void reset() {
parentDetector.reset();
}
/**
* Handles the given motion event.
* @param event event to handle
* @return whether or not the event was handled
*/
public boolean onTouchEvent(@NonNull final MotionEvent event) {
return parentDetector.onTouchEvent(event);
}
@Override
public void onGestureBegin(@NonNull Detector detector) {
if (listener != null) {
listener.onGestureBegin(this);
}
}
@Override
public void onGestureUpdate(@NonNull Detector detector) {
if (listener != null) {
listener.onGestureUpdate(this);
}
}
@Override
public void onGestureEnd(@NonNull Detector detector) {
if (listener != null) {
listener.onGestureEnd(this);
}
}
private float calcAverage(float[] arr, int len) {
float sum = 0;
for (int i = 0; i < len; i++) {
sum += arr[i];
}
return (len > 0) ? sum / len : 0;
}
/**
* Restarts the current gesture
*/
public void restartGesture() {
parentDetector.restartGesture();
}
/**
* Gets the X coordinate of the pivot point
*/
public float getPivotX() {
return calcAverage(parentDetector.getStartX(), parentDetector.getCount());
}
/**
* Gets the Y coordinate of the pivot point
*/
public float getPivotY() {
return calcAverage(parentDetector.getStartY(), parentDetector.getCount());
}
/**
* Gets the X component of the translation
*/
public float getTranslationX() {
return calcAverage(parentDetector.getCurrentX(), parentDetector.getCount()) -
calcAverage(parentDetector.getStartX(), parentDetector.getCount());
}
/**
* Gets the Y component of the translation
*/
public float getTranslationY() {
return calcAverage(parentDetector.getCurrentY(), parentDetector.getCount()) -
calcAverage(parentDetector.getStartY(), parentDetector.getCount());
}
/**
* Gets the scale
*/
public float getScale() {
if (parentDetector.getCount() < MultiPointerGestureDetector.MAX_POINTERS) {
return DEFAULT_SCALE; // Scale 1 == nothing
} else {
float startDeltaX = parentDetector.getStartX()[1] - parentDetector.getStartX()[0];
float startDeltaY = parentDetector.getStartY()[1] - parentDetector.getStartY()[0];
float currentDeltaX = parentDetector.getCurrentX()[1] - parentDetector.getCurrentX()[0];
float currentDeltaY = parentDetector.getCurrentY()[1] - parentDetector.getCurrentY()[0];
float startDist = (float) Math.hypot(startDeltaX, startDeltaY);
float currentDist = (float) Math.hypot(currentDeltaX, currentDeltaY);
return currentDist / startDist;
}
}
/**
* Gets the rotation in radians
*/
public float getRotation() {
if (parentDetector.getCount() < MultiPointerGestureDetector.MAX_POINTERS) {
return DEFAULT_ROTATION; // Rotation 0 == no rotation
} else {
float startDeltaX = parentDetector.getStartX()[1] - parentDetector.getStartX()[0];
float startDeltaY = parentDetector.getStartY()[1] - parentDetector.getStartY()[0];
float currentDeltaX = parentDetector.getCurrentX()[1] - parentDetector.getCurrentX()[0];
float currentDeltaY = parentDetector.getCurrentY()[1] - parentDetector.getCurrentY()[0];
float startAngle = (float) Math.atan2(startDeltaY, startDeltaX);
float currentAngle = (float) Math.atan2(currentDeltaY, currentDeltaX);
return currentAngle - startAngle;
}
}
}
|
package com.metoo.foundation.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.metoo.core.constant.Globals;
import com.metoo.core.domain.IdEntity;
/**
*
* <p>
* Title: OrderEnoughReduce.java
* </p>
*
* <p>
* Description: 满就减实体类。
* </p>
*
* <p>
* Copyright: Copyright (c) 2015
* </p>
*
* <p>
* Company: 沈阳网之商科技有限公司 www.koala.com
* </p>
*
* @author lixiaoyang
*
* @date 2014-9-19
*
* @version koala_b2b2c 2.0
*/
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Entity
@Table(name = Globals.DEFAULT_TABLE_SUFFIX + "enough_reduce")
public class EnoughReduce extends IdEntity {
private String ertitle;// 活动标题
@Temporal(TemporalType.DATE)
private Date erbegin_time;// 开始时间
@Temporal(TemporalType.DATE)
private Date erend_time;// 结束时间
private int ersequence;// 活动序号
@Column(columnDefinition = "int default 0")
private int erstatus;// 审核状态 -10为审核未通过 默认为0待审核 10为 审核通过
// 20为已结束。5为提交审核,此时商家不能再修改 30为活动已关闭
@Column(columnDefinition = "LongText")
private String failed_reason;// 审核失败原因
@Column(columnDefinition = "LongText")
private String ercontent;// 活动说明
private String ertag;// 活动的标识,满xxx减xxx
private String store_id;// 对应的店铺id
private String store_name;// 对应的店铺名字
private int er_type;// 满就减类型,0为自营,1为商家
@Column(columnDefinition = "LongText")
private String ergoods_ids_json;// 活动商品json
@Column(columnDefinition = "LongText")
private String er_json;// 满、减金额的json
@Column(columnDefinition = "LongText")
private String erbanner_goods_ids;// 活动精选商品id
public EnoughReduce() {
super();
// TODO Auto-generated constructor stub
}
public EnoughReduce(Long id, Date addTime) {
super(id, addTime);
// TODO Auto-generated constructor stub
}
public String getFailed_reason() {
return failed_reason;
}
public void setFailed_reason(String failed_reason) {
this.failed_reason = failed_reason;
}
public String getStore_name() {
return store_name;
}
public void setStore_name(String store_name) {
this.store_name = store_name;
}
public int getEr_type() {
return er_type;
}
public void setEr_type(int er_type) {
this.er_type = er_type;
}
public String getErtitle() {
return ertitle;
}
public void setErtitle(String ertitle) {
this.ertitle = ertitle;
}
public Date getErbegin_time() {
return erbegin_time;
}
public void setErbegin_time(Date erbegin_time) {
this.erbegin_time = erbegin_time;
}
public Date getErend_time() {
return erend_time;
}
public void setErend_time(Date erend_time) {
this.erend_time = erend_time;
}
public int getErsequence() {
return ersequence;
}
public void setErsequence(int ersequence) {
this.ersequence = ersequence;
}
public int getErstatus() {
return erstatus;
}
public void setErstatus(int erstatus) {
this.erstatus = erstatus;
}
public String getErcontent() {
return ercontent;
}
public void setErcontent(String ercontent) {
this.ercontent = ercontent;
}
public String getErtag() {
return ertag;
}
public void setErtag(String ertag) {
this.ertag = ertag;
}
public String getStore_id() {
return store_id;
}
public void setStore_id(String store_id) {
this.store_id = store_id;
}
public String getErgoods_ids_json() {
return ergoods_ids_json;
}
public void setErgoods_ids_json(String ergoods_ids_json) {
this.ergoods_ids_json = ergoods_ids_json;
}
public String getEr_json() {
return er_json;
}
public void setEr_json(String er_json) {
this.er_json = er_json;
}
public String getErbanner_goods_ids() {
return erbanner_goods_ids;
}
public void setErbanner_goods_ids(String erbanner_goods_ids) {
this.erbanner_goods_ids = erbanner_goods_ids;
}
}
|
package br.edu.ifpb.bdnc.projeto.entidades;
import com.vividsolutions.jts.geom.Point;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalTime;
/**
*
* @author Edilva
*/
public class Carona implements Serializable {
private int id;
private String origemTxt;
private String destinoTxt;
private Point origem;
private Point destino;
private LocalDate dataViagem;
private LocalTime horaSaida;
private String duracao;
private double ajudaCusto;
private String distancia;
private Usuario usuario;
public Carona(int id, String origemTxt, String destinoTxt, Point origem, Point destino, LocalDate dataViagem, LocalTime horaSaida, String duracao, double ajudaCusto, String distancia, Usuario usuario) {
this.id = id;
this.origemTxt = origemTxt;
this.destinoTxt = destinoTxt;
this.origem = origem;
this.destino = destino;
this.dataViagem = dataViagem;
this.horaSaida = horaSaida;
this.duracao = duracao;
this.ajudaCusto = ajudaCusto;
this.distancia = distancia;
this.usuario = usuario;
}
public Carona(String origemTxt, String destinoTxt, Point origem, Point destino, LocalDate dataViagem, LocalTime horaSaida, String duracao, double ajudaCusto, String distancia, Usuario usuario) {
this.origemTxt = origemTxt;
this.destinoTxt = destinoTxt;
this.origem = origem;
this.destino = destino;
this.dataViagem = dataViagem;
this.horaSaida = horaSaida;
this.duracao = duracao;
this.ajudaCusto = ajudaCusto;
this.distancia = distancia;
this.usuario = usuario;
}
public Carona() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOrigemTxt() {
return origemTxt;
}
public void setOrigemTxt(String origemTxt) {
this.origemTxt = origemTxt;
}
public String getDestinoTxt() {
return destinoTxt;
}
public void setDestinoTxt(String destinoTxt) {
this.destinoTxt = destinoTxt;
}
public Point getOrigem() {
return origem;
}
public void setOrigem(Point origem) {
this.origem = origem;
}
public Point getDestino() {
return destino;
}
public void setDestino(Point destino) {
this.destino = destino;
}
public LocalDate getDataViagem() {
return dataViagem;
}
public void setDataViagem(LocalDate dataViagem) {
this.dataViagem = dataViagem;
}
public LocalTime getHoraSaida() {
return horaSaida;
}
public void setHoraSaida(LocalTime horaSaida) {
this.horaSaida = horaSaida;
}
public String getDuracao() {
return duracao;
}
public void setDuracao(String duracao) {
this.duracao = duracao;
}
public double getAjudaCusto() {
return ajudaCusto;
}
public void setAjudaCusto(double ajudaCusto) {
this.ajudaCusto = ajudaCusto;
}
public String getDistancia() {
return distancia;
}
public void setDistancia(String distancia) {
this.distancia = distancia;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
@Override
public int hashCode() {
int hash = 5;
hash = 29 * hash + this.id;
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 Carona other = (Carona) obj;
if (this.id != other.id) {
return false;
}
return true;
}
@Override
public String toString() {
return "Carona{" + "id=" + id + ", origemTxt=" + origemTxt + ", destinoTxt=" + destinoTxt + ", origem=" + origem + ", destino=" + destino + ", dataViagem=" + dataViagem + ", horaSaida=" + horaSaida + ", duracao=" + duracao + ", ajudaCusto=" + ajudaCusto + ", distancia=" + distancia + ", usuario=" + usuario + '}';
}
}
|
package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dao.TeamDAO;
import com.model.Team;
@Service
@Transactional
public class TeamServiceImpl implements TeamService {
@Autowired
private TeamDAO teamDAO;
public void addTeam(Team team) {
teamDAO.addTeam(team);
}
public void updateTeam(Team team) {
teamDAO.updateTeam(team);
}
public Team getTeam(int id) {
return teamDAO.getTeam(id);
}
public void deleteTeam(int id) {
// TODO Auto-generated method stub
teamDAO.deleteTeam(id);
}
public List<Team> getTeam() {
return teamDAO.getTeam();
}
@Override
public java.util.List<Team> getTeam() {
// TODO Auto-generated method stub
return null;
}
}
|
package com.mike.blog.modal;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotBlank;
import java.util.Date;
/**
* This is the entity for blog
*
* @author Michael Ng
*
*/
@Entity
public class Blog {
@Id
@GeneratedValue //Auto generate primary key Id
private long id;
@NotBlank
private String title;
@NotBlank
private String content;
@NotBlank
private Date date;
@NotBlank
private String creator;
private String image;
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Blog() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
|
package todo;
import com.sun.tools.javac.comp.Todo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.SortedSet;
/**
* Created by sbyan on 6/20/16.
*/
@EnableAutoConfiguration
@RestController
@RequestMapping("/todo")
public class TodoController {
private TodoRepository todoItems;
public TodoController() {
todoItems = new TodoRepositoryImpl();
}
@RequestMapping("/all")
public Collection<TodoItem> getAllTodos() {
return todoItems.getAll();
}
@RequestMapping("/{key}")
public TodoItem getByKey(@PathVariable("key") String key) {
TodoItem item = todoItems.find(key);
return item;
}
@RequestMapping(method = RequestMethod.POST, value = "/create")
public String create(@RequestBody TodoItem item) {
todoItems.add(item);
return "Create succussful!";
}
@RequestMapping(method = RequestMethod.PUT, value = "/update/{key}")
public String update(@PathVariable("key") String key, @RequestBody TodoItem item) {
if (item == null || !item.getKey().equals(key))
{
return "error";
}
TodoItem todo = todoItems.find(key);
todoItems.update(item);
return "update succussful";
}
@RequestMapping(method = RequestMethod.DELETE, value = "/delete/{key}")
public String delete(@PathVariable("key") String key) {
todoItems.remove(key);
return "delete succussful";
}
// public static void main(String[] args) {
// SpringApplication.run(TodoController.class);
// }
}
|
/* Ara - capture species and specimen data
*
* Copyright (C) 2009 INBio (Instituto Nacional de Biodiversidad)
*
* This program 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
* (at your option) any later version.
*
* This program 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 org.inbio.ara.facade.indicator;
import java.util.List;
import javax.ejb.Remote;
import org.inbio.ara.dto.indicator.IndicatorDTO;
/**
*
* @author gsulca
*/
@Remote
public interface IndicatorFacadeRemote {
public List<IndicatorDTO> getChildrenByIndicatorId(Long indicatorId);
public IndicatorDTO getIndicatorByIndicatorId(Long indicatorId);
public IndicatorDTO saveNewIndicator(IndicatorDTO iDTO);
public IndicatorDTO updateIndicator(IndicatorDTO iDTO);
public Long countChildrenByIndicatorId(Long indicatorId);
public void deleteIndicator(Long IndicatorId);
public void saveIndicatorDublinCores(Long indicatorId, List<String> dublinCoreIds, String userName);
public Long countDublinCoreByIndicator(Long indicatorId);
public List<Long> getDublinCoreIdsByIndicator(Long indicatorId);
public void deleteIndicatorDublinCoreByIndicator(Long indicatorId);
public void deleteIndicatorDublinCoreById(Long indicatorId, Long dublinCoreId);
public void deleteIndicatorDublinCoreByIds(Long indicatorId, List<String> dublinCoreIds);
}
|
package dwz.common.component.threadpool;
import dwz.common.component.threadpool.ThreadPool.ThreadDiagnose;
/**
* 诊断信息接口
*
* @Author: LCF
* @Date: 2020/1/8 15:17
* @Package: dwz.common.component.threadpool
*/
public interface ThreadPoolDiagnose {
public boolean running();
public int maxsize();
public int size();
public ThreadDiagnose[] getDiagnose();
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.stdext.credential;
import org.springframework.stereotype.Component;
import pl.edu.icm.unity.server.authn.LocalCredentialVerificator;
import pl.edu.icm.unity.server.authn.LocalCredentialVerificatorFactory;
/**
* Produces verificators of certificates.
* @author K. Benedyczak
*/
@Component
public class CertificateVerificatorFactory implements LocalCredentialVerificatorFactory
{
public static final String NAME = "certificate";
@Override
public String getName()
{
return NAME;
}
@Override
public String getDescription()
{
return "Verifies certificates";
}
@Override
public LocalCredentialVerificator newInstance()
{
return new CertificateVerificator(getName(), getDescription());
}
@Override
public boolean isSupportingInvalidation()
{
return false;
}
}
|
package test;
public class TeamCommand
{
private int ave_total = 0; //默认为0为ave,1代表total
private int all_hot = -1; //默认小于零代表所有球队的信息,当大于零时代表获得热门球队,数值为命令数组的下标
private int num = -1; //默认值为-1,代表无此命令,值为30.当num为正数时,代表命令数组的下标
private int base_high = 0; //默认值为0代表基本数据类型,1代表高阶数据
private int sort = -1; //-1代表没有,当它大于1时代表命令数组的下标
public void readCommand(String[] command)
{
String str = null;
for (int i =1; i < command.length; i++)
{
switch (command[i])
{
case "-avg":
ave_total = 0;
break;
case "-total":
ave_total = 1;
break;
case "-all":
all_hot = -1;
break;
case "-hot":
all_hot = i +1;
break;
case "-n":
num = i +1;
break;
case "-high":
base_high = 1;
break;
case "-sort":
sort = i +1;
break;
}
}
}
public int getAve_total() {
return ave_total;
}
public int getAll_hot() {
return all_hot;
}
public int getNum() {
return num;
}
public int getBase_high() {
return base_high;
}
public int getSort() {
return sort;
}
}
|
/*
* IpFilter.java
*
* Created on 2007Äê7ÔÂ7ÈÕ, ÉÏÎç10:02
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package tot.filter;
import tot.global.Sysconfig;
import tot.util.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.regexp.RE;
/**
*
* @author totcms
*/
public final class IpFilter {
private static Log log = LogFactory.getLog(IpFilter.class);
private static RE[] blockedIPs = null;
private IpFilter() { //prevent instantiation
}
static {
//IPOptions ipOptions = new IPOptions();
//String[] blockedIPArray = StringUtil.getStringArray(ipOptions.blockedIP, ";");
String[] blockedIPArray = StringUtils.split(Sysconfig.getBlockedIPs(), ";");
blockedIPs = new RE[blockedIPArray.length];
for (int i = 0; i < blockedIPArray.length; i++) {
String currentIPRegExp = StringUtils.replaceString(blockedIPArray[i],"*", "(\\d{1,3})");
currentIPRegExp = "^" + currentIPRegExp + "$";
try {
log.debug("currentIPRegExp = " + currentIPRegExp);
blockedIPs[i] = new RE(currentIPRegExp);
} catch (Exception ex) {
log.error("Cannot parse the regular expression = " + currentIPRegExp, ex);
}
}
}
/**
* Filter the IP
* @param ip
* @return true if the IP in this request is ok
* false if the IP in this request is blocked
*/
public static boolean filter(String ip) {
if (ip == null) {
return false;
}
String checkIP =ip;
for (int i = 0; i < blockedIPs.length; i++) {
RE currentBlockedIP = blockedIPs[i];
if (currentBlockedIP != null) {
synchronized (currentBlockedIP) {
if (currentBlockedIP.match(checkIP)) {
return false;
}
}
}
}
return true;
}
} |
package com.ggtf.xieyingwu.brightnessapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private int brightness;
private TextView tv;
private BrightnessUtils utils;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
utils = new BrightnessUtils(this);
brightness = utils.getScreenBrightness();
showText(false);
}
public void btnClick(View view) {
switch (view.getId()) {
case R.id.btn_up:
brightness += 5;
break;
case R.id.btn_down:
brightness -= 5;
break;
}
checkBrightnessValue();
showText(true);
}
private void showText(boolean change) {
String text = "当前屏幕亮度:" + brightness;
tv.setText(text);
if (change) {
utils.saveScreenBrightness(brightness);
BrightnessUtils.saveBrightness(getContentResolver(), brightness);
}
}
private void checkBrightnessValue() {
// 亮度0-255
if (brightness >= 255) {
brightness = 0;
} else if (brightness <= 0) {
brightness = 255;
}
}
}
|
package com.lei.tang.frame.service.user.impl;
import com.lei.tang.frame.service.user.LoginRecordService;
import com.lei.tang.frame.service.user.UserAccountService;
import domain.CommonResponse;
import domain.user.UserAccountBean;
import entity.user.UserAccount;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import repository.user.UserAccountRepository;
import utils.AESUtil;
import utils.PasswordUtil;
import javax.servlet.http.HttpServletRequest;
/**
* @author tanglei
* @date 18/10/12
*/
@Service("userAccountService")
public class UserAccountServiceImpl implements UserAccountService {
@Autowired
private UserAccountRepository userAccountRepository;
@Autowired
private LoginRecordService loginRecordService;
@Override
public UserAccountBean login(HttpServletRequest request, String userAccount, String userPassword) {
Subject subject = SecurityUtils.getSubject();
//没有验证
if (!subject.isAuthenticated()) {
Assert.hasText(userAccount, "登录账号不能为空");
Assert.hasText(userPassword, "登录密码不能为空");
UsernamePasswordToken token = new UsernamePasswordToken(userAccount, userPassword);
//登录,抛出的异常在全局异常中处理
subject.login(token);
}
loginRecordService.save(request,(UserAccount) subject.getPrincipal());
return buildUserAccountBean(subject);
}
private UserAccountBean buildUserAccountBean(Subject subject) {
Assert.notNull(subject, "内部错误");
UserAccountBean bean = new UserAccountBean();
UserAccount account = (UserAccount) subject.getPrincipal();
bean.setAccount(account.getAccount());
bean.setToken(AESUtil.encrypt(subject.getSession().getId().toString()));
return bean;
}
@Override
public void logout() {
Subject subject = SecurityUtils.getSubject();
if (subject.isAuthenticated()) {
subject.logout();
}
}
@Override
public CommonResponse addUser(String userAccount, String userPassword) {
Assert.hasText(userAccount, "账号不能为空");
Assert.hasText(userPassword, "密码不能为空");
Assert.isNull(userAccountRepository.findUserAccountByAccount(userAccount), "账号已存在");
UserAccount account = new UserAccount();
account.setAccount(userAccount);
account.setIsAdmin(true);
account.setIsSystem(true);
String salty = PasswordUtil.generateSalty(userPassword);
account.setPasswordSalty(salty);
account.setPassword(PasswordUtil.encryptPassword(userPassword, salty));
userAccountRepository.save(account);
return new CommonResponse(true);
}
}
|
package karolinakaminska.github.com;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class PathReaderDbHelper extends SQLiteOpenHelper{
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "PathReader.db";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + PathReaderContract.PathEntry.TABLE_NAME + " (" +
PathReaderContract.PathEntry._ID + " INTEGER PRIMARY KEY," +
PathReaderContract.PathEntry.COLUMN_NAME_START_DATE + " TIMESTAMP," +
PathReaderContract.PathEntry.COLUMN_NAME_END_DATE + " TIMESTAMP," +
PathReaderContract.PathEntry.COLUMN_NAME_LOCATIONS + " LONGTEXT)";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + PathReaderContract.PathEntry.TABLE_NAME;
public PathReaderDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_CREATE_ENTRIES);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
//...
}
}
|
public class SortingAlgorithms {
public static void selectionSort(int[] arr) {
for(int pivot = 0; pivot < arr.length - 1; pivot++) {
int lowPosition = pivot;
for(int k = pivot + 1; k < arr.length; k++) {
//checks if it's the lowest
if(arr[k] < arr[lowPosition]) {
//sets lowest
lowPosition = k;
}
}
//switches numbers
int temp = arr[pivot];
arr[pivot] = arr[lowPosition];
arr[lowPosition] = temp;
}
}
public static void selectionSort(String[] arr) {
for(int pivot = 0; pivot < arr.length - 1; pivot++) {
int lowPosition = pivot;
for(int k = pivot + 1; k < arr.length; k++) {
//checks if it's the lowest
if(arr[k].compareTo(arr[lowPosition]) < 0) {
//sets lowest
lowPosition = k;
}
}
//switches string
String temp = arr[pivot];
arr[pivot] = arr[lowPosition];
arr[lowPosition] = temp;
}
}
public static void printArr(int[] arr) {
for(int num : arr) {
System.out.print(num + ", ");
}
System.out.println();
}
public static void printArr(String[] arr) {
for(String str : arr) {
System.out.print(str + ", ");
}
System.out.println();
}
}
|
package com.itheima;
import java.util.Scanner;
public class DebugTest02 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("输入第一个整数");
int a=in.nextInt();
System.out.println("输入第二个数");
int b=in.nextInt();
int max=getMax(a,b);
System.out.println("较大的值是"+max);
}
public static int getMax(int a,int b){
if(a>b){
return a;
}else{
return b;
}
}
}
|
package ru.duester.streams.v8.sources;
public class IterableStreamSource<T> implements IStreamSource<T> {
private IteratorStreamSource<T> iteratorSource;
public IterableStreamSource(Iterable<T> iterable) {
iteratorSource = new IteratorStreamSource<T>(iterable.iterator());
}
@Override
public T next() {
return iteratorSource.next();
}
}
|
package com.github.xuchengen;
/**
* 银联支付异常类
* 作者:徐承恩
* 邮箱:xuchengen@gmail.com
* 日期:2019/8/29
*/
public class UnionPayException extends Exception {
private static final long serialVersionUID = 8689355700637811882L;
public UnionPayException() {
super();
}
public UnionPayException(String message) {
super(message);
}
public UnionPayException(String message, Throwable cause) {
super(message, cause);
}
public UnionPayException(Throwable cause) {
super(cause);
}
}
|
package com.uchain.core.consensus;
import com.uchain.core.SwitchResult;
import java.util.List;
@FunctionalInterface
public interface OnSwitchBlock {
SwitchResult onSwitch(List<ForkItem> from, List<ForkItem> to, SwitchState switchState);
}
|
package com.stk123.model.bo;
import com.stk123.common.util.JdbcUtils.Column;
import java.math.BigDecimal;
import java.io.Serializable;
import com.stk123.common.util.JdbcUtils.Table;
@SuppressWarnings("serial")
@Table(name="STK_FN_TYPE")
public class StkFnType implements Serializable {
@Column(name="TYPE", pk=true)
private Integer type;
@Column(name="NAME")
private String name;
@Column(name="NAME_ALIAS")
private String nameAlias;
@Column(name="SOURCE")
private Integer source;
@Column(name="STATUS")
private Integer status;
@Column(name="MARKET")
private Integer market;
@Column(name="IS_PERCENT")
private Integer isPercent;
@Column(name="CURRENCY_UNIT_ADJUST")
private BigDecimal currencyUnitAdjust;
@Column(name="DISP_NAME")
private String dispName;
@Column(name="DISP_ORDER")
private Integer dispOrder;
@Column(name="RE_CALC")
private String reCalc;
@Column(name="TAB")
private Integer tab;
@Column(name="PRECISION")
private Integer precision;
@Column(name="COLSPAN")
private Integer colspan;
public Integer getType(){
return this.type;
}
public void setType(Integer type){
this.type = type;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public String getNameAlias(){
return this.nameAlias;
}
public void setNameAlias(String nameAlias){
this.nameAlias = nameAlias;
}
public Integer getSource(){
return this.source;
}
public void setSource(Integer source){
this.source = source;
}
public Integer getStatus(){
return this.status;
}
public void setStatus(Integer status){
this.status = status;
}
public Integer getMarket(){
return this.market;
}
public void setMarket(Integer market){
this.market = market;
}
public Integer getIsPercent(){
return this.isPercent;
}
public void setIsPercent(Integer isPercent){
this.isPercent = isPercent;
}
public BigDecimal getCurrencyUnitAdjust(){
return this.currencyUnitAdjust;
}
public void setCurrencyUnitAdjust(BigDecimal currencyUnitAdjust){
this.currencyUnitAdjust = currencyUnitAdjust;
}
public String getDispName(){
return this.dispName;
}
public void setDispName(String dispName){
this.dispName = dispName;
}
public Integer getDispOrder(){
return this.dispOrder;
}
public void setDispOrder(Integer dispOrder){
this.dispOrder = dispOrder;
}
public String getReCalc(){
return this.reCalc;
}
public void setReCalc(String reCalc){
this.reCalc = reCalc;
}
public Integer getTab(){
return this.tab;
}
public void setTab(Integer tab){
this.tab = tab;
}
public Integer getPrecision(){
return this.precision;
}
public void setPrecision(Integer precision){
this.precision = precision;
}
public Integer getColspan() {
return colspan;
}
public void setColspan(Integer colspan) {
this.colspan = colspan;
}
public String toString(){
return "type="+type+",name="+name+",nameAlias="+nameAlias+",source="+source+",status="+status+",market="+market+",isPercent="+isPercent+",currencyUnitAdjust="+currencyUnitAdjust+",dispName="+dispName+",dispOrder="+dispOrder+",reCalc="+reCalc+",tab="+tab+",precision="+precision;
}
}
|
package com.appirio.service.test.dao;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.appirio.service.member.api.MemberDistributionStats;
import com.appirio.service.member.api.SubTrackDistributionStats;
import com.appirio.service.member.dao.MemberDistributionStatsDAO;
import com.appirio.service.test.dao.util.DynamoDbTableUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.powermock.api.mockito.PowerMockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
*
* Created by rakeshrecharla on 8/23/15.
*/
public class MemberDistributionStatsDAOTest {
/**
* Logger for the class
*/
private Logger logger = LoggerFactory.getLogger(MemberDistributionStatsDAOTest.class);
private MemberDistributionStatsDAO memberDistributionStatsDAO;
private static final boolean MOCK_DB = true;
private static final String MemberDistributionStatsTable = "RatingsDistribution";
private static final DynamoDBMapper mapper = PowerMockito.mock(DynamoDBMapper.class);
private static final String track = "DEVELOP";
private static final String subTrack = "ARCHITECTURE";
private DynamoDbTableUtil dynamoDbTableUtil = new DynamoDbTableUtil();
private MemberDistributionStats buildMemberDistributionStats() {
SubTrackDistributionStats subTrackDistributionStats = new SubTrackDistributionStats();
subTrackDistributionStats.setRatingRange0To099(1L);
subTrackDistributionStats.setRatingRange1000To1099(10L);
MemberDistributionStats memberDistributionStats = new MemberDistributionStats();
memberDistributionStats.setTrack(track);
memberDistributionStats.setSubTrack(subTrack);
memberDistributionStats.setDistribution(subTrackDistributionStats);
return memberDistributionStats;
}
@Before
public void init() {
if (MOCK_DB) {
MemberDistributionStats memberDistributionStats = buildMemberDistributionStats();
this.memberDistributionStatsDAO = new MemberDistributionStatsDAO(mapper);
when(mapper.load(MemberDistributionStats.class, track, subTrack)).thenReturn(memberDistributionStats);
}
else {
this.memberDistributionStatsDAO = new MemberDistributionStatsDAO(dynamoDbTableUtil.getMapper());
ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<AttributeDefinition>();
attributeDefinitions.add(new AttributeDefinition()
.withAttributeName("track")
.withAttributeType("S"));
attributeDefinitions.add(new AttributeDefinition()
.withAttributeName("subTrack")
.withAttributeType("S"));
ArrayList<KeySchemaElement> keySchema = new ArrayList<KeySchemaElement>();
keySchema.add(new KeySchemaElement()
.withAttributeName("track")
.withKeyType(KeyType.HASH));
keySchema.add(new KeySchemaElement()
.withAttributeName("subTrack")
.withKeyType(KeyType.RANGE));
dynamoDbTableUtil.createDynamoDbTable(MemberDistributionStatsTable, keySchema, attributeDefinitions, null);
dynamoDbTableUtil.getDynamoDBTableInformation(MemberDistributionStatsTable);
Item item = new Item()
.withPrimaryKey("track", track, "subTrack", subTrack)
.withString("distribution", "{\"ratingRange0To099\":1,\"ratingRange1000To1099\":10}");
dynamoDbTableUtil.loadDynamoDbTable(MemberDistributionStatsTable, item);
}
}
@Test
public void testGetMemberDistributionStats() {
logger.debug("Get member distribution stats for " + MemberDistributionStatsTable);
MemberDistributionStats memberDistributionStats = memberDistributionStatsDAO.getMemberDistributionStats(track, subTrack);
if (MOCK_DB) {
verify(mapper).load(any(), anyString(), anyString());
}
assertNotNull(memberDistributionStats);
assertEquals(memberDistributionStats.getTrack(), track);
assertEquals(memberDistributionStats.getSubTrack(), subTrack);
assertEquals(memberDistributionStats.getDistribution().getRatingRange0To099(), Long.valueOf(1));
assertEquals(memberDistributionStats.getDistribution().getRatingRange1000To1099(), Long.valueOf(10));
}
@After
public void deleteMemberDistributionStatsTable() {
if (!MOCK_DB) {
dynamoDbTableUtil.deleteDynamoDbTable(MemberDistributionStatsTable);
}
}
}
|
package com.citibank.ods.common.security.connector;
import com.citibank.latam.sgway.service.LegacySgConnector;
import com.citibank.latam.sgway.util.RecordList;
/**
* @author leonardo.nakada
*
* Adaptador do Legacy Connection do Objeto MOCK SECURITY GATEWAY
*/
public class SecurityGatewayMockAdapter implements SecurityGatewayInterface
{
LegacySgConnector lc = null;
public SecurityGatewayMockAdapter()
{
lc = new LegacySgConnector();
}
/**
* Verifica se o usuário pode acessar o sistema
*/
public boolean canAccessSystem( String loginID_, String userIP_,
String sessionSpec_, int systemID_ )
throws Exception
{
return lc.canAccessSystem( loginID_, userIP_, sessionSpec_, systemID_ );
}
/**
* Carrega os módulos e as funções
*/
public RecordList getSystemModulesAndFunctions( String loginID_,
String userIP_,
String sessionSpec_,
int systemID_ )
throws Exception
{
return lc.getSystemModulesAndFunctions( loginID_, userIP_, sessionSpec_,
systemID_ );
}
/**
* Carrega os módulos
*/
public RecordList getSystemModules( String loginID_, String userIP_,
String sessionSpec_, int systemID_ )
throws Exception
{
return lc.getSystemModules( loginID_, userIP_, sessionSpec_, systemID_ );
}
/**
* Carrega as funções
*/
public RecordList getSystemModuleFunctions( String loginID_,
String userIP_,
String sessionSpec_,
int systemID_, int moduleID_ )
throws Exception
{
return lc.getSystemModuleFunctions( loginID_, userIP_, sessionSpec_,
systemID_, moduleID_ );
}
/*
* Carrega Nome e Sobrenome do usuário.
*/
public RecordList getUserBasicProfile( String loginID_, String userIP_,
String sessionSpec_ ) throws Exception
{
return lc.getUserBasicProfile( loginID_, userIP_, sessionSpec_ );
}
} |
package com.hhdb.csadmin.plugin.tree.ui.rightMenu;
import java.awt.event.ActionEvent;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import com.hh.frame.common.log.LM;
import com.hh.frame.swingui.event.CmdEvent;
import com.hhdb.csadmin.plugin.tree.HTree;
import com.hhdb.csadmin.plugin.tree.service.ScriptService;
import com.hhdb.csadmin.plugin.tree.ui.BaseTreeNode;
import com.hhdb.csadmin.plugin.tree.ui.script.MarScriptPanel;
/**
* 数据库集合右键菜单
*
* @author huyuanzhui
*
*/
public class DBsMenu extends BasePopupMenu {
private static final long serialVersionUID = 1L;
private BaseTreeNode treeNode;
private HTree htree = null;
public DBsMenu(HTree htree){
this.htree = htree;
add(createMenuItem("脚本管理", "scriptmar", this));
addSeparator();
add(createMenuItem("新建数据库", "adddb", this));
add(createMenuItem("刷新", "refresh", this));
}
public DBsMenu getInstance(BaseTreeNode node) {
treeNode = node;
return this;
}
@Override
public void actionPerformed(ActionEvent e) {
String actionCmd = e.getActionCommand();
if (actionCmd.equals("adddb")) {
CmdEvent addevent = new CmdEvent(htree.PLUGIN_ID, "com.hhdb.csadmin.plugin.database", "add");
htree.sendEvent(addevent);
}
else if (actionCmd.equals("refresh")) {
try {
htree.treeService.refreshDBCollection(treeNode);
} catch (Exception e1) {
LM.error(LM.Model.CS.name(), e1);
JOptionPane.showMessageDialog(null, e1.getMessage(), "消息",
JOptionPane.ERROR_MESSAGE);
}
}else if(actionCmd.equals("scriptmar")){
try {
if(!ScriptService.checkTableEst()){
ScriptService.initTable();
}
String toId = "com.hhdb.csadmin.plugin.tabpane";
CmdEvent tabPanelEvent = new CmdEvent(htree.PLUGIN_ID, toId, "AddPanelEvent");
tabPanelEvent.addProp("TAB_TITLE", "数据库脚本管理");
tabPanelEvent.addProp("COMPONENT_ID", "script_"+ScriptService.dbtype);
tabPanelEvent.addProp("ICO", "keys.png");
tabPanelEvent.setObj(new MarScriptPanel(ScriptService.dbtype));
htree.sendEvent(tabPanelEvent);
} catch (SQLException e1) {
LM.error(LM.Model.CS.name(), e1);
JOptionPane.showMessageDialog(null, e1.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
}
|
package com.lesports.airjordanplayer.ui.parser;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lesports.airjordanplayer.data.StreamInfoItem;
import com.lesports.airjordanplayer.data.VideoStreamItem;
import com.lesports.airjordanplayer.data.VideoStreamItemPrivate;
import com.lesports.airjordanplayer.ui.VideoStreamMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/**
* Created by xiaohs on 15/8/17.
*/
public class VODStreamMetadataParserImpl implements VideoStreamMetadataParser {
private static final Logger logger = LoggerFactory.getLogger(VODStreamMetadataParserImpl.class);
@Override
public VideoStreamMetadata parse(JsonObject jsonObject) throws Exception {
logger.info("Will parse VOD scheduling metadata from facade server: JSON -> " + jsonObject.toString());
JsonObject dataFragment = jsonObject.get("data").getAsJsonObject();
JsonObject infoFragment = dataFragment.getAsJsonObject().get("infos").getAsJsonObject();
VideoStreamMetadata metadata = new VideoStreamMetadata();
metadata.setTimestamp(jsonObject.get("timestamp").getAsString());
metadata.setStatus(dataFragment.get("status").getAsString());
for (Map.Entry<String, JsonElement> subElement : infoFragment.entrySet()) {
VideoStreamItem item = new VideoStreamItemPrivate();
item.setQualityName(subElement.getKey());
item.setType(VideoStreamItem.VideoStreamItemType.VOD);
JsonElement content = subElement.getValue();
StreamInfoItem streamInfoItem = new StreamInfoItem();
for (Map.Entry<String, JsonElement> contentElement : content.getAsJsonObject().entrySet()) {
if (contentElement.getKey().equalsIgnoreCase("code")) {
int code = contentElement.getValue().getAsInt();
streamInfoItem.setCode(code);
}
else if(contentElement.getKey().equalsIgnoreCase("isPay")) {
int isPay = contentElement.getValue().getAsInt();
streamInfoItem.setIsPay(isPay);
}
else if(contentElement.getKey().contains("Url")){
streamInfoItem.setUrl(contentElement.getValue().getAsString());
}
// if (contentElement.getKey().equalsIgnoreCase("code")) {
// int code = contentElement.getValue().getAsInt();
// item.setPlayable(code == 1 ? true : false);
// } else {
// item.getSchedulingUriCollection().add(contentElement.getValue().getAsString());
// }
}
item.getSchedulingUriCollection().add(streamInfoItem);
metadata.getAvailableQualifiedStreamItems().put(QualityMapConstants.QUALITY_MAP.get(item.getQualityName()), item);
}
return metadata;
}
}
|
package com.techelevator.models;
public abstract class NationalParkObject {
public abstract NationalParkObject getParent();
}
|
package cr.ac.tec.ce1103.structures.simple;
/**
* Clase de busqueda binaria
* @author Daniela Hernández
*
* @param <Tipo>
*/
public class BinarySearch <Tipo extends Comparable>{
private int indiceBusqueda;
public int getIndiceBuscado(){return indiceBusqueda;}
public static Integer[] RandomArray(){
Integer arreglo[] = new Integer[10];
for (int i=0; i<arreglo.length; i++){
arreglo[i] = (int)(Math.random()*100);
}
return arreglo;
}
/**
* Ordenamiento bubblesort
* @param arreglo
* @return
*/
public Tipo[] Ordenar(Tipo[] arreglo){
Tipo temp;
for(int ordenados = 0; ordenados<arreglo.length; ordenados++ ){
int desordenados = arreglo.length-ordenados;
int j = 0;
for(int i=0; i<desordenados-1;i++){
j=i+1;
if(arreglo[i].compareTo(arreglo[j])>0){
temp=arreglo[i];
arreglo[i]=arreglo[j];
arreglo[j]=temp;
}
}
}
return arreglo;
}
/**
* Realiza la busqueda de
* @param arreglo
* @param buscado
* @return valor del indice
*/
public Integer Busqueda(Tipo[] arregloOrdenado , Tipo Dato) {
int superior = arregloOrdenado.length - 1 ;
int inferiror = 0;
int medio;
while(inferiror<=superior){
//se toma la parte entera
medio = (inferiror + superior)/2;
if(Dato.compareTo(arregloOrdenado[medio])> 0)
inferiror = medio + 1 ;
else if (Dato.compareTo(arregloOrdenado[medio]) < 0)
superior = medio - 1;
else
return medio;
}
return -1;
}
}
|
package me.gabreuw.bearapi.domain.service.exception;
import org.springframework.web.bind.annotation.ResponseStatus;
import static org.springframework.http.HttpStatus.NOT_FOUND;
@ResponseStatus(NOT_FOUND)
public class BeerNotFoundException extends RuntimeException {
public BeerNotFoundException(String beerName) {
super(String.format(
"Beer with name %s not found in the system.",
beerName
));
}
public BeerNotFoundException(Long beerId) {
super(String.format(
"Beer with id %s not found in the system.",
beerId
));
}
}
|
package com.kieferlam.battlelan.game.player;
import com.kieferlam.battlelan.game.Game;
import com.kieferlam.battlelan.game.bufferobjects.CircleVBO;
import com.kieferlam.battlelan.game.bufferobjects.RectangleVBO;
import com.kieferlam.battlelan.game.bufferobjects.TexCoordBufferObject;
import com.kieferlam.battlelan.game.graphics.KrythicsTextureLoader;
import com.kieferlam.battlelan.game.graphics.TextureAnimator;
import com.kieferlam.battlelan.game.map.PhysicsCharacterBody;
import com.kieferlam.battlelan.game.shaders.Shader;
import com.kieferlam.battlelan.game.shaders.ShaderProgram;
import com.kieferlam.battlelan.settings.InputHandler;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.World;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import java.io.IOException;
/**
* Created by Kiefer on 02/05/2015.
*/
public class Character implements Playable{
public static ShaderProgram renderProgram;
public static Shader vertexShader, fragmentShader;
public static int uniformPositionLocation, uniformTextureLocation, uniformTextureOffsetLocation, uniformTextureCoordSizeLocation, uniformReflectLocation;
static{
renderProgram = new ShaderProgram();
vertexShader = new Shader(GL20.GL_VERTEX_SHADER);
fragmentShader = new Shader(GL20.GL_FRAGMENT_SHADER);
try {
vertexShader.loadSource(System.getProperty("user.dir") + "/Battlelan/src/com/kieferlam/battlelan/game/shaders/characterVertexShader.vert");
fragmentShader.loadSource(System.getProperty("user.dir") + "/Battlelan/src/com/kieferlam/battlelan/game/shaders/characterFragmentShader.frag");
vertexShader.attachSource();
fragmentShader.attachSource();
vertexShader.compile();
fragmentShader.compile();
renderProgram.attachShader(vertexShader);
renderProgram.attachShader(fragmentShader);
renderProgram.link();
renderProgram.validate();
renderProgram.use();
uniformPositionLocation = renderProgram.getUniformLocation("position");
uniformReflectLocation = renderProgram.getUniformLocation("reflect");
uniformTextureLocation = renderProgram.getUniformLocation("texture_diffuse");
uniformTextureOffsetLocation = renderProgram.getUniformLocation("texCoordOffset");
uniformTextureCoordSizeLocation = renderProgram.getUniformLocation("texCoordSize");
} catch (IOException e) {
e.printStackTrace();
}
}
public PhysicsCharacterBody body;
private RectangleVBO vbo;
private TexCoordBufferObject texBO;
private CircleVBO physicsVbo;
private Vec2 physicsRenderPosition;
private int texture_ID;
private TextureAnimator animator;
private boolean shouldReflect;
public Character(World world, Vec2 position, String textureLocation, TextureAnimator animator){
body = new PhysicsCharacterBody(world, position);
float renderBodyRadius = PhysicsCharacterBody.bodyRadius*1.0f/10.0f;
physicsRenderPosition = new Vec2(body.getRenderPosition(1.0f / 10.0f).x - renderBodyRadius, body.getRenderPosition(1.0f / 10.0f).y - renderBodyRadius);
vbo = new RectangleVBO(-renderBodyRadius, -renderBodyRadius, renderBodyRadius*2, renderBodyRadius*2.0f);
texBO = new TexCoordBufferObject(new float[]{
0.0f, animator.spriteSize.y,
animator.spriteSize.x, 0.0f,
0.0f, 0.0f,
0.0f, animator.spriteSize.y,
animator.spriteSize.x, 0.0f,
animator.spriteSize.x, animator.spriteSize.y
});
texBO.load(GL15.GL_STATIC_READ);
physicsVbo = new CircleVBO(body.getRenderPosition(1.0f / 10.0f).x, body.getRenderPosition(1.0f/10.0f).y, renderBodyRadius, 20);
texture_ID = KrythicsTextureLoader.loadTexture(KrythicsTextureLoader.loadImage(textureLocation));
this.animator = animator;
shouldReflect = false;
}
@Override
public void cursorPosEvent(long windowId, double xpos, double ypos) {
}
@Override
public void mouseButtonEvent(long windowId, int button, int action, int mods) {
}
@Override
public void keyEvent(long windowId, int key, int scancode, int action, int mods) {
if(action == GLFW.GLFW_PRESS){
if(key == Game.settings.bind_Jump){
body.jump();
}
}
}
@Override
public void logic(double delta, double time, InputHandler handler) {
float deltaf = (float) delta;
if(handler.right_down){
body.moveRight(deltaf);
}
if(handler.left_down){
body.moveLeft(deltaf);
}
animator.update(time * 1000);
System.out.println((animator.getTextureCoord()));
}
@Override
public void render(double delta) {
physicsVbo.position.set(body.getRenderPosition(1.0f / 10.0f));
// physicsVbo.enableState();
// physicsVbo.bindPointer();
// physicsVbo.render(program, positionLocation);
renderProgram.use();
GL13.glActiveTexture(GL13.GL_TEXTURE0);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture_ID);
renderProgram.setUniformInt(uniformTextureLocation, 0);
renderProgram.setUniformVec2(uniformTextureOffsetLocation, animator.getTextureCoord());
renderProgram.setUniformVec2(uniformTextureCoordSizeLocation, animator.spriteSize);
renderProgram.setUniformInt(uniformReflectLocation, shouldReflect ? 1 : 0);
physicsRenderPosition.set(physicsVbo.position);
vbo.position.set(physicsRenderPosition);
vbo.enableState();
texBO.enableState();
vbo.bindPointer();
texBO.bindPointer();
vbo.render(renderProgram, uniformPositionLocation);
}
@Override
public void delete() {
vbo.getVertexBufferObject().delete();
physicsVbo.getVertexBufferObject().delete();
texBO.delete();
GL11.glDeleteTextures(texture_ID);
}
}
|
package com.iq.demo;
class RemovingDuplicatesSimple {
public static void main(String[] args) {
String ip = "AAAB";
int count =0;
String op = "";
for (int i = 0; i < ip.length(); i++)
{
// if (ip.charAt(i % ip.length()) != ip.charAt((i + 1) % ip.length()))
if(ip.charAt(i % ip.length()) != ip.charAt((i+1) % ip.length()))
{
op += ip.charAt(i);
}
}
System.out.println(count + op);
}
}
//9923110930 |
package com.sapient.dao;
import java.sql.SQLException;
import java.util.List;
import com.sapient.model.Bug;
public interface IBugService {
void save(Bug newbug);
Bug selectBug(int id);
List<Bug> selectAllBugs();
boolean updateBug(Bug updatebug) throws SQLException;
void setBugDAO(BugDAOMock mockbugdao);
} |
package quanlycuahangsach;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class FileKH {
public static boolean saveFile(ArrayList<KhachHang> list, String path){
ArrayList<KhachHang> list1= new ArrayList<>();
// list1 = readFile(path);
try{
FileOutputStream fot= new FileOutputStream(path);
ObjectOutputStream oos= new ObjectOutputStream(fot);
// oos.writeObject(list1);
oos.writeObject(list);
oos.close();
fot.close();
return true;
}catch (Exception ex){
ex.printStackTrace();
}
return false;
}
public static ArrayList<KhachHang> readFile(String path){
ArrayList<KhachHang> listR= new ArrayList<>();
try {
FileInputStream fis= new FileInputStream(path);
ObjectInputStream ois= new ObjectInputStream(fis);
Object data= ois.readObject();
listR= (ArrayList<KhachHang>) data;
ois.close();
fis.close();
}catch (Exception ex){
ex.printStackTrace();
}
return listR;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.fastHotel.vista;
/**
*
* @author rudolf
*/
import java.awt.Color;
import java.awt.Component;
/*from w ww .j a va 2 s . c o m*/
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListCellRenderer;
public class Main extends JPanel {
final String[] DATA = {"One\n1", "Two\n2", "Three\n3", "saque cervezas huaris de las habitaciones: 204 y 208, para poner a la habitacion 209."};
DefaultListModel<String> listModel = new DefaultListModel<>();
JList<String> list = new JList<>(listModel);
public Main() {
list.setCellRenderer(new Listm(3, 30));
add(new JScrollPane(list));
for (String datum : DATA) {
listModel.addElement(datum);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new Main());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class Listm extends JTextArea implements ListCellRenderer {
protected Listm(int rows, int cols) {
super(rows, cols);
setBorder(BorderFactory.createLineBorder(Color.blue));
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
setLineWrap(true);
setWrapStyleWord(true);
setText(value.toString());
if (cellHasFocus) {
setBackground(Color.RED);
} else if (isSelected) {
setBackground(Color.BLUE);
} else {
setBackground(null);
}
return this;
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.junit.jupiter.event;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.springframework.test.context.event.ApplicationEventsHolder;
/**
* Default implementation of {@link PublishedEvents}.
*
* <p>Copied from the Moduliths project.
*
* @author Oliver Drotbohm
* @author Sam Brannen
* @since 5.3.3
*/
class DefaultPublishedEvents implements PublishedEvents {
@Override
public <T> TypedPublishedEvents<T> ofType(Class<T> type) {
return SimpleTypedPublishedEvents.of(ApplicationEventsHolder.getRequiredApplicationEvents().stream(type));
}
private static class SimpleTypedPublishedEvents<T> implements TypedPublishedEvents<T> {
private final List<T> events;
private SimpleTypedPublishedEvents(List<T> events) {
this.events = events;
}
static <T> SimpleTypedPublishedEvents<T> of(Stream<T> stream) {
return new SimpleTypedPublishedEvents<>(stream.toList());
}
@Override
public <S extends T> TypedPublishedEvents<S> ofSubType(Class<S> subType) {
return SimpleTypedPublishedEvents.of(getFilteredEvents(subType::isInstance)//
.map(subType::cast));
}
@Override
public TypedPublishedEvents<T> matching(Predicate<? super T> predicate) {
return SimpleTypedPublishedEvents.of(getFilteredEvents(predicate));
}
@Override
public <S> TypedPublishedEvents<T> matchingMapped(Function<T, S> mapper, Predicate<? super S> predicate) {
return SimpleTypedPublishedEvents.of(this.events.stream().flatMap(it -> {
S mapped = mapper.apply(it);
return predicate.test(mapped) ? Stream.of(it) : Stream.empty();
}));
}
private Stream<T> getFilteredEvents(Predicate<? super T> predicate) {
return this.events.stream().filter(predicate);
}
@Override
public Iterator<T> iterator() {
return this.events.iterator();
}
@Override
public String toString() {
return this.events.toString();
}
}
}
|
package com.codehunte.tis91d.model;
import javax.persistence.*;
@Entity
@Table(name = "cities")
public class City {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "idCity")
private int idCity;
@Column(name = "name", columnDefinition = "varchar(50)")
private String name;
public City() {
}
public City(int idCity, String name) {
this.idCity = idCity;
this.name = name;
}
public int getIdCity() {
return idCity;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "City{" +
"idCity=" + idCity +
", name='" + name + '\'' +
'}';
}
}
|
package edu.oleg088097.arkanoid.gameobjects;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
public class Paddle {
private int initialX;
private int initialY;
private int rightEdge;
private RectF rect;
private RectF drawedRect;
private float dx = 0;
private final Paint paintGray;
private final Paint paintBlue ;
public Paddle() {
rect = new RectF();
drawedRect = new RectF();
paintGray = new Paint();
paintGray.setColor(Color.parseColor("#666666"));
paintBlue = new Paint();
paintBlue.setColor(Color.parseColor("#00ccff")); //text_blue in decimal form
}
public void set(float width, float heigth, int initX, int initY, int rEdge) {
rect.set(initX, initY, initX + width, initY + heigth);
rightEdge = rEdge;
initialX = initX;
initialY = initY;
}
public void setDx(float x) {
dx = x;
}
public float getDx() {
return dx;
}
public void move() {
if (isEdge()) {
return;
}
rect.offset(dx, 0);
}
public RectF getRect() {
return rect;
}
public void resetState() {
rect.offsetTo(initialX, initialY);
}
public void expand() {
float x = rect.centerX();
float width = rect.width();
rect.set(x - width, rect.top, x + width, rect.bottom);
if (rect.right > rightEdge) {
rect.offset(rightEdge - rect.right, 0);
} else if (rect.left < 0) {
rect.offset(-rect.left, 0);
}
}
public void compress() {
float x = rect.centerX();
float width_4 = rect.width() / 4;
rect.set(x - width_4, rect.top, x + width_4, rect.bottom);
}
private boolean isEdge(){
float x = rect.left + dx;
return (x < 0) || (x > rightEdge - rect.width());
}
public void drawPaddle(Canvas canvas, float interpolation) {
if (isEdge()) {
interpolation = 0;
}
drawedRect.set(rect);
drawedRect.offset(dx * interpolation, 0);
paintGray.setStrokeWidth(2);
paintGray.setStyle(Paint.Style.FILL_AND_STROKE);
canvas.drawRoundRect(drawedRect, 10, 10, paintGray);
paintBlue.setStrokeWidth(2);
paintBlue.setStyle(Paint.Style.STROKE);
canvas.drawRoundRect(drawedRect.left+2, drawedRect.top+2, drawedRect.right-2, drawedRect.bottom-2, 10, 10, paintBlue);
canvas.drawRect(drawedRect.left+drawedRect.width()/2.23f, drawedRect.top+2, drawedRect.right-drawedRect.width()/2.23f,
drawedRect.bottom-2, paintBlue);
paintGray.setStyle(Paint.Style.FILL);
canvas.drawRect(drawedRect.left+drawedRect.width()/2.23f, drawedRect.top, drawedRect.right-drawedRect.width()/2.23f,
drawedRect.bottom, paintGray);
canvas.drawRect(drawedRect.left+drawedRect.width()/2.088f, drawedRect.top+1, drawedRect.right-drawedRect.width()/2.088f,
drawedRect.bottom-1, paintBlue);
}
}
|
package com.esum.web.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.apache.commons.collections.OrderedMap;
import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.esum.appetizer.util.BeanUtils;
import com.esum.framework.common.util.SequenceProperties;
import com.esum.framework.core.component.ComponentConstants;
import com.esum.framework.core.component.ComponentInfo;
import com.esum.framework.core.component.ComponentStatus;
import com.esum.framework.core.exception.SystemException;
import com.esum.framework.core.management.ManagementException;
import com.esum.framework.core.management.admin.AS2Admin;
import com.esum.framework.core.management.admin.EbMSAdmin;
import com.esum.framework.core.management.admin.XTrusAdmin;
import com.esum.framework.core.management.admin.XtrusAdminFactory;
import com.esum.framework.core.management.mbean.TransactionStatus;
import com.esum.framework.core.management.mbean.queue.QueueStatus;
import com.esum.framework.core.node.table.NodeInfo;
import com.esum.web.apps.componentinfo.service.ComponentInfoService;
import com.esum.web.apps.nodeinfo.service.NodeInfoService;
import com.esum.web.ims.jms.service.JmsInfoService;
public class ReloadXTrusAdmin {
protected final Log logger = LogFactory.getLog(getClass());
private static ReloadXTrusAdmin instance;
public static ReloadXTrusAdmin getInstance() {
if(instance==null)
instance = new ReloadXTrusAdmin();
return instance;
}
private List<NodeInfo> nodeInfoList = null;
private List<ComponentInfo> componentInfoList = null;
private List<XTrusAdmin> adminList = null;
private List<AS2Admin> as2AdminList = null;
private List<EbMSAdmin> ebmsAdminList = null;
private ReloadXTrusAdmin() {
initNodeInfos();
}
private void initNodeInfos() {
if (logger.isDebugEnabled())
logger.debug("Node information initializing...");
NodeInfoService nodeInfoService = BeanUtils.getBean(NodeInfoService.class);
List<NodeInfo> nodeList = nodeInfoService.getNodeInfoList();
ComponentInfoService componentInfoService = BeanUtils.getBean(ComponentInfoService.class);
List<ComponentInfo> componentList = componentInfoService.getProcessComponentInfoList();
this.nodeInfoList = new ArrayList<NodeInfo>();
for (NodeInfo nodeInfo : nodeList) {
nodeInfoList.add(nodeInfo);
}
this.componentInfoList = new ArrayList<ComponentInfo>();
for (ComponentInfo componentInfo : componentList) {
componentInfoList.add(componentInfo);
}
try {
loadXtrusAdmin();
} catch (ManagementException e) {
logger.error("loadXtrusAdmin error: " + e.getMessage(), e);
}
try {
loadAS2Admin();
} catch (ManagementException e) {
logger.error("loadAS2Admin error: " + e.getMessage(), e);
}
try {
loadEbMSAdmin();
} catch (ManagementException e) {
logger.error("loadEbMSAdmin error: " + e.getMessage(), e);
}
}
public List<NodeInfo> getMainNodeInfoList() {
if(this.nodeInfoList==null || this.nodeInfoList.size()==0)
return null;
List<NodeInfo> mainNodes = new ArrayList<NodeInfo>();
for(int i=0;i<this.nodeInfoList.size();i++) {
NodeInfo nodeInfo = this.nodeInfoList.get(i);
if(nodeInfo.getNodeType().equals(ComponentConstants.LOCATION_TYPE_MAIN))
mainNodes.add(nodeInfo);
}
return mainNodes;
}
private NodeInfo getMainNodeInfo(String mainNodeId) {
if(this.nodeInfoList==null || this.nodeInfoList.size()==0)
return null;
for(int i=0;i<this.nodeInfoList.size();i++) {
NodeInfo nodeInfo = this.nodeInfoList.get(i);
if(nodeInfo.getNodeType().equals(ComponentConstants.LOCATION_TYPE_MAIN) && nodeInfo.getNodeId().equals(mainNodeId))
return nodeInfo;
}
return null;
}
public NodeInfo getNodeInfo(String nodeId) {
if(this.nodeInfoList==null || this.nodeInfoList.size()==0)
return null;
for(int i=0;i<this.nodeInfoList.size();i++) {
NodeInfo nodeInfo = this.nodeInfoList.get(i);
if(nodeInfo.getNodeId().equals(nodeId))
return nodeInfo;
}
return null;
}
public NodeInfo getMainNodeInfoByNodeId(String nodeId) {
if(nodeId == null) {
nodeId = "MAIN";
}
if(this.nodeInfoList==null || this.nodeInfoList.size()==0)
return null;
NodeInfo found = null;
for(int i=0;i<this.nodeInfoList.size();i++) {
NodeInfo nodeInfo = this.nodeInfoList.get(i);
if(nodeInfo.getNodeId().equals(nodeId)) {
found = nodeInfo;
break;
}
}
if(found==null)
return null;
if(found.getNodeType().equals(ComponentConstants.LOCATION_TYPE_SUB)) {
return getMainNodeInfo(found.getMainNodeId());
}
return found;
}
public List<NodeInfo> getMainNodeListByCompId(String compId) {
List<String> mainNodeIdList = new ArrayList<String>();
for (int i=0; i<this.componentInfoList.size(); i++) {
ComponentInfo compInfo = componentInfoList.get(i);
if (compInfo.getId().equals(compId)) {
String mainNodeId = compInfo.getMainNodeId();
if (!mainNodeIdList.contains(mainNodeId))
mainNodeIdList.add(mainNodeId);
}
}
List<NodeInfo> mainNodeList = new ArrayList<NodeInfo>();
for (int i=0; i<mainNodeIdList.size(); i++) {
NodeInfo mainNodeInfo = getMainNodeInfoByNodeId(mainNodeIdList.get(i));
if (mainNodeInfo != null)
mainNodeList.add(mainNodeInfo);
}
return mainNodeList;
}
/**
* 특정 컴포넌트가 실행되는 노드 정보를 가져온다.
*/
public List<NodeInfo> getNodeListByCompId(String compId) {
List<String> foundList = new ArrayList<String>();
for (int i=0; i<this.componentInfoList.size(); i++) {
ComponentInfo compInfo = componentInfoList.get(i);
if (compInfo.getId().equals(compId)) {
String nodeId = compInfo.getNodeId();
if (!foundList.contains(nodeId))
foundList.add(nodeId);
}
}
List<NodeInfo> retNodeList = new ArrayList<NodeInfo>();
for (int i=0; i<foundList.size(); i++) {
NodeInfo nodeInfo = getNodeInfo(foundList.get(i));
if (nodeInfo != null)
retNodeList.add(nodeInfo);
}
return retNodeList;
}
/**
* XtrusAdmin 정보를 로드한다.
*/
public List<XTrusAdmin> loadXtrusAdmin() throws ManagementException {
List<NodeInfo> mainNodeInfoList = getMainNodeInfoList();
if(this.adminList!=null) {
return this.adminList;
}
this.adminList = new ArrayList<XTrusAdmin>();
for (int i=0;i<mainNodeInfoList.size(); i++) {
NodeInfo nodeInfo = mainNodeInfoList.get(i);
XTrusAdmin xtrusAdmin = XtrusAdminFactory.getInstance().getXtrusAdmin(
nodeInfo.getNodeId(), nodeInfo.getHostName(), nodeInfo.getPort());
this.adminList.add(xtrusAdmin);
}
return this.adminList;
}
/**
* 특정 노드에 대한 XtrusAdmin객체를 생성한다.
*/
public XTrusAdmin getXtrusAdminByNodeId(String nodeId) throws ManagementException {
NodeInfo nodeInfo = getMainNodeInfoByNodeId(nodeId);
if (nodeInfo == null) {
logger.error("Could not find MainNodeId from nodeId '"+nodeId+"'");
throw new ManagementException("xTrusAdminLoad()", "Could not find MainNodeId from nodeId '"+nodeId+"'");
}
XTrusAdmin xtrusAdmin = XtrusAdminFactory.getInstance().getXtrusAdmin(
nodeInfo.getNodeId(), nodeInfo.getHostName(), nodeInfo.getPort());
return xtrusAdmin;
}
public List<XTrusAdmin> getXtrusAdminListByCompId(String componentId) throws ManagementException {
List<NodeInfo> mainNodeInfoList = getMainNodeListByCompId(componentId);
List<XTrusAdmin> xTrusAdminList = new ArrayList<XTrusAdmin>();
int size = mainNodeInfoList.size();
for (int i=0; i<size; i++) {
NodeInfo nodeInfo = mainNodeInfoList.get(i);
XTrusAdmin xtrusAdmin = XtrusAdminFactory.getInstance().getXtrusAdmin(
nodeInfo.getNodeId(), nodeInfo.getHostName(), nodeInfo.getPort());
xTrusAdminList.add(xtrusAdmin);
}
return xTrusAdminList;
}
private boolean getRemoteStatus(XTrusAdmin xtrusAdmin, String compId) {
if (StringUtils.isEmpty(compId)) {
return false;
}
if (compId.equals(ComponentConstants.MAIN_COMPONENT_ID)) {
return true;
}
try {
String status = xtrusAdmin.getComponentStatus(compId);
return ComponentConstants.STATUS_RUNNING.equals(status);
} catch (Exception e) {
logger.error("ReloadXTrusAdmin getRemoteStatus Fail Exception", e);
return false;
}
}
public static String[] SECURITY_INFO_RECORD = new String[] {
"pki_store_id",
"xml_dsig_info_id",
"xml_enc_info_id",
"ftp_auth_info_id",
"http_auth_info_id",
"ssh_auth_info_id",
"sap_function_info_id"
};
public static String MAIN_COMPONENT_ID = "ROUTER";
/**
* System에서 사용하는 보안정보들을 Reload하도록 호출한다.
*/
public void reloadSecurityInfoRecord(String[] ids, String infoTableId) throws SystemException {
logger.info("Reloading security info record... infoTableId : "+infoTableId);
if (!ArrayUtils.contains(SECURITY_INFO_RECORD, infoTableId)) {
return;
}
if (adminList != null) {
for (XTrusAdmin xtrusAdmin : adminList) {
boolean running = getRemoteStatus(xtrusAdmin, MAIN_COMPONENT_ID);
if (running) {
xtrusAdmin.reloadSecurityInfo(infoTableId, ids);
}
}
}
}
/**
* IMS의 설정정보가 신규/변경/삭제 되었을 경우, 서버에게 reload할 수 있도록 알려준다.
*/
public void reloadInfoRecord(String nodeId, String[] ids, String infoTableId) throws SystemException {
logger.info("Reloading info record. nodeId : " + nodeId + ", infoTableId : "+infoTableId);
if (ArrayUtils.contains(SECURITY_INFO_RECORD, infoTableId)) {
reloadSecurityInfoRecord(ids, infoTableId);
} else {
if (StringUtils.isNotEmpty(nodeId)) {
XTrusAdmin xtrusAdmin = getXtrusAdminByNodeId(nodeId);
boolean running = getRemoteStatus(xtrusAdmin, MAIN_COMPONENT_ID);
if (running) {
xtrusAdmin.reloadInfoRecord(infoTableId, ids);
}
} else {
// 모든 MAIN 노드 들에게 알려준다.
if (adminList != null) {
for (XTrusAdmin xtrusAdmin : adminList) {
logger.info("Calling to '"+xtrusAdmin.getNodeId()+" for reloading InfoRecord");
boolean running = getRemoteStatus(xtrusAdmin, MAIN_COMPONENT_ID);
if (running) {
xtrusAdmin.reloadInfoRecord(infoTableId, ids);
}
}
}
}
}
}
public void reloadComponent(String[] ids, String compId) throws SystemException {
List<XTrusAdmin> xtrusAdminList = loadXtrusAdmin();
for (XTrusAdmin xtrusAdmin : xtrusAdminList) {
boolean isStarted = getRemoteStatus(xtrusAdmin, compId);
if (isStarted) {
xtrusAdmin.reloadComponent(compId, ids, true, true);
}
}
}
/**
* Get the status information of Queue.
*
* @param nodeId
* @return OrderedMap<ComponentStatus, List<QueueStatus>>
* @throws ManagementException
*/
public OrderedMap getQueueStatusList(String nodeId) throws ManagementException {
XTrusAdmin xtrusAdmin = getXtrusAdminByNodeId(nodeId);
try {
return xtrusAdmin.getQueueStatusList();
} catch (Exception e) {
logger.error("ReloadXTrusAdmin getQueueStatusList Fail Exception", e);
return new ListOrderedMap();
}
}
public String getComponentProperty(String componentId, String key) throws ManagementException {
String result = "";
List<XTrusAdmin> xtrusAdminList = getXtrusAdminListByCompId(componentId);
if (xtrusAdminList.size() > 0) {
XTrusAdmin xtrusAdmin = xtrusAdminList.get(0);
result = xtrusAdmin.getComponentProperty(componentId, key);
}
return result;
}
public SequenceProperties getConfigProperties(String nodeId, String compId, String relatedConfigPath) throws ManagementException {
if (logger.isDebugEnabled()) {
logger.debug("getConfigProperties(): nodeId: " + nodeId);
}
if (StringUtils.isEmpty(nodeId)) {
List<XTrusAdmin> xtrusAdminList = getXtrusAdminListByCompId(compId);
for (XTrusAdmin xtrusAdmin : xtrusAdminList) {
boolean isStarted = getRemoteStatus(xtrusAdmin, compId);
if (isStarted) {
try {
return xtrusAdmin.getConfigProperties(relatedConfigPath);
} catch (Exception e) {
logger.error("ReloadXTrusAdmin getConfigProperties failed.", e);
}
}
}
throw new ManagementException("getConfigProperties()",
compId + " Component is not running. Cannot get properties '" + relatedConfigPath + "'.");
} else {
String[] nodeIds = StringUtils.splitPreserveAllTokens(nodeId, ',');
// 첫번째 노드로 설정 정보 확인.
String compNodeId = nodeIds[0];
XTrusAdmin xtrusAdmin = getXtrusAdminByNodeId(compNodeId);
boolean isStarted = getRemoteStatus(xtrusAdmin, compId);
if (isStarted) {
try {
return xtrusAdmin.getConfigProperties(relatedConfigPath);
} catch (Exception e) {
throw e;
}
}
throw new ManagementException("getConfigProperties()",
compId + " Component is not running. nodeId '" + compNodeId + "'. Cannot get properties '" + relatedConfigPath + "'.");
}
}
private static final String HOTDEPLOY_SYSTEM_ERROR = "E909"; // TODO : throw AppetizerExeption(...);
public String deploy(String[] nodeIds, String appName, String version, String appFileName,
byte[] fileData, String description) throws ManagementException {
String result = null;
for(String nodeId : nodeIds) {
XTrusAdmin xTrusAdmin = getXtrusAdminByNodeId(nodeId);
try {
result = xTrusAdmin.deploy(nodeIds, appName, version, appFileName, fileData, description);
if(StringUtils.isNotEmpty(result) && !result.equals("0"))
return result;
} catch (ManagementException e) {
logger.error("ReloadXTrusAdmin deploy failed.", e);
return HOTDEPLOY_SYSTEM_ERROR;
}
}
return result;
}
public String delete(String nodeId, String appName, String version) throws ManagementException {
XTrusAdmin xTrusAdmin = getXtrusAdminByNodeId(nodeId);
try {
return xTrusAdmin.delete(appName, version);
} catch (ManagementException e) {
logger.error("ReloadXTrusAdmin delete failed.", e);
return HOTDEPLOY_SYSTEM_ERROR;
}
}
public String start(String nodeId, String appName, String version, String mode) throws ManagementException {
XTrusAdmin xTrusAdmin = getXtrusAdminByNodeId(nodeId);
try {
return xTrusAdmin.start(appName, version, mode);
} catch (ManagementException e) {
logger.error("ReloadXTrusAdmin start failed.", e);
return HOTDEPLOY_SYSTEM_ERROR;
}
}
public String stop(String nodeId, String appName, String version) throws ManagementException {
XTrusAdmin xTrusAdmin = getXtrusAdminByNodeId(nodeId);
try {
return xTrusAdmin.stop(appName, version);
} catch (ManagementException e) {
logger.error("ReloadXTrusAdmin stop failed.", e);
return HOTDEPLOY_SYSTEM_ERROR;
}
}
public String restart(String nodeId, String appName, String version) throws ManagementException {
XTrusAdmin xTrusAdmin = getXtrusAdminByNodeId(nodeId);
try {
return xTrusAdmin.restart(appName, version);
} catch (ManagementException e) {
logger.error("ReloadXTrusAdmin reStart failed.", e);
return HOTDEPLOY_SYSTEM_ERROR;
}
}
public String redeploy(String nodeId, String appName, String version) throws ManagementException {
XTrusAdmin xTrusAdmin = getXtrusAdminByNodeId(nodeId);
try {
return xTrusAdmin.redeploy(appName, version);
} catch (ManagementException e) {
logger.error("ReloadXTrusAdmin reDeploy failed.", e);
return HOTDEPLOY_SYSTEM_ERROR;
}
}
/**
* AS2Admin 정보를 로드한다.
*/
public List<AS2Admin> loadAS2Admin() throws ManagementException {
List<NodeInfo> mainNodeInfoList = getMainNodeInfoList();
if (this.as2AdminList != null) {
return this.as2AdminList;
}
this.as2AdminList = new ArrayList<AS2Admin>();
for (int i = 0; i < mainNodeInfoList.size(); i++) {
NodeInfo nodeInfo = mainNodeInfoList.get(i);
AS2Admin as2Admin = AS2Admin.newInstance(nodeInfo.getNodeId(), nodeInfo.getHostName(), nodeInfo.getPort());
as2Admin.setNodeId(nodeInfo.getNodeId());
this.as2AdminList.add(as2Admin);
}
return this.as2AdminList;
}
/**
* 특정 노드에 대한 AS2Admin 객체를 생성한다.
*/
public AS2Admin getAS2AdminByNodeId(NodeInfo nodeInfo) throws ManagementException {
AS2Admin as2Admin = AS2Admin.newInstance(nodeInfo.getNodeId(), nodeInfo.getHostName(), nodeInfo.getPort());
as2Admin.setNodeId(nodeInfo.getNodeId());
return as2Admin;
}
/**
* EbMSAdmin 정보를 로드한다.
*/
public List<EbMSAdmin> loadEbMSAdmin() throws ManagementException {
List<NodeInfo> mainNodeInfoList = getMainNodeInfoList();
if (this.ebmsAdminList != null) {
return this.ebmsAdminList;
}
this.ebmsAdminList = new ArrayList<EbMSAdmin>();
for (int i = 0; i < mainNodeInfoList.size(); i++) {
NodeInfo nodeInfo = mainNodeInfoList.get(i);
EbMSAdmin ebmsAdmin = EbMSAdmin.newInstance(nodeInfo.getNodeId(), nodeInfo.getHostName(), nodeInfo.getPort());
this.ebmsAdminList.add(ebmsAdmin);
}
return this.ebmsAdminList;
}
/**
* 특정 노드에 대한 EbMSAdmin 객체를 생성한다.
*/
public EbMSAdmin getEbMSAdminByNodeId(NodeInfo nodeInfo) throws ManagementException {
EbMSAdmin ebmsAdmin = EbMSAdmin.newInstance(nodeInfo.getNodeId(), nodeInfo.getHostName(), nodeInfo.getPort());
return ebmsAdmin;
}
/**
* 해당 컴포넌트의 Transaction Queue 정보들을 리턴한다.
*/
public List<QueueStatus> getQueueStatusList(final String mainNodeId, final String componentId) {
List<QueueStatus> queueStatusList = new ArrayList<QueueStatus>();
try {
if ("AS2".equals(componentId)) {
List<NodeInfo> nodeInfos = getNodeListByCompId(componentId);
for(NodeInfo nodeInfo : nodeInfos) {
if(nodeInfo.getMainNodeId().equals(mainNodeId)) {
AS2Admin as2Admin = getAS2AdminByNodeId(nodeInfo);
List<TransactionStatus> statusList = new ArrayList<TransactionStatus>();
try {
statusList = as2Admin.getTransactionStatus();
queueStatusList.addAll(getQueueStatusById(nodeInfo.getNodeId(), statusList, componentId));
} catch (Exception e) {
logger.warn("Cannot get Status Info. "+e.getMessage());
continue;
}
}
}
} else if ("EBMS".equals(componentId)) {
List<NodeInfo> nodeInfos = getNodeListByCompId(componentId);
for(NodeInfo nodeInfo : nodeInfos) {
if(nodeInfo.getMainNodeId().equals(mainNodeId)) {
EbMSAdmin ebmsAdmin = getEbMSAdminByNodeId(nodeInfo);
try {
List<TransactionStatus> statusList = ebmsAdmin.getTransactionStatus();
queueStatusList.addAll(getQueueStatusById(nodeInfo.getNodeId(), statusList, componentId));
} catch (Exception e) {
logger.warn("Cannot get Status Info. "+e.getMessage());
continue;
}
}
}
} else if ("JMS".equals(componentId)) {
List<NodeInfo> nodeInfos = getNodeListByCompId(componentId);
JmsInfoService jmsInfoService = BeanUtils.getBean(JmsInfoService.class);
for (NodeInfo nodeInfo : nodeInfos) {
String nodeId = nodeInfo.getNodeId();
if (nodeInfo.getMainNodeId().equals(mainNodeId)) {
// JMS의 PULL 채널명을 가져와야 한다.
List<String> queueNameList = jmsInfoService.getJmsQueueNameList(nodeId);
try {
XTrusAdmin xtrusAdmin = getXtrusAdminByNodeId(nodeId);
List<QueueStatus> statusList = xtrusAdmin.getQueueStatusAt(queueNameList);
if (statusList != null) {
for (QueueStatus queue : statusList) {
queue.putComponentStatus(nodeId, new ComponentStatus(nodeId, componentId,
queue.getConsumerCount()==0?ComponentConstants.STATUS_SHUTDOWN:ComponentConstants.STATUS_RUNNING));
queue.setCompId(componentId);
}
}
queueStatusList.addAll(statusList);
} catch (Exception e) {
logger.warn("Cannot get Status Info. "+e.getMessage());
continue;
}
}
}
}
} catch (Exception e) {
logger.error("Failed to get Queue StatusList. nodeId: " + mainNodeId + ", compId: " + componentId + ": " + e.getMessage());
}
return queueStatusList;
}
private List<QueueStatus> getQueueStatusById(String nodeId, List<TransactionStatus> list, final String componentId) {
List<QueueStatus> queueList = new ArrayList<QueueStatus>();
if (list == null || list.size() == 0) {
return null;
}
for (TransactionStatus tx : list) {
// 여러개의 node에 동일 컴포넌트가 구동될 수 있기때문에
// Queue 기준으로 해당되는 컴포넌트를 put한다.(컴포넌트 기준이 아닌 채널 이름 기준)
QueueStatus queue = new QueueStatus(componentId, tx.getChannelName(), tx.getConsumerCount(), tx.getCurrentSize());
queue.putComponentStatus(nodeId,
new ComponentStatus(nodeId, componentId, tx.getConsumerCount()==0?ComponentConstants.STATUS_SHUTDOWN:ComponentConstants.STATUS_RUNNING));
queueList.add(queue);
}
return queueList;
}
/**
* Purge Queue.
*/
public boolean purgeQueue(String mainNodeId, String componentId, String channelName) {
try {
if ("AS2".equals(componentId)) {
AS2Admin as2Admin = getAS2AdminByNodeId(getNodeInfo(mainNodeId));
//"Inbound", "Outbound"
return as2Admin.purgeTransaction(channelName);
} else if ("EBMS".equals(componentId)) {
EbMSAdmin ebmsAdmin = getEbMSAdminByNodeId(getNodeInfo(mainNodeId));
//"Inbound", "Outbound"
return ebmsAdmin.purgeTransaction(channelName);
}
} catch (Exception e) {
logger.error("Failed to purge Queue: " + e.getMessage());
}
return false;
}
/**
* Restart Queue Listener.
* Restart할 노드명과 컴포넌트명, 채널명이 들어와야 한다.
*/
public boolean restartQueueListener(String nodeId, String componentId, String channelName) {
try {
if ("AS2".equals(componentId)) {
AS2Admin as2Admin = getAS2AdminByNodeId(getNodeInfo(nodeId));
//"Inbound", "Outbound"
return as2Admin.restartTransaction(channelName);
} else if ("EBMS".equals(componentId)) {
EbMSAdmin ebmsAdmin = getEbMSAdminByNodeId(getNodeInfo(nodeId));
//"Inbound", "Outbound"
return ebmsAdmin.restartTransaction(channelName);
}
} catch (Exception e) {
logger.error("Failed to restart QueueListener: " + e.getMessage());
}
return false;
}
/** PKI **/
public boolean isKeyEntry(String nodeId, String path, char[] bytes, String type, String alias) throws SystemException {
XTrusAdmin admin = getXtrusAdminByNodeId(nodeId);
if (admin == null) {
logger.error("Failed to isKeyEntry. xTrusAdmin with '" + nodeId + "' not found.");
return false;
}
return admin.isKeyEntry(nodeId, path, bytes, type, alias);
}
public Map<String, String> createCertificateStore(String nodeId, String keystoreType, String alias, String path, String password, String certPath)
throws SystemException, FileNotFoundException, IOException {
XTrusAdmin admin = getXtrusAdminByNodeId(nodeId);
if (admin == null) {
logger.error("Failed to createCertificateStore. xTrusAdmin with '" + nodeId + "' not found.");
return null;
}
return admin.createCertificateStore(nodeId, keystoreType, alias, path, password, certPath);
}
/** SSL **/
public SequenceProperties getSSLSequencePropertiesConfig(String path) throws SystemException {
XTrusAdmin admin = getXtrusAdminByNodeId(null);
if (admin == null) {
logger.error("Failed to createCertificateStore. xTrusAdmin main not found.");
return null;
}
return admin.getSSLSequencePropertiesConfig(path);
}
public String replacePropertyToValue(String nodeId, String path) throws SystemException {
XTrusAdmin admin = getXtrusAdminByNodeId(nodeId);
if (admin == null) {
logger.error("Failed to replacePropertyToValue. xTrusAdmin with '" + nodeId + "' not found.");
return null;
}
return admin.replacePropertyToValue(nodeId, path);
}
public void loadAllStore(String path1, char[] bytes1, String type1, String path2, char[] bytes2, String type2) throws SystemException {
XTrusAdmin admin = getXtrusAdminByNodeId(null);
if (admin == null) {
logger.error("Failed to loadAllStore. xTrusAdmin main not found.");
return;
}
admin.loadAllStore(path1, bytes1, type1, path2, bytes2, type2);
}
public Map<String, Vector<String>> getStoreValueList(String alias) throws SystemException {
return getStoreValueList(alias, 0, -1);
}
public Map<String, Vector<String>> getStoreValueList(String alias, int startIdx, int endIdx) throws SystemException {
XTrusAdmin admin = getXtrusAdminByNodeId(null);
if (admin == null) {
logger.error("Failed to getStoreValueList. xTrusAdmin main not found.");
return null;
}
return admin.getStoreValueList(alias, startIdx, endIdx);
}
public Map<String, String> getStoreValue(String alias) throws SystemException {
XTrusAdmin admin = getXtrusAdminByNodeId(null);
if (admin == null) {
logger.error("Failed to getStoreValue. xTrusAdmin main not found.");
return null;
}
return admin.getStoreValue(alias);
}
public void loadTrustStore(String path, char[] bytes, String type) throws SystemException {
XTrusAdmin admin = getXtrusAdminByNodeId(null);
if (admin == null) {
logger.error("Failed to loadTrustStore. xTrusAdmin main not found.");
return;
}
admin.loadTrustStore(path, bytes, type);
}
public void deleteEntry(String nodeId, String alias) throws SystemException {
XTrusAdmin admin = getXtrusAdminByNodeId(nodeId);
if (admin == null) {
logger.error("Failed to deleteEntry. xTrusAdmin with '" + nodeId + "' not found.");
return;
}
admin.deleteEntry(nodeId, alias);
}
public void loadKeyStore(String path, char[] bytes, String type) throws SystemException {
XTrusAdmin admin = getXtrusAdminByNodeId(null);
if (admin == null) {
logger.error("Failed to loadKeyStore. xTrusAdmin main not found.");
return;
}
}
public void setCertificateEntry(String nodeId, byte[] items, String alias) throws SystemException {
XTrusAdmin admin = getXtrusAdminByNodeId(nodeId);
if (admin == null) {
logger.error("Failed to setCertificateEntry. xTrusAdmin with '" + nodeId + "' not found.");
return;
}
admin.setCertificateEntry(nodeId, items, alias);
}
public void setSSLProperty(String key, String value, String path) throws SystemException {
XTrusAdmin admin = getXtrusAdminByNodeId(null);
if (admin == null) {
logger.error("Failed to setSSLProperty. xTrusAdmin main not found.");
return;
}
admin.setSSLProperty(key, value, path);
}
/**
* 배치를 실행한다.
*
* @param nodeId 실행할 노드 ID
* @param batchIfId 실행할 배치IF ID
* @return 실행결과 (true: 성공, false: 실패)
* @throws SystemException
*/
public boolean executeBatch(String nodeId, String batchIfId) throws SystemException {
String BATCH_COMPONENT_ID = "BATCH";
XTrusAdmin admin = getXtrusAdminByNodeId(nodeId);
if (admin == null) {
logger.error("Could not execute batch. xTrusAdmin with '" + nodeId + "' not found.");
return false;
}
boolean running = getRemoteStatus(admin, BATCH_COMPONENT_ID);
if (running) {
return admin.executeBatch(batchIfId);
}
return false;
}
}
|
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.junit4;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.testfixture.beans.Employee;
import org.springframework.beans.testfixture.beans.Pet;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContextManager;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Simple JUnit 4 based integration test which demonstrates how to use JUnit's
* {@link Parameterized} Runner in conjunction with
* {@link ContextConfiguration @ContextConfiguration}, the
* {@link DependencyInjectionTestExecutionListener}, and a
* {@link TestContextManager} to provide dependency injection to a
* <em>parameterized test instance</em>.
*
* @author Sam Brannen
* @since 2.5
* @see org.springframework.test.context.junit4.rules.ParameterizedSpringRuleTests
*/
@RunWith(Parameterized.class)
@ContextConfiguration
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class })
public class ParameterizedDependencyInjectionTests {
private static final AtomicInteger invocationCount = new AtomicInteger();
private static final TestContextManager testContextManager = new TestContextManager(ParameterizedDependencyInjectionTests.class);
@Autowired
private ApplicationContext applicationContext;
@Autowired
private Pet pet;
@Parameter(0)
public String employeeBeanName;
@Parameter(1)
public String employeeName;
@Parameters(name = "bean [{0}], employee [{1}]")
public static String[][] employeeData() {
return new String[][] { { "employee1", "John Smith" }, { "employee2", "Jane Smith" } };
}
@BeforeClass
public static void BeforeClass() {
invocationCount.set(0);
}
@Before
public void injectDependencies() throws Exception {
testContextManager.prepareTestInstance(this);
}
@Test
public final void verifyPetAndEmployee() {
invocationCount.incrementAndGet();
// Verifying dependency injection:
assertThat(this.pet).as("The pet field should have been autowired.").isNotNull();
// Verifying 'parameterized' support:
Employee employee = this.applicationContext.getBean(this.employeeBeanName, Employee.class);
assertThat(employee.getName()).as("Name of the employee configured as bean [" + this.employeeBeanName + "].").isEqualTo(this.employeeName);
}
@AfterClass
public static void verifyNumParameterizedRuns() {
assertThat(invocationCount.get()).as("Number of times the parameterized test method was executed.").isEqualTo(employeeData().length);
}
}
|
package com.simplon.esportdata.controllers;
import com.simplon.esportdata.services.AdminService;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/admin")
@RestController
public class AdminController {
private final AdminService service;
protected AdminController(AdminService service) {
this.service = service;
}
@DeleteMapping("/cache/{region}")
protected void clearCacheRegion(@PathVariable("region") String region) {
service.clearCacheRegion(region);
}
@DeleteMapping("/caches")
protected void clearCacheRegions() {
service.clearCacheRegions();
}
}
|
/*
* 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 ejerc1;
import java.util.Scanner;
/**
*
* @author examen
*/
public class Obra {
String nombre;
String autor;
Scanner entrada = new Scanner(System.in);
public Obra() {
establecerNombre();
establecerAutor();
}
public Obra(String nombre, String autor) {
this.nombre = nombre;
this.autor = autor;
}
public void mostrarObra() {
System.out.println("Obra: " + nombre);
System.out.println("Autor: " + autor);
}
public String obtenerNombre() {
return nombre;
}
public void establecerNombre() {
System.out.print("Indique el nombre de la obra: ");
this.nombre = entrada.next();
}
public String obtenerAutor() {
return autor;
}
public void establecerAutor() {
System.out.print("Indique el nombre del autor: ");
this.autor = entrada.next();
}
} |
/*
* 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.core.io;
import org.springframework.lang.Nullable;
import org.springframework.util.ResourceUtils;
/**
* Strategy interface for loading resources (e.g., class path or file system
* resources). An {@link org.springframework.context.ApplicationContext}
* is required to provide this functionality plus extended
* {@link org.springframework.core.io.support.ResourcePatternResolver} support.
*
* <p>{@link DefaultResourceLoader} is a standalone implementation that is
* usable outside an ApplicationContext and is also used by {@link ResourceEditor}.
*
* <p>Bean properties of type {@code Resource} and {@code Resource[]} can be populated
* from Strings when running in an ApplicationContext, using the particular
* context's resource loading strategy.
*
* @author Juergen Hoeller
* @since 10.03.2004
* @see Resource
* @see org.springframework.core.io.support.ResourcePatternResolver
* @see org.springframework.context.ApplicationContext
* @see org.springframework.context.ResourceLoaderAware
*/
public interface ResourceLoader {
/** Pseudo URL prefix for loading from the class path: "classpath:". */
String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;
/**
* Return a {@code Resource} handle for the specified resource location.
* <p>The handle should always be a reusable resource descriptor,
* allowing for multiple {@link Resource#getInputStream()} calls.
* <p><ul>
* <li>Must support fully qualified URLs, e.g. "file:C:/test.dat".
* <li>Must support classpath pseudo-URLs, e.g. "classpath:test.dat".
* <li>Should support relative file paths, e.g. "WEB-INF/test.dat".
* (This will be implementation-specific, typically provided by an
* ApplicationContext implementation.)
* </ul>
* <p>Note that a {@code Resource} handle does not imply an existing resource;
* you need to invoke {@link Resource#exists} to check for existence.
* @param location the resource location
* @return a corresponding {@code Resource} handle (never {@code null})
* @see #CLASSPATH_URL_PREFIX
* @see Resource#exists()
* @see Resource#getInputStream()
*/
Resource getResource(String location);
/**
* Expose the {@link ClassLoader} used by this {@code ResourceLoader}.
* <p>Clients which need to access the {@code ClassLoader} directly can do so
* in a uniform manner with the {@code ResourceLoader}, rather than relying
* on the thread context {@code ClassLoader}.
* @return the {@code ClassLoader}
* (only {@code null} if even the system {@code ClassLoader} isn't accessible)
* @see org.springframework.util.ClassUtils#getDefaultClassLoader()
* @see org.springframework.util.ClassUtils#forName(String, ClassLoader)
*/
@Nullable
ClassLoader getClassLoader();
}
|
package com.driva.drivaapi.service.impl;
import com.driva.drivaapi.exception.LessonNotFoundException;
import com.driva.drivaapi.mapper.LessonMapper;
import com.driva.drivaapi.mapper.dto.LessonDTO;
import com.driva.drivaapi.model.lesson.Lesson;
import com.driva.drivaapi.model.product.Product;
import com.driva.drivaapi.model.user.Instructor;
import com.driva.drivaapi.model.user.pojo.GeneralLesson;
import com.driva.drivaapi.model.user.pojo.StudentLesson;
import com.driva.drivaapi.repository.LessonRepository;
import com.driva.drivaapi.service.LessonService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
public class LessonServiceImpl implements LessonService {
private final LessonRepository lessonRepository;
private final LessonMapper lessonMapper;
@Override
public List<LessonDTO> findAll() {
final List<Lesson> lessons = lessonRepository.findAll();
return lessonMapper.entitiesToLessonDTOs(lessons);
}
@Override
public Lesson find(Long id) {
return lessonRepository.findById(id).orElseThrow(
() -> new LessonNotFoundException("Lesson does not exist, id: " + id));
}
@Override
public LessonDTO findToLessonDTO(Long id) {
return lessonMapper.entityToLessonDTO(find(id));
}
@Override
public GeneralLesson findToGeneralLesson(Long id) {
final Lesson lesson = find(id);
return lessonMapper.entityToGeneralLesson(lesson);
}
@Override
public List<LessonDTO> findLessonsByInstructorId(Long id) {
final List<Lesson> lessons = lessonRepository.findByInstructorId_Id(id);
return lessonMapper.entitiesToLessonDTOs(lessons);
}
@Override
public LessonDTO save(LessonDTO lessonDTO, Product product, Instructor instructor) {
final Lesson lesson = lessonMapper.lessonDTOtoEntity(lessonDTO, product, instructor);
final Lesson savedLesson = lessonRepository.save(lesson);
return lessonMapper.entityToLessonDTO(savedLesson);
}
@Override
public LessonDTO update(Long id, LessonDTO lessonDTO, Instructor instructor) {
final Lesson lesson = find(id);
Lesson updatedLesson = lesson.update(lessonDTO);
updatedLesson.setInstructorId(instructor);
final Lesson save = lessonRepository.save(updatedLesson);
return lessonMapper.entityToLessonDTO(save);
}
@Override
public void delete(Long id) {
final Lesson lesson = find(id);
lessonRepository.delete(lesson);
}
@Override
public List<LessonDTO> findByProductId(Long productId) {
List<Lesson> lessons = lessonRepository.findByProductId_Id(productId);
return lessonMapper.entitiesToLessonDTOs(lessons);
}
public List<StudentLesson> findByProductIdToStudentLesson(Long productId) {
List<Lesson> lessons = lessonRepository.findByProductId_Id(productId);
return lessonMapper.entitiesToStudentLessonDTOs(lessons);
}
@Override
public List<GeneralLesson> findAllToGeneralLessons() {
final List<Lesson> lessons = lessonRepository.findAll();
return lessonMapper.entitiesToGeneralLessons(lessons);
}
@Override
public List<GeneralLesson> findAllLessonsByProductId(Long id) {
final List<Lesson> lessons = lessonRepository.findAllByProductId_Id(id);
return lessonMapper.entitiesToGeneralLessons(lessons);
}
}
|
package unisinos.tradutores.antlr.main.analiser;
import lombok.Builder;
import lombok.Getter;
import unisinos.tradutores.antlr.main.domain.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.Objects.isNull;
@Getter
@Builder
public class MethodAnaliser {
private Map<String, Integer> commands;
private final List<Method> methods;
private static final String PREFIX = "\t-> ";
private Integer getWeight(String command) {
if (isNull(commands)) {
initCommandWeight();
}
return commands.getOrDefault(command, 0);
}
private void initCommandWeight() {
commands = new HashMap<>();
commands.put("if", 1);
commands.put("else ifif", 1);
commands.put("case", 1);
commands.put("for", 1);
commands.put("do", 1);
commands.put("while", 1);
commands.put("?", 1);
commands.put("catch", 1);
}
public void analise() {
System.out.println("Resultados:");
methods.forEach(method -> {
System.out.println("-> Método: " + method.getName());
complexidadeCiclomatica(method);
fanOut(method);
nesting(method);
});
}
private void complexidadeCiclomatica(final Method method) {
int complexidadeCiclomatica = method.getCommands().stream().mapToInt(this::getWeight).sum();
complexidadeCiclomatica++;
System.out.println(PREFIX + "Complexidade Ciclomática: " + complexidadeCiclomatica);
}
private void fanOut(final Method method) {
System.out.println(PREFIX + "Fanout: " + method.getMethodsCalls().size());
}
private void nesting(final Method method) {
int nesting = 1;
int currentNesting = 1;
final List<String> blockStatements = new ArrayList<>(method.getBlockStatements());
Collections.reverse(blockStatements);
for (int i = 0; i < blockStatements.size() - 1; i++) {
String current = blockStatements.get(i);
String next = blockStatements.get(i + 1);
if (current.length() == next.length()) {
continue;
}
if (next.contains(current)) {
currentNesting++;
}
if (currentNesting > nesting) {
nesting = currentNesting;
}
}
System.out.println(PREFIX + "Aninhamento: " + nesting);
}
}
|
package picoplaca;
import java.util.HashMap;
public class DataMemory {
private static HashMap<String, String> _daysPlate;
private static HashMap<String, String> allowedHours;
public static HashMap<String, String> get_daysPlate() {
return _daysPlate;
}
public static HashMap<String, String> getAllowedHours() {
return allowedHours;
}
public static boolean createData(){
//save data in memory
try{
_daysPlate = new HashMap<String, String>();
_daysPlate.put("MONDAY", "1-2");
_daysPlate.put("TUESDAY", "3-4");
_daysPlate.put("WEDNESDAY", "5-6");
_daysPlate.put("THURSDAY", "7-8");
_daysPlate.put("FRIDAY", "9-0");
allowedHours = new HashMap<String, String>();
allowedHours.put("MORNING", "7.00-9.50");
allowedHours.put("AFTERNOON", "16.00-19.50");
return true;
}catch(Exception ex){
return false;
}
}
}
|
/************************************************
*
* Author: Ralph Joachim
*
************************************************/
package com.itembase.currency;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
* Application configuration settings read from application.properties
* are read and set in the object properties below
* Note: Only properties that begin with exchange. are stored here
*/
@Configuration
@EnableCaching
@ConfigurationProperties("exchange")
public class ApiConfig {
private boolean useShuffle;
private int requestTimeout=10_000;
private Duration cacheDuration;
private int apiRetry;
private int apiBackoff;
private List<String> baseUrls = new ArrayList<String>();
private List<String> rateUrls = new ArrayList<String>();
public boolean getUseShuffle() {
return useShuffle;
}
public long getRequestTimeout() {
return requestTimeout;
}
public List<String> getBaseUrls() {
return baseUrls;
}
public List<String> getRateUrls() {
return rateUrls;
}
public int getApiRetry() {
return apiRetry;
}
public int getApiBackoff() {
return apiBackoff;
}
public Duration getCacheDuration() {
return this.cacheDuration;
}
public void setUseShuffle(boolean useShuffle) {
this.useShuffle = useShuffle;
}
public void setRequestTimeout(int requestTimeout) {
this.requestTimeout = requestTimeout;
}
public void setBaseUrls(List<String> baseUrls) {
this.baseUrls = baseUrls;
}
public void setRateUrls(List<String> rateUrls){
this.rateUrls = rateUrls;
}
public void setCacheDuration(long timeMs) {
this.cacheDuration = Duration.ofMillis(timeMs);
}
public void setApiRetry(int apiRetry) {
this.apiRetry = apiRetry;
}
public void setApiBackoff(int apiBackoff) {
this.apiBackoff = apiBackoff;
}
/**
* Randomly rearranges the set of API endpoints read from application.properties file
*/
public void shuffle() {
if(this.useShuffle) {
int n = baseUrls.size();
for (int current = 0; current < (n - 1); current++) {
int other = ThreadLocalRandom.current().nextInt(current + 1, n);
swap(baseUrls, current, other);
swap(rateUrls, current, other);
}
}
}
private void swap(List<String> items, int i, int j) {
String tmp = items.get(i);
items.set(i,items.get(j));
items.set(j,tmp);
}
}
|
package com.example.web.client;
import com.example.soap.ProductClient;
import com.example.soap.product.ProductModel;
import com.example.web.form.ProductForm;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.Collections;
import java.util.List;
@Slf4j
@Controller
@RequiredArgsConstructor
public class ProductController {
private final ProductClient productClient;
@GetMapping({"/product"})
public String index(Model model) {
try {
List<ProductModel> products = productClient.getAllProducts();
model.addAttribute("productsDto", products);
model.addAttribute("productForm", new ProductForm());
} catch (RuntimeException e) {
model.addAttribute("productsDto", Collections.emptyList());
model.addAttribute("errorMessage", "Error: " + e.getMessage());
}
return "product-all";
}
@GetMapping("/product/{id}")
public String getProduct(@PathVariable("id") Integer id, Model model) {
ProductModel productModel = productClient.getProductById(id);
ProductForm productForm = new ProductForm();
log.info(productModel.toString());
BeanUtils.copyProperties(productModel, productForm);
log.info(productForm.toString());
model.addAttribute("productForm", productForm);
return "product-form-update";
}
@GetMapping("/product/new")
public String getProductNew(Model model) {
ProductForm productForm = new ProductForm();
model.addAttribute("productForm", productForm);
return "product-form-add";
}
@PostMapping("/product")
public String addProduct(Model model, ProductForm productForm) {
ProductModel productModel = new ProductModel();
productModel.setName(productForm.getName());
productModel.setDescription(productForm.getDescription());
try {
productModel = productClient.addProduct(productModel);
productForm.setId(productModel.getId());
model.addAttribute("productForm", productForm);
} catch (Exception e) {
log.error(e.getMessage());
model.addAttribute("errorMessage", "Error: " + e.getMessage());
}
return "product-form-add";
}
@PutMapping("/product")
public String updateProduct(Model model, ProductForm productForm) {
log.info(productForm.toString());
ProductModel productModel = new ProductModel();
BeanUtils.copyProperties(productForm, productModel);
try {
productModel = productClient.updateProduct(productModel);
productForm.setId(productModel.getId());
model.addAttribute("productForm", productForm);
} catch (Exception e) {
log.error(e.getMessage());
model.addAttribute("errorMessage", "Error: " + e.getMessage());
}
return "product-form-update";
}
}
|
package cn.jpush.impl.im;
import cn.jpush.kafka.MultiScheme;
import cn.jpush.kafka.MultiSchemeFactory;
public class SendSchemeFactory implements MultiSchemeFactory {
@Override
public MultiScheme createScheme() {
return new SendScheme();
}
}
|
package net.integration.zk;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
/**
* @author: zhangwei
* @date: 下午1:03/2018/8/1
*/
public class TestLock {
private CuratorFramework client;
@Before
public void init(){
client = createCuratorFramework(null, "test-lock");
client.start();
}
@After
public void destruct(){
if(client != null)
client.close();
}
private static CuratorFramework createCuratorFramework(String connectString, String namespace){
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
CuratorFramework client = builder.connectString(connectString == null ? "47.91.217.180:12181" : connectString)
.sessionTimeoutMs(30000)
.connectionTimeoutMs(30000)
.canBeReadOnly(false)
.retryPolicy(new ExponentialBackoffRetry(1000, Integer.MAX_VALUE))
.namespace(namespace)
.defaultData(null)
.build();
return client;
}
@Test
public void lockTest(){
try {
InterProcessMutex lock = new InterProcessMutex(client, "/examples/unlock");
if(lock.acquire(10, TimeUnit.SECONDS)){
System.out.println("get Lock");
}
lock.release();
}catch (Exception e){
e.printStackTrace();
}
}
@Test
public void lockTest1(){
try{
System.out.println(new String(client.getData().forPath("/test")));
}catch (Exception e){
e.printStackTrace();
}
}
}
|
package slimeknights.tconstruct.tools;
import net.minecraft.entity.monster.EntitySlime;
import slimeknights.tconstruct.library.traits.AbstractTrait;
import slimeknights.tconstruct.tools.traits.TraitAlien;
import slimeknights.tconstruct.tools.traits.TraitAquadynamic;
import slimeknights.tconstruct.tools.traits.TraitAridiculous;
import slimeknights.tconstruct.tools.traits.TraitAutosmelt;
import slimeknights.tconstruct.tools.traits.TraitBaconlicious;
import slimeknights.tconstruct.tools.traits.TraitBonusDamage;
import slimeknights.tconstruct.tools.traits.TraitBreakable;
import slimeknights.tconstruct.tools.traits.TraitCheap;
import slimeknights.tconstruct.tools.traits.TraitCheapskate;
import slimeknights.tconstruct.tools.traits.TraitColdblooded;
import slimeknights.tconstruct.tools.traits.TraitCrude;
import slimeknights.tconstruct.tools.traits.TraitCrumbling;
import slimeknights.tconstruct.tools.traits.TraitDense;
import slimeknights.tconstruct.tools.traits.TraitDepthdigger;
import slimeknights.tconstruct.tools.traits.TraitDuritos;
import slimeknights.tconstruct.tools.traits.TraitEcological;
import slimeknights.tconstruct.tools.traits.TraitEnderference;
import slimeknights.tconstruct.tools.traits.TraitEndspeed;
import slimeknights.tconstruct.tools.traits.TraitEstablished;
import slimeknights.tconstruct.tools.traits.TraitFlammable;
import slimeknights.tconstruct.tools.traits.TraitFreezing;
import slimeknights.tconstruct.tools.traits.TraitHeavy;
import slimeknights.tconstruct.tools.traits.TraitHellish;
import slimeknights.tconstruct.tools.traits.TraitHoly;
import slimeknights.tconstruct.tools.traits.TraitHovering;
import slimeknights.tconstruct.tools.traits.TraitInsatiable;
import slimeknights.tconstruct.tools.traits.TraitJagged;
import slimeknights.tconstruct.tools.traits.TraitLightweight;
import slimeknights.tconstruct.tools.traits.TraitMagnetic;
import slimeknights.tconstruct.tools.traits.TraitMomentum;
import slimeknights.tconstruct.tools.traits.TraitPetramor;
import slimeknights.tconstruct.tools.traits.TraitPoisonous;
import slimeknights.tconstruct.tools.traits.TraitPrickly;
import slimeknights.tconstruct.tools.traits.TraitSharp;
import slimeknights.tconstruct.tools.traits.TraitShocking;
import slimeknights.tconstruct.tools.traits.TraitSlimey;
import slimeknights.tconstruct.tools.traits.TraitSpiky;
import slimeknights.tconstruct.tools.traits.TraitSplintering;
import slimeknights.tconstruct.tools.traits.TraitSplinters;
import slimeknights.tconstruct.tools.traits.TraitSplitting;
import slimeknights.tconstruct.tools.traits.TraitSqueaky;
import slimeknights.tconstruct.tools.traits.TraitStiff;
import slimeknights.tconstruct.tools.traits.TraitStonebound;
import slimeknights.tconstruct.tools.traits.TraitSuperheat;
import slimeknights.tconstruct.tools.traits.TraitTasty;
import slimeknights.tconstruct.tools.traits.TraitUnnatural;
import slimeknights.tconstruct.tools.traits.TraitWritable;
import slimeknights.tconstruct.world.entity.EntityBlueSlime;
public class TinkerTraits {
// general material traits
public static final AbstractTrait alien = new TraitAlien();
public static final AbstractTrait aquadynamic = new TraitAquadynamic();
public static final AbstractTrait aridiculous = new TraitAridiculous();
public static final AbstractTrait autosmelt = new TraitAutosmelt();
public static final AbstractTrait baconlicious = new TraitBaconlicious();
public static final AbstractTrait cheap = new TraitCheap();
public static final AbstractTrait cheapskate = new TraitCheapskate();
public static final AbstractTrait coldblooded = new TraitColdblooded();
public static final AbstractTrait crude = new TraitCrude(1);
public static final AbstractTrait crude2 = new TraitCrude(2);
public static final AbstractTrait crumbling = new TraitCrumbling();
public static final AbstractTrait dense = new TraitDense();
public static final AbstractTrait depthdigger = new TraitDepthdigger();
public static final AbstractTrait duritos = new TraitDuritos(); // yes you read that correctly
public static final AbstractTrait ecological = new TraitEcological();
public static final AbstractTrait enderference = new TraitEnderference();
public static final AbstractTrait established = new TraitEstablished();
public static final AbstractTrait flammable = new TraitFlammable();
public static final AbstractTrait fractured = new TraitBonusDamage("fractured", 1.5f);
public static final AbstractTrait heavy = new TraitHeavy();
public static final AbstractTrait hellish = new TraitHellish();
public static final AbstractTrait holy = new TraitHoly();
public static final AbstractTrait insatiable = new TraitInsatiable();
public static final AbstractTrait jagged = new TraitJagged();
public static final AbstractTrait lightweight = new TraitLightweight();
public static final AbstractTrait magnetic = new TraitMagnetic(1);
public static final AbstractTrait magnetic2 = new TraitMagnetic(2);
public static final AbstractTrait momentum = new TraitMomentum();
public static final AbstractTrait petramor = new TraitPetramor();
public static final AbstractTrait poisonous = new TraitPoisonous();
public static final AbstractTrait prickly = new TraitPrickly();
public static final AbstractTrait sharp = new TraitSharp();
public static final AbstractTrait shocking = new TraitShocking();
public static final AbstractTrait slimeyGreen = new TraitSlimey("green", EntitySlime.class);
public static final AbstractTrait slimeyBlue = new TraitSlimey("blue", EntityBlueSlime.class);
public static final AbstractTrait spiky = new TraitSpiky();
public static final AbstractTrait splintering = new TraitSplintering();
public static final AbstractTrait splinters = new TraitSplinters();
public static final AbstractTrait squeaky = new TraitSqueaky();
public static final AbstractTrait superheat = new TraitSuperheat();
public static final AbstractTrait stiff = new TraitStiff();
public static final AbstractTrait stonebound = new TraitStonebound();
public static final AbstractTrait tasty = new TraitTasty();
public static final AbstractTrait unnatural = new TraitUnnatural();
public static final AbstractTrait writable = new TraitWritable(1);
public static final AbstractTrait writable2 = new TraitWritable(2);
// arrow shaft traits
public static final AbstractTrait breakable = new TraitBreakable();
public static final AbstractTrait endspeed = new TraitEndspeed();
public static final AbstractTrait freezing = new TraitFreezing();
public static final AbstractTrait hovering = new TraitHovering();
public static final AbstractTrait splitting = new TraitSplitting();
}
|
package com.intel.realsense.librealsense;
public class DisparityTransformFilter extends Filter {
public DisparityTransformFilter(boolean transformToDisparity){
mHandle = nCreate(mQueue.getHandle(), transformToDisparity);
}
private static native long nCreate(long queueHandle, boolean transformToDisparity);
} |
package com.doc.spring.custom;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class BeanToValidate implements Validator{
//Nice to have a name at least
private String name;
public boolean supports(Class<?> clazz) {
return BeanToValidate.class.equals(clazz);
}
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "name", "name.empty");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package com.yxkj.facexradix.star;
import java.util.List;
public class MobPushBean {
private String appkey;
private String content;
private int target;
private int type;
private List<Integer> plats;
private List<String> registrationIds;
private String data;
private String extras;
private int iosProduction;
public String getExtras() {
return extras;
}
public void setExtras(String extras) {
this.extras = extras;
}
public int getIosProduction() {
return iosProduction;
}
public void setIosProduction(int iosProduction) {
this.iosProduction = iosProduction;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getAppkey() {
return appkey;
}
public void setAppkey(String appkey) {
this.appkey = appkey;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getTarget() {
return target;
}
public void setTarget(int target) {
this.target = target;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public List<Integer> getPlats() {
return plats;
}
public void setPlats(List<Integer> plats) {
this.plats = plats;
}
public List<String> getRegistrationIds() {
return registrationIds;
}
public void setRegistrationIds(List<String> registrationIds) {
this.registrationIds = registrationIds;
}
}
|
/**
* PayloadTypeResolver
*/
package com.bs.bod.converter;
import java.util.Collection;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.fasterxml.jackson.databind.jsontype.TypeDeserializer;
import com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder;
/**
* @author dbs on Dec 30, 2015 5:18:57 PM
*
* @version 1.0
* @since 0.0.3
*
*/
public class PayloadTypeResolver extends StdTypeResolverBuilder {
@Override
public TypeDeserializer buildTypeDeserializer(final DeserializationConfig config, final JavaType baseType, final Collection<NamedType> subtypes) {
return new CustomPayloadTypeDeserializer(baseType, null, _typeProperty, _typeIdVisible, _defaultImpl);
}
}
|
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n;
n=sc.nextInt();
int a[]=new int[n];
System.out.print("Elements in array: ");
for(int j=0;j<n;j++)
{
a[j]=sc.nextInt();
}
int max=0,min=a[0];
for(int i=0;i<=n-1;i++)
{
if(max<a[i])
{
max=a[i];
}
if(min>a[1])
{
min=a[i];
}
}
System.out.print("min = "+min);
System.out.println(" max = "+max);
}
}
|
package com.vipvideo.ui.adpter;
import android.view.View;
import android.widget.TextView;
import com.lixh.base.adapter.VBaseHolder;
import com.vipvideo.R;
import com.vipvideo.bean.TitleBean;
import butterknife.Bind;
/**
* Created by Moushao on 2017/8/30.
*/
public class TitleHolder extends VBaseHolder<TitleBean> {
@Bind(R.id.tv_title)
TextView title;
public TitleHolder(View itemView) {
super(itemView);
}
@Override
public void setData(int ps, TitleBean data) {
super.setData(ps, data);
title.setText(data.getTitle());
}
}
|
package meli.tmr.solarsystem.exceptions;
public class NoWeatherFoundException extends RuntimeException {
public NoWeatherFoundException(String msg){
super(msg);
}
}
|
package com.sshfortress.dao.system.mapper;
import java.util.List;
import java.util.Map;
import com.sshfortress.common.beans.SysConfig;
import com.sshfortress.common.beans.SysConfigKeyValue;
public interface SysConfigMapper {
int deleteByPrimaryKey(Long id);
int insert(SysConfig record);
int insertSelective(SysConfig record);
SysConfig selectByPrimaryKey(Long id);
/** 更新配置的值 */
int updateCvalueByCkey(SysConfig config);
/** 查询配置的值 */
String getCvalueByCkey(String ckey);
int updateByPrimaryKey(SysConfig record);
String selectGroupCodeByCkey(Map<String,Object> params);
List<SysConfigKeyValue> selectKeyValueByGroupCode(Map<String,Object> params);
/** 获取配置的全部数据 */
List<Map<String,Object>> selectByAll();
} |
package com.joandora.demo.rpc_3;
import java.util.UUID;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.AMQP.Queue.DeclareOk;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
public class Client {
public static void main(String[] args) throws Exception {
ConnectionFactory cf = new ConnectionFactory();
cf.setHost("192.168.144.128");
Connection conn = cf.newConnection();
Channel channel = conn.createChannel();
// 申明一个队列,不带参数的话,这个队列在连接关闭时,启动删除
DeclareOk ok = channel.queueDeclare();
// rabbitmq会自动给新生成的队列取名
String returnQueueName = ok.getQueue();
QueueingConsumer consumer = new QueueingConsumer(channel);
// 指定消费队列 ,服务端在接受到消息后,会往这个队列里面放入返回消息
channel.basicConsume(returnQueueName, true, consumer);
String correlationId = UUID.randomUUID().toString();
//封装一个correlationId相当于是一个标志,其实没什么用。服务端接收后,又传回给客户端。客户端可以对这个值进行比较。
BasicProperties proeprties = new BasicProperties.Builder().correlationId(correlationId).replyTo(returnQueueName).build();
channel.basicPublish("", "rpc_queue_joan", proeprties, "hello".getBytes());
while(true) {
Delivery delivery = consumer.nextDelivery();
if(delivery.getProperties().getCorrelationId().equals(correlationId)) {
System.out.println("client get response : " +new String(delivery.getBody()));
break;
}
}
conn.close();
}
}
|
package tool;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
* 读取/写入properties文件的工具类
*/
public class PropertyOper {
private static Logger logger = Logger.getLogger(PropertyOper.class);
/**
* 根据Key在制定的properties文件中读取Value
* @param filePath properties文件路径
* @param key 要获取value的key
* @return key对应的value
*/
public static String GetValueByKey(String filePath, String key) {
Properties pps = new Properties();
String value = null;
try {
//InputStream in = new BufferedInputStream(new FileInputStream(filePath));
InputStream in = PropertyOper.class.getClassLoader().getResourceAsStream(filePath );
pps.load(in);
value = pps.getProperty(key);
//System.out.println(key + " = " + value);
} catch (IOException e) {
logger.warn("Cannot open property file <"+filePath+">", e);
return null;
} catch (Exception e) {
// TODO: handle exception
logger.warn("Finding property value of key <"+key+">in file <"+filePath+"> failed.", e);
return null;
}
return value;
}
/**
* 读取Properties的全部信息
* @param filePath properties文件路径
* @return 存储所有key-value对的map
* @throws IOException 文件IO操作失败会抛出异常
*/
public static Map<String, String> GetAllProperties(String filePath) throws IOException {
Properties pps = new Properties();
InputStream in = PropertyOper.class.getClassLoader().getResourceAsStream(filePath );
pps.load(in);
Enumeration<?> en = pps.propertyNames(); // 得到配置文件的名字
Map<String, String> result = new HashMap<>();
while (en.hasMoreElements()) {
String strKey = (String) en.nextElement();
String strValue = pps.getProperty(strKey);
result.put(strKey, strValue);
//System.out.println(strKey + "=" + strValue);
}
return result;
}
/**
* 写入Properties信息
* @param filePath properties文件路径
* @param pKey 要写入的key
* @param pValue key对应的value
* @throws IOException 写入IO错误时抛出异常
*/
public static void WriteProperties(String filePath, String pKey, String pValue) throws IOException {
Properties pps = new Properties();
InputStream in = new FileInputStream(filePath);
// 从输入流中读取属性列表(键和元素对)
pps.load(in);
// 调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。
// 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
OutputStream out = new FileOutputStream(filePath);
pps.setProperty(pKey, pValue);
// 以适合使用 load 方法加载到 Properties 表中的格式,
// 将此 Properties 表中的属性列表(键和元素对)写入输出流
pps.store(out, "Update " + pKey + " name");
}
/**
* 通过HashMap批量写入Properties信息
* @param filePath properties文件路径
* @param map 存储要写入文件的key-value对的Map
* @throws IOException 当写入IO出现错误时抛出异常
*/
public static void WriteProperties(String filePath, Map<String, String> map) throws IOException {
Properties pps = new Properties();
InputStream in = new FileInputStream(filePath);
// 从输入流中读取属性列表(键和元素对)
pps.load(in);
// pps.load(PropertyOper.class.getClassLoader().getResourceAsStream(filename));
// 调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。
// 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
OutputStream out = new FileOutputStream(filePath);
for (Entry<String, String> entry : map.entrySet()) {
pps.setProperty(entry.getKey(), entry.getValue());
}
// 以适合使用 load 方法加载到 Properties 表中的格式,
// 将此 Properties 表中的属性列表(键和元素对)写入输出流
pps.store(out, "Update " + "" + " name");
GetAllProperties(filePath);
}
} |
package cc.ipotato.generic;
/**
* Created by Hello on 2017/11/13.
*/
class Message<T>{
private T note;
public void setNote(T note) {
this.note = note;
}
public T getNote() {
return note;
}
}
public class MessageTest {
public static void main(String[] args) {
Message<Integer> stringMessage = new Message<>();
stringMessage.setNote(99);
fun(stringMessage);
}
//泛型中的通配符使用
public static void fun(Message<?> temp){
// temp.setNote("hhhhh"); // 出错
System.out.println(temp.getNote());
}
}
|
package br.com.juliafealves.agenda.ui.activities;
public interface ConstantsActivities {
String KEY_STUDENT = "student";
}
|
package com.test.heap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* .堆化,从下至上,以新增为例
* @author YLine
*
* 2019年3月19日 下午7:45:03
*/
public class SolutionHeapifyUp
{
/**
* .创建一个,测试数据
* @return 数组,为了方便拓展,使用List
*/
public List<Integer> buildTestSource()
{
List<Integer> dataList = new ArrayList<>();
dataList.add(null); // 首个空
dataList.addAll(Arrays.asList(33));
dataList.addAll(Arrays.asList(17, 21));
dataList.addAll(Arrays.asList(16, 13, 15, 9));
dataList.addAll(Arrays.asList(5, 6, 7, 8, 1, 2));
return dataList;
}
public void insert(List<Integer> dataList, int newValue)
{
// 插入最后一个
dataList.add(newValue);
// 从下至上,堆化
SolutionHeap.heapifyUp(dataList, dataList.size() - 1);
}
}
|
/**
* Copyright (C) 2008 Atlassian
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.atlassian.theplugin.idea.config.serverconfig;
import com.atlassian.theplugin.commons.ServerType;
import com.atlassian.theplugin.commons.cfg.ServerCfg;
import com.atlassian.theplugin.commons.cfg.ServerIdImpl;
import com.atlassian.theplugin.commons.cfg.UserCfg;
import com.atlassian.theplugin.commons.exception.ServerPasswordNotProvidedException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class GenericServerConfigurationFormTest extends TestCase {
private GenericServerConfigForm genericServerConfigurationForm;
@Override
protected void setUp() throws Exception {
super.setUp();
genericServerConfigurationForm = new GenericServerConfigForm(null, null, null);
}
public void testGenericSetGetData() throws Exception {
assertNotNull(genericServerConfigurationForm.getRootComponent());
ServerCfg inServerBean = createServerBean();
genericServerConfigurationForm.setData(inServerBean);
genericServerConfigurationForm.finalizeData();
genericServerConfigurationForm.saveData();
ServerCfg outServerBean = genericServerConfigurationForm.getServerCfg();
// form use cloned instance
assertSame(inServerBean, outServerBean);
checkServerBean(outServerBean);
}
private static ServerCfg createServerBean() {
ServerCfg tmp = new ServerCfg(true, "name", new ServerIdImpl()) {
@Override
public ServerType getServerType() {
return null;
}
public boolean isDontUseBasicAuth() {
return false;
}
public UserCfg getBasicHttpUser() {
return null;
}
public boolean isUseSessionCookies() {
return false;
}
@Override
public ServerCfg getClone() {
throw new UnsupportedOperationException("not yet implemented");
}
};
tmp.setPassword("password");
tmp.setPasswordStored(true);
tmp.setUrl("url");
tmp.setUsername("userName");
return tmp;
}
private static void checkServerBean(ServerCfg outServer) throws ServerPasswordNotProvidedException {
assertEquals("name", outServer.getName());
assertEquals("password", outServer.getPassword());
assertEquals("http://url", outServer.getUrl());
assertEquals("userName", outServer.getUsername());
}
public static Test suite() {
return new TestSuite(GenericServerConfigurationFormTest.class);
}
}
|
package org.valdi.entities.packets;
import java.lang.reflect.InvocationTargetException;
import org.bukkit.entity.Player;
import org.valdi.entities.iDisguise;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
public abstract class ProtocolLibPacketListener extends PacketAdapter {
private final iDisguise addon;
private final ProtocolManager protocolManager;
protected ProtocolLibPacketListener(iDisguise addon, ListenerPriority listenerPriority, PacketType... arrpacketType) {
super(addon, listenerPriority, arrpacketType);
this.addon = addon;
this.protocolManager = ProtocolLibrary.getProtocolManager();
}
protected iDisguise getAddon() {
return this.addon;
}
protected ProtocolManager getProtocolManager() {
return this.protocolManager;
}
protected void sendPacket(Player observer, PacketContainer packet) throws InvocationTargetException {
this.protocolManager.sendServerPacket(observer, packet);
}
}
|
package com.example.gopalawasthi.movielovers;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
import static com.example.gopalawasthi.movielovers.MoviesAdapter.IMAGE;
/**
* Created by Gopal Awasthi on 22-03-2018.
*/
public class popularmovieadapter extends RecyclerView.Adapter<popularmovieadapter.MovieHolder>{
Context context;
List<Nowplaying.ResultsBean> beans;
public static final String IMAGE ="http://image.tmdb.org/t/p/w780";
interface OnitemClicklistener{
void OnitemClick(int position);
void OnlongitemClick(int position);
}
OnitemClicklistener clicklistener;
public popularmovieadapter(Context context, List<Nowplaying.ResultsBean> beans,OnitemClicklistener clicklistener) {
this.context = context;
this.beans = beans;
this.clicklistener = clicklistener;
}
@NonNull
@Override
public MovieHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.custom_nowplayingview,parent,false);
popularmovieadapter.MovieHolder holder = new popularmovieadapter.MovieHolder(v);
return holder;
}
@Override
public void onBindViewHolder(@NonNull final MovieHolder holder, int position) {
Nowplaying.ResultsBean bean = beans.get(position);
holder.name.setText(bean.getTitle());
String a= Float.toString((float) bean.getVote_average());
holder.rating.setText(a);
String b =bean.getPoster_path();
holder.imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clicklistener.OnitemClick(holder.getAdapterPosition());
}
});
holder.imageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
clicklistener.OnlongitemClick(holder.getAdapterPosition());
return true;
}
});
Picasso.get().load(IMAGE+bean.getBackdrop_path()).fit().into(holder.imageView);
}
@Override
public int getItemCount() {
return beans.size();
}
class MovieHolder extends RecyclerView.ViewHolder{
TextView name ;
ImageView imageView;
TextView rating;
View itemView;
public MovieHolder(View itemView) {
super(itemView);
this.itemView = itemView;
name = itemView.findViewById(R.id.nowshowingtitle);
imageView = itemView.findViewById(R.id.imagenowplaying);
rating = itemView.findViewById(R.id.userrating);
}
}
}
|
package dwz.framework.timer.impl;
import java.util.Collection;
import java.util.Date;
import dwz.framework.timer.TaskEngine;
import dwz.framework.timer.TaskFactory;
import dwz.framework.timer.TaskParse;
import dwz.framework.timer.TaskUnit;
/**
* @Author: LCF
* @Date: 2020/1/8 17:08
* @Package: dwz.framework.timer.impl
*/
public class DefaultTaskFactory extends TaskFactory {
private TaskParse parser = null;
@Override
public Runnable getTask(String name) {
if (parser == null)
return null;
TaskUnit taskUnit = this.parser.getTaskUnit(name);
if (taskUnit != null) {
return taskUnit.getTask();
}
return null;
}
@Override
public void initTasks(String filePath) {
if (filePath == null) {
return;
}
this.parser = new TaskParseImpl(filePath);
}
@Override
public void startAllTasks() {
if (this.parser == null)
return;
startTasks(this.parser.getTaskUnits());
}
@Override
public void startTasks(Collection<TaskUnit> units) {
if (units == null || units.isEmpty())
return;
for (TaskUnit taskUnit : units) {
if (taskUnit.isRunnable()) {
Runnable task = taskUnit.getTask();
Date startTime = taskUnit.getStartTime();
int priority = taskUnit.getPriority();
long period = taskUnit.getPeriod();
if (period == 0) {
TaskEngine.scheduleTask(task, startTime, priority);
} else {
TaskEngine.scheduleTask(task, startTime, period, priority);
}
}
}
}
@Override
public TaskParse getTaskParse() {
return this.parser;
}
}
|
package orm.integ.dao.sql;
public interface PageRequest {
public int getStart();
public int getLimit();
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lab04;
/**
*
* @author yancy
*/
public class DateAdvisor {
public int rateMatch(Person me, Person match){
int match_rate = 0;
return match_rate;
}
// public MyArrayList getMatches(Person me, MyArrayList<Person>){
//
// }
}
|
package com.GestiondesClub.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.GestiondesClub.dao.RoleEtudiantDao;
import com.GestiondesClub.entities.RoleEtudiant;
@Service
public class RoleEtudiantServ {
@Autowired
private RoleEtudiantDao roleEtudiantDao;
public List<RoleEtudiant> findRoles() {
return roleEtudiantDao.findAll();
}
}
|
import org.junit.Test;
import static org.junit.Assert.*;
public class TestOffByN {
CharacterComparator offBy5 = new OffByN(5);
@Test
public void equalChars() {
assertTrue(offBy5.equalChars('a', 'f'));
assertFalse(offBy5.equalChars('a', 'b'));
}
}
|
package negocio.vo;
public class Empleado {
private Integer id;
private String nombre;
private Integer sueldo;
private Integer codTienda;
private Especialidad especialidad;
public Empleado() {
super();
}
public Empleado(Integer id, String nombre, Integer sueldo, Integer codTienda, Especialidad especialidad) {
this.id = id;
this.nombre = nombre;
this.sueldo = sueldo;
this.codTienda = codTienda;
this.especialidad = especialidad;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Integer getSueldo() {
return sueldo;
}
public void setSueldo(Integer sueldo) {
this.sueldo = sueldo;
}
public Integer getCodTienda() {
return codTienda;
}
public void setCodTienda(Integer codTienda) {
this.codTienda = codTienda;
}
public Especialidad getEspecialidad() {
return especialidad;
}
public void setEspecialidad(Especialidad especialidad) {
this.especialidad = especialidad;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codTienda == null) ? 0 : codTienda.hashCode());
result = prime * result + ((especialidad == null) ? 0 : especialidad.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((nombre == null) ? 0 : nombre.hashCode());
result = prime * result + ((sueldo == null) ? 0 : sueldo.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Empleado other = (Empleado) obj;
if (codTienda == null) {
if (other.codTienda != null)
return false;
} else if (!codTienda.equals(other.codTienda))
return false;
if (especialidad != other.especialidad)
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (nombre == null) {
if (other.nombre != null)
return false;
} else if (!nombre.equals(other.nombre))
return false;
if (sueldo == null) {
if (other.sueldo != null)
return false;
} else if (!sueldo.equals(other.sueldo))
return false;
return true;
}
}
|
package com.dokyme.alg4.sorting.priorityqueue;
import com.dokyme.alg4.sorting.basic.Transaction;
import edu.princeton.cs.algs4.Stack;
import edu.princeton.cs.algs4.StdOut;
import java.io.*;
import java.util.Scanner;
/**
* Created by intellij IDEA.But customed by hand of Dokyme.
*
* @author dokym
* @date 2018/5/8-22:04
* Description:
*/
public class TopM {
public static void main(String[] args) {
try {
int M = 5;
Scanner scanner = new Scanner(new File("tinyBatch.txt"));
MinHeap<Transaction> minHeap = new MinHeap<>(20);
while (scanner.hasNextLine()) {
minHeap.insert(new Transaction(scanner.nextLine()));
if (minHeap.size() > M) {
minHeap.delMin();
}
}
Stack<Transaction> stack = new Stack<>();
while (!minHeap.isEmpty()) {
stack.push(minHeap.delMin());
}
for (Transaction t : stack) {
StdOut.println(t);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Identity;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.TableImpl;
import schema.BitnamiEdx;
import schema.Keys;
import schema.tables.records.CreditHistoricalcreditrequestRecord;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class CreditHistoricalcreditrequest extends TableImpl<CreditHistoricalcreditrequestRecord> {
private static final long serialVersionUID = -1150718467;
/**
* The reference instance of <code>bitnami_edx.credit_historicalcreditrequest</code>
*/
public static final CreditHistoricalcreditrequest CREDIT_HISTORICALCREDITREQUEST = new CreditHistoricalcreditrequest();
/**
* The class holding records for this type
*/
@Override
public Class<CreditHistoricalcreditrequestRecord> getRecordType() {
return CreditHistoricalcreditrequestRecord.class;
}
/**
* The column <code>bitnami_edx.credit_historicalcreditrequest.id</code>.
*/
public final TableField<CreditHistoricalcreditrequestRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>bitnami_edx.credit_historicalcreditrequest.created</code>.
*/
public final TableField<CreditHistoricalcreditrequestRecord, Timestamp> CREATED = createField("created", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "");
/**
* The column <code>bitnami_edx.credit_historicalcreditrequest.modified</code>.
*/
public final TableField<CreditHistoricalcreditrequestRecord, Timestamp> MODIFIED = createField("modified", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "");
/**
* The column <code>bitnami_edx.credit_historicalcreditrequest.uuid</code>.
*/
public final TableField<CreditHistoricalcreditrequestRecord, String> UUID = createField("uuid", org.jooq.impl.SQLDataType.VARCHAR.length(32).nullable(false), this, "");
/**
* The column <code>bitnami_edx.credit_historicalcreditrequest.username</code>.
*/
public final TableField<CreditHistoricalcreditrequestRecord, String> USERNAME = createField("username", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, "");
/**
* The column <code>bitnami_edx.credit_historicalcreditrequest.parameters</code>.
*/
public final TableField<CreditHistoricalcreditrequestRecord, String> PARAMETERS = createField("parameters", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, "");
/**
* The column <code>bitnami_edx.credit_historicalcreditrequest.status</code>.
*/
public final TableField<CreditHistoricalcreditrequestRecord, String> STATUS = createField("status", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, "");
/**
* The column <code>bitnami_edx.credit_historicalcreditrequest.history_id</code>.
*/
public final TableField<CreditHistoricalcreditrequestRecord, Integer> HISTORY_ID = createField("history_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>bitnami_edx.credit_historicalcreditrequest.history_date</code>.
*/
public final TableField<CreditHistoricalcreditrequestRecord, Timestamp> HISTORY_DATE = createField("history_date", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "");
/**
* The column <code>bitnami_edx.credit_historicalcreditrequest.history_type</code>.
*/
public final TableField<CreditHistoricalcreditrequestRecord, String> HISTORY_TYPE = createField("history_type", org.jooq.impl.SQLDataType.VARCHAR.length(1).nullable(false), this, "");
/**
* The column <code>bitnami_edx.credit_historicalcreditrequest.course_id</code>.
*/
public final TableField<CreditHistoricalcreditrequestRecord, Integer> COURSE_ID = createField("course_id", org.jooq.impl.SQLDataType.INTEGER, this, "");
/**
* The column <code>bitnami_edx.credit_historicalcreditrequest.history_user_id</code>.
*/
public final TableField<CreditHistoricalcreditrequestRecord, Integer> HISTORY_USER_ID = createField("history_user_id", org.jooq.impl.SQLDataType.INTEGER, this, "");
/**
* The column <code>bitnami_edx.credit_historicalcreditrequest.provider_id</code>.
*/
public final TableField<CreditHistoricalcreditrequestRecord, Integer> PROVIDER_ID = createField("provider_id", org.jooq.impl.SQLDataType.INTEGER, this, "");
/**
* Create a <code>bitnami_edx.credit_historicalcreditrequest</code> table reference
*/
public CreditHistoricalcreditrequest() {
this("credit_historicalcreditrequest", null);
}
/**
* Create an aliased <code>bitnami_edx.credit_historicalcreditrequest</code> table reference
*/
public CreditHistoricalcreditrequest(String alias) {
this(alias, CREDIT_HISTORICALCREDITREQUEST);
}
private CreditHistoricalcreditrequest(String alias, Table<CreditHistoricalcreditrequestRecord> aliased) {
this(alias, aliased, null);
}
private CreditHistoricalcreditrequest(String alias, Table<CreditHistoricalcreditrequestRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public Schema getSchema() {
return BitnamiEdx.BITNAMI_EDX;
}
/**
* {@inheritDoc}
*/
@Override
public Identity<CreditHistoricalcreditrequestRecord, Integer> getIdentity() {
return Keys.IDENTITY_CREDIT_HISTORICALCREDITREQUEST;
}
/**
* {@inheritDoc}
*/
@Override
public UniqueKey<CreditHistoricalcreditrequestRecord> getPrimaryKey() {
return Keys.KEY_CREDIT_HISTORICALCREDITREQUEST_PRIMARY;
}
/**
* {@inheritDoc}
*/
@Override
public List<UniqueKey<CreditHistoricalcreditrequestRecord>> getKeys() {
return Arrays.<UniqueKey<CreditHistoricalcreditrequestRecord>>asList(Keys.KEY_CREDIT_HISTORICALCREDITREQUEST_PRIMARY);
}
/**
* {@inheritDoc}
*/
@Override
public List<ForeignKey<CreditHistoricalcreditrequestRecord, ?>> getReferences() {
return Arrays.<ForeignKey<CreditHistoricalcreditrequestRecord, ?>>asList(Keys.CREDIT_HISTORIC_HISTORY_USER_ID_52A9922F26A69E7E_FK_AUTH_USER_ID);
}
/**
* {@inheritDoc}
*/
@Override
public CreditHistoricalcreditrequest as(String alias) {
return new CreditHistoricalcreditrequest(alias, this);
}
/**
* Rename this table
*/
public CreditHistoricalcreditrequest rename(String name) {
return new CreditHistoricalcreditrequest(name, null);
}
}
|
package com.nsbhasin.nowyouseeme.ui;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import com.nsbhasin.nowyouseeme.data.Location;
import com.nsbhasin.nowyouseeme.data.LocationRepository;
import java.util.List;
public class LocationViewModel extends AndroidViewModel {
private LocationRepository mRepository;
private LiveData<List<Location>> mLocations;
public LocationViewModel(@NonNull Application application) {
super(application);
mRepository = new LocationRepository(application);
mLocations = mRepository.getLocations();
}
public LiveData<List<Location>> getLocations() {
return mLocations;
}
public void insert(Location location) {
mRepository.insert(location);
}
}
|
public class Main {
public static void main(String[] args) {
int costInKopecks = 20_00;
int percent = 5;
float amount = costInKopecks * percent / 100 / 100;
System.out.println(amount);
}
} |
import java.util.*;
class shaurya
{
static boolean present(int num,int[] arr)
{
int count=arr.length;
for(var i=0;i<count;i++)
{
if(arr[i]==num)
{
return true;
}
}
return false;
}
public static int missing(int[] arr)
{
int smallest=arr[0],largest=0;
for(int x=0;x<arr.length;x++)
{
if(arr[x]<smallest)
smallest=arr[x];
if(arr[x]>largest)
largest=arr[x];
}
// System.out.println(smallest+" "+largest);
for(int x=smallest;x<largest;x++)
{
if(!(present(x, arr)))
{
return x;
}
// else
// {
// }
}
return -1;
}
public static int repeating(int[] arr)
{
for(int x=0;x<arr.length;x++)
{
for(int y=x+1;y<arr.length;y++)
{
if(arr[x]==arr[y])
return arr[x];
}
}
return -1;
}
public static void main(String args[])
{
Scanner sc=new Scanner (System.in);
int x;
System.out.println("enter the length of array");
int n=sc.nextInt();
System.out.println("enter the elements");
int[] arr=new int[n];
for(x=0;x<n;x++)
{
arr[x]=sc.nextInt();
}
if(missing(arr)>=0)
System.out.println(missing(arr)+" is the missing element");
else
System.out.println("no missing element");
if(repeating(arr)>=0)
System.out.println(repeating(arr)+" is the repeating element");
else
System.out.println("no repeating element");
}
}
|
package mongodb.configuration;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
/**
* This is the base configuration for the Mongo Plugin.
*/
public abstract class MongoBaseConfiguration implements DisposableBean {
public abstract MongoDbFactory mongoDbFactory();
public abstract MongoTemplate mongoTemplate();
}
|
package edu.frostburg.cosc460;
import java.util.Random;
/**
*
* @author Matt
*
* Page Generator makes semi-random strings of integers from 0 to 9 that
* are eventually returned in an array to be used in our testing class.
*/
public class PageGenerator {
private int[] pageReference; //the array that will be filled with random numbers
Random random; //Random object to make the random numbers with
/**
* Initiatizes the array pageReference with size sizeOfReferenceString and
* initializes the Random object.
*
* @param sizeOfReferenceString Size of the array of random numbers to be returned
* in the method getReferenceString()
*/
public PageGenerator(int sizeOfReferenceString)
{
pageReference = new int[sizeOfReferenceString];
random = new Random();
}
/**
* Builds a string of semi-random numbers from 0 - 9 that tend to repeat themselves.
* The returned array is to emulate same page requests in order to analyze page
* replacement algorithms.
*
* @return An int[] of semi-random integers from 0 - 9
*/
public int[] getReferenceString()
{
//return a semi-random string of numbers 0 through 9.
int tempRandom;
int n;
for(int i = 0; i < pageReference.length; i++)
{
//Half the time, we reuse pages that have been used already
if((tempRandom = random.nextInt(20)) < 10)
{
pageReference[i] = tempRandom;
}
else
{
//get a page number that we've used before
n = random.nextInt(i + 1);// add 1 since nextInt() only accepts numbers > 0
pageReference[i] = pageReference[n];
}
}
return pageReference;
//return new int[]{7,0,1,2,0,3,0,4,2,3,0,3,0,3,2,1,2,0,1,7,0,1};
//return new int[]{0,1,1,3,3,0,5,1};
//return new int[]{0, 0, 0, 0, 5, 3, 2, 0};
}
}
|
package com.flushoutsolutions.foheart.data;
/**
* Created by Manuel on 10/08/2014.
*/
public class SendDataData {
public int _id;
public int fk_application;
public int fk_user;
public String table_name;
public int row_id;
public String record;
public int sent;
public String datetime;
public SendDataData(int _id, int fk_application, int fk_user, String table_name, int row_id, String record, int sent, String datetime)
{
this._id = _id;
this.fk_application = fk_application;
this.fk_user = fk_user;
this.table_name = table_name;
this.row_id = row_id;
this.record = record;
this.sent = sent;
this.datetime = datetime;
}
public SendDataData(int fk_application, int fk_user, String table_name, int row_id, String record, int sent, String datetime)
{
this.fk_application = fk_application;
this.fk_user = fk_user;
this.table_name = table_name;
this.row_id = row_id;
this.record = record;
this.sent = sent;
this.datetime = datetime;
}
}
|
//wap a java application accept number in regurlar matrix form siz is 2X3 and print same?
import java.util.*;
class matrix
{
public static void main(String args[])
{
Scanner x=new Scanner(System.in);
int num[][]=new int[2][3];
int r,c;
for(r=0;r<2;r++){
System.out.println("Inset Row Value"+r);
for(c=0;c<num[r].length;c++){
System.out.println("Enter number:-");
num[r][c]=x.nextInt();
}
}
System.out.println("Displaying array index/elements");
for(r=0;r<2;r++){
System.out.print("\n");
for(c=0;c<num[r].length;c++)
System.out.print(num[r][c]+" ");
}
}//close of main
}//close of class |
package View;
import Model.MyModel;
import Server.*;
import ViewModel.MyViewModel;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
MyModel model = new MyModel();
MyViewModel myViewModel = new MyViewModel(model);
model.addObserver(myViewModel);
//TODO check if can be changed to IMODEL
primaryStage.setTitle("The Incredible Maze!");
FXMLLoader fxmlLoader = new FXMLLoader();
Parent root = fxmlLoader.load(getClass().getResource("MyView.fxml").openStream());
Scene scene = new Scene(root,800,700);
scene.getStylesheets().add(getClass().getResource("ViewStyle.css").toExternalForm());
MyViewController myViewController = fxmlLoader.getController();
myViewController.setResizeEvent(scene);
myViewController.setViewModel(myViewModel);
myViewModel.addObserver(myViewController);
scene.addEventFilter(KeyEvent.KEY_PRESSED, event -> myViewController.KeyPressed(event));
primaryStage.setScene(scene);
SetStageCloseEvent(primaryStage, myViewController);
primaryStage.show();
//myViewModel.generateMaze(10,10);
//Rise Servers
}
private void SetStageCloseEvent(Stage primaryStage, MyViewController myViewController) {
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent windowEvent) {
myViewController.exitCorrectly();
windowEvent.consume();
}
});
}
public static void main(String[] args) {
launch(args);
}
}
|
package diplomski.autoceste.services;
import diplomski.autoceste.forms.DiscountDto;
import diplomski.autoceste.models.Discount;
import diplomski.autoceste.models.PrivateUser;
import diplomski.autoceste.models.Vehicle;
import diplomski.autoceste.models.VehicleDiscountLabel;
import diplomski.autoceste.repositories.DiscountRepository;
import diplomski.autoceste.repositories.VehicleDiscountLabelRepository;
import diplomski.autoceste.util.NumberComparator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class DiscountServiceImpl implements DiscountService {
private final VehicleDiscountLabelRepository vehicleDiscountLabelRepository;
private final DiscountRepository discountRepository;
private List<Discount> activeDiscounts;
private NumberComparator comparator;
@Autowired
public DiscountServiceImpl(VehicleDiscountLabelRepository vehicleDiscountLabelRepository, DiscountRepository discountRepository, NumberComparator comparator) {
this.vehicleDiscountLabelRepository = vehicleDiscountLabelRepository;
this.discountRepository = discountRepository;
this.activeDiscounts = discountRepository.findAll();
this.comparator = comparator;
}
@Override
public boolean addVehicleDiscountLabel(VehicleDiscountLabel label) {
try {
vehicleDiscountLabelRepository.save(label);
} catch (DataIntegrityViolationException e) {
return false;
}
return true;
}
public Set<Discount> findAllDiscountForPrivateUser(PrivateUser user) {
return new HashSet<>();
}
public HashSet<Discount> findAllDiscountForVehicle(Vehicle vehicle) {
List<Discount> applyDiscounts = new ArrayList<>();
for (Discount d : activeDiscounts) {
List<VehicleDiscountLabel> labels = findAllLabelsByNames(d.getLabels());
for (VehicleDiscountLabel l : labels) {
if (l.getCategory().equals(vehicle.getCategory())) {
switch (l.getOperation()) {
case NONE:
if ((boolean) vehicle.get(l.getName())) {
applyDiscounts.add(d);
}
case EQUALS:
Number param = (Number) vehicle.get(l.getName());
if (param.equals(l.getValue())) {
applyDiscounts.add(d);
}
break;
case MORE:
param = (Number) vehicle.get(l.getName());
if (comparator.compare(param, l.getValue()) > 0) {
applyDiscounts.add(d);
}
break;
case LESS:
param = (Number) vehicle.get(l.getName());
if (comparator.compare(param, l.getValue()) < 0) {
applyDiscounts.add(d);
}
break;
case PRESENT:
break;
}
}
}
}
return new HashSet(applyDiscounts);
}
@Override
public List<VehicleDiscountLabel> getAllVehicleDiscountLabel() {
return vehicleDiscountLabelRepository.findAll();
}
@Override
public boolean addDiscount(DiscountDto dto) {
Discount d = dto.toDiscount();
d.setLabels(dto.getLabels());
try {
discountRepository.save(d);
} catch (DataIntegrityViolationException e) {
e.printStackTrace();
return false;
}
return true;
}
private List<VehicleDiscountLabel> findAllLabelsByNames(List<String> labelNames) {
List<VehicleDiscountLabel> labels = new ArrayList<>();
for (String l : labelNames) {
labels.addAll(vehicleDiscountLabelRepository.findAllByName(l));
}
return labels;
}
public List<DiscountDto> getDiscounts() {
List<Discount> d = discountRepository.findAll();
return d.stream().map(DiscountDto::new).collect(Collectors.toList());
}
@Scheduled(cron = "0 0 0 * * *")
public void checkForNewDiscounts() {
this.activeDiscounts.addAll(discountRepository.findByStartDateLessThanAndEndDateGreaterThan(LocalDate.now(), LocalDate.now()));
}
}
|
package com.junzhao.base.utils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.RequestBody;
/**
* Created by gk on 2016/1/29.
*/
public class ImageUtil {
/**
* 根据计算的inSampleSize,得到压缩后图片
*
* @param pathName
* @param reqWidth
* @param reqHeight
* @return
*/
private static ImageUtil mInstance;
public static ImageUtil getInstance() {
if (mInstance == null) {
synchronized (ImageUtil.class) {
if (mInstance == null) {
mInstance = new ImageUtil();
}
}
}
return mInstance;
}
/**
* 根据计算的inSampleSize,得到压缩后图片
*
* @param
* @param reqWidth
* @param reqHeight
* @return
*/
/* public Bitmap decodeSampledBitmapFromResource(String pathName,
int reqWidth, int reqHeight) {
// 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, options);
// 调用上面定义的方法计算inSampleSize值
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// 使用获取到的inSampleSize值再次解析图片
options.inJustDecodeBounds = false;
Logger.i("options.inSampleSize = " + options.inSampleSize);
Bitmap bitmap = BitmapFactory.decodeFile(pathName, options);
return cQuality(bitmap);
}
*/
public void decodeBitmapFromBitmap(Bitmap bitmapSrc, int reqWidth, int reqHeight, FileOutputStream fileOutputStream) {
if (reqHeight == 0) {
reqHeight = bitmapSrc.getHeight();
}
int inSampleSize = calculateRadio(bitmapSrc.getWidth(), bitmapSrc.getHeight(), reqWidth, reqHeight);
bitmapSrc = bitmapSrc.createScaledBitmap(bitmapSrc, bitmapSrc.getWidth() / inSampleSize, bitmapSrc.getHeight() / inSampleSize, false);
cQuality(bitmapSrc, fileOutputStream);
// return bitmapSrc;
}
/**
* 计算inSampleSize,用于压缩图片
*
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
private int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// 源图片的宽度
int width = options.outWidth;
int height = options.outHeight;
int inSampleSize = 1;
/* if (width > reqWidth && height > reqHeight) {
// 计算出实际宽度和目标宽度的比率
int widthRatio = Math.round((float) width / (float) reqWidth);
int heightRatio = Math.round((float) height / (float) reqHeight);
inSampleSize = Math.max(widthRatio, heightRatio);
}*/
inSampleSize = calculateRadio(width, height, reqWidth, reqHeight);
return inSampleSize;
}
private int calculateRadio(int width, int height, int reqWidth, int reqHeight) {
int inSampleSize = 1;
if (width >= height && width > reqWidth) {//如果宽度大的话根据宽度固定大小缩放
inSampleSize = (int) (width / reqWidth);
} else if (width < height && height > reqHeight) {//如果高度高的话根据宽度固定大小缩放
inSampleSize = (int) (height / reqHeight);
}
return inSampleSize;
}
/*
public boolean saveBitmap2file(Bitmap bmp, String filename) {
int quality = 100;
OutputStream stream = null;
Bitmap.CompressFormat format = Bitmap.CompressFormat.PNG;
try {
stream = new FileOutputStream(UIUtils.getExternalCacheDir() + File.separator + filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (!(filename.endsWith(".png") || filename.endsWith(".PNG"))) {
format = Bitmap.CompressFormat.JPEG;
bmp = cQuality(bmp);
}
return bmp.compress(format, quality, stream);
}*/
/**
* 根据bitmap压缩图片质量
*
* @param bitmap 未压缩的bitmap
* @return 压缩后的bitmap
*/
public void cQuality(Bitmap bitmap, FileOutputStream fileOutputStream) {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
int beginRate = 100;
//第一个参数 :图片格式 ,第二个参数: 图片质量,100为最高,0为最差 ,第三个参数:保存压缩后的数据的流
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bOut);
while (bOut.size() / 1024 > 90) { //如果压缩后大于100Kb,则提高压缩率,重新压缩 如果是png会进入死循环吗
beginRate -= 10;
bOut.reset();
bitmap.compress(Bitmap.CompressFormat.JPEG, beginRate, bOut);
}
try {
fileOutputStream.write(bOut.toByteArray());
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/* Logger.i("==================" + beginRate);
ByteArrayInputStream bInt = new ByteArrayInputStream(bOut.toByteArray());
Bitmap newBitmap = BitmapFactory.decodeStream(bInt);
if (newBitmap != null) {
return newBitmap;
} else {
return bitmap;
}*/
}
final int REQUEST_CODE_GALLERY = 1001;
public Map<String, RequestBody> wrapUploadImgRequest(File imgFile) {
Map<String, RequestBody> map = new HashMap<>();
if (imgFile != null) {
RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), imgFile);
map.put("image\"; filename=\"" + imgFile.getName() + "", fileBody);
}
return map;
}
/**
* 根据图片路径生成bitmap 并压缩,防止内存溢出
*
* @param srcPath
* @return
*/
public static Bitmap getimage(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//开始读入图片,此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);//此时返回bm为空
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
//现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
float hh = 800f;//这里设置高度为800f
float ww = 480f;//这里设置宽度为480f
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;//be=1表示不缩放
if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;//设置缩放比例
//重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
}
public static Bitmap comp(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
if (baos.toByteArray().length / 1024 > 1024) {//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
baos.reset();//重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%,把压缩后的数据存放到baos中
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
BitmapFactory.Options newOpts = new BitmapFactory.Options();
//开始读入图片,此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
//现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
float hh = 800f;//这里设置高度为800f
float ww = 480f;//这里设置宽度为480f
//缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
int be = 1;//be=1表示不缩放
if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;//设置缩放比例
newOpts.inPreferredConfig = Bitmap.Config.RGB_565;//降低图片从ARGB888到RGB565
//重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
isBm = new ByteArrayInputStream(baos.toByteArray());
bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
}
/**
* 将bitmap 压缩
*
* @param image
* @return
*/
public static Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 100;
while (baos.toByteArray().length / 1024 > 100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset();//重置baos即清空baos
options -= 10;//每次都减少10
image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
return bitmap;
}
/**
* 将bitmap 压缩
*
* @param image
* @return
*/
public static Bitmap compressImage(Bitmap image, int size) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 100;
while (baos.size() / 1024 > size) { //
baos.reset();//重置baos即清空baos
options -= 10;//每次都减少10
image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
}
MyLogger.kLog().e("图片压缩后大小:"+baos.toByteArray().length);
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
MyLogger.kLog().e("图片压缩后大小:"+bitmap.getByteCount());
return bitmap;
}
/***
* 根据图片路径生成文件并压缩
* @param path
* @return
*/
public static File scal(String path) {
//String path = fileUri.getPath();
File outputFile = new File(path);
long fileSize = outputFile.length();
final long fileMaxSize = 200 * 1024;
if (fileSize >= fileMaxSize) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
int height = options.outHeight;
int width = options.outWidth;
double scale = Math.sqrt((float) fileSize / fileMaxSize);
options.outHeight = (int) (height / scale);
options.outWidth = (int) (width / scale);
options.inSampleSize = (int) (scale + 0.5);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
outputFile = new File(FileUtil.createImageFile2().getPath());
FileOutputStream fos = null;
try {
if (!outputFile.exists()){
outputFile.createNewFile();
}
fos = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("", "sss ok " + outputFile.length());
if (!bitmap.isRecycled()) {
bitmap.recycle();
} else {
File tempFile = outputFile;
outputFile = new File(FileUtil.createImageFile2().getPath());
copyFileUsingFileChannels(tempFile, outputFile);
}
}
return outputFile;
}
public static File scalgif(String path) {
//String path = fileUri.getPath();
File outputFile = new File(path);
long fileSize = outputFile.length();
final long fileMaxSize = 200 * 1024;
if (fileSize >= fileMaxSize) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
int height = options.outHeight;
int width = options.outWidth;
double scale = Math.sqrt((float) fileSize / fileMaxSize);
options.outHeight = (int) (height / scale);
options.outWidth = (int) (width / scale);
options.inSampleSize = (int) (scale + 0.5);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
outputFile = new File(FileUtil.createImageGifFile().getPath());
FileOutputStream fos = null;
try {
fos = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("", "sss ok " + outputFile.length());
if (!bitmap.isRecycled()) {
bitmap.recycle();
} else {
File tempFile = outputFile;
outputFile = new File(FileUtil.createImageGifFile().getPath());
copyFileUsingFileChannels(tempFile, outputFile);
}
}
return outputFile;
}
public static File scal(String path,int size) {
Bitmap bitmap = BitmapFactory.decodeFile(path);
bitmap = compressImage(bitmap,size);
FileOutputStream fos = null;
try {
File file = new File(FileUtil.createImageFile2().getPath());
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
bitmap.recycle();
return file;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/***
* 根据uri生成文件并压缩
* @param fileUri
* @return
*/
public static File scal(Uri fileUri) {
String path = fileUri.getPath();
File outputFile = new File(path);
long fileSize = outputFile.length();
final long fileMaxSize = 200 * 1024;
if (fileSize >= fileMaxSize) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
int height = options.outHeight;
int width = options.outWidth;
double scale = Math.sqrt((float) fileSize / fileMaxSize);
options.outHeight = (int) (height / scale);
options.outWidth = (int) (width / scale);
options.inSampleSize = (int) (scale + 0.5);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
outputFile = new File(FileUtil.createImageFile2().getPath());
FileOutputStream fos = null;
try {
fos = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch bloc v
e.printStackTrace();
}
Log.d("", "sss ok " + outputFile.length());
if (!bitmap.isRecycled()) {
bitmap.recycle();
} else {
File tempFile = outputFile;
outputFile = new File(FileUtil.createImageFile2().getPath());
copyFileUsingFileChannels(tempFile, outputFile);
}
}
return outputFile;
}
private static void copyFileUsingFileChannels(File source, File dest){
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} finally {
try {
inputChannel.close();
outputChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
package com.sunny.netty.chat.util;
import java.util.UUID;
/**
* <Description> <br>
*
* @author Sunny<br>
* @version 1.0<br>
* @taskId: <br>
* @createDate 2018/10/27 13:55 <br>
* @see com.sunny.netty.chat.util <br>
*/
public class IDUtil {
public static String randomId() {
return UUID.randomUUID().toString().split("-")[0];
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.