blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d23b2bffc06e25332e85edbf4b6df4da5e0d4dae | ce66a3061461c5f9226537ec9cd5a7c0817a5219 | /src/main/java/chain_of_responsibility/example/second/middleware/RoleCheckMiddleware.java | 2975b528963503d150b3766e10b8befefe1ed8c6 | [] | no_license | mattrandom/DesignPatterns | c970acc12113a07283f58494fd55c00f28ad34c6 | b59e61c8f152522f1168fe63452d196b647259da | refs/heads/master | 2022-12-22T09:47:06.609188 | 2020-09-28T18:00:54 | 2020-09-28T18:00:54 | 291,809,274 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 553 | java | package chain_of_responsibility.example.second.middleware;
/**
* ConcreteHandler. Checks a user's role.
*/
public class RoleCheckMiddleware extends Middleware {
@Override
public boolean check(String email, String password) {
if (email.equals("[email protected]")) {
System.out.println("Hello, admin!");
return true;
}
if (email.equals("[email protected]")) {
System.out.println("Hello, user!");
return true;
}
return checkNext(email, password);
}
}
| [
"[email protected]"
] | |
d79d20d1da4334c1be5ae5481efdbf3219e69a4d | c340adb4e58376f3adb3247e9bc167ed34070a70 | /src/inlamningsuppgift2/GameBoard.java | 8d01203dec6dc98791d54b59c57b5831a87049a4 | [] | no_license | TKYK93/OOPInlamningsUppgift2 | ce635a5636fbfb16a3d11d330f6f0baa499d8082 | f39f83aecda54b11cf71a8f0f11bd9e76cdb7213 | refs/heads/master | 2023-08-30T02:12:18.813855 | 2021-10-22T12:52:23 | 2021-10-22T12:52:23 | 419,741,670 | 0 | 0 | null | 2021-10-21T14:08:35 | 2021-10-21T13:48:04 | Java | UTF-8 | Java | false | false | 6,024 | java | package inlamningsuppgift2;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class GameBoard extends JPanel {
private int rows = 4;
private int columns = 4;
private Tile[][] tiles = new Tile[rows][columns];
GameBoard() {
setMaximumSize(new Dimension(Config.gameBoardWidth, Config.gameBoardHeight));
setLayout(new GridLayout(rows,columns));
// ----- For test only in case of 4 x 4 -----------
testForGameClearFuncInitialize();
// -------------------------------
// initializeTiles();
}
// For test only in case of 4 x 4
public void testForGameClearFuncInitialize() {
ArrayList<Integer> listTest = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 15));
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
int tileNumber = listTest.remove(0);
Tile currentTile = new Tile(tileNumber, j, i);
if(tileNumber == rows * columns){
currentTile.setBackground(new Color(223,212,202));
currentTile.setText("");
}
currentTile.addActionListener(event -> {
swapTiles(currentTile);
boolean isGameDone = checkIsGameDone();
if(isGameDone){
System.out.println("Congrats!! Game is clear!!");
showGameClearMessage();
}
});
tiles[i][j] = currentTile;
add(currentTile);
}
}
}
public void initializeTiles() {
removeAll();
// create a random order array
ArrayList<Integer> list = new ArrayList<>();
for(int j = 1 ; j < rows*columns ; j++) {
list.add(j);
}
Collections.shuffle(list);
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++){
if(i == rows-1 && j == columns-1){
Tile emptyTile = new Tile(rows*columns, columns-1, rows-1);
emptyTile.setText("");
emptyTile.setBackground(new Color(223,212,202));
tiles[rows-1][columns-1] = emptyTile;
add(emptyTile);
break;
}
int tileNumber = list.remove(0);
Tile currentTile = new Tile(tileNumber, j, i);
currentTile.addActionListener(event -> {
swapTiles(currentTile);
boolean isGameDone = checkIsGameDone();
if(isGameDone){
showGameClearMessage();
}
});
tiles[i][j] = currentTile;
add(currentTile);
}
}
}
private void setTilesFromList(){
removeAll();
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
add(tiles[i][j]);
}
}
revalidate();
}
public Tile getEmptyTile(){
for(int i = 0; i < rows ; i++){
for(int j = 0; j < columns;j++){
if(tiles[i][j].getNumber() == rows * columns){
return tiles[i][j];
}
}
}
return null;
}
public boolean checkIsNextTileEmpty(Tile tile, String direction) {
Tile emptyTile = getEmptyTile();
if(emptyTile == null){
return false;
}
int x = tile.getXPos();
int y = tile.getYPos();
int emptyX = emptyTile.getXPos();
int emptyY = emptyTile.getYPos();
switch(direction){
case "UP":
return x == emptyX && y - 1 == emptyY;
case "DOWN":
return x == emptyX && y + 1 == emptyY;
case "LEFT":
return x - 1 == emptyX && y == emptyY;
case "RIGHT":
return x + 1 == emptyX && y == emptyY;
default:
return false;
}
}
public boolean swapTiles(Tile tile){
boolean isUpEmpty = checkIsNextTileEmpty(tile, "UP");
boolean isDownEmpty = checkIsNextTileEmpty(tile, "DOWN");
boolean isLeftEmpty = checkIsNextTileEmpty(tile, "LEFT");
boolean isRightEmpty = checkIsNextTileEmpty(tile, "RIGHT");
if(isUpEmpty || isDownEmpty || isLeftEmpty || isRightEmpty ){
Tile emptyTile = getEmptyTile();
int emptyTileX = emptyTile.getXPos();
int emptyTileY = emptyTile.getYPos();
int tileX = tile.getXPos();
int tileY = tile.getYPos();
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
if(tiles[i][j].getNumber() == tile.getNumber()){
emptyTile.setXPos(tileX);
emptyTile.setYPos(tileY);
tiles[i][j] = emptyTile;
} else if(tiles[i][j].getNumber() == rows*columns){
tile.setXPos(emptyTileX);
tile.setYPos(emptyTileY);
tiles[i][j] = tile;
}
}
}
setTilesFromList();
return true;
}
return false;
}
public boolean checkIsGameDone () {
int correctNumber = 1;
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
if(tiles[i][j].getNumber() != correctNumber){
return false;
}
correctNumber++;
}
}
return true;
}
public void showGameClearMessage(){
removeAll();
setLayout(new BorderLayout());
add(new GameDonePanel());
revalidate();
}
}
| [
"[email protected]"
] | |
c06c65a8a7a499755c95edd98336a8e3c324141e | d75bb974ed4922e1c050bb0bd61e3b91785d548f | /base-infra/src/main/java/br/com/jsbse/arquitetura/json/EnumeradoPersistenteDtoDeserializer.java | d7b9362572286eb82fe96a504369d77c6ba71954 | [] | no_license | brunoaquino/BaseInfra | 7705088af0232fb6735a78d6086a1d118ee31471 | 8b6750f1f6ca1e4964f016f062cf438ffd5d184e | refs/heads/master | 2021-01-18T20:53:29.723782 | 2015-11-30T12:38:54 | 2015-11-30T12:38:54 | 45,698,132 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,057 | java | package br.com.jsbse.arquitetura.json;
import java.io.IOException;
import br.com.jsbse.arquitetura.entidade.EnumeradoPersistenteDto;
import br.com.jsbse.arquitetura.servico.dto.EnumeradoDto;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
public class EnumeradoPersistenteDtoDeserializer extends JsonDeserializer<EnumeradoPersistenteDto> {
@Override
public EnumeradoDto deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
JsonNode idNode = node.get("id");
if (idNode == null)
return null;
String id = idNode.asText();
JsonNode descricaoNode = node.get("descricao");
String descricao = descricaoNode != null ? descricaoNode.asText() : null;
return new EnumeradoDto(id, descricao);
}
}
| [
"[email protected]"
] | |
629da88d4ff565d0084bfe669ee116f54c68db00 | 8184579bed3dda3b0d121166672f908654c220cb | /src/test/java/com/zhou/epitome/kafka/KafkaTest.java | 4097731fd23919daa5f495731f3f2df16abee335 | [] | no_license | laicz/epitome | 435da674d30a0a4c6f9a0163185246841f8342d4 | 309a3ade653a2337c25b5fd1e7adf95775c12b9a | refs/heads/master | 2022-06-30T16:29:05.212921 | 2019-06-10T14:27:50 | 2019-06-10T14:27:50 | 171,470,082 | 0 | 0 | null | 2022-06-21T00:56:52 | 2019-02-19T12:30:14 | Java | UTF-8 | Java | false | false | 7,742 | java | /**
* Date: 2019/6/523:55
* AUTHOR: Administrator
*/
package com.zhou.epitome.kafka;
import com.google.common.collect.ImmutableList;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.junit.Before;
import org.junit.Test;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
/**
* 2019/6/5 23:55
* created by zhoumb
*/
public class KafkaTest {
private KafkaProducer<String, String> kafkaProducer;
private KafkaConsumer<String, String> kafkaConsumer;
private static final String TOPIC_NAME = "test1";
/**
* 获取kafka生产者
*/
@Before
public void createProducer() {
Properties kafkaProps = new Properties();
kafkaProps.put("bootstrap.servers", "60.205.176.135:9092");
kafkaProps.put("key.serializer", StringSerializer.class.getName());
kafkaProps.put("value.serializer", StringSerializer.class.getName());
kafkaProps.put("linger.ms", 10000L);
kafkaProducer = new KafkaProducer<>(kafkaProps);
kafkaProps.remove("key.serializer");
}
/**
* 获取kafka消费者
*/
@Before
public void createConsumer() {
kafkaConsumer = getKafkaConsumer("test_group", TOPIC_NAME);
}
@Test
public void testToPosition() {
System.out.println(toPosition(-1));
System.out.println(Integer.MAX_VALUE);
}
/**
* 发送消息至不存在的topic中
* 会同时创建kafka的topic
*/
@Test
public void testSendNotExistsTopic() throws InterruptedException {
ProducerRecord<String, String> record = new ProducerRecord<>("not_exists_topic", "test_key1", "test_value");
kafkaProducer.send(record);
}
/**
* 同步发送数据
* 特点:
* 低延时
* 低吞吐率
* 无数据丢失
*/
@Test
public void testSyncSendMessage() {
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC_NAME, "key1", "value1");
try {
//同步发送数据并返回回调
//如果发生异常且
RecordMetadata recordMetadata = kafkaProducer.send(record).get();
System.out.println("offset:" + recordMetadata.offset() + " : hasOffset:" + recordMetadata.hasOffset());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
/**
* 异步发送消息
*/
private CountDownLatch countDownLatch = new CountDownLatch(1);
@Test
public void asyncSendMessage() throws InterruptedException {
ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC_NAME, "async_send_message_key", "async_send_message_value");
long currentTimeMillis = System.currentTimeMillis();
kafkaProducer.send(record, new DemoProducerCallback());
countDownLatch.await();
System.out.println(System.currentTimeMillis() - currentTimeMillis);
}
/**
* 异步发送消息回调
*/
class DemoProducerCallback implements Callback {
@Override
public void onCompletion(RecordMetadata metadata, Exception exception) {
if (Objects.nonNull(metadata)) {
System.out.println("offset:" + metadata.offset() + " : hasOffset:" + metadata.hasOffset());
}
if (Objects.nonNull(exception)) {
exception.printStackTrace();
}
countDownLatch.countDown();
}
}
@Test
public void testConsumer() {
Map<String, List<PartitionInfo>> stringListMap = kafkaConsumer.listTopics();
stringListMap.forEach((key, partitionInfos) -> {
System.out.println("----------------------------");
partitionInfos.forEach(info -> {
System.out.println("key:" + key + ",partition:" + info.partition() + ",relic " + info.replicas());
});
});
}
/**
* Rebalance:当发生rebalance时,如果存在还有被消费的offset还没有被提交,容易发生重复读的情况,需要在rebalance之前将offset进行提交
*/
@Test
public void rollPollTopic() {
kafkaConsumer.subscribe(Collections.singleton(TOPIC_NAME), new ConsumerRebalanceListener() {
/**
* 该方法会在消费者停止读取数据之后,broker重新分配(reloadBalance)之前调用
* @param partitions
*/
@Override
public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
kafkaConsumer.commitSync();
}
/**
* 该方法会在broker重新分配之后,消费者重新读取数据之前调用
* @param partitions
*/
@Override
public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
}
});
while (true) {
ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(100L));
for (ConsumerRecord<String, String> record : records) {
System.out.println("--------------------------------------------------------------------------------------------");
System.out.println("key[" + record.key() + "] : value[" + record.value() + "] : offset[" + record.offset() + "] : partition:[" + record.partition() + "]");
kafkaConsumer.commitSync();
}
}
}
@Test
public void syncAndAsyncCommit() {
kafkaConsumer.subscribe(ImmutableList.of(TOPIC_NAME));
while (true) {
ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(100L));
for (ConsumerRecord<String, String> record : records) {
System.out.println("--------------------------------------------------------------------------------------------");
System.out.println("key[" + record.key() + "] : value[" + record.value() + "] : offset[" + record.offset() + "] : partition:[" + record.partition() + "]");
}
//处理完所有的业务,同步提交offset
try {
kafkaConsumer.commitSync();
} catch (Exception e) {
//如果发生异常,则异步提交offset,异步提交不会重试
kafkaConsumer.commitAsync();
}
}
}
private int toPosition(int target) {
return target & 0x7fffffff;
}
public KafkaConsumer getKafkaConsumer(final String groupId, String... topicName) {
Properties properties = new Properties();
properties.put("bootstrap.servers", "60.205.176.135:9092");
properties.put("group.id", groupId);
properties.put("key.deserializer", StringDeserializer.class.getName());
properties.put("value.deserializer", StringDeserializer.class.getName());
return new KafkaConsumer<>(properties);
}
}
| [
"[email protected]"
] | |
365080a17be4b5877e6052535641041cccc89a6f | 263a8c497ffb766cbcf93ea71417e4dbd31ab06d | /app/src/androidTest/java/com/dezhoutuu/zhuan/ExampleInstrumentedTest.java | 6d5ed7bbe013adca89370fbba5a025da7c980278 | [] | no_license | DeZhouTUU/zhuan | 7705bc058ce8f077e91ce5265920142916c9a469 | 494696a51ea816f13cacf9afde21671d76c55b19 | refs/heads/master | 2020-03-18T21:17:34.761133 | 2018-06-09T09:45:27 | 2018-06-09T09:45:27 | 135,272,187 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 739 | java | package com.dezhoutuu.zhuan;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.dezhoutuu.zhuan", appContext.getPackageName());
}
}
| [
"act_product_detail_ticket_parent"
] | act_product_detail_ticket_parent |
dbef545808f275b31605a9743b7a63eca50ef7ce | b3942e0003f1848d834aa5382f6eefc07080642b | /app/src/test/java/id/sch/smktelkom/learn/fragment1/ExampleUnitTest.java | 0d2c2dfdb653e3de1a60a3298b0147f60c43754b | [] | no_license | farras13/Fragment1 | 6d994a9a78d35733da9d815a736de6f316cf761e | 9aead816b3c9f42046a197715f550dd873014b03 | refs/heads/master | 2021-01-11T16:06:53.433120 | 2017-02-08T20:14:22 | 2017-02-08T20:14:22 | 80,006,744 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 421 | java | package id.sch.smktelkom.learn.fragment1;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
71874710b1c3091dceff06585e2b2d123a50ab8c | e03c628499dd00e5abc2e88362ec07cccd947920 | /src/naftoreiclag/flowchartarch/Surprise.java | 8214a05538258be46d97a35e2f8b71f753e3cd6f | [
"Apache-2.0"
] | permissive | Naftoreiclag/Flow-Chart-Architecture | e015376cb527e1020d1fae4ccac50c19c983c87b | 1a515da7511b1230206920ff1a9c108ec054439b | refs/heads/master | 2021-01-02T22:17:31.000993 | 2014-10-31T04:07:20 | 2014-10-31T04:07:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 408 | java | /* Copyright (c) 2014 "Naftoreiclag" https://github.com/Naftoreiclag
*
* Distributed under the Apache License Version 2.0 (http://www.apache.org/licenses/)
* See accompanying file LICENSE
*/
package naftoreiclag.flowchartarch;
public class Surprise
{
public String string;
public Surprise(String string)
{
this.string = string;
}
@Override
public String toString()
{
return string;
}
}
| [
"[email protected]"
] | |
371c143487fd7c39e2de51c05e871b7794ed448f | f86135957c9118a74305c4deb33817dbbfd68b86 | /src/com/git/java/swings/DataSet.java | 1fb141282d7cedb4d69e4a51f6e7cea904f049d8 | [] | no_license | webapps1/myjavaproject | 2fce75ddeddc73b6f9043ee587decb9014520875 | ff09f041c337889cc47224888942d22fc46d2d5c | refs/heads/master | 2021-01-10T01:37:48.134681 | 2015-05-21T05:31:24 | 2015-05-21T05:31:24 | 35,991,663 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,201 | java | package com.git.java.swings;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.sql.*;
import javax.swing.*;
public class DataSet implements ActionListener
{
public JFrame frame=new JFrame("GUI Main");
public JPanel top=new JPanel();
public JPanel bottom=new JPanel();
public JLabel lpid,lpname,ldisease,lrdate,lstage,lage,lzip;
public JTextField tpid,tpname,tdisease,trdate,tstage,tfage,tfzip;
public JButton add,add1,clear,exit,update,delete,checkavail;
Connection con;
Statement st = null;
ResultSet rs = null;
PreparedStatement ps=null,ps1=null;
public DataSet()
{
top.setLayout(null);
bottom.setLayout(null);
topdesign();
frame.add(top);
frame.setLayout(new GridLayout(1,1));
frame.setSize(435,380);
frame.setVisible(true);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int w = frame.getSize().width;
int h = frame.getSize().height;
int x = (dim.width-w)/2;
int y = (dim.height-h)/2;
frame.setLocation(x, y);
frame.setResizable(false);
update.setEnabled(false);
delete.setEnabled(false);
}
public void topdesign()
{
lpid=new JLabel("Patient ID");
lpid.setBounds(40,15,100,20);
top.add(lpid);
lpname=new JLabel("Patient Name");
lpname.setBounds(40,55,100,20);
top.add(lpname);
ldisease=new JLabel("Disease");
ldisease.setBounds(40,95,100,20);
top.add(ldisease);
lrdate=new JLabel("Rec. Date");
lrdate.setBounds(40,135,100,20);
top.add(lrdate);
lstage=new JLabel("Stage");
lstage.setBounds(40,175,100,20);
top.add(lstage);
lage=new JLabel("Age");
lage.setBounds(40,215,100,20);
top.add(lage);
lzip=new JLabel("ZIP Code");
lzip.setBounds(40,255,100,20);
top.add(lzip);
tpid=new JTextField();
tpid.setBounds(160,15,100,20);
//tpid.setText("Auto");
top.add(tpid);
tpname=new JTextField();
tpname.setBounds(160,55,200,20);
top.add(tpname);
tdisease=new JTextField();
tdisease.setBounds(160,95,180,20);
top.add(tdisease);
trdate=new JTextField();
trdate.setBounds(160,135,180,20);
top.add(trdate);
tstage=new JTextField();
tstage.setBounds(160,175,100,20);
top.add(tstage);
tfage=new JTextField();
tfage.setBounds(160,215,100,20);
top.add(tfage);
tfzip=new JTextField();
tfzip.setBounds(160,255,100,20);
top.add(tfzip);
add1=new JButton("Generalize");
add1.setBounds(280,255,120,25);
top.add(add1);
add=new JButton("k-Anonymous Update");
add.setBounds(20,305,215,25);
top.add(add);
update=new JButton("Update");
update.setBounds(100,305,60,25);
//top.add(update);
clear=new JButton("Clear");
clear.setBounds(260,305,60,25);
top.add(clear);
exit=new JButton("Exit");
exit.setBounds(340,305,60,25);
top.add(exit);
delete=new JButton("Delete");
delete.setBounds(180,305,60,25);
//top.add(delete);
checkavail=new JButton("Search");
checkavail.setBounds(270,13,100,25);
top.add(checkavail);
add1.addActionListener(this);
add.addActionListener(this);
clear.addActionListener(this);
update.addActionListener(this);
exit.addActionListener(this);
delete.addActionListener(this);
checkavail.addActionListener(this);
add.setEnabled(false);
tpname.setText("");
}
public void actionPerformed(ActionEvent ae)
{
try
{
if(ae.getSource()==add)
{
JOptionPane.showMessageDialog(null,"Anonymous update succeeded.");
tpname.setText("");
tdisease.setText("");
trdate.setText("");
tstage.setText("");
tfage.setText("");
tpid.setText("");
tfzip.setText("");
add.setEnabled(false);
}
else if(ae.getSource()==add1)
{
try
{
JOptionPane.showMessageDialog(null,"Operation failed...");
}catch(Exception ex2)
{
System.out.println("excet "+ex2);
JOptionPane.showMessageDialog(null,ex2);
}
}
else if(ae.getSource()==exit)
{
frame.setVisible(false);
}
else if(ae.getSource()==clear)
{
tpname.setText("");
tdisease.setText("");
trdate.setText("");
tstage.setText("");
tfage.setText("");
tpid.setText("");
tfzip.setText("");
}
else if(ae.getSource()==update)
{
try
{
JOptionPane.showMessageDialog(null,"Record Updated Successfully");
}catch(Exception ex2)
{
System.out.println("excet "+ex2);
}
}
else if(ae.getSource()==delete)
{
try
{
JOptionPane.showMessageDialog(null,"Record Deleted Successfully");
}catch(Exception ex2)
{
System.out.println("excet "+ex2);
}
}
else if(ae.getSource()==checkavail)
{
int rid = Integer.parseInt(tpid.getText());
if(rid==0)
{
JOptionPane.showMessageDialog(null,"Please Enter Resource ID");
}
}
}catch(Exception ac)
{
ac.printStackTrace();
}
}
} | [
"[email protected]"
] | |
d4ad8b621068dd65692dd2d972c022a61aa58df2 | 9bd6bc4fa68c6059f17105070afb3ca85f58174e | /org.eclipse.om2m-1.0.0/org.eclipse.om2m.commons/src/main/java/org/eclipse/om2m/commons/resource/AreaNwkDeviceInfoAnnc.java | 39a0c33bc32711fc95aec7ffb93d49799b18de7f | [] | no_license | rocky-nupt/weather_web-based-on-om2m | 93f0d65bc18e95e65639be69bc6d91de66ba75ec | a0dd271ce0298fb1e8233cdcfec790c7bbd1ae23 | refs/heads/master | 2021-01-19T09:48:34.071438 | 2018-03-08T02:58:03 | 2018-03-08T02:58:03 | 87,788,260 | 6 | 1 | null | 2019-05-21T14:35:42 | 2017-04-10T08:48:50 | Java | UTF-8 | Java | false | false | 8,474 | java | /*******************************************************************************
* Copyright (c) 2013-2016 LAAS-CNRS (www.laas.fr)
* 7 Colonel Roche 31077 Toulouse - France
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* Thierry Monteil : Project manager, technical co-manager
* Mahdi Ben Alaya : Technical co-manager
* Samir Medjiah : Technical co-manager
* Khalil Drira : Strategy expert
* Guillaume Garzone : Developer
* François Aïssaoui : Developer
*
* New contributors :
*******************************************************************************/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.04.15 at 03:56:27 PM CEST
//
package org.eclipse.om2m.commons.resource;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Java class for anonymous complex type.
*
* <p>
* The following schema fragment specifies the expected content contained within
* this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{http://www.onem2m.org/xml/protocols}announcedMgmtResource">
* <sequence>
* <element name="devID" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="devType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="areaNwkId" type="{http://www.w3.org/2001/XMLSchema}anyURI" minOccurs="0"/>
* <element name="sleepInterval" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger" minOccurs="0"/>
* <element name="sleepDuration" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger" minOccurs="0"/>
* <element name="status" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="listOfNeighbors" type="{http://www.onem2m.org/xml/protocols}listOfURIs" minOccurs="0"/>
* <choice minOccurs="0">
* <element name="childResource" type="{http://www.onem2m.org/xml/protocols}childResourceRef" maxOccurs="unbounded"/>
* <element ref="{http://www.onem2m.org/xml/protocols}subscription" maxOccurs="unbounded"/>
* </choice>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "devID", "devType", "areaNwkId",
"sleepInterval", "sleepDuration", "status", "listOfNeighbors",
"childResource", "subscription" })
@XmlRootElement(name = "areaNwkDeviceInfoAnnc")
public class AreaNwkDeviceInfoAnnc extends AnnouncedMgmtResource {
protected String devID;
protected String devType;
@XmlSchemaType(name = "anyURI")
protected String areaNwkId;
@XmlSchemaType(name = "nonNegativeInteger")
protected BigInteger sleepInterval;
@XmlSchemaType(name = "nonNegativeInteger")
protected BigInteger sleepDuration;
protected String status;
@XmlList
protected List<String> listOfNeighbors;
protected List<ChildResourceRef> childResource;
@XmlElement(namespace = "http://www.onem2m.org/xml/protocols")
protected List<Subscription> subscription;
/**
* Gets the value of the devID property.
*
* @return possible object is {@link String }
*
*/
public String getDevID() {
return devID;
}
/**
* Sets the value of the devID property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setDevID(String value) {
this.devID = value;
}
/**
* Gets the value of the devType property.
*
* @return possible object is {@link String }
*
*/
public String getDevType() {
return devType;
}
/**
* Sets the value of the devType property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setDevType(String value) {
this.devType = value;
}
/**
* Gets the value of the areaNwkId property.
*
* @return possible object is {@link String }
*
*/
public String getAreaNwkId() {
return areaNwkId;
}
/**
* Sets the value of the areaNwkId property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setAreaNwkId(String value) {
this.areaNwkId = value;
}
/**
* Gets the value of the sleepInterval property.
*
* @return possible object is {@link BigInteger }
*
*/
public BigInteger getSleepInterval() {
return sleepInterval;
}
/**
* Sets the value of the sleepInterval property.
*
* @param value
* allowed object is {@link BigInteger }
*
*/
public void setSleepInterval(BigInteger value) {
this.sleepInterval = value;
}
/**
* Gets the value of the sleepDuration property.
*
* @return possible object is {@link BigInteger }
*
*/
public BigInteger getSleepDuration() {
return sleepDuration;
}
/**
* Sets the value of the sleepDuration property.
*
* @param value
* allowed object is {@link BigInteger }
*
*/
public void setSleepDuration(BigInteger value) {
this.sleepDuration = value;
}
/**
* Gets the value of the status property.
*
* @return possible object is {@link String }
*
*/
public String getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setStatus(String value) {
this.status = value;
}
/**
* Gets the value of the listOfNeighbors property.
*
* <p>
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned list will
* be present inside the JAXB object. This is why there is not a
* <CODE>set</CODE> method for the listOfNeighbors property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getListOfNeighbors().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list {@link String }
*
*
*/
public List<String> getListOfNeighbors() {
if (listOfNeighbors == null) {
listOfNeighbors = new ArrayList<String>();
}
return this.listOfNeighbors;
}
/**
* Gets the value of the childResource property.
*
* <p>
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned list will
* be present inside the JAXB object. This is why there is not a
* <CODE>set</CODE> method for the childResource property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getChildResource().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ChildResourceRef }
*
*
*/
public List<ChildResourceRef> getChildResource() {
if (childResource == null) {
childResource = new ArrayList<ChildResourceRef>();
}
return this.childResource;
}
/**
* Gets the value of the subscription property.
*
* <p>
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned list will
* be present inside the JAXB object. This is why there is not a
* <CODE>set</CODE> method for the subscription property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getSubscription().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Subscription }
*
*
*/
public List<Subscription> getSubscription() {
if (subscription == null) {
subscription = new ArrayList<Subscription>();
}
return this.subscription;
}
}
| [
"[email protected]"
] | |
90fb31580e17f149d0a044a46e0787e287b161dd | d3187abadded3cb02d626866b10fdb6d52f3a706 | /erpweb/src/test/java/com/hejian/men/repository/JpaMappingTest.java | 0ef4e7cbd7979bf3939ffd010e9858126c16929a | [] | no_license | mhjian/GitTest | 7ceb78f57330c49a3baddaa1ead1acdbd36f6208 | b297f8f2e1cd7a987d5e9f2015d6a4215c6a3010 | refs/heads/master | 2021-01-10T06:30:52.621119 | 2014-04-11T15:40:15 | 2014-04-11T15:40:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,180 | java | package com.hejian.men.repository;
import static org.junit.Assert.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springside.modules.test.spring.SpringTransactionalTestCase;
@ContextConfiguration(locations = { "/applicationContext.xml" })
public class JpaMappingTest extends SpringTransactionalTestCase {
private static Logger logger = LoggerFactory.getLogger(JpaMappingTest.class);
@PersistenceContext
private EntityManager em;
@Test
public void allClassMapping() throws Exception {
Metamodel model = em.getEntityManagerFactory().getMetamodel();
assertTrue("No entity mapping found", model.getEntities().size() > 0);
for (EntityType entityType : model.getEntities()) {
String entityName = entityType.getName();
em.createQuery("select o from " + entityName + " o").getResultList();
logger.info("ok: " + entityName);
}
}
}
| [
"[email protected]"
] | |
fe6f615afc2704ba77cb33cc080fd171f9dacf67 | 9756f8dfd536ec22cdb742818156fb310a0f1f85 | /src/main/java/iks/gog/jpatst/model/Role.java | 13ca76615bb485db31207866f2327de9d8dfcc0d | [] | no_license | CruelIks/simpleForum | b18a96b7439bfa73bb9d94c61c094d82ae688b1b | b9b937fb952d1406248e850b10b23a498b80a9b9 | refs/heads/master | 2021-01-15T14:19:31.835965 | 2017-08-14T18:53:05 | 2017-08-14T18:53:05 | 99,688,184 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 68 | java | package iks.gog.jpatst.model;
public enum Role {
USER, ADMIN
}
| [
"[email protected]"
] | |
b8459446a8beb267dfffee4026b92c1cc8b145a6 | 553628b33a1da2e499b991b56dee8cb775687a0c | /lib_domain/src/main/java/com/barber/domain/entity/User.java | df0133958d9f3921c21ca5fa817e515ac9d8b2e7 | [] | no_license | AniltonMoraisJr/SpringBootBarberJwt | 5814370413a6f87da23c961fbd75f8589d4aa946 | bc758f0d54682a7d35895f6ebe5fa730f08a0802 | refs/heads/main | 2023-06-05T14:46:32.557567 | 2021-06-13T18:23:36 | 2021-06-13T18:23:36 | 376,376,252 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,326 | java | package com.barber.domain.entity;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
@Data
@EqualsAndHashCode(callSuper=false)
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name="users")
public class User extends AuditModel implements Serializable {
private static final long serialVersionUID = -7977572072555953926L;
@NotBlank
@Size(max = 40)
private String name;
@NotBlank
@Size(max = 15)
private String username;
@NotBlank
@Size(max = 40)
@Email
private String email;
@NotBlank
@Size(max = 100)
private String password;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
}
| [
"[email protected]"
] | |
3890f524bf3678d2daa19cd39d8296d0430d64a3 | 6034ce04789d9609fa0bd57619d6913041a17e7a | /src/main/java/com/blogger/comment/constant/CommentConstants.java | e9b4bc3497209adcf6c8d79e111a26509fe08ffc | [] | no_license | rohitagrawal701/blogger-comment-module | 3f689cd3400b5866e5537d18fd29a44fc9d4a43d | a388d4dd643e200175ce25df7663ef1ff588833e | refs/heads/master | 2020-03-14T01:51:48.317041 | 2018-09-26T06:29:44 | 2018-09-26T06:29:44 | 131,386,601 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,035 | java | package com.blogger.comment.constant;
/**
* Application level constants.
*
* @author Rohit.
*/
public class CommentConstants {
/**
* Message to be shown on success
*/
public static final String SUCCESS = "success";
/**
* Success code.
*/
public static final String SUCCESS_CODE = "0";
/**
* No record found error.
*/
public static final String RECORDS_NOT_FOUND = "records.not.found";
/**
* Syntax Error code.
*/
public static final String ERROR_SYNTAX_CODE = "SNT1001";
/**
* Status type - Syntax error.
*/
public static final String ERROR_SYNTAX_TYPE = "Syntax Error";
/**
* Runtime Exception code
*/
public static final String ERROR_APPLICATION_CODE = "RUN1008";
/**
* Status type - Runtime error.
*/
public static final String ERROR_APPLICATION_TYPE = "Runtime Error";
/**
* Status type - Service error.
*/
public static final String ERROR_TYPE_SERVICE = "Service Error";
}
| [
"[email protected]"
] | |
76f3f1b0690766ae67358fe89336c083f3044811 | c47fbeee0a1bd4affe8e5592f624b9bfb28799d3 | /graphql-complete/src/main/java/com/github/dreamylost/HttpExampleApplication.java | 63e62063bae4e2a36cfc0f88cb01721c9cfa0534 | [] | no_license | jipeihao/springboot-examples | eede1457e0b38455149946e6d78c95a54f305f96 | cc7dbb6e0582dee919e2fcb83f179b0ec8d0fa23 | refs/heads/master | 2023-07-17T03:46:13.632626 | 2021-09-01T11:36:19 | 2021-09-01T11:36:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 423 | java | package com.github.dreamylost;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//启动本类
//入门的中文文档 https://graphql.org.cn/learn/queries-fields.html
@SpringBootApplication
public class HttpExampleApplication {
public static void main(String[] args) {
SpringApplication.run(HttpExampleApplication.class, args);
}
}
| [
"[email protected]"
] | |
5d1e67c84c5d2ea989baf21f61f87bc14c5b57d9 | d3ce33abba161ff578b33032332d53d41846bac1 | /collection_1120/src/course/fileAndIO2_1128/demo/Test3.java | 82fc951c64e66d5d495334a1014e3b4152394d11 | [] | no_license | wangshiyudori/JavaOOP-JavaWeb | bf905d59ab03bde184dd4a17692719b86227b0b8 | 6dca1a0d70f5710253cb7be7f9988635a5b85706 | refs/heads/master | 2022-11-04T13:24:48.216716 | 2020-06-16T14:39:17 | 2020-06-16T14:39:17 | 272,728,153 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,303 | java | package course.fileAndIO2_1128.demo;
import java.io.*;
public class Test3 {
public static void main(String[] args) {
String fileName = "cat.jpg";
String fileName2 = "cat2.jpg";
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(fileName);
outputStream = new FileOutputStream(fileName2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
DataInputStream dataInputStream = new DataInputStream(inputStream);
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
int data = 0;
try {
while (dataInputStream.available()>0){
data = dataInputStream.read();
dataOutputStream.write(data);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
dataOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
dataInputStream.close();
inputStream.close();
dataOutputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
851233941e89a7d3eacbbe4190467fed1d98b46b | 5751f920a13ea8e3cf8ef00e880e439cfd6b29b9 | /ConvenienceServices/src/com/future/link/utils/ToolString.java | 0c6855e17414e321bcaabdf016ad228155dc5350 | [] | no_license | zbb-jzh/ConvenienceServices | b22cd2d9abeec7e3bc3e9eecae5d426ca85e9952 | 25e2969f2e5cdc08d000d887e29dac853bccec7f | refs/heads/master | 2020-04-13T18:38:59.032611 | 2019-01-04T08:53:34 | 2019-01-04T08:53:34 | 163,380,916 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,911 | java | package com.future.link.utils;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 字符串处理常用方法
*/
public abstract class ToolString {
@SuppressWarnings("unused")
private static Logger log = Logger.getLogger(ToolString.class);
/**
* 常用正则表达式:匹配非负整数(正整数 + 0)
*/
public final static String regExp_integer_1 = "^\\d+$";
/**
* 常用正则表达式:匹配正整数
*/
public final static String regExp_integer_2 = "^[0-9]*[1-9][0-9]*$";
/**
* 常用正则表达式:匹配非正整数(负整数 + 0)
*/
public final static String regExp_integer_3 = "^((-\\d+) ?(0+))$";
/**
* 常用正则表达式:匹配负整数
*/
public final static String regExp_integer_4 = "^-[0-9]*[1-9][0-9]*$";
/**
* 常用正则表达式:匹配整数
*/
public final static String regExp_integer_5 = "^-?\\d+$";
/**
* 常用正则表达式:匹配非负浮点数(正浮点数 + 0)
*/
public final static String regExp_float_1 = "^\\d+(\\.\\d+)?$";
/**
* 常用正则表达式:匹配正浮点数
*/
public final static String regExp_float_2 = "^(([0-9]+\\.[0-9]*[1-9][0-9]*) ?([0-9]*[1-9][0-9]*\\.[0-9]+) ?([0-9]*[1-9][0-9]*))$";
/**
* 常用正则表达式:匹配非正浮点数(负浮点数 + 0)
*/
public final static String regExp_float_3 = "^((-\\d+(\\.\\d+)?) ?(0+(\\.0+)?))$";
/**
* 常用正则表达式:匹配负浮点数
*/
public final static String regExp_float_4 = "^(-(([0-9]+\\.[0-9]*[1-9][0-9]*) ?([0-9]*[1-9][0-9]*\\.[0-9]+) ?([0-9]*[1-9][0-9]*)))$";
/**
* 常用正则表达式:匹配浮点数
*/
public final static String regExp_float_5 = "^(-?\\d+)(\\.\\d+)?$";
/**
* 常用正则表达式:匹配由26个英文字母组成的字符串
*/
public final static String regExp_letter_1 = "^[A-Za-z]+$";
/**
* 常用正则表达式:匹配由26个英文字母的大写组成的字符串
*/
public final static String regExp_letter_2 = "^[A-Z]+$";
/**
* 常用正则表达式:匹配由26个英文字母的小写组成的字符串
*/
public final static String regExp_letter_3 = "^[a-z]+$";
/**
* 常用正则表达式:匹配由数字和26个英文字母组成的字符串
*/
public final static String regExp_letter_4 = "^[A-Za-z0-9]+$";
/**
* 常用正则表达式:匹配由数字、26个英文字母或者下划线组成的字符串
*/
public final static String regExp_letter_5 = "^\\w+$";
/**
* 常用正则表达式:匹配email地址
*/
public final static String regExp_email = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
/**
* 常用正则表达式:匹配url
*/
public final static String regExp_url_1 = "^[a-zA-z]+://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$";
/**
* 常用正则表达式:匹配url
*/
public final static String regExp_url_2 = "[a-zA-z]+://[^\\s]*";
/**
* 常用正则表达式:匹配中文字符
*/
public final static String regExp_chinese_1 = "[\\u4e00-\\u9fa5]";
/**
* 常用正则表达式:匹配双字节字符(包括汉字在内)
*/
public final static String regExp_chinese_2 = "[^\\x00-\\xff]";
/**
* 常用正则表达式:匹配空行
*/
public final static String regExp_line = "\\n[\\s ? ]*\\r";
/**
* 常用正则表达式:匹配HTML标记
*/
public final static String regExp_html_1 = "/ <(.*)>.* <\\/\\1> ? <(.*) \\/>/";
/**
* 常用正则表达式:匹配首尾空格
*/
public final static String regExp_startEndEmpty = "(^\\s*) ?(\\s*$)";
/**
* 常用正则表达式:匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线)
*/
public final static String regExp_accountNumber = "^[a-zA-Z][a-zA-Z0-9_]{4,15}$";
/**
* 常用正则表达式:匹配国内电话号码,匹配形式如 0511-4405222 或 021-87888822
*/
public final static String regExp_telephone = "\\d{3}-\\d{8} ?\\d{4}-\\d{7}";
/**
* 常用正则表达式:匹配国内手机号码 11位数
*/
public final static String regExp_phone = "\\d{11}";
/**
* 常用正则表达式:腾讯QQ号, 腾讯QQ号从10000开始
*/
public final static String regExp_qq = "[1-9][0-9]{4,}";
/**
* 常用正则表达式:匹配中国邮政编码
*/
public final static String regExp_postbody = "[1-9]\\d{5}(?!\\d)";
/**
* 常用正则表达式:匹配身份证, 中国的身份证为15位或18位
*/
public final static String regExp_idCard = "\\d{15} ?\\d{18}";
/**
* 常用正则表达式:IP
*/
public final static String regExp_ip = "\\d+\\.\\d+\\.\\d+\\.\\d+";
/**
* 字符编码
*/
public final static String encoding = "UTF-8";
/**
* 验证字符串是否匹配指定正则表达式
* @param content
* @param regExp
* @return
*/
public static boolean regExpVali(String content, String regExp){
Pattern pattern = Pattern.compile(regExp);
Matcher matcher = pattern.matcher(content);
return matcher.matches();
}
/**
* Url Base64编码
*
* @param data 待编码数据
* @return String 编码数据
* @throws Exception
*/
public static String encode(String data) throws Exception {
// 执行编码
byte[] b = Base64.encodeBase64URLSafe(data.getBytes(encoding));
return new String(b, encoding);
}
/**
* Url Base64解码
*
* @param data
* 待解码数据
* @return String 解码数据
* @throws Exception
*/
public static String decode(String data) throws Exception {
// 执行解码
byte[] b = Base64.decodeBase64(data.getBytes(encoding));
return new String(b, encoding);
}
/**
* URL编码(utf-8)
*
* @param source
* @return
*/
public static String urlEncode(String source) {
String result = source;
try {
result = java.net.URLEncoder.encode(source, encoding);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
/**
* 根据内容类型判断文件扩展名
* @param contentType 内容类型
* @return
*/
public static String getFileExt(String contentType) {
String fileExt = "";
if ("image/jpeg".equals(contentType)){
fileExt = ".jpg";
} else if ("audio/mpeg".equals(contentType)){
fileExt = ".mp3";
} else if ("audio/amr".equals(contentType)){
fileExt = ".amr";
} else if ("video/mp4".equals(contentType)){
fileExt = ".mp4";
} else if ("video/mpeg4".equals(contentType)){
fileExt = ".mp4";
}
return fileExt;
}
/**
* 获取bean名称
* @param bean
* @return
*/
public static String beanName(Object bean) {
String fullClassName = bean.getClass().getName();
String classNameTemp = fullClassName.substring(fullClassName.lastIndexOf(".") + 1, fullClassName.length());
return classNameTemp.substring(0, 1) + classNameTemp.substring(1);
}
public final static Pattern referer_pattern = Pattern.compile("@([^@^\\s^:]{1,})([\\s\\:\\,\\;]{0,1})");//@.+?[\\s:]
/**
* 处理提到某人 @xxxx
* @param contents 传入的文本内容
* @param userReferers 传出被引用到的会员名单
* @return 返回带有链接的文本内容
*/
public static String userLinks(String contents, List<String> userReferers) {
StringBuilder html = new StringBuilder();
/* int lastIdx = 0;
Matcher matchr = referer_pattern.matcher(contents);
while (matchr.find()) {
String origion_str = matchr.group();
//System.out.println("-->"+origion_str);
String userName = origion_str.substring(1, origion_str.length()).trim();
//char ch = str.charAt(str.length()-1);
//if(ch == ':' || ch == ',' || ch == ';')
// str = str.substring(0, str.length()-1);
//System.out.println(str);
html.append(contents.substring(lastIdx, matchr.start()));
User user = null;
Object userObj = User.dao.cacheGet(userName);
if (null != userObj) {
user = (User) userObj;
} else {
Map<String, Object> param = new HashMap<String, Object>();
param.put("column", "username");
String sql = ToolSqlXml.getSql(User.sqlId_column, param, ConstantRender.sql_renderType_beetl);
List<User> userList = User.dao.find(sql, userName);
if (userList.size() == 1) {
user = userList.get(0);
}
}
if(user != null){
html.append("<a href='http://www.xx.com/"+user.getStr("username")+"' class='referer' target='_blank'>@");
html.append(userName.trim());
html.append("</a> ");
if(userReferers != null && !userReferers.contains(user.getPKValue())){
userReferers.add(user.getPKValue());
}
} else {
html.append(origion_str);
}
lastIdx = matchr.end();
//if(ch == ':' || ch == ',' || ch == ';')
// html.append(ch);
}
html.append(contents.substring(lastIdx));*/
return html.toString();
}
/**
* 首字母转小写
* @param s
* @return
*/
public static String toLowerCaseFirstOne(String s) {
if(Character.isLowerCase(s.charAt(0))){
return s;
} else {
return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
}
}
/**
* 首字母转大写
* @param s
* @return
*/
public static String toUpperCaseFirstOne(String s) {
if(Character.isUpperCase(s.charAt(0))){
return s;
} else {
return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
}
}
/**
*将list内容转换成以逗号分隔开的字符串
* @param list
* @return
*/
public static String idToSqlIn(List<?> list, boolean isString) {
if(list== null || list.isEmpty()) {
return "";
} else {
StringBuilder sb = new StringBuilder(list.size() * 35);
for(Object idTmp: list) {
if(sb.length()!= 0) {
sb.append(',');
}
if(isString) {
sb.append('\'').append(idTmp).append('\'');
} else {
sb.append(idTmp);
}
}
return sb.toString();
}
}
/**
*将list中对象中对应的propName,连接成以逗号分隔开的字符串
* @param list
* @return
*/
public static String idToSqlIn(List<?> list, String propName, boolean isString) {
if(list== null || list.isEmpty()) {
return "";
} else {
StringBuilder sb = new StringBuilder(list.size() * 35);
for(Object obj: list) {
if(sb.length()!= 0) {
sb.append(',');
}
if(isString) {
sb.append('\'').append(ReflectUtils.getValue(obj, propName)).append('\'');
} else {
sb.append(ReflectUtils.getValue(obj, propName));
}
}
return sb.toString();
}
}
}
| [
"[email protected]"
] | |
54587c6a3dde31e530d6eb0fae7076ff272926a9 | 96670d2b28a3fb75d2f8258f31fc23d370af8a03 | /reverse_engineered/sources/com/beastbikes/android/ble/ui/NavigationActivity.java | a9463cada9d034ccc1115a7b592c2770a76e6aaf | [] | no_license | P79N6A/speedx | 81a25b63e4f98948e7de2e4254390cab5612dcbd | 800b6158c7494b03f5c477a8cf2234139889578b | refs/heads/master | 2020-05-30T18:43:52.613448 | 2019-06-02T07:57:10 | 2019-06-02T08:15:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 32,696 | java | package com.beastbikes.android.ble.ui;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.Polyline;
import com.beastbikes.android.C1373R;
import com.beastbikes.android.ble.CentralService;
import com.beastbikes.android.ble.CentralService.C1596c;
import com.beastbikes.android.ble.biz.C1661h;
import com.beastbikes.android.ble.biz.C1662i;
import com.beastbikes.android.ble.dao.entity.BleDevice;
import com.beastbikes.android.ble.dto.C1667b;
import com.beastbikes.android.ble.dto.C1668c;
import com.beastbikes.android.ble.dto.C1669d;
import com.beastbikes.android.ble.dto.NavigationLocation;
import com.beastbikes.android.ble.ui.p098a.C1740p;
import com.beastbikes.android.ble.ui.widget.WayPointLinearLayout;
import com.beastbikes.android.ble.ui.widget.WayPointLinearLayout.C1687a;
import com.beastbikes.android.locale.C1849a;
import com.beastbikes.android.utils.C2558g;
import com.beastbikes.android.utils.p080a.C1454a;
import com.beastbikes.framework.ui.android.utils.Toasts;
import com.mapbox.mapboxsdk.MapboxAccountManager;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.services.commons.ServicesException;
import com.mapbox.services.commons.models.Position;
import com.mapbox.services.directions.v5.DirectionsCriteria;
import com.mapbox.services.directions.v5.MapboxDirections;
import com.mapbox.services.directions.v5.MapboxDirections.Builder;
import com.mapbox.services.directions.v5.models.DirectionsResponse;
import com.mapbox.services.directions.v5.models.DirectionsRoute;
import java.util.ArrayList;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
@TargetApi(18)
public class NavigationActivity extends NavigationBaseActivity implements C1687a {
/* renamed from: d */
private static final Logger f7615d = LoggerFactory.getLogger("NavigationActivity");
/* renamed from: e */
private TextView f7616e;
/* renamed from: f */
private TextView f7617f;
/* renamed from: g */
private Button f7618g;
/* renamed from: h */
private RelativeLayout f7619h;
/* renamed from: i */
private TextView f7620i;
/* renamed from: j */
private TextView f7621j;
/* renamed from: k */
private TextView f7622k;
/* renamed from: l */
private WayPointLinearLayout f7623l;
/* renamed from: m */
private LatLng f7624m;
/* renamed from: n */
private LatLng f7625n;
/* renamed from: o */
private SparseArray<LatLng> f7626o;
/* renamed from: p */
private C1668c f7627p;
/* renamed from: q */
private ArrayList<Position> f7628q;
/* renamed from: r */
private C1454a f7629r;
/* renamed from: s */
private BleDevice f7630s;
/* renamed from: t */
private C1662i f7631t;
/* renamed from: u */
private boolean f7632u = true;
/* renamed from: v */
private boolean f7633v = true;
/* renamed from: w */
private ServiceConnection f7634w = new C16845(this);
/* renamed from: com.beastbikes.android.ble.ui.NavigationActivity$2 */
class C16812 implements Callback<DirectionsResponse> {
/* renamed from: a */
final /* synthetic */ NavigationActivity f7597a;
C16812(NavigationActivity navigationActivity) {
this.f7597a = navigationActivity;
}
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
NavigationActivity.f7615d.error("Response code: " + response.code() + " message: " + response.message());
if (response.body() == null) {
NavigationActivity.f7615d.error("No routes found, make sure you set the right user and access token.");
Toasts.show(this.f7597a, this.f7597a.getString(C1373R.string.str_navigation_calcuate_route_failed_and_retry_later));
} else if (((DirectionsResponse) response.body()).getRoutes().size() < 1) {
NavigationActivity.f7615d.error("No routes found");
Toasts.show(this.f7597a, this.f7597a.getString(C1373R.string.str_navigation_calcuate_route_failed_and_retry_later));
} else {
DirectionsRoute directionsRoute = (DirectionsRoute) ((DirectionsResponse) response.body()).getRoutes().get(0);
if (directionsRoute == null) {
Toasts.show(this.f7597a, this.f7597a.getString(C1373R.string.str_navigation_calcuate_route_failed_and_retry_later));
return;
}
this.f7597a.m9116a(new C1668c(directionsRoute), false);
this.f7597a.m9106c();
}
}
public void onFailure(Call<DirectionsResponse> call, Throwable th) {
Toasts.show(this.f7597a, this.f7597a.getString(C1373R.string.str_navigation_calcuate_route_failed_and_retry_later));
this.f7597a.m9106c();
}
}
/* renamed from: com.beastbikes.android.ble.ui.NavigationActivity$4 */
class C16834 implements Runnable {
/* renamed from: a */
final /* synthetic */ NavigationActivity f7602a;
C16834(NavigationActivity navigationActivity) {
this.f7602a = navigationActivity;
}
public void run() {
Toasts.show(this.f7602a, this.f7602a.getString(C1373R.string.str_sync_success));
this.f7602a.finish();
}
}
/* renamed from: com.beastbikes.android.ble.ui.NavigationActivity$5 */
class C16845 implements ServiceConnection {
/* renamed from: a */
final /* synthetic */ NavigationActivity f7603a;
C16845(NavigationActivity navigationActivity) {
this.f7603a = navigationActivity;
}
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
NavigationActivity.f7615d.info("onServiceConnected");
CentralService a = ((C1596c) iBinder).m8563a();
this.f7603a.c = a.m8582b();
this.f7603a.c.mo3145a(this.f7603a);
}
public void onServiceDisconnected(ComponentName componentName) {
NavigationActivity.f7615d.info("onServiceDisconnected");
}
}
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
Intent intent = new Intent("com.beastbikes.android.ble.intent.action.CENTRAL_CONTROL");
intent.setPackage(getPackageName());
startService(intent);
bindService(intent, this.f7634w, 1);
}
/* renamed from: a */
protected void mo3201a(Bundle bundle) {
super.mo3201a(bundle);
if (getIntent() != null) {
this.f7630s = (BleDevice) getIntent().getSerializableExtra("extraBleDevice");
}
if (this.f7630s == null) {
Toasts.show((Context) this, getString(C1373R.string.str_ble_retry_after_connect_to_device));
finish();
return;
}
this.f7629r = C1454a.a();
m9127d();
this.a.setOnMapStatusChangeListener(this);
}
public void onClick(View view) {
super.onClick(view);
Intent intent;
switch (view.getId()) {
case C1373R.id.activity_navigation_tv_my_location:
intent = new Intent(this, SearchLocationActivity.class);
intent.putExtra("search_event_id", 6);
a(intent, 6);
return;
case C1373R.id.activity_navigation_tv_destination_location:
intent = new Intent(this, SearchLocationActivity.class);
intent.putExtra("search_event_id", 7);
a(intent, 7);
return;
case C1373R.id.btn_calculate_route:
if (this.f7632u) {
if (this.f7624m != null && this.f7625n != null) {
try {
m9118a(this.f7624m, this.f7625n, this.f7626o);
return;
} catch (ServicesException e) {
e.printStackTrace();
f7615d.error("getRoute error e: " + e);
return;
}
}
return;
} else if (this.f7629r.a(this, "show_disclaimer", false)) {
m9115a(this.f7627p, this.f7628q);
return;
} else {
startActivityForResult(new Intent(this, DisclaimerActivity.class), 90);
return;
}
case C1373R.id.tv_navigation_how_to_use_nav:
startActivity(new Intent(this, NavigationDescActivity.class));
return;
default:
return;
}
}
protected void onActivityResult(int i, int i2, Intent intent) {
if (i2 == -1 && i == 90) {
this.f7629r.a(this, "show_disclaimer", Boolean.valueOf(true)).apply();
m9115a(this.f7627p, this.f7628q);
}
}
/* renamed from: b */
protected void m9139b(int i, Object obj) {
switch (i) {
case 6:
m9121a(true, obj);
break;
case 7:
m9121a(false, obj);
break;
case 8:
m9120a(obj);
break;
}
if (this.f7624m == null || this.f7625n == null) {
this.f7618g.setBackground(ContextCompat.getDrawable(this, C1373R.drawable.bg_navigation_btn_gray));
} else {
this.f7618g.setBackground(ContextCompat.getDrawable(this, C1373R.drawable.bg_navigation_btn_black));
}
}
protected void onDestroy() {
super.onDestroy();
if (this.f7634w != null) {
unbindService(this.f7634w);
}
}
/* renamed from: a */
public void mo3200a(double d, double d2) {
}
/* renamed from: b */
public void mo3204b(double d, double d2) {
}
protected void a_(final NavigationLocation navigationLocation) {
runOnUiThread(new Runnable(this) {
/* renamed from: b */
final /* synthetic */ NavigationActivity f7596b;
public void run() {
if (this.f7596b.f7616e != null) {
this.f7596b.f7616e.setText(navigationLocation.getName());
this.f7596b.f7616e.setCompoundDrawablesWithIntrinsicBounds(C1373R.drawable.ic_select_location_my_location, 0, 0, 0);
this.f7596b.f7616e.setTextColor(Color.parseColor("#111111"));
this.f7596b.f7624m = new LatLng(navigationLocation.getLatitude(), navigationLocation.getLongitude());
this.f7596b.f7633v = true;
}
}
});
}
/* renamed from: c */
public void mo3205c(int i) {
Intent intent = new Intent(this, SearchLocationActivity.class);
intent.putExtra("search_event_id", 8);
intent.putExtra("way_point_position", i);
a(intent, 8);
}
/* renamed from: a */
public void mo3202a(NavigationLocation navigationLocation, int i) {
int i2 = 0;
if (this.f7626o != null && this.f7626o.size() > 0 && navigationLocation != null) {
int i3;
this.f7626o.remove(i);
ArrayList arrayList = new ArrayList();
int size = this.f7626o.size();
for (i3 = 0; i3 < size; i3++) {
LatLng latLng = (LatLng) this.f7626o.get(this.f7626o.keyAt(i3));
if (latLng != null) {
arrayList.add(latLng);
}
}
this.f7626o.clear();
Iterator it = arrayList.iterator();
while (it.hasNext()) {
i3 = i2 + 1;
this.f7626o.put(i2, (LatLng) it.next());
i2 = i3;
}
this.f7632u = true;
this.f7618g.setText(C1373R.string.str_navigation_calculate_route);
if (this.f7619h != null) {
this.f7619h.setVisibility(8);
}
m9131h();
m9129f();
}
}
/* renamed from: a */
public void mo3199a() {
this.f7623l.m9379a();
}
/* renamed from: a */
private void m9121a(boolean z, Object obj) {
NavigationLocation navigationLocation;
if (obj != null) {
navigationLocation = (NavigationLocation) ((Intent) obj).getSerializableExtra("mapboxlocation");
} else if (this.b == null) {
Toasts.show((Context) this, getString(C1373R.string.str_get_location_info_failed));
f7615d.error("获取位置信息失败");
return;
} else {
navigationLocation = this.b;
if (this.f7633v && !z) {
this.f7633v = false;
this.f7624m = null;
this.f7616e.setText(C1373R.string.str_navigation_select_start);
this.f7616e.setCompoundDrawablesWithIntrinsicBounds(C1373R.drawable.ic_select_location_my_location_gray, 0, 0, 0);
this.f7616e.setTextColor(Color.parseColor("#999999"));
}
if (!this.f7633v && z) {
this.f7633v = true;
this.f7625n = null;
this.f7617f.setText(C1373R.string.str_navigation_select_destination);
this.f7617f.setCompoundDrawablesWithIntrinsicBounds(C1373R.drawable.ic_select_location_destination_gray, 0, 0, 0);
this.f7617f.setTextColor(Color.parseColor("#999999"));
}
}
if (navigationLocation != null) {
if (C1849a.m9641a()) {
com.baidu.mapapi.model.LatLng g = C2558g.m12851g(navigationLocation.getLatitude(), navigationLocation.getLongitude());
this.a.m11658a(g.latitude, g.longitude);
} else {
com.google.android.gms.maps.model.LatLng a = C2558g.m12841a(navigationLocation.getLatitude(), navigationLocation.getLongitude());
this.a.m11658a(a.latitude, a.longitude);
}
if (z) {
this.f7624m = new LatLng(navigationLocation.getLatitude(), navigationLocation.getLongitude());
this.f7616e.setText(navigationLocation.getName());
this.f7616e.setCompoundDrawablesWithIntrinsicBounds(C1373R.drawable.ic_select_location_my_location, 0, 0, 0);
this.f7616e.setTextColor(Color.parseColor("#111111"));
f7615d.info("start: " + navigationLocation.getName());
} else {
this.f7625n = new LatLng(navigationLocation.getLatitude(), navigationLocation.getLongitude());
this.f7617f.setText(navigationLocation.getName());
this.f7617f.setCompoundDrawablesWithIntrinsicBounds(C1373R.drawable.ic_location_red, 0, 0, 0);
this.f7617f.setTextColor(Color.parseColor("#111111"));
f7615d.info("destination: " + navigationLocation.getName());
}
this.f7632u = true;
this.f7618g.setText(C1373R.string.str_navigation_calculate_route);
if (this.f7619h != null) {
this.f7619h.setVisibility(8);
}
m9129f();
m9131h();
}
}
/* renamed from: a */
private void m9120a(Object obj) {
if (obj != null) {
Intent intent = (Intent) obj;
NavigationLocation navigationLocation = (NavigationLocation) intent.getSerializableExtra("mapboxlocation");
int intExtra = intent.getIntExtra("way_point_position", -1);
if (navigationLocation != null && intExtra != -1) {
f7615d.info("wayPoint: position: " + intExtra + " location: " + navigationLocation);
if (this.f7626o == null) {
this.f7626o = new SparseArray(3);
}
this.f7626o.put(intExtra, new LatLng(navigationLocation.getLatitude(), navigationLocation.getLongitude()));
this.f7623l.m9381a(intExtra, navigationLocation);
m9129f();
if (C1849a.m9641a()) {
com.baidu.mapapi.model.LatLng g = C2558g.m12851g(navigationLocation.getLatitude(), navigationLocation.getLongitude());
this.a.m11658a(g.latitude, g.longitude);
} else {
com.google.android.gms.maps.model.LatLng a = C2558g.m12841a(navigationLocation.getLatitude(), navigationLocation.getLongitude());
this.a.m11658a(a.latitude, a.longitude);
}
this.f7632u = true;
this.f7618g.setText(C1373R.string.str_navigation_calculate_route);
if (this.f7619h != null) {
this.f7619h.setVisibility(8);
}
m9131h();
}
}
}
/* renamed from: d */
private void m9127d() {
((ViewStub) findViewById(C1373R.id.viewStub_before_select_location)).inflate();
this.f7616e = (TextView) findViewById(C1373R.id.activity_navigation_tv_my_location);
this.f7617f = (TextView) findViewById(C1373R.id.activity_navigation_tv_destination_location);
this.f7618g = (Button) findViewById(C1373R.id.btn_calculate_route);
TextView textView = (TextView) findViewById(C1373R.id.tv_navigation_how_to_use_nav);
this.f7623l = (WayPointLinearLayout) findViewById(C1373R.id.wayPointLinear);
this.f7616e.setOnClickListener(this);
this.f7617f.setOnClickListener(this);
this.f7618g.setOnClickListener(this);
textView.setOnClickListener(this);
this.f7623l.setOnClickWayPointListener(this);
}
/* renamed from: e */
private void m9128e() {
if (this.f7619h == null) {
((ViewStub) findViewById(C1373R.id.viewStub_route_info)).inflate();
this.f7619h = (RelativeLayout) findViewById(C1373R.id.relative_navigation_route_info);
this.f7620i = (TextView) findViewById(C1373R.id.activity_navigation_tv_distance);
this.f7621j = (TextView) findViewById(C1373R.id.activity_navigation_tv_distance_unit);
this.f7622k = (TextView) findViewById(C1373R.id.activity_navigation_tv_total_time);
}
this.f7619h.setVisibility(0);
}
/* renamed from: f */
private void m9129f() {
m9130g();
if (this.f7624m != null) {
this.a.m11667a(this.f7624m, (int) C1373R.drawable.ic_navigation_start_pos);
}
if (this.f7625n != null) {
this.a.m11667a(this.f7625n, (int) C1373R.drawable.ic_navigation_destination_pos);
}
if (this.f7626o != null) {
int size = this.f7626o.size();
for (int i = 0; i < size; i++) {
LatLng latLng = (LatLng) this.f7626o.get(this.f7626o.keyAt(i));
if (latLng != null) {
this.a.m11667a(latLng, (int) C1373R.drawable.ic_navigation_way_point_pos);
}
}
}
}
/* renamed from: g */
private void m9130g() {
if (this.a != null) {
boolean a = C1849a.m9641a();
ArrayList markers = this.a.getMarkers();
if (markers != null && !markers.isEmpty()) {
Iterator it = markers.iterator();
while (it.hasNext()) {
Object next = it.next();
if (a) {
((Marker) next).remove();
} else {
((com.google.android.gms.maps.model.Marker) next).remove();
}
}
}
}
}
/* renamed from: a */
private void m9118a(LatLng latLng, LatLng latLng2, SparseArray<LatLng> sparseArray) throws ServicesException {
if (latLng == null || latLng2 == null) {
f7615d.info("Origin or destination is null");
return;
}
if (this.f7628q == null) {
this.f7628q = new ArrayList();
}
this.f7628q.clear();
ArrayList arrayList = new ArrayList();
if (sparseArray != null && sparseArray.size() > 0) {
int size = sparseArray.size();
for (int i = 0; i < size; i++) {
LatLng latLng3 = (LatLng) sparseArray.get(sparseArray.keyAt(i));
if (latLng3 != null) {
this.f7628q.add(Position.fromCoordinates(latLng3.getLongitude(), latLng3.getLatitude()));
arrayList.add(latLng3);
}
}
}
f7615d.info("Way points size: " + this.f7628q.size());
if (C1849a.m9641a()) {
m9119a(latLng, latLng2, arrayList);
} else {
m9126b(latLng, latLng2, arrayList);
}
}
/* renamed from: a */
private void m9116a(C1668c c1668c, boolean z) {
m9125b(c1668c, z);
m9128e();
Iterator it = c1668c.m9050c().iterator();
double d = 0.0d;
double d2 = 0.0d;
while (it.hasNext()) {
C1667b c1667b = (C1667b) it.next();
d += c1667b.m9045a();
d2 = c1667b.m9046b() + d2;
}
if (d < 1000.0d) {
this.f7620i.setText(String.valueOf(d));
if (C1849a.m9645b((Context) this)) {
this.f7621j.setText(C1373R.string.metre);
} else {
d = C1849a.m9646c(d);
this.f7621j.setText("feet");
}
} else {
d /= 1000.0d;
if (C1849a.m9645b((Context) this)) {
this.f7621j.setText(C1373R.string.kilometre);
} else {
d = C1849a.m9638a(d);
this.f7621j.setText("mile");
}
}
this.f7620i.setText(String.format("%.1f", new Object[]{Double.valueOf(d)}));
f7615d.info("route total distance: " + d);
f7615d.info("route total time: " + d);
if (d2 < 3600.0d) {
this.f7622k.setText(getString(C1373R.string.str_approximately) + ((((long) d2) % 3600) / 60) + getString(C1373R.string.str_minute));
} else {
this.f7622k.setText(getString(C1373R.string.str_approximately) + (((long) d2) / 3600) + getString(C1373R.string.str_hour) + ((((long) d2) % 3600) / 60) + getString(C1373R.string.str_minute));
}
this.f7632u = false;
this.f7618g.setText(C1373R.string.str_navigation_async_to_central);
}
/* renamed from: b */
private void m9125b(C1668c c1668c, boolean z) {
if (c1668c == null) {
f7615d.info("method drawRoute NavigationRouteDTO is null");
return;
}
this.f7627p = c1668c;
ArrayList arrayList = new ArrayList();
Iterator it = c1668c.m9050c().iterator();
while (it.hasNext()) {
Iterator it2 = ((C1667b) it.next()).m9047c().iterator();
while (it2.hasNext()) {
arrayList.addAll(((C1669d) it2.next()).m9051a());
}
}
int size = arrayList.size();
LatLng[] latLngArr = new LatLng[size];
int i;
Position position;
if (z) {
for (i = 0; i < size; i++) {
position = (Position) arrayList.get(i);
latLngArr[i] = C2558g.m12850f(position.getLatitude(), position.getLongitude());
}
} else {
for (i = 0; i < size; i++) {
position = (Position) arrayList.get(i);
latLngArr[i] = new LatLng(position.getLatitude(), position.getLongitude());
}
}
this.f7624m = latLngArr[0];
this.f7625n = latLngArr[size - 1];
m9129f();
m9131h();
this.a.m11671a(latLngArr, 8, Color.parseColor("#ff584f"));
}
/* renamed from: h */
private void m9131h() {
boolean a = C1849a.m9641a();
ArrayList polylines = this.a.getPolylines();
if (polylines != null && !polylines.isEmpty()) {
Iterator it = polylines.iterator();
while (it.hasNext()) {
Object next = it.next();
if (a) {
((Polyline) next).remove();
} else {
((com.google.android.gms.maps.model.Polyline) next).remove();
}
}
}
}
/* renamed from: a */
private void m9115a(C1668c c1668c, ArrayList<Position> arrayList) {
if (c1668c != null) {
if (m9132i()) {
FragmentTransaction beginTransaction = getFragmentManager().beginTransaction();
Fragment findFragmentByTag = getFragmentManager().findFragmentByTag("SYNC_DATA");
if (findFragmentByTag != null) {
beginTransaction.remove(findFragmentByTag);
return;
}
findFragmentByTag = new C1740p();
Bundle bundle = new Bundle();
bundle.putInt("sync_type", 3);
bundle.putString("central_id", this.f7630s.getMacAddress());
findFragmentByTag.m9298a(this.c);
findFragmentByTag.setArguments(bundle);
if (this.c == null) {
f7615d.error("mManager is null");
return;
} else if (1 == this.c.mo3134a(16, "1.0.1", c1668c, arrayList)) {
Toasts.show((Context) this, getString(C1373R.string.str_navigation_route_is_too_long));
return;
} else {
beginTransaction.add(findFragmentByTag, "SYNC_DATA").commitAllowingStateLoss();
return;
}
}
Toasts.show((Context) this, getString(C1373R.string.str_ble_retry_after_connect_to_device));
}
}
/* renamed from: i */
private boolean m9132i() {
return C1661h.m8999a().m9004b() != null;
}
/* renamed from: a */
private void m9119a(LatLng latLng, LatLng latLng2, ArrayList<LatLng> arrayList) throws ServicesException {
f7615d.info("使用 Mapbox Direction服务进行路线规划, 起点 = " + latLng.toString() + ", 终点:" + latLng2.toString() + ", 途经点数: " + arrayList);
Builder builder = new Builder();
if (!(arrayList == null || arrayList.isEmpty())) {
ArrayList arrayList2 = new ArrayList();
Iterator it = arrayList.iterator();
while (it.hasNext()) {
LatLng latLng3 = (LatLng) it.next();
arrayList2.add(Position.fromCoordinates(latLng3.getLongitude(), latLng3.getLatitude()));
}
builder.setCoordinates(arrayList2);
}
MapboxDirections build = builder.setOrigin(Position.fromCoordinates(latLng.getLongitude(), latLng.getLatitude())).setDestination(Position.fromCoordinates(latLng2.getLongitude(), latLng2.getLatitude())).setProfile(DirectionsCriteria.PROFILE_CYCLING).setAccessToken(MapboxAccountManager.getInstance().getAccessToken()).setSteps(Boolean.valueOf(true)).build();
m9103a(true, getString(C1373R.string.str_loading));
build.enqueueCall(new C16812(this));
}
/* renamed from: b */
private void m9126b(final LatLng latLng, final LatLng latLng2, final ArrayList<LatLng> arrayList) {
f7615d.info("使用Google Map Direction服务进行路线规划, 起点 = " + latLng.toString() + ", 终点:" + latLng2.toString() + ", 途经点数: " + arrayList);
if (this.f7631t == null) {
this.f7631t = new C1662i(this);
}
getAsyncTaskQueue().m13740a(new AsyncTask<Void, Void, C1668c>(this) {
/* renamed from: d */
final /* synthetic */ NavigationActivity f7601d;
protected /* synthetic */ Object doInBackground(Object[] objArr) {
return m9091a((Void[]) objArr);
}
protected /* synthetic */ void onPostExecute(Object obj) {
m9092a((C1668c) obj);
}
protected void onPreExecute() {
this.f7601d.m9103a(true, this.f7601d.getString(C1373R.string.str_loading));
}
/* renamed from: a */
protected C1668c m9091a(Void... voidArr) {
Exception exception;
C1668c c1668c;
com.google.android.gms.maps.model.LatLng a = C2558g.m12841a(latLng.getLatitude(), latLng.getLongitude());
com.google.android.gms.maps.model.LatLng a2 = C2558g.m12841a(latLng2.getLatitude(), latLng2.getLongitude());
String a3 = this.f7601d.m9114a(a);
String a4 = this.f7601d.m9114a(a2);
String str = "";
if (arrayList == null || arrayList.size() <= 0) {
NavigationActivity.f7615d.info("Way points is null or empty");
} else {
NavigationActivity.f7615d.info("Way points size: " + arrayList.size());
StringBuilder stringBuilder = new StringBuilder();
Iterator it = arrayList.iterator();
while (it.hasNext()) {
LatLng latLng = (LatLng) it.next();
stringBuilder.append(this.f7601d.m9114a(C2558g.m12841a(latLng.getLatitude(), latLng.getLongitude())));
stringBuilder.append("|");
}
str = stringBuilder.substring(0, stringBuilder.length() - 1);
}
C1668c c1668c2 = null;
try {
c1668c2 = this.f7601d.f7631t.m9013a("bicycling", a3, a4, str, "");
try {
if (!TextUtils.equals(c1668c2.m9049b(), "ZERO_RESULTS")) {
return c1668c2;
}
NavigationActivity.f7615d.info("Get direction with bicycling failed, and try with driving");
return this.f7601d.f7631t.m9013a(DirectionsCriteria.PROFILE_DRIVING, a3, a4, str, "tolls|highways|ferries");
} catch (Exception e) {
exception = e;
c1668c = c1668c2;
exception.printStackTrace();
return c1668c;
}
} catch (Exception e2) {
exception = e2;
c1668c = c1668c2;
exception.printStackTrace();
return c1668c;
}
}
/* renamed from: a */
protected void m9092a(C1668c c1668c) {
this.f7601d.m9106c();
if (c1668c == null || c1668c.m9050c() == null) {
Toasts.show(this.f7601d, this.f7601d.getString(C1373R.string.str_navigation_calcuate_route_failed_and_retry_later));
NavigationActivity.f7615d.error("Calculate route failed with NavigationRouteDTO is null");
return;
}
if (TextUtils.equals(c1668c.m9048a(), DirectionsCriteria.PROFILE_DRIVING)) {
Toasts.show(this.f7601d, this.f7601d.getString(C1373R.string.str_navigation_change_to_driving_modes_decs));
}
this.f7601d.m9116a(c1668c, true);
NavigationActivity.f7615d.info("NavigationRouteDTO", c1668c);
}
}, new Void[0]);
}
/* renamed from: a */
private String m9114a(com.google.android.gms.maps.model.LatLng latLng) {
if (latLng == null) {
return "";
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(latLng.latitude);
stringBuilder.append(",");
stringBuilder.append(latLng.longitude);
return stringBuilder.toString();
}
/* renamed from: b */
public void mo3197b(int i) {
runOnUiThread(new C16834(this));
}
}
| [
"Gith1974"
] | Gith1974 |
9ee95dba9d1571c014cfaf95cb1dd3f850d55992 | c37ef54d151f8e70b6d521575f0b3b300b55525c | /api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/core/audit/AuditCouchbaseProperties.java | 6e55c329b057146e219a0dc86e61d0781e100f33 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | viswatejan/cas | f29c02f4b4ccfe73800012439f06dfdf9e2bffcc | 671ffd44cd8ebee06c3815502b73cbd56fa46b5b | refs/heads/master | 2020-03-22T18:27:33.912304 | 2018-07-10T19:36:28 | 2018-07-10T19:36:28 | 140,461,569 | 0 | 0 | Apache-2.0 | 2018-07-10T16:42:51 | 2018-07-10T16:42:50 | null | UTF-8 | Java | false | false | 677 | java | package org.apereo.cas.configuration.model.core.audit;
import lombok.Getter;
import lombok.Setter;
import org.apereo.cas.configuration.model.support.couchbase.BaseCouchbaseProperties;
import org.apereo.cas.configuration.support.RequiresModule;
/**
* This is {@link AuditCouchbaseProperties}.
*
* @author Misagh Moayyed
* @since 6.0.0
*/
@RequiresModule(name = "cas-server-support-audit-couchbase")
@Getter
@Setter
public class AuditCouchbaseProperties extends BaseCouchbaseProperties {
private static final long serialVersionUID = 580545095591694L;
/**
* Whether audit records should be executed asynchronously.
*/
private boolean asynchronous;
}
| [
"[email protected]"
] | |
55386ccdc0bbd8fccf5ab80195ea0317b0b497cb | 39853dddb26625d8bac7f99f45e689795e38f00d | /src/com/rockchip/itvbox/service/impl/WeatherIcon.java | 95e00166af03a73884de272218cf2189a7805343 | [] | no_license | doniexun/ITVLanucher | 1b8b6ef2a7f30341c97a71ce27dc32bc05e39ba2 | 3a679f1b134bb03ea687b9cf2018fc1c811110a3 | refs/heads/master | 2020-05-05T11:11:48.562777 | 2016-09-03T15:15:20 | 2016-09-03T15:15:20 | null | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 2,974 | java | /*******************************************************************
* Company: Fuzhou Rockchip Electronics Co., Ltd
* Description:
* @author: [email protected]
* Create at: 2014年3月27日 下午2:01:16
*
* Modification History:
* Date Author Version Description
* ------------------------------------------------------------------
* 2014年3月27日 fxw 1.0 create
*******************************************************************/
package com.rockchip.itvbox.service.impl;
import com.rockchip.itvbox.R;
public class WeatherIcon {
public static int[] getIconsByWeatherInfo(String weather) {
String[] strs = weather.split("转|到");
int[] resIds = new int[strs.length];
for (int i = 0; i < strs.length; i++) {
resIds[i] = getIconBySplitWeather(strs[i]);
}
if (resIds.length == 3) {
if (resIds[0] == 0) {
int[] newResids = new int[2];
newResids[0] = resIds[1];
newResids[1] = resIds[2];
resIds = newResids;
}
} else if (resIds.length == 1) {
int[] newResids = new int[2];
newResids[0] = resIds[0];
newResids[1] = 0;
resIds = newResids;
}
return resIds;
}
private static int getIconBySplitWeather(String weather) {
if (weather.equals("阴")) {
return R.drawable.ic_weather_cloudy_l;
} else if (weather.equals("多云")) {
return R.drawable.ic_weather_partly_cloudy_l;
} else if (weather.equals("晴")) {
return R.drawable.ic_weather_clear_day_l;
} else if (weather.equals("小雨")) {
return R.drawable.ic_weather_chance_of_rain_l;
} else if (weather.equals("中雨")) {
return R.drawable.ic_weather_rain_xl;
} else if (weather.equals("大雨")) {
return R.drawable.ic_weather_heavy_rain_l;
} else if (weather.equals("暴雨")) {
return R.drawable.ic_weather_heavy_rain_l;
} else if (weather.equals("大暴雨")) {
return R.drawable.ic_weather_heavy_rain_l;
} else if (weather.equals("特大暴雨")) {
return R.drawable.ic_weather_heavy_rain_l;
} else if (weather.equals("阵雨")) {
return R.drawable.ic_weather_chance_storm_l;
} else if (weather.equals("雷阵雨")) {
return R.drawable.ic_weather_thunderstorm_l;
} else if (weather.equals("小雪")) {
return R.drawable.ic_weather_chance_snow_l;
} else if (weather.equals("中雪")) {
return R.drawable.ic_weather_flurries_l;
} else if (weather.equals("大雪")) {
return R.drawable.ic_weather_snow_l;
} else if (weather.equals("暴雪")) {
return R.drawable.ic_weather_snow_l;
} else if (weather.equals("冰雹")) {
return R.drawable.ic_weather_icy_sleet_l;
} else if (weather.equals("雨夹雪")) {
return R.drawable.ic_weather_icy_sleet_l;
} else if (weather.equals("风")) {
return R.drawable.ic_weather_windy_l;
} else if (weather.equals("龙卷风")) {
return R.drawable.ic_weather_windy_l;
} else if (weather.equals("雾")) {
return R.drawable.ic_weather_fog_l;
}
return 0;
}
}
| [
"[email protected]"
] | |
2f18c176e67d1f0f6cd217047d215df12c93dfae | e75be673baeeddee986ece49ef6e1c718a8e7a5d | /submissions/blizzard/Corpus/ecf/390.java | d4dbd15952572dfbd177e73fa1b94b86ebfa93c1 | [
"MIT"
] | permissive | zhendong2050/fse18 | edbea132be9122b57e272a20c20fae2bb949e63e | f0f016140489961c9e3c2e837577f698c2d4cf44 | refs/heads/master | 2020-12-21T11:31:53.800358 | 2018-07-23T10:10:57 | 2018-07-23T10:10:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,556 | java | /*
* $HeadURL: https://svn.apache.org/repos/asf/jakarta/commons/proper/httpclient/branches/HTTPCLIENT_3_0_BRANCH/src/test/org/apache/commons/httpclient/TestAll.java $
* $Revision: 1.1 $
* $Date: 2009/02/13 18:07:49 $
* ====================================================================
*
* Copyright 1999-2004 The Apache Software Foundation
*
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.httpclient;
import org.apache.commons.httpclient.auth.TestAuthAll;
import org.apache.commons.httpclient.cookie.TestCookieAll;
import org.apache.commons.httpclient.params.TestParamsAll;
import junit.framework.*;
/**
* @author Remy Maucherat
* @author Rodney Waldhoff
* @version $Id: TestAll.java,v 1.1 2009/02/13 18:07:49 slewis Exp $
*/
public class TestAll extends TestCase {
public TestAll(String testName) {
super(testName);
}
public static Test suite() {
TestSuite suite = new TestSuite();
// Fundamentals
suite.addTest(TestHttpMethodFundamentals.suite());
suite.addTest(TestHttpStatus.suite());
suite.addTest(TestStatusLine.suite());
suite.addTest(TestRequestLine.suite());
suite.addTest(TestHeader.suite());
suite.addTest(TestHeaderElement.suite());
suite.addTest(TestHeaderOps.suite());
suite.addTest(TestResponseHeaders.suite());
suite.addTest(TestRequestHeaders.suite());
suite.addTest(TestStreams.suite());
suite.addTest(TestParameterParser.suite());
suite.addTest(TestParameterFormatter.suite());
suite.addTest(TestNVP.suite());
suite.addTest(TestMethodCharEncoding.suite());
suite.addTest(TestHttpVersion.suite());
suite.addTest(TestEffectiveHttpVersion.suite());
suite.addTest(TestHttpParser.suite());
suite.addTest(TestBadContentLength.suite());
suite.addTest(TestEquals.suite());
suite.addTest(TestQueryParameters.suite());
// Exceptions
suite.addTest(TestExceptions.suite());
// HTTP state management
suite.addTest(TestHttpState.suite());
suite.addTest(TestCookieAll.suite());
// Authentication
suite.addTest(TestCredentials.suite());
suite.addTest(TestAuthAll.suite());
// Redirects
suite.addTest(TestRedirects.suite());
// Connection management
suite.addTest(TestHttpConnection.suite());
suite.addTest(TestHttpConnectionManager.suite());
suite.addTest(TestConnectionPersistence.suite());
suite.addTest(TestIdleConnectionTimeout.suite());
suite.addTest(TestMethodAbort.suite());
// Preferences
suite.addTest(TestParamsAll.suite());
suite.addTest(TestVirtualHost.suite());
suite.addTest(TestHostConfiguration.suite());
// URIs
suite.addTest(TestURI.suite());
suite.addTest(TestURIUtil.suite());
suite.addTest(TestURIUtil2.suite());
// Method specific
suite.addTest(TestEntityEnclosingMethod.suite());
suite.addTest(TestPostParameterEncoding.suite());
suite.addTest(TestPostMethod.suite());
suite.addTest(TestPartsNoHost.suite());
suite.addTest(TestMultipartPost.suite());
// Non compliant behaviour
suite.addTest(TestNoncompliant.suite());
// Proxy
suite.addTest(TestProxy.suite());
suite.addTest(TestProxyWithRedirect.suite());
return suite;
}
public static void main(String args[]) {
String[] testCaseName = { TestAll.class.getName() };
junit.textui.TestRunner.main(testCaseName);
}
}
| [
"[email protected]"
] | |
4d61ebf4fe1e3086467f93fb322d0fa75e6e0913 | 7dc6bf17c5acc4a5755063a3ffc0c86f4b6ad8c3 | /java_decompiled_from_smali/com/google/ads/doubleclick/a.java | 10e6b7402e0dfdbb3ef9d318e17d662b5aace76b | [] | no_license | alecsandrudaj/mobileapp | 183dd6dc5c2fe8ab3aa1f21495d4221e6f304965 | b1b4ad337ec36ffb125df8aa1d04c759c33c418a | refs/heads/master | 2023-02-19T18:07:50.922596 | 2021-01-07T15:30:44 | 2021-01-07T15:30:44 | 300,325,195 | 0 | 0 | null | 2020-11-19T13:26:25 | 2020-10-01T15:18:57 | Smali | UTF-8 | Java | false | false | 268 | java | package com.google.ads.doubleclick;
public class a extends com.google.ads.b.a.a {
private String a;
public String a() {
return this.a;
}
/* renamed from: b */
public a c() {
super.c();
return this;
}
}
| [
"[email protected]"
] | |
d977ed3a0df54476f91ca9905aa914896a47643d | cc511ceb3194cfdd51f591e50e52385ba46a91b3 | /example/source_code/jackrabbit/jackrabbit-jcr-tests/src/main/java/org/apache/jackrabbit/test/ISO8601.java | c4499390aacddeeef6545dee207cdc62487cc92a | [] | no_license | huox-lamda/testing_hw | a86cdce8d92983e31e653dd460abf38b94a647e4 | d41642c1e3ffa298684ec6f0196f2094527793c3 | refs/heads/master | 2020-04-16T19:24:49.643149 | 2019-01-16T15:47:13 | 2019-01-16T15:47:13 | 165,858,365 | 3 | 3 | null | null | null | null | UTF-8 | Java | false | false | 5,068 | java | org apach jackrabbit test
java util calendar
java util gregorian calendar gregoriancalendar
java util time zone timezon
code iso8601 code util class helper method
deal date time format specif iso8601 compliant
format href http www org note datetim iso
support format
pre
plusmn yyyi ddthh ssstzd
pre
pre
plusmn yyyi digit year option sign valu
denot year bce valu denot year
denot year bce denot year bce
denot year
digit month januari
digit dai month
digit hour allow
digit minut
digit
sss digit millisecond
tzd time zone design zulu utc offset utc
form
pre
iso8601
pars iso8601 compliant date time string
param text date time string pars
return code calendar code code null code input
pars
throw illegalargumentexcept code null code argument pass
calendar pars string text
text
illeg argument except illegalargumentexcept argument null
check option lead sign
sign
start
text start startswith
sign
start
text start startswith
sign
start
sign sign sign impli
start
expect format remaind string
yyyi ddthh ssstzd
note java text simpledateformat
pars handl year tzd'
year month dai hour min sec
string tzid
year yyyi
year integ pars int parseint text substr start start
start
delimit
text char charat start
start
month
month integ pars int parseint text substr start start
start
delimit
text char charat start
start
dai
dai integ pars int parseint text substr start start
start
delimit 't'
text char charat start
start
hour
hour integ pars int parseint text substr start start
start
delimit
text char charat start
start
minut
min integ pars int parseint text substr start start
start
delimit
text char charat start
start
sec integ pars int parseint text substr start start
start
delimit
text char charat start
start
millisecond sss
integ pars int parseint text substr start start
start
time zone design
text char charat start text char charat start
offset utc format
tzid gmt text substr start
text substr start equal
tzid gmt
invalid time zone design
index bound except indexoutofboundsexcept
number format except numberformatexcept
time zone timezon time zone timezon time zone gettimezon tzid
verifi return time zone gettimezon default gmt
getid equal tzid
invalid time zone
initi calendar object
calendar cal calendar instanc getinst
cal set lenient setleni
year era
sign year
set era bce adjust year
cal set calendar year year
cal set calendar era gregorian calendar gregoriancalendar
cal set calendar year year
cal set calendar era gregorian calendar gregoriancalendar
month base
cal set calendar month month
dai month
cal set calendar dai month dai month dai
hour
cal set calendar hour dai hour dai hour
minut
cal set calendar minut min
cal set calendar sec
millisecond
cal set calendar millisecond
call trigger illegalargumentexcept
set valu illeg rang
cal time gettim
addit check valid year
year getyear cal
illeg argument except illegalargumentexcept
cal
format code calendar code iso8601 compliant
date time string
param cal time format date time string
return format date time string
throw illegalargumentexcept code null code argument pass
calendar repres defin iso year
digit
string format calendar cal illeg argument except illegalargumentexcept
cal
illeg argument except illegalargumentexcept argument null
format date time string
yyyi ddthh ssstzd
note java text simpledateformat
format handl year tzd'
string buffer stringbuff buf string buffer stringbuff
year yyyi
append pad int appendzeropaddedint buf year getyear cal
buf append
month
append pad int appendzeropaddedint buf cal calendar month
buf append
dai
append pad int appendzeropaddedint buf cal calendar dai month dai month
buf append
hour
append pad int appendzeropaddedint buf cal calendar hour dai hour dai
buf append
minut
append pad int appendzeropaddedint buf cal calendar minut
buf append
append pad int appendzeropaddedint buf cal calendar
buf append
millisecond sss
append pad int appendzeropaddedint buf cal calendar millisecond
time zone design
time zone timezon cal time zone gettimezon
determin offset timezon utc incl daylight save
offset offset getoffset cal time milli gettimeinmilli
offset
hour math ab offset
minut math ab offset
buf append offset
append pad int appendzeropaddedint buf hour
buf append
append pad int appendzeropaddedint buf minut
buf append
buf string tostr
return astronom year calendar
param cal calendar instanc
return astronom year
throw illegalargumentexcept calendar repres
defin iso year
digit
year getyear calendar cal illeg argument except illegalargumentexcept
determin era adjust year
year cal calendar year
cal set isset calendar era
cal calendar era gregorian calendar gregoriancalendar
calcul year astronom system
year bce astronom year
year year
year year
illeg argument except illegalargumentexcept calendar
year digit format iso8601 year
year
append pad number string buffer
intern helper method perform
valid argument
param buf string buffer append
param number append
param precis number digit append
append pad int appendzeropaddedint string buffer stringbuff buf precis
buf append
exp precis exp exp
math pow exp
buf append
buf append
| [
"[email protected]"
] | |
79a77cf28d05ad06db3bfdb2fac3040d211e567e | f333d697be409c778d6d4739bcca4f1500ac4405 | /Rainbow-S2S-Sample-JavaEchoBot/botloader/node_modules/rainbow-s2s-starterkit-nodejs/tests/java/BotSample/rainbow_authent_portal/src/main/java/com/ale/rainbow/s2s/client/auth/models/GetApiRainbowPingSuccess.java | 0a72c0c61494ef628bdf2be57ae9cb9087433e85 | [
"MIT"
] | permissive | Rainbow-CPaaS/Rainbow-S2S-Samples | 9ec0b52caa7d22512d4be7e769d84d0e83f5603e | 733f80e4c34498441ca3cbc7b2530d8f885277cc | refs/heads/master | 2023-01-27T12:59:50.683207 | 2020-03-18T16:35:49 | 2020-03-18T16:35:49 | 222,710,441 | 1 | 3 | NOASSERTION | 2023-01-24T01:39:28 | 2019-11-19T14:06:45 | Java | UTF-8 | Java | false | false | 4,252 | java | /*
* Rainbow authentication portal
* # Rainbow authentication portal API guide ## Preamble [Download Postman collection][0] ### Introduction This guide describes list of API services that are provided by OT Rainbow authentication portal system. Services are used to manage OT Rainbow authentication. ### Protocol REST interface is used for sending/receiving OT rainbow API messages. HTTP request GET is used. Standard HTTP responses are used to provide requested information or error status. There is no session notion in OT Rainbow system, so requests could be issued according stateless model, without transport conservation between them. JSON is used as a main format for data encoding in message body part. Each request is started with the following pattern /{module}/{version}/ where {module} is a portal module name to address and {version} is a version of used API, par example, “v1.0”. ### Security considerations Each request should contain some credential information to authenticate itself. Standard HTTP authentication with basic/bearer modes is used. JSON Web Token mechanism is used to provide authentication information. JWT has a expire timeout that is controlled by OT Rainbow portal to prevent very long token usage. Also authentication with application token is used. The token must be provided in the request HTTP header, using a custom header: APIKey. At server side, token is verified, and if it doesn’t match, 403 Not Allowed response is sent. TLS is used as a transport protocol to support message exchanges between OT Rainbow portal and an application. [0]: AuthenticationPortalServer_postman.json
*
* The version of the OpenAPI document: 1.104.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.ale.rainbow.s2s.client.auth.models;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.io.Serializable;
/**
* GetApiRainbowPingSuccess
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-02-13T18:40:41.602485+01:00[Europe/Paris]")
public class GetApiRainbowPingSuccess implements Serializable {
private static final long serialVersionUID = 1L;
public static final String SERIALIZED_NAME_STATUS = "status";
@SerializedName(SERIALIZED_NAME_STATUS)
private String status;
public GetApiRainbowPingSuccess status(String status) {
this.status = status;
return this;
}
/**
* State of authentication portal server <br/> <code>OK</code> if server status is good
* @return status
**/
@ApiModelProperty(required = true, value = "State of authentication portal server <br/> <code>OK</code> if server status is good")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GetApiRainbowPingSuccess getApiRainbowPingSuccess = (GetApiRainbowPingSuccess) o;
return Objects.equals(this.status, getApiRainbowPingSuccess.status);
}
@Override
public int hashCode() {
return Objects.hash(status);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class GetApiRainbowPingSuccess {\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| [
"[email protected]"
] | |
c1b60c48c76c9d0a2c73ee842a56f78bfea09236 | 2422a44995b77fe292d714dddd065c155ceb21a8 | /ec-provider/src/main/java/com/moriaty/bean/db/Attach.java | 599dc28e7a0c4857930ee53cbcf7bc2907b35662 | [] | no_license | Mor1aty/ElectricChamberlain | 0b6aa1c1bee6d33d248cd17b8d638254d0810d01 | b5cf569e3fd103d60d98d7454ec72725108c7b29 | refs/heads/master | 2022-06-21T09:40:33.971663 | 2020-05-20T04:50:25 | 2020-05-20T04:50:25 | 246,566,680 | 0 | 0 | null | 2022-06-17T03:00:07 | 2020-03-11T12:36:29 | Java | UTF-8 | Java | false | false | 345 | java | package com.moriaty.bean.db;
import lombok.Data;
/**
* @author 16计算机 Moriaty
* @version 1.0
* @copyright :Moriaty 版权所有 © 2019
* @date 2020/3/11 22:49
* @Description TODO
* 附件表
*/
@Data
public class Attach {
private long id;
private int type;
private String fileLocation;
private String context;
}
| [
"[email protected]"
] | |
b17897ae629920d7dfc2535cbed743228f8107aa | 0b0cc171457f32b5259ac2e0891d617abdfc0e47 | /src/org/lwjgl/util/mapped/CacheLineSize.java | ef96b5c5b02dab1fa283417db0af1cc52543917b | [] | no_license | bobolicener/star-rod | 24b403447b4bd82af1bca734c63ac38785748824 | 59235901ab024c5af267daebf92344b20538251a | refs/heads/master | 2020-07-01T20:12:10.960817 | 2019-08-08T14:54:46 | 2019-08-08T14:54:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,020 | java | package org.lwjgl.util.mapped;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.MemoryUtil;
import sun.misc.Unsafe;
final class CacheLineSize
{
private CacheLineSize() {}
static int getCacheLineSize()
{
int THREADS = 2;
int REPEATS = 200000;
int LOCAL_REPEATS = 100000;
int MAX_SIZE = LWJGLUtil.getPrivilegedInteger("org.lwjgl.util.mapped.CacheLineMaxSize", 1024).intValue() / 4;
double TIME_THRESHOLD = 1.0D + LWJGLUtil.getPrivilegedInteger("org.lwjgl.util.mapped.CacheLineTimeThreshold", 50).intValue() / 100.0D;
ExecutorService executorService = Executors.newFixedThreadPool(2);
ExecutorCompletionService<Long> completionService = new ExecutorCompletionService(executorService);
try
{
IntBuffer memory = getMemory(MAX_SIZE);
int WARMUP = 10;
for (int i = 0; i < 10; i++) {
doTest(2, 100000, 0, memory, completionService);
}
long totalTime = 0L;
int count = 0;
int cacheLineSize = 64;
boolean found = false;
for (int i = MAX_SIZE; i >= 1; i >>= 1) {
long time = doTest(2, 100000, i, memory, completionService);
if (totalTime > 0L) {
long avgTime = totalTime / count;
if (time / avgTime > TIME_THRESHOLD) {
cacheLineSize = (i << 1) * 4;
found = true;
break;
}
}
totalTime += time;
count++;
}
if (LWJGLUtil.DEBUG) {
if (found) {
LWJGLUtil.log("Cache line size detected: " + cacheLineSize + " bytes");
} else {
LWJGLUtil.log("Failed to detect cache line size, assuming " + cacheLineSize + " bytes");
}
}
return cacheLineSize;
} finally {
executorService.shutdown();
}
}
public static void main(String[] args) {
CacheUtil.getCacheLineSize();
}
static long memoryLoop(int index, int repeats, IntBuffer memory, int padding) {
long address = MemoryUtil.getAddress(memory) + index * padding * 4;
long time = System.nanoTime();
for (int i = 0; i < repeats; i++)
{
MappedHelper.ivput(MappedHelper.ivget(address) + 1, address);
}
return System.nanoTime() - time;
}
private static IntBuffer getMemory(int START_SIZE) {
int PAGE_SIZE = MappedObjectUnsafe.INSTANCE.pageSize();
ByteBuffer buffer = ByteBuffer.allocateDirect(START_SIZE * 4 + PAGE_SIZE).order(ByteOrder.nativeOrder());
if (MemoryUtil.getAddress(buffer) % PAGE_SIZE != 0L)
{
buffer.position(PAGE_SIZE - (int)(MemoryUtil.getAddress(buffer) & PAGE_SIZE - 1));
}
return buffer.asIntBuffer();
}
private static long doTest(int threads, int repeats, int padding, IntBuffer memory, ExecutorCompletionService<Long> completionService) {
for (int i = 0; i < threads; i++)
submitTest(completionService, i, repeats, memory, padding);
return waitForResults(threads, completionService);
}
private static void submitTest(ExecutorCompletionService<Long> completionService, int index, final int repeats, final IntBuffer memory, final int padding) {
completionService.submit(new Callable() {
public Long call() throws Exception {
return Long.valueOf(CacheLineSize.memoryLoop(val$index, repeats, memory, padding));
}
});
}
private static long waitForResults(int count, ExecutorCompletionService<Long> completionService) {
try {
long totalTime = 0L;
for (int i = 0; i < count; i++)
totalTime += ((Long)completionService.take().get()).longValue();
return totalTime;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| [
"[email protected]"
] | |
4c68bf6a3ba56dd37d00e1507b3df0659f6037a5 | 1ebd71e2179be8a2baec90ff3f326a3f19b03a54 | /hybris/bin/modules/cds-integration/profileservices/src/com/hybris/yprofile/common/Utils.java | e8a52376b8f6435b8e4c3e593aace4862eaa62f1 | [] | no_license | shaikshakeeb785/hybrisNew | c753ac45c6ae264373e8224842dfc2c40a397eb9 | 228100b58d788d6f3203333058fd4e358621aba1 | refs/heads/master | 2023-08-15T06:31:59.469432 | 2021-09-03T09:02:04 | 2021-09-03T09:02:04 | 402,680,399 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,938 | java | /*
* Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved.
*/
package com.hybris.yprofile.common;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.hybris.yprofile.consent.cookie.EnhancedCookieGenerator;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.util.WebUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class Utils {
private static final Logger LOG = Logger.getLogger(Utils.class);
private static final Map<String, String> SITE_ID_MAP = new HashMap<String, String>();
static {
SITE_ID_MAP.put("1", "electronics");
SITE_ID_MAP.put("2", "apparel-de");
SITE_ID_MAP.put("3", "apparel-uk");
}
private Utils() {
//Default private constructor
}
public static String formatDouble(Double d){
if(d == null){
return "";
}
final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
decimalFormatSymbols.setDecimalSeparator('.');
decimalFormatSymbols.setGroupingSeparator(',');
final DecimalFormat decimalFormat = new DecimalFormat("#,##0.00", decimalFormatSymbols);
return decimalFormat.format(d);
}
public static String formatDate(Date d){
final DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
return df2.format(d);
}
public static String remapSiteId(String siteId) {
final String result = SITE_ID_MAP.get(siteId);
if (StringUtils.isNotBlank(result)) {
return result;
}
return siteId;
}
public static Optional<String> getHeader(final HttpServletRequest request, final String headerName) {
if (request == null) {
return Optional.empty();
}
return Optional.ofNullable(request.getHeader(headerName));
}
public static Optional<Cookie> getCookie(final HttpServletRequest request, final String cookieName) {
if (request == null) {
return Optional.empty();
}
return Optional.ofNullable(WebUtils.getCookie(request, cookieName));
}
public static void setCookie(final EnhancedCookieGenerator enhancedCookieGenerator,
final HttpServletResponse response,
final String cookieName,
final String cookieValue,
final boolean isSessionCookie) {
enhancedCookieGenerator.setCookieName(cookieName);
enhancedCookieGenerator.setSessionCookie(isSessionCookie);
enhancedCookieGenerator.addCookie(response, cookieValue);
}
public static void removeCookie(final EnhancedCookieGenerator enhancedCookieGenerator,
final HttpServletResponse response,
final String cookieName) {
enhancedCookieGenerator.setCookieName(cookieName);
enhancedCookieGenerator.removeCookie(response);
}
public static String parseObjectToJson(Object obj) {
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
String event = obj.toString();
try {
event = mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
LOG.debug("Encountered problem with json processing", e);
}
return event;
}
}
| [
"[email protected]"
] | |
84fd54efcd616269f213efb2a69e4fdf918e25c5 | ebf81b55aa53f06fae0ba8c8ccd3ffcf0ccb0b14 | /boardview/src/main/java/com/riclage/boardview/WordSearchBoardView.java | c994f6340a4b662ad6d67a49cb2dbed7ec3eb814 | [] | no_license | SarahAlhabeeb/Qafelah | 73293ff84196e1bdb47b3587841c769f5e8e32f8 | 97483bc75adacb88b2e2b7912450ccebf2bd9819 | refs/heads/master | 2021-01-20T09:25:58.730110 | 2018-08-15T04:19:20 | 2018-08-15T04:19:20 | 90,251,336 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,990 | java | package com.riclage.boardview;
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.IntDef;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
*
* Created by Ricardo on 27/01/2016.
*/
public class WordSearchBoardView extends TiledBoardView {
public static final int DIRECTION_UNKNOWN = 0;
public static final int DIRECTION_LEFT_TO_RIGHT = 1;
public static final int DIRECTION_TOP_TO_BOTTOM = 2;
public static final int DIRECTION_TOP_BOTTOM_LEFT_RIGHT = 3;
@Retention(RetentionPolicy.SOURCE)
@IntDef({DIRECTION_UNKNOWN, DIRECTION_LEFT_TO_RIGHT, DIRECTION_TOP_TO_BOTTOM, DIRECTION_TOP_BOTTOM_LEFT_RIGHT})
public @interface Direction {}
public interface OnWordSelectedListener {
/**
* Listener for the clients of this board to tell it whether a selected word is valid or not.
* If a selected word is valid, the board will highlight it, otherwise it will be discarded.
* @param selectedWord the selected word
* @return True if the word is valid and should be kept selected
*/
boolean onWordSelected(BoardWord selectedWord);
}
public interface OnWordHighlightedListener {
/**
* Listener for the clients of this board to take action after a word has been successfully highlighted.
* @param highlightedWord the highlighted word
*/
void onWordHighlighted(BoardWord highlightedWord);
}
private SelectedWord currentSelectedWord;
private List<SelectedWord> selectedWords;
private OnWordSelectedListener listener;
private OnWordHighlightedListener highlightedListener;
public WordSearchBoardView(Context context) {
super(context);
init();
}
public WordSearchBoardView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public WordSearchBoardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@SuppressWarnings("unused")
public WordSearchBoardView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
selectedWords = new ArrayList<>();
}
@Override
protected void initBoardTileViews(Context context) {
for (int i = 0; i < getTileCount(); i++) {
LetterTileView tileView = new LetterTileView(context);
tileView.setBackgroundResource(getTileBackgroundDrawableResId());
addView(tileView);
}
}
@Override
public void clearBoard() {
List<SelectedWord> selectedWordsToClear = new ArrayList<>(this.selectedWords);
this.selectedWords.clear();
for (SelectedWord word : selectedWordsToClear) {
updateTiles(word.selectedTiles, false, false);
}
}
/**
* Sets the given letters on the grid
* @param letterBoard A 2-d (row-by-col) array containing the letters to set
*/
public void setLetterBoard(String[][] letterBoard) {
if (letterBoard.length != getNumRows()
|| letterBoard[0].length != getNumCols()) {
setBoardSize(letterBoard.length, letterBoard[0].length);
}
int row, col;
for (int i=0; i < getChildCount(); i++) {
row = i / getNumCols();
col = i % getNumCols();
LetterTileView child = (LetterTileView) getChildAt(i);
child.setLetter(letterBoard[row][col]);
}
}
private boolean canInsertWordOnBoard(String word, BoardPoint startPoint, @Direction int selectionType, String[][] letterBoard) {
BoardPoint currPoint = startPoint;
for (char wordLetter : word.toCharArray()) {
String boardLetter = letterBoard[currPoint.row][currPoint.col];
if (!TextUtils.isEmpty(boardLetter) && !boardLetter.equals(String.valueOf(wordLetter))) {
return false;
}
currPoint = shift(currPoint, selectionType, 1);
}
return true;
}
public List<BoardWord> generateRandomLetterBoard(List<String> validWords) {
int boardSize = 4;
for (String word : validWords) {
if (word.length() > boardSize) {
boardSize = word.length();
}
}
return generateRandomLetterBoard(validWords, Math.min(10, boardSize + 1));
}
public List<BoardWord> generateRandomLetterBoard(List<String> validWords, int boardSize) {
String[][] letterBoard = new String[boardSize][boardSize];
List<BoardWord> wordLocations = new ArrayList<>(validWords.size());
for (String word : validWords) {
if (word.length() > boardSize) {
throw new IllegalArgumentException("Word '" + word + "' is longer than the specified board size");
}
@Direction int selectionType;
int row, col;
int tries = 0;
do {
Random r = new Random();
//noinspection ResourceType
selectionType = r.nextInt(3) + 1;
row = selectionType == DIRECTION_LEFT_TO_RIGHT ? r.nextInt(boardSize)
: (boardSize - word.length() == 0 ? 0 : r.nextInt(boardSize - word.length()));
col = selectionType == DIRECTION_TOP_TO_BOTTOM ? r.nextInt(boardSize)
: (boardSize - word.length() == 0 ? 0 : r.nextInt(boardSize - word.length()));
} while (tries++ < 100 && !canInsertWordOnBoard(word, new BoardPoint(row, col), selectionType, letterBoard));
if (tries == 100) break;
BoardPoint startPoint = new BoardPoint(row, col);
BoardPoint currPoint = startPoint;
for (char c : word.toCharArray()) {
letterBoard[currPoint.row][currPoint.col] = String.valueOf(c);
currPoint = shift(currPoint, selectionType, 1);
}
wordLocations.add(new BoardWord(word, selectionType, startPoint));
}
for (int row = 0; row < letterBoard.length; row++) {
char [] arabicChar = {'ء', 'آ', 'أ', 'ؤ', 'إ', 'ئ','ا', 'ب','ة', 'ت', 'ث', 'ج', 'ح', 'خ', 'د', 'ذ', 'ر','ز','س','ش', 'ص',
'ض', 'ط', 'ظ', 'ع', 'غ', 'ف', 'ق', 'ك', 'ل', 'م', 'ن', 'ه', 'و', 'ي' ,'ى' };
for (int col = 0; col < letterBoard[row].length; col++) {
if (TextUtils.isEmpty(letterBoard[row][col])) {
Random r = new Random();
//TODO: This only considers the English alphabet for now
letterBoard[row][col] = String.valueOf(arabicChar[(r.nextInt(arabicChar.length))]);
}
}
}
setLetterBoard(letterBoard);
return wordLocations;
}
public void setOnWordSelectedListener(OnWordSelectedListener listener) {
this.listener = listener;
}
public void setOnWordHighlightedListener(OnWordHighlightedListener listener) {
this.highlightedListener = listener;
}
@Override
protected Parcelable onSaveInstanceState() {
List<LetterTile> tiles = new ArrayList<>(getChildCount());
int row, col;
for (int i = 0; i < getChildCount(); i++) {
row = i / getNumCols();
col = i % getNumCols();
View child = getChildAt(i);
tiles.add(new LetterTile(row, col, child));
}
Parcelable p = super.onSaveInstanceState();
SavedState savedState = new SavedState(p);
savedState.boardRows = getNumRows();
savedState.boardCols = getNumCols();
savedState.boardTiles = tiles;
savedState.selectedWords = this.selectedWords;
return savedState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
this.selectedWords = savedState.selectedWords;
String[][] letterBoard = new String[savedState.boardRows][savedState.boardCols];
for (LetterTile tile : savedState.boardTiles) {
letterBoard[tile.row][tile.col] = tile.letter;
}
setLetterBoard(letterBoard);
for (SelectedWord word : selectedWords) {
for (Tile tile : word.selectedTiles) {
tile.view = getChildAt(tile.row, tile.col);
tile.view.setPressed(false);
tile.view.setSelected(true);
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float X = event.getX();
float Y = event.getY();
int row = (int) (Y / getTileSize());
int col = (int) (X / getTileSize());
View child = getChildAt(row, col);
//Exit on invalid touches
if (event.getActionMasked() != MotionEvent.ACTION_UP
&& (row >= getNumRows()
|| col >= getNumCols()
|| child == null)) {
return true;
}
super.onTouchEvent(event);
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
Tile currentTile = new Tile(row, col, child);
if (currentSelectedWord == null) {
currentSelectedWord = new SelectedWord(currentTile);
} else if (!currentTile.equals(currentSelectedWord.lastTile)
&& currentSelectedWord.isTileValid(currentTile)) {
if (!currentSelectedWord.isTileAllowed(currentTile)) {
//Clear the status of the old selection
updateTiles(currentSelectedWord.selectedTiles, false, false);
//If the current tile is valid but not allowed for the current word selection,
//start a new selection that matches the tile
currentSelectedWord = new SelectedWord(currentSelectedWord.getInitialTile());
}
List<Tile> tiles = getTilesBetween(currentSelectedWord.lastTile, currentTile);
if (tiles.size() > 0) {
currentSelectedWord.addTiles(tiles);
}
}
updateTiles(currentSelectedWord.selectedTiles, true, false);
break;
case MotionEvent.ACTION_UP:
if (currentSelectedWord != null) {
boolean isValidSelection = (listener != null && listener.onWordSelected(currentSelectedWord.toBoardWord()));
updateTiles(currentSelectedWord.selectedTiles, false, isValidSelection);
if (isValidSelection) {
selectedWords.add(currentSelectedWord);
if(highlightedListener != null) {
highlightedListener.onWordHighlighted(currentSelectedWord.toBoardWord());
}
}
currentSelectedWord = null;
}
break;
default:
return false;
}
return true;
}
private boolean isTileSelected(Tile tile, @Direction int direction) {
for (SelectedWord word : selectedWords) {
//A selected tile cannot be selected again for the same selection type
if (direction == DIRECTION_UNKNOWN || word.direction == direction) {
for (Tile wordTile : word.selectedTiles) {
//Check also the previous tile in the same direction to prevent connected
//selected tiles for different words from happening
if (wordTile.equals(tile) || wordTile.equals(shift(tile, direction, -1))) {
return true;
}
}
}
}
return false;
}
private View getChildAt(int row, int col) {
return getChildAt(col + row * getNumCols());
}
private void updateTiles(List<Tile> tiles, boolean pressed, boolean selected) {
for (Tile tile : tiles) {
tile.view.setPressed(pressed);
//Keep the tile selected if it belongs to a previously selected word
tile.view.setSelected(selected || isTileSelected(tile, DIRECTION_UNKNOWN));
}
}
/**
* Get all the tiles between the start and end, excluding the
* start tile but including the end one
*/
private List<Tile> getTilesBetween(Tile startTile, Tile endTile) {
List<Tile> tiles = new ArrayList<>();
@Direction int direction = startTile.getDirectionFrom(endTile);
BoardPoint currPoint = startTile;
if (direction != DIRECTION_UNKNOWN) {
while (!currPoint.equals(endTile)) {
currPoint = shift(currPoint, direction, 1);
View child = getChildAt(currPoint.row, currPoint.col);
Tile t = new Tile(currPoint.row, currPoint.col, child);
if (isTileSelected(t, direction)) {
break;
} else {
tiles.add(t);
}
}
}
return tiles;
}
private BoardPoint shift(BoardPoint point, @Direction int direction, int n) {
if (direction == DIRECTION_TOP_TO_BOTTOM) {
return new BoardPoint(point.row + n, point.col);
} else if (direction == DIRECTION_LEFT_TO_RIGHT) {
return new BoardPoint(point.row, point.col + n);
} else if (direction == DIRECTION_TOP_BOTTOM_LEFT_RIGHT) {
return new BoardPoint(point.row + n, point.col + n);
}
return point;
}
private static class SelectedWord implements Parcelable {
private @Direction
int direction = DIRECTION_UNKNOWN;
private Tile lastTile;
private List<Tile> selectedTiles;
public SelectedWord(Tile initialTile) {
lastTile = initialTile;
selectedTiles = new ArrayList<>();
selectedTiles.add(initialTile);
}
protected SelectedWord(Parcel in) {
//noinspection ResourceType
direction = in.readInt();
lastTile = in.readParcelable(Tile.class.getClassLoader());
selectedTiles = in.createTypedArrayList(Tile.CREATOR);
}
public static final Creator<SelectedWord> CREATOR = new Creator<SelectedWord>() {
@Override
public SelectedWord createFromParcel(Parcel in) {
return new SelectedWord(in);
}
@Override
public SelectedWord[] newArray(int size) {
return new SelectedWord[size];
}
};
public boolean isTileValid(Tile tile) {
return getInitialTile().getDirectionFrom(tile) != DIRECTION_UNKNOWN;
}
public boolean isTileAllowed(Tile tile) {
@Direction int currType = lastTile.getDirectionFrom(tile);
return currType != DIRECTION_UNKNOWN
&& (direction == DIRECTION_UNKNOWN || direction == currType);
}
public Tile getInitialTile() {
return selectedTiles.get(0);
}
public void addTiles(List<Tile> tiles) {
if (direction == DIRECTION_UNKNOWN) {
direction = lastTile.getDirectionFrom(tiles.get(0));
}
selectedTiles.addAll(tiles);
lastTile = selectedTiles.get(selectedTiles.size() - 1);
}
@Override
public String toString() {
StringBuilder letters = new StringBuilder(selectedTiles.size());
for (Tile letterTile : selectedTiles) {
letters.append(((LetterTileView) letterTile.view).getLetter());
}
return letters.toString();
}
public BoardWord toBoardWord() {
return new BoardWord(toString(), direction, getInitialTile());
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(direction);
dest.writeParcelable(lastTile, flags);
dest.writeTypedList(selectedTiles);
}
}
protected static class LetterTile extends Tile {
private final String letter;
public LetterTile(int row, int col, View view) {
super(row, col, view);
letter = ((LetterTileView)view).getLetter();
}
protected LetterTile(Parcel in) {
super(in);
letter = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(letter);
}
public static final Creator<LetterTile> CREATOR = new Creator<LetterTile>() {
@Override
public LetterTile createFromParcel(Parcel in) {
return new LetterTile(in);
}
@Override
public LetterTile[] newArray(int size) {
return new LetterTile[size];
}
};
}
private static class SavedState extends BaseSavedState {
private int boardRows, boardCols;
private List<LetterTile> boardTiles;
private List<SelectedWord> selectedWords;
public SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
boardRows = in.readInt();
boardCols = in.readInt();
boardTiles = in.createTypedArrayList(LetterTile.CREATOR);
selectedWords = in.createTypedArrayList(SelectedWord.CREATOR);
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(boardRows);
out.writeInt(boardCols);
out.writeTypedList(boardTiles);
out.writeTypedList(selectedWords);
}
public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
| [
"[email protected]"
] | |
a326e048eb73131752a3c52c2039d62478cd7f7f | b2ac73870276533b58473e0f2be097318f0ed7c4 | /discovery/src/main/java/com/techiprimers/discovery/DiscoveryApplication.java | 83f625e54d0c81b851f0135704ccdd52d4ba2cb8 | [] | no_license | nuwan-git/techiprimers-microserviceapplication-security-production-ready | 1d3b2e39a3ec1a6941f2e8f01828db138cbb5b73 | ebe9491eaf20fa1e7df07986af3601ecc18a2a5f | refs/heads/master | 2022-12-31T13:04:31.589930 | 2020-09-15T13:07:39 | 2020-09-15T13:07:39 | 295,730,437 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 500 | java | package com.techiprimers.discovery;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class DiscoveryApplication {
public static void main(String[] args) {
SpringApplication.run(DiscoveryApplication.class, args);
}
}
| [
"[email protected]"
] | |
b53bff8ed8624af87119df71d8160c230e948ae0 | a602b60995bc968384747c0a79b0cde380edf33e | /georef/src/main/java/georef/Settings.java | 3d7bc0c34a531c6067a01b413e6c15543ef31536 | [
"MIT"
] | permissive | diogocapela/isep-lapr4 | 8347f23b3c5627a3976a10baba9fde69749b1d5b | c72cef5112e06b319e0176aca98fadeb85950aa6 | refs/heads/master | 2020-04-24T00:07:12.463040 | 2019-02-19T21:53:00 | 2019-07-05T01:02:48 | 171,555,980 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 436 | java | package georef;
public class Settings {
public static String CLOUDINARY_URL = "cloudinary://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static String GOOGLE_API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static String MICROSOFT_API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static String DEFAULT_STRATEGY = "Google";
public static String DB_PU = "DATABASE_01";
}
| [
"[email protected]"
] | |
3200a32fc1b0c0e6612999d55c8660de5afff697 | 42beccdb1e18b61c6a3b28cfa5d5d94e1c58e9a3 | /backend/src/main/java/ch/lucbu/m151/webshop/model/dto/ProductDto.java | be413b4085244bb41ec7051a75923beb90862500 | [] | no_license | lucbu01/M151 | 9a21d02062bf1ab02b926d0721ac3e0cd2d71f21 | e37056287c36301721675d07e9379136e76b15dc | refs/heads/master | 2021-05-26T01:55:48.637703 | 2020-06-26T22:03:39 | 2020-06-26T22:03:39 | 254,008,187 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,645 | java | package ch.lucbu.m151.webshop.model.dto;
import java.math.BigDecimal;
import java.util.UUID;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import org.hibernate.validator.constraints.Length;
import ch.lucbu.m151.webshop.model.Product;
public class ProductDto extends Dto {
private UUID id;
private Long number;
@NotBlank
@Length(max = 100)
private String name;
@NotBlank
private String description;
@Min(value = 0)
private BigDecimal price;
private boolean active;
public ProductDto() {
}
public ProductDto(Product product, boolean withDescription) {
this.id = product.getId();
this.number = product.getNumber();
this.name = product.getName();
if (withDescription) {
this.description = product.getDescription();
}
this.price = product.getPrice();
this.active = product.isActive();
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public Long getNumber() {
return number;
}
public void setNumber(Long number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public void setActive(boolean active) {
this.active = active;
}
public boolean isActive() {
return active;
}
}
| [
"[email protected]"
] | |
5371d87680368c9da8c7c61b24bd24b74d6bb0e0 | 905df94b559e9b2335de1cdc0c5b9a2e116089c3 | /app/src/main/java/com/example/claire/studiochat/ChatActivity.java | 30df93a367444a4f9f2965962b2b898d1fac0b1a | [] | no_license | clairewcheng/StudioChat | adee40f1933e3d68eb2566719dbdecedb799a258 | f9ea6342fd818d27651228d50e30fe556c7ab375 | refs/heads/master | 2020-04-05T01:17:36.626613 | 2018-11-06T18:42:23 | 2018-11-06T18:42:23 | 156,430,751 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,612 | java | package com.example.claire.studiochat;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class ChatActivity extends AppCompatActivity implements View.OnClickListener {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference messages = database.getReference("messages");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.send_button);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText input = (EditText) findViewById(R.id.message_entry);
ChatMessage message = new ChatMessage(input.getText().toString(),FirebaseAuth.getInstance()
.getCurrentUser()
.getDisplayName());
// Read the input and push the data to Firebase database
messages.child("messages").child("ID:" + input.getText()).setValue(message);
//messages.push().setValue(message);
input.setText("");
}
});
}
@Override
public void onClick(View view) {
}
}
| [
"[email protected]"
] | |
7a57736124a94a7ea8743e411501c53ffe5eebb6 | d2cb1f4f186238ed3075c2748552e9325763a1cb | /methods_all/nonstatic_methods/javax_swing_text_html_InlineView_getResizeWeight_int.java | 62cea30b32f098e284660db25cf29f412d49d5f4 | [] | no_license | Adabot1/data | 9e5c64021261bf181b51b4141aab2e2877b9054a | 352b77eaebd8efdb4d343b642c71cdbfec35054e | refs/heads/master | 2020-05-16T14:22:19.491115 | 2019-05-25T04:35:00 | 2019-05-25T04:35:00 | 183,001,929 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 203 | java | class javax_swing_text_html_InlineView_getResizeWeight_int{ public static void function() {javax.swing.text.html.InlineView obj = new javax.swing.text.html.InlineView();obj.getResizeWeight(-375362265);}} | [
"[email protected]"
] | |
11edd2b2205f6d4ee3609d01218b0410629a59e3 | c9bc23ad5b3b2d21dec737c73c1e6c2a1cbe3504 | /app/src/main/java/android/support/v7/widget/aw.java | 28812c4329693410be4e49e337cade55aa767204 | [] | no_license | IamWilliamWang/wolf | 2e68faed4cab5ba5b04ae52bc44550be04f36079 | 6b7ff2b74f0413578a1a34132750e5d79b0c0fe6 | refs/heads/master | 2020-05-27T10:45:18.596136 | 2017-02-20T09:58:02 | 2017-02-20T09:58:02 | 82,542,835 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,151 | java | package android.support.v7.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.b.k;
import android.util.AttributeSet;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
public class aw extends ViewGroup.MarginLayoutParams
{
public float g;
public int h = -1;
public aw(int paramInt1, int paramInt2)
{
super(paramInt1, paramInt2);
this.g = 0.0F;
}
public aw(Context paramContext, AttributeSet paramAttributeSet)
{
super(paramContext, paramAttributeSet);
paramContext = paramContext.obtainStyledAttributes(paramAttributeSet, k.LinearLayoutCompat_Layout);
this.g = paramContext.getFloat(k.LinearLayoutCompat_Layout_android_layout_weight, 0.0F);
this.h = paramContext.getInt(k.LinearLayoutCompat_Layout_android_layout_gravity, -1);
paramContext.recycle();
}
public aw(ViewGroup.LayoutParams paramLayoutParams)
{
super(paramLayoutParams);
}
}
/* Location: C:\Users\Administrator\Desktop\狼王\classes.jar
* Qualified Name: android.support.v7.widget.aw
* JD-Core Version: 0.6.0
*/ | [
"[email protected]"
] | |
4998dee1ac9ee4fa5f47d554a4af365658a4e0fa | 0be4f384ae892bd1e4508ee095748cc1f6df5da0 | /src/GUI/Main.java | 2c2cf9ff5f7be754d53099bf309b0d4f77bb48e5 | [] | no_license | Maxenboy/MovieSearch | f2bd9e3462f64fa4bba0436ba316199b3f6ed10e | 84fc31d4a7686acf584c54c0a364c6e02d3560af | refs/heads/master | 2021-01-22T03:54:21.061458 | 2013-11-19T17:50:17 | 2013-11-19T17:50:17 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | Java | false | false | 377 | java | package GUI;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
final JFrame frame = new Frame("Filmer ©");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(Toolkit.getDefaultToolkit().getScreenSize().width, 600);
frame.setLocationRelativeTo(null);
}
}
| [
"[email protected]"
] | |
af49289415811ce4c82c36b84fea3a1b45510f66 | 2fbdcefd3cd39d77eb9efee9d7aa910634cdf46f | /demo 2/src/main/java/br/com/qaacademy/controller/HelloController.java | 82b17045314b35a02659821262fe90b748d8f587 | [] | no_license | flaviogoncalvesdias/EstudosApiSpring | 68e38ac4a9f26df38ddf71486de849ba63bb7737 | e08459fb5b76c1b40c652eaf1879f67adee772a0 | refs/heads/main | 2023-02-23T13:17:10.904076 | 2021-01-24T02:35:54 | 2021-01-24T02:35:54 | 310,741,793 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 381 | java | package br.com.qaacademy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@RequestMapping("/")
@ResponseBody
public String hello(){
return "Bem Vindo a API QA Academy";
}
}
| [
"[email protected]"
] | |
9af90042989aeb4d27ba1da65ed27cfc773a00b3 | 565d6d61c8003d5a4aee122034817d44e55b00ff | /spring-osgi-master/integration-tests/tests/src/test/java/org/springframework/osgi/iandt/blueprint/core/ExporterTest.java | 19551d3322b5c74dfa58cf006f8cf6eb85ae6a74 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | vinayv1208/Egiants_tasks | c56b3e8d38c75a594d3d094845e42b1bab983542 | 894e6cc0f95757e87218105c31926bd3cb1a74ab | refs/heads/master | 2023-01-09T21:10:09.690459 | 2019-09-22T13:11:39 | 2019-09-22T13:11:39 | 204,596,002 | 1 | 0 | null | 2022-12-31T02:49:54 | 2019-08-27T01:45:56 | Java | UTF-8 | Java | false | false | 1,342 | java | /*
* Copyright 2006-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.osgi.iandt.blueprint.core;
import org.osgi.framework.ServiceRegistration;
import org.springframework.osgi.iandt.blueprint.BaseBlueprintIntegrationTest;
import org.springframework.osgi.util.OsgiStringUtils;
/**
* @author Costin Leau
*/
public class ExporterTest extends BaseBlueprintIntegrationTest {
@Override
protected String[] getConfigLocations() {
return new String[] { "org/springframework/osgi/iandt/blueprint/core/exporter-test.xml" };
}
public void testExportedServiceProperties() throws Exception {
ServiceRegistration reg = (ServiceRegistration) applicationContext.getBean("simple");
System.out.println(OsgiStringUtils.nullSafeToString(reg.getReference()));
}
}
| [
"[email protected]"
] | |
74213c71768d656f9cace66b242dd81a90421f5f | 0c19d90324929eb30a901b4f7f293a52d8a5c361 | /src/exercises/section3SequentialStructure/Exercise4Sum.java | 740274ce7fca34a945db4008287976ba7a25f512 | [] | no_license | martadrozsa/curso-udemy-algoritmos-e-logica-de-programacao-java | c34948b93136486490b56e2ee5855d809e4f3a3e | 1776570882b4b0dc8d3cefde76e91305774b4b57 | refs/heads/main | 2023-07-06T14:08:39.113420 | 2021-08-04T13:52:33 | 2021-08-04T13:52:33 | 392,099,112 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 578 | java | package exercises.section3SequentialStructure;
import java.util.Scanner;
// Fazer um programa para ler dois valores inteiros X e Y, e depois mostrar na tela o valor da soma destes números.
public class Exercise4Sum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of X: ");
int x = sc.nextInt();
System.out.print("Enter the value of Y: ");
int y = sc.nextInt();
int sum = x + y;
System.out.println("Sum = " + sum);
sc.close();
}
}
| [
"[email protected]"
] | |
9df17a89edc6a8fe9d294c42d5dc4c7ee7e1283f | a1e49f5edd122b211bace752b5fb1bd5c970696b | /projects/org.springframework.jms/src/main/java/org/springframework/jms/connection/TransactionAwareConnectionFactoryProxy.java | e406bb4ca18c175993343f8c42fd5693ecc3b3e9 | [
"Apache-2.0"
] | permissive | savster97/springframework-3.0.5 | 4f86467e2456e5e0652de9f846f0eaefc3214cfa | 34cffc70e25233ed97e2ddd24265ea20f5f88957 | refs/heads/master | 2020-04-26T08:48:34.978350 | 2019-01-22T14:45:38 | 2019-01-22T14:45:38 | 173,434,995 | 0 | 0 | Apache-2.0 | 2019-03-02T10:37:13 | 2019-03-02T10:37:12 | null | UTF-8 | Java | false | false | 12,970 | java | /*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jms.connection;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TransactionInProgressException;
import org.springframework.util.Assert;
/**
* Proxy for a target JMS {@link javax.jms.ConnectionFactory}, adding awareness of
* Spring-managed transactions. Similar to a transactional JNDI ConnectionFactory
* as provided by a J2EE server.
*
* <p>Messaging code which should remain unaware of Spring's JMS support can work with
* this proxy to seamlessly participate in Spring-managed transactions. Note that the
* transaction manager, for example {@link JmsTransactionManager}, still needs to work
* with the underlying ConnectionFactory, <i>not</i> with this proxy.
*
* <p><b>Make sure that TransactionAwareConnectionFactoryProxy is the outermost
* ConnectionFactory of a chain of ConnectionFactory proxies/adapters.</b>
* TransactionAwareConnectionFactoryProxy can delegate either directly to the
* target factory or to some intermediary adapter like
* {@link UserCredentialsConnectionFactoryAdapter}.
*
* <p>Delegates to {@link ConnectionFactoryUtils} for automatically participating
* in thread-bound transactions, for example managed by {@link JmsTransactionManager}.
* <code>createSession</code> calls and <code>close</code> calls on returned Sessions
* will behave properly within a transaction, that is, always work on the transactional
* Session. If not within a transaction, normal ConnectionFactory behavior applies.
*
* <p>Note that transactional JMS Sessions will be registered on a per-Connection
* basis. To share the same JMS Session across a transaction, make sure that you
* operate on the same JMS Connection handle - either through reusing the handle
* or through configuring a {@link SingleConnectionFactory} underneath.
*
* <p>Returned transactional Session proxies will implement the {@link SessionProxy}
* interface to allow for access to the underlying target Session. This is only
* intended for accessing vendor-specific Session API or for testing purposes
* (e.g. to perform manual transaction control). For typical application purposes,
* simply use the standard JMS Session interface.
*
* @author Juergen Hoeller
* @since 2.0
* @see UserCredentialsConnectionFactoryAdapter
* @see SingleConnectionFactory
*/
public class TransactionAwareConnectionFactoryProxy
implements ConnectionFactory, QueueConnectionFactory, TopicConnectionFactory {
private boolean synchedLocalTransactionAllowed = false;
private ConnectionFactory targetConnectionFactory;
/**
* Create a new TransactionAwareConnectionFactoryProxy.
*/
public TransactionAwareConnectionFactoryProxy() {
}
/**
* Create a new TransactionAwareConnectionFactoryProxy.
* @param targetConnectionFactory the target ConnectionFactory
*/
public TransactionAwareConnectionFactoryProxy(ConnectionFactory targetConnectionFactory) {
setTargetConnectionFactory(targetConnectionFactory);
}
/**
* Set the target ConnectionFactory that this ConnectionFactory should delegate to.
*/
public final void setTargetConnectionFactory(ConnectionFactory targetConnectionFactory) {
Assert.notNull(targetConnectionFactory, "targetConnectionFactory must not be nul");
this.targetConnectionFactory = targetConnectionFactory;
}
/**
* Return the target ConnectionFactory that this ConnectionFactory should delegate to.
*/
protected ConnectionFactory getTargetConnectionFactory() {
return this.targetConnectionFactory;
}
/**
* Set whether to allow for a local JMS transaction that is synchronized with a
* Spring-managed transaction (where the main transaction might be a JDBC-based
* one for a specific DataSource, for example), with the JMS transaction committing
* right after the main transaction. If not allowed, the given ConnectionFactory
* needs to handle transaction enlistment underneath the covers.
* <p>Default is "false": If not within a managed transaction that encompasses
* the underlying JMS ConnectionFactory, standard Sessions will be returned.
* Turn this flag on to allow participation in any Spring-managed transaction,
* with a local JMS transaction synchronized with the main transaction.
*/
public void setSynchedLocalTransactionAllowed(boolean synchedLocalTransactionAllowed) {
this.synchedLocalTransactionAllowed = synchedLocalTransactionAllowed;
}
/**
* Return whether to allow for a local JMS transaction that is synchronized
* with a Spring-managed transaction.
*/
protected boolean isSynchedLocalTransactionAllowed() {
return this.synchedLocalTransactionAllowed;
}
public Connection createConnection() throws JMSException {
Connection targetConnection = this.targetConnectionFactory.createConnection();
return getTransactionAwareConnectionProxy(targetConnection);
}
public Connection createConnection(String username, String password) throws JMSException {
Connection targetConnection = this.targetConnectionFactory.createConnection(username, password);
return getTransactionAwareConnectionProxy(targetConnection);
}
public QueueConnection createQueueConnection() throws JMSException {
if (!(this.targetConnectionFactory instanceof QueueConnectionFactory)) {
throw new javax.jms.IllegalStateException("'targetConnectionFactory' is no QueueConnectionFactory");
}
QueueConnection targetConnection =
((QueueConnectionFactory) this.targetConnectionFactory).createQueueConnection();
return (QueueConnection) getTransactionAwareConnectionProxy(targetConnection);
}
public QueueConnection createQueueConnection(String username, String password) throws JMSException {
if (!(this.targetConnectionFactory instanceof QueueConnectionFactory)) {
throw new javax.jms.IllegalStateException("'targetConnectionFactory' is no QueueConnectionFactory");
}
QueueConnection targetConnection =
((QueueConnectionFactory) this.targetConnectionFactory).createQueueConnection(username, password);
return (QueueConnection) getTransactionAwareConnectionProxy(targetConnection);
}
public TopicConnection createTopicConnection() throws JMSException {
if (!(this.targetConnectionFactory instanceof TopicConnectionFactory)) {
throw new javax.jms.IllegalStateException("'targetConnectionFactory' is no TopicConnectionFactory");
}
TopicConnection targetConnection =
((TopicConnectionFactory) this.targetConnectionFactory).createTopicConnection();
return (TopicConnection) getTransactionAwareConnectionProxy(targetConnection);
}
public TopicConnection createTopicConnection(String username, String password) throws JMSException {
if (!(this.targetConnectionFactory instanceof TopicConnectionFactory)) {
throw new javax.jms.IllegalStateException("'targetConnectionFactory' is no TopicConnectionFactory");
}
TopicConnection targetConnection =
((TopicConnectionFactory) this.targetConnectionFactory).createTopicConnection(username, password);
return (TopicConnection) getTransactionAwareConnectionProxy(targetConnection);
}
/**
* Wrap the given Connection with a proxy that delegates every method call to it
* but handles Session lookup in a transaction-aware fashion.
* @param target the original Connection to wrap
* @return the wrapped Connection
*/
protected Connection getTransactionAwareConnectionProxy(Connection target) {
List<Class> classes = new ArrayList<Class>(3);
classes.add(Connection.class);
if (target instanceof QueueConnection) {
classes.add(QueueConnection.class);
}
if (target instanceof TopicConnection) {
classes.add(TopicConnection.class);
}
return (Connection) Proxy.newProxyInstance(
Connection.class.getClassLoader(),
classes.toArray(new Class[classes.size()]),
new TransactionAwareConnectionInvocationHandler(target));
}
/**
* Invocation handler that exposes transactional Sessions for the underlying Connection.
*/
private class TransactionAwareConnectionInvocationHandler implements InvocationHandler {
private final Connection target;
public TransactionAwareConnectionInvocationHandler(Connection target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Invocation on ConnectionProxy interface coming in...
if (method.getName().equals("equals")) {
// Only consider equal when proxies are identical.
return (proxy == args[0]);
}
else if (method.getName().equals("hashCode")) {
// Use hashCode of Connection proxy.
return System.identityHashCode(proxy);
}
else if (Session.class.equals(method.getReturnType())) {
Session session = ConnectionFactoryUtils.getTransactionalSession(
getTargetConnectionFactory(), this.target, isSynchedLocalTransactionAllowed());
if (session != null) {
return getCloseSuppressingSessionProxy(session);
}
}
else if (QueueSession.class.equals(method.getReturnType())) {
QueueSession session = ConnectionFactoryUtils.getTransactionalQueueSession(
(QueueConnectionFactory) getTargetConnectionFactory(), (QueueConnection) this.target,
isSynchedLocalTransactionAllowed());
if (session != null) {
return getCloseSuppressingSessionProxy(session);
}
}
else if (TopicSession.class.equals(method.getReturnType())) {
TopicSession session = ConnectionFactoryUtils.getTransactionalTopicSession(
(TopicConnectionFactory) getTargetConnectionFactory(), (TopicConnection) this.target,
isSynchedLocalTransactionAllowed());
if (session != null) {
return getCloseSuppressingSessionProxy(session);
}
}
// Invoke method on target Connection.
try {
return method.invoke(this.target, args);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
private Session getCloseSuppressingSessionProxy(Session target) {
List<Class> classes = new ArrayList<Class>(3);
classes.add(SessionProxy.class);
if (target instanceof QueueSession) {
classes.add(QueueSession.class);
}
if (target instanceof TopicSession) {
classes.add(TopicSession.class);
}
return (Session) Proxy.newProxyInstance(
SessionProxy.class.getClassLoader(),
classes.toArray(new Class[classes.size()]),
new CloseSuppressingSessionInvocationHandler(target));
}
}
/**
* Invocation handler that suppresses close calls for a transactional JMS Session.
*/
private static class CloseSuppressingSessionInvocationHandler implements InvocationHandler {
private final Session target;
public CloseSuppressingSessionInvocationHandler(Session target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Invocation on SessionProxy interface coming in...
if (method.getName().equals("equals")) {
// Only consider equal when proxies are identical.
return (proxy == args[0]);
}
else if (method.getName().equals("hashCode")) {
// Use hashCode of Connection proxy.
return System.identityHashCode(proxy);
}
else if (method.getName().equals("commit")) {
throw new TransactionInProgressException("Commit call not allowed within a managed transaction");
}
else if (method.getName().equals("rollback")) {
throw new TransactionInProgressException("Rollback call not allowed within a managed transaction");
}
else if (method.getName().equals("close")) {
// Handle close method: not to be closed within a transaction.
return null;
}
else if (method.getName().equals("getTargetSession")) {
// Handle getTargetSession method: return underlying Session.
return this.target;
}
// Invoke method on target Session.
try {
return method.invoke(this.target, args);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
}
| [
"[email protected]"
] | |
b69c4952f0f0771b315db3c6f792768013aebb2d | 66c6599b80c2ca7edd7a01758aac5fa3b316b4b4 | /src/main/java/com/company/data/BenchmarkData.java | d8d5bf093df2a2b526480368cb2d9f0f12576532 | [] | no_license | FilosGabriel/Allocating-radio-frequencies-using-graph-coloring- | 9c4faa4cfa8e7496a60c89e2d967e1ddc9ea4006 | 3efdc87c2f4bb115ea406f402e2d560f74c538bb | refs/heads/master | 2020-08-15T19:50:00.669108 | 2019-10-16T12:37:01 | 2019-10-16T12:37:01 | 215,399,047 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,108 | java | package com.company.data;
import com.company.data.custom.Format;
public class BenchmarkData {
public void setInfo(GeneralInfo info) {
this.info = info;
}
public void setCellsInfo(Cells cellsInfo) {
CellsInfo = cellsInfo;
}
public void setCellRelations(Relations cellRelations) {
this.cellRelations = cellRelations;
}
public GeneralInfo getGeneralInfo() {
return info;
}
public Cells getCellsInfo() {
return CellsInfo;
}
public Relations getCellRelations() {
return cellRelations;
}
public Format getFormat() {
return format;
}
public void setFormat(Format format) {
this.format = format;
}
@Override
public String toString() {
return "BenchmarkData{" +
format +
info +
", CellsInfo=" + CellsInfo +
", cellRelations=" + cellRelations +
'}';
}
private Format format;
private GeneralInfo info;
private Cells CellsInfo;
private Relations cellRelations;
}
| [
"[email protected]"
] | |
c3b40b0e0efdcbc56c014fccf3468df86215424e | 49317d0b09639f0633f533b5568bcac0a4dfe1bf | /2. Unified Modeling Language (UML)/sis-leilao/src/main/java/Lance.java | 79f3f3f96bf190c6c29a81a1590d5921cbaab346 | [] | no_license | falvojr-classes/unip-2019-2-ads-poo2 | f8a1e780fa8621de940218d5aa01da467fb62b60 | 3cd0a096b438cb722960bfa054ac58b6f0015cb6 | refs/heads/master | 2020-06-26T03:01:33.852101 | 2019-11-04T22:54:24 | 2019-11-04T22:54:24 | 199,506,080 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 544 | java | import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Lance {
private Participante participante;
private double valor;
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("Nome: %s", participante.getNome()));
sb.append(System.lineSeparator());
sb.append(String.format("CPF: %s", participante.getCpf()));
sb.append(System.lineSeparator());
sb.append(String.format("Valor: R$%.2f", valor));
sb.append(System.lineSeparator());
return sb.toString();
}
}
| [
"[email protected]"
] | |
492a3da6d6204b271d73f4089ad04abadab1f0bf | c1a9357cf34cb93fe1828a43d6782bcefa211804 | /source_code/netweaver/src/main/java/com/sap/netweaver/porta/ide/eclipse/server/control/PublishException.java | 351dd7ed813e15ff71c1c032eb5a4766fb612e79 | [] | no_license | Hessah/Quality-Metrics-of-Test-suites-for-TDD-Applications | d5bd48b1c1965229f8249dcfc53a10869bb9bbb0 | d7abc677685ab0bc11ae9bc41dd2554bceaf18a8 | refs/heads/master | 2020-05-29T22:38:33.553795 | 2014-12-22T23:55:02 | 2014-12-22T23:55:02 | 24,071,022 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,417 | java | /*******************************************************************************
* Copyright (c) 2009, 2010 SAP AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Kaloyan Raev (SAP AG) - initial API and implementation
*******************************************************************************/
package com.sap.netweaver.porta.ide.eclipse.server.control;
import com.sap.netweaver.porta.core.CoreException;
import com.sap.netweaver.porta.core.DeployResult;
import com.sap.netweaver.porta.core.DeployResultStatus;
public class PublishException extends CoreException {
private static final long serialVersionUID = -698578474515838790L;
private DeployResult deployResult;
public PublishException(DeployResult deployResult) {
super(getMessage(deployResult.getStatus()));
this.deployResult = deployResult;
}
private static String getMessage(DeployResultStatus status) {
switch (status) {
case ERROR: return "The publish operation finished with error. ";
case WARNING: return "The publish operation finished with warning. ";
default: return "";
}
}
public DeployResult getDeployResult() {
return deployResult;
}
}
| [
"[email protected]"
] | |
dedf2629b9d9d45bcfd25b401323f9da33490705 | 30ac8fe966006e1aab5d6896e9006ad17f87c039 | /homework/HW09/PokemonFactory.java | dcd7e4376ff4712a5e5db0dd5b565b523cc7cb01 | [] | no_license | messinarnd/cs1331_intro_to_oop | 2d346f644fb08eba00fadf8360e39378a387c3b0 | 1b50317550ea631af764065b644e81831e87f6b3 | refs/heads/master | 2020-06-23T05:27:44.948795 | 2019-07-24T00:43:04 | 2019-07-24T00:43:04 | 198,529,641 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,663 | java | // I worked on this alone
import java.util.ArrayList;
/**
* A factory that creates a list of Pokemon for the Pokedex
* @author Christopher Messina
* @version 1.2
*/
public final class PokemonFactory {
private static ArrayList<Pokemon> pokemon;
/**
* Creates the list of Pokemon in the Pokedex
*
* @return pokemon an arraylist of Pokemon
*/
public static ArrayList<Pokemon> createPokemon() {
pokemon = new ArrayList<>();
Pokemon bulbasaur = new Pokemon("Bulbasaur", "001.png", Type.GRASS,
Type.POISON);
bulbasaur.setDescription("A strange seed was planted on its back at "
+ "birth. The plant sprouts and grows with this Pokemon.");
bulbasaur.setGeneration(1);
bulbasaur.setNumber(1);
bulbasaur.createDetailView();
bulbasaur.createSideView();
Pokemon charmander = new Pokemon("Charmander", "004.png", Type.FIRE);
charmander.setDescription("Obviously prefers hot places. When it "
+ "rains, steam is said to spout from the tip of its tail.");
charmander.setGeneration(1);
charmander.setNumber(4);
charmander.createDetailView();
charmander.createSideView();
Pokemon squirtle = new Pokemon("Squirtle", "007.png", Type.WATER);
squirtle.setDescription("After birth, its back swells and hardens"
+ " into a shell. Powerfully sprays foam from its mouth.");
squirtle.setGeneration(1);
squirtle.setNumber(7);
squirtle.createDetailView();
squirtle.createSideView();
Pokemon pikachu = new Pokemon("Pikachu", "025.png", Type.ELECTRIC);
pikachu.setDescription("Whenever Pikachu comes across something new, "
+ "it blasts it with a jolt of electricity. If you come across "
+ "a blackened berry, it's evidence that this Pokémon mistook the"
+ " intensity of its charge. ");
pikachu.setNumber(25);
pikachu.createDetailView();
pikachu.createSideView();
Pokemon abra = new Pokemon("Abra", "063.png", Type.PSYCHIC);
abra.setNumber(63);
abra.setDescription("Abra sleeps for eighteen hours a day. However,"
+ " it can sense the presence of foes even while it is sleeping. "
+ "In such a situation, this Pokémon immediately teleports "
+ "to safety. ");
abra.createDetailView();
abra.createSideView();
pokemon.add(bulbasaur);
pokemon.add(charmander);
pokemon.add(squirtle);
pokemon.add(pikachu);
pokemon.add(abra);
return pokemon;
}
}
| [
"[email protected]"
] | |
2b78aa01299b8193a8cf7efb00446ee301870f5b | 77da783664fe34722588a34a8490129ab6c76289 | /loveread-manager/loveread-manager-web/src/main/java/cn/neusoft/loveread/manager/config/MySettingFileConfig.java | b07ac5b7808517eaed0e06777670a0629866df6e | [] | no_license | DonjuanXX/LoveRead | 4f681209ba1cae7065818df78f78d7acb101f60d | 3e85f043e320cb69f17b6922df3598fc33e23a7e | refs/heads/master | 2020-04-13T07:36:28.583069 | 2019-05-19T01:46:22 | 2019-05-19T01:46:22 | 163,056,400 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 272 | java | package cn.neusoft.loveread.manager.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:conf/conf.properties")
public class MySettingFileConfig {
}
| [
"[email protected]"
] | |
eaa7a35c9587610ad7a215c8b958bf43c7e8e789 | 5d22b09f12282aef45e52eace150d9e7c51fc05f | /app/src/main/java/com/example/hellochat/PagerAdapter.java | 7a282a3a7fea18f33440874e49cc25fb1970efbe | [] | no_license | hellohridoy/HelloChat | 377039a246afb0d51717dd8ca71acd7cf8e5aeea | 0fb7afaba6ab31dadd996baf8921f40caa3626c6 | refs/heads/master | 2023-08-27T05:51:11.253658 | 2021-11-02T14:43:31 | 2021-11-02T14:43:31 | 422,184,600 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 780 | java | package com.example.hellochat;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class PagerAdapter extends FragmentPagerAdapter {
int tabCount;
public PagerAdapter(@NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
tabCount=behavior;
}
@NonNull
@Override
public Fragment getItem(int position) {
switch (position){
case 0:return new chatFragment();
case 1:return new statusFragment();
case 2:return new callFragment();
default:return null;
}
}
@Override
public int getCount() {
return tabCount;
}
}
| [
"[email protected]"
] | |
03a17729d36bbe57ad60cee14c20e3401f025379 | 0ff4bff61e610e6b139a8ad70ebf89a80c213aff | /src/main/java/org/khmerslide/configuration/MvcConfiguration.java | 1aeeb6633e1e94186460d6369a9657aa49032292 | [] | no_license | ExcaCambo/Khmer-Slide-Team | 6fe1ab4f6643bcfece985dbec183608b6def4543 | 0f26839dd8f7a45f5b741199508168cc2414aecc | refs/heads/master | 2021-01-22T08:28:15.454338 | 2016-08-09T02:24:11 | 2016-08-09T02:24:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,150 | java | package org.khmerslide.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("/home");
registry.addViewController("/home").setViewName("/home");
registry.addViewController("/index").setViewName("/index");
// registry.addViewController("/about").setViewName("/about");
registry.addViewController("/admin").setViewName("/admin/index");
registry.addViewController("/admin/index").setViewName("/admin/index");
registry.addViewController("/admin/home").setViewName("/admin/index");
registry.addViewController("/admin/user-list").setViewName("/admin/user-list");
registry.addViewController("/admin/add-user").setViewName("/admin/add-user");
registry.addViewController("/admin/edit-user").setViewName("/admin/edit-user");
registry.addViewController("/admin/doc-list").setViewName("/admin/doc-list");
registry.addViewController("/user").setViewName("/user/index");
registry.addViewController("/user/index").setViewName("/user/index");
registry.addViewController("/user/home").setViewName("/user/index");
// registry.addViewController("/user").setViewName("/user/user");
// registry.addViewController("/dba").setViewName("/dba");
registry.addViewController("/login").setViewName("/login");
registry.addViewController("/swagger").setViewName("/swagger/index");
// Errors
registry.addViewController("/401").setViewName("/error/401");
registry.addViewController("/access-denied").setViewName("/error/403");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET","POST","DELETE","PUT","OPTIONS","PATCH")
.allowedOrigins("*");
}
}
| [
"[email protected]"
] | |
6fe7561bf4fb16f925da0b6f30d54d12dda9d3a7 | e213608cf6dac78a21242faca66ff9d56112d0fb | /src/java/persistencia/daos/TempCargueFacturacionDAO.java | 401ab2c980b94457c77cc46737629a601997ef7d | [] | no_license | jota09/comunidades | e425a016aeb1021ff77781523559220c900852eb | b92ffcd48e866ce4033b83577ccf6932d0b0846b | refs/heads/master | 2021-01-20T13:37:14.027785 | 2017-05-03T19:27:24 | 2017-05-03T19:27:24 | 82,694,156 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,768 | java | /*
* 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 persistencia.daos;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import persistencia.conexion.ConexionBD;
import persistencia.entidades.TempCargueFacturacion;
/**
*
* @author manuel.alcala
*/
public class TempCargueFacturacionDAO implements GestionDAO {
@Override
public int getCount(Object object) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object getObject(Object object) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List getListObject(Object object) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List getListObject() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public int updateObject(Object object) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public int insertObject(Object object) {
TempCargueFacturacion temp = (TempCargueFacturacion) object;
Connection con = null;
int tam = 0;
try {
con = ConexionBD.obtenerConexion();
String sql = "insert into temp_cargue_facturacion(documento,detalle,valor,fecha_vencimiento,proceso_codigo,num_factura) values(?,?,?,?,?,?)";
PreparedStatement pS = con.prepareStatement(sql);
pS.setInt(1, temp.getDocumento());
pS.setString(2, temp.getDetalle());
pS.setDouble(3, temp.getValor());
pS.setDate(4, new Date(temp.getFecha_vencimiento().getTime()));
pS.setInt(5, temp.getProceso().getCodigo());
pS.setString(6, temp.getNum_Factura());
System.out.println("Temporal:" + pS);
tam = pS.executeUpdate();
pS.close();
} catch (ClassNotFoundException ex) {
Logger.getLogger(TempCargueFacturacionDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(TempCargueFacturacionDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TempCargueFacturacionDAO.class.getName()).log(Level.SEVERE, null, ex);
} finally {
ConexionBD.cerrarConexion(con);
}
return tam;
}
@Override
public void deleteObject(Object object) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List getListByCondition(Object object) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List getListByPagination(Object object) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| [
"[email protected]"
] | |
2d4218fcc931e314f408e796cad6a26bf94b97fa | 0fd3f5edc85d8a189b3b66af9cedb435d0490537 | /app/CET6/src/com/yingshibao/cet4/bean/School.java | 9c59a5dacdadb7cc7012cc75d15fa7494c6bcdd2 | [] | no_license | zhanfangzxc/CET4 | 1579a5ba59ac9973e5c974bf5d50873ae964373c | c387c97e60a6c37d3f4577277d6bcd17716ffc0b | refs/heads/master | 2020-05-18T17:12:51.047373 | 2014-10-10T05:31:29 | 2014-10-10T05:31:29 | 25,021,326 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 421 | java | package com.yingshibao.cet4.bean;
public class School {
private int id;
private String name;
private String abbr;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAbbr() {
return abbr;
}
public void setAbbr(String abbr) {
this.abbr = abbr;
}
}
| [
"[email protected]"
] | |
90c7f7d662b4be5c43a51da275a59dc9412e2d32 | 6e6e0bb14ffd84ad87cf5d8c469961c5016f85fd | /src/main/java/agendafinanceira/services/SetorService.java | 8ca8370fe08ec80b8e5ded8728b9cd20dff66500 | [] | no_license | osmarmartins/agendafinanceira-spring | 305bcc53f7c992d79e1dd71c2598d9a1c3326537 | 9df776813c5af4a893faa3d8e2bd7dd9c9a6573f | refs/heads/master | 2021-01-23T16:55:59.468264 | 2018-04-09T12:35:46 | 2018-04-09T12:35:46 | 102,751,119 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,546 | java | package agendafinanceira.services;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import agendafinanceira.models.SetorModel;
import agendafinanceira.models.enums.Ativo;
import agendafinanceira.repositories.SetorRepository;
import agendafinanceira.services.exception.DescricaoExistenteException;
import agendafinanceira.services.exception.ExcluirEntidadeException;
@Service
public class SetorService {
@Autowired
private SetorRepository setorRepository;
@Transactional
public SetorModel salvar(SetorModel setor) {
Optional<SetorModel> setorOptional = setorRepository.findByDescricaoIgnoreCase(setor.getDescricao());
if (setorOptional.isPresent() && !setorOptional.get().getIdSetor().equals(setor.getIdSetor()) ) {
throw new DescricaoExistenteException("Setor já cadastrado");
}
return setorRepository.saveAndFlush(setor);
}
@Transactional
public void excluir(SetorModel setor) {
try {
setorRepository.delete(setor);
setorRepository.flush();
} catch (ExcluirEntidadeException e) {
throw new ExcluirEntidadeException("Não foi possível excluir o setor! Verifique se está em uso nos lançamentos financeiros.");
}
}
@Transactional
public void alterarStatus(SetorModel setor){
setor.setAtivo(setor.getAtivo().equals(Ativo.ATIVO)?Ativo.INATIVO:Ativo.ATIVO);
setorRepository.save(setor);
}
}
| [
"[email protected]"
] | |
8c1ff37b1552475c33d1d03544fe74baa5154089 | f2907d908542173737d69865287c80ca3e7d7cf7 | /src/main/java/bluepumpkin/services/AdminService.java | 2412ea64b278d0274712ce72912174f12e607040 | [] | no_license | lubomirkonik/blue-pumpkin | a991d5817bda9e6766570b63002660d643c1d32d | be49acc6a49c163de954d914a93b752b8b57aad9 | refs/heads/master | 2021-01-01T17:37:09.564595 | 2015-04-19T18:42:12 | 2015-04-19T18:42:12 | 29,161,867 | 0 | 0 | null | 2015-04-02T02:49:18 | 2015-01-12T23:09:27 | Java | UTF-8 | Java | false | false | 5,013 | java | package bluepumpkin.services;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import bluepumpkin.domain.Employee;
import bluepumpkin.domain.Event;
import bluepumpkin.domain.Participant;
import bluepumpkin.domain.Team;
import bluepumpkin.domain.web.Eventw;
import bluepumpkin.repository.EmployeeRepository;
import bluepumpkin.repository.EventRepository;
import bluepumpkin.repository.ParticipantRepository;
import bluepumpkin.repository.TeamRepository;
@Service
public class AdminService {
private final ParticipantRepository participantRepository;
private final EventRepository eventRepository;
private final EmployeeRepository employeeRepository;
private final TeamRepository teamRepository;
@Autowired
public AdminService(final ParticipantRepository participantRepository,
final EventRepository eventRepository,
final EmployeeRepository employeeRepository,
final TeamRepository teamRepository) {
this.participantRepository = participantRepository;
this.eventRepository = eventRepository;
this.employeeRepository = employeeRepository;
this.teamRepository = teamRepository;
}
public List<Participant> getWaitingParticipations() {
List<Participant> waitingParticipations = participantRepository.findByStatus("Waiting");
List<Participant> waitingFuturePs = waitingParticipations.stream()
.filter(p -> p.getEventID().getDateTime().compareTo(new Date()) > 0)
.collect(Collectors.toList());
Collections.reverse(waitingFuturePs);
return waitingFuturePs;
}
public void changeParticipationStatusToApproved(String id) {
Participant participation = participantRepository.findOne(id);
participation.setStatus("Approved");
participantRepository.save(participation);
}
public void changeParticipationStatusToDenied(String id) {
Participant participation = participantRepository.findOne(id);
participation.setStatus("Denied");
participantRepository.save(participation);
}
public List<Event> getUpcomingEvents() {
List<Event> allEvents = eventRepository.findAll();
List<Event> upcomingEvents = new ArrayList<>();
for (Event event : allEvents) {
if (event.getDateTime().compareTo(new Date()) > 0) {
upcomingEvents.add(event);
}
}
upcomingEvents = sortEventsByTime(upcomingEvents);
// sorted by time ascending
return upcomingEvents;
}
public List<Event> getPastEvents() {
List<Event> allEvents = eventRepository.findAll();
List<Event> pastEvents = new ArrayList<>();
for (Event event : allEvents) {
if (event.getDateTime().compareTo(new Date()) < 0) {
pastEvents.add(event);
}
}
pastEvents = sortEventsByTime(pastEvents);
Collections.reverse(pastEvents);
// sorted by time descending
return pastEvents;
}
private List<Event> sortEventsByTime(List<Event> events) {
List<Event> sorted = events.stream()
.sorted((p1, p2) -> p1.getDateTime().compareTo(p2.getDateTime()))
.collect(Collectors.toList());
return sorted;
}
public Eventw findEvent(String id) {
Event e = eventRepository.findOne(id);
Eventw ew = new Eventw(e.getId(), e.getType(), e.getName(), e.getPlace(), e.getDateTime());
return ew;
}
public void createEvent(Eventw eventw) {
Event event = new Event(UUID.randomUUID().toString(), eventw.getType(), eventw.getName(), eventw.getPlace(), eventw.getDateTime(), "");
eventRepository.save(event);
}
public void updateEvent(Eventw ew) {
Event e = new Event(ew.getId(), ew.getType(), ew.getName(), ew.getPlace(), ew.getDateTime(), "");
eventRepository.save(e);
}
public List<String> getEventTypes() {
return Arrays.asList("Meeting,Training,Sports Event,Trip".split(","));
}
public void deleteEvent(String id) {
Event event = eventRepository.findOne(id);
// get event's participants and delete each one
event.getParticipantList().forEach(p -> participantRepository.delete(p));
// if event is of type 'Sports Event'
if (event.getType().equals("Sports Event")) {
// iterate through event's teams
event.getTeamList().forEach(team -> {
// iterate through team's employees and delete the team from each employee - deletes record from 'team_member' assoc. table
team.getEmployeeList().forEach(emp -> {
emp.getTeamList().remove(team);
employeeRepository.save(emp);
});
teamRepository.delete(team);
});
}
eventRepository.delete(id);
}
public List<Employee> getAccounts() {
Comparator<Employee> byLastName = (c1, c2) -> c1.getLastName()
.compareTo(c2.getLastName());
Comparator<Employee> byDepartment = (c1, c2) -> c1.getDepartment()
.compareTo(c2.getDepartment());
return employeeRepository.findAll().stream()
.sorted(byDepartment.thenComparing(byLastName))
.collect(Collectors.toList());
}
}
| [
"[email protected]"
] | |
83164c3e629eb7ca172acf7e9e9679dfedf4d1b6 | 020f13c2b2142f7e0b9340a2f9dc1a61966a9b10 | /JavaProgramming/JavaTest_0408-0409/Workshop.java | 40f2c2f09df231dd61c839e3a1f8dc59823253a7 | [] | no_license | SuYOUNGgg/JavaStudy | cf03af09c40452110399840fe2195122e659a66e | c750b152e7d2211a7c2e04afbd51fdc7a2f46ff5 | refs/heads/master | 2022-10-19T04:59:34.730748 | 2020-06-11T08:38:33 | 2020-06-11T08:38:33 | 255,542,950 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 2,137 | java | import java.util.Scanner;
class cost {
public static int am = 2000;
public static int cl = 3000;
public static int bg = 1500;
public static int cc = 500;
public static int Calc(int what, int n) {
return what*n;
}
}
public class Workshop {
public static void main(String[] args) {
System.out.println( "========= 메뉴 =========" );
System.out.println( " 1. 아메리카노 2000원" );
System.out.println( " 2. 카페라떼 3000원" );
System.out.println( " 3. 베이글 1500원" );
System.out.println( " 4. 크림치즈 500원\n" );
System.out.println( "========= 주문 =========" );
System.out.print( " 아메리카노 주문 수량 : " );
int am = getUserInput();
System.out.print( " 카페라떼 주문 수량 : " );
int cl = getUserInput();
System.out.print( " 베이글 주문 수량 : " );
int bg = getUserInput();
System.out.print( " 크림치즈 주문 수량 : " );
int cc = getUserInput();
int total=0;
System.out.println( "========= 금액 =========" );
total = total + cost.Calc(cost.am,am);
System.out.println( " 아메리카노 : " + cost.Calc(cost.am,am));
total += cost.Calc(cost.cl, cl);
System.out.println( " 카페라떼 : " + cost.Calc(cost.cl, cl));
total += cost.Calc(cost.bg, bg);
System.out.println(" 베이글 : " + cost.Calc(cost.bg, bg));
total += cost.Calc(cost.cc, cc);
System.out.println( " 크림치즈 : " + cost.Calc(cost.cc,cc));
double dPoint = 0;
System.out.println( "==================" );
System.out.print( " 총 구매 금액 : " + total);
if (total > 30000) {
dPoint = total*0.02;
}
else if (total >12000) {
dPoint = total*0.01;
}
else dPoint = 0;
System.out.println(" 포인트 적립 : " + dPoint);
}
public static int getUserInput() {
Scanner scanner = new Scanner(System.in);
int value = scanner.nextInt();
return value;
}
}
| [
"[email protected]"
] | |
ca09e837014c3fe74a70b8dfa5357d4a2b4b27cb | 6dbae30c806f661bcdcbc5f5f6a366ad702b1eea | /Corpus/ecf/2684.java | c9e44afe59a9ee31c5bfbc7e0d292f750be389b6 | [
"MIT"
] | permissive | SurfGitHub/BLIZZARD-Replication-Package-ESEC-FSE2018 | d3fd21745dfddb2979e8ac262588cfdfe471899f | 0f8f4affd0ce1ecaa8ff8f487426f8edd6ad02c0 | refs/heads/master | 2020-03-31T15:52:01.005505 | 2018-10-01T23:38:50 | 2018-10-01T23:38:50 | 152,354,327 | 1 | 0 | MIT | 2018-10-10T02:57:02 | 2018-10-10T02:57:02 | null | UTF-8 | Java | false | false | 823 | java | /*******************************************************************************
* Copyright (c) 2004 Composent, Inc. and others. All rights reserved. This
* program and the accompanying materials are made available under the terms of
* the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: Composent, Inc. - initial API and implementation
******************************************************************************/
package org.eclipse.ecf.core.sharedobject.util;
/**
* Queue that includes both enqueue ({@link IQueueEnqueue}) and dequeue ({@link IQueueDequeue})
* operations
*
* @see IQueueEnqueue
* @see IQueueDequeue
*/
public interface IQueue extends IQueueDequeue, IQueueEnqueue {
// no methods
}
| [
"[email protected]"
] | |
9ccfb36357e465cce0a0e4f76f730c9aa0fdb002 | 53061544ded8e62116e9f86dbdb5f4bd647f4f9e | /HaravanProductsListDemo/gen/com/haravan/android/productlistdemo/R.java | b1cbd27cbad0443305ebedd7be7ce88ce43daa8c | [
"MIT"
] | permissive | LeeU1911/haravan_java_api | 7df0987d6d8a54b1cd17e72c0b47c9a0c3be98cb | 18d6dbf71d8bc77e09484898fb3dbb0e501ab935 | refs/heads/master | 2020-04-02T22:00:35.843112 | 2015-04-18T03:52:08 | 2015-04-18T03:52:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,485 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.haravan.android.productlistdemo;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class id {
public static final int addShopAuthorizeButton=0x7f050003;
public static final int addShopShopname=0x7f050001;
public static final int shopNameHeading=0x7f050000;
public static final int showProductsCountView=0x7f050004;
public static final int textView1=0x7f050002;
}
public static final class layout {
public static final int add_shop_screen=0x7f030000;
public static final int main=0x7f030001;
}
public static final class string {
public static final int app_name=0x7f040001;
public static final int authorize=0x7f040007;
public static final int dot_myharavan_dot_com=0x7f040005;
public static final int hello=0x7f040000;
public static final int missingShopName=0x7f040008;
public static final int haravan_api_key=0x7f040002;
public static final int haravan_shared_secret=0x7f040003;
public static final int haravan_shop_name_heading=0x7f040004;
public static final int haravan_shop_name_hint=0x7f040006;
}
}
| [
"[email protected]"
] | |
408e42a866ac74df05f376a6fa3fb93c784726ba | ed20f3fa2f95fb97d3abed76f68a51b051516b8c | /app/src/main/java/com/example/silviu086/licenta/CalatoriiAdaugateConfirmareTask.java | 4f34a985fbf88bfa04930ed72ad5df4c40b56de3 | [] | no_license | silviu086/Ridesharing | b3588b694f704ea2d0cef3b6a9acc2ddd377af28 | 0109429b3213881e35215b4bde4ef9f472917303 | refs/heads/master | 2021-01-20T21:16:09.145902 | 2016-11-12T12:04:55 | 2016-11-12T12:04:55 | 59,952,810 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,341 | java | package com.example.silviu086.licenta;
import android.app.ProgressDialog;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Silviu086 on 24.06.2016.
*/
public class CalatoriiAdaugateConfirmareTask extends AsyncTask<String, Integer, String> {
private String calatorieId;
private String pasagerId;
//private ProgressDialog progressDialog;
private TaskCompleted taskCompleted;
public CalatoriiAdaugateConfirmareTask(String calatorieId, String pasagerId, TaskCompleted taskCompleted) {
this.calatorieId = calatorieId;
this.pasagerId = pasagerId;
//this.progressDialog = progressDialog;
this.taskCompleted = taskCompleted;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
taskCompleted.onTaskCompleted(result);
}
@Override
protected String doInBackground(String... params) {
try{
URL url = new URL(UrlLinks.URL_CONFIRMA_CERERE);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
String query = new Uri.Builder()
.appendQueryParameter("id_calatorie", calatorieId)
.appendQueryParameter("id_pasager", pasagerId)
.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while( (line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
is.close();
conn.disconnect();
JSONObject json = new JSONObject(sb.toString());
int success = json.getInt("success");
if(success == 1){
url = new URL(UrlLinks.URL_GCM_MESSAGE);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.connect();
query = new Uri.Builder()
.appendQueryParameter("id_destinatar", String.valueOf(pasagerId))
.appendQueryParameter("id_expeditor", String.valueOf(NavigationActivity.account.getId()))
.appendQueryParameter("id_calatorie", String.valueOf(calatorieId))
.appendQueryParameter("type", "1").build().getEncodedQuery();
os = con.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
is = con.getInputStream();
reader = new BufferedReader(new InputStreamReader(is));
sb = new StringBuilder();
while( (line = reader.readLine()) != null){
sb.append(line);
}
Log.i("CalatoriiAdaugateConfir", sb.toString());
reader.close();
is.close();
con.disconnect();
return "success";
} else{
return "failed";
}
}catch (Exception ex){
Log.e("ConfirmareTask: ", ex.toString());
}
return "null";
}
}
| [
"[email protected]"
] | |
a410753751d001e1b1bc32d0612f76a1dcf0c458 | 2951adff191c1abc589cfc680f9e638d92d97595 | /wg-client-simple/src/main/java/com/fjut/view/component/FormManagerPanel.java | 1f06fb0a2bb3bbbb9cdc8d30fa8f3bfa1b4d2000 | [
"MIT"
] | permissive | Denjor/software-demo | 9bb9e3fa7eaf66a9aba502cc1613e9be3e834361 | de003054404232a8068d6cf5156b5e923b6ec1d3 | refs/heads/master | 2020-05-20T18:23:25.484993 | 2019-07-31T02:42:37 | 2019-07-31T02:42:37 | 185,705,316 | 0 | 0 | MIT | 2019-07-31T02:42:39 | 2019-05-09T01:37:38 | Java | UTF-8 | Java | false | false | 8,033 | java | package com.fjut.view.component;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.fjut.pojo.Materials;
import com.fjut.pojo.vo.ComboxVo;
import com.fjut.service.MaterialsSellDetailService;
import com.fjut.service.MaterialsSellService;
import com.fjut.service.MaterialsService;
import com.fjut.util.MD5Util;
import com.fjut.util.POIUtil;
import com.fjut.util.SpringContextUtils;
import com.fjut.view.page.MaterialsBillPrintPage;
import com.fjut.view.page.MaterialsInOutPrintPage;
/**
* 报表管理面板
* @Scope("prototype") 设置为动态创建,每调用一次当前类就创建一次
* @Component("FormManagerPanel") 设置当前为组件
* @Lazy 设置为懒加载
*/
@Lazy
@Scope("prototype")
@Component("FormManagerPanel")
@SuppressWarnings("all")
public class FormManagerPanel extends JPanel {
private JPanel chartPanel;
private MaterialsService materialsService = SpringContextUtils.getBean(MaterialsService.class);
private MaterialsSellService materialsSellService = SpringContextUtils.getBean(MaterialsSellService.class);
private MaterialsSellDetailService materialsSellDetailService = SpringContextUtils.getBean(MaterialsSellDetailService.class);
/**
* Create the panel.
*/
public FormManagerPanel() {
setBounds(0, 0, 1165, 730);
setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(Color.LIGHT_GRAY));
panel.setBounds(10, 76, 1145, 624);
add(panel);
panel.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBorder(BorderFactory.createTitledBorder("报表查看"));
panel_1.setBounds(10, 49, 1125, 525);
panel.add(panel_1);
panel_1.setLayout(new BorderLayout(0, 0));
JLabel label_3 = new JLabel("物料");
label_3.setBounds(10, 14, 54, 15);
panel.add(label_3);
JComboBox materialsComboBox = new JComboBox();
materialsComboBox.setBounds(40, 11, 97, 21);
panel.add(materialsComboBox);
JLabel label = new JLabel("年份");
label.setBounds(147, 15, 54, 15);
panel.add(label);
JComboBox yearComboBox = new JComboBox();
yearComboBox.setBounds(182, 12, 97, 21);
panel.add(yearComboBox);
JLabel label_1 = new JLabel("月份区间");
label_1.setBounds(289, 15, 54, 15);
panel.add(label_1);
JComboBox monthComBox1 = new JComboBox();
monthComBox1.setBounds(345, 12, 62, 21);
panel.add(monthComBox1);
JLabel label_2 = new JLabel("-");
label_2.setBounds(412, 15, 24, 15);
panel.add(label_2);
JComboBox monthComBox2 = new JComboBox();
monthComBox2.setBounds(422, 12, 62, 21);
panel.add(monthComBox2);
JButton lookBtn = new JButton("查看");
//查看图表
lookBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ComboxVo material = (ComboxVo) materialsComboBox.getSelectedItem();
//获取时间区间
String year = (String) yearComboBox.getSelectedItem();
int month1 = (int) monthComBox1.getSelectedItem();
int month2 = (int) monthComBox2.getSelectedItem();
if(month1 > month2) {
JOptionPane.showMessageDialog(null, "月份区间选择错误", "提示", JOptionPane.ERROR_MESSAGE);
return;
}
//删除原有图标
if(chartPanel != null) panel_1.remove(chartPanel);
//创建新的报表
chartPanel = ChartComponent.getChartPanel(material.getKey(), year, month1, month2);
panel_1.add(chartPanel);
//刷新
panel_1.validate();
}
});
lookBtn.setBounds(597, 10, 93, 23);
panel.add(lookBtn);
JButton saveBtn = new JButton("保存图片");
saveBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ComboxVo material = (ComboxVo) materialsComboBox.getSelectedItem();
String year = (String) yearComboBox.getSelectedItem();
int month1 = (int) monthComBox1.getSelectedItem();
int month2 = (int) monthComBox2.getSelectedItem();
if(month1 > month2) {
JOptionPane.showMessageDialog(null, "月份区间选择错误", "提示", JOptionPane.ERROR_MESSAGE);
return;
}
JFileChooser jFileChooser = new JFileChooser();
jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
jFileChooser.showSaveDialog(null);
//获取保存目录
File selectedFile = jFileChooser.getSelectedFile();
if(selectedFile != null) {
File file = new File(selectedFile.getAbsoluteFile() + "/" + MD5Util.getMD5() + ".png");
if(ChartComponent.saveChartPNG(file, material.getKey(), year, month1, month2)) {
JOptionPane.showMessageDialog(null, "保存成功", "提示", JOptionPane.INFORMATION_MESSAGE);
}else {
JOptionPane.showMessageDialog(null, "保存失败", "提示", JOptionPane.ERROR_MESSAGE);
}
}
}
});
saveBtn.setBounds(803, 10, 93, 23);
panel.add(saveBtn);
JButton lookBigBtn = new JButton("大图查看");
lookBigBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ComboxVo material = (ComboxVo) materialsComboBox.getSelectedItem();
String year = (String) yearComboBox.getSelectedItem();
int month1 = (int) monthComBox1.getSelectedItem();
int month2 = (int) monthComBox2.getSelectedItem();
if(month1 > month2) {
JOptionPane.showMessageDialog(null, "月份区间选择错误", "提示", JOptionPane.ERROR_MESSAGE);
return;
}
//创建一个Frame窗口用于显示创建的Chart图表
ChartComponent.createChartFrame(material.getKey(), year, month1, month2);
}
});
lookBigBtn.setBounds(700, 10, 93, 23);
panel.add(lookBigBtn);
JButton btnNewButton = new JButton("打印进出仓订单");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//显示打印进出仓订单界面
new MaterialsInOutPrintPage().setVisible(true);
}
});
btnNewButton.setBounds(10, 20, 143, 43);
add(btnNewButton);
JButton button_1 = new JButton("打印仓库账本");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//显示打印仓库账本
new MaterialsBillPrintPage().setVisible(true);
}
});
button_1.setBounds(173, 20, 143, 43);
add(button_1);
//初始化
init(materialsComboBox, yearComboBox, monthComBox1, monthComBox2);
JButton flushBtn = new JButton("刷新");
flushBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//重新加载数据
init(materialsComboBox, yearComboBox, monthComBox1, monthComBox2);
}
});
flushBtn.setBounds(494, 10, 93, 23);
panel.add(flushBtn);
}
/**
* 初始化
* @param materialsComboBox
* @param yearComboBox
* @param monthComBox1
* @param monthComBox2
*/
public void init(JComboBox materialsComboBox, JComboBox yearComboBox, JComboBox monthComBox1, JComboBox monthComBox2) {
//清空
materialsComboBox.removeAllItems();
yearComboBox.removeAllItems();
monthComBox1.removeAllItems();
monthComBox2.removeAllItems();
List<Materials> materialList = materialsService.getAllMaterialList();
if(materialList != null) {
for (Materials materials : materialList) {
materialsComboBox.addItem(new ComboxVo(materials.getId(), materials.getMaterialsName()));
}
}
List<String> years = materialsSellService.getAllYear();
if(years != null) {
for (String year : years) {
yearComboBox.addItem(year);
}
}
for (int i = 1; i <= 12; i++) {
monthComBox1.addItem(i);
monthComBox2.addItem(i);
}
}
}
| [
"[email protected]"
] | |
04a5791a994f2daa29bf26e36b3cb4d3e66f7642 | 136c729ec3c3a584e21be74b88fb28df09be3a74 | /src/main/java/com/qa/democart/utils/ElementUtil.java | 2edd684ac33f89d46d9016583b89b4d0c3a5631c | [] | no_license | abhhi12/abhhi12_Oct2020EvePOMSeries | 73e35a58124762000ad0a57827bdd50664c1f37d | 0e4443e684d61e30686a648c9ac16d93b6419932 | refs/heads/master | 2023-02-27T03:40:06.910875 | 2021-02-01T10:25:19 | 2021-02-01T10:25:19 | 332,516,938 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,828 | java | package com.qa.democart.utils;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ElementUtil {
private WebDriver driver;
public ElementUtil(WebDriver driver) {
this.driver = driver;
}
public WebElement getElement(By locator) {
return driver.findElement(locator);
}
public List<WebElement> getElements(By locator) {
return driver.findElements(locator);
}
public void doClick(By locator) {
getElement(locator).click();
}
public void doSendKeys(By locator, String value) {
WebElement element=getElement(locator);
element.clear();//is liye q ki jab new search karege to har baar new value le ga clear kar k nahi to search overwrirte hota rahega
element.sendKeys(value);
}
public void doActionsSendKeys(By locator, String value) {
Actions action = new Actions(driver);
action.moveToElement(getElement(locator)).sendKeys(value).build().perform();
}
public void doActionsClick(By locator) {
Actions action = new Actions(driver);
action.moveToElement(getElement(locator)).click().build().perform();
}
public void doMoveToElement(By locator) {
Actions action = new Actions(driver);
action.moveToElement(getElement(locator)).perform();
}
public void clickOnSubMenu(By parentMenu, By firstSubMenu) throws InterruptedException {
doMoveToElement(parentMenu);
Thread.sleep(2000);
doActionsClick(firstSubMenu);
}
public void clickOnSubMenu(By parentMenu, By firstSubMenu, By secondSubMenu) throws InterruptedException {
doMoveToElement(parentMenu);
Thread.sleep(2000);
doMoveToElement(firstSubMenu);
Thread.sleep(2000);
doActionsClick(secondSubMenu);
}
public String doGetText(By locator) {
return getElement(locator).getText();
}
public String doGetAttribute(By locator, String attributeName) {
return getElement(locator).getAttribute(attributeName);
}
public boolean doIsDisplayed(By locator) {
return getElement(locator).isDisplayed();
}
public boolean checkElementPresent(By locator) {
if (getElements(locator).size()>0) {
return true;
}
return false;
}
public void clickElement(By locator, String value) {
List<WebElement> eleList = getElements(locator);
System.out.println(eleList.size());
for (int i = 0; i < eleList.size(); i++) {
String text = eleList.get(i).getText();
System.out.println(text);
if (text.equals(value)) {
eleList.get(i).click();
break;
}
}
}
//************************************Drop Down Utils *******************************
//Select class Dropdown utils:
public void doSelectByIndex(By locator, int index) {
Select select = new Select(getElement(locator));
select.selectByIndex(index);
}
public void doSelectByVisibleText(By locator, String text) {
Select select = new Select(getElement(locator));
select.selectByVisibleText(text);
}
public void doSelectByValue(By locator, String value) {
Select select = new Select(getElement(locator));
select.selectByValue(value);
}
public List<String> getDropDownOptionsValues(By locator) {
List<String> optionsValList = new ArrayList<>();
Select select = new Select(getElement(locator));
List<WebElement> optionsList = select.getOptions();
for (WebElement e : optionsList) {
String text = e.getText();
optionsValList.add(text);
}
return optionsValList;
}
public void selectDropDownValue(By locator, String value) {
List<WebElement> optionsList = getElements(locator);
for (WebElement e : optionsList) {
String text = e.getText();
if (text.equals(value)) {
e.click();
break;
}
}
}
//************************wait utils *************************
public List<WebElement> VisibilityOffAllElemsnts(By locator, int timeOut) {
WebDriverWait wait = new WebDriverWait(driver, timeOut);
return wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(locator));
}
public void getPageElementsText(By locator, int timeOut) {
VisibilityOffAllElemsnts(locator, timeOut).stream().forEach(ele -> System.out.println(ele.getText()));
}
/**presenceOfElementLocated:
* An expectation for checking that an element is present on the DOM of a page.
* This does not necessarily mean that the element is visible.
*/
public WebElement waitForElementPresent(By locator, int timeOut) {
WebDriverWait wait = new WebDriverWait(driver, timeOut);
return wait.until(ExpectedConditions.presenceOfElementLocated(locator));
}
/**
* An expectation for checking that an element, known to be present on the DOM of a page, is visible.
* Visibility means that the element is not only displayed but also has a height and width
* that is greater than 0.
* @param locator
* @param timeOut
* @return
*/
public WebElement waitForElementVisible(By locator, int timeOut) {
WebDriverWait wait = new WebDriverWait(driver, timeOut);
return wait.until(ExpectedConditions.visibilityOf(getElement(locator)));
}
public boolean waitForUrlToBe(String urlValue, int timeOut) {
WebDriverWait wait = new WebDriverWait(driver, timeOut);
return wait.until(ExpectedConditions.urlContains(urlValue));
}
/**
* An exception for checking an element is visible and enabled such that you can click on it.
* @param locator
* @param timeOut
*/
public void clickWhenReady(By locator, int timeOut) {
WebDriverWait wait = new WebDriverWait(driver, timeOut);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(locator));
element.click();
}
public Alert waitForAlert(int timeOut) {
WebDriverWait wait = new WebDriverWait(driver, timeOut);
return wait.until(ExpectedConditions.alertIsPresent());
}
public void acceptJSAlert(int timeOut) {
waitForAlert(timeOut).accept();
}
public void dismissJSAlert(int timeOut) {
waitForAlert(timeOut).dismiss();
}
public String getAlertText(int timeOut) {
return waitForAlert(timeOut).getText();
}
public String waitForTitleToBe(String title, int timeOut) {
WebDriverWait wait = new WebDriverWait(driver, timeOut);
wait.until(ExpectedConditions.titleContains(title));
return driver.getTitle();
}
/**
* This Method is checking the presence of element using FluentWait
* @param locator
* @param timeOut
* @param pollingTime
* @return
*/
public WebElement WaitForElementFluentWait(By locator, int timeOut, int pollingTime) {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(timeOut))
.pollingEvery(Duration.ofSeconds(pollingTime))
.ignoring(NoSuchElementException.class)
.ignoring(StaleElementReferenceException.class);
return wait.until(ExpectedConditions.presenceOfElementLocated(locator));
}
/**
* This Method is checking the presence of element using FluentWait
* @param locator
* @param timeOut
* @return
*/
public WebElement WaitForElementFluentWait(By locator, int timeOut) {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(timeOut))
.ignoring(NoSuchElementException.class)
.ignoring(StaleElementReferenceException.class);
return wait.until(ExpectedConditions.presenceOfElementLocated(locator));
}
/**
* This method check the page is fully loaded or not
* @param timeOut
*/
public void jsWaitForPageLoad(int timeOut) {
JavascriptExecutor jse = ((JavascriptExecutor)driver);
String jsCommand = "return document.readyState";
if(jse.executeScript(jsCommand).toString().equals("complete")) {
System.out.println("Page is fully loaded");
return;
}
for(int i=0; i<timeOut; i++) {
try {
Thread.sleep(500);//500 is milisecond
if(jse.executeScript(jsCommand).toString().equals("complete")) {
System.out.println("Page is fully loaded");
break;
}
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
| [
"[email protected]"
] | |
ad40093520b99d04cbbef260cd5fb3b18b88934d | d5d514372741662d76f66a13bd72dec0c78e0d58 | /6-12 (2)/src/DicServerFrame.java | 4c931729200a40bf64b42f3bd90af60ddba6702e | [] | no_license | heoshun/java | 4b826eeca2cf68beb3ba102a1c611f7e08d6ed13 | d10810d08fd23ed893dff3deace9473da9749008 | refs/heads/master | 2020-04-29T01:36:12.720034 | 2019-06-19T07:35:40 | 2019-06-19T07:35:40 | 175,736,130 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 1,399 | java | import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
public class DicServerFrame extends JFrame {
private JTextField eng = new JTextField(10);
private JTextField kor = new JTextField(10);
private JButton saveBtn = new JButton("저장");
private JButton searchBtn = new JButton("찾기");
private JTextArea ta = new JTextArea(7, 25);
private HashMap<String, String> dic = new HashMap<String, String>();
public DicServerFrame() {
super("Dic Server");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(350, 300);
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(new JLabel("영어"));
c.add(eng);
c.add(new JLabel("한글"));
c.add(kor);
c.add(saveBtn);
c.add(searchBtn);
saveBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ta.append("삽입 ("+eng.getText()+"." +kor.getText()
dic.put(eng.getText(), kor.getText());
}
});
searchBtn.addActionListener(new ActionListener) {
} | [
"USER@AMP-24"
] | USER@AMP-24 |
9e00ef468d43943bd0f17359eefb1e3d4a6eee10 | 2370f5580c5a7ad14cdbafb64c190b592504e515 | /org.tencompetence.ldauthor/src/org/tencompetence/ldauthor/ui/views/inspector/IInspectorProvider.java | e8799e4f78bed1528396e1cb66f12ebfafd41f65 | [] | no_license | vicsanhu/ontoConcept | 317f844eb5bad73ffabe875287c3518cd6bf7a16 | eb89178a2612780a007d8d3325149b08655c87d8 | refs/heads/master | 2020-05-18T15:12:06.584603 | 2013-02-28T01:24:15 | 2013-02-28T01:24:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,104 | java | /*
* Copyright (c) 2007, Consortium Board TENCompetence
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the TENCompetence nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY CONSORTIUM BOARD TENCOMPETENCE ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CONSORTIUM BOARD TENCOMPETENCE BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.tencompetence.ldauthor.ui.views.inspector;
import org.eclipse.core.runtime.IAdaptable;
/**
* Interface to signify a View or Editor or Window that uses the Inspector
* Implementers must over-ride Object getAdapter(Class adapter) to return a handle to
* the currently selected ILDMultiPageEditor
*
*
*
* @author Phillip Beauvoir
* @version $Id: IInspectorProvider.java,v 1.2 2009/06/20 17:28:20 phillipus Exp $
*/
public interface IInspectorProvider extends IAdaptable {
}
| [
"[email protected]"
] | |
785dfa1798de6011ebf8cc45600a32a9f7f379d1 | 5192a590c3927fbf686b53e0e2a8e649b9605e3d | /src/thirtyDaysOfCode/day12/Inheritance1/MySuperclass.java | 7126653bfd28097b1f8833f109c2891af2e0ca99 | [] | no_license | elcioishizuka/hackerRank-practice | 3942d0f07f1aa8eb37df003c2c2a909f2026c9de | e15e571cd642bd4e9fc28c4f58ab19067e390ff4 | refs/heads/master | 2023-03-18T06:54:41.000938 | 2021-03-11T00:31:42 | 2021-03-11T00:31:42 | 338,342,974 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 381 | java | package thirtyDaysOfCode.day12.Inheritance1;
// Superclass
class MySuperclass {
// Superclass' instance variable:
String myString;
// Superclass' default (empty) constructor:
MySuperclass() {
}
// Superclass' parameterized constructor:
MySuperclass(String myString) {
// Initialize instance variable
this.myString = myString;
}
}
| [
"[email protected]"
] | |
8a784365e79b02a6fea8398f54dc251521186e27 | 4f503a4c5faa32c0225767f5403fb1892b743357 | /PremiereApplication/src/JavaPremiereDBSQLSecurityApp/ViewMyCustomerData.java | abb578e2cf7e031c22cf21d295aba1bd789c6100 | [] | no_license | mgelbfis/PremiereInventoryApplication_MCIN616-FinalProject | e3e0cd1a7f1de1a1644c3f8dadd49cd7835b722f | 4aa55533da526084f1707afc1b16a55a8a7099f1 | refs/heads/master | 2021-07-23T18:46:48.401315 | 2017-10-30T11:29:48 | 2017-10-30T11:29:48 | 108,841,257 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,721 | java | package JavaPremiereDBSQLSecurityApp;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
public class ViewMyCustomerData extends JFrame {
private final int WINDOW_WIDTH = 800;
private final int WINDOW_HEIGHT = 800;
private JPanel custPanel;
private Connection dbConnection;
public ViewMyCustomerData(Connection dbConnection) {
// store the reference to the database --- back end
this.dbConnection = dbConnection;
// verify that a databse connection exists
if (this.dbConnection == null) {
JOptionPane.showMessageDialog(null, "missing database connection --- contact IT");
} else { // continue with this process
this.custPanel = new JPanel();
custPanel.setLayout(new GridLayout(3,2));
setTitle("Veiw My Customer Data");
// set window size
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
// Specify an action for the close button.
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// set up layout of the window
setLayout(new BorderLayout());
String getEmpData = "select * from CustomerData";
Statement sqlStatement = null;
try{
sqlStatement = dbConnection.createStatement();
//execute the query
ResultSet rs = sqlStatement.executeQuery(getEmpData);
JTable table = new JTable(buildTableModel(rs));
add(new JScrollPane(table));
pack();
setVisible(true);
System.out.println(this.getClass());
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
public DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
}
| [
"[email protected]"
] | |
59a49a6b5c7c4260d487e412ae24b1983c511fbc | b7a6fa209f09e1da9aa23019869e311a6af8252e | /app/src/main/java/com/ravijain/sankalp/fragments/SpPeriodDialog.java | e2c48a3ec91aab38ae0ee0f4b50be73659e32c4f | [] | no_license | ravi-jain/SankalpRepository | 9b356e2206969c028fb07b893f8a97a1e6527d86 | f18a8287542182b21a917c382f4825f6b5ca2aee | refs/heads/master | 2020-04-12T09:35:48.014782 | 2017-10-22T05:19:48 | 2017-10-22T05:19:48 | 62,598,690 | 0 | 0 | null | 2017-10-22T05:19:48 | 2016-07-05T02:05:36 | Java | UTF-8 | Java | false | false | 6,176 | java | package com.ravijain.sankalp.fragments;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.NumberPicker;
import android.widget.TextView;
import com.ravijain.sankalp.R;
import com.ravijain.sankalp.support.SpConstants;
import com.ravijain.sankalp.support.SpCalendarViewHandler;
import com.ravijain.sankalp.support.SpDateUtils;
import java.util.Calendar;
import java.util.Date;
/**
* Created by ravijain on 9/1/2016.
*/
public class SpPeriodDialog extends DialogFragment implements View.OnClickListener {
private Date _fromDate, _toDate;
//private CaldroidFragment _calViewFragment;
private SpCalendarViewHandler _calendarView;
private int _periodKey = SpConstants.INTENT_VALUE_SANKALP_LIST_FILTER_DAY;
private NumberPicker _monthPicker, _yearPicker;
private SpAddSankalpFragment _parentFragment;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.period_dialog, container, false);
v.findViewById(R.id.pd_ok_action).setOnClickListener(this);
v.findViewById(R.id.pd_cancel_action).setOnClickListener(this);
Bundle b = getArguments();
if (b != null) {
_periodKey = b.getInt(SpConstants.INTENT_KEY_SANKALP_PERIOD, SpConstants.INTENT_VALUE_SANKALP_LIST_FILTER_DAY);
}
String periodTitle = getString(R.string.selectPeriod);
if (_periodKey == SpConstants.INTENT_VALUE_SANKALP_LIST_FILTER_DAY) {
periodTitle = getString(R.string.selectDay);
_setUpCalendarForDay(v);
} else if (_periodKey == SpConstants.INTENT_VALUE_SANKALP_LIST_FILTER_MONTH) {
periodTitle = getString(R.string.selectMonth);
_setUpMonthYearPicker(v);
} else if (_periodKey == SpConstants.INTENT_VALUE_SANKALP_LIST_FILTER_YEAR) {
periodTitle = getString(R.string.selectYear);
_setUpYearPicker(v);
} else if (_periodKey == SpConstants.INTENT_VALUE_SANKALP_LIST_FILTER_RANGE) {
periodTitle = getString(R.string.selectInterval);
_setUpCalendarForRange(v);
}
((TextView) v.findViewById(R.id.period_title)).setText(periodTitle);
return v;
}
private void _setUpCalendarForDay(View v) {
v.findViewById(R.id.period_calendarView).setVisibility(View.VISIBLE);
_calendarView = new SpCalendarViewHandler(getContext(), v);
_calendarView.constructCalendar(R.id.period_calendar, SpCalendarViewHandler.SELECTION_MODE_SINGLE);
}
private void _setUpCalendarForRange(View v) {
v.findViewById(R.id.period_calendarView).setVisibility(View.VISIBLE);
_calendarView = new SpCalendarViewHandler(getContext(), v);
_calendarView.constructCalendar(R.id.period_calendar, SpCalendarViewHandler.SELECTION_MODE_RANGE);
}
private void _setUpYearPicker(View v) {
v.findViewById(R.id.year_picker_ll).setVisibility(View.VISIBLE);
Calendar c = Calendar.getInstance();
_yearPicker = (NumberPicker) v.findViewById(R.id.year_picker_solo);
_yearPicker.setWrapSelectorWheel(true);
_yearPicker.setMaxValue(2100);
_yearPicker.setMinValue(1900);
_yearPicker.setValue(c.get(Calendar.YEAR));
}
private void _setUpMonthYearPicker(View v) {
v.findViewById(R.id.month_year_picker).setVisibility(View.VISIBLE);
Calendar c = Calendar.getInstance();
_monthPicker = (NumberPicker) v.findViewById(R.id.month_picker);
_monthPicker.setWrapSelectorWheel(true);
_monthPicker.setMaxValue(11);
_monthPicker.setMinValue(0);
_monthPicker.setValue(c.get(Calendar.MONTH));
_monthPicker.setDisplayedValues(SpDateUtils.getMonthStrings());
_yearPicker = (NumberPicker) v.findViewById(R.id.year_picker);
_yearPicker.setWrapSelectorWheel(true);
_yearPicker.setMaxValue(2100);
_yearPicker.setMinValue(1900);
_yearPicker.setValue(c.get(Calendar.YEAR));
}
public void onStart() {
super.onStart();
getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.pd_ok_action) {
if (_periodKey == SpConstants.INTENT_VALUE_SANKALP_LIST_FILTER_DAY || _periodKey == SpConstants.INTENT_VALUE_SANKALP_LIST_FILTER_RANGE) {
if (_calendarView != null) {
Date[] dates = _calendarView.getRangeDates();
_fromDate = SpDateUtils.beginOfDate(dates[0]);
_toDate = SpDateUtils.endOfDate(dates[1]);
}
} else if (_periodKey == SpConstants.INTENT_VALUE_SANKALP_LIST_FILTER_MONTH) {
if (_monthPicker != null && _yearPicker != null) {
int month = _monthPicker.getValue();
int year = _yearPicker.getValue();
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, month);
c.set(Calendar.YEAR, year);
_fromDate = SpDateUtils.beginOfMonth(c);
_toDate = SpDateUtils.endOfMonth(c);
}
} else if (_periodKey == SpConstants.INTENT_VALUE_SANKALP_LIST_FILTER_YEAR) {
if (_yearPicker != null) {
int year = _yearPicker.getValue();
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
_fromDate = SpDateUtils.beginOfYear(c);
_toDate = SpDateUtils.endOfYear(c);
}
}
_parentFragment.setPeriod(_fromDate, _toDate);
dismiss();
} else {
dismiss();
}
}
public void setParentFragment(SpAddSankalpFragment parentFragment) {
this._parentFragment = parentFragment;
}
}
| [
"[email protected]"
] | |
3402afc296ef0cc1c193c00e5242afd99ac5a780 | 4572750d1e660a6fa06b075489ee5bc6d80c9aed | /app/src/main/java/com/example/ae/yourhub/LikeList.java | 02024fe390fa68af6541afe9a5ffa0e23dbb1a0d | [] | no_license | nilevars/Yourhub2 | ca7b65c85460a12c6dded2849c8a82262424c65e | 82e00df34692b3e503b42bbde70c1010b563df44 | refs/heads/master | 2021-06-04T03:53:31.201213 | 2020-09-05T08:04:46 | 2020-09-05T08:04:46 | 123,288,285 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,198 | java | package com.example.ae.yourhub;
import android.content.Context;
import android.util.Log;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
/**
* Created by A E on 15-May-17.
*/
public class LikeList {
String userid,postid,like;
boolean result=false;
private static final String REGISTER_URL = "http://q8hub.com/yourhub/forum/like_insert.php";
private static final String REGISTER_URL2 = "http://q8hub.com/yourhub/forum/like_check.php";
public static final String KEY_POST = "post_id";
public static final String KEY_CHOICE = "choice";
public static final String KEY_USER = "user_id";
Context context;
Session session;
LikeList(Context c, String postid)
{
this.postid=postid;
context=c;
session=new Session(context);
}
LikeList(Context c, String postid, String like)
{
this.postid=postid;
this.like=like;
context=c;
session=new Session(context);
}
boolean insert()
{
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
Log.e("insert response",response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_POST,postid);
params.put(KEY_CHOICE, like);
params.put(KEY_USER, session.getid());
System.out.println("params:"+params.toString());
Log.e("Insert params", params.toString());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
return true;
}
boolean checkLike()
{
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, REGISTER_URL2,
new Response.Listener<String>(){
@Override
public void onResponse(String response){
//Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
Log.e("response",response);
if(response.equals("yes"))
{
result=true;
Log.e("result",""+result);
}
}
},
new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
Log.e("r error",error.toString());
//Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_POST,postid);
params.put(KEY_USER, session.getid());
System.out.println("params:"+params.toString());
Log.e("Insert params", params.toString());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
return true;
}
boolean testlike()
{
return result;
}
}
| [
"[email protected]"
] | |
7a85123ff77b89e26eb9c447421d95c3211ea36f | 05e36f74a4a82a22ff8dcb03e83555c0b5c9cf7e | /app/src/main/java/com/mukeshkpdeveloper/mytask/UI/fragments/PostFragment.java | 45ec1feae0788c3dbd722f290f76e139cc0cd43a | [] | no_license | mukeshkumar7470/MyTask-HackerKernel | cef1a0bbd4cdf0d667a317ac6df4e77672c3f9bf | 76bdb67bb9e0b1218940d83863725e6ab1dfcfc3 | refs/heads/master | 2023-06-28T08:31:50.738002 | 2021-07-30T07:54:20 | 2021-07-30T07:54:20 | 390,948,872 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,285 | java | package com.mukeshkpdeveloper.mytask.UI.fragments;
import android.content.Context;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.facebook.shimmer.ShimmerFrameLayout;
import com.mukeshkpdeveloper.mytask.R;
import com.mukeshkpdeveloper.mytask.adapters.PostsAdapter;
import com.mukeshkpdeveloper.mytask.models.PostsModel;
import com.mukeshkpdeveloper.mytask.networking.ApiInterface;
import com.mukeshkpdeveloper.mytask.utils.Constant;
import com.mukeshkpdeveloper.mytask.utils.Util;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class PostFragment extends Fragment {
RecyclerView rvPosts;
Context context;
private ArrayList<PostsModel> recyclerDataArrayList;
private PostsAdapter recyclerViewAdapter;
ProgressBar mprogressBar;
private ShimmerFrameLayout mFrameLayout;
public PostFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_post, container, false);
context =getActivity();
rvPosts = view.findViewById(R.id.rv_posts);
// mprogressBar = view.findViewById(R.id.progress_bar);
mFrameLayout =view.findViewById(R.id.shimmerLayout);
// call api
getPosts();
return view;
}
private void getPosts() {
if (Util.isNetworkAvailable(context)) {
// mprogressBar.setVisibility(View.VISIBLE);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.POST_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface retrofitAPI = retrofit.create(ApiInterface.class);
Call<ArrayList<PostsModel>> call = retrofitAPI.getPostList();
call.enqueue(new Callback<ArrayList<PostsModel>>() {
@Override
public void onResponse(Call<ArrayList<PostsModel>> call, Response<ArrayList<PostsModel>> response) {
// inside on response method we are checking
// if the response is success or not.
// mprogressBar.setVisibility(View.GONE);
if (response.code() == 200) {
recyclerDataArrayList = response.body();
// below line we are running a loop to add data to our adapter class.
for (int i = 0; i < recyclerDataArrayList.size(); i++) {
recyclerViewAdapter = new PostsAdapter(recyclerDataArrayList, context);
LinearLayoutManager manager = new LinearLayoutManager(context);
rvPosts.setLayoutManager(manager);
rvPosts.setAdapter(recyclerViewAdapter);
}
mFrameLayout.startShimmer();
mFrameLayout.setVisibility(View.GONE);
rvPosts.setVisibility(View.VISIBLE);
}
}
@Override
public void onFailure(Call<ArrayList<PostsModel>> call, Throwable t) {
// in the method of on failure we are displaying a
// toast message for fail to get data.
Util.showProgressBar(context, false);
Toast.makeText(context, "Fail to get data", Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public void onResume() {
mFrameLayout.startShimmer();
super.onResume();
}
@Override
public void onPause() {
mFrameLayout.stopShimmer();
super.onPause();
}
} | [
"[email protected]"
] | |
4f6728be308534cf08381df86756013025f82e77 | 50add8286b791d2a1ed21f3fe807c1cf87d64173 | /kettle5.0.1-src-eclipse/ui/org/pentaho/di/ui/trans/dialog/TransDialog.java | 1eb318120a05b231d23948bb1b506641b9cc683e | [
"Apache-2.0"
] | permissive | Piouy/pentaho-kettle-serial | 418f63d981429eeab56160169deb0555a91008f6 | 5a915839de1ee5b0435f3fb6dbe9657f638d36a8 | refs/heads/master | 2021-09-10T06:11:54.094488 | 2018-03-21T09:58:15 | 2018-03-21T09:58:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 104,806 | java | /*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.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 org.pentaho.di.ui.trans.dialog;
import java.util.ArrayList;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.database.Database;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.ChannelLogTable;
import org.pentaho.di.core.logging.LogStatus;
import org.pentaho.di.core.logging.LogTableField;
import org.pentaho.di.core.logging.LogTableInterface;
import org.pentaho.di.core.logging.MetricsLogTable;
import org.pentaho.di.core.logging.PerformanceLogTable;
import org.pentaho.di.core.logging.StepLogTable;
import org.pentaho.di.core.logging.TransLogTable;
import org.pentaho.di.core.parameters.DuplicateParamException;
import org.pentaho.di.core.parameters.UnknownParamException;
import org.pentaho.di.core.plugins.PluginInterface;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryDirectory;
import org.pentaho.di.repository.RepositoryDirectoryInterface;
import org.pentaho.di.trans.TransDependency;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.TransMeta.TransformationType;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.steps.databaselookup.DatabaseLookupMeta;
import org.pentaho.di.trans.steps.tableinput.TableInputMeta;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.database.dialog.DatabaseDialog;
import org.pentaho.di.ui.core.database.dialog.SQLEditor;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.gui.WindowProperty;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.ComboVar;
import org.pentaho.di.ui.core.widget.FieldDisabledListener;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.repository.dialog.SelectDirectoryDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
public class TransDialog extends Dialog
{
public static final int LOG_INDEX_TRANS = 0;
public static final int LOG_INDEX_STEP = 1;
public static final int LOG_INDEX_PERFORMANCE = 2;
public static final int LOG_INDEX_CHANNEL = 3;
public static final int LOG_INDEX_METRICS = 4;
private static Class<?> PKG = TransDialog.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
public static enum Tabs { TRANS_TAB, PARAM_TAB, LOG_TAB, DATE_TAB, DEP_TAB, MISC_TAB, MONITOR_TAB, EXTRA_TAB, }
private CTabFolder wTabFolder;
private FormData fdTabFolder;
private CTabItem wTransTab, wParamTab, wLogTab, wDateTab, wDepTab, wMiscTab, wMonitorTab;
private Text wTransname;
private Text wTransFilename;
// Trans description
private Text wTransdescription;
private Label wlExtendeddescription;
private Text wExtendeddescription;
// Trans Status
private Label wlTransstatus;
private CCombo wTransstatus;
private FormData fdlTransstatus, fdTransstatus;
//Trans version
private Text wTransversion;
private FormData fdlExtendeddescription, fdExtendeddescription;
private Text wDirectory;
private Button wbDirectory;
private Text wCreateUser;
private Text wCreateDate;
private Text wModUser;
private Text wModDate;
private Button wbLogconnection;
private ComboVar wLogconnection;
private TextVar wLogSizeLimit;
private TextVar wLogTimeout;
private int previousLogTableIndex = -1;
private TableView wOptionFields;
private TextVar wLogTable;
private TextVar wLogSchema;
private TextVar wLogInterval;
private CCombo wMaxdateconnection;
private Text wMaxdatetable;
private Text wMaxdatefield;
private Text wMaxdateoffset;
private Text wMaxdatediff;
private TableView wFields;
private TableView wParamFields;
private Text wSizeRowset;
private Button wUniqueConnections;
private Button wOK, wGet, wSQL, wCancel;
private FormData fdGet;
private Listener lsOK, lsGet, lsSQL, lsCancel;
private TransMeta transMeta;
private Shell shell;
private SelectionAdapter lsDef;
private ModifyListener lsMod;
private Repository rep;
private PropsUI props;
private RepositoryDirectoryInterface newDirectory;
private int middle;
private int margin;
private String[] connectionNames;
private Button wShowFeedback;
private Text wFeedbackSize;
private TextVar wSharedObjectsFile;
private boolean sharedObjectsFileChanged;
private Button wManageThreads;
private boolean directoryChangeAllowed;
private Label wlDirectory;
private Button wEnableStepPerfMonitor;
private Text wStepPerfInterval;
private CCombo wTransformationType;
private Tabs currentTab = null;
protected boolean changed;
private List wLogTypeList;
private Composite wLogOptionsComposite;
private Composite wLogComp;
private TransLogTable transLogTable;
private PerformanceLogTable performanceLogTable;
private ChannelLogTable channelLogTable;
private StepLogTable stepLogTable;
private MetricsLogTable metricsLogTable;
private DatabaseDialog databaseDialog;
private SelectionAdapter lsModSel;
private TextVar wStepPerfMaxSize;
private ArrayList<TransDialogPluginInterface> extraTabs;
public TransDialog(Shell parent, int style, TransMeta transMeta, Repository rep, Tabs currentTab)
{
this(parent, style, transMeta, rep);
this.currentTab = currentTab;
}
public TransDialog(Shell parent, int style, TransMeta transMeta, Repository rep)
{
super(parent, style);
this.props = PropsUI.getInstance();
this.transMeta = transMeta;
this.rep = rep;
this.newDirectory = null;
directoryChangeAllowed=true;
changed=false;
// Create a copy of the trans log table object
//
transLogTable = (TransLogTable) transMeta.getTransLogTable().clone();
performanceLogTable = (PerformanceLogTable) transMeta.getPerformanceLogTable().clone();
channelLogTable = (ChannelLogTable) transMeta.getChannelLogTable().clone();
stepLogTable = (StepLogTable) transMeta.getStepLogTable().clone();
metricsLogTable = (MetricsLogTable) transMeta.getMetricsLogTable().clone();
}
public TransMeta open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
shell.setImage(GUIResource.getInstance().getImageTransGraph());
lsMod = new ModifyListener() { public void modifyText(ModifyEvent e) { changed=true; } };
lsModSel = new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { changed=true; } };
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(BaseMessages.getString(PKG, "TransDialog.Shell.Title"));
middle = props.getMiddlePct();
margin = Const.MARGIN;
wTabFolder = new CTabFolder(shell, SWT.BORDER);
props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB);
wTabFolder.setSimple(false);
addTransTab();
addParamTab();
addLogTab();
addDateTab();
addDepTab();
addMiscTab();
addMonitoringTab();
// See if there are any other tabs to be added...
extraTabs = new ArrayList<TransDialogPluginInterface>();
java.util.List<PluginInterface> transDialogPlugins = PluginRegistry.getInstance().getPlugins(TransDialogPluginType.class);
for (PluginInterface transDialogPlugin : transDialogPlugins) {
try {
TransDialogPluginInterface extraTab = (TransDialogPluginInterface) PluginRegistry.getInstance().loadClass(transDialogPlugin);
extraTab.addTab(transMeta, parent, wTabFolder);
extraTabs.add(extraTab);
} catch(Exception e) {
new ErrorDialog(shell, "Error", "Error loading transformation dialog plugin with id "+transDialogPlugin.getIds()[0], e);
}
}
fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.top = new FormAttachment(0, 0);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.bottom= new FormAttachment(100, -50);
wTabFolder.setLayoutData(fdTabFolder);
// THE BUTTONS
wOK=new Button(shell, SWT.PUSH);
wOK.setText(BaseMessages.getString(PKG, "System.Button.OK"));
wSQL=new Button(shell, SWT.PUSH);
wSQL.setText(BaseMessages.getString(PKG, "System.Button.SQL"));
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel"));
BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wSQL, wCancel }, Const.MARGIN, null);
// Add listeners
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
lsGet = new Listener() { public void handleEvent(Event e) { get(); } };
lsSQL = new Listener() { public void handleEvent(Event e) { sql(); } };
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
wOK.addListener (SWT.Selection, lsOK );
wGet.addListener (SWT.Selection, lsGet );
wSQL.addListener (SWT.Selection, lsSQL );
wCancel.addListener(SWT.Selection, lsCancel);
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wTransname.addSelectionListener( lsDef );
wTransdescription.addSelectionListener( lsDef );
wTransversion.addSelectionListener( lsDef );
wMaxdatetable.addSelectionListener( lsDef );
wMaxdatefield.addSelectionListener( lsDef );
wMaxdateoffset.addSelectionListener( lsDef );
wMaxdatediff.addSelectionListener( lsDef );
wSizeRowset.addSelectionListener( lsDef );
wUniqueConnections.addSelectionListener( lsDef );
wFeedbackSize.addSelectionListener( lsDef );
wStepPerfInterval.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
if (currentTab != null){
setCurrentTab(currentTab);
}else{
wTabFolder.setSelection(0);
}
getData();
BaseStepDialog.setSize(shell);
changed = false;
sharedObjectsFileChanged = false;
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return transMeta;
}
private DatabaseDialog getDatabaseDialog(){
if(databaseDialog != null){
return databaseDialog;
}
databaseDialog = new DatabaseDialog(shell);
return databaseDialog;
}
private void addTransTab()
{
//////////////////////////
// START OF TRANS TAB///
///
wTransTab=new CTabItem(wTabFolder, SWT.NONE);
wTransTab.setText(BaseMessages.getString(PKG, "TransDialog.TransTab.Label"));
Composite wTransComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wTransComp);
FormLayout transLayout = new FormLayout();
transLayout.marginWidth = Const.FORM_MARGIN;
transLayout.marginHeight = Const.FORM_MARGIN;
wTransComp.setLayout(transLayout);
// Transformation name:
Label wlTransname = new Label(wTransComp, SWT.RIGHT);
wlTransname.setText(BaseMessages.getString(PKG, "TransDialog.Transname.Label"));
props.setLook(wlTransname);
FormData fdlTransname = new FormData();
fdlTransname.left = new FormAttachment(0, 0);
fdlTransname.right= new FormAttachment(middle, -margin);
fdlTransname.top = new FormAttachment(0, margin);
wlTransname.setLayoutData(fdlTransname);
wTransname=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wTransname);
wTransname.addModifyListener(lsMod);
FormData fdTransname = new FormData();
fdTransname.left = new FormAttachment(middle, 0);
fdTransname.top = new FormAttachment(0, margin);
fdTransname.right= new FormAttachment(100, 0);
wTransname.setLayoutData(fdTransname);
// Transformation name:
Label wlTransFilename = new Label(wTransComp, SWT.RIGHT);
wlTransFilename.setText(BaseMessages.getString(PKG, "TransDialog.TransFilename.Label"));
props.setLook(wlTransFilename);
FormData fdlTransFilename = new FormData();
fdlTransFilename.left = new FormAttachment(0, 0);
fdlTransFilename.right= new FormAttachment(middle, -margin);
fdlTransFilename.top = new FormAttachment(wTransname, margin);
wlTransFilename.setLayoutData(fdlTransFilename);
wTransFilename=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wTransFilename);
wTransFilename.addModifyListener(lsMod);
FormData fdTransFilename = new FormData();
fdTransFilename.left = new FormAttachment(middle, 0);
fdTransFilename.top = new FormAttachment(wTransname, margin);
fdTransFilename.right= new FormAttachment(100, 0);
wTransFilename.setLayoutData(fdTransFilename);
wTransFilename.setEditable(false);
wTransFilename.setBackground(GUIResource.getInstance().getColorLightGray());
// Transformation description:
Label wlTransdescription = new Label(wTransComp, SWT.RIGHT);
wlTransdescription.setText(BaseMessages.getString(PKG, "TransDialog.Transdescription.Label"));
props.setLook(wlTransdescription);
FormData fdlTransdescription = new FormData();
fdlTransdescription.left = new FormAttachment(0, 0);
fdlTransdescription.right= new FormAttachment(middle, -margin);
fdlTransdescription.top = new FormAttachment(wTransFilename, margin);
wlTransdescription.setLayoutData(fdlTransdescription);
wTransdescription=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wTransdescription);
wTransdescription.addModifyListener(lsMod);
FormData fdTransdescription = new FormData();
fdTransdescription.left = new FormAttachment(middle, 0);
fdTransdescription.top = new FormAttachment(wTransFilename, margin);
fdTransdescription.right= new FormAttachment(100, 0);
wTransdescription.setLayoutData(fdTransdescription);
// Transformation Extended description
wlExtendeddescription = new Label(wTransComp, SWT.RIGHT);
wlExtendeddescription.setText(BaseMessages.getString(PKG, "TransDialog.Extendeddescription.Label"));
props.setLook(wlExtendeddescription);
fdlExtendeddescription = new FormData();
fdlExtendeddescription.left = new FormAttachment(0, 0);
fdlExtendeddescription.top = new FormAttachment(wTransdescription, margin);
fdlExtendeddescription.right = new FormAttachment(middle, -margin);
wlExtendeddescription.setLayoutData(fdlExtendeddescription);
wExtendeddescription = new Text(wTransComp, SWT.MULTI | SWT.LEFT | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
props.setLook(wExtendeddescription,Props.WIDGET_STYLE_FIXED);
wExtendeddescription.addModifyListener(lsMod);
fdExtendeddescription = new FormData();
fdExtendeddescription.left = new FormAttachment(middle, 0);
fdExtendeddescription.top = new FormAttachment(wTransdescription, margin);
fdExtendeddescription.right = new FormAttachment(100, 0);
fdExtendeddescription.bottom =new FormAttachment(50, -margin);
wExtendeddescription.setLayoutData(fdExtendeddescription);
//Trans Status
wlTransstatus = new Label(wTransComp, SWT.RIGHT);
wlTransstatus.setText(BaseMessages.getString(PKG, "TransDialog.Transstatus.Label"));
props.setLook(wlTransstatus);
fdlTransstatus = new FormData();
fdlTransstatus.left = new FormAttachment(0, 0);
fdlTransstatus.right = new FormAttachment(middle, 0);
fdlTransstatus.top = new FormAttachment(wExtendeddescription, margin*2);
wlTransstatus.setLayoutData(fdlTransstatus);
wTransstatus = new CCombo(wTransComp, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER);
wTransstatus.add(BaseMessages.getString(PKG, "TransDialog.Draft_Transstatus.Label"));
wTransstatus.add(BaseMessages.getString(PKG, "TransDialog.Production_Transstatus.Label"));
wTransstatus.add("");
wTransstatus.select(-1); // +1: starts at -1
props.setLook(wTransstatus);
fdTransstatus= new FormData();
fdTransstatus.left = new FormAttachment(middle, 0);
fdTransstatus.top = new FormAttachment(wExtendeddescription, margin*2);
fdTransstatus.right = new FormAttachment(100, 0);
wTransstatus.setLayoutData(fdTransstatus);
// Transformation Transversion:
Label wlTransversion = new Label(wTransComp, SWT.RIGHT);
wlTransversion.setText(BaseMessages.getString(PKG, "TransDialog.Transversion.Label"));
props.setLook(wlTransversion);
FormData fdlTransversion = new FormData();
fdlTransversion.left = new FormAttachment(0, 0);
fdlTransversion.right= new FormAttachment(middle, -margin);
fdlTransversion.top = new FormAttachment(wTransstatus, margin);
wlTransversion.setLayoutData(fdlTransversion);
wTransversion=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wTransversion);
wTransversion.addModifyListener(lsMod);
FormData fdTransversion = new FormData();
fdTransversion.left = new FormAttachment(middle, 0);
fdTransversion.top = new FormAttachment(wTransstatus, margin);
fdTransversion.right= new FormAttachment(100, 0);
wTransversion.setLayoutData(fdTransversion);
// Directory:
wlDirectory = new Label(wTransComp, SWT.RIGHT);
wlDirectory.setText(BaseMessages.getString(PKG, "TransDialog.Directory.Label"));
props.setLook(wlDirectory);
FormData fdlDirectory = new FormData();
fdlDirectory.left = new FormAttachment(0, 0);
fdlDirectory.right= new FormAttachment(middle, -margin);
fdlDirectory.top = new FormAttachment(wTransversion, margin);
wlDirectory.setLayoutData(fdlDirectory);
wbDirectory=new Button(wTransComp, SWT.PUSH);
wbDirectory.setToolTipText(BaseMessages.getString(PKG, "TransDialog.selectTransFolder.Tooltip"));
wbDirectory.setImage(GUIResource.getInstance().getImageArrow());
props.setLook(wbDirectory);
FormData fdbDirectory = new FormData();
fdbDirectory.right= new FormAttachment(100, 0);
fdbDirectory.top = new FormAttachment(wTransversion, 0);
wbDirectory.setLayoutData(fdbDirectory);
wbDirectory.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
if (rep!=null)
{
RepositoryDirectoryInterface directoryFrom = transMeta.getRepositoryDirectory();
if (directoryFrom==null) directoryFrom = new RepositoryDirectory();
ObjectId idDirectoryFrom = directoryFrom.getObjectId();
SelectDirectoryDialog sdd = new SelectDirectoryDialog(shell, SWT.NONE, rep);
RepositoryDirectoryInterface rd = sdd.open();
if (rd!=null)
{
if (idDirectoryFrom!=rd.getObjectId())
{
// We need to change this in the repository as well!!
// We do this when the user pressed OK
newDirectory = rd;
wDirectory.setText(rd.getPath());
}
else
{
// Same directory!
}
}
}
else
{
}
}
});
wDirectory=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wDirectory);
wDirectory.setEditable(false);
wDirectory.setEnabled(false);
FormData fdDirectory = new FormData();
fdDirectory.left = new FormAttachment(middle, 0);
fdDirectory.top = new FormAttachment(wTransversion, margin);
fdDirectory.right= new FormAttachment(wbDirectory, 0);
wDirectory.setLayoutData(fdDirectory);
// Create User:
Label wlCreateUser = new Label(wTransComp, SWT.RIGHT);
wlCreateUser.setText(BaseMessages.getString(PKG, "TransDialog.CreateUser.Label"));
props.setLook(wlCreateUser);
FormData fdlCreateUser = new FormData();
fdlCreateUser.left = new FormAttachment(0, 0);
fdlCreateUser.right= new FormAttachment(middle, -margin);
fdlCreateUser.top = new FormAttachment(wDirectory, margin);
wlCreateUser.setLayoutData(fdlCreateUser);
wCreateUser=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wCreateUser);
wCreateUser.setEditable(false);
wCreateUser.addModifyListener(lsMod);
FormData fdCreateUser = new FormData();
fdCreateUser.left = new FormAttachment(middle, 0);
fdCreateUser.top = new FormAttachment(wDirectory, margin);
fdCreateUser.right= new FormAttachment(100, 0);
wCreateUser.setLayoutData(fdCreateUser);
// Created Date:
Label wlCreateDate = new Label(wTransComp, SWT.RIGHT);
wlCreateDate.setText(BaseMessages.getString(PKG, "TransDialog.CreateDate.Label"));
props.setLook(wlCreateDate);
FormData fdlCreateDate = new FormData();
fdlCreateDate.left = new FormAttachment(0, 0);
fdlCreateDate.right= new FormAttachment(middle, -margin);
fdlCreateDate.top = new FormAttachment(wCreateUser, margin);
wlCreateDate.setLayoutData(fdlCreateDate);
wCreateDate=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wCreateDate);
wCreateDate.setEditable(false);
wCreateDate.addModifyListener(lsMod);
FormData fdCreateDate = new FormData();
fdCreateDate.left = new FormAttachment(middle, 0);
fdCreateDate.top = new FormAttachment(wCreateUser, margin);
fdCreateDate.right= new FormAttachment(100, 0);
wCreateDate.setLayoutData(fdCreateDate);
// Modified User:
Label wlModUser = new Label(wTransComp, SWT.RIGHT);
wlModUser.setText(BaseMessages.getString(PKG, "TransDialog.LastModifiedUser.Label"));
props.setLook(wlModUser);
FormData fdlModUser = new FormData();
fdlModUser.left = new FormAttachment(0, 0);
fdlModUser.right= new FormAttachment(middle, -margin);
fdlModUser.top = new FormAttachment(wCreateDate, margin);
wlModUser.setLayoutData(fdlModUser);
wModUser=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wModUser);
wModUser.setEditable(false);
wModUser.addModifyListener(lsMod);
FormData fdModUser = new FormData();
fdModUser.left = new FormAttachment(middle, 0);
fdModUser.top = new FormAttachment(wCreateDate, margin);
fdModUser.right= new FormAttachment(100, 0);
wModUser.setLayoutData(fdModUser);
// Modified Date:
Label wlModDate = new Label(wTransComp, SWT.RIGHT);
wlModDate.setText(BaseMessages.getString(PKG, "TransDialog.LastModifiedDate.Label"));
props.setLook(wlModDate);
FormData fdlModDate = new FormData();
fdlModDate.left = new FormAttachment(0, 0);
fdlModDate.right= new FormAttachment(middle, -margin);
fdlModDate.top = new FormAttachment(wModUser, margin);
wlModDate.setLayoutData(fdlModDate);
wModDate=new Text(wTransComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wModDate);
wModDate.setEditable(false);
wModDate.addModifyListener(lsMod);
FormData fdModDate = new FormData();
fdModDate.left = new FormAttachment(middle, 0);
fdModDate.top = new FormAttachment(wModUser, margin);
fdModDate.right= new FormAttachment(100, 0);
wModDate.setLayoutData(fdModDate);
FormData fdTransComp = new FormData();
fdTransComp.left = new FormAttachment(0, 0);
fdTransComp.top = new FormAttachment(0, 0);
fdTransComp.right = new FormAttachment(100, 0);
fdTransComp.bottom= new FormAttachment(100, 0);
wTransComp.setLayoutData(fdTransComp);
wTransComp.layout();
wTransTab.setControl(wTransComp);
/////////////////////////////////////////////////////////////
/// END OF TRANS TAB
/////////////////////////////////////////////////////////////
}
private void addParamTab()
{
//////////////////////////
// START OF PARAM TAB
///
wParamTab=new CTabItem(wTabFolder, SWT.NONE);
wParamTab.setText(BaseMessages.getString(PKG, "TransDialog.ParamTab.Label"));
FormLayout paramLayout = new FormLayout ();
paramLayout.marginWidth = Const.MARGIN;
paramLayout.marginHeight = Const.MARGIN;
Composite wParamComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wParamComp);
wParamComp.setLayout(paramLayout);
Label wlFields = new Label(wParamComp, SWT.RIGHT);
wlFields.setText(BaseMessages.getString(PKG, "TransDialog.Parameters.Label"));
props.setLook(wlFields);
FormData fdlFields = new FormData();
fdlFields.left = new FormAttachment(0, 0);
fdlFields.top = new FormAttachment(0, 0);
wlFields.setLayoutData(fdlFields);
final int FieldsCols=3;
final int FieldsRows=transMeta.listParameters().length;
ColumnInfo[] colinf=new ColumnInfo[FieldsCols];
colinf[0]=new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.ColumnInfo.Parameter.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false);
colinf[1]=new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.ColumnInfo.Default.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false);
colinf[2]=new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.ColumnInfo.Description.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false);
wParamFields=new TableView(transMeta, wParamComp,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI,
colinf,
FieldsRows,
lsMod,
props
);
FormData fdFields = new FormData();
fdFields.left = new FormAttachment(0, 0);
fdFields.top = new FormAttachment(wlFields, margin);
fdFields.right = new FormAttachment(100, 0);
fdFields.bottom= new FormAttachment(100, 0);
wParamFields.setLayoutData(fdFields);
FormData fdDepComp = new FormData();
fdDepComp.left = new FormAttachment(0, 0);
fdDepComp.top = new FormAttachment(0, 0);
fdDepComp.right = new FormAttachment(100, 0);
fdDepComp.bottom= new FormAttachment(100, 0);
wParamComp.setLayoutData(fdDepComp);
wParamComp.layout();
wParamTab.setControl(wParamComp);
/////////////////////////////////////////////////////////////
/// END OF PARAM TAB
/////////////////////////////////////////////////////////////
}
private void addLogTab()
{
//////////////////////////
// START OF LOG TAB///
///
wLogTab=new CTabItem(wTabFolder, SWT.NONE);
wLogTab.setText(BaseMessages.getString(PKG, "TransDialog.LogTab.Label"));
FormLayout LogLayout = new FormLayout ();
LogLayout.marginWidth = Const.MARGIN;
LogLayout.marginHeight = Const.MARGIN;
wLogComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wLogComp);
wLogComp.setLayout(LogLayout);
// Add a log type List on the left hand side...
//
wLogTypeList = new List(wLogComp, SWT.SINGLE | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
props.setLook(wLogTypeList);
wLogTypeList.add(BaseMessages.getString(PKG, "TransDialog.LogTableType.Transformation")); // Index 0
wLogTypeList.add(BaseMessages.getString(PKG, "TransDialog.LogTableType.Step")); // Index 1
wLogTypeList.add(BaseMessages.getString(PKG, "TransDialog.LogTableType.Performance")); // Index 2
wLogTypeList.add(BaseMessages.getString(PKG, "TransDialog.LogTableType.LoggingChannels")); // Index 3
wLogTypeList.add(BaseMessages.getString(PKG, "TransDialog.LogTableType.Metrics")); // Index 3
FormData fdLogTypeList = new FormData();
fdLogTypeList.left = new FormAttachment(0, 0);
fdLogTypeList.top = new FormAttachment(0, 0);
fdLogTypeList.right= new FormAttachment(middle/2, 0);
fdLogTypeList.bottom= new FormAttachment(100, 0);
wLogTypeList.setLayoutData(fdLogTypeList);
wLogTypeList.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
showLogTypeOptions(wLogTypeList.getSelectionIndex());
}
});
// On the right side we see a dynamic area : a composite...
//
wLogOptionsComposite = new Composite(wLogComp, SWT.BORDER);
FormLayout logOptionsLayout = new FormLayout ();
logOptionsLayout.marginWidth = Const.MARGIN;
logOptionsLayout.marginHeight = Const.MARGIN;
wLogOptionsComposite.setLayout(logOptionsLayout);
props.setLook(wLogOptionsComposite);
FormData fdLogOptionsComposite = new FormData();
fdLogOptionsComposite.left = new FormAttachment(wLogTypeList, margin);
fdLogOptionsComposite.top = new FormAttachment(0, 0);
fdLogOptionsComposite.right= new FormAttachment(100, 0);
fdLogOptionsComposite.bottom= new FormAttachment(100, 0);
wLogOptionsComposite.setLayoutData(fdLogOptionsComposite);
FormData fdLogComp = new FormData();
fdLogComp.left = new FormAttachment(0, 0);
fdLogComp.top = new FormAttachment(0, 0);
fdLogComp.right = new FormAttachment(100, 0);
fdLogComp.bottom= new FormAttachment(100, 0);
wLogComp.setLayoutData(fdLogComp);
wLogComp.layout();
wLogTab.setControl(wLogComp);
/////////////////////////////////////////////////////////////
/// END OF LOG TAB
/////////////////////////////////////////////////////////////
}
private void showLogTypeOptions(int index) {
if (index!=previousLogTableIndex) {
// Remember the that was entered data...
//
switch(previousLogTableIndex) {
case LOG_INDEX_TRANS : getTransLogTableOptions(); break;
case LOG_INDEX_PERFORMANCE : getPerformanceLogTableOptions(); break;
case LOG_INDEX_CHANNEL : getChannelLogTableOptions(); break;
case LOG_INDEX_STEP : getStepLogTableOptions(); break;
case LOG_INDEX_METRICS : getMetricsLogTableOptions(); break;
default: break;
}
// clean the log options composite...
//
for (Control control : wLogOptionsComposite.getChildren()) {
control.dispose();
}
switch(index) {
case LOG_INDEX_TRANS : showTransLogTableOptions(); break;
case LOG_INDEX_PERFORMANCE : showPerformanceLogTableOptions(); break;
case LOG_INDEX_CHANNEL : showChannelLogTableOptions(); break;
case LOG_INDEX_STEP : showStepLogTableOptions(); break;
case LOG_INDEX_METRICS : showMetricsLogTableOptions(); break;
default: break;
}
}
}
private void getTransLogTableOptions() {
if (previousLogTableIndex==LOG_INDEX_TRANS) {
// The connection...
//
transLogTable.setConnectionName( wLogconnection.getText() );
transLogTable.setSchemaName( wLogSchema.getText() );
transLogTable.setTableName( wLogTable.getText() );
transLogTable.setLogInterval( wLogInterval.getText() );
transLogTable.setLogSizeLimit( wLogSizeLimit.getText() );
transLogTable.setTimeoutInDays( wLogTimeout.getText() );
for (int i=0;i<transLogTable.getFields().size();i++) {
TableItem item = wOptionFields.table.getItem(i);
LogTableField field = transLogTable.getFields().get(i);
field.setEnabled(item.getChecked());
field.setFieldName(item.getText(1));
if (field.isSubjectAllowed()) {
field.setSubject(transMeta.findStep(item.getText(2)));
}
}
}
}
private Control addDBSchemaTableLogOptions(LogTableInterface logTable) {
// Log table connection...
//
Label wlLogconnection = new Label(wLogOptionsComposite, SWT.RIGHT);
wlLogconnection.setText(BaseMessages.getString(PKG, "TransDialog.LogConnection.Label"));
props.setLook(wlLogconnection);
FormData fdlLogconnection = new FormData();
fdlLogconnection.left = new FormAttachment(0, 0);
fdlLogconnection.right= new FormAttachment(middle, -margin);
fdlLogconnection.top = new FormAttachment(0, 0);
wlLogconnection.setLayoutData(fdlLogconnection);
wbLogconnection=new Button(wLogOptionsComposite, SWT.PUSH);
wbLogconnection.setText(BaseMessages.getString(PKG, "TransDialog.LogconnectionButton.Label"));
wbLogconnection.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
DatabaseMeta databaseMeta = new DatabaseMeta();
databaseMeta.shareVariablesWith(transMeta);
getDatabaseDialog().setDatabaseMeta(databaseMeta);
if (getDatabaseDialog().open()!=null)
{
transMeta.addDatabase(getDatabaseDialog().getDatabaseMeta());
wLogconnection.add(getDatabaseDialog().getDatabaseMeta().getName());
wLogconnection.select(wLogconnection.getItemCount()-1);
}
}
});
FormData fdbLogconnection = new FormData();
fdbLogconnection.right= new FormAttachment(100, 0);
fdbLogconnection.top = new FormAttachment(0, 0);
wbLogconnection.setLayoutData(fdbLogconnection);
wLogconnection=new ComboVar(transMeta, wLogOptionsComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wLogconnection);
wLogconnection.addModifyListener(lsMod);
FormData fdLogconnection = new FormData();
fdLogconnection.left = new FormAttachment(middle, 0);
fdLogconnection.top = new FormAttachment(0, 0);
fdLogconnection.right= new FormAttachment(wbLogconnection, -margin);
wLogconnection.setLayoutData(fdLogconnection);
wLogconnection.setItems(transMeta.getDatabaseNames());
wLogconnection.setText(Const.NVL(logTable.getConnectionName(), ""));
wLogconnection.setToolTipText(BaseMessages.getString(PKG, "TransDialog.LogConnection.Tooltip", logTable.getConnectionNameVariable()));
// Log schema ...
//
Label wlLogSchema = new Label(wLogOptionsComposite, SWT.RIGHT);
wlLogSchema.setText(BaseMessages.getString(PKG, "TransDialog.LogSchema.Label"));
props.setLook(wlLogSchema);
FormData fdlLogSchema = new FormData();
fdlLogSchema.left = new FormAttachment(0, 0);
fdlLogSchema.right= new FormAttachment(middle, -margin);
fdlLogSchema.top = new FormAttachment(wLogconnection, margin);
wlLogSchema.setLayoutData(fdlLogSchema);
wLogSchema=new TextVar(transMeta, wLogOptionsComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wLogSchema);
wLogSchema.addModifyListener(lsMod);
FormData fdLogSchema = new FormData();
fdLogSchema.left = new FormAttachment(middle, 0);
fdLogSchema.top = new FormAttachment(wLogconnection, margin);
fdLogSchema.right= new FormAttachment(100, 0);
wLogSchema.setLayoutData(fdLogSchema);
wLogSchema.setText(Const.NVL(logTable.getSchemaName(), ""));
wLogSchema.setToolTipText(BaseMessages.getString(PKG, "TransDialog.LogSchema.Tooltip", logTable.getSchemaNameVariable()));
// Log table...
//
Label wlLogtable = new Label(wLogOptionsComposite, SWT.RIGHT);
wlLogtable.setText(BaseMessages.getString(PKG, "TransDialog.Logtable.Label"));
props.setLook(wlLogtable);
FormData fdlLogtable = new FormData();
fdlLogtable.left = new FormAttachment(0, 0);
fdlLogtable.right= new FormAttachment(middle, -margin);
fdlLogtable.top = new FormAttachment(wLogSchema, margin);
wlLogtable.setLayoutData(fdlLogtable);
wLogTable=new TextVar(transMeta, wLogOptionsComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wLogTable);
wLogTable.addModifyListener(lsMod);
FormData fdLogtable = new FormData();
fdLogtable.left = new FormAttachment(middle, 0);
fdLogtable.top = new FormAttachment(wLogSchema, margin);
fdLogtable.right= new FormAttachment(100, 0);
wLogTable.setLayoutData(fdLogtable);
wLogTable.setText(Const.NVL(logTable.getTableName(), ""));
wLogTable.setToolTipText(BaseMessages.getString(PKG, "TransDialog.LogTable.Tooltip", logTable.getTableNameVariable()));
return wLogTable;
}
private void showTransLogTableOptions() {
previousLogTableIndex=LOG_INDEX_TRANS;
addDBSchemaTableLogOptions(transLogTable);
// Log interval...
//
Label wlLogInterval = new Label(wLogOptionsComposite, SWT.RIGHT);
wlLogInterval.setText(BaseMessages.getString(PKG, "TransDialog.LogInterval.Label"));
props.setLook(wlLogInterval);
FormData fdlLogInterval = new FormData();
fdlLogInterval.left = new FormAttachment(0, 0);
fdlLogInterval.right= new FormAttachment(middle, -margin);
fdlLogInterval.top = new FormAttachment(wLogTable, margin);
wlLogInterval.setLayoutData(fdlLogInterval);
wLogInterval=new TextVar(transMeta, wLogOptionsComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wLogInterval);
wLogInterval.addModifyListener(lsMod);
FormData fdLogInterval = new FormData();
fdLogInterval.left = new FormAttachment(middle, 0);
fdLogInterval.top = new FormAttachment(wLogTable, margin);
fdLogInterval.right= new FormAttachment(100, 0);
wLogInterval.setLayoutData(fdLogInterval);
wLogInterval.setText(Const.NVL(transLogTable.getLogInterval(), ""));
// The log timeout in days
//
Label wlLogTimeout = new Label(wLogOptionsComposite, SWT.RIGHT);
wlLogTimeout.setText(BaseMessages.getString(PKG, "TransDialog.LogTimeout.Label"));
wlLogTimeout.setToolTipText(BaseMessages.getString(PKG, "TransDialog.LogTimeout.Tooltip"));
props.setLook(wlLogTimeout);
FormData fdlLogTimeout = new FormData();
fdlLogTimeout.left = new FormAttachment(0, 0);
fdlLogTimeout.right= new FormAttachment(middle, -margin);
fdlLogTimeout.top = new FormAttachment(wLogInterval, margin);
wlLogTimeout.setLayoutData(fdlLogTimeout);
wLogTimeout=new TextVar(transMeta, wLogOptionsComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wLogTimeout.setToolTipText(BaseMessages.getString(PKG, "TransDialog.LogTimeout.Tooltip"));
props.setLook(wLogTimeout);
wLogTimeout.addModifyListener(lsMod);
FormData fdLogTimeout = new FormData();
fdLogTimeout.left = new FormAttachment(middle, 0);
fdLogTimeout.top = new FormAttachment(wLogInterval, margin);
fdLogTimeout.right= new FormAttachment(100, 0);
wLogTimeout.setLayoutData(fdLogTimeout);
wLogTimeout.setText(Const.NVL(transLogTable.getTimeoutInDays(), ""));
// The log size limit
//
Label wlLogSizeLimit = new Label(wLogOptionsComposite, SWT.RIGHT);
wlLogSizeLimit.setText(BaseMessages.getString(PKG, "TransDialog.LogSizeLimit.Label"));
wlLogSizeLimit.setToolTipText(BaseMessages.getString(PKG, "TransDialog.LogSizeLimit.Tooltip"));
props.setLook(wlLogSizeLimit);
FormData fdlLogSizeLimit = new FormData();
fdlLogSizeLimit.left = new FormAttachment(0, 0);
fdlLogSizeLimit.right= new FormAttachment(middle, -margin);
fdlLogSizeLimit.top = new FormAttachment(wLogTimeout, margin);
wlLogSizeLimit.setLayoutData(fdlLogSizeLimit);
wLogSizeLimit=new TextVar(transMeta, wLogOptionsComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wLogSizeLimit.setToolTipText(BaseMessages.getString(PKG, "TransDialog.LogSizeLimit.Tooltip"));
props.setLook(wLogSizeLimit);
wLogSizeLimit.addModifyListener(lsMod);
FormData fdLogSizeLimit = new FormData();
fdLogSizeLimit.left = new FormAttachment(middle, 0);
fdLogSizeLimit.top = new FormAttachment(wLogTimeout, margin);
fdLogSizeLimit.right= new FormAttachment(100, 0);
wLogSizeLimit.setLayoutData(fdLogSizeLimit);
wLogSizeLimit.setText(Const.NVL(transLogTable.getLogSizeLimit(), ""));
// Add the fields grid...
//
Label wlFields = new Label(wLogOptionsComposite, SWT.NONE);
wlFields.setText(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.Label"));
props.setLook(wlFields);
FormData fdlFields = new FormData();
fdlFields.left = new FormAttachment(0, 0);
fdlFields.top = new FormAttachment(wLogSizeLimit, margin*2);
wlFields.setLayoutData(fdlFields);
final java.util.List<LogTableField> fields = transLogTable.getFields();
final int nrRows=fields.size();
ColumnInfo[] colinf=new ColumnInfo[] {
new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.FieldName"), ColumnInfo.COLUMN_TYPE_TEXT, false ),
new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.StepName"), ColumnInfo.COLUMN_TYPE_CCOMBO, transMeta.getStepNames()),
new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.Description"), ColumnInfo.COLUMN_TYPE_TEXT, false, true),
};
FieldDisabledListener disabledListener = new FieldDisabledListener() {
public boolean isFieldDisabled(int rowNr) {
if (rowNr>=0 && rowNr<fields.size()) {
LogTableField field = fields.get(rowNr);
return !field.isSubjectAllowed();
} else {
return true;
}
}
};
colinf[1].setDisabledListener(disabledListener);
wOptionFields=new TableView(transMeta, wLogOptionsComposite,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.CHECK, // add a check to the left...
colinf,
nrRows,
true,
lsMod,
props
);
wOptionFields.setSortable(false);
for (int i=0;i<fields.size();i++) {
LogTableField field = fields.get(i);
TableItem item = wOptionFields.table.getItem(i);
item.setChecked(field.isEnabled());
item.setText(new String[] { "", Const.NVL(field.getFieldName(), ""), field.getSubject()==null?"":field.getSubject().toString(), Const.NVL(field.getDescription(), "") });
// Exceptions!!!
//
if (disabledListener.isFieldDisabled(i)) {
item.setBackground(2, GUIResource.getInstance().getColorLightGray());
}
}
wOptionFields.table.getColumn(0).setText(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.Enabled"));
FormData fdOptionFields = new FormData();
fdOptionFields.left = new FormAttachment(0, 0);
fdOptionFields.top = new FormAttachment(wlFields, margin);
fdOptionFields.right = new FormAttachment(100, 0);
fdOptionFields.bottom = new FormAttachment(100, 0);
wOptionFields.setLayoutData(fdOptionFields);
wOptionFields.optWidth(true);
wOptionFields.layout();
wLogOptionsComposite.layout(true, true);
wLogComp.layout(true, true);
}
private void getPerformanceLogTableOptions() {
if (previousLogTableIndex==LOG_INDEX_PERFORMANCE) {
// The connection...
//
performanceLogTable.setConnectionName( wLogconnection.getText() );
performanceLogTable.setSchemaName( wLogSchema.getText() );
performanceLogTable.setTableName( wLogTable.getText() );
performanceLogTable.setLogInterval( wLogInterval.getText() );
performanceLogTable.setTimeoutInDays( wLogTimeout.getText() );
for (int i=0;i<performanceLogTable.getFields().size();i++) {
TableItem item = wOptionFields.table.getItem(i);
LogTableField field = performanceLogTable.getFields().get(i);
field.setEnabled(item.getChecked());
field.setFieldName(item.getText(1));
}
}
}
private void showPerformanceLogTableOptions() {
previousLogTableIndex=LOG_INDEX_PERFORMANCE;
addDBSchemaTableLogOptions(performanceLogTable);
// Log interval...
//
Label wlLogInterval = new Label(wLogOptionsComposite, SWT.RIGHT);
wlLogInterval.setText(BaseMessages.getString(PKG, "TransDialog.LogInterval.Label"));
props.setLook(wlLogInterval);
FormData fdlLogInterval = new FormData();
fdlLogInterval.left = new FormAttachment(0, 0);
fdlLogInterval.right= new FormAttachment(middle, -margin);
fdlLogInterval.top = new FormAttachment(wLogTable, margin);
wlLogInterval.setLayoutData(fdlLogInterval);
wLogInterval=new TextVar(transMeta, wLogOptionsComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wLogInterval);
wLogInterval.addModifyListener(lsMod);
FormData fdLogInterval = new FormData();
fdLogInterval.left = new FormAttachment(middle, 0);
fdLogInterval.top = new FormAttachment(wLogTable, margin);
fdLogInterval.right= new FormAttachment(100, 0);
wLogInterval.setLayoutData(fdLogInterval);
wLogInterval.setText(Const.NVL(performanceLogTable.getLogInterval(), ""));
// The log timeout in days
//
Label wlLogTimeout = new Label(wLogOptionsComposite, SWT.RIGHT);
wlLogTimeout.setText(BaseMessages.getString(PKG, "TransDialog.LogTimeout.Label"));
wlLogTimeout.setToolTipText(BaseMessages.getString(PKG, "TransDialog.LogTimeout.Tooltip"));
props.setLook(wlLogTimeout);
FormData fdlLogTimeout = new FormData();
fdlLogTimeout.left = new FormAttachment(0, 0);
fdlLogTimeout.right= new FormAttachment(middle, -margin);
fdlLogTimeout.top = new FormAttachment(wLogInterval, margin);
wlLogTimeout.setLayoutData(fdlLogTimeout);
wLogTimeout=new TextVar(transMeta, wLogOptionsComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wLogTimeout.setToolTipText(BaseMessages.getString(PKG, "TransDialog.LogTimeout.Tooltip"));
props.setLook(wLogTimeout);
wLogTimeout.addModifyListener(lsMod);
FormData fdLogTimeout = new FormData();
fdLogTimeout.left = new FormAttachment(middle, 0);
fdLogTimeout.top = new FormAttachment(wLogInterval, margin);
fdLogTimeout.right= new FormAttachment(100, 0);
wLogTimeout.setLayoutData(fdLogTimeout);
wLogTimeout.setText(Const.NVL(performanceLogTable.getTimeoutInDays(), ""));
// Add the fields grid...
//
Label wlFields = new Label(wLogOptionsComposite, SWT.NONE);
wlFields.setText(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.Label"));
props.setLook(wlFields);
FormData fdlFields = new FormData();
fdlFields.left = new FormAttachment(0, 0);
fdlFields.top = new FormAttachment(wLogTimeout, margin*2);
wlFields.setLayoutData(fdlFields);
final java.util.List<LogTableField> fields = performanceLogTable.getFields();
final int nrRows=fields.size();
ColumnInfo[] colinf=new ColumnInfo[] {
new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.FieldName"), ColumnInfo.COLUMN_TYPE_TEXT, false ),
new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.Description"), ColumnInfo.COLUMN_TYPE_TEXT, false, true),
};
FieldDisabledListener disabledListener = new FieldDisabledListener() {
public boolean isFieldDisabled(int rowNr) {
if (rowNr>=0 && rowNr<fields.size()) {
LogTableField field = fields.get(rowNr);
return field.isSubjectAllowed();
} else {
return true;
}
}
};
colinf[1].setDisabledListener(disabledListener);
wOptionFields=new TableView(transMeta, wLogOptionsComposite,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.CHECK, // add a check to the left...
colinf,
nrRows,
true,
lsMod,
props
);
wOptionFields.setSortable(false);
for (int i=0;i<fields.size();i++) {
LogTableField field = fields.get(i);
TableItem item = wOptionFields.table.getItem(i);
item.setChecked(field.isEnabled());
item.setText(new String[] { "", Const.NVL(field.getFieldName(), ""), Const.NVL(field.getDescription(), "") });
}
wOptionFields.table.getColumn(0).setText(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.Enabled"));
FormData fdOptionFields = new FormData();
fdOptionFields.left = new FormAttachment(0, 0);
fdOptionFields.top = new FormAttachment(wlFields, margin);
fdOptionFields.right = new FormAttachment(100, 0);
fdOptionFields.bottom = new FormAttachment(100, 0);
wOptionFields.setLayoutData(fdOptionFields);
wOptionFields.optWidth(true);
wOptionFields.layout();
wLogOptionsComposite.layout(true, true);
wLogComp.layout(true, true);
}
private void getChannelLogTableOptions() {
if (previousLogTableIndex==LOG_INDEX_CHANNEL) {
// The connection...
//
channelLogTable.setConnectionName( wLogconnection.getText() );
channelLogTable.setSchemaName( wLogSchema.getText() );
channelLogTable.setTableName( wLogTable.getText() );
channelLogTable.setTimeoutInDays( wLogTimeout.getText() );
for (int i=0;i<channelLogTable.getFields().size();i++) {
TableItem item = wOptionFields.table.getItem(i);
LogTableField field = channelLogTable.getFields().get(i);
field.setEnabled(item.getChecked());
field.setFieldName(item.getText(1));
}
}
}
private void getMetricsLogTableOptions() {
if (previousLogTableIndex == LOG_INDEX_METRICS) {
// The connection...
//
metricsLogTable.setConnectionName(wLogconnection.getText());
metricsLogTable.setSchemaName(wLogSchema.getText());
metricsLogTable.setTableName(wLogTable.getText());
metricsLogTable.setTimeoutInDays(wLogTimeout.getText());
for (int i = 0; i < metricsLogTable.getFields().size(); i++) {
TableItem item = wOptionFields.table.getItem(i);
LogTableField field = metricsLogTable.getFields().get(i);
field.setEnabled(item.getChecked());
field.setFieldName(item.getText(1));
}
}
}
private void showChannelLogTableOptions() {
previousLogTableIndex=LOG_INDEX_CHANNEL;
addDBSchemaTableLogOptions(channelLogTable);
// The log timeout in days
//
Label wlLogTimeout = new Label(wLogOptionsComposite, SWT.RIGHT);
wlLogTimeout.setText(BaseMessages.getString(PKG, "TransDialog.LogTimeout.Label"));
wlLogTimeout.setToolTipText(BaseMessages.getString(PKG, "TransDialog.LogTimeout.Tooltip"));
props.setLook(wlLogTimeout);
FormData fdlLogTimeout = new FormData();
fdlLogTimeout.left = new FormAttachment(0, 0);
fdlLogTimeout.right= new FormAttachment(middle, -margin);
fdlLogTimeout.top = new FormAttachment(wLogTable, margin);
wlLogTimeout.setLayoutData(fdlLogTimeout);
wLogTimeout=new TextVar(transMeta, wLogOptionsComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wLogTimeout.setToolTipText(BaseMessages.getString(PKG, "TransDialog.LogTimeout.Tooltip"));
props.setLook(wLogTimeout);
wLogTimeout.addModifyListener(lsMod);
FormData fdLogTimeout = new FormData();
fdLogTimeout.left = new FormAttachment(middle, 0);
fdLogTimeout.top = new FormAttachment(wLogTable, margin);
fdLogTimeout.right= new FormAttachment(100, 0);
wLogTimeout.setLayoutData(fdLogTimeout);
wLogTimeout.setText(Const.NVL(channelLogTable.getTimeoutInDays(), ""));
// Add the fields grid...
//
Label wlFields = new Label(wLogOptionsComposite, SWT.NONE);
wlFields.setText(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.Label"));
props.setLook(wlFields);
FormData fdlFields = new FormData();
fdlFields.left = new FormAttachment(0, 0);
fdlFields.top = new FormAttachment(wLogTimeout, margin*2);
wlFields.setLayoutData(fdlFields);
final java.util.List<LogTableField> fields = channelLogTable.getFields();
final int nrRows=fields.size();
ColumnInfo[] colinf=new ColumnInfo[] {
new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.FieldName"), ColumnInfo.COLUMN_TYPE_TEXT, false ),
new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.Description"), ColumnInfo.COLUMN_TYPE_TEXT, false, true),
};
FieldDisabledListener disabledListener = new FieldDisabledListener() {
public boolean isFieldDisabled(int rowNr) {
if (rowNr>=0 && rowNr<fields.size()) {
LogTableField field = fields.get(rowNr);
return field.isSubjectAllowed();
} else {
return true;
}
}
};
colinf[1].setDisabledListener(disabledListener);
wOptionFields=new TableView(transMeta, wLogOptionsComposite,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.CHECK, // add a check to the left...
colinf,
nrRows,
true,
lsMod,
props
);
wOptionFields.setSortable(false);
for (int i=0;i<fields.size();i++) {
LogTableField field = fields.get(i);
TableItem item = wOptionFields.table.getItem(i);
item.setChecked(field.isEnabled());
item.setText(new String[] { "", Const.NVL(field.getFieldName(), ""), Const.NVL(field.getDescription(), "") });
}
wOptionFields.table.getColumn(0).setText(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.Enabled"));
FormData fdOptionFields = new FormData();
fdOptionFields.left = new FormAttachment(0, 0);
fdOptionFields.top = new FormAttachment(wlFields, margin);
fdOptionFields.right = new FormAttachment(100, 0);
fdOptionFields.bottom = new FormAttachment(100, 0);
wOptionFields.setLayoutData(fdOptionFields);
wOptionFields.optWidth(true);
wOptionFields.layout();
wLogOptionsComposite.layout(true, true);
wLogComp.layout(true, true);
}
private void showMetricsLogTableOptions() {
previousLogTableIndex=LOG_INDEX_METRICS;
addDBSchemaTableLogOptions(metricsLogTable);
// The log timeout in days
//
Label wlLogTimeout = new Label(wLogOptionsComposite, SWT.RIGHT);
wlLogTimeout.setText(BaseMessages.getString(PKG, "TransDialog.LogTimeout.Label"));
wlLogTimeout.setToolTipText(BaseMessages.getString(PKG, "TransDialog.LogTimeout.Tooltip"));
props.setLook(wlLogTimeout);
FormData fdlLogTimeout = new FormData();
fdlLogTimeout.left = new FormAttachment(0, 0);
fdlLogTimeout.right= new FormAttachment(middle, -margin);
fdlLogTimeout.top = new FormAttachment(wLogTable, margin);
wlLogTimeout.setLayoutData(fdlLogTimeout);
wLogTimeout=new TextVar(transMeta, wLogOptionsComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wLogTimeout.setToolTipText(BaseMessages.getString(PKG, "TransDialog.LogTimeout.Tooltip"));
props.setLook(wLogTimeout);
wLogTimeout.addModifyListener(lsMod);
FormData fdLogTimeout = new FormData();
fdLogTimeout.left = new FormAttachment(middle, 0);
fdLogTimeout.top = new FormAttachment(wLogTable, margin);
fdLogTimeout.right= new FormAttachment(100, 0);
wLogTimeout.setLayoutData(fdLogTimeout);
wLogTimeout.setText(Const.NVL(channelLogTable.getTimeoutInDays(), ""));
// Add the fields grid...
//
Label wlFields = new Label(wLogOptionsComposite, SWT.NONE);
wlFields.setText(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.Label"));
props.setLook(wlFields);
FormData fdlFields = new FormData();
fdlFields.left = new FormAttachment(0, 0);
fdlFields.top = new FormAttachment(wLogTimeout, margin*2);
wlFields.setLayoutData(fdlFields);
final java.util.List<LogTableField> fields = metricsLogTable.getFields();
final int nrRows=fields.size();
ColumnInfo[] colinf=new ColumnInfo[] {
new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.FieldName"), ColumnInfo.COLUMN_TYPE_TEXT, false ),
new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.Description"), ColumnInfo.COLUMN_TYPE_TEXT, false, true),
};
FieldDisabledListener disabledListener = new FieldDisabledListener() {
public boolean isFieldDisabled(int rowNr) {
if (rowNr>=0 && rowNr<fields.size()) {
LogTableField field = fields.get(rowNr);
return field.isSubjectAllowed();
} else {
return true;
}
}
};
colinf[1].setDisabledListener(disabledListener);
wOptionFields=new TableView(transMeta, wLogOptionsComposite,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.CHECK, // add a check to the left...
colinf,
nrRows,
true,
lsMod,
props
);
wOptionFields.setSortable(false);
for (int i=0;i<fields.size();i++) {
LogTableField field = fields.get(i);
TableItem item = wOptionFields.table.getItem(i);
item.setChecked(field.isEnabled());
item.setText(new String[] { "", Const.NVL(field.getFieldName(), ""), Const.NVL(field.getDescription(), "") });
}
wOptionFields.table.getColumn(0).setText(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.Enabled"));
FormData fdOptionFields = new FormData();
fdOptionFields.left = new FormAttachment(0, 0);
fdOptionFields.top = new FormAttachment(wlFields, margin);
fdOptionFields.right = new FormAttachment(100, 0);
fdOptionFields.bottom = new FormAttachment(100, 0);
wOptionFields.setLayoutData(fdOptionFields);
wOptionFields.optWidth(true);
wOptionFields.layout();
wLogOptionsComposite.layout(true, true);
wLogComp.layout(true, true);
}
private void getStepLogTableOptions() {
if (previousLogTableIndex==LOG_INDEX_STEP) {
// The connection...
//
stepLogTable.setConnectionName( wLogconnection.getText() );
stepLogTable.setSchemaName( wLogSchema.getText() );
stepLogTable.setTableName( wLogTable.getText() );
stepLogTable.setTimeoutInDays( wLogTimeout.getText() );
for (int i=0;i<stepLogTable.getFields().size();i++) {
TableItem item = wOptionFields.table.getItem(i);
LogTableField field = stepLogTable.getFields().get(i);
field.setEnabled(item.getChecked());
field.setFieldName(item.getText(1));
}
}
}
private void showStepLogTableOptions() {
previousLogTableIndex=LOG_INDEX_STEP;
addDBSchemaTableLogOptions(stepLogTable);
// The log timeout in days
//
Label wlLogTimeout = new Label(wLogOptionsComposite, SWT.RIGHT);
wlLogTimeout.setText(BaseMessages.getString(PKG, "TransDialog.LogTimeout.Label"));
wlLogTimeout.setToolTipText(BaseMessages.getString(PKG, "TransDialog.LogTimeout.Tooltip"));
props.setLook(wlLogTimeout);
FormData fdlLogTimeout = new FormData();
fdlLogTimeout.left = new FormAttachment(0, 0);
fdlLogTimeout.right= new FormAttachment(middle, -margin);
fdlLogTimeout.top = new FormAttachment(wLogTable, margin);
wlLogTimeout.setLayoutData(fdlLogTimeout);
wLogTimeout=new TextVar(transMeta, wLogOptionsComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wLogTimeout.setToolTipText(BaseMessages.getString(PKG, "TransDialog.LogTimeout.Tooltip"));
props.setLook(wLogTimeout);
wLogTimeout.addModifyListener(lsMod);
FormData fdLogTimeout = new FormData();
fdLogTimeout.left = new FormAttachment(middle, 0);
fdLogTimeout.top = new FormAttachment(wLogTable, margin);
fdLogTimeout.right= new FormAttachment(100, 0);
wLogTimeout.setLayoutData(fdLogTimeout);
wLogTimeout.setText(Const.NVL(stepLogTable.getTimeoutInDays(), ""));
// Add the fields grid...
//
Label wlFields = new Label(wLogOptionsComposite, SWT.NONE);
wlFields.setText(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.Label"));
props.setLook(wlFields);
FormData fdlFields = new FormData();
fdlFields.left = new FormAttachment(0, 0);
fdlFields.top = new FormAttachment(wLogTimeout, margin*2);
wlFields.setLayoutData(fdlFields);
final java.util.List<LogTableField> fields = stepLogTable.getFields();
final int nrRows=fields.size();
ColumnInfo[] colinf=new ColumnInfo[] {
new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.FieldName"), ColumnInfo.COLUMN_TYPE_TEXT, false ),
new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.Description"), ColumnInfo.COLUMN_TYPE_TEXT, false, true),
};
FieldDisabledListener disabledListener = new FieldDisabledListener() {
public boolean isFieldDisabled(int rowNr) {
if (rowNr>=0 && rowNr<fields.size()) {
LogTableField field = fields.get(rowNr);
return field.isSubjectAllowed();
} else {
return true;
}
}
};
colinf[1].setDisabledListener(disabledListener);
wOptionFields=new TableView(transMeta, wLogOptionsComposite,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.CHECK, // add a check to the left...
colinf,
nrRows,
true,
lsMod,
props
);
wOptionFields.setSortable(false);
for (int i=0;i<fields.size();i++) {
LogTableField field = fields.get(i);
TableItem item = wOptionFields.table.getItem(i);
item.setChecked(field.isEnabled());
item.setText(new String[] { "", Const.NVL(field.getFieldName(), ""), Const.NVL(field.getDescription(), "") });
}
wOptionFields.table.getColumn(0).setText(BaseMessages.getString(PKG, "TransDialog.TransLogTable.Fields.Enabled"));
FormData fdOptionFields = new FormData();
fdOptionFields.left = new FormAttachment(0, 0);
fdOptionFields.top = new FormAttachment(wlFields, margin);
fdOptionFields.right = new FormAttachment(100, 0);
fdOptionFields.bottom = new FormAttachment(100, 0);
wOptionFields.setLayoutData(fdOptionFields);
wOptionFields.optWidth(true);
wOptionFields.layout();
wLogOptionsComposite.layout(true, true);
wLogComp.layout(true, true);
}
private void addDateTab()
{
//////////////////////////
// START OF DATE TAB///
///
wDateTab=new CTabItem(wTabFolder, SWT.NONE);
wDateTab.setText(BaseMessages.getString(PKG, "TransDialog.DateTab.Label"));
FormLayout DateLayout = new FormLayout ();
DateLayout.marginWidth = Const.MARGIN;
DateLayout.marginHeight = Const.MARGIN;
Composite wDateComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wDateComp);
wDateComp.setLayout(DateLayout);
// Max date table connection...
Label wlMaxdateconnection = new Label(wDateComp, SWT.RIGHT);
wlMaxdateconnection.setText(BaseMessages.getString(PKG, "TransDialog.MaxdateConnection.Label"));
props.setLook(wlMaxdateconnection);
FormData fdlMaxdateconnection = new FormData();
fdlMaxdateconnection.left = new FormAttachment(0, 0);
fdlMaxdateconnection.right= new FormAttachment(middle, -margin);
fdlMaxdateconnection.top = new FormAttachment(0, 0);
wlMaxdateconnection.setLayoutData(fdlMaxdateconnection);
wMaxdateconnection=new CCombo(wDateComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wMaxdateconnection);
wMaxdateconnection.addModifyListener(lsMod);
FormData fdMaxdateconnection = new FormData();
fdMaxdateconnection.left = new FormAttachment(middle, 0);
fdMaxdateconnection.top = new FormAttachment(0, 0);
fdMaxdateconnection.right= new FormAttachment(100, 0);
wMaxdateconnection.setLayoutData(fdMaxdateconnection);
// Maxdate table...:
Label wlMaxdatetable = new Label(wDateComp, SWT.RIGHT);
wlMaxdatetable.setText(BaseMessages.getString(PKG, "TransDialog.MaxdateTable.Label"));
props.setLook(wlMaxdatetable);
FormData fdlMaxdatetable = new FormData();
fdlMaxdatetable.left = new FormAttachment(0, 0);
fdlMaxdatetable.right= new FormAttachment(middle, -margin);
fdlMaxdatetable.top = new FormAttachment(wMaxdateconnection, margin);
wlMaxdatetable.setLayoutData(fdlMaxdatetable);
wMaxdatetable=new Text(wDateComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wMaxdatetable);
wMaxdatetable.addModifyListener(lsMod);
FormData fdMaxdatetable = new FormData();
fdMaxdatetable.left = new FormAttachment(middle, 0);
fdMaxdatetable.top = new FormAttachment(wMaxdateconnection, margin);
fdMaxdatetable.right= new FormAttachment(100, 0);
wMaxdatetable.setLayoutData(fdMaxdatetable);
// Maxdate field...:
Label wlMaxdatefield = new Label(wDateComp, SWT.RIGHT);
wlMaxdatefield.setText(BaseMessages.getString(PKG, "TransDialog.MaxdateField.Label"));
props.setLook(wlMaxdatefield);
FormData fdlMaxdatefield = new FormData();
fdlMaxdatefield.left = new FormAttachment(0, 0);
fdlMaxdatefield.right= new FormAttachment(middle, -margin);
fdlMaxdatefield.top = new FormAttachment(wMaxdatetable, margin);
wlMaxdatefield.setLayoutData(fdlMaxdatefield);
wMaxdatefield=new Text(wDateComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wMaxdatefield);
wMaxdatefield.addModifyListener(lsMod);
FormData fdMaxdatefield = new FormData();
fdMaxdatefield.left = new FormAttachment(middle, 0);
fdMaxdatefield.top = new FormAttachment(wMaxdatetable, margin);
fdMaxdatefield.right= new FormAttachment(100, 0);
wMaxdatefield.setLayoutData(fdMaxdatefield);
// Maxdate offset...:
Label wlMaxdateoffset = new Label(wDateComp, SWT.RIGHT);
wlMaxdateoffset.setText(BaseMessages.getString(PKG, "TransDialog.MaxdateOffset.Label"));
props.setLook(wlMaxdateoffset);
FormData fdlMaxdateoffset = new FormData();
fdlMaxdateoffset.left = new FormAttachment(0, 0);
fdlMaxdateoffset.right= new FormAttachment(middle, -margin);
fdlMaxdateoffset.top = new FormAttachment(wMaxdatefield, margin);
wlMaxdateoffset.setLayoutData(fdlMaxdateoffset);
wMaxdateoffset=new Text(wDateComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wMaxdateoffset);
wMaxdateoffset.addModifyListener(lsMod);
FormData fdMaxdateoffset = new FormData();
fdMaxdateoffset.left = new FormAttachment(middle, 0);
fdMaxdateoffset.top = new FormAttachment(wMaxdatefield, margin);
fdMaxdateoffset.right= new FormAttachment(100, 0);
wMaxdateoffset.setLayoutData(fdMaxdateoffset);
// Maxdate diff...:
Label wlMaxdatediff = new Label(wDateComp, SWT.RIGHT);
wlMaxdatediff.setText(BaseMessages.getString(PKG, "TransDialog.Maxdatediff.Label"));
props.setLook(wlMaxdatediff);
FormData fdlMaxdatediff = new FormData();
fdlMaxdatediff.left = new FormAttachment(0, 0);
fdlMaxdatediff.right= new FormAttachment(middle, -margin);
fdlMaxdatediff.top = new FormAttachment(wMaxdateoffset, margin);
wlMaxdatediff.setLayoutData(fdlMaxdatediff);
wMaxdatediff=new Text(wDateComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wMaxdatediff);
wMaxdatediff.addModifyListener(lsMod);
FormData fdMaxdatediff = new FormData();
fdMaxdatediff.left = new FormAttachment(middle, 0);
fdMaxdatediff.top = new FormAttachment(wMaxdateoffset, margin);
fdMaxdatediff.right= new FormAttachment(100, 0);
wMaxdatediff.setLayoutData(fdMaxdatediff);
connectionNames = new String[transMeta.nrDatabases()];
for (int i=0;i<transMeta.nrDatabases();i++)
{
DatabaseMeta ci = transMeta.getDatabase(i);
wMaxdateconnection.add(ci.getName());
connectionNames[i] = ci.getName();
}
FormData fdDateComp = new FormData();
fdDateComp.left = new FormAttachment(0, 0);
fdDateComp.top = new FormAttachment(0, 0);
fdDateComp.right = new FormAttachment(100, 0);
fdDateComp.bottom= new FormAttachment(100, 0);
wDateComp.setLayoutData(fdDateComp);
wDateComp.layout();
wDateTab.setControl(wDateComp);
/////////////////////////////////////////////////////////////
/// END OF DATE TAB
/////////////////////////////////////////////////////////////
}
private void addDepTab()
{
//////////////////////////
// START OF Dep TAB///
///
wDepTab=new CTabItem(wTabFolder, SWT.NONE);
wDepTab.setText(BaseMessages.getString(PKG, "TransDialog.DepTab.Label"));
FormLayout DepLayout = new FormLayout ();
DepLayout.marginWidth = Const.MARGIN;
DepLayout.marginHeight = Const.MARGIN;
Composite wDepComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wDepComp);
wDepComp.setLayout(DepLayout);
Label wlFields = new Label(wDepComp, SWT.RIGHT);
wlFields.setText(BaseMessages.getString(PKG, "TransDialog.Fields.Label"));
props.setLook(wlFields);
FormData fdlFields = new FormData();
fdlFields.left = new FormAttachment(0, 0);
fdlFields.top = new FormAttachment(0, 0);
wlFields.setLayoutData(fdlFields);
final int FieldsCols=3;
final int FieldsRows=transMeta.nrDependencies();
ColumnInfo[] colinf=new ColumnInfo[FieldsCols];
colinf[0]=new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.ColumnInfo.Connection.Label"), ColumnInfo.COLUMN_TYPE_CCOMBO, connectionNames);
colinf[1]=new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.ColumnInfo.Table.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false);
colinf[2]=new ColumnInfo(BaseMessages.getString(PKG, "TransDialog.ColumnInfo.Field.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false);
wFields=new TableView(transMeta, wDepComp,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI,
colinf,
FieldsRows,
lsMod,
props
);
wGet=new Button(wDepComp, SWT.PUSH);
wGet.setText(BaseMessages.getString(PKG, "TransDialog.GetDependenciesButton.Label"));
fdGet = new FormData();
fdGet.bottom = new FormAttachment(100, 0);
fdGet.left = new FormAttachment(50, 0);
wGet.setLayoutData(fdGet);
FormData fdFields = new FormData();
fdFields.left = new FormAttachment(0, 0);
fdFields.top = new FormAttachment(wlFields, margin);
fdFields.right = new FormAttachment(100, 0);
fdFields.bottom= new FormAttachment(wGet, 0);
wFields.setLayoutData(fdFields);
FormData fdDepComp = new FormData();
fdDepComp.left = new FormAttachment(0, 0);
fdDepComp.top = new FormAttachment(0, 0);
fdDepComp.right = new FormAttachment(100, 0);
fdDepComp.bottom= new FormAttachment(100, 0);
wDepComp.setLayoutData(fdDepComp);
wDepComp.layout();
wDepTab.setControl(wDepComp);
/////////////////////////////////////////////////////////////
/// END OF DEP TAB
/////////////////////////////////////////////////////////////
}
private void addMiscTab()
{
//////////////////////////
// START OF PERFORMANCE TAB///
///
wMiscTab=new CTabItem(wTabFolder, SWT.NONE);
wMiscTab.setText(BaseMessages.getString(PKG, "TransDialog.MiscTab.Label"));
Composite wMiscComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wMiscComp);
FormLayout perfLayout = new FormLayout();
perfLayout.marginWidth = Const.FORM_MARGIN;
perfLayout.marginHeight = Const.FORM_MARGIN;
wMiscComp.setLayout(perfLayout);
// Rows in Rowset:
Label wlSizeRowset = new Label(wMiscComp, SWT.RIGHT);
wlSizeRowset.setText(BaseMessages.getString(PKG, "TransDialog.SizeRowset.Label"));
wlSizeRowset.setToolTipText(BaseMessages.getString(PKG, "TransDialog.SizeRowset.Tooltip"));
props.setLook(wlSizeRowset);
FormData fdlSizeRowset = new FormData();
fdlSizeRowset.left = new FormAttachment(0, 0);
fdlSizeRowset.right= new FormAttachment(middle, -margin);
fdlSizeRowset.top = new FormAttachment(0, margin);
wlSizeRowset.setLayoutData(fdlSizeRowset);
wSizeRowset=new Text(wMiscComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wSizeRowset.setToolTipText(BaseMessages.getString(PKG, "TransDialog.SizeRowset.Tooltip"));
props.setLook(wSizeRowset);
wSizeRowset.addModifyListener(lsMod);
FormData fdSizeRowset = new FormData();
fdSizeRowset.left = new FormAttachment(middle, 0);
fdSizeRowset.top = new FormAttachment(0, margin);
fdSizeRowset.right= new FormAttachment(100, 0);
wSizeRowset.setLayoutData(fdSizeRowset);
// Show feedback in transformations steps?
Label wlShowFeedback = new Label(wMiscComp, SWT.RIGHT);
wlShowFeedback.setText(BaseMessages.getString(PKG, "TransDialog.ShowFeedbackRow.Label"));
props.setLook(wlShowFeedback);
FormData fdlShowFeedback = new FormData();
fdlShowFeedback.left = new FormAttachment(0, 0);
fdlShowFeedback.top = new FormAttachment(wSizeRowset, margin);
fdlShowFeedback.right= new FormAttachment(middle, -margin);
wlShowFeedback.setLayoutData(fdlShowFeedback);
wShowFeedback=new Button(wMiscComp, SWT.CHECK);
props.setLook(wShowFeedback);
wShowFeedback.addSelectionListener(lsModSel);
FormData fdShowFeedback = new FormData();
fdShowFeedback.left = new FormAttachment(middle, 0);
fdShowFeedback.top = new FormAttachment(wSizeRowset, margin);
fdShowFeedback.right= new FormAttachment(100, 0);
wShowFeedback.setLayoutData(fdShowFeedback);
// Feedback size
Label wlFeedbackSize = new Label(wMiscComp, SWT.RIGHT);
wlFeedbackSize.setText(BaseMessages.getString(PKG, "TransDialog.FeedbackSize.Label"));
props.setLook(wlFeedbackSize);
FormData fdlFeedbackSize = new FormData();
fdlFeedbackSize.left = new FormAttachment(0, 0);
fdlFeedbackSize.right= new FormAttachment(middle, -margin);
fdlFeedbackSize.top = new FormAttachment(wShowFeedback, margin);
wlFeedbackSize.setLayoutData(fdlFeedbackSize);
wFeedbackSize=new Text(wMiscComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wFeedbackSize);
wFeedbackSize.addModifyListener(lsMod);
FormData fdFeedbackSize = new FormData();
fdFeedbackSize.left = new FormAttachment(middle, 0);
fdFeedbackSize.right= new FormAttachment(100, -margin);
fdFeedbackSize.top = new FormAttachment(wShowFeedback, margin);
wFeedbackSize.setLayoutData(fdFeedbackSize);
// Unique connections
Label wlUniqueConnections = new Label(wMiscComp, SWT.RIGHT);
wlUniqueConnections.setText(BaseMessages.getString(PKG, "TransDialog.UniqueConnections.Label"));
props.setLook(wlUniqueConnections);
FormData fdlUniqueConnections = new FormData();
fdlUniqueConnections.left = new FormAttachment(0, 0);
fdlUniqueConnections.right= new FormAttachment(middle, -margin);
fdlUniqueConnections.top = new FormAttachment(wFeedbackSize, margin);
wlUniqueConnections.setLayoutData(fdlUniqueConnections);
wUniqueConnections=new Button(wMiscComp, SWT.CHECK);
props.setLook(wUniqueConnections);
wUniqueConnections.addSelectionListener(lsModSel);
FormData fdUniqueConnections = new FormData();
fdUniqueConnections.left = new FormAttachment(middle, 0);
fdUniqueConnections.top = new FormAttachment(wFeedbackSize, margin);
fdUniqueConnections.right= new FormAttachment(100, 0);
wUniqueConnections.setLayoutData(fdUniqueConnections);
// Shared objects file
Label wlSharedObjectsFile = new Label(wMiscComp, SWT.RIGHT);
wlSharedObjectsFile.setText(BaseMessages.getString(PKG, "TransDialog.SharedObjectsFile.Label"));
props.setLook(wlSharedObjectsFile);
FormData fdlSharedObjectsFile = new FormData();
fdlSharedObjectsFile.left = new FormAttachment(0, 0);
fdlSharedObjectsFile.right= new FormAttachment(middle, -margin);
fdlSharedObjectsFile.top = new FormAttachment(wUniqueConnections, margin);
wlSharedObjectsFile.setLayoutData(fdlSharedObjectsFile);
wSharedObjectsFile=new TextVar(transMeta, wMiscComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wlSharedObjectsFile.setToolTipText(BaseMessages.getString(PKG, "TransDialog.SharedObjectsFile.Tooltip"));
wSharedObjectsFile.setToolTipText(BaseMessages.getString(PKG, "TransDialog.SharedObjectsFile.Tooltip"));
props.setLook(wSharedObjectsFile);
FormData fdSharedObjectsFile = new FormData();
fdSharedObjectsFile.left = new FormAttachment(middle, 0);
fdSharedObjectsFile.top = new FormAttachment(wUniqueConnections, margin);
fdSharedObjectsFile.right= new FormAttachment(100, 0);
wSharedObjectsFile.setLayoutData(fdSharedObjectsFile);
wSharedObjectsFile.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent arg0)
{
sharedObjectsFileChanged = true;
}
}
);
// Show feedback in transformations steps?
Label wlManageThreads = new Label(wMiscComp, SWT.RIGHT);
wlManageThreads.setText(BaseMessages.getString(PKG, "TransDialog.ManageThreadPriorities.Label"));
props.setLook(wlManageThreads);
FormData fdlManageThreads = new FormData();
fdlManageThreads.left = new FormAttachment(0, 0);
fdlManageThreads.top = new FormAttachment(wSharedObjectsFile, margin);
fdlManageThreads.right= new FormAttachment(middle, -margin);
wlManageThreads.setLayoutData(fdlManageThreads);
wManageThreads=new Button(wMiscComp, SWT.CHECK);
wManageThreads.addSelectionListener(lsModSel);
props.setLook(wManageThreads);
FormData fdManageThreads = new FormData();
fdManageThreads.left = new FormAttachment(middle, 0);
fdManageThreads.top = new FormAttachment(wSharedObjectsFile, margin);
fdManageThreads.right= new FormAttachment(100, 0);
wManageThreads.setLayoutData(fdManageThreads);
// Single threaded option ...
Label wlTransformationType = new Label(wMiscComp, SWT.RIGHT);
wlTransformationType.setText(BaseMessages.getString(PKG, "TransDialog.TransformationType.Label"));
wlTransformationType.setToolTipText(BaseMessages.getString(PKG, "TransDialog.TransformationType.Tooltip", Const.CR));
props.setLook(wlTransformationType);
FormData fdlTransformationType = new FormData();
fdlTransformationType.left = new FormAttachment(0, 0);
fdlTransformationType.right = new FormAttachment(middle, -margin);
fdlTransformationType.top = new FormAttachment(wManageThreads, margin);
wlTransformationType.setLayoutData(fdlTransformationType);
wTransformationType = new CCombo(wMiscComp, SWT.NORMAL);
wTransformationType.setToolTipText(BaseMessages.getString(PKG, "TransDialog.TransformationType.Tooltip", Const.CR));
wTransformationType.addSelectionListener(lsModSel);
props.setLook(wTransformationType);
FormData fdTransformationType = new FormData();
fdTransformationType.left = new FormAttachment(middle, 0);
fdTransformationType.top = new FormAttachment(wManageThreads, margin);
fdTransformationType.right = new FormAttachment(100, 0);
wTransformationType.setLayoutData(fdTransformationType);
wTransformationType.setItems(TransformationType.getTransformationTypesDescriptions());
FormData fdMiscComp = new FormData();
fdMiscComp.left = new FormAttachment(0, 0);
fdMiscComp.top = new FormAttachment(0, 0);
fdMiscComp.right = new FormAttachment(100, 0);
fdMiscComp.bottom= new FormAttachment(100, 0);
wMiscComp.setLayoutData(fdMiscComp);
wMiscComp.layout();
wMiscTab.setControl(wMiscComp);
/////////////////////////////////////////////////////////////
/// END OF PERF TAB
/////////////////////////////////////////////////////////////
}
private void addMonitoringTab() {
// ////////////////////////
// START OF MONITORING TAB///
// /
wMonitorTab = new CTabItem(wTabFolder, SWT.NONE);
wMonitorTab.setText(BaseMessages.getString(PKG, "TransDialog.MonitorTab.Label"));
Composite wMonitorComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wMonitorComp);
FormLayout monitorLayout = new FormLayout();
monitorLayout.marginWidth = Const.FORM_MARGIN;
monitorLayout.marginHeight = Const.FORM_MARGIN;
wMonitorComp.setLayout(monitorLayout);
//
// Enable step performance monitoring?
//
Label wlEnableStepPerfMonitor = new Label(wMonitorComp, SWT.LEFT);
wlEnableStepPerfMonitor.setText(BaseMessages.getString(PKG, "TransDialog.StepPerformanceMonitoring.Label"));
props.setLook(wlEnableStepPerfMonitor);
FormData fdlSchemaName = new FormData();
fdlSchemaName.left = new FormAttachment(0, 0);
fdlSchemaName.right = new FormAttachment(middle, -margin);
fdlSchemaName.top = new FormAttachment(0, 0);
wlEnableStepPerfMonitor.setLayoutData(fdlSchemaName);
wEnableStepPerfMonitor = new Button(wMonitorComp, SWT.CHECK);
props.setLook(wEnableStepPerfMonitor);
FormData fdEnableStepPerfMonitor = new FormData();
fdEnableStepPerfMonitor.left = new FormAttachment(middle, 0);
fdEnableStepPerfMonitor.right = new FormAttachment(100, 0);
fdEnableStepPerfMonitor.top = new FormAttachment(0, 0);
wEnableStepPerfMonitor.setLayoutData(fdEnableStepPerfMonitor);
wEnableStepPerfMonitor.addSelectionListener(lsModSel);
wEnableStepPerfMonitor.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent selectionEvent) {
setFlags();
}
});
//
// Step performance interval
//
Label wlStepPerfInterval = new Label(wMonitorComp, SWT.LEFT);
wlStepPerfInterval.setText(BaseMessages.getString(PKG, "TransDialog.StepPerformanceInterval.Label"));
props.setLook(wlStepPerfInterval);
FormData fdlStepPerfInterval = new FormData();
fdlStepPerfInterval.left = new FormAttachment(0, 0);
fdlStepPerfInterval.right = new FormAttachment(middle, -margin);
fdlStepPerfInterval.top = new FormAttachment(wEnableStepPerfMonitor, margin);
wlStepPerfInterval.setLayoutData(fdlStepPerfInterval);
wStepPerfInterval = new Text(wMonitorComp, SWT.LEFT | SWT.BORDER | SWT.SINGLE);
props.setLook(wStepPerfInterval);
FormData fdStepPerfInterval = new FormData();
fdStepPerfInterval.left = new FormAttachment(middle, 0);
fdStepPerfInterval.right = new FormAttachment(100, 0);
fdStepPerfInterval.top = new FormAttachment(wEnableStepPerfMonitor, margin);
wStepPerfInterval.setLayoutData(fdStepPerfInterval);
wStepPerfInterval.addModifyListener(lsMod);
//
// Step performance interval
//
Label wlStepPerfMaxSize = new Label(wMonitorComp, SWT.LEFT);
wlStepPerfMaxSize.setText(BaseMessages.getString(PKG, "TransDialog.StepPerformanceMaxSize.Label"));
wlStepPerfMaxSize.setToolTipText(BaseMessages.getString(PKG, "TransDialog.StepPerformanceMaxSize.Tooltip"));
props.setLook(wlStepPerfMaxSize);
FormData fdlStepPerfMaxSize = new FormData();
fdlStepPerfMaxSize.left = new FormAttachment(0, 0);
fdlStepPerfMaxSize.right = new FormAttachment(middle, -margin);
fdlStepPerfMaxSize.top = new FormAttachment(wStepPerfInterval, margin);
wlStepPerfMaxSize.setLayoutData(fdlStepPerfMaxSize);
wStepPerfMaxSize = new TextVar(transMeta, wMonitorComp, SWT.LEFT | SWT.BORDER | SWT.SINGLE);
wStepPerfMaxSize.setToolTipText(BaseMessages.getString(PKG, "TransDialog.StepPerformanceMaxSize.Tooltip"));
props.setLook(wStepPerfMaxSize);
FormData fdStepPerfMaxSize = new FormData();
fdStepPerfMaxSize.left = new FormAttachment(middle, 0);
fdStepPerfMaxSize.right = new FormAttachment(100, 0);
fdStepPerfMaxSize.top = new FormAttachment(wStepPerfInterval, margin);
wStepPerfMaxSize.setLayoutData(fdStepPerfMaxSize);
wStepPerfMaxSize.addModifyListener(lsMod);
FormData fdMonitorComp = new FormData();
fdMonitorComp.left = new FormAttachment(0, 0);
fdMonitorComp.top = new FormAttachment(0, 0);
fdMonitorComp.right = new FormAttachment(100, 0);
fdMonitorComp.bottom = new FormAttachment(100, 0);
wMonitorComp.setLayoutData(fdMonitorComp);
wMonitorComp.layout();
wMonitorTab.setControl(wMonitorComp);
// ///////////////////////////////////////////////////////////
// / END OF MONITORING TAB
// ///////////////////////////////////////////////////////////
}
public void dispose()
{
shell.dispose();
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData() {
wTransname.setText(Const.NVL(transMeta.getName(), ""));
wTransFilename.setText(Const.NVL(transMeta.getFilename(), ""));
wTransdescription.setText(Const.NVL(transMeta.getDescription(), ""));
wExtendeddescription.setText(Const.NVL(transMeta.getExtendedDescription(), ""));
wTransversion.setText(Const.NVL(transMeta.getTransversion(), ""));
wTransstatus.select(transMeta.getTransstatus() - 1);
if (transMeta.getCreatedUser() != null)
wCreateUser.setText(transMeta.getCreatedUser());
if (transMeta.getCreatedDate() != null)
wCreateDate.setText(transMeta.getCreatedDate().toString());
if (transMeta.getModifiedUser() != null)
wModUser.setText(transMeta.getModifiedUser());
if (transMeta.getModifiedDate() != null)
wModDate.setText(transMeta.getModifiedDate().toString());
if (transMeta.getMaxDateConnection() != null)
wMaxdateconnection.setText(transMeta.getMaxDateConnection().getName());
if (transMeta.getMaxDateTable() != null)
wMaxdatetable.setText(transMeta.getMaxDateTable());
if (transMeta.getMaxDateField() != null)
wMaxdatefield.setText(transMeta.getMaxDateField());
wMaxdateoffset.setText(Double.toString(transMeta.getMaxDateOffset()));
wMaxdatediff.setText(Double.toString(transMeta.getMaxDateDifference()));
// The dependencies
for (int i = 0; i < transMeta.nrDependencies(); i++) {
TableItem item = wFields.table.getItem(i);
TransDependency td = transMeta.getDependency(i);
DatabaseMeta conn = td.getDatabase();
String table = td.getTablename();
String field = td.getFieldname();
if (conn != null)
item.setText(1, conn.getName());
if (table != null)
item.setText(2, table);
if (field != null)
item.setText(3, field);
}
// The named parameters
String[] parameters = transMeta.listParameters();
for (int idx = 0; idx < parameters.length; idx++) {
TableItem item = wParamFields.table.getItem(idx);
String defValue;
try {
defValue = transMeta.getParameterDefault(parameters[idx]);
} catch (UnknownParamException e) {
defValue = "";
}
String description;
try {
description = transMeta.getParameterDescription(parameters[idx]);
} catch (UnknownParamException e) {
description = "";
}
item.setText(1, parameters[idx]);
item.setText(2, Const.NVL(defValue, ""));
item.setText(3, Const.NVL(description, ""));
}
wSizeRowset.setText(Integer.toString(transMeta.getSizeRowset()));
wUniqueConnections.setSelection(transMeta.isUsingUniqueConnections());
wShowFeedback.setSelection(transMeta.isFeedbackShown());
wFeedbackSize.setText(Integer.toString(transMeta.getFeedbackSize()));
wSharedObjectsFile.setText(Const.NVL(transMeta.getSharedObjectsFile(), ""));
wManageThreads.setSelection(transMeta.isUsingThreadPriorityManagment());
wTransformationType.setText(transMeta.getTransformationType().getDescription());
wFields.setRowNums();
wFields.optWidth(true);
wParamFields.setRowNums();
wParamFields.optWidth(true);
// Directory:
if (transMeta.getRepositoryDirectory() != null && transMeta.getRepositoryDirectory().getPath() != null)
wDirectory.setText(transMeta.getRepositoryDirectory().getPath());
// Performance monitoring tab:
//
wEnableStepPerfMonitor.setSelection(transMeta.isCapturingStepPerformanceSnapShots());
wStepPerfInterval.setText(Long.toString(transMeta.getStepPerformanceCapturingDelay()));
wStepPerfMaxSize.setText(Const.NVL(transMeta.getStepPerformanceCapturingSizeLimit(), ""));
wTransname.selectAll();
wTransname.setFocus();
for (TransDialogPluginInterface extraTab : extraTabs) {
try {
extraTab.getData(transMeta);
} catch(Exception e) {
new ErrorDialog(shell, "Error", "Error adding extra plugin tab", e);
}
}
setFlags();
}
public void setFlags()
{
wbDirectory.setEnabled(rep!=null);
// wDirectory.setEnabled(rep!=null);
wlDirectory.setEnabled(rep!=null);
// wlStepLogtable.setEnabled(wEnableStepPerfMonitor.getSelection());
// wStepLogtable.setEnabled(wEnableStepPerfMonitor.getSelection());
// wlLogSizeLimit.setEnabled(wLogfield.getSelection());
// wLogSizeLimit.setEnabled(wLogfield.getSelection());
}
private void cancel() {
props.setScreen(new WindowProperty(shell));
transMeta = null;
dispose();
}
private void ok() {
boolean OK = true;
getLogInfo();
transMeta.setTransLogTable(transLogTable);
transMeta.setPerformanceLogTable(performanceLogTable);
transMeta.setChannelLogTable(channelLogTable);
transMeta.setStepLogTable(stepLogTable);
transMeta.setMetricsLogTable(metricsLogTable);
// transMeta.setStepPerformanceLogTable(wStepLogtable.getText());
transMeta.setMaxDateConnection(transMeta.findDatabase(wMaxdateconnection.getText()));
transMeta.setMaxDateTable(wMaxdatetable.getText());
transMeta.setMaxDateField(wMaxdatefield.getText());
transMeta.setName(wTransname.getText());
transMeta.setDescription(wTransdescription.getText());
transMeta.setExtendedDescription(wExtendeddescription.getText());
transMeta.setTransversion(wTransversion.getText());
if (wTransstatus.getSelectionIndex() != 2) {
transMeta.setTransstatus(wTransstatus.getSelectionIndex() + 1);
} else {
transMeta.setTransstatus(-1);
}
try {
transMeta.setMaxDateOffset(Double.parseDouble(wMaxdateoffset.getText()));
} catch (Exception e) {
MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
mb.setText(BaseMessages.getString(PKG, "TransDialog.InvalidOffsetNumber.DialogTitle"));
mb.setMessage(BaseMessages.getString(PKG, "TransDialog.InvalidOffsetNumber.DialogMessage"));
mb.open();
wMaxdateoffset.setFocus();
wMaxdateoffset.selectAll();
OK = false;
}
try {
transMeta.setMaxDateDifference(Double.parseDouble(wMaxdatediff.getText()));
} catch (Exception e) {
MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
mb.setText(BaseMessages.getString(PKG, "TransDialog.InvalidDateDifferenceNumber.DialogTitle"));
mb.setMessage(BaseMessages.getString(PKG, "TransDialog.InvalidDateDifferenceNumber.DialogMessage"));
mb.open();
wMaxdatediff.setFocus();
wMaxdatediff.selectAll();
OK = false;
}
// Clear and add current dependencies
transMeta.removeAllDependencies();
int nrNonEmptyFields = wFields.nrNonEmpty();
for (int i = 0; i < nrNonEmptyFields; i++) {
TableItem item = wFields.getNonEmpty(i);
DatabaseMeta db = transMeta.findDatabase(item.getText(1));
String tablename = item.getText(2);
String fieldname = item.getText(3);
TransDependency td = new TransDependency(db, tablename, fieldname);
transMeta.addDependency(td);
}
// Clear and add parameters
transMeta.eraseParameters();
nrNonEmptyFields = wParamFields.nrNonEmpty();
for (int i = 0; i < nrNonEmptyFields; i++) {
TableItem item = wParamFields.getNonEmpty(i);
try {
transMeta.addParameterDefinition(item.getText(1), item.getText(2), item.getText(3));
} catch (DuplicateParamException e) {
// Ignore the duplicate parameter.
}
}
transMeta.activateParameters();
transMeta.setSizeRowset(Const.toInt(wSizeRowset.getText(), Const.ROWS_IN_ROWSET));
transMeta.setUsingUniqueConnections(wUniqueConnections.getSelection());
transMeta.setFeedbackShown(wShowFeedback.getSelection());
transMeta.setFeedbackSize(Const.toInt(wFeedbackSize.getText(), Const.ROWS_UPDATE));
transMeta.setSharedObjectsFile(wSharedObjectsFile.getText());
transMeta.setUsingThreadPriorityManagment(wManageThreads.getSelection());
transMeta.setTransformationType( TransformationType.values()[ Const.indexOfString(wTransformationType.getText(), TransformationType.getTransformationTypesDescriptions()) ] );
if (directoryChangeAllowed && transMeta.getObjectId()!=null) {
if (newDirectory != null) {
RepositoryDirectoryInterface dirFrom = transMeta.getRepositoryDirectory();
try {
ObjectId newId = rep.renameTransformation(transMeta.getObjectId(), newDirectory, transMeta.getName());
transMeta.setObjectId(newId);
transMeta.setRepositoryDirectory(newDirectory);
} catch (KettleException ke) {
transMeta.setRepositoryDirectory(dirFrom);
OK = false;
new ErrorDialog(shell, BaseMessages.getString(PKG, "TransDialog.ErrorMovingTransformation.DialogTitle"), BaseMessages.getString(PKG, "TransDialog.ErrorMovingTransformation.DialogMessage"), ke);
}
}
} else {
// Just update to the new selected directory...
//
if (newDirectory != null)
transMeta.setRepositoryDirectory(newDirectory);
}
// Performance monitoring tab:
//
transMeta.setCapturingStepPerformanceSnapShots(wEnableStepPerfMonitor.getSelection());
transMeta.setStepPerformanceCapturingSizeLimit(wStepPerfMaxSize.getText());
try {
long stepPerformanceCapturingDelay = Long.parseLong(wStepPerfInterval.getText());
// values equal or less than zero cause problems during monitoring
if (stepPerformanceCapturingDelay <= 0 && transMeta.isCapturingStepPerformanceSnapShots()) {
throw new KettleException();
} else {
if(stepPerformanceCapturingDelay <= 0) {
// PDI-4848: Default to 1 second if step performance monitoring is disabled
stepPerformanceCapturingDelay = 1000;
}
transMeta.setStepPerformanceCapturingDelay(stepPerformanceCapturingDelay);
}
} catch (Exception e) {
MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
mb.setText(BaseMessages.getString(PKG, "TransDialog.InvalidStepPerfIntervalNumber.DialogTitle"));
mb.setMessage(BaseMessages.getString(PKG, "TransDialog.InvalidStepPerfIntervalNumber.DialogMessage"));
mb.open();
wStepPerfInterval.setFocus();
wStepPerfInterval.selectAll();
OK = false;
}
for (TransDialogPluginInterface extraTab : extraTabs) {
try {
extraTab.ok(transMeta);
} catch(Exception e) {
new ErrorDialog(shell, "Error", "Error getting information from extra plugin tab", e);
}
}
if (OK) {
transMeta.setChanged(changed || transMeta.hasChanged());
dispose();
}
}
// Get the dependencies
private void get()
{
Table table = wFields.table;
for (int i=0;i<transMeta.nrSteps();i++)
{
StepMeta stepMeta = transMeta.getStep(i);
String con=null;
String tab=null;
TableItem item=null;
StepMetaInterface sii = stepMeta.getStepMetaInterface();
if (sii instanceof TableInputMeta)
{
TableInputMeta tii = (TableInputMeta)stepMeta.getStepMetaInterface();
if (tii.getDatabaseMeta()==null)
{
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setMessage(BaseMessages.getString(PKG, "TransDialog.DatabaseMetaNotSet.Text"));
mb.open();
return;
}
con = tii.getDatabaseMeta().getName();
tab = getTableFromSQL(tii.getSQL());
if (tab==null) tab=stepMeta.getName();
}
if (sii instanceof DatabaseLookupMeta)
{
DatabaseLookupMeta dvli = (DatabaseLookupMeta)stepMeta.getStepMetaInterface();
con = dvli.getDatabaseMeta().getName();
tab = dvli.getTablename();
if (tab==null) tab=stepMeta.getName();
break;
}
if (tab!=null || con!=null)
{
item = new TableItem(table, SWT.NONE);
if (con!=null) item.setText(1, con);
if (tab!=null) item.setText(2, tab);
}
}
wFields.setRowNums();
}
private String getTableFromSQL(String sql)
{
if (sql==null) return null;
int idxfrom = sql.toUpperCase().indexOf("FROM");
int idxto = sql.toUpperCase().indexOf("WHERE");
if (idxfrom==-1) return null;
if (idxto==-1) idxto=sql.length();
return sql.substring(idxfrom+5, idxto);
}
/**
* Generates code for create table...
* Conversions done by Database
*/
private void sql()
{
getLogInfo();
try {
boolean allOK = true;
for (LogTableInterface logTable : new LogTableInterface[] { transLogTable, performanceLogTable, channelLogTable, stepLogTable, metricsLogTable, } ) {
if (logTable.getDatabaseMeta()!=null && !Const.isEmpty(logTable.getTableName())) {
// OK, we have something to work with!
//
Database db = null;
try {
db = new Database(transMeta, logTable.getDatabaseMeta());
db.shareVariablesWith(transMeta);
db.connect();
StringBuilder ddl = new StringBuilder();
RowMetaInterface fields = logTable.getLogRecord(LogStatus.START, null, null).getRowMeta();
String tableName = db.environmentSubstitute(logTable.getTableName());
String schemaTable = logTable.getDatabaseMeta().getQuotedSchemaTableCombination(db.environmentSubstitute(logTable.getSchemaName()), tableName);
String createTable = db.getDDL(schemaTable, fields);
if (!Const.isEmpty(createTable))
{
ddl.append("-- ").append(logTable.getLogTableType()).append(Const.CR);
ddl.append("--").append(Const.CR).append(Const.CR);
ddl.append(createTable).append(Const.CR);
}
java.util.List<RowMetaInterface> indexes = logTable.getRecommendedIndexes();
for (int i=0;i<indexes.size();i++) {
RowMetaInterface index = indexes.get(i);
if (!index.isEmpty()) {
String createIndex = db.getCreateIndexStatement(schemaTable, "IDX_"+tableName+"_"+(i+1), index.getFieldNames(), false, false, false, true);
if (!Const.isEmpty(createIndex)) {
ddl.append(createIndex);
}
}
}
if (ddl.length()>0) {
allOK=false;
SQLEditor sqledit = new SQLEditor(transMeta, shell, SWT.NONE, logTable.getDatabaseMeta(), transMeta.getDbCache(), ddl.toString());
sqledit.open();
}
} finally {
if (db!=null) {
db.disconnect();
}
}
}
}
if (allOK) {
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setText(BaseMessages.getString(PKG, "TransDialog.NoSqlNedds.DialogTitle"));
mb.setMessage(BaseMessages.getString(PKG, "TransDialog.NoSqlNedds.DialogMessage"));
mb.open();
}
} catch(Exception e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "TransDialog.ErrorOccurred.DialogTitle"), BaseMessages.getString(PKG, "TransDialog.ErrorOccurred.DialogMessage"), e);
}
}
private void getLogInfo() {
getTransLogTableOptions();
getPerformanceLogTableOptions();
getChannelLogTableOptions();
getStepLogTableOptions();
getMetricsLogTableOptions();
}
public boolean isSharedObjectsFileChanged()
{
return sharedObjectsFileChanged;
}
public void setDirectoryChangeAllowed(boolean directoryChangeAllowed) {
this.directoryChangeAllowed = directoryChangeAllowed;
}
private void setCurrentTab(Tabs currentTab){
switch (currentTab) {
case PARAM_TAB:
wTabFolder.setSelection(wParamTab);
break;
case MISC_TAB:
wTabFolder.setSelection(wMiscTab);
break;
case DATE_TAB:
wTabFolder.setSelection(wDateTab);
break;
case LOG_TAB:
wTabFolder.setSelection(wLogTab);
break;
case DEP_TAB:
wTabFolder.setSelection(wDepTab);
break;
case MONITOR_TAB:
wTabFolder.setSelection(wMonitorTab);
break;
case EXTRA_TAB:
if (extraTabs.size()>0) {
wTabFolder.setSelection(extraTabs.get(0).getTab());
}
break;
case TRANS_TAB:
default:
wTabFolder.setSelection(wTransTab);
break;
}
}
} | [
"[email protected]"
] | |
820c79fbd7ef0b7a8bc8a40a5b73c19d23db7c39 | 3999c1034a70935846d7208ff0b69fe537814a40 | /karma-common/src/main/java/edu/isi/karma/rep/alignment/LinkPriorityComparator.java | 23a4b19ac54ad056bfe5d3067ed05a02002e3f1a | [
"Apache-2.0"
] | permissive | usc-isi-i2/Web-Karma | 2f15b7759ce3338702f3da3a06fbee8ba118de8e | 05392615086538e95322278e705f76f9bbf2ed71 | refs/heads/master | 2023-09-02T05:18:12.455691 | 2023-08-31T16:40:28 | 2023-08-31T16:40:28 | 2,442,452 | 526 | 187 | Apache-2.0 | 2023-09-06T23:14:09 | 2011-09-23T06:58:53 | Java | UTF-8 | Java | false | false | 2,227 | java | /*******************************************************************************
* Copyright 2012 University of Southern California
*
* 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.
*
* This code was developed by the Information Integration Group as part
* of the Karma project at the Information Sciences Institute of the
* University of Southern California. For more information, publications,
* and related projects, please see: http://www.isi.edu/integration
******************************************************************************/
package edu.isi.karma.rep.alignment;
import java.util.Comparator;
public class LinkPriorityComparator implements Comparator<LabeledLink> {
@Override
public int compare(LabeledLink o1, LabeledLink o2) {
String p1 = getPriority(o1);
String p2 = getPriority(o2);
return p1.compareTo(p2);
}
private String getPriority(LabeledLink link) {
if (link instanceof ObjectPropertyLink && ((ObjectPropertyLink)link).getObjectPropertyType() == ObjectPropertyType.Direct) return "0";
else if (link instanceof ObjectPropertyLink && ((ObjectPropertyLink)link).getObjectPropertyType() == ObjectPropertyType.Indirect) return "1";
else if (link instanceof ObjectPropertyLink && ((ObjectPropertyLink)link).getObjectPropertyType() == ObjectPropertyType.WithOnlyDomain) return "2";
else if (link instanceof ObjectPropertyLink && ((ObjectPropertyLink)link).getObjectPropertyType() == ObjectPropertyType.WithOnlyRange) return "2";
else if (link instanceof ObjectPropertyLink && ((ObjectPropertyLink)link).getObjectPropertyType() == ObjectPropertyType.WithoutDomainAndRange) return "3";
else if (link instanceof SubClassLink) return "4";
else return "5";
}
}
| [
"[email protected]"
] | |
84dcda1863045d7fbecdccdd47729ba0cc51224d | 8a21d470aa02ef82717eaec68b7d756e058d793a | /Flash Card Study/src/QuestionImporter.java | f0a26164926ac7d629689c8a29539b8a9a4f1d81 | [] | no_license | zinktrita/Cert-Study | a36096802a808037cf29941e9ded741a6b5c730c | 95ba1274a6b45cded791be0b531105384a970f74 | refs/heads/master | 2021-01-20T05:31:20.238331 | 2014-12-23T17:45:27 | 2014-12-23T17:45:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,133 | java | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public abstract class QuestionImporter {
static String tmpQuestionNumber;
static String tmpQuestion;
static String tmpCorrectAnswer;
static List<String> tmpPossibleAnswers = new ArrayList<String>();
public static void importFile(String file) {
BufferedReader br;
try {
br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
if (isQuestionNumber(line) == true) {
tmpQuestionNumber = line;
}
else if (isPossibleAnswer(line) == true) {
tmpPossibleAnswers.add(line);
}
else if (isExplanation(line) == true) {
ClassMain.questionList.add(new Question(tmpQuestionNumber, tmpQuestion, tmpCorrectAnswer, tmpPossibleAnswers));
tmpPossibleAnswers.clear();
}
else if (isCorrectAnswer(line) == true) {
tmpCorrectAnswer = line;
}
else {
tmpQuestion = line;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
static boolean isPossibleAnswer(String line) {
boolean returnValue = false;
if (line.charAt(1) == '.') {
returnValue = true;
}
return returnValue;
}
static boolean isCorrectAnswer(String line) {
boolean returnValue = true;
for (int i = 0; i < "Answer".length(); i++) {
if (line.charAt(i) != "Answer".charAt(i)) {
return false;
}
}
return returnValue;
}
static boolean isExplanation(String line) {
boolean returnValue = true;
for (int i = 0; i < "Explanation".length(); i++) {
if (line.charAt(i) != "Explanation".charAt(i)) {
return false;
}
}
return returnValue;
}
static boolean isQuestionNumber(String line) {
boolean returnValue = true;
for (int i = 0; i < "QUESTION".length(); i++) {
if (line.charAt(i) != "QUESTION".charAt(i)) {
return false;
}
}
return returnValue;
}
}
| [
"[email protected]"
] | |
49f9b8e07bb84abdc1beebeabe249ed425da4e38 | e7be1dcb6e197ec87a2abce68d44dd40bc880f03 | /gen/com/intellij/xtextLanguage/xtext/psi/XtextTypes.java | a88d9fb209ef257f4c1e8e303079e59be5d00d15 | [] | no_license | pakhopav/XtextLanguage | 5df95daabf83b25ca90b2fa8010d5b6636bed36c | d9e1526453f0404821bfcbe41f3f49e3f708940e | refs/heads/master | 2020-07-02T07:22:53.224149 | 2019-08-12T13:40:44 | 2019-08-12T13:40:44 | 201,455,657 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | true | 14,375 | java | // This is a generated file. Not intended for manual editing.
package com.intellij.xtextLanguage.xtext.psi;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.PsiElement;
import com.intellij.lang.ASTNode;
import com.intellij.xtextLanguage.xtext.impl.*;
public interface XtextTypes {
IElementType ABSTRACT_METAMODEL_DECLARATION = new XtextElementType("ABSTRACT_METAMODEL_DECLARATION");
IElementType ABSTRACT_NEGATED_TOKEN = new XtextElementType("ABSTRACT_NEGATED_TOKEN");
IElementType ABSTRACT_TERMINAL = new XtextElementType("ABSTRACT_TERMINAL");
IElementType ABSTRACT_TOKEN = new XtextElementType("ABSTRACT_TOKEN");
IElementType ABSTRACT_TOKEN_WITH_CARDINALITY = new XtextElementType("ABSTRACT_TOKEN_WITH_CARDINALITY");
IElementType ACTION = new XtextElementType("ACTION");
IElementType ALTERNATIVES = new XtextElementType("ALTERNATIVES");
IElementType ANNOTATION = new XtextElementType("ANNOTATION");
IElementType ASSIGNABLE_ALTERNATIVES = new XtextElementType("ASSIGNABLE_ALTERNATIVES");
IElementType ASSIGNABLE_TERMINAL = new XtextElementType("ASSIGNABLE_TERMINAL");
IElementType ASSIGNMENT = new XtextElementType("ASSIGNMENT");
IElementType ATOM = new XtextElementType("ATOM");
IElementType CHARACTER_RANGE = new XtextElementType("CHARACTER_RANGE");
IElementType CONDITIONAL_BRANCH = new XtextElementType("CONDITIONAL_BRANCH");
IElementType CONJUNCTION = new XtextElementType("CONJUNCTION");
IElementType CROSS_REFERENCE = new XtextElementType("CROSS_REFERENCE");
IElementType CROSS_REFERENCEABLE_TERMINAL = new XtextElementType("CROSS_REFERENCEABLE_TERMINAL");
IElementType DISJUNCTION = new XtextElementType("DISJUNCTION");
IElementType ENUM_LITERALS = new XtextElementType("ENUM_LITERALS");
IElementType ENUM_LITERAL_DECLARATION = new XtextElementType("ENUM_LITERAL_DECLARATION");
IElementType ENUM_RULE = new XtextElementType("ENUM_RULE");
IElementType EOF = new XtextElementType("EOF");
IElementType GENERATED_METAMODEL = new XtextElementType("GENERATED_METAMODEL");
IElementType GRAMMAR_ID = new XtextElementType("GRAMMAR_ID");
IElementType GROUP = new XtextElementType("GROUP");
IElementType KEYWORD = new XtextElementType("KEYWORD");
IElementType LITERAL_CONDITION = new XtextElementType("LITERAL_CONDITION");
IElementType NAMED_ARGUMENT = new XtextElementType("NAMED_ARGUMENT");
IElementType NEGATED_TOKEN = new XtextElementType("NEGATED_TOKEN");
IElementType NEGATION = new XtextElementType("NEGATION");
IElementType PARAMETER = new XtextElementType("PARAMETER");
IElementType PARAMETER_REFERENCE = new XtextElementType("PARAMETER_REFERENCE");
IElementType PARENTHESIZED_ASSIGNABLE_ELEMENT = new XtextElementType("PARENTHESIZED_ASSIGNABLE_ELEMENT");
IElementType PARENTHESIZED_CONDITION = new XtextElementType("PARENTHESIZED_CONDITION");
IElementType PARENTHESIZED_ELEMENT = new XtextElementType("PARENTHESIZED_ELEMENT");
IElementType PARENTHESIZED_TERMINAL_ELEMENT = new XtextElementType("PARENTHESIZED_TERMINAL_ELEMENT");
IElementType PARSER_RULE = new XtextElementType("PARSER_RULE");
IElementType PREDICATED_GROUP = new XtextElementType("PREDICATED_GROUP");
IElementType PREDICATED_KEYWORD = new XtextElementType("PREDICATED_KEYWORD");
IElementType PREDICATED_RULE_CALL = new XtextElementType("PREDICATED_RULE_CALL");
IElementType REFERENCED_METAMODEL = new XtextElementType("REFERENCED_METAMODEL");
IElementType REFERENCE_ABSTRACT_METAMODEL_DECLARATION = new XtextElementType("REFERENCE_ABSTRACT_METAMODEL_DECLARATION");
IElementType REFERENCE_ABSTRACT_RULE_RULE_ID = new XtextElementType("REFERENCE_ABSTRACT_RULE_RULE_ID");
IElementType REFERENCE_ECORE_E_CLASSIFIER = new XtextElementType("REFERENCE_ECORE_E_CLASSIFIER");
IElementType REFERENCE_ECORE_E_ENUM_LITERAL = new XtextElementType("REFERENCE_ECORE_E_ENUM_LITERAL");
IElementType REFERENCE_ECORE_E_PACKAGE_STRING = new XtextElementType("REFERENCE_ECORE_E_PACKAGE_STRING");
IElementType REFERENCE_GRAMMAR_GRAMMAR_ID = new XtextElementType("REFERENCE_GRAMMAR_GRAMMAR_ID");
IElementType REFERENCE_PARAMETER_ID = new XtextElementType("REFERENCE_PARAMETER_ID");
IElementType RULE_CALL = new XtextElementType("RULE_CALL");
IElementType RULE_ID = new XtextElementType("RULE_ID");
IElementType RULE_IDENTIFIER = new XtextElementType("RULE_IDENTIFIER");
IElementType RULE_NAME_AND_PARAMS = new XtextElementType("RULE_NAME_AND_PARAMS");
IElementType TERMINAL_ALTERNATIVES = new XtextElementType("TERMINAL_ALTERNATIVES");
IElementType TERMINAL_GROUP = new XtextElementType("TERMINAL_GROUP");
IElementType TERMINAL_RULE = new XtextElementType("TERMINAL_RULE");
IElementType TERMINAL_RULE_CALL = new XtextElementType("TERMINAL_RULE_CALL");
IElementType TERMINAL_TOKEN = new XtextElementType("TERMINAL_TOKEN");
IElementType TERMINAL_TOKEN_ELEMENT = new XtextElementType("TERMINAL_TOKEN_ELEMENT");
IElementType TYPE_REF = new XtextElementType("TYPE_REF");
IElementType UNORDERED_GROUP = new XtextElementType("UNORDERED_GROUP");
IElementType UNTIL_TOKEN = new XtextElementType("UNTIL_TOKEN");
IElementType VALID_ID = new XtextElementType("VALID_ID");
IElementType WILDCARD = new XtextElementType("WILDCARD");
IElementType ACX_MARK = new XtextTokenType("!");
IElementType AMPERSAND = new XtextTokenType("&");
IElementType ANY_OTHER = new XtextTokenType("ANY_OTHER");
IElementType AS = new XtextTokenType("as");
IElementType ASTERISK = new XtextTokenType("*");
IElementType AT_SIGN = new XtextTokenType("@");
IElementType COLON = new XtextTokenType(":");
IElementType COLONS = new XtextTokenType("::");
IElementType COMMA = new XtextTokenType(",");
IElementType CURRENT = new XtextTokenType("current");
IElementType DOT = new XtextTokenType(".");
IElementType ENUM = new XtextTokenType("enum");
IElementType EOF_KEY = new XtextTokenType("EOF");
IElementType EQUALS = new XtextTokenType("=");
IElementType FALCE = new XtextTokenType("false");
IElementType FRAGMENT = new XtextTokenType("fragment");
IElementType GENERATE = new XtextTokenType("generate");
IElementType GRAMMAR = new XtextTokenType("grammar");
IElementType HIDDEN = new XtextTokenType("hidden");
IElementType ID = new XtextTokenType("ID");
IElementType IMPORT = new XtextTokenType("import");
IElementType INT = new XtextTokenType("INT");
IElementType L_ANGLE_BRACKET = new XtextTokenType("<");
IElementType L_BRACE = new XtextTokenType("{");
IElementType L_BRACKET = new XtextTokenType("(");
IElementType L_SQUARE_BRACKET = new XtextTokenType("[");
IElementType ML_COMMENT = new XtextTokenType("ML_COMMENT");
IElementType PIPE = new XtextTokenType("|");
IElementType PLUS = new XtextTokenType("+");
IElementType PLUS_EQUALS = new XtextTokenType("+=");
IElementType PRED = new XtextTokenType("=>");
IElementType QUES_EQUALS = new XtextTokenType("?=");
IElementType QUES_MARK = new XtextTokenType("?");
IElementType RANGE = new XtextTokenType("..");
IElementType RETURNS = new XtextTokenType("returns");
IElementType R_ANGLE_BRACKET = new XtextTokenType(">");
IElementType R_BRACE = new XtextTokenType("}");
IElementType R_BRACKET = new XtextTokenType(")");
IElementType R_SQUARE_BRACKET = new XtextTokenType("]");
IElementType SEMICOLON = new XtextTokenType(";");
IElementType SL_COMMENT = new XtextTokenType("SL_COMMENT");
IElementType STRING = new XtextTokenType("STRING");
IElementType TERMINAL = new XtextTokenType("terminal");
IElementType TRUE = new XtextTokenType("true");
IElementType WEAK_PRED = new XtextTokenType("->");
IElementType WITH = new XtextTokenType("with");
class Factory {
public static PsiElement createElement(ASTNode node) {
IElementType type = node.getElementType();
if (type == ABSTRACT_METAMODEL_DECLARATION) {
return new XtextAbstractMetamodelDeclarationImpl(node);
}
else if (type == ABSTRACT_NEGATED_TOKEN) {
return new XtextAbstractNegatedTokenImpl(node);
}
else if (type == ABSTRACT_TERMINAL) {
return new XtextAbstractTerminalImpl(node);
}
else if (type == ABSTRACT_TOKEN) {
return new XtextAbstractTokenImpl(node);
}
else if (type == ABSTRACT_TOKEN_WITH_CARDINALITY) {
return new XtextAbstractTokenWithCardinalityImpl(node);
}
else if (type == ACTION) {
return new XtextActionImpl(node);
}
else if (type == ALTERNATIVES) {
return new XtextAlternativesImpl(node);
}
else if (type == ANNOTATION) {
return new XtextAnnotationImpl(node);
}
else if (type == ASSIGNABLE_ALTERNATIVES) {
return new XtextAssignableAlternativesImpl(node);
}
else if (type == ASSIGNABLE_TERMINAL) {
return new XtextAssignableTerminalImpl(node);
}
else if (type == ASSIGNMENT) {
return new XtextAssignmentImpl(node);
}
else if (type == ATOM) {
return new XtextAtomImpl(node);
}
else if (type == CHARACTER_RANGE) {
return new XtextCharacterRangeImpl(node);
}
else if (type == CONDITIONAL_BRANCH) {
return new XtextConditionalBranchImpl(node);
}
else if (type == CONJUNCTION) {
return new XtextConjunctionImpl(node);
}
else if (type == CROSS_REFERENCE) {
return new XtextCrossReferenceImpl(node);
}
else if (type == CROSS_REFERENCEABLE_TERMINAL) {
return new XtextCrossReferenceableTerminalImpl(node);
}
else if (type == DISJUNCTION) {
return new XtextDisjunctionImpl(node);
}
else if (type == ENUM_LITERALS) {
return new XtextEnumLiteralsImpl(node);
}
else if (type == ENUM_LITERAL_DECLARATION) {
return new XtextEnumLiteralDeclarationImpl(node);
}
else if (type == ENUM_RULE) {
return new XtextEnumRuleImpl(node);
}
else if (type == EOF) {
return new XtextEofImpl(node);
}
else if (type == GENERATED_METAMODEL) {
return new XtextGeneratedMetamodelImpl(node);
}
else if (type == GRAMMAR_ID) {
return new XtextGrammarIDImpl(node);
}
else if (type == GROUP) {
return new XtextGroupImpl(node);
}
else if (type == KEYWORD) {
return new XtextKeywordImpl(node);
}
else if (type == LITERAL_CONDITION) {
return new XtextLiteralConditionImpl(node);
}
else if (type == NAMED_ARGUMENT) {
return new XtextNamedArgumentImpl(node);
}
else if (type == NEGATED_TOKEN) {
return new XtextNegatedTokenImpl(node);
}
else if (type == NEGATION) {
return new XtextNegationImpl(node);
}
else if (type == PARAMETER) {
return new XtextParameterImpl(node);
}
else if (type == PARAMETER_REFERENCE) {
return new XtextParameterReferenceImpl(node);
}
else if (type == PARENTHESIZED_ASSIGNABLE_ELEMENT) {
return new XtextParenthesizedAssignableElementImpl(node);
}
else if (type == PARENTHESIZED_CONDITION) {
return new XtextParenthesizedConditionImpl(node);
}
else if (type == PARENTHESIZED_ELEMENT) {
return new XtextParenthesizedElementImpl(node);
}
else if (type == PARENTHESIZED_TERMINAL_ELEMENT) {
return new XtextParenthesizedTerminalElementImpl(node);
}
else if (type == PARSER_RULE) {
return new XtextParserRuleImpl(node);
}
else if (type == PREDICATED_GROUP) {
return new XtextPredicatedGroupImpl(node);
}
else if (type == PREDICATED_KEYWORD) {
return new XtextPredicatedKeywordImpl(node);
}
else if (type == PREDICATED_RULE_CALL) {
return new XtextPredicatedRuleCallImpl(node);
}
else if (type == REFERENCED_METAMODEL) {
return new XtextReferencedMetamodelImpl(node);
}
else if (type == REFERENCE_ABSTRACT_METAMODEL_DECLARATION) {
return new XtextREFERENCEAbstractMetamodelDeclarationImpl(node);
}
else if (type == REFERENCE_ABSTRACT_RULE_RULE_ID) {
return new XtextREFERENCEAbstractRuleRuleIDImpl(node);
}
else if (type == REFERENCE_ECORE_E_CLASSIFIER) {
return new XtextREFERENCEEcoreEClassifierImpl(node);
}
else if (type == REFERENCE_ECORE_E_ENUM_LITERAL) {
return new XtextREFERENCEEcoreEEnumLiteralImpl(node);
}
else if (type == REFERENCE_ECORE_E_PACKAGE_STRING) {
return new XtextREFERENCEEcoreEPackageSTRINGImpl(node);
}
else if (type == REFERENCE_GRAMMAR_GRAMMAR_ID) {
return new XtextREFERENCEGrammarGrammarIDImpl(node);
}
else if (type == REFERENCE_PARAMETER_ID) {
return new XtextREFERENCEParameterIDImpl(node);
}
else if (type == RULE_CALL) {
return new XtextRuleCallImpl(node);
}
else if (type == RULE_ID) {
return new XtextRuleIDImpl(node);
}
else if (type == RULE_IDENTIFIER) {
return new XtextRuleIdentifierImpl(node);
}
else if (type == RULE_NAME_AND_PARAMS) {
return new XtextRuleNameAndParamsImpl(node);
}
else if (type == TERMINAL_ALTERNATIVES) {
return new XtextTerminalAlternativesImpl(node);
}
else if (type == TERMINAL_GROUP) {
return new XtextTerminalGroupImpl(node);
}
else if (type == TERMINAL_RULE) {
return new XtextTerminalRuleImpl(node);
}
else if (type == TERMINAL_RULE_CALL) {
return new XtextTerminalRuleCallImpl(node);
}
else if (type == TERMINAL_TOKEN) {
return new XtextTerminalTokenImpl(node);
}
else if (type == TERMINAL_TOKEN_ELEMENT) {
return new XtextTerminalTokenElementImpl(node);
}
else if (type == TYPE_REF) {
return new XtextTypeRefImpl(node);
}
else if (type == UNORDERED_GROUP) {
return new XtextUnorderedGroupImpl(node);
}
else if (type == UNTIL_TOKEN) {
return new XtextUntilTokenImpl(node);
}
else if (type == VALID_ID) {
return new XtextValidIDImpl(node);
}
else if (type == WILDCARD) {
return new XtextWildcardImpl(node);
}
throw new AssertionError("Unknown element type: " + type);
}
}
}
| [
"[email protected]"
] | |
4df2e796c0cf0c9ace48e26df870502d834e3f64 | d4136260a61f6d1c8ab900288d48da1469884349 | /health_service/health_member/src/test/java/com/itheima/health/service/impl/MemberServiceImplTest.java | 4f8887b083add56b9a2f6d96ee68720ab5c1c245 | [] | no_license | yhl-1219/- | aea75fe5cb34be297afa5697c846caa4d9e72df7 | a294c03034997be9ad8576a9ec49586c50747e8a | refs/heads/master | 2023-02-13T09:26:37.084154 | 2021-01-23T08:10:30 | 2021-01-23T08:10:30 | 332,652,043 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 385 | java | package com.itheima.health.service.impl;
import com.itheima.health.utils.date.DateUtils;
import org.junit.Test;
import java.util.Calendar;
import java.util.Date;
import static org.junit.Assert.*;
public class MemberServiceImplTest {
@Test
public void demo() {
Date date = DateUtils.parseString2Date("2020-01", "yyyy-MM");
System.out.println(date);
}
} | [
"[email protected]"
] | |
0a85d93be107154f59d3338c4c6626ca8d036d06 | 3887feba5a004134c400230479e7402e13b09da8 | /src/main/java/com/taskapplication/service/impl/TaskServiceImpl.java | b31b0419daf310cae3bb30d1c1eadc03150bd8b7 | [] | no_license | kaanbariskocabas/Task-Application | 8e7f90ef9f26697ce926f6a4e55cc2ee6860ad6d | 511151a93e9e7b7ff1e5fe01de3143bd8620976a | refs/heads/main | 2023-08-24T04:08:16.018029 | 2021-11-01T21:29:10 | 2021-11-01T21:29:10 | 416,929,639 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,675 | java | package com.taskapplication.service.impl;
import com.taskapplication.api.model.TaskCreationRequest;
import com.taskapplication.api.model.TaskUpdateRequest;
import com.taskapplication.exception.BaseException;
import com.taskapplication.model.Task;
import com.taskapplication.repositories.TaskRepository;
import com.taskapplication.service.TaskService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
import static com.taskapplication.util.StringUtil.isBlank;
@Service
@RequiredArgsConstructor
public class TaskServiceImpl implements TaskService {
private final TaskRepository taskRepository;
@Override
public Task create(TaskCreationRequest taskCreationRequest) {
return taskRepository.save(getNewTask(taskCreationRequest));
}
@Override
public void delete(Long taskId) {
taskRepository.deleteById(taskId);
}
@Override
public Task update(TaskUpdateRequest taskUpdateRequest) {
return taskRepository.save(getUpdatedTask(taskUpdateRequest));
}
@Override
public List<Task> filter() {
return null;
}
@Override
public Task findById(long taskId) {
return taskRepository.findById(getId(taskId))
.orElseThrow(() -> new TaskValidationException("Specified task is not found."));
}
private static Task getNewTask(TaskCreationRequest taskCreationRequest) {
checkTaskCreateRequest(taskCreationRequest);
final Task task = new Task();
task.setTitle(taskCreationRequest.getTitle());
task.setContent(taskCreationRequest.getContent());
return task;
}
private Task getUpdatedTask(TaskUpdateRequest taskUpdateRequest) {
checkTaskUpdateRequest(taskUpdateRequest);
final Task task = findById(taskUpdateRequest.getTaskId());
task.setTitle(taskUpdateRequest.getTitle());
task.setContent(taskUpdateRequest.getContent());
return task;
}
private static void checkTaskUpdateRequest(TaskUpdateRequest taskUpdateRequest) {
if (taskUpdateRequest == null || taskUpdateRequest.getTaskId() < 1)
throw new TaskValidationException("Task id must be provided.");
}
private static void checkTaskCreateRequest(TaskCreationRequest taskCreationRequest) {
if (taskCreationRequest == null || isBlank(taskCreationRequest.getTitle()))
throw new TaskValidationException("Title must be provided.");
}
public static class TaskValidationException extends BaseException {
private TaskValidationException(String message) {
super(message);
}
}
}
| [
"[email protected]"
] | |
afff2f158beb030ff69424379f0a32eec687e493 | 01635b4cdc428efc6d6320e384067375575a6835 | /app/src/main/java/sscom/tess/dem_1/Arith.java | a170d15748ca1a24af32991ad17efb5604911dd2 | [] | no_license | beasonshu/ModeStocks | dd0df00e8425852744518a3898c7979b3e31f6a7 | 9a7fd080267a69171b7f0ac7ab77b214496a4b2f | refs/heads/master | 2020-04-08T04:01:52.454603 | 2019-02-25T12:00:14 | 2019-02-25T12:00:14 | 158,999,649 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,577 | java | package sscom.tess.dem_1;
import java.math.BigDecimal;
/**
* Created by shu.xinghu on 2017/6/16.
*/
public class Arith {
// 默认除法运算精度
public static final int DEF_DIV_SCALE = 1000;
/**
* 提供精确的加法运算。
* @param v1 被加数
* @param v2 加数
* @return 两个参数的和
*/
public static BigDecimal add(double v1, double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2);
}
public static BigDecimal add(String v1, String v2){
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
return b1.add(b2);
}
/**
* 提供精确的减法运算。
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
public static BigDecimal sub(double v1, double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2);
}
public static BigDecimal sub(String v1, String v2){
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
return b1.subtract(b2);
}
/**
* 提供精确的乘法运算。
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static BigDecimal mul(double v1, double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2);
}
public static BigDecimal mul(String v1, String v2){
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
return b1.multiply(b2);
}
/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
* 小数点以后 10 位,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @return 两个参数的商
*/
public static BigDecimal div(double v1, double v2){
return div(Double.toString(v1),Double.toString(v1));
}
public static BigDecimal div(String v1, String v2){
return div(v1,v2,DEF_DIV_SCALE);
}
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由 scale 参数指
* 定精度,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static BigDecimal div(String v1, String v2, int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
return b1.divide(b2,scale, BigDecimal.ROUND_DOWN);
}
/**
* 提供精确的小数位四舍五入处理。
* @param v 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return 四舍五入后的结果
*/
public static BigDecimal round(double v, int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one,scale, BigDecimal.ROUND_HALF_UP);
}
}
| [
"[email protected]"
] | |
7d3ccbfd0c2bae147cdf3bb4db2159bd4e9fd4a2 | a7a762b3d5317aac656ed4b1393a61c928c5b1c8 | /app/src/main/java/com/bcit/comp3717/assignment01/list_row_layout.java | 6fc8549f8e0c9f42c57d39703476c140250952db | [] | no_license | Phil-CST-BCIT/COMP3717_Assignment01 | 494c5a16a25b31ff7160db59a324b634a84b34be | dbc0240ec6452dd572dc3860c4499319a788fa7a | refs/heads/master | 2022-12-30T07:54:38.981976 | 2020-10-18T22:57:45 | 2020-10-18T22:57:45 | 304,777,128 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 357 | java | package com.bcit.comp3717.assignment01;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class list_row_layout extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_row_layout);
}
} | [
"[email protected]"
] | |
b70a93d4e8cbec749955bfc0aec36a96a464a06d | b855f10be49ac03dcd83c3113f92b714291a9036 | /interpreter/ParseException.java | 3385f14bc852e50133c331dfdd8256e355974646 | [] | no_license | shchun/dp_java | 67f96fc5ac6df9fc524de080969367fab1d9f93a | 27623f2acb7ccf8c04616c26f34e5c62a1f8f7a0 | refs/heads/master | 2021-01-20T05:58:15.065673 | 2013-09-16T05:52:06 | 2013-09-16T05:52:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 108 | java |
public class ParseException extends Exception {
public ParseException (String msg) {
super(msg);
}
}
| [
"[email protected]"
] | |
767e633b1e0e264648f013fb560050308c190b17 | 96a3717d95037bc574135390532a383cdebb8434 | /src/mvc/Shapes/Triangle.java | 4e69342836ceea4d8da01c033bf00c8247a3c586 | [] | no_license | Snubb/Studsa_boll | 2bab38c6846aeab925f6987e8be843538057b577 | 50792807c6af3075cc9de39b4bcd70b16d9aff72 | refs/heads/master | 2023-09-01T00:51:15.499663 | 2021-10-26T10:01:50 | 2021-10-26T10:01:50 | 400,141,211 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,588 | java | package mvc.Shapes;
/**
* 2D Triangle in screen coordinates
* Vertices must come in clockwise order
* Created 2021-03-31
*
* @author Magnus Silverdal
*/
public class Triangle extends mvc.Shapes.Shape {
private mvc.Shapes.Point[] vertices = new mvc.Shapes.Point[3];
private mvc.Shapes.Line[] edges = new mvc.Shapes.Line[3];
public Triangle(mvc.Shapes.Point p0, mvc.Shapes.Point p1, mvc.Shapes.Point p2) {
vertices[0] = p0;
vertices[1] = p1;
vertices[2] = p2;
sortVertices();
edges[0] = new mvc.Shapes.Line(vertices[0],vertices[1]);
edges[1] = new mvc.Shapes.Line(vertices[1],vertices[2]);
edges[2] = new mvc.Shapes.Line(vertices[2],vertices[0]);
}
public mvc.Shapes.Line[] getEdges() {
return edges;
}
public mvc.Shapes.Point[] getVertices() {
return vertices;
}
// Find the ordering of vertices for Bresenhamstyle fill...
public void sortVertices() {
int leftmost = 0;
if (vertices[0].getX() > vertices[1].getX()) {
leftmost = 1;
}
if (vertices[leftmost].getX() > vertices[2].getX()) {
leftmost = 2;
}
if (leftmost == 1) {
mvc.Shapes.Point tmp = vertices[0];
vertices[0] = vertices[1];
vertices[1] = vertices[2];
vertices[2] = tmp;
}
if (leftmost == 2) {
mvc.Shapes.Point tmp = vertices[0];
vertices[0] = vertices[2];
vertices[2] = vertices[1];
vertices[1] = tmp;
}
}
}
| [
"[email protected]"
] | |
49ad319f77b2a461f604f33b21658bc21c7c1378 | 6eda00019e257011a5234be816e142ab02848e56 | /Lesson_5/src/main/java/Thing.java | 96161105d9c1f9474f297d0390c75869bb4a1444 | [] | no_license | Maxim-ka/Algorithms-and-data-structures-in-Java.-Basic-course. | ef33e7e41e1704590bd1ad2cad1d00b63b7a87ac | 14b169644013d51c9f1ba3d566f3dc90bfdc01ac | refs/heads/lesson_1 | 2020-03-27T06:26:49.164928 | 2018-09-28T10:37:56 | 2018-09-28T10:37:56 | 146,106,573 | 0 | 0 | null | 2018-09-28T10:37:57 | 2018-08-25T15:25:48 | Java | UTF-8 | Java | false | false | 562 | java | import java.util.Random;
public class Thing {
private int weight;
private int jewel;
public int getWeight() {
return weight;
}
public int getJewel() {
return jewel;
}
public Thing() {
weight = new Random().nextInt(100) + 1;
jewel = new Random().nextInt(100);
}
public Thing(int weight, int jewel) {
this.weight = weight;
this.jewel = jewel;
}
@Override
public String toString() {
return String.format("weight- %d, jewel- %d;", weight, jewel);
}
}
| [
"[email protected]"
] | |
24528d51cf4c5340715a9c02a0dbc58e3ca26f99 | ca2cd696a88fe3b34f274594cb72d1cf3ce3e3ee | /hobbypedia/src/main/java/net/kzn/hobbypedia/model/CheckoutModel.java | 8731715dbdd82e28acae6dcdb2ad7829b7603159 | [] | no_license | MitanshiPatel12/hobbypedia | d1330e0e7879b07e321e39eda9c8d23cdd34de88 | b28e9d9649501dd4d389ed06dd73826ae4664650 | refs/heads/master | 2020-04-01T03:26:08.223803 | 2018-10-13T00:44:02 | 2018-10-13T00:44:02 | 149,311,729 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,416 | java | package net.kzn.hobbypedia.model;
import java.io.Serializable;
import java.util.List;
import net.kzn.hobbypediabackend.dto.Address;
import net.kzn.hobbypediabackend.dto.Cart;
import net.kzn.hobbypediabackend.dto.CartLine;
import net.kzn.hobbypediabackend.dto.OrderDetail;
import net.kzn.hobbypediabackend.dto.User;
public class CheckoutModel implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private User user;
private Address shipping;
private Cart cart;
private List<CartLine> cartLines;
private OrderDetail orderDetail;
private double checkoutTotal;
public OrderDetail getOrderDetail() {
return orderDetail;
}
public void setOrderDetail(OrderDetail orderDetail) {
this.orderDetail = orderDetail;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
public double getCheckoutTotal() {
return checkoutTotal;
}
public void setCheckoutTotal(double checkoutTotal) {
this.checkoutTotal = checkoutTotal;
}
public List<CartLine> getCartLines() {
return cartLines;
}
public void setCartLines(List<CartLine> cartLines) {
this.cartLines = cartLines;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Address getShipping() {
return shipping;
}
public void setShipping(Address shipping) {
this.shipping = shipping;
}
}
| [
"[email protected]"
] | |
893e936557c8bee48b7d0abe5956521e6d86d42d | d3a5c9a0ffc7d00fa635061b6e6b50ac738ddf38 | /src/main/java/pk/temp/bm/models/ProductData.java | 5c47520f509a82825136f7ce64edc9c692d68f6c | [] | no_license | btz1/BusinessManager | 6cb967a3b6b816444d2c3d9e708f366f77c3826a | daea0d9c8b205b1c5e7ed5586067f52762853a95 | refs/heads/master | 2021-04-18T20:33:27.806330 | 2018-04-18T15:07:15 | 2018-04-18T15:07:15 | 126,891,026 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 962 | java | package pk.temp.bm.models;
public class ProductData {
private String SKU;
private String name;
private double price;
private double specialPrice;
private int quantity;
private String UPC;
public String getSKU() {
return SKU;
}
public void setSKU(String sKU) {
SKU = sKU;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getSpecialPrice() {
return specialPrice;
}
public void setSpecialPrice(double specialPrice) {
this.specialPrice = specialPrice;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getUPC() {
return UPC;
}
public void setUPC(String uPC) {
UPC = uPC;
}
}
| [
"[email protected]"
] | |
66fbc9e0a5eec1f5a468989090a5e681b51886e2 | 2f1f883b88c35fbdd7bcdad42b364df465f61279 | /ses-app/ses-web-website/src/main/java/com/redescooter/ses/web/website/vo/product/AddProductColourEnter.java | 62e8347f0ce39ea6f2f82d456c17ec773e584599 | [
"MIT"
] | permissive | RedElect/ses-server | bd4a6c6091d063217655ab573422f4cf37c8dcbf | 653cda02110cb31a36d8435cc4c72e792467d134 | refs/heads/master | 2023-06-19T16:16:53.418793 | 2021-07-19T09:19:25 | 2021-07-19T09:19:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 761 | java | package com.redescooter.ses.web.website.vo.product;
import com.redescooter.ses.api.common.vo.base.GeneralEnter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @Author jerry
* @Date 2021/1/6 1:02 上午
* @Description 产品颜色关系新增入参
**/
@ApiModel(value = "产品颜色关系新增入参", description = "产品颜色关系新增入参")
@Data
@EqualsAndHashCode(callSuper = true)
public class AddProductColourEnter extends GeneralEnter {
/**
* 主键
*/
@ApiModelProperty(value="主键")
private Long productId;
/**
* 主键
*/
@ApiModelProperty(value="产品颜色")
private Long colourId;
}
| [
"[email protected]"
] | |
7dfa9c262c251ff8e8d66072c3d955daeea8e02a | f8c6f91e33dbdcb1309da51d6ce7523801d3b162 | /hadoop_hdfs/MapReduce/src/main/java/com/atguigu/mapreduce/wc1/WordCountMapper.java | e328043dfa66d0e2e511ed0de110a2affbdf79cd | [] | no_license | zzp15222522401/daima | c8ffc4b0e0dbede6278f1e4e87b05deb9f13bb00 | df84b0fa1d0fb3eb5f7e69aa02320494daf90172 | refs/heads/hot-fix | 2023-05-07T11:07:16.489284 | 2021-05-31T09:43:54 | 2021-05-31T09:43:54 | 358,160,076 | 0 | 1 | null | 2021-05-31T09:43:54 | 2021-04-15T07:01:35 | null | UTF-8 | Java | false | false | 895 | java | package com.atguigu.mapreduce.wc1;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
/**
* 采用一行一行的方法读取文件,然后进行切割,组成key-value的形式
*
*/
public class WordCountMapper extends Mapper<LongWritable,Text,Text, IntWritable> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
//longwritable key 这里用不到
String string = value.toString();//将读取的每行数据进行数据转换
String[] s = string.split(" ");
for (String s1 : s) {
Text text = new Text(s1);
IntWritable intWritable = new IntWritable(1);
context.write(text,intWritable);
}
}
}
| [
"[email protected]"
] | |
45db92a16ed34d86f4bb08e7c7946b3934eb2234 | 9af5afa6c79e90e6e4654cf403d6ad166e89fd01 | /Metcheck/src/com/davidsonecm/metcheck/rest/GetWeather.java | 28ca7f785594faba25c47c9813f52e6290356da9 | [] | no_license | chrisdavecm/MyApps | c9dbd4a669df2c257da59bd256980155c4381720 | 654780152b865f1424a9cc7bfe3d65bcd91fe8c7 | refs/heads/master | 2021-01-19T13:33:40.276216 | 2013-02-05T00:52:04 | 2013-02-05T00:52:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,871 | java | package com.davidsonecm.metcheck.rest;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.List;
import com.davidsonecm.metcheck.Weather;
/**
* A class to go get the weather
*
* @author User
*
*/
public class GetWeather {
public Weather getWeatherNow(String location) throws ParseException, IOException {
URL url = new URL("http://www.metcheck.com/V40/UK/FREE/today.asp?zipcode="+URLEncoder.encode(location));
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
final char[] buffer = new char[0x10000];
StringBuilder out = new StringBuilder();
Reader in = new InputStreamReader(is, "UTF-8");
try {
int read;
do {
read = in.read(buffer, 0, buffer.length);
if (read>0) {
out.append(buffer, 0, read);
}
} while (read>=0);
} finally {
in.close();
}
String result = out.toString();
return HTMLToWeatherConverter.extractFirstRow(result);
}
public List<Weather> getWeatherNext24Hours(String location) throws ParseException, IOException{
URL url = new URL("http://www.metcheck.com/V40/UK/FREE/today.asp?zipcode="+URLEncoder.encode(location));
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
final char[] buffer = new char[0x10000];
StringBuilder out = new StringBuilder();
Reader in = new InputStreamReader(is, "UTF-8");
try {
int read;
do {
read = in.read(buffer, 0, buffer.length);
if (read>0) {
out.append(buffer, 0, read);
}
} while (read>=0);
} finally {
in.close();
}
String result = out.toString();
return HTMLToWeatherConverter.extractDay(result);
}
} | [
"[email protected]"
] | |
fb75d5e9ca61b09d3bef8db1d0a4cebe75221dfd | 8edc3029a65f895992826412a537cc228849493a | /foodie/src/main/java/com/buildweek/foodie/services/UserAuditing.java | fda06d609ab5d6c1dcbdbf48a082899ca780662e | [] | no_license | Build-Week-Foodie-Funz/back-end | 304a23410559b9e9c3b54e4beacc72b9603db65f | 966ce4c86033c7d3e3de13fbe8209bfdbe6f449b | refs/heads/master | 2022-12-10T12:04:20.224939 | 2019-10-24T02:00:46 | 2019-10-24T02:00:46 | 209,888,592 | 0 | 0 | null | 2022-11-16T12:25:47 | 2019-09-20T22:07:18 | Java | UTF-8 | Java | false | false | 849 | java | package com.buildweek.foodie.services;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
public class UserAuditing implements AuditorAware<String>
{
@Override
public Optional<String> getCurrentAuditor()
{
String uname;
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
if (authentication != null)
{
uname = authentication.getName();
} else
{
uname = "SYSTEM";
}
return Optional.of(uname);
}
} | [
"[email protected]"
] | |
9cb5b76b5c51daa4898b8314d3f089a59f934c68 | bdc7f4cbedfc22a1a4e3b4969d3e90bc9665ba93 | /src/ie/gmit/sw/ai/maze/BattleLogic.java | ef025664a60af789f4a9d2f34551450ee4d216c4 | [] | no_license | seaniemc/AI-neuralnet-mazegame | e64f542eb13182099d37017492aaebcf9640e5c4 | c7fbedf2953faf25513980f14efae814899a3143 | refs/heads/master | 2021-01-19T11:08:59.000584 | 2017-10-29T21:36:35 | 2017-10-29T21:36:35 | 87,930,852 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,290 | java | package ie.gmit.sw.ai.maze;
/**
* Created by Sean on 20/04/2017.
*/import net.sourceforge.jFuzzyLogic.FIS;
import net.sourceforge.jFuzzyLogic.FunctionBlock;
import net.sourceforge.jFuzzyLogic.rule.Variable;
public class BattleLogic {
public BattleLogic(){
}
public boolean startBattle(Warrior player, Spider enemy, String fclFilePath){
FIS fis = FIS.load(fclFilePath, true);
if(fis == null){
System.err.println("Error loading: '" + fclFilePath + "'");
return true;
}
FunctionBlock functionBlock = fis.getFunctionBlock("fight");
fis.setVariable("health", player.getHealth());
fis.setVariable("armor", player.getArmor());
fis.setVariable("weapon", player.getWeaponStrength());
fis.evaluate();
Variable annihilation = functionBlock.getVariable("annihilation");
System.out.println("Annihilation Percentage: " + (int)annihilation.getValue() + "%\n");
boolean enemyWon = false;
player.setHealth((int)(player.getHealth() - (100 - annihilation.getValue())));
player.setArmor((int)(player.getArmor() - (100 - annihilation.getValue() + 10)));
player.setWeaponStrength((int)(player.getWeaponStrength() * (annihilation.getValue() / 100)));
// If the weapon was damaged enough then destroy the weapon
if(player.getWeaponStrength() < 35){
player.setWeaponStrength(0);
player.setWeapon("Unarmed");
}
// Checking armor
if(player.getArmor() <= 0){
player.setArmor(0);
}
// Checking health below zero, if true then the game is over
if(player.getHealth() <= 0){
player.setHealth(0);
player.setGameOver(true);
System.out.println("Game Over!");
System.out.println("Player Score: " + player.getScore() + "\n");
enemyWon = true;
}
// If the player wins the fight then update the player object variables
if(!enemyWon){
player.setScore(player.getScore() + 25);
System.out.println("Player Health: " + player.getHealth());
System.out.println("Player Armor: " + player.getArmor() + "\n");
}
return enemyWon;
}
}
| [
"Sean McGrath"
] | Sean McGrath |
fa9198f05470453660451a0d448d1bf748d75f6f | 14cd92ed732ae46b11e33a60aeabc2ad6cb22735 | /FoodOrderingApp-service/src/main/java/com/upgrad/FoodOrderingApp/service/entity/CustomerAddressEntity.java | e5b728cab663110267f81a8e8914361d1cd9f008 | [] | no_license | Mandeepk01/FoodOrderingApp | c609df875d4ba93655dd5bba56213a2f3c2c767a | 93cb045586290c659a181ba83934836f95c47e1d | refs/heads/main | 2023-01-08T08:46:41.741044 | 2020-11-02T20:17:06 | 2020-11-02T20:17:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,033 | java | package com.upgrad.FoodOrderingApp.service.entity;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import javax.persistence.*;
import java.io.Serializable;
//This Class represents the CustomerAddress table in the DB.
@Entity
@Table(name = "customer_address")
@NamedQueries({
@NamedQuery(name = "getAllCustomerAddressByCustomer",query = "SELECT c from CustomerAddressEntity c where c.customer = :customer_entity AND c.address.active = :active"),
@NamedQuery(name = "getCustomerAddressByAddress",query = "SELECT c from CustomerAddressEntity c where c.address = :address_entity"),
@NamedQuery(name = "customerAddressByAddressId", query = "select ca from CustomerAddressEntity ca where ca.id=:id"),
@NamedQuery(name = "custAddressByCustIdAddressId", query = "select ca from CustomerAddressEntity ca where ca.customer=:customer and ca.address=:address"),
@NamedQuery(name = "customerAddressesListByCustomerId", query = "select ca from CustomerAddressEntity ca where ca.customer = :customer")
})
public class CustomerAddressEntity implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "customer_id")
@OnDelete(action = OnDeleteAction.CASCADE)
private CustomerEntity customer;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "address_id")
@OnDelete(action = OnDeleteAction.NO_ACTION)
private AddressEntity address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public CustomerEntity getCustomer() {
return customer;
}
public void setCustomer(CustomerEntity customer) {
this.customer = customer;
}
public AddressEntity getAddress() {
return address;
}
public void setAddress(AddressEntity address) {
this.address = address;
}
}
| [
"[email protected]"
] | |
4415ddae4789927e96de24ea3307754e99bb4122 | 21f418ebd026f1d525c0182a42e10e614018833a | /app/src/main/java/com/example/administrator/view/GlideCircleTransform.java | 272fbc15be404965ecb90056c06b391204703cdc | [] | no_license | lt594963425/MyAppDemo | 8036492b6da141d6ecf58303eff9f8af792b95a8 | a961dde56fe90baee4a660382c3054b61001c5ad | refs/heads/master | 2021-09-22T10:26:25.032259 | 2018-09-08T09:17:29 | 2018-09-08T09:17:29 | 109,342,095 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,888 | java | package com.example.administrator.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
/**
* 加载圆形图片
* Created by 15111429213 on 2016/11/11.
* --------日期 ---------维护人------------ 变更内容 --------
* 2016/11/11 刘涛 新增Person类
* 2016/11/11 刘涛 增加sex属性
**/
public class GlideCircleTransform extends BitmapTransformation{
public GlideCircleTransform(Context context) {
super(context);
}
@Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return circleCrop(pool, toTransform);
}
private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
// TODO this could be acquired from the pool too
Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
return result;
}
@Override public String getId() {
return getClass().getName();
}
} | [
"[email protected]"
] | |
b19c7d2038d46dc280f7545c025065454fcadb9a | 3b786d3854e830a4b46ee55851ca186becbfa650 | /IntegrationTesting/dvs/vmops/createvm/Pos004.java | e1b4b794ceb78c826eb02e74bcd6ad57cc917d00 | [] | no_license | Cloudxtreme/MyProject | d81f8d38684333c22084b88141b712c78b140777 | 5b55817c050b637e2747084290f6206d2e622938 | refs/heads/master | 2021-05-31T10:26:42.951835 | 2015-12-10T09:57:04 | 2015-12-10T09:57:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,370 | java | /*
* ************************************************************************
*
* Copyright 2008 VMware, Inc. All rights reserved. -- VMware Confidential
*
* ************************************************************************
*/
package dvs.vmops.createvm;
import static com.vmware.vc.VirtualMachinePowerState.POWERED_OFF;
import static com.vmware.vcqa.TestConstants.VM_VIRTUALDEVICE_ETHERNET_VMXNET2;
import static com.vmware.vcqa.util.Assert.assertTrue;
import java.util.List;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.vmware.vc.DVSConfigInfo;
import com.vmware.vc.DistributedVirtualSwitchPortConnection;
import com.vmware.vc.ManagedObjectReference;
import com.vmware.vc.VirtualMachineConfigSpec;
import com.vmware.vcqa.TestConstants;
import com.vmware.vcqa.util.TestUtil;
import com.vmware.vcqa.vim.Folder;
import dvs.vmops.VMopsBase;
/**
* Create a VM on a standalone host to connect to an existing standalone DVPort.
* The device is of type VirtualVmxnet2.The backing is of type DVPort backing
* and the port connection is a DVPort connection.
*/
public class Pos004 extends VMopsBase
{
/*
* Private data variables
*/
private VirtualMachineConfigSpec vmConfigSpec = null;
private DistributedVirtualSwitchPortConnection dvsPortConnection = null;
private String dvSwitchUuid = null;
private String portKey = null;
private ManagedObjectReference vmMor = null;
/**
* Set test description.
*/
@Override
public void setTestDescription()
{
setTestDescription("Create a VM on a Standalone host to connect to"
+ "an existing standalone DVPort.");
}
/**
* Method to setup the environment for the test. 1. Create the DVSwitch. 2.
* Create the Standalone DVPort. 3. Create the VM ConfigSpec.
*
* @param connectAnchor ConnectAnchor object
* @return <code>true</code> if setup is successful.
*/
@Override
@BeforeMethod(alwaysRun=true)
public boolean testSetUp()
throws Exception
{
boolean status = false;
List<String> portKeys = null;
log.info("test setup Begin:");
if (super.testSetUp()) {
hostMor = ihs.getStandaloneHost();
log.info("Host Mor :" + hostMor);
log.info("Host Name :" + ihs.getHostName(hostMor));
// create the DVS by using standalone host.
dvsMor = iFolder.createDistributedVirtualSwitch(dvsName, hostMor);
Thread.sleep(10); // Sleep for 10 Sec.
nwSystemMor = ins.getNetworkSystem(hostMor);
if (ins.refresh(nwSystemMor)) {
log.info("Network refreshed.");
}
// add the pnics to DVS
hostNetworkConfig = iDVSwitch.getHostNetworkConfigMigrateToDVS(
dvsMor, hostMor);
if (hostNetworkConfig != null && hostNetworkConfig.length == 2) {
log.info("Found the NetworkConfig.");
// update the network to use the DVS.
networkUpdated = ins.updateNetworkConfig(
ins.getNetworkSystem(hostMor), hostNetworkConfig[0],
TestConstants.CHANGEMODE_MODIFY);
if (networkUpdated) {
portKeys = iDVSwitch.addStandaloneDVPorts(dvsMor, 1);
if (portKeys != null) {
log.info("Successfully get the standalone DVPortkeys");
portKey = portKeys.get(0);
DVSConfigInfo info = iDVSwitch.getConfig(dvsMor);
dvSwitchUuid = info.getUuid();
// create the DistributedVirtualSwitchPortConnection
// object.
dvsPortConnection = buildDistributedVirtualSwitchPortConnection(
dvSwitchUuid, portKey, null);
vmConfigSpec = buildCreateVMCfg(dvsPortConnection,
VM_VIRTUALDEVICE_ETHERNET_VMXNET2, hostMor);
log.info("Successfully created VMConfig spec.");
status = true;
} else {
log.error("Failed to get the standalone DVPortkeys ");
}
} else {
log.error("Failed to find network config.");
}
}
}
assertTrue(status, "Setup failed");
return status;
}
/**
* Test. 1. Create the VM. 2. Varify the ConfigSpecs and Power-ops
* operations.
*
* @param connectAnchor ConnectAnchor.
*/
@Override
@Test(description = "Create a VM on a Standalone host to connect to"
+ "an existing standalone DVPort.")
public void test()
throws Exception
{
boolean status = false;
vmMor = new Folder(super.getConnectAnchor()).createVM(
ivm.getVMFolder(), vmConfigSpec, ihs.getPoolMor(hostMor),
hostMor);
if (vmMor != null) {
log.info("Successfully created VM.");
status = verify(vmMor, null, vmConfigSpec);
} else {
log.error("Unable to create VM.");
}
assertTrue(status, "Test Failed");
}
/**
* Method to restore the state as it was before the test is started.
*
* @param connectAnchor ConnectAnchor object
* @return <code>true</code> if successful.
*/
@Override
@AfterMethod(alwaysRun=true)
public boolean testCleanUp()
throws Exception
{
boolean status = true;
try {
if (vmMor != null && ivm.setVMState(vmMor, POWERED_OFF, false)) {
status = destroy(vmMor);// destroy the VM.
} else {
log.warn("VM not found");
}
} catch (Exception e) {
TestUtil.handleException(e);
}
try {
if (networkUpdated) {
// Restore the network to use the DVS.
status &= ins.updateNetworkConfig(nwSystemMor,
hostNetworkConfig[1], TestConstants.CHANGEMODE_MODIFY);
}
} catch (Exception e) {
TestUtil.handleException(e);
} finally {
status &= super.testCleanUp();
}
assertTrue(status, "Cleanup failed");
return status;
}
}
| [
"[email protected]"
] | |
ee7e25aada72e45d55b62ee69cec3e62f0384cfc | d6b41c2c1e70ccb359944acc355790589bdbba9b | /src/com/tintin/linkedList/Offer35.java | 9b68e81ac7fa213b7c34b25f44bc0e4d8b4f79dd | [] | no_license | tintinng/leetcodes | 1f2ca4382f5a1ed45f3de12fc1cf92f73af69c9a | d99e24438fbb7bf5c0c20548dd1f933d242efda0 | refs/heads/master | 2021-03-12T00:13:21.146682 | 2020-08-12T13:10:15 | 2020-08-12T13:10:15 | 246,573,096 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,167 | java | package com.tintin.linkedList;
import java.util.HashMap;
public class Offer35 {
public static void main(String[] args) {
}
}
/**
* 遍历两遍,第一遍copy除random以外的其他数据,并构造一个hash表,将两个链表的节点一一对应
* 时间:O(n)
* 空间:O(n)
*/
class SolutionOffer35 {
public Node copyRandomList(Node head) {
HashMap<Node,Node> map = new HashMap<>();
Node dummy = new Node(-1);
Node p = head;
Node pre = dummy;
dummy.next = p;
// 第一遍 copy除 random以外的其他数据,并构造一个 hash表,将两个链表的节点一一对应
while (p != null) {
Node node = new Node(p.val);
pre.next = node;
pre = node;
map.put(p, node);
p = p.next;
}
// dummy已经是第二个链表的哑节点
p = dummy.next;
// 第二遍copy对应的 random
while (p!=null) {
Node rand = map.get(head.random);
p.random = rand;
p = p.next;
head = head.next;
}
return dummy.next;
}
}
| [
"[email protected]"
] | |
804f1155a986bd87d4eb17a254bbd54d62af6f62 | 862e764d41505b9f2b3d76f4347ea8f0c6446dd9 | /src/com/dgrissom/expparser/IToken.java | f954414e37337a2edc70f2c7d3dfb02a8fe06b54 | [] | no_license | MCMastery/expression-parser | d3c8c68ad8e66873ab7824121998ac672cbe1372 | bdf89baa2ae9af9200e933a541e52d84b1b4bab5 | refs/heads/master | 2021-01-17T19:00:42.756377 | 2016-07-12T17:13:18 | 2016-07-12T17:13:18 | 63,177,330 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 709 | java | package com.dgrissom.expparser;
public interface IToken {
String getToken();
/*
Returns an IToken from the given string
*/
static IToken parse(String token) {
// check if it is a value
ValueToken valueToken = ValueToken.parse(token);
if (valueToken != null)
return valueToken;
// check if it is an operator
Operator operator = Operator.fromToken(token);
if (operator != null)
return operator;
// check if it is a function
Function function = Function.fromToken(token);
if (function != null)
return function;
// must be an in valid token
return null;
}
}
| [
"[email protected]"
] | |
46e202df15d60e48b2edfb2ffe684ee4ffe611a7 | 294d9d5df0275d404389b96e6beabb35b355f7d3 | /src/main/java/dosn/database/entities/User.java | 37452256bf512e85061f969227fa366303bf28a9 | [] | no_license | fsalem/DOSN.database.module | 3145cb75f7ffaaab3bcc54d15e15b431dfdfd5d1 | dbbd5d35a57232921b5c3ea1a7fbc6179435879d | refs/heads/master | 2021-01-17T18:50:36.122099 | 2016-05-28T17:21:41 | 2016-05-28T17:21:41 | 59,906,321 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,454 | java | package dosn.database.entities;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* The persistent class for the T_USER database table.
*
*/
@Entity
@Table(name = "T_USER")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id", unique = true, nullable = false)
private String userId;
@Column(name = "user_email", nullable = false, length = 45)
private String userEmail;
@Column(length = 100)
private String user_GID;
@Column(name = "user_name", nullable = false, length = 45)
private String userName;
@Column(name = "user_password", nullable = false, length = 45)
private String userPassword;
@Column(name = "profile_hidden", nullable = false, columnDefinition = "TINYINT", length = 1)
private Boolean profileHidden;
// bi-directional many-to-one association to UserFriend
@OneToMany(mappedBy = "TUser")
private Set<UserFriend> TUserFriends;
// bi-directional many-to-many association to Interest
@ManyToMany
@JoinTable(name = "T_USER_INTEREST", joinColumns = { @JoinColumn(name = "user_id", nullable = false) }, inverseJoinColumns = { @JoinColumn(name = "interest_id", nullable = false) })
private Set<Interest> TInterests;
public User() {
}
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserEmail() {
return this.userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUser_GID() {
return this.user_GID;
}
public void setUser_GID(String user_GID) {
this.user_GID = user_GID;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return this.userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public Boolean getProfileHidden() {
return profileHidden;
}
public void setProfileHidden(Boolean profileHidden) {
this.profileHidden = profileHidden;
}
public Set<UserFriend> getTUserFriends() {
return this.TUserFriends;
}
public void setTUserFriends(Set<UserFriend> TUserFriends) {
this.TUserFriends = TUserFriends;
}
public Set<Interest> getTInterests() {
return this.TInterests;
}
public void setTInterests(Set<Interest> TInterests) {
this.TInterests = TInterests;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((userEmail == null) ? 0 : userEmail.hashCode());
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
result = prime * result
+ ((userName == null) ? 0 : userName.hashCode());
result = prime * result
+ ((userPassword == null) ? 0 : userPassword.hashCode());
result = prime * result
+ ((user_GID == null) ? 0 : user_GID.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;
User other = (User) obj;
if (userEmail == null) {
if (other.userEmail != null)
return false;
} else if (!userEmail.equals(other.userEmail))
return false;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
if (userName == null) {
if (other.userName != null)
return false;
} else if (!userName.equals(other.userName))
return false;
if (userPassword == null) {
if (other.userPassword != null)
return false;
} else if (!userPassword.equals(other.userPassword))
return false;
if (user_GID == null) {
if (other.user_GID != null)
return false;
} else if (!user_GID.equals(other.user_GID))
return false;
return true;
}
} | [
"[email protected]"
] | |
4d468d7caf8daa3f36a41ef70915a3306ed7e7c6 | 02d6eb14093692e736d4bfb6c84f548faf236a93 | /src/main/java/com/jicl/design/decorator/Client.java | 5b0fe689658d8e61997ce5891e0f1dae7f0cca60 | [] | no_license | jichunlei/Java-Design-Mode | 80a6bf467ee2b4dd72a11bdcddd507630e75dede | cc88c604c790495b415dc5498ebc8905a1f0c5a3 | refs/heads/master | 2021-07-02T23:33:26.696104 | 2020-11-12T10:56:48 | 2020-11-12T10:56:48 | 193,521,900 | 0 | 0 | null | 2020-10-13T14:07:44 | 2019-06-24T14:30:54 | Java | UTF-8 | Java | false | false | 1,067 | java | package com.jicl.design.decorator;
/**
* TODO
*
* @author : xianzilei
* @date : 2020/10/9 19:05
*/
public class Client {
public static void main(String[] args) {
//点一杯黑咖啡,啥都不加
AbstractCafe cafe1 = new BlackCafe();
System.out.println(cafe1.getDescription() + ",花费" + cafe1.cost());
//点一杯浓咖啡,加两份摩卡和一份豆浆
AbstractCafe cafe2 = new ThickCafe();
//加第一份摩卡
cafe2 = new MochaCondiment(cafe2);
//加第二份摩卡
cafe2 = new MochaCondiment(cafe2);
//加一份豆浆
cafe2 = new SoyCondiment(cafe2);
System.out.println(cafe2.getDescription() + ",花费" + cafe2.cost());
//点一杯黑咖啡,加两份豆浆
AbstractCafe cafe3 = new BlackCafe();
//加第一份豆浆
cafe3 = new SoyCondiment(cafe3);
//加第二份豆浆
cafe3 = new SoyCondiment(cafe3);
System.out.println(cafe3.getDescription() + ",花费" + cafe3.cost());
}
}
| [
"[email protected]"
] | |
1d1ee7302e9ec06c302648b566d959712062507e | c3274f05100c62657776c46a2b83dd0a658b3c5b | /PApple2/src/com/example/papple2/layerAdapter.java | e42f3ada20396d21f248fab7f078d031f45672ed | [] | no_license | SMPT-Groep3/Smart-Mobile | 7d36f6b6a8bb9c5a1b8d7e3c5ac923113447d134 | a77c678474e546aad96922f468549e8e0752a111 | refs/heads/master | 2020-11-26T19:22:31.695720 | 2015-01-29T15:21:03 | 2015-01-29T15:21:03 | 26,953,853 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,360 | java | package com.example.papple2;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
public class layerAdapter extends ArrayAdapter<LayerItem> {
private Context context;
private static LayerItem selectedItem;
private int selectedIndex = -1;
private static List<LayerItem> items;
public layerAdapter(Context context) {
super(context, R.layout.layer_item, LayerItemProvider.getInstance().getItems());
// TODO Auto-generated constructor stub
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
final LayerItem item = super.getItem(position);
final int positionlist = position;
final ViewGroup parentView = parent;
View myView = convertView;
if(myView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myView = inflater.inflate(R.layout.layer_item, null);
}
ImageView image = (ImageView)myView.findViewById(R.id.imageView1);
image.setImageBitmap(item.getImg());
image.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
selectedItem = item;
selectedIndex = positionlist;
notifyDataSetChanged();
}
});
image.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
context);
alertDialog.setTitle("Remove Item");
alertDialog.setMessage("Are you sure you want to remove this item?");
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
LayerItemProvider.getInstance().removeItem(positionlist);
notifyDataSetChanged();
EditorActivity.getCanvas().invalidate();
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//do nothing
}
});
alertDialog.show();
return false;
}
});
CheckBox cb = (CheckBox)myView.findViewById(R.id.checkBox1);
cb.setChecked(item.isVisible());
if (selectedIndex == position)
{
myView.setBackgroundColor(Color.BLUE);
}
else
{
myView.setBackgroundColor(Color.WHITE);
}
cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
item.setVisible(isChecked);
EditorActivity.getCanvas().invalidate();
}
});
return myView;
}
public static LayerItem getSelectedItem()
{
return selectedItem;
}
}
| [
"[email protected]"
] | |
82514de21c4bb76f01860ba43597264908ab687c | a7302726b37eea07e2c00e80279f286f6052031d | /explore-springframework/src/main/java/org/lr/explore/components/springframework/ExploreFileSystemXmlApplicationContext.java | 10a2c5da655d8cd4341e4ef8b2740de73e858b63 | [] | no_license | lirui10093622/explore-components | 3f600e15e443bf4c6bca45536cb91dd52a1eae8a | eb17a197bb42dfa877876e3532e5fe7b190e135e | refs/heads/master | 2021-07-08T14:33:29.916130 | 2019-07-22T15:09:17 | 2019-07-22T15:09:17 | 197,527,932 | 0 | 0 | null | 2020-10-13T14:40:27 | 2019-07-18T06:43:02 | Java | UTF-8 | Java | false | false | 669 | java | package org.lr.explore.components.springframework;
import org.lr.explore.components.springframework.bean.HelloService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
/**
* @author neil
* @email [email protected]
* @time 2019-07-22 21:09:12
*/
public class ExploreFileSystemXmlApplicationContext {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext("classpath:applicationContext.xml");
HelloService bean = context.getBean("helloService", HelloService.class);
bean.sayHello("张三");
}
}
| [
"[email protected]"
] | |
40857a2252a6b771b2a14cb8a7f0b572244090fb | 981c5dfbbb21cbdc0a855dc96e59479c360cc83a | /app/src/main/java/me/vociegif/android/mvp/vo/StickerFile.java | 0494229f75b13a88908d8c8b50db980dda8e4be7 | [
"Apache-2.0"
] | permissive | junchenChow/exciting-app | 3bc5d4d8068059919d4ca79a932d9db365155132 | b9f136ae80c0e03932b611c79978f6c5204306d5 | refs/heads/master | 2021-01-01T19:37:23.357849 | 2017-09-27T08:14:31 | 2017-09-27T08:14:31 | 98,629,263 | 5 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,186 | java | package me.vociegif.android.mvp.vo;
import java.io.Serializable;
import java.util.List;
public class StickerFile implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String imgname; //格子里面的背景name
private String imgname_url;
private int width;
private int height;
private List<StickerPaint> sticker; //格子里面的贴纸信息
public String getImgname() {
return imgname;
}
public void setImgname(String imgname) {
this.imgname = imgname;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public List<StickerPaint> getSticker() {
return sticker;
}
public void setSticker(List<StickerPaint> sticker) {
this.sticker = sticker;
}
public String getImgname_url() {
return imgname_url;
}
public void setImgname_url(String imgname_url) {
this.imgname_url = imgname_url;
}
}
| [
"[email protected]"
] | |
d93bf5b7f9f19c87a6ce2d8a4592b354627c0fa1 | 43e619b2c6f62f9322c31efe5ff66ea89c586816 | /lvfs/src/test/edu/brown/lasvegas/lvfs/local/LocalBlockCompressionFixLenFloatGzipTest.java | f5a071b68632063d9f9b0a18e88aa225a1cd788d | [] | no_license | hanson5b/las-vegas | 6a35e83cd2f98505c32da3239ca0ad06ec092bdc | dc3e0af44fbbca84c58305c331429966f3c38949 | refs/heads/master | 2021-01-01T06:55:36.425154 | 2013-03-10T03:59:23 | 2013-03-10T03:59:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 303 | java | package edu.brown.lasvegas.lvfs.local;
import edu.brown.lasvegas.CompressionType;
public class LocalBlockCompressionFixLenFloatGzipTest extends LocalBlockCompressionFixLenFloatTest {
@Override
protected CompressionType getType() {
return CompressionType.GZIP_BEST_COMPRESSION;
}
}
| [
"[email protected]"
] | |
8d2efe23fe94c69e22b3c3b008288cc25b5598d0 | 254d3e86ffb44cd881cfbd51ff7d3bb2fd11e274 | /src/main/java/com/idea/cms/config/RabbitMqConfig.java | 6dc7ac4a92c81886a5b2107cc681f493948cd473 | [] | no_license | Vc-lucifer/demo | c16e7cc65953f3b3ddb3c1b3e0550a3121fe8c9a | a4e6606403c4abf089cb5512cee55be425341b42 | refs/heads/master | 2020-04-13T04:01:37.242867 | 2018-12-28T09:20:14 | 2018-12-28T09:20:14 | 162,948,696 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 568 | java | package com.idea.cms.config;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Author: Lucifer
* @Description: 队列配置,队列的名称,发送者和接受者的名称必须一致,否则接收不到消息
* @Date: 2018/12/21
*/
@Configuration
public class RabbitMqConfig {
@Bean
public Queue Queue1() {
return new Queue("Tset01");
}
@Bean
public Queue Queue2() {
return new Queue("Tset02");
}
} | [
"[email protected]"
] | |
8aef65c30f048e12d1d337749f30afa1f85dd7f0 | 23c82be900d6d4462c65d67c1ed50749fc02d0ce | /src/main/java/com/test/testapplication/service/MathReaderService.java | 0124631e2ca0218b733e95c444c3fb27859bbf80 | [] | no_license | RozaShig/TestApplication | 334ee8b80c70be8fba45728c254f4b8b9de10bc2 | 1388dd0c56182acd0c799c331b03c71efdeb5199 | refs/heads/master | 2022-11-04T22:22:03.245412 | 2020-06-28T12:35:12 | 2020-06-28T12:35:12 | 275,580,883 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,867 | java | package com.test.testapplication.service;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
@Service
public class MathReaderService {
private String doMath (String line) {
try {
long operand1, operand2;
if (line.contains("*")) {
operand1 = Long.parseLong(line.substring(0, line.indexOf("*")));
operand2 = Long.parseLong(line.substring(line.indexOf("*") + 1));
return String.valueOf(operand1 * operand2);
} else if (line.contains("/")) {
operand1 = Long.parseLong(line.substring(0, line.indexOf("/")));
operand2 = Long.parseLong(line.substring(line.indexOf("/") + 1));
return String.valueOf(operand1 / operand2);
} else if (line.contains("+")) {
operand1 = Long.parseLong(line.substring(0, line.indexOf("+")));
operand2 = Long.parseLong(line.substring(line.indexOf("+") + 1));
return String.valueOf(operand1 + operand2);
} else if (line.contains("-")) {
operand1 = Long.parseLong(line.substring(0, line.indexOf("-")));
operand2 = Long.parseLong(line.substring(line.indexOf("-") + 1));
return String.valueOf(operand1 - operand2);
}
return null;
} catch (NumberFormatException e) {
System.out.println("Строка " + line + " содержит ошибку, один из операндов не является целым числом");
return null;
} catch (ArithmeticException e) {
System.out.println("Строка " + line + " содержит ошибку, деление на 0");
return null;
}
}
public String doTask(String path) {
try {
File file = new File(path);
FileReader fileReader = new FileReader(file);
//создаем BufferedReader с существующего FileReader для построчного считывания
BufferedReader reader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter("out.txt");
File outFile = new File("out.txt");
String line = reader.readLine();
while (line != null) {
// действия со строкой
String result = doMath(line);
if (result != null)
fileWriter.write(result.concat("\n"));
line = reader.readLine();
}
fileWriter.close();
return outFile.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| [
"[email protected]"
] | |
564c270cf2930afff5c2e114de8d110fb7c7c0ef | c61f2fad090ec1dff231bfb5b11e6d1320c653c9 | /src/main/java/hiber/model/Car.java | 7f8f26fa7556d5b89f958fb56c7d0f5541ce6103 | [] | no_license | paxansx/spring_hibernate_2.2.1 | 500f6fde18577121ed1ef25bf4b0e5e79add7096 | 04f37015c96f2ca77b8a56c83dceeb8d7f20ebb5 | refs/heads/master | 2023-02-23T16:07:20.383346 | 2021-01-29T13:09:49 | 2021-01-29T13:09:49 | 334,149,187 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 984 | java | package hiber.model;
import javax.persistence.*;
@Entity
@Table(name = "cars")
public class Car {
@Id
@Column(name = "series")
private int series;
@Column(name = "model")
private String model;
@OneToOne(mappedBy = "car")
private User user;
public Car(){}
public Car( String model,int series) {
this.series = series;
this.model = model;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getSeries() {
return series;
}
public void setSeries(int series) {
this.series = series;
}
@Override
public String toString() {
return "Car{" +
"series=" + series +
", model='" + model + '\'' +
'}';
}
} | [
"[email protected]"
] | |
56daabd31c451aee17f19eed23530353fc5f40b8 | 5cf7292f80f7c0e455d24b59bd074283014c9a2e | /app/src/main/java/tequila/Config.java | 4bae65ae64b3ea7ee783e1141a1dfee90b35b919 | [] | no_license | williamcspace/android-demo | 850ec3667ae002575014d04ccfbe6c66d2346847 | feb7c732f873bc41020ab3c02c2e09085995553f | refs/heads/master | 2021-01-20T06:57:03.084416 | 2015-10-01T10:02:33 | 2015-10-01T10:02:33 | 40,971,351 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,168 | java | package tequila;
import android.util.Log;
public class Config {
public static final String APP_VERSION = "v0.0.8";
// (MIN) assert -> error -> warn -> info -> debug -> verbose (MAX)
public static final int LOG_LEVEL = Log.VERBOSE;
// public static final String TXL_API_URL = "http://192.168.1.4:3000";
public static final String TXL_API_URL = "http://192.168.0.110:3000";
// public static final String TXL_API_URL = "http://test.tangxinli.com";
public static final String WX_API_URL = "https://api.weixin.qq.com";
public static final String WX_PAY_API_URL = "https://api.mch.weixin.qq.com";
public static final String RECT_MD_IMG = "/rect/md?q=";
public static final Integer PAGER_SIZE = 15;
public static final String COOKIE_KEY = "Set-Cookie";
public static final String SESSION_KEY = "express:sess";
public static final String SESSION_KEY_SIG = "express:sess.sig";
public static final String DB_VERSION = "v0.0.8";
public static final Integer SQL_SCHEMA_VERSION = 1;
public static final String FIELD_TABLE = "tequila_field_table";
public static final String TXL_NOTIFY_URL = "http://www.tangxinli.com";
//微信开放ID
public static final String WX_APP_ID = "wxd6ea79a9cfe9a6c2";
public static final String WX_APP_SECRET = "2372e90f6967c4c992ddf76b8893ea13";
public static final String WX_MCH_ID = "1252795601";
public static final String WX_MCH_KEY = "6d9c547cf146054a5a720606a7694467";
//支付宝
// 商户PID
public static final String ALIPAY_PARTNER = "2088811650935840";
public static final String ALIPAY_KEY = "xd72x235azqe9ciqwax86u4ywntn8igf";
// 商户收款账号
public static final String ALIPAY_SELLER = "[email protected]";
// 商户私钥,pkcs8格式
public static final String ALIPAY_RSA_PRIVATE = "MIICXQIBAAKBgQDZBh3v5gxcSQ77MfW9Q6JNuZwwrNMO5cOfXQnS/Ewa6HFKHwCZZNHYWrZfTu+HNtW2QhxJYtRuuUUvovT2mTeUupdnYmtkCGBjTMN0weHP9cNdnf/aF+GNjnfI+Rf3nfFCWdSmi6gGHaFZnqO52GOezcQrnLDbje7cWxG8CUOCLwIDAQABAoGARjJSUJxqdxcyf1GjmLpdryJQQPZFtlXfNpbTbKkqvLFeo4jvmq4fqgl9X8qac3PrIG61047iA4ZtuIDPF0xry1krp3V6SAqZ0yxdjDECb4p1TKyyavORdTgd8mGq7DEJa3lLwunvqCs0WL0S+WlFIRzWtNOUZIgPrCIIR9Tc5ZECQQDsiEC1IErNGnxWyJztbm49mBLDfsK20EEBVlFPMLGv4drmNj4aMZL/UkMq1cLY9xAovMBozpwEoxQbreDR65gNAkEA6uLSg3Bfby4Q0OuMIIBq9ZSik/zhflYaH98i/LWE7Ak296x2bnwmCPm07bvFh2ygAt3Oippwdxsu/73HyH7YKwJBANHNja/bY94H1zBXI7MK1+f0gvg68NWdZXudJ+QZKhL7P+IhTPaI8H1eZ0uQbhNrGj84JWcRlJwcVtKyaY9p7OUCQQCcbonjLfDxO83JRkah0sTpX59TTgTjvfZSKarEgSPQi2aHVt3dQWOXcK6V8gtg4PBEWHLZDng+auVHP56RoiDXAkAmxQ6gz6Glc2IA1feUgq/LbhLx2X/txlmPAaB1LLOI6OWotACr0I5QUBdD//2L9SXsrk6datkrBdBUzKIWgI1G";
// 支付宝公钥
public static final String ALIPAY_RSA_PUBLIC = "-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB-----END PUBLIC KEY-----";
//QQ开放ID
public static final String QQ_APP_ID = "100424468";
public static final String QQ_APP_KEY = "c7394704798a158208a74ab60104f0ba";
}
| [
"[email protected]"
] | |
8144d1792e7cb67c993eb614d9b038f2bb714857 | 202f047f449069ac3d5f567ff6de7a2ed4793e79 | /Codigo/AppNaranja/src/alc/appnaranja/presentador/IPresentadorPedirCita3.java | ea0edf0d84b8cb22a82202fa1c0ef8997f7f48bd | [] | no_license | aluzardo/trabajo-fin-de-grado | 2aad252cc5bec9e5f4cc3f667331c45e1d2dc274 | 1e8b17a539b795dcb3bd06a1b25e298e808f3a15 | refs/heads/master | 2021-01-10T14:28:29.592695 | 2016-01-14T00:18:52 | 2016-01-14T00:18:52 | 49,609,127 | 1 | 0 | null | null | null | null | WINDOWS-1250 | Java | false | false | 850 | java | package alc.appnaranja.presentador;
public interface IPresentadorPedirCita3 {
/**
* Se realizan todas las operaciones necesarias para mostrar la VistaPedirCita3.
*/
public void mostrarVistaPedirCita3();
/**
* Carga las fechas disponibles del modelo
*/
public void cargarFechas();
/**
* Presenta en la vista las fechas disponibles
*/
public void presentarFechas();
/**
* Carga las horas disponibles del modelo.
*/
public void cargarHoras();
/**
* Presenta las horas disponibles en la vista.
*/
public void presentarHoras();
/**
* Guarda en el modelo los datos introducidos por el usuario en la vista
*/
public void guardarDatos();
/**
* Lanza la actividad ConfirmarCita de la aplicación, donde el usuario puede confirmar la cita que ha introducido.
*/
public void lanzarConfirmarCita();
}
| [
"[email protected]"
] | |
d8f2e72f8fcb5720b82317ea19d91b5d49602ecc | b87a389bd09e16f1174236fdcd6a990707aef697 | /src/main/java/com/aaa/dao/InterviewDao.java | 7ac25dbec7fc9df43cb9ef7ab98e90465180a022 | [] | no_license | XJing9/ailybg | e881423c7946388964855c4c09d0b75f6125905e | 0a23176f46bdd9575a893bfc304603eebb92da38 | refs/heads/master | 2022-12-08T22:47:19.859759 | 2020-09-07T00:44:33 | 2020-09-07T00:44:33 | 289,138,766 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 899 | java | package com.aaa.dao;
import com.aaa.entity.Interview;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface InterviewDao extends tk.mybatis.mapper.common.Mapper<Interview> {
@Select("select * from Interview i1 left join entreprenenur e1 on i1.ent_id=e1.ent_id")
List<Interview>listint();
@Select("select * from Interview i1 left join entreprenenur e1 on i1.ent_id=e1.ent_id where i1.int_name like CONCAT('%',#{int_name},'%')")
List<Interview>mhlistint(@Param("int_name") String int_name);
@Delete("delete from Interview where int_id=#{int_id}")
Integer deleteint(Integer int_id);
@Update("update Interview set int_name=#{int_name},int_email=#{int_email}," +
"int_qq=#{int_qq},int_reladdress=#{int_reladdress},ent_id=#{ent_id},int_state=#{int_state} where int_id=#{int_id}")
Integer updateint(Interview interview);
} | [
"[email protected]"
] | |
11f347a98a68079af736798e1cc29b968fb35d34 | b3ef7415cad326aed00212c47c367150accf8b23 | /src/main/java/com/ccreanga/guava/showcase/eventbus/Producer.java | f93981736c602adb085a3e4184c9c5f6ff0cafe6 | [] | no_license | cornelcreanga/guava_tests | 7c3300aba696ee2046d7bf15b8c859a45ae0fd8c | c844fff05654d4f0f0d92368d6f954176b529969 | refs/heads/master | 2016-08-11T15:12:42.683677 | 2016-03-29T08:13:35 | 2016-03-29T08:13:35 | 54,837,822 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 160 | java | package com.ccreanga.guava.showcase.eventbus;
public class Producer {
public Producer() {
EventBusService.getInstance().postEvent("cucu");
}
}
| [
"tarnavenimures47"
] | tarnavenimures47 |
dd1dfdd193ebaf5c15f8ca3568aeb9c5f8adcf84 | c910b384330f2724cd2364de06bd0b4ce58099f7 | /components/cronet/android/test/javatests/src/org/chromium/net/CronetUrlRequestContextTest.java | f8c347ac94740634d65799db890e742d0b31b062 | [
"BSD-3-Clause"
] | permissive | techtonik/chromium | 3d4d5cf30a1a61f2d5559ac58638ce38cf2ab5cd | 319329de7edb672d11217094c5f9b77bc7af1f26 | refs/heads/master | 2021-10-02T05:10:56.666038 | 2015-10-13T20:09:21 | 2015-10-13T20:10:56 | 44,329,819 | 0 | 1 | null | 2015-10-15T16:14:05 | 2015-10-15T16:14:04 | null | UTF-8 | Java | false | false | 33,163 | java | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Looper;
import android.test.suitebuilder.annotation.SmallTest;
import org.chromium.base.PathUtils;
import org.chromium.base.test.util.Feature;
import org.chromium.net.TestUrlRequestListener.ResponseStep;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.concurrent.Executor;
/**
* Test CronetEngine.
*/
public class CronetUrlRequestContextTest extends CronetTestBase {
// URLs used for tests.
private static final String TEST_URL = "http://127.0.0.1:8000";
private static final String URL_404 = "http://127.0.0.1:8000/notfound404";
private static final String MOCK_CRONET_TEST_FAILED_URL =
"http://mock.failed.request/-2";
private static final String MOCK_CRONET_TEST_SUCCESS_URL =
"http://mock.http/success.txt";
CronetTestActivity mActivity;
static class RequestThread extends Thread {
public TestUrlRequestListener mListener;
final CronetTestActivity mActivity;
final String mUrl;
final ConditionVariable mRunBlocker;
public RequestThread(CronetTestActivity activity, String url,
ConditionVariable runBlocker) {
mActivity = activity;
mUrl = url;
mRunBlocker = runBlocker;
}
@Override
public void run() {
mRunBlocker.block();
CronetEngine cronetEngine = mActivity.initCronetEngine();
mListener = new TestUrlRequestListener();
UrlRequest.Builder urlRequestBuilder =
new UrlRequest.Builder(mUrl, mListener, mListener.getExecutor(), cronetEngine);
urlRequestBuilder.build().start();
mListener.blockForDone();
}
}
/**
* Listener that shutdowns the request context when request has succeeded
* or failed.
*/
class ShutdownTestUrlRequestListener extends TestUrlRequestListener {
@Override
public void onSucceeded(UrlRequest request, ExtendedResponseInfo info) {
super.onSucceeded(request, info);
mActivity.mCronetEngine.shutdown();
}
@Override
public void onFailed(UrlRequest request,
ResponseInfo info,
UrlRequestException error) {
super.onFailed(request, info, error);
mActivity.mCronetEngine.shutdown();
}
}
static class TestExecutor implements Executor {
private final LinkedList<Runnable> mTaskQueue = new LinkedList<Runnable>();
@Override
public void execute(Runnable task) {
mTaskQueue.add(task);
}
public void runAllTasks() {
try {
while (mTaskQueue.size() > 0) {
mTaskQueue.remove().run();
}
} catch (NoSuchElementException e) {
}
}
}
static class TestNetworkQualityListener
implements NetworkQualityRttListener, NetworkQualityThroughputListener {
int mRttObservationCount;
int mThroughputObservationCount;
public void onRttObservation(int rttMs, long when, int source) {
mRttObservationCount++;
}
public void onThroughputObservation(int throughputKbps, long when, int source) {
mThroughputObservationCount++;
}
public int rttObservationCount() {
return mRttObservationCount;
}
public int throughputObservationCount() {
return mThroughputObservationCount;
}
}
@SmallTest
@Feature({"Cronet"})
public void testConfigUserAgent() throws Exception {
String userAgentName = "User-Agent";
String userAgentValue = "User-Agent-Value";
CronetEngine.Builder cronetEngineBuilder = new CronetEngine.Builder(mActivity);
cronetEngineBuilder.setUserAgent(userAgentValue);
cronetEngineBuilder.setLibraryName("cronet_tests");
String[] commandLineArgs = {CronetTestActivity.CONFIG_KEY, cronetEngineBuilder.toString()};
mActivity = launchCronetTestAppWithUrlAndCommandLineArgs(TEST_URL,
commandLineArgs);
assertTrue(NativeTestServer.startNativeTestServer(
getInstrumentation().getTargetContext()));
TestUrlRequestListener listener = new TestUrlRequestListener();
UrlRequest.Builder urlRequestBuilder =
new UrlRequest.Builder(NativeTestServer.getEchoHeaderURL(userAgentName), listener,
listener.getExecutor(), mActivity.mCronetEngine);
urlRequestBuilder.build().start();
listener.blockForDone();
assertEquals(userAgentValue, listener.mResponseAsString);
}
@SmallTest
@Feature({"Cronet"})
public void testDataReductionProxyEnabled() throws Exception {
mActivity = launchCronetTestAppAndSkipFactoryInit();
// Ensure native code is loaded before trying to start test server.
new CronetEngine.Builder(getInstrumentation().getTargetContext())
.setLibraryName("cronet_tests")
.build()
.shutdown();
assertTrue(NativeTestServer.startNativeTestServer(
getInstrumentation().getTargetContext()));
if (!NativeTestServer.isDataReductionProxySupported()) {
return;
}
String serverHostPort = NativeTestServer.getHostPort();
// Enable the Data Reduction Proxy and configure it to use the test
// server as its primary proxy, and to check successfully that this
// proxy is OK to use.
CronetEngine.Builder cronetEngineBuilder =
new CronetEngine.Builder(getInstrumentation().getTargetContext());
cronetEngineBuilder.enableDataReductionProxy("test-key");
cronetEngineBuilder.setDataReductionProxyOptions(serverHostPort, "unused.net:9999",
NativeTestServer.getFileURL("/secureproxychecksuccess.txt"));
cronetEngineBuilder.setLibraryName("cronet_tests");
mActivity.mCronetEngine = cronetEngineBuilder.build();
TestUrlRequestListener listener = new TestUrlRequestListener();
// Construct and start a request that can only be returned by the test
// server. This request will fail if the configuration logic for the
// Data Reduction Proxy is not used.
UrlRequest.Builder urlRequestBuilder = new UrlRequest.Builder(
"http://DomainThatDoesnt.Resolve/datareductionproxysuccess.txt", listener,
listener.getExecutor(), mActivity.mCronetEngine);
urlRequestBuilder.build().start();
listener.blockForDone();
// Verify that the request is successful and that the Data Reduction
// Proxy logic configured to use the test server as its proxy.
assertEquals(200, listener.mResponseInfo.getHttpStatusCode());
assertEquals(serverHostPort, listener.mResponseInfo.getProxyServer());
assertEquals(
"http://DomainThatDoesnt.Resolve/datareductionproxysuccess.txt",
listener.mResponseInfo.getUrl());
}
@SmallTest
@Feature({"Cronet"})
public void testRealTimeNetworkQualityObservationsNotEnabled() throws Exception {
mActivity = launchCronetTestApp();
TestNetworkQualityListener networkQualityListener = new TestNetworkQualityListener();
try {
mActivity.mCronetEngine.addRttListener(networkQualityListener);
fail("Should throw an exception.");
} catch (IllegalStateException e) {
}
try {
mActivity.mCronetEngine.addThroughputListener(networkQualityListener);
fail("Should throw an exception.");
} catch (IllegalStateException e) {
}
TestUrlRequestListener listener = new TestUrlRequestListener();
UrlRequest urlRequest =
mActivity.mCronetEngine.createRequest(TEST_URL, listener, listener.getExecutor());
urlRequest.start();
listener.blockForDone();
assertEquals(0, networkQualityListener.rttObservationCount());
assertEquals(0, networkQualityListener.throughputObservationCount());
mActivity.mCronetEngine.shutdown();
}
@SmallTest
@Feature({"Cronet"})
public void testRealTimeNetworkQualityObservationsListenerRemoved() throws Exception {
mActivity = launchCronetTestApp();
TestExecutor testExecutor = new TestExecutor();
TestNetworkQualityListener networkQualityListener = new TestNetworkQualityListener();
mActivity.mCronetEngine.enableNetworkQualityEstimatorForTesting(true, true, testExecutor);
mActivity.mCronetEngine.addRttListener(networkQualityListener);
mActivity.mCronetEngine.addThroughputListener(networkQualityListener);
mActivity.mCronetEngine.removeRttListener(networkQualityListener);
mActivity.mCronetEngine.removeThroughputListener(networkQualityListener);
TestUrlRequestListener listener = new TestUrlRequestListener();
UrlRequest urlRequest =
mActivity.mCronetEngine.createRequest(TEST_URL, listener, listener.getExecutor());
urlRequest.start();
listener.blockForDone();
testExecutor.runAllTasks();
assertEquals(0, networkQualityListener.rttObservationCount());
assertEquals(0, networkQualityListener.throughputObservationCount());
mActivity.mCronetEngine.shutdown();
}
@SmallTest
@Feature({"Cronet"})
public void testRealTimeNetworkQualityObservations() throws Exception {
mActivity = launchCronetTestApp();
TestExecutor testExecutor = new TestExecutor();
TestNetworkQualityListener networkQualityListener = new TestNetworkQualityListener();
mActivity.mCronetEngine.enableNetworkQualityEstimatorForTesting(true, true, testExecutor);
mActivity.mCronetEngine.addRttListener(networkQualityListener);
mActivity.mCronetEngine.addThroughputListener(networkQualityListener);
TestUrlRequestListener listener = new TestUrlRequestListener();
UrlRequest urlRequest =
mActivity.mCronetEngine.createRequest(TEST_URL, listener, listener.getExecutor());
urlRequest.start();
listener.blockForDone();
testExecutor.runAllTasks();
assertTrue(networkQualityListener.rttObservationCount() > 0);
assertTrue(networkQualityListener.throughputObservationCount() > 0);
mActivity.mCronetEngine.shutdown();
}
@SmallTest
@Feature({"Cronet"})
public void testShutdown() throws Exception {
mActivity = launchCronetTestApp();
TestUrlRequestListener listener = new ShutdownTestUrlRequestListener();
// Block listener when response starts to verify that shutdown fails
// if there are active requests.
listener.setAutoAdvance(false);
UrlRequest.Builder urlRequestBuilder = new UrlRequest.Builder(
TEST_URL, listener, listener.getExecutor(), mActivity.mCronetEngine);
UrlRequest urlRequest = urlRequestBuilder.build();
urlRequest.start();
try {
mActivity.mCronetEngine.shutdown();
fail("Should throw an exception");
} catch (Exception e) {
assertEquals("Cannot shutdown with active requests.",
e.getMessage());
}
listener.waitForNextStep();
assertEquals(ResponseStep.ON_RESPONSE_STARTED, listener.mResponseStep);
try {
mActivity.mCronetEngine.shutdown();
fail("Should throw an exception");
} catch (Exception e) {
assertEquals("Cannot shutdown with active requests.",
e.getMessage());
}
listener.startNextRead(urlRequest);
listener.waitForNextStep();
assertEquals(ResponseStep.ON_READ_COMPLETED, listener.mResponseStep);
try {
mActivity.mCronetEngine.shutdown();
fail("Should throw an exception");
} catch (Exception e) {
assertEquals("Cannot shutdown with active requests.",
e.getMessage());
}
// May not have read all the data, in theory. Just enable auto-advance
// and finish the request.
listener.setAutoAdvance(true);
listener.startNextRead(urlRequest);
listener.blockForDone();
}
@SmallTest
@Feature({"Cronet"})
public void testShutdownDuringInit() throws Exception {
final CronetTestActivity activity = launchCronetTestAppAndSkipFactoryInit();
final ConditionVariable block = new ConditionVariable(false);
// Post a task to main thread to block until shutdown is called to test
// scenario when shutdown is called right after construction before
// context is fully initialized on the main thread.
Runnable blockingTask = new Runnable() {
public void run() {
try {
block.block();
} catch (Exception e) {
fail("Caught " + e.getMessage());
}
}
};
// Ensure that test is not running on the main thread.
assertTrue(Looper.getMainLooper() != Looper.myLooper());
new Handler(Looper.getMainLooper()).post(blockingTask);
// Create new request context, but its initialization on the main thread
// will be stuck behind blockingTask.
final CronetEngine cronetEngine = activity.initCronetEngine();
// Unblock the main thread, so context gets initialized and shutdown on
// it.
block.open();
// Shutdown will wait for init to complete on main thread.
cronetEngine.shutdown();
// Verify that context is shutdown.
try {
cronetEngine.stopNetLog();
fail("Should throw an exception.");
} catch (Exception e) {
assertEquals("Engine is shut down.", e.getMessage());
}
}
@SmallTest
@Feature({"Cronet"})
public void testInitAndShutdownOnMainThread() throws Exception {
final CronetTestActivity activity = launchCronetTestAppAndSkipFactoryInit();
final ConditionVariable block = new ConditionVariable(false);
// Post a task to main thread to init and shutdown on the main thread.
Runnable blockingTask = new Runnable() {
public void run() {
// Create new request context, loading the library.
final CronetEngine cronetEngine = activity.initCronetEngine();
// Shutdown right after init.
cronetEngine.shutdown();
// Verify that context is shutdown.
try {
cronetEngine.stopNetLog();
fail("Should throw an exception.");
} catch (Exception e) {
assertEquals("Engine is shut down.", e.getMessage());
}
block.open();
}
};
new Handler(Looper.getMainLooper()).post(blockingTask);
// Wait for shutdown to complete on main thread.
block.block();
}
@SmallTest
@Feature({"Cronet"})
public void testMultipleShutdown() throws Exception {
mActivity = launchCronetTestApp();
try {
mActivity.mCronetEngine.shutdown();
mActivity.mCronetEngine.shutdown();
fail("Should throw an exception");
} catch (Exception e) {
assertEquals("Engine is shut down.", e.getMessage());
}
}
@SmallTest
@Feature({"Cronet"})
public void testShutdownAfterError() throws Exception {
mActivity = launchCronetTestApp();
TestUrlRequestListener listener = new ShutdownTestUrlRequestListener();
UrlRequest.Builder urlRequestBuilder = new UrlRequest.Builder(MOCK_CRONET_TEST_FAILED_URL,
listener, listener.getExecutor(), mActivity.mCronetEngine);
urlRequestBuilder.build().start();
listener.blockForDone();
assertTrue(listener.mOnErrorCalled);
}
@SmallTest
@Feature({"Cronet"})
public void testShutdownAfterCancel() throws Exception {
mActivity = launchCronetTestApp();
TestUrlRequestListener listener = new TestUrlRequestListener();
// Block listener when response starts to verify that shutdown fails
// if there are active requests.
listener.setAutoAdvance(false);
UrlRequest.Builder urlRequestBuilder = new UrlRequest.Builder(
TEST_URL, listener, listener.getExecutor(), mActivity.mCronetEngine);
UrlRequest urlRequest = urlRequestBuilder.build();
urlRequest.start();
try {
mActivity.mCronetEngine.shutdown();
fail("Should throw an exception");
} catch (Exception e) {
assertEquals("Cannot shutdown with active requests.",
e.getMessage());
}
listener.waitForNextStep();
assertEquals(ResponseStep.ON_RESPONSE_STARTED, listener.mResponseStep);
urlRequest.cancel();
mActivity.mCronetEngine.shutdown();
}
@SmallTest
@Feature({"Cronet"})
public void testNetLog() throws Exception {
Context context = getInstrumentation().getTargetContext();
File directory = new File(PathUtils.getDataDirectory(context));
File file = File.createTempFile("cronet", "json", directory);
CronetEngine cronetEngine = new CronetUrlRequestContext(
new CronetEngine.Builder(context).setLibraryName("cronet_tests"));
// Start NetLog immediately after the request context is created to make
// sure that the call won't crash the app even when the native request
// context is not fully initialized. See crbug.com/470196.
cronetEngine.startNetLogToFile(file.getPath(), false);
// Start a request.
TestUrlRequestListener listener = new TestUrlRequestListener();
UrlRequest.Builder urlRequestBuilder =
new UrlRequest.Builder(TEST_URL, listener, listener.getExecutor(), cronetEngine);
urlRequestBuilder.build().start();
listener.blockForDone();
cronetEngine.stopNetLog();
assertTrue(file.exists());
assertTrue(file.length() != 0);
assertFalse(hasBytesInNetLog(file));
assertTrue(file.delete());
assertTrue(!file.exists());
}
@SmallTest
@Feature({"Cronet"})
public void testNetLogAfterShutdown() throws Exception {
mActivity = launchCronetTestApp();
TestUrlRequestListener listener = new TestUrlRequestListener();
UrlRequest.Builder urlRequestBuilder = new UrlRequest.Builder(
TEST_URL, listener, listener.getExecutor(), mActivity.mCronetEngine);
urlRequestBuilder.build().start();
listener.blockForDone();
mActivity.mCronetEngine.shutdown();
File directory = new File(PathUtils.getDataDirectory(
getInstrumentation().getTargetContext()));
File file = File.createTempFile("cronet", "json", directory);
try {
mActivity.mCronetEngine.startNetLogToFile(file.getPath(), false);
fail("Should throw an exception.");
} catch (Exception e) {
assertEquals("Engine is shut down.", e.getMessage());
}
assertFalse(hasBytesInNetLog(file));
assertTrue(file.delete());
assertTrue(!file.exists());
}
@SmallTest
@Feature({"Cronet"})
public void testNetLogStartMultipleTimes() throws Exception {
mActivity = launchCronetTestApp();
File directory = new File(PathUtils.getDataDirectory(
getInstrumentation().getTargetContext()));
File file = File.createTempFile("cronet", "json", directory);
// Start NetLog multiple times.
mActivity.mCronetEngine.startNetLogToFile(file.getPath(), false);
mActivity.mCronetEngine.startNetLogToFile(file.getPath(), false);
mActivity.mCronetEngine.startNetLogToFile(file.getPath(), false);
mActivity.mCronetEngine.startNetLogToFile(file.getPath(), false);
// Start a request.
TestUrlRequestListener listener = new TestUrlRequestListener();
UrlRequest.Builder urlRequestBuilder = new UrlRequest.Builder(
TEST_URL, listener, listener.getExecutor(), mActivity.mCronetEngine);
urlRequestBuilder.build().start();
listener.blockForDone();
mActivity.mCronetEngine.stopNetLog();
assertTrue(file.exists());
assertTrue(file.length() != 0);
assertFalse(hasBytesInNetLog(file));
assertTrue(file.delete());
assertTrue(!file.exists());
}
@SmallTest
@Feature({"Cronet"})
public void testNetLogStopMultipleTimes() throws Exception {
mActivity = launchCronetTestApp();
File directory = new File(PathUtils.getDataDirectory(
getInstrumentation().getTargetContext()));
File file = File.createTempFile("cronet", "json", directory);
mActivity.mCronetEngine.startNetLogToFile(file.getPath(), false);
// Start a request.
TestUrlRequestListener listener = new TestUrlRequestListener();
UrlRequest.Builder urlRequestBuilder = new UrlRequest.Builder(
TEST_URL, listener, listener.getExecutor(), mActivity.mCronetEngine);
urlRequestBuilder.build().start();
listener.blockForDone();
// Stop NetLog multiple times.
mActivity.mCronetEngine.stopNetLog();
mActivity.mCronetEngine.stopNetLog();
mActivity.mCronetEngine.stopNetLog();
mActivity.mCronetEngine.stopNetLog();
mActivity.mCronetEngine.stopNetLog();
assertTrue(file.exists());
assertTrue(file.length() != 0);
assertFalse(hasBytesInNetLog(file));
assertTrue(file.delete());
assertTrue(!file.exists());
}
@SmallTest
@Feature({"Cronet"})
public void testNetLogWithBytes() throws Exception {
Context context = getInstrumentation().getTargetContext();
File directory = new File(PathUtils.getDataDirectory(context));
File file = File.createTempFile("cronet", "json", directory);
CronetEngine cronetEngine = new CronetUrlRequestContext(
new CronetEngine.Builder(context).setLibraryName("cronet_tests"));
// Start NetLog with logAll as true.
cronetEngine.startNetLogToFile(file.getPath(), true);
// Start a request.
TestUrlRequestListener listener = new TestUrlRequestListener();
UrlRequest.Builder urlRequestBuilder =
new UrlRequest.Builder(TEST_URL, listener, listener.getExecutor(), cronetEngine);
urlRequestBuilder.build().start();
listener.blockForDone();
cronetEngine.stopNetLog();
assertTrue(file.exists());
assertTrue(file.length() != 0);
assertTrue(hasBytesInNetLog(file));
assertTrue(file.delete());
assertTrue(!file.exists());
}
private boolean hasBytesInNetLog(File logFile) throws Exception {
BufferedReader logReader = new BufferedReader(new FileReader(logFile));
try {
String logLine;
while ((logLine = logReader.readLine()) != null) {
if (logLine.contains("\"hex_encoded_bytes\"")) {
return true;
}
}
return false;
} finally {
logReader.close();
}
}
private void enableCache(int cacheType) throws Exception {
String cacheTypeString = "";
if (cacheType == CronetEngine.Builder.HTTP_CACHE_DISK) {
cacheTypeString = CronetTestActivity.CACHE_DISK;
} else if (cacheType == CronetEngine.Builder.HTTP_CACHE_DISK_NO_HTTP) {
cacheTypeString = CronetTestActivity.CACHE_DISK_NO_HTTP;
} else if (cacheType == CronetEngine.Builder.HTTP_CACHE_IN_MEMORY) {
cacheTypeString = CronetTestActivity.CACHE_IN_MEMORY;
}
String[] commandLineArgs = {CronetTestActivity.CACHE_KEY, cacheTypeString};
mActivity = launchCronetTestAppWithUrlAndCommandLineArgs(null,
commandLineArgs);
assertTrue(NativeTestServer.startNativeTestServer(
getInstrumentation().getTargetContext()));
}
private void checkRequestCaching(String url, boolean expectCached) {
checkRequestCaching(url, expectCached, false);
}
private void checkRequestCaching(String url, boolean expectCached,
boolean disableCache) {
TestUrlRequestListener listener = new TestUrlRequestListener();
UrlRequest.Builder urlRequestBuilder = new UrlRequest.Builder(
url, listener, listener.getExecutor(), mActivity.mCronetEngine);
if (disableCache) {
urlRequestBuilder.disableCache();
}
urlRequestBuilder.build().start();
listener.blockForDone();
assertEquals(expectCached, listener.mResponseInfo.wasCached());
}
@SmallTest
@Feature({"Cronet"})
public void testEnableHttpCacheDisabled() throws Exception {
enableCache(CronetEngine.Builder.HTTP_CACHE_DISABLED);
String url = NativeTestServer.getFileURL("/cacheable.txt");
checkRequestCaching(url, false);
checkRequestCaching(url, false);
checkRequestCaching(url, false);
}
@SmallTest
@Feature({"Cronet"})
public void testEnableHttpCacheInMemory() throws Exception {
enableCache(CronetEngine.Builder.HTTP_CACHE_IN_MEMORY);
String url = NativeTestServer.getFileURL("/cacheable.txt");
checkRequestCaching(url, false);
checkRequestCaching(url, true);
NativeTestServer.shutdownNativeTestServer();
checkRequestCaching(url, true);
}
@SmallTest
@Feature({"Cronet"})
public void testEnableHttpCacheDisk() throws Exception {
enableCache(CronetEngine.Builder.HTTP_CACHE_DISK);
String url = NativeTestServer.getFileURL("/cacheable.txt");
checkRequestCaching(url, false);
checkRequestCaching(url, true);
NativeTestServer.shutdownNativeTestServer();
checkRequestCaching(url, true);
}
@SmallTest
@Feature({"Cronet"})
public void testEnableHttpCacheDiskNoHttp() throws Exception {
enableCache(CronetEngine.Builder.HTTP_CACHE_DISABLED);
String url = NativeTestServer.getFileURL("/cacheable.txt");
checkRequestCaching(url, false);
checkRequestCaching(url, false);
checkRequestCaching(url, false);
}
@SmallTest
@Feature({"Cronet"})
public void testDisableCache() throws Exception {
enableCache(CronetEngine.Builder.HTTP_CACHE_DISK);
String url = NativeTestServer.getFileURL("/cacheable.txt");
// When cache is disabled, making a request does not write to the cache.
checkRequestCaching(url, false, true /** disable cache */);
checkRequestCaching(url, false);
// When cache is enabled, the second request is cached.
checkRequestCaching(url, false, true /** disable cache */);
checkRequestCaching(url, true);
// Shut down the server, next request should have a cached response.
NativeTestServer.shutdownNativeTestServer();
checkRequestCaching(url, true);
// Cache is disabled after server is shut down, request should fail.
TestUrlRequestListener listener = new TestUrlRequestListener();
UrlRequest.Builder urlRequestBuilder = new UrlRequest.Builder(
url, listener, listener.getExecutor(), mActivity.mCronetEngine);
urlRequestBuilder.disableCache();
urlRequestBuilder.build().start();
listener.blockForDone();
assertNotNull(listener.mError);
assertEquals("Exception in CronetUrlRequest: net::ERR_CONNECTION_REFUSED",
listener.mError.getMessage());
}
@SmallTest
@Feature({"Cronet"})
public void testEnableHttpCacheDiskNewEngine() throws Exception {
enableCache(CronetEngine.Builder.HTTP_CACHE_DISK);
String url = NativeTestServer.getFileURL("/cacheable.txt");
checkRequestCaching(url, false);
checkRequestCaching(url, true);
NativeTestServer.shutdownNativeTestServer();
checkRequestCaching(url, true);
// Shutdown original context and create another that uses the same cache.
mActivity.mCronetEngine.shutdown();
mActivity.mCronetEngine = mActivity.getCronetEngineBuilder().build();
checkRequestCaching(url, true);
}
@SmallTest
@Feature({"Cronet"})
public void testInitEngineAndStartRequest() {
CronetTestActivity activity = launchCronetTestAppAndSkipFactoryInit();
// Immediately make a request after initializing the engine.
CronetEngine cronetEngine = activity.initCronetEngine();
TestUrlRequestListener listener = new TestUrlRequestListener();
UrlRequest.Builder urlRequestBuilder =
new UrlRequest.Builder(TEST_URL, listener, listener.getExecutor(), cronetEngine);
urlRequestBuilder.build().start();
listener.blockForDone();
assertEquals(200, listener.mResponseInfo.getHttpStatusCode());
}
@SmallTest
@Feature({"Cronet"})
public void testInitEngineStartTwoRequests() throws Exception {
CronetTestActivity activity = launchCronetTestAppAndSkipFactoryInit();
// Make two requests after initializing the context.
CronetEngine cronetEngine = activity.initCronetEngine();
int[] statusCodes = {0, 0};
String[] urls = {TEST_URL, URL_404};
for (int i = 0; i < 2; i++) {
TestUrlRequestListener listener = new TestUrlRequestListener();
UrlRequest.Builder urlRequestBuilder =
new UrlRequest.Builder(urls[i], listener, listener.getExecutor(), cronetEngine);
urlRequestBuilder.build().start();
listener.blockForDone();
statusCodes[i] = listener.mResponseInfo.getHttpStatusCode();
}
assertEquals(200, statusCodes[0]);
assertEquals(404, statusCodes[1]);
}
@SmallTest
@Feature({"Cronet"})
public void testInitTwoEnginesSimultaneously() throws Exception {
final CronetTestActivity activity = launchCronetTestAppAndSkipFactoryInit();
// Threads will block on runBlocker to ensure simultaneous execution.
ConditionVariable runBlocker = new ConditionVariable(false);
RequestThread thread1 = new RequestThread(activity, TEST_URL, runBlocker);
RequestThread thread2 = new RequestThread(activity, URL_404, runBlocker);
thread1.start();
thread2.start();
runBlocker.open();
thread1.join();
thread2.join();
assertEquals(200, thread1.mListener.mResponseInfo.getHttpStatusCode());
assertEquals(404, thread2.mListener.mResponseInfo.getHttpStatusCode());
}
@SmallTest
@Feature({"Cronet"})
public void testInitTwoEnginesInSequence() throws Exception {
final CronetTestActivity activity = launchCronetTestAppAndSkipFactoryInit();
ConditionVariable runBlocker = new ConditionVariable(true);
RequestThread thread1 = new RequestThread(activity, TEST_URL, runBlocker);
RequestThread thread2 = new RequestThread(activity, URL_404, runBlocker);
thread1.start();
thread1.join();
thread2.start();
thread2.join();
assertEquals(200, thread1.mListener.mResponseInfo.getHttpStatusCode());
assertEquals(404, thread2.mListener.mResponseInfo.getHttpStatusCode());
}
@SmallTest
@Feature({"Cronet"})
public void testInitDifferentEngines() throws Exception {
// Test that concurrently instantiating Cronet context's upon various
// different versions of the same Android Context does not cause crashes
// like crbug.com/453845
mActivity = launchCronetTestApp();
CronetEngine firstEngine =
new CronetUrlRequestContext(mActivity.createCronetEngineBuilder(mActivity));
CronetEngine secondEngine = new CronetUrlRequestContext(
mActivity.createCronetEngineBuilder(mActivity.getApplicationContext()));
CronetEngine thirdEngine = new CronetUrlRequestContext(
mActivity.createCronetEngineBuilder(new ContextWrapper(mActivity)));
firstEngine.shutdown();
secondEngine.shutdown();
thirdEngine.shutdown();
}
}
| [
"[email protected]"
] | |
14e6f19dbbe643af3073098c0346ef4ab6eff9f4 | 78b4e2d4bed10c82ea03341920a36f83df0b5717 | /YB-RBAC/src/main/java/com/yb/loginmodule/controller/loginController.java | 3b10ff18eec334296555d49f03b6d9657d9a0a84 | [] | no_license | lxm-sa/- | 0cfdfcb050d94e272c1c3d36635b2222a842e482 | 080f8b1aa30284fd88671e7a5dd9061c67a5effb | refs/heads/master | 2022-07-12T10:51:46.945816 | 2019-10-11T02:53:10 | 2019-10-11T02:53:10 | 214,329,086 | 0 | 0 | null | 2022-06-29T17:41:58 | 2019-10-11T02:48:35 | JavaScript | UTF-8 | Java | false | false | 2,665 | java | package com.yb.loginmodule.controller;
import com.yb.base.pojo.RoleEntity;
import com.yb.base.pojo.UserEntity;
import com.yb.loginmodule.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
@Controller
public class loginController {
@Autowired
private UserService userService;
@RequestMapping(value="/toLogin")
public String toLogin(HttpServletRequest request) throws Exception{
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "login";
}
@RequestMapping(value="/toIndex")
public String toIndex(HttpServletRequest request) {
try {
HttpSession session = request.getSession();
Map<String,Object> usermap = ( Map<String,Object>)session.getAttribute("user");
UserEntity user =(UserEntity) usermap.get("user");
if(user.getStatus()==0){
request.setAttribute("msg", "用户审核未通过,如有意见,请联系管理员");
return "forward:/toLogin";
}if(user.getStatus()==2){
request.setAttribute("msg", "用户待审核状态,如果时间紧急,请联系管理员");
return "forward:/toLogin";
}if(user.getIsdelete()==1){
request.setAttribute("msg", "该账号已被锁定,请联系管理员");
return "forward:/toLogin";
}
SecurityUtils.getSubject().getSession().setTimeout(120*60*1000);
return "index";
}catch (Exception e){
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "forward:/toLogin";
}
}
@RequestMapping("/logout")
public String logout(HttpSession session, Model model) {
Subject subject = SecurityUtils.getSubject();
subject.logout();
model.addAttribute("msg","安全退出!");
return "login";
}
@RequestMapping("/register")
public String register(Model model) {
List<RoleEntity> list = userService.selectAllRole();
model.addAttribute("roles",list);
return "register";
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.