blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 7
410
| content_id
stringlengths 40
40
| detected_licenses
listlengths 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
684M
⌀ | 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 132
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 28
values | content
stringlengths 3
9.45M
| authors
listlengths 1
1
| author_id
stringlengths 0
352
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
df66099bcedea5cbe6fea6cef57127bd2e058400
|
6b09c1b724b5313107bfae87e666c593dc41f5e1
|
/app/src/main/java/com/example/medicalsupportsystem/MainActivity.java
|
575a692256eb0d26a6ec672b9ba6a7eb80ec434c
|
[] |
no_license
|
benesi-fundos/newlyupdated
|
437b6c4a044967d35109b41925ef65b7b4c4b1f3
|
f5437571982ab801fa5476abf7098ba5e07a202b
|
refs/heads/main
| 2023-07-16T06:18:09.188057
| 2021-08-27T18:56:30
| 2021-08-27T18:56:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,285
|
java
|
package com.example.medicalsupportsystem;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public Button signup1, signin1, signup2, signin2, goForTest, visitHospital;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signup1 =(Button)findViewById(R.id.btn1);
signin1 =(Button)findViewById(R.id.btn2);
signup2 =(Button)findViewById(R.id.btnb1);
signin2=(Button)findViewById(R.id.btnb2);
goForTest=(Button)findViewById(R.id.btn3);
visitHospital = (Button)findViewById(R.id.visthosp);
signup1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent create = new Intent(MainActivity.this, signup.class);
startActivity(create);
}
});
signup2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent create = new Intent(MainActivity.this, signuppatient.class);
startActivity(create);
}
});
signin1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent create1 = new Intent(MainActivity.this, register.class);
startActivity(create1);
}
});
signin2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent create1 = new Intent(MainActivity.this, task2.class);
startActivity(create1);
}
});
goForTest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, diagnosissection.class);
startActivity(intent);
}
});
visitHospital.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Appointmants.class);
startActivity(intent);
}
});
}
}
|
[
"benesi-fundos"
] |
benesi-fundos
|
de609998b80595c5d91b0cc73a1a178102ef3c2d
|
4c9a93e06b0af708f6e0d2d4d44ed7c1a7580eb2
|
/xstream/src/java/com/thoughtworks/xstream/converters/extended/ActivationDataFlavorConverter.java
|
a7e6904facff1efc9220438bf123169c8e38d213
|
[
"BSD-3-Clause"
] |
permissive
|
zeshuai007/xstream
|
dc550a39a3ba980ce276310854e9fbb197ac78dc
|
87ccfbf98a8db545f4d30f2fc71a8a0c37609dc2
|
refs/heads/master
| 2021-02-14T09:33:15.275733
| 2020-03-04T10:59:27
| 2020-03-21T09:04:48
| 244,793,330
| 0
| 0
|
NOASSERTION
| 2020-03-04T10:59:55
| 2020-03-04T02:55:08
|
Java
|
UTF-8
|
Java
| false
| false
| 3,618
|
java
|
/*
* Copyright (C) 2015 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 21.06.2015 by Joerg Schaible
*/
package com.thoughtworks.xstream.converters.extended;
import javax.activation.ActivationDataFlavor;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* Converts an {@link ActivationDataFlavor}.
*
* @author Jörg Schaible
* @since 1.4.9
*/
public class ActivationDataFlavorConverter implements Converter {
@Override
public boolean canConvert(final Class<?> type) {
return type == ActivationDataFlavor.class;
}
@Override
public void marshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) {
final ActivationDataFlavor dataFlavor = ActivationDataFlavor.class.cast(source);
final String mimeType = dataFlavor.getMimeType();
if (mimeType != null) {
writer.startNode("mimeType");
writer.setValue(mimeType);
writer.endNode();
}
final String name = dataFlavor.getHumanPresentableName();
if (name != null) {
writer.startNode("humanRepresentableName");
writer.setValue(name);
writer.endNode();
}
final Class<?> representationClass = dataFlavor.getRepresentationClass();
if (representationClass != null) {
writer.startNode("representationClass");
context.convertAnother(representationClass);
writer.endNode();
}
}
@Override
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
String mimeType = null;
String name = null;
Class<?> type = null;
while (reader.hasMoreChildren()) {
reader.moveDown();
final String elementName = reader.getNodeName();
if (elementName.equals("mimeType")) {
mimeType = reader.getValue();
} else if (elementName.equals("humanRepresentableName")) {
name = reader.getValue();
} else if (elementName.equals("representationClass")) {
type = (Class<?>)context.convertAnother(null, Class.class);
} else {
final ConversionException exception = new ConversionException("Unknown child element");
exception.add("element", reader.getNodeName());
throw exception;
}
reader.moveUp();
}
ActivationDataFlavor dataFlavor = null;
try {
if (type == null) {
dataFlavor = new ActivationDataFlavor(mimeType, name);
} else if (mimeType == null) {
dataFlavor = new ActivationDataFlavor(type, name);
} else {
dataFlavor = new ActivationDataFlavor(type, mimeType, name);
}
} catch (final IllegalArgumentException ex) {
throw new ConversionException(ex);
} catch (final NullPointerException ex) {
throw new ConversionException(ex);
}
return dataFlavor;
}
}
|
[
"joerg.schaible@gmx.de"
] |
joerg.schaible@gmx.de
|
913a6a46ba17523c212bcf147cf925a6dc3ab0eb
|
420ffaaf845d1ca9396c876b0b5d1addddbec50b
|
/src/practiceJava4/Car.java
|
9e6e4dd35531ccb19d5e97cec656fc9c2f66771b
|
[] |
no_license
|
PranaliSonawane1106/java
|
e5ad449a66ddf17dfc4647585a712c7ae0888b52
|
573d5e0937ee4b079236e04ec277fd096b2be35a
|
refs/heads/master
| 2023-07-05T11:36:20.379840
| 2021-08-31T10:00:47
| 2021-08-31T10:00:47
| 401,649,255
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 529
|
java
|
package practiceJava4;
public class Car extends Vehicle {
// Private field
private String bodyStyle;
// Parameterized Constructor
public Car(String make, String color, int year, String model, String bodyStyle) {
super(make, color, year, model); //calling parent class constructor
this.bodyStyle = bodyStyle;
}
public void carDetails() { //details of car
printDetails(); //calling method from parent class
System.out.println("Body Style: " + bodyStyle);
}
}
|
[
"pranalisonawane1106@gmail.com"
] |
pranalisonawane1106@gmail.com
|
f6d305b64dbf9347399e7d608a73c1592b104bb1
|
ee60fd71f19003ac9eff69a93350adf27c878e7a
|
/src/geometries/Cylinder.java
|
860154900144be0b8fac14d67df7e2c0a371b521
|
[] |
no_license
|
RuthMil/SEI_project_5780
|
48418e76626a553aea08773356f55e8e7c5f8d0a
|
8bfe1729d39618f856d53b778b50d232c4db7672
|
refs/heads/master
| 2022-11-18T04:51:27.838288
| 2020-07-15T19:32:39
| 2020-07-15T19:32:39
| 248,635,635
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,663
|
java
|
package geometries;
import primitives.*;
import static primitives.Util.alignZero;
import static primitives.Util.isZero;
/**
* Cylinder class is implementing a cylinder, extends tube, with a radius, axis ray, and height
* @author Ruth Miller
* ruthmiller2000@gmail.com
*/
public class Cylinder extends Tube {
protected double _height;
@Override
public String toString() {
return "height= " + _height +
", " + super.toString();
}
/**
* Height getter
* @return an height of a cylinder
*/
public double get_height() {
return _height;
}
/**
* Constructor for Cylinder class, gets a radius, ray and height and creates a new match cylinder
* @param _radius
* @param _axisRay
* @param _height
*/
public Cylinder(double _radius, Ray _axisRay, double _height) {
super(_radius, _axisRay);
this._height = _height;
}
/**
* Constructor for Cylinder class, gets an emission, a radius, ray and height and creates a new match cylinder
* @param emission emission light
* @param _radius
* @param _axisRay
* @param _height
*/
public Cylinder(Color emission, double _radius, Ray _axisRay, double _height) {
this(_radius, _axisRay, _height);
this._emission = emission;
}
/**
* Constructor for Cylinder class, gets an emission, a radius, ray and height and creates a new match cylinder
* @param material material of the cylinder
* @param emission emission light
* @param _radius
* @param _axisRay
* @param _height
*/
public Cylinder(Material material, Color emission, double _radius, Ray _axisRay, double _height) {
this(emission, _radius, _axisRay, _height);
this._material = material;
}
/**
* Return a normal to the cylinder
* @param point3D a point that the normal will start from it
* @return a normal to cylinder
*/
public Vector getNormal(Point3D point3D) {
double t;
// if point3D is equal to p0 point in the axis ray, return the direction vector
try{
t = alignZero(this._axisRay.getDir().dotProduct(point3D.subtract(this._axisRay.get_p0())));
}
catch (Exception e){
return this._axisRay.getDir();
}
// if the point is at one of the bases, return the direction vector
if(t ==0 || isZero(this._height - Math.abs(t)))
return this._axisRay.getDir();
Point3D O = this._axisRay.get_p0().add(this._axisRay.getDir().scale(t));
return point3D.subtract(O).normalize();
}
}
|
[
"ruthmiller2000@gmail.com"
] |
ruthmiller2000@gmail.com
|
fce892edb86f000bf3e237134ef66e6f997b8fdd
|
f23a4b48cc469ca3864cd364f34b20c424604a8f
|
/app/src/test/java/com/jyh/rest/ExampleUnitTest.java
|
5148effc2226f7bb5cb3634afa4fc1d57df50ac9
|
[] |
no_license
|
wulafu/Rest-master
|
d1d2a719d925cf7aac5f6863c0027aa832379c40
|
c36b993a5552c7041236f34eb0548def2561b73b
|
refs/heads/master
| 2021-01-12T05:51:37.005062
| 2016-12-23T10:25:25
| 2016-12-23T10:25:25
| 77,218,077
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 305
|
java
|
package com.jyh.rest;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
|
[
"763211273@qq.com"
] |
763211273@qq.com
|
0dc1cacd97c27107b42b941fb9ebe9b0861453ce
|
af5b6be44ee9bcc5ed03c69091872b551b133042
|
/libs/traci4matlab/traci4matlab/src/co/edu/unalmed/gaunal/traci4matlab/utils/DataReader.java
|
d0eb59270b574558156121d6219f2b937e8a64e7
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
ioannismavromatis/sumoCAVs
|
cc69b0e2d63b2620cea5b07c22c8eef4d1ed5fc8
|
210fd6df0c0a1fa9d3d8a27f5105ccc8b4c092b2
|
refs/heads/master
| 2021-01-15T04:34:13.816804
| 2020-02-25T01:06:10
| 2020-02-25T01:06:10
| 242,878,978
| 2
| 0
| null | 2020-02-25T01:07:47
| 2020-02-25T01:07:46
| null |
UTF-8
|
Java
| false
| false
| 1,527
|
java
|
/*
* Thanks to Rodney Thomson for this code
* http://www.mathworks.com/matlabcentral/fileexchange/25249-tcp-ip-socket-communications-in-matlab-using-java-classes
* This class improves the TraCI4Matlab performance when reading from the server.
*
* Copyright 2019 Universidad Nacional de Colombia,
* Politecnico Jaime Isaza Cadavid.
* Authors: Andres Acosta, Jairo Espinosa, Jorge Espinosa.
* $Id: DataReader.java 48 2018-12-26 15:35:20Z afacostag $
*/
package co.edu.unalmed.gaunal.traci4matlab.utils;
import java.io.DataInput;
import java.io.EOFException;
import java.io.IOException;
import java.io.StreamCorruptedException;
/**
*
* @author GaunalJD
*/
public class DataReader {
public DataReader(DataInput data_input)
{
m_data_input = data_input;
}
public byte[] readBuffer(int length) throws IOException
{
byte[] buffer = new byte[length];
try
{
m_data_input.readFully(buffer, 0, length);
}
catch (StreamCorruptedException e)
{
System.out.println("Stream Corrupted Exception Occured");
buffer = new byte[0];
}
catch (EOFException e)
{
System.out.println("EOF Reached");
buffer = new byte[0];
}
catch (IOException e)
{
System.out.println("IO Exception Occured");
buffer = new byte[0];
}
return buffer;
}
private DataInput m_data_input;
}
|
[
"ioan.mavromatis@gmail.com"
] |
ioan.mavromatis@gmail.com
|
0d91ef8bb48f1104159cb85a5674c401eb11500f
|
e4a4021ed2bbee9b2756adb6bfceec57b0d93d09
|
/wyj/Day62_SpringBoot-WYJ/src/main/java/com/lanou/springbootwyj/mapper/ArticleMapper.java
|
435e8ae980f07123fb6b1ae5bba8703599613f69
|
[] |
no_license
|
1639259135/My_Project
|
27b730b9487cc2156379f784cc02ad2bd74e1d26
|
79f10c38921306c1ad70009d753191e4c2b109e8
|
refs/heads/master
| 2021-04-15T09:35:37.331245
| 2018-03-23T07:17:46
| 2018-03-23T07:17:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 765
|
java
|
package com.lanou.springbootwyj.mapper;
import com.lanou.springbootwyj.domain.Article;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ArticleMapper {
@Select("select * from article")
List<Article> findArticles();
@Select("select * from article limit #{page},#{PAGE_SIZE}")
List<Article> findArticleByHot(@Param("page") int page, @Param("PAGE_SIZE") int PAGE_SIZE);
@Select("select * from article where type = #{type}")
List<Article> selectByType(@Param("type") String type);
@Select("select * from article where goods_id = #{id}")
List<Article> selectById(@Param("id") int id);
}
|
[
"34057787+Sole-Memory-ddw@users.noreply.github.com"
] |
34057787+Sole-Memory-ddw@users.noreply.github.com
|
25a77b7980aaf0163a3eeec79912e1bf08e0be51
|
0e2eed7cca32367c797938e3c8e24e5d83ba2ca8
|
/app/src/main/java/com/xkj/binaryoption/bean/HistoryDataList.java
|
356a24fd2cbed428dee7a5a92b35e962f3c7b99d
|
[] |
no_license
|
AreYReady/BinaryOption
|
fd23c098ccdf58adeb678a350335ba0d0f4fe548
|
60bd6c3b3dbe275f2a39c7fe2b3270a000991595
|
refs/heads/master
| 2021-01-19T23:52:28.954837
| 2017-05-13T03:05:26
| 2017-05-13T03:05:26
| 89,043,127
| 0
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,279
|
java
|
package com.xkj.binaryoption.bean;
import java.io.Serializable;
import java.util.List;
/**
* @author xjunda
* @date 2016-07-18
* 历史数据列表
*/
public class HistoryDataList implements Serializable, IHistoryDataList {
/**
* msg_type : 1101
* result_code : 0
* count : 2
* digits : 5
*/
private int msg_type;
private int result_code;
private int count;
private int digits;
private List<HistoryData> items;
private String symbol;
private int period;
private long cacheTime;
/**
* 历史最近一次价格
*/
private String nowPrice = "0.00000";
private int flag;
private double[] price;
public int getMsg_type() {
return msg_type;
}
public void setMsg_type(int msg_type) {
this.msg_type = msg_type;
}
public int getResult_code() {
return result_code;
}
public void setResult_code(int result_code) {
this.result_code = result_code;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getDigits() {
return digits;
}
public void setDigits(int digits) {
this.digits = digits;
}
public List<HistoryData> getItems() {
return items;
}
public void setItems(List<HistoryData> items) {
this.items = items;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public int getPeriod() {
return period;
}
public void setPeriod(int period) {
this.period = period;
}
public long getCacheTime() {
return cacheTime;
}
public void setCacheTime(long cacheTime) {
this.cacheTime = cacheTime;
}
public String getNowPrice() {
return nowPrice;
}
public void setNowPrice(String nowPrice) {
this.nowPrice = nowPrice;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public double[] getPrice() {
return price;
}
public void setPrice(double[] price) {
this.price = price;
}
}
|
[
"jimdaxu@qq.com"
] |
jimdaxu@qq.com
|
150549767eb866b342cf84673b43ec8768318c3f
|
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/21/21_73c5c105e2ff0853742c14fce731689ee8ccf11e/ImportFileStatusWidget/21_73c5c105e2ff0853742c14fce731689ee8ccf11e_ImportFileStatusWidget_s.java
|
9b01a2eb756457c2e4d59c4cfdd09629b58b4801
|
[] |
no_license
|
zhongxingyu/Seer
|
48e7e5197624d7afa94d23f849f8ea2075bcaec0
|
c11a3109fdfca9be337e509ecb2c085b60076213
|
refs/heads/master
| 2023-07-06T12:48:55.516692
| 2023-06-22T07:55:56
| 2023-06-22T07:55:56
| 259,613,157
| 6
| 2
| null | 2023-06-22T07:55:57
| 2020-04-28T11:07:49
| null |
UTF-8
|
Java
| false
| false
| 7,040
|
java
|
package eu.europeana.dashboard.client.collections;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Widget;
import eu.europeana.dashboard.client.CollectionHolder;
import eu.europeana.dashboard.client.DashboardWidget;
import eu.europeana.dashboard.client.Reply;
import eu.europeana.dashboard.client.dto.EuropeanaCollectionX;
import eu.europeana.dashboard.client.dto.ImportFileX;
/**
* Hold an import file and present the appropriate widget for doing things with it.
*
* @author Gerald de Jong, Beautiful Code BV, <geralddejong@gmail.com>
*/
public class ImportFileStatusWidget extends DashboardWidget {
private static final int STATUS_CHECK_DELAY = 1000;
private CollectionHolder holder;
private StatusCheckTimer statusCheckTimer;
private HorizontalPanel panel = new HorizontalPanel();
public ImportFileStatusWidget(World world, CollectionHolder holder) {
super(world);
this.holder = holder;
this.panel.setSpacing(6);
refreshPanel();
holder.addListener(new CollectionHolder.CollectionUpdateListener() {
public void collectionUpdated(EuropeanaCollectionX collection) {
refreshPanel();
}
});
}
public Widget createWidget() {
return panel;
}
public void refreshPanel() {
panel.clear();
if (holder.getImportFile() == null) {
panel.add(new HTML(world.messages().noImportFilePresent()));
}
else {
final ImportFileX importFile = holder.getImportFile();
panel.add(new HTML(world.messages().theFileIs(importFile.getFileName())));
switch (importFile.getState()) {
case NONEXISTENT:
panel.add(new HTML(world.messages().noImportFilePresent()));
checkTransitionFromState(ImportFileX.State.NONEXISTENT);
break;
case UPLOADING:
panel.add(new HTML(world.messages().uploading()));
checkTransitionFromState(ImportFileX.State.UPLOADING);
break;
case UPLOADED:
panel.add(new HTML(world.messages().uploaded()));
Button commenceImport = new Button(world.messages().commenceImport());
commenceImport.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent sender) {
world.service().commenceImport(importFile, holder.getCollection().getId(), true, new Reply<ImportFileX>() {
public void onSuccess(ImportFileX result) {
holder.setImportFile(result);
}
});
}
});
panel.add(commenceImport);
panel.add(new HTML(world.messages().or()));
break;
case IMPORTING:
panel.add(new HTML(world.messages().importing()));
Button cancelImport = new Button(world.messages().abortImport());
cancelImport.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent sender) {
world.service().abortImport(importFile, true, new Reply<ImportFileX>() {
public void onSuccess(ImportFileX result) {
holder.setImportFile(result);
}
});
}
});
panel.add(cancelImport);
checkTransitionFromState(ImportFileX.State.IMPORTING);
break;
case IMPORTED:
panel.add(new HTML(world.messages().imported()));
break;
case ERROR:
panel.add(new HTML(world.messages().haltedWithAnError()));
break;
default:
throw new RuntimeException("Unknown state");
}
}
}
public void waitForFile() {
checkTransitionFromState(ImportFileX.State.NONEXISTENT);
}
private void checkTransitionFromState(ImportFileX.State currentState) {
if (statusCheckTimer != null) {
if (!statusCheckTimer.checks(currentState)) {
statusCheckTimer.cancel();
statusCheckTimer = new StatusCheckTimer(currentState);
statusCheckTimer.schedule(STATUS_CHECK_DELAY);
}
}
else {
statusCheckTimer = new StatusCheckTimer(currentState);
statusCheckTimer.schedule(STATUS_CHECK_DELAY);
}
}
private class StatusCheckTimer extends Timer {
private ImportFileX.State currentState;
private StatusCheckTimer(ImportFileX.State currentState) {
this.currentState = currentState;
}
public boolean checks(ImportFileX.State currentState) {
return this.currentState == currentState;
}
public void run() {
GWT.log("checking for " + holder.getCollection().getFileName(), null);
world.service().checkImportFileStatus(holder.getCollection().getFileName(), true, new Reply<ImportFileX>() {
public void onSuccess(ImportFileX result) {
if (result != null) {
holder.setImportFile(result);
if (result.getState() == currentState) {
GWT.log("waiting for " + holder.getCollection().getName() + " from " + currentState, null);
StatusCheckTimer.this.schedule(STATUS_CHECK_DELAY);
}
else {
statusCheckTimer = null;
}
}
else if (currentState == ImportFileX.State.NONEXISTENT) {
GWT.log("waiting for " + holder.getCollection().getName() + " from " + currentState, null);
StatusCheckTimer.this.schedule(STATUS_CHECK_DELAY);
}
else {
GWT.log("no import file named " + holder.getCollection().getFileName(), null);
holder.clearImportFile();
statusCheckTimer = null;
}
}
});
}
}
}
|
[
"yuzhongxing88@gmail.com"
] |
yuzhongxing88@gmail.com
|
40fce9bc54c23e6bfcf5d06fdd4879fae6aca8a2
|
a6ee3c990da28776a6f8e27d633e0d20e373752a
|
/src/DataModel/UserImpl.java
|
898b159c13fbfeee194bda07cb64e46f37343444
|
[] |
no_license
|
fanyibo/BlackNote
|
8c569b442a4f4079050a79a0721fee23ea42c5fb
|
bef6daa4c5d4a054745de5bad3f34aa19b553487
|
refs/heads/master
| 2016-09-06T15:43:41.162049
| 2013-07-19T20:20:58
| 2013-07-19T20:20:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 521
|
java
|
package DataModel;
public class UserImpl implements User {
private int id;
private String userName, pass, email;
public UserImpl(int id, String userName, String pass, String email){
this.id = id;
this.userName = userName;
this.pass = pass;
this.email = email;
}
@Override
public int getID() {
return id;
}
@Override
public String getUserName() {
return userName;
}
@Override
public String getPass() {
return pass;
}
@Override
public String getEmail() {
return email;
}
}
|
[
"fanyibo@Yibos-MacBook-Pro.local"
] |
fanyibo@Yibos-MacBook-Pro.local
|
8737875fab6609bd1651d60b820cfa7da3baa6b5
|
e79d1c0f72612b93c57cfd41e3963fc899100814
|
/week1/LinkedList/LinkedListTest.java
|
ba78256a2974c8316a1dc26da9bdd5d7ff479ee0
|
[] |
no_license
|
dongyyyyy/2020_02_Algorithm
|
4bd5058ec84b2731c502d03d94d18e7c3094a47d
|
97ebdb491ad9b9bfb7d53f69da78a3d446ddb3cc
|
refs/heads/master
| 2023-01-20T17:04:49.800706
| 2020-11-29T02:53:17
| 2020-11-29T02:53:17
| 291,628,008
| 6
| 2
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 544
|
java
|
package LinkedList;
public class LinkedListTest {
public static void main(String args[])
{
LinkedList list = new LinkedList();
ListNode temp = new ListNode();
for(int i = 0; i <= 6 ; i++)
{
list.addLastNode(Character.toString((char)(i+65)));
}
list.showList();
temp = list.search("A"); // search methods
list.insert(temp, "D");
list.showList();
list.delete("A");
list.delete("G");
list.showList();
list.deleteLastNode();
list.deleteLastNode();
list.deleteLastNode();
list.showList();
}
}
|
[
"dongyoung0218@gmail.com"
] |
dongyoung0218@gmail.com
|
88fa20158b8def56f3090dddbea0aaef043e1da8
|
5bd81f1d0e1e8ca3e9c96810f8639de7906f56b7
|
/work-5/src/main/java/ru/otus/work5/extractor/BookResultSetExtractor.java
|
bb16fb19f3fbf54874cff8836304306f79d09c6d
|
[] |
no_license
|
mgilivanov/2019-11-otus-spring-GilivanovM
|
770c398e14de3b2ec0e439fee06883c14a787b3d
|
73b8f70a193dee85e8cd2f422e054551b5436f36
|
refs/heads/master
| 2022-09-20T07:14:13.900313
| 2020-06-01T08:37:33
| 2020-06-01T08:37:33
| 225,004,561
| 0
| 0
| null | 2022-09-08T01:09:45
| 2019-11-30T11:52:17
|
Java
|
UTF-8
|
Java
| false
| false
| 1,448
|
java
|
package ru.otus.work5.extractor;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Component;
import ru.otus.work5.domain.Author;
import ru.otus.work5.domain.Book;
import ru.otus.work5.domain.Genre;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
@Component
public class BookResultSetExtractor implements
ResultSetExtractor<Map<Long, Book>> {
@Override
public Map<Long, Book> extractData(ResultSet rs) throws SQLException,
DataAccessException {
Map<Long, Book> books = new HashMap<>();
while (rs.next()) {
long id = rs.getLong("id");
Book book = books.get(id);
if (book == null) {
book = new Book(id, rs.getString("name"));
books.put(book.getId(), book);
}
long authorId = rs.getLong("author_id");
Author author = new Author(authorId, rs.getString("author_name"));
if (!book.getAuthors().contains(author)) {
book.addAuthor(author);
}
long genreId = rs.getLong("genre_id");
Genre genre = new Genre(genreId, rs.getString("genre_name"));
if (!book.getGenres().contains(genre)) {
book.addGenre(genre);
}
}
return books;
}
}
|
[
"maratgilivanov@yandex.ru"
] |
maratgilivanov@yandex.ru
|
4c4858b32e1878c74e55a0fd8b3d9c7859a6609a
|
aa23a19ab8e6a19c4ab9e039e62d7271ed357f1f
|
/CarWorkshop/CarWorkshop_v4/src/uo/ri/ui/admin/action/UpdateMechanicAction.java
|
a1fae87b6191ba8a1fb975b4ac772ad9797b2eed
|
[] |
no_license
|
mistermboy/RI
|
409179fed877754e18f417252929d7a452169442
|
3d7c3c5a801460bbda0b5fe4e3f6a2a095810b0f
|
refs/heads/master
| 2021-03-27T13:46:32.425013
| 2018-01-25T22:52:13
| 2018-01-25T22:52:13
| 103,941,796
| 1
| 0
| null | 2020-06-16T07:58:07
| 2017-09-18T13:21:58
|
Java
|
UTF-8
|
Java
| false
| false
| 605
|
java
|
package uo.ri.ui.admin.action;
import uo.ri.common.BusinessException;
import uo.ri.conf.ServicesFactory;
import alb.util.console.Console;
import alb.util.menu.Action;
public class UpdateMechanicAction implements Action {
@Override
public void execute() throws BusinessException {
// Pedir datos
Long id = Console.readLong("Id del mecánico");
String nombre = Console.readString("Nombre");
String apellidos = Console.readString("Apellidos");
ServicesFactory.getAdminService().updateMechanic(id, nombre, apellidos);
// Mostrar resultado
Console.println("Mecánico actualizado");
}
}
|
[
"pabloyo97@hotmail.com"
] |
pabloyo97@hotmail.com
|
5d811504dc8e9c6d626a553294d167dad9059fca
|
746cc4763cb3ea38d5b71d973ae89b5254b1e4d2
|
/EmaLaeServerApplication/test/dao/FormationDaoTest.java
|
4db579b3fb1dcddf0c65c2c86fc6fc9e0a508b5a
|
[] |
no_license
|
AndreMiras/ema-lae
|
2b301b50e267ceaec4d630a1896dd2fe42a15e8c
|
c754bd3b1b328a583dde79b89f69d35a84f2bb3b
|
refs/heads/master
| 2021-01-23T15:54:59.102398
| 2011-12-21T07:29:59
| 2011-12-21T07:29:59
| 33,007,911
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 15,227
|
java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import database.entity.CourseSession;
import database.entity.CourseSession.SessionType;
import database.entity.Formation;
import database.entity.Promotion;
import database.util.HibernateUtil;
import database.util.InitDatabase;
import exceptions.DaoException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.List;
/**
*
* @author logar
*/
public class FormationDaoTest {
public FormationDaoTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
HibernateUtil.getSessionFactoryForTests();
InitDatabase initDatabase = new InitDatabase();
initDatabase.dropFormations();
initDatabase.createFormations();
}
@AfterClass
public static void tearDownClass() throws Exception {
HibernateUtil.getSessionFactoryForTests().close();
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testCreate() {
System.out.println("create");
Formation obj = new Formation();
// the object shouldn't have an id, until it gets one from the DAO
assertNull(obj.getFormationId());
FormationDao instance = new FormationDao();
Integer result = instance.create(obj);
// the object should now have an id given from the DAO
assertNotNull(result);
}
/**
* Test of read method, of class GroupDao.
*/
@Test
public void testRead() {
System.out.println("read");
Formation formation = new Formation("formation4read");
FormationDao instance = new FormationDao();
Integer formationID = instance.create(formation);
Formation result = instance.read(formationID);
assertEquals("formation4read", result.getName());
}
/**
* Test of update method, of class GroupDao.
*/
@Test
public void testUpdate() {
System.out.println("update");
Formation newFormation = new Formation("formation4Update");
FormationDao instance = new FormationDao();
Integer newFormationID = instance.create(newFormation);
// re-read the saved newUser from the database
newFormation = instance.read(newFormationID);
// update it locally
newFormation.setName("formation4UpdateNew");
// re-hit the database
instance.update(newFormation);
// re-read the updated newUser from the database
newFormation = instance.read(newFormationID);
assertEquals("formation4UpdateNew", newFormation.getName());
}
/**
* Test of delete method, of class GroupDao.
*/
@Test
public void testDelete() {
System.out.println("delete");
Integer nbToBeDeleted;
FormationDao instance = new FormationDao();
List<Formation> allFormationsBefore = instance.all();
Formation formationToDelete = allFormationsBefore.get(0);
// cascade deletion
nbToBeDeleted =
formationToDelete.getChildrenFormations().size() + 1;
// asserts that the object still exists
assertNotNull(instance.read(formationToDelete.getFormationId()));
// deletes the first record
instance.delete(formationToDelete);
List<Formation> allFormationsAfter = instance.all();
// not record should now be found
assertNull(instance.read(formationToDelete.getFormationId()));
// only one record was deleted
assertTrue(allFormationsBefore.size() - nbToBeDeleted ==
allFormationsAfter.size());
}
//@Test(expected = HibernateException.class)
public void testAddFormationShouldFail() {
System.out.println("create");
Formation f1 = new Formation("parent formation");
FormationDao instance = new FormationDao();
Integer result = instance.create(f1);
Formation f2 = new Formation("child formation");
f2.setParentFormation(f1);
assertFalse(f1.getChildrenFormations().contains(f2));
f1.addFormation(f2);
instance.update(f1);
}
@Test
public void testAddFormation() {
System.out.println("create");
FormationDao formationDao = new FormationDao();
// Instantiate the objects
Formation f1 = new Formation("parent formation");
Formation f2 = new Formation("child formation");
// No parent and not children by default
assertTrue(f1.getChildrenFormations().isEmpty());
assertTrue(f2.getChildrenFormations().isEmpty());
assertTrue(f1.getParentFormation() == null);
assertTrue(f2.getParentFormation() == null);
// Creating parent/children relation
f2.setParentFormation(f1);
assertTrue(f1.getChildrenFormations().size() == 1);
assertTrue(f2.getChildrenFormations().isEmpty());
assertTrue(f1.getParentFormation() == null);
assertTrue(f2.getParentFormation() == f1);
// Insertion of the parent formation into the database
Integer parentPk = formationDao.create(f1);
// Check that the child formation does appear in the parent's children
assertTrue(f1.containsChild(f2));
// Check it's still true after a read from database
f1 = formationDao.read(parentPk);
assertTrue(f1.getChildrenFormations().size() == 1);
assertTrue(f1.containsChild(f2));
}
@Test // TODO: finish this up
public void testSetChildrenFormations() {
System.out.println("create");
FormationDao formationDao = new FormationDao();
// Instantiate the objects
Formation pf1 = new Formation("ParentFormation1");
Formation cf1 = new Formation("ChildFormation1");
Formation cf2 = new Formation("ChildFormation2");
Formation cf3 = new Formation("ChildFormation3");
// No parent and not children by default
assertTrue(pf1.getChildrenFormations().isEmpty());
assertTrue(cf1.getChildrenFormations().isEmpty());
assertTrue(pf1.getParentFormation() == null);
assertTrue(cf1.getParentFormation() == null);
// Creating parent/children relation
HashSet<Formation> formationSet = new HashSet<Formation>();
formationSet.add(cf1);
formationSet.add(cf2);
formationSet.add(cf3);
pf1.setChildrenFormations(formationSet);
assertTrue(pf1.getChildrenFormations().size() == 3);
assertTrue(cf2.getChildrenFormations().isEmpty());
assertTrue(cf1.getParentFormation() == pf1);
assertTrue(cf2.getParentFormation() == pf1);
assertTrue(cf3.getParentFormation() == pf1);
// Check that the child formation does appear in the parent's children
assertTrue(pf1.getChildrenFormations().contains(cf1));
assertTrue(pf1.getChildrenFormations().contains(cf2));
assertTrue(pf1.getChildrenFormations().contains(cf3));
// Insertion of the parent formation into the database
Integer parentPk = formationDao.create(pf1);
// Check it's still true after a read from database
pf1 = formationDao.read(parentPk);
assertTrue(pf1.getChildrenFormations().size() == 3);
assertTrue(pf1.containsChild(cf1));
assertTrue(pf1.containsChild(cf2));
assertTrue(pf1.containsChild(cf3));
/*
* Now lets try to set a formation HashSet a second time
* to see if the previous one gets overridden.
* So we set cf1 and cf3 but not cf2
*/
formationSet.clear();
formationSet.add(cf1);
formationSet.add(cf3);
pf1.setChildrenFormations(formationSet);
assertTrue(pf1.getChildrenFormations().size() == 2);
assertTrue(cf1.getParentFormation() == pf1);
// assertTrue(cf2.getParentFormation() == null);
assertTrue(cf3.getParentFormation() == pf1);
formationDao.update(pf1); // updating the database
// Check it's still true after a read from database
pf1 = formationDao.read(parentPk);
assertTrue(pf1.getChildrenFormations().size() == 2);
assertTrue(pf1.containsChild(cf1));
assertFalse(pf1.containsChild(cf2));
assertTrue(pf1.containsChild(cf3));
}
@Test
public void testSetPromotion()
{
System.out.println("set Promotion");
Formation formation = new Formation("formation4setPromotion");
FormationDao fInstance = new FormationDao();
Promotion promotion = new Promotion("promotion4setPromotion");
Integer formationID = fInstance.create(formation);
formation = fInstance.read(formationID);
formation.setPromotion(promotion);
fInstance.update(formation);
formation = fInstance.read(formationID);
assertTrue(formation.getPromotion().getName().equals(promotion.getName()));
/*
* now let's try to set a promotion again after it was already
* persisted in the database
*/
promotion = null;
formation = new Formation("anotherFormation2");
PromotionDao promotionDao = new PromotionDao();
HashMap<String, String> querySet = new HashMap<String, String>();
querySet.put("name", "promotion4setPromotion");
try
{
promotion = promotionDao.get(querySet);
} catch (DaoException ex)
{
Logger.getLogger(FormationDaoTest.class.getName()).log(
Level.SEVERE, null, ex);
}
formation.setPromotion(promotion);
formationID = fInstance.create(formation);
formation = fInstance.read(formationID);
assertTrue(formation.getPromotion().getName().equals(
promotion.getName()));
}
@Test
public void testAddSession() {
System.out.println("add session");
FormationDao formationDao = new FormationDao();
// Instantiate the objects
Formation f1 = new Formation("parent formation");
CourseSession cs1 = new CourseSession(SessionType.Course);
// No parent and not children by default
assertTrue(f1.getSessions().isEmpty());
assertTrue(cs1.getFormation() == null);
// Creating parent/children relation
cs1.setFormation(f1);
assertTrue(f1.getSessions().size() == 1);
assertTrue(cs1.getFormation() == f1);
// Insertion of the parent formation into the database
Integer formationPk = formationDao.create(f1);
// Check that the child formation does appear in the parent's children
assertTrue(f1.containsSession(cs1));
// Check it's still true after a read from database
f1 = formationDao.read(formationPk);
assertTrue(f1.getSessions().size() == 1);
assertTrue(f1.containsSession(cs1));
}
@Test // TODO: finish this up
public void testSetSessions() {
System.out.println("create");
FormationDao formationDao = new FormationDao();
// Instantiate the objects
Formation f1 = new Formation("ParentFormation1");
CourseSession cs1 = new CourseSession(SessionType.Course);
CourseSession cs2 = new CourseSession(SessionType.Practical);
CourseSession cs3 = new CourseSession(SessionType.Test);
// Nothing should be set by default
assertTrue(f1.getSessions().isEmpty());
assertTrue(cs1.getFormation() == null);
// Creating relation
HashSet<CourseSession> sessionsSet = new HashSet<CourseSession>();
sessionsSet.add(cs1);
sessionsSet.add(cs2);
sessionsSet.add(cs3);
f1.setSessions(sessionsSet);
assertTrue(f1.getSessions().size() == 3);
assertTrue(cs1.getFormation() == f1);
assertTrue(cs2.getFormation() == f1);
assertTrue(cs3.getFormation() == f1);
// Check that the child formation does appear in the parent's children
assertTrue(f1.getSessions().contains(cs1));
assertTrue(f1.getSessions().contains(cs2));
assertTrue(f1.getSessions().contains(cs3));
// Insertion of the parent formation into the database
Integer formationPk = formationDao.create(f1);
// Check it's still true after a read from database
f1 = formationDao.read(formationPk);
assertTrue(f1.getSessions().size() == 3);
assertTrue(f1.containsSession(cs1));
assertTrue(f1.containsSession(cs2));
assertTrue(f1.containsSession(cs3));
/*
* Now lets try to set a formation HashSet a second time
* to see if the previous one gets overridden.
* So we set cf1 and cf3 but not cf2
*/
sessionsSet.clear();
sessionsSet.add(cs1);
sessionsSet.add(cs3);
f1.setSessions(sessionsSet);
assertTrue(f1.getSessions().size() == 2);
assertTrue(cs1.getFormation() == f1);
// assertTrue(cf2.getParentFormation() == null);
assertTrue(cs3.getFormation() == f1);
formationDao.update(f1); // updating the database
// Check it's still true after a read from database
f1 = formationDao.read(formationPk);
assertTrue(f1.getSessions().size() == 2);
assertTrue(f1.containsSession(cs1));
assertFalse(f1.containsSession(cs2));
assertTrue(f1.containsSession(cs3));
}
/**
* Test of find method, of class GroupDao.
*/
//TODO @Test
// public void testFind() {
// System.out.println("find");
// HashMap<String, String> querySet = null;
// GroupDao instance = new GroupDao();
// List expResult = null;
// List result = instance.find(querySet);
// assertEquals(expResult, result);
// // TODO review the generated test code and remove the default call to fail.
// fail("The test case is a prototype.");
// }
/**
* Test of get method, of class GroupDao.
*/
//TODO @Test
// public void testGet() {
// System.out.println("get");
// HashMap<String, String> querySet = null;
// GroupDao instance = new GroupDao();
// Group expResult = null;
// Group result = instance.get(querySet);
// assertEquals(expResult, result);
// // TODO review the generated test code and remove the default call to fail.
// fail("The test case is a prototype.");
// }
/**
* Test of all method, of class GroupDao.
*/
//TODO @Test
// public void testAll() {
// System.out.println("all");
// GroupDao instance = new GroupDao();
// List expResult = null;
// List result = instance.all();
// assertEquals(expResult, result);
// // TODO review the generated test code and remove the default call to fail.
// fail("The test case is a prototype.");
// }
}
|
[
"andre.miras@gmail.com"
] |
andre.miras@gmail.com
|
85b906256acade0045176a84b917ec8434966252
|
84d5d2c9f2d470de91d13e709e896551d312de2d
|
/src/main/java/com/example/vyrwu/agillicDemoMvn/Account/AccountController.java
|
33370cd3cc8f3ff50ec614e7ba0ca211154879bd
|
[] |
no_license
|
vyrwu/spring-mvc-demo
|
5bf17a3abb4fb90905bc379ea5d92b739980b3bb
|
e20869c6edb6ed9f097961f3a265977a608b2fd9
|
refs/heads/master
| 2020-06-03T04:18:15.597291
| 2019-06-11T19:17:40
| 2019-06-11T19:17:40
| 191,435,235
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 4,021
|
java
|
package com.example.vyrwu.agillicDemoMvn.Account;
import com.example.vyrwu.agillicDemoMvn.Bookmark.BookmarkService;
import com.example.vyrwu.agillicDemoMvn.JsonRequests.JsonIDRequest;
import org.apache.coyote.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMessage;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.util.UriComponentsBuilder;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.security.ProviderException;
import java.util.Arrays;
import java.util.Collection;
import java.util.function.Supplier;
@RestController
@RequestMapping("/users")
class AccountController {
@Autowired
AccountService accountService;
@Autowired
BookmarkService bookmarkService;
// --- GET method for displaying complete account list /users
@RequestMapping(method = RequestMethod.GET, produces = "application/json")
ResponseEntity getAll(HttpServletRequest request) {
Collection<Account> allAccounts = accountService.getAll();
HttpHeaders customHeader = new HttpHeaders();
customHeader.add("Methods", "GET PUT POST DELETE");
customHeader.add("DELETE", "in:application/json;format:{ids:[long args]}");
return new ResponseEntity<>(allAccounts, customHeader, HttpStatus.OK);
}
// --- OPTIONS for getting http method definitions
@RequestMapping(method = RequestMethod.OPTIONS, produces = "text/plain")
ResponseEntity help(HttpServletRequest request) {
HttpHeaders customHeader = new HttpHeaders();
customHeader.add("Allows", "GET HEAD PUT POST DELETE OPTIONS");
return new ResponseEntity<>("DELETE\ninput:application/json\nstructure:{ids:[long args]}", customHeader, HttpStatus.OK);
}
// --- POST for adding accounts /users
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
ResponseEntity add(@RequestBody Account account) {
accountService.save(new Account(account.getUsername(), account.getPassword()));
Account createdAccount = accountService.get(account.getUsername());
return new ResponseEntity<>(createdAccount, HttpStatus.CREATED);
}
// --- DELETE for deleting accounts (also deletes bookmarks of removed account)
@RequestMapping(method = RequestMethod.DELETE, consumes = "application/json")
ResponseEntity remove(@RequestBody JsonIDRequest idList) {
Arrays.stream(idList.ids).forEach(id -> {
if (accountService.contains(id)) {
accountService.get(id).getBookmarks().forEach(
bookmark -> bookmarkService.remove(bookmark.getId()));
accountService.remove(id);
} else {
System.err.println("Missing ID: " + id);
}
});
return ResponseEntity.noContent().build();
}
// --- PUT for updating account credentials /users
// If user exists, update credentials. Else, create new user.
@RequestMapping(method = RequestMethod.PUT, consumes = "application/json")
ResponseEntity put(@RequestBody Account account) {
if (!accountService.contains(account.getUsername())) {
return add(account);
}
Account targetAccount = accountService.get(account.getUsername());
targetAccount.setUsername(account.getUsername());
targetAccount.setPassword(account.getPassword());
accountService.save(targetAccount);
return ResponseEntity.ok().build();
}
@RequestMapping(path = "exception", method = RequestMethod.GET)
ResponseEntity ex() throws HttpClientErrorException {
throw new ProviderException();
}
}
|
[
"aleksander.nowak@agillic.com"
] |
aleksander.nowak@agillic.com
|
e8d45f7bc7b39302c38a2c3197fdbc509b48efff
|
5080532430b15216ddb73c303392323b40651226
|
/1.JavaSyntax/src/com/javarush/task/task01/task0132/Solution.java
|
5282c3f1102f852ae161dad4ab48de80f5669bdd
|
[] |
no_license
|
cmmttd/JR
|
96f2b79886ee78cdcb19dc3a8bd607a2cbe6efd5
|
be450e5f06faa78b0eb50c83f93a0641f5ee45f7
|
refs/heads/master
| 2020-06-11T22:07:58.664569
| 2020-05-14T19:02:59
| 2020-05-14T19:02:59
| 194,095,316
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 484
|
java
|
package com.javarush.task.task01.task0132;
/*
Сумма цифр трехзначного числа
*/
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
//напишите тут ваш код
int hund = (number / 100);
int dec = (number / 10) % 10;
int rem = (number % 10);
return hund + dec + rem;
}
}
|
[
"forledwatch@gmail.com"
] |
forledwatch@gmail.com
|
e0376b65b6e3f2036abf6ccee03c689b22928c4e
|
583ae786b5803fc256a586922ee132b5fd801cb3
|
/talfDreamer/src/main/java/com/helloworld/dao/WishListDAO.java
|
79f7237abd0bc896d832dd4ce19b60c4321699fa
|
[] |
no_license
|
V-Jayesh-R/MyProject
|
9c1d9ed8c744a8f376e13f14851510dcd9801948
|
b6741b7b4da414bbaf78076562e1a56083eefc84
|
refs/heads/master
| 2021-01-19T22:40:48.799568
| 2017-05-18T10:10:39
| 2017-05-18T10:10:39
| 88,841,655
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 264
|
java
|
package com.helloworld.dao;
import com.helloworld.model.WishListItems;
public interface WishListDAO {
public void addToWishList(WishListItems wishListItems);
public String displayWishList(int userId);
public void deleteFromWishList(int wishListItemId);
}
|
[
"jvkillercool@gmail.com"
] |
jvkillercool@gmail.com
|
8f906fdf10cccce0d9de67477ef5bfeff35b525d
|
e2b11aff7abcc16f84d3f51cf45c984ef917d409
|
/src/main/java/cubex2/cs3/registry/ShapelessRecipeRegistry.java
|
c943c2283ec936effb7f004d0f2cb7c4a6681667
|
[] |
no_license
|
Lollipop-Studio/CustomStuff3
|
45221ecafbb0f3bd20f3b7cf0499e0f6e434e172
|
0cdba13acf5bdace1e2a582f75797c65f31aeb6a
|
refs/heads/1710
| 2023-03-26T02:32:17.085531
| 2021-03-20T03:29:13
| 2021-03-20T03:29:13
| 342,443,904
| 0
| 0
| null | 2021-03-20T03:29:13
| 2021-02-26T02:49:24
| null |
UTF-8
|
Java
| false
| false
| 842
|
java
|
package cubex2.cs3.registry;
import cubex2.cs3.common.BaseContentPack;
import cubex2.cs3.common.ShapelessRecipe;
import cubex2.cs3.ingame.gui.Window;
import cubex2.cs3.ingame.gui.WindowShapelessRecipes;
import cubex2.cs3.lib.Strings;
public class ShapelessRecipeRegistry extends ContentRegistry<ShapelessRecipe>
{
public ShapelessRecipeRegistry(BaseContentPack pack)
{
super(pack);
}
@Override
public ShapelessRecipe newDataInstance()
{
return new ShapelessRecipe(pack);
}
@Override
public Window createListWindow()
{
return new WindowShapelessRecipes(pack);
}
@Override
public String getNameForEditPack()
{
return "Shapeless Recipes";
}
@Override
public String getName()
{
return Strings.REGISTRY_SHAPELESS_RECIPE;
}
}
|
[
"beanflame@163.com"
] |
beanflame@163.com
|
33017d72e3c0c2f16b509328b246ee9730d41391
|
6d2dd262c47e7a8e0854d5e3273eb2a03d2638fc
|
/gmall-cart/src/main/java/com/atguigu/gmall/cart/config/MvcConfig.java
|
509d173919e0e2756ddc39b0cc57605779cacf76
|
[
"Apache-2.0"
] |
permissive
|
VeronicaYyq/gmall-vero
|
66a30f3a223a3f338e644d29a628cb5b2f5a5551
|
efec9de368ade4f755075db0e063b9396fff24ee
|
refs/heads/master
| 2022-12-23T08:34:24.703137
| 2019-10-19T13:38:30
| 2019-10-19T13:38:30
| 209,934,029
| 0
| 0
|
Apache-2.0
| 2022-12-10T05:23:37
| 2019-09-21T06:05:48
|
JavaScript
|
UTF-8
|
Java
| false
| false
| 670
|
java
|
package com.atguigu.gmall.cart.config;
import com.atguigu.gmall.cart.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
}
}
|
[
"Veronica_Yyq@126.com"
] |
Veronica_Yyq@126.com
|
4e0c9d9955fcbfbec080c56e52ed07140b39b5fd
|
e60618182ca774d3cfc11ed88125aad0925693ab
|
/Go Cloud Source Code/Netbeans 6.1 - Virtual Machine/CloudComputingServer/src/org/cit/CloudComputing/T_Editor.java
|
5efd0e29387d0c8a0b6af09f3d36cf6db34c5b0f
|
[] |
no_license
|
gokcse/Go-Cloud
|
55e6ab83629e9339d5a22ff24e209d2ecc03deab
|
ff5e05c7fc11e177fd0970e7635d4c9b1eaf6056
|
refs/heads/master
| 2020-05-06T15:49:29.551449
| 2012-02-25T19:47:03
| 2012-02-25T19:47:03
| 3,546,735
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 24,331
|
java
|
package org.cit.CloudComputing;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Vector;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
//////////////////////////////////////////////////////////////////////////////////
class Frame_class extends Frame
implements ActionListener, ItemListener, CloudComputable { // open brace of Frame_class
MenuItem item1, item2, item3, item4, item5, item6;
MenuItem item7, item8, item9;
MenuItem item10;
MenuItem fontitem1, fontitem2, fontitem3, fontitem4;
MenuItem sizeitem1, sizeitem2, sizeitem3, sizeitem4, sizeitem5, sizeitem6, sizeitem7,
sizeitem8, sizeitem9, sizeitem10, sizeitem11, sizeitem12;
MenuItem styleitem1, styleitem2, styleitem3;
MenuItem bkcitem[] = new MenuItem[13];
MenuItem frcitem[] = new MenuItem[13];
String filename = "", directory = "", findstr = "", fname = "", dir = "";
JTextArea txtArea;
JMenuItem Open;
int fontNumeric = 12;
TextArea tx1 = new TextArea();
String fileName = null;
String copystring;
int fontStyle = Font.PLAIN;
String fontName = "Courier";
FileDialog openDialog;
FileDialog saveDialog;
private ErrorDialog errorDialog = null;
private TEDialog teDialog = null;
String s;
static String st = "";
String heading = " Save File ";
static int window_no = 0;
static int window_counter = 0;
///////////////////////////////////////////////////////////////////////////////
Frame_class(String title) {//start of Frame_class constructor
super(title);
MenuBar mbar = new MenuBar();
setMenuBar(mbar);
menu(mbar);
AddChoice(mbar);
bkfrcolor(mbar);
textarea(this);
menu1(mbar);
//create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this);
//register it to receive those event
addWindowListener(adapter);
//addKeyListener(this);
//requestFocus();
this.AddDialog();
tx1.setBackground(Color.white);
tx1.setForeground(Color.black);
//this.setVisible(true);
}//end of Frame_class constructor
/////////////////////////////////////////////////////////////////////////////////
public String[] listOfServices() {
String[] services = {"Open", "Save", "Close" };
return services;
}
public String getInfo() {
return "This is a cool text editor.";
}
public String[] listOfAvailableComponents() {
String[] components = {"textarea"};
return components;
}
public String openFileService(String filename){
try{
StringBuffer ret=new StringBuffer("");
String cur_line=new String();
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
while((cur_line=br.readLine()) != null){
ret.append(ret + "\n" + cur_line);
}
return ret.toString();
}catch(Exception e){
e.printStackTrace();
return "";
}
}
public void menu1(MenuBar mbar) {//start of menu1()
Menu help = new Menu(" Help ");
help.add(item10 = new MenuItem("About.."));
mbar.add(help);
item10.addActionListener(this);
}
public void menu(MenuBar mbar) {//start of menu()
Menu file = new Menu(" File ");
file.add(item1 = new MenuItem("New"));
file.add(item2 = new MenuItem("Open"));
file.add(item3 = new MenuItem("Close"));
file.add(item4 = new MenuItem("Save"));
file.add(item5 = new MenuItem("Save As"));
file.addSeparator();
file.add(item6 = new MenuItem("Exit"));
mbar.add(file);
Menu edit = new Menu(" Edit ");
edit.add(item7 = new MenuItem("Cut"));
edit.add(item8 = new MenuItem("Copy"));
edit.add(item9 = new MenuItem("Paste"));
mbar.add(edit);
item1.addActionListener(this);
item2.addActionListener(this);
item3.addActionListener(this);
item4.addActionListener(this);
item5.addActionListener(this);
item6.addActionListener(this);
item7.addActionListener(this);
item8.addActionListener(this);
item9.addActionListener(this);
}//end of menu()
//////////////////////////////////////////////////////////////////////////////
private void AddChoice(MenuBar mbar) {
Menu font = new Menu(" Font ");
font.add(fontitem1 = new MenuItem("Courier"));
font.addSeparator();
font.add(fontitem2 = new MenuItem("Arial"));
font.addSeparator();
font.add(fontitem4 = new MenuItem("TimesRoman"));
mbar.add(font);
Menu size = new Menu(" Size ");
size.add(sizeitem1 = new MenuItem("8"));
size.addSeparator();
size.add(sizeitem2 = new MenuItem("10"));
size.addSeparator();
size.add(sizeitem3 = new MenuItem("12"));
size.addSeparator();
size.add(sizeitem4 = new MenuItem("14"));
size.addSeparator();
size.add(sizeitem5 = new MenuItem("16"));
size.addSeparator();
size.add(sizeitem6 = new MenuItem("18"));
size.addSeparator();
size.add(sizeitem7 = new MenuItem("20"));
size.addSeparator();
size.add(sizeitem8 = new MenuItem("22"));
size.addSeparator();
size.add(sizeitem9 = new MenuItem("24"));
size.addSeparator();
size.add(sizeitem10 = new MenuItem("26"));
size.addSeparator();
size.add(sizeitem11 = new MenuItem("28"));
size.addSeparator();
size.add(sizeitem12 = new MenuItem("30"));
mbar.add(size);
Menu fontstyle = new Menu(" Font Style ");
fontstyle.add(styleitem1 = new MenuItem("Bold"));
fontstyle.addSeparator();
fontstyle.add(styleitem2 = new MenuItem("Plain"));
fontstyle.addSeparator();
fontstyle.add(styleitem3 = new MenuItem("Italic"));
mbar.add(fontstyle);
fontitem1.addActionListener(this);
fontitem2.addActionListener(this);
//fontitem3.addActionListener(this);
fontitem4.addActionListener(this);
sizeitem1.addActionListener(this);
sizeitem2.addActionListener(this);
sizeitem3.addActionListener(this);
sizeitem4.addActionListener(this);
sizeitem5.addActionListener(this);
sizeitem6.addActionListener(this);
sizeitem7.addActionListener(this);
sizeitem8.addActionListener(this);
sizeitem9.addActionListener(this);
sizeitem10.addActionListener(this);
sizeitem11.addActionListener(this);
sizeitem12.addActionListener(this);
styleitem1.addActionListener(this);
styleitem2.addActionListener(this);
styleitem3.addActionListener(this);
}
private void bkfrcolor(MenuBar mbar) {
Menu bkcolor = new Menu(" BackGround Color ");
Menu frcolor = new Menu(" Text Color ");
String colname[] = {"Red", "Blue", "Green", "Cyan", "Black", "Dark Gray",
"Gray", "Light Gray", "Magenta", "Orange", "Pink", "White", "Yellow"};
String frcolname[] = {" Red", " Blue", " Green", " Cyan", " Black", " Dark Gray",
" Gray", " Light Gray", " Magenta", " Orange", " Pink", " White", " Yellow"};
for (int i = 0; i <= 12; i++) {
bkcolor.add(bkcitem[i] = new MenuItem(colname[i]));
bkcitem[i].addActionListener(this);
frcolor.add(frcitem[i] = new MenuItem(frcolname[i]));
frcitem[i].addActionListener(this);
}
mbar.add(bkcolor);
mbar.add(frcolor);
}
public void textarea(Frame_class fc1) {
tx1.setEditable(true);
fc1.add(tx1);
}
/////////////////////////////////////////////////////////////////////////////
public void actionPerformed(ActionEvent ae) {
String args = (String) ae.getActionCommand();
if (args.equals("New")) {
StartNewWindow();
} else if (args.equals("Open")) {
heading = " Open File ";
openFile();
} else if (args.equals("Save")) {
heading = " Save File ";
saveOpenedFile();
} else if (args.equals("Close")) {
closedFile();
} else if (args.equals("Save As")) {
heading = " Save File As ";
saveAsFile(this);
} else if (args.equals("Exit")) {
System.exit(0);
} else if (args.equals("Cut")) {
cut();
} else if (args.equals("Copy")) {
copy();
} else if (args.equals("Paste")) {
paste();
} else if (args.equals("Courier")) {
fontName = "Courier";
textfont();
} else if (args.equals("Arial")) {
fontName = "Arial";
textfont();
} else if (args.equals("TimesRoman")) {
fontName = "TimesRoman";
textfont();
} else if (args.equals("8")) {
fontNumeric = 8;
textfont();
} else if (args.equals("8")) {
fontNumeric = 8;
textfont();
} else if (args.equals("8")) {
fontNumeric = 8;
textfont();
} else if (args.equals("10")) {
fontNumeric = 10;
textfont();
} else if (args.equals("12")) {
fontNumeric = 12;
textfont();
} else if (args.equals("14")) {
fontNumeric = 14;
textfont();
} else if (args.equals("16")) {
fontNumeric = 16;
textfont();
} else if (args.equals("18")) {
fontNumeric = 18;
textfont();
} else if (args.equals("20")) {
fontNumeric = 20;
textfont();
} else if (args.equals("22")) {
fontNumeric = 22;
textfont();
} else if (args.equals("24")) {
fontNumeric = 24;
textfont();
} else if (args.equals("26")) {
fontNumeric = 26;
textfont();
} else if (args.equals("28")) {
fontNumeric = 28;
textfont();
} else if (args.equals("30")) {
fontNumeric = 30;
textfont();
} else if (args.equals("Bold")) {
fontStyle = Font.BOLD;
textfont();
} else if (args.equals("Plain")) {
fontStyle = Font.PLAIN;
textfont();
} else if (args.equals("Italic")) {
fontStyle = Font.ITALIC;
textfont();
} else if (args.equals("Red")) {
tx1.setBackground(Color.red);
} else if (args.equals("Blue")) {
tx1.setBackground(Color.blue);
} else if (args.equals("Green")) {
tx1.setBackground(Color.green);
} else if (args.equals("Cyan")) {
tx1.setBackground(Color.cyan);
} else if (args.equals("Black")) {
tx1.setBackground(Color.black);
} else if (args.equals("Dark Gray")) {
tx1.setBackground(Color.darkGray);
} else if (args.equals("Gray")) {
tx1.setBackground(Color.gray);
} else if (args.equals("Light Gray")) {
tx1.setBackground(Color.lightGray);
} else if (args.equals("Magenta")) {
tx1.setBackground(Color.magenta);
} else if (args.equals("Orange")) {
tx1.setBackground(Color.orange);
} else if (args.equals("Pink")) {
tx1.setBackground(Color.pink);
} else if (args.equals("White")) {
tx1.setBackground(Color.white);
} else if (args.equals("Yellow")) {
tx1.setBackground(Color.yellow);
} else if (args.equals(" Red")) {
tx1.setForeground(Color.red);
} else if (args.equals(" Blue")) {
tx1.setForeground(Color.blue);
} else if (args.equals(" Green")) {
tx1.setForeground(Color.green);
} else if (args.equals(" Cyan")) {
tx1.setForeground(Color.cyan);
} else if (args.equals(" Black")) {
tx1.setForeground(Color.black);
} else if (args.equals(" Dark Gray")) {
tx1.setForeground(Color.darkGray);
} else if (args.equals(" Gray")) {
tx1.setForeground(Color.gray);
} else if (args.equals(" Light Gray")) {
tx1.setForeground(Color.lightGray);
} else if (args.equals(" Magenta")) {
tx1.setForeground(Color.magenta);
} else if (args.equals(" Orange")) {
tx1.setForeground(Color.orange);
} else if (args.equals(" Pink")) {
tx1.setForeground(Color.pink);
} else if (args.equals(" White")) {
tx1.setForeground(Color.white);
} else if (args.equals(" Yellow")) {
tx1.setForeground(Color.yellow);
} else if (args.equals("About..")) {
showTEDialog("I, Rajagopal Neelakantan, working as an Application Developer in IBM.\n" + "This Text Editor was developed in Java as a part of Mini Project in System Software. \n" + "To know more about me \n\n" + "Mail me at rajneela@in.ibm.com\n\n" + "Thanks for using this product.\n" + "\tRajagopal Neelakantan");
}
}
// }
private void textfont() {
tx1.setFont(new Font(fontName, fontStyle, fontNumeric));
}
public void itemStateChanged(ItemEvent ie) {
}
private void StartNewWindow() {
++window_counter;
++window_no;
st = Integer.toString(window_no);
Frame_class f = new Frame_class("Text Editor 1.0 By Rajagopal Neelakantan : New Window " + st);
f.setSize(700, 600);
}
private void newWindow() {
fileName = null;
tx1.setText("");
tx1.requestFocus();
}
private boolean lentest() {
s = tx1.getText();
int len = s.length();
if (len > 0) {
return (true);
} else {
return (false);
}
}
private void closedFile() {
if (lentest()) {
saveOpenedFile();
newWindow();
String ar;
if (window_no >= 1) {
ar = "New Window " + st + " : ";
} else {
ar = "";
}
this.setTitle("Text Editor 1.0 By Rajagopal Neelakantan : " + ar + "*.*");
} else {
newWindow();
}
}
/* public void keyPressed(KeyEvent ke){
int key=ke.getKeyCode();
switch(key){
case KeyEvent.VK_F1:openFile();break;
}
}*/
////////////////////////////////////////////////////////////////////////////////
// public void keyReleased(KeyEvent ke){}
// public void keyTyped(KeyEvent ke){}
// The Dialog boxes for openinig and saving file
private void AddDialog() {
openDialog = new FileDialog(this, "Open File", FileDialog.LOAD);
saveDialog = new FileDialog(this, "Save File", FileDialog.SAVE);
}
//cuts selected textand places it on the buffer
public void cut() {
copystring = tx1.getSelectedText();
tx1.replaceText("", tx1.getSelectionStart(), tx1.getSelectionEnd());
tx1.requestFocus();
}
//copies selected text to buffer
public void copy() {
copystring = tx1.getSelectedText();
tx1.requestFocus();
}
//paste text from buffer to the screen
public void paste() {
if (copystring.length() > 0) {
tx1.insertText(copystring, tx1.getSelectionStart());
}
tx1.requestFocus();
}
@SuppressWarnings("deprecation")
private void openFile() {
try {
FileDialog f = new FileDialog(this, "OPEN", FileDialog.LOAD);
f.show();
fname = f.getFile();
dir = f.getDirectory();
if (fname == null || dir == null) {
} else {
filename = fname;
directory = dir;
File fi = new File(directory, filename);
FileInputStream fs = new FileInputStream(fi);
byte b[] = new byte[fs.available()];
fs.read(b);
txtArea.setText(new String(b));
txtArea.append("");
setTitle(filename + " - NOTEPAD");
txtArea.setCaretPosition(0);
}
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "File is not found.Please verify the file name", "OPEN", JOptionPane.WARNING_MESSAGE);
Open.doClick();
}
// String filename;
//
// openDialog.setVisible(true);
//
// filename=openDialog.getFile();
// if(filename!=null){
// filename=check(filename);
// if(read(filename))
// {
// fileName=filename;String ar;
// if(window_no>=1){ar="New Window "+st+" : ";}else ar="";
// this.setTitle("Text Editor 1.0 By Rajagopal Neelakantan : "+ar+fileName);
// }
// }
// tx1.requestFocus();
}
private boolean read(String filename) {
String line;
FileInputStream in = null;
DataInputStream dataIn = null;
BufferedInputStream bis = null;
StringBuffer buffer = new StringBuffer();
try {
in = new FileInputStream(filename);
bis = new BufferedInputStream(in);
dataIn = new DataInputStream(bis);
} catch (Throwable e) {
showErrorDialog("Can't open\"" + filename + "\"");
return (false);
}
try {
while ((line = dataIn.readLine()) != null) {
buffer.append(line + "\n");
}
in.close();
tx1.setText(buffer.toString());
} catch (IOException e) {
showErrorDialog("Can't read \"" + filename + "\"");
return (false);
}
return (true);
}
private String check(String filename) {
if (filename.endsWith(".*.*")) {
filename = filename.substring(0, filename.length() - 4);
}
return (filename);
}
//method saves a file you opened previously
//method produces error if you did not open a file previously
public void saveOpenedFile() {
if (!lentest()) {
showErrorDialog("There is no Text to Save");
} else if (fileName == null) {
saveAsFile(this);
//showErrorDialog("You did not previously open a file.Use save as.");
} else {
write(fileName);
tx1.requestFocus();
}
}
//methods save as the file you are currently editing
private void saveAsFile(Frame_class f1) {
if (!lentest()) {
showErrorDialog("There is no Text to Save");
} else {
String filename;
saveDialog.setVisible(true);
filename = saveDialog.getFile();
if (filename != null) {
filename = check(filename);
if (write(filename)) {
fileName = filename;
f1.setTitle(" Text Editor 1.0 By Rajagopal Neelakantan : " + heading + " : " + fileName + " " + st);
}
}
tx1.requestFocus();
}
}
public void saveFileService(String data, String filename){
try{
FileWriter test;
test=new FileWriter(filename);
test.write(data);
test.close();
}catch(Exception e){
e.printStackTrace();
}
}
//method handles writing files to the file system
private boolean write(String filename) {
FileOutputStream os = null;
try {
os = new FileOutputStream(filename);
} catch (Throwable e) {
showErrorDialog("Can't write\"" + filename + "\"");
return (false);
}
try {
String s = tx1.getText();
int len = s.length();
for (int i = 0; i < len; i++) {
os.write(s.charAt(i));
}
os.close();
} catch (IOException e) {
showErrorDialog("can't write\"" + filename + "\"");
return (false);
}
return (true);
}
//DialogBoxes.......
public void showErrorDialog(String message) {
if (errorDialog != null) {
errorDialog.dispose();
}
errorDialog = new ErrorDialog(this, message);
errorDialog.setVisible(true);
}
public void showTEDialog(String message) {
if (teDialog != null) {
teDialog.dispose();
}
teDialog = new TEDialog(this, message);
teDialog.setVisible(true);
}
}//close brace of Frame_class
////////////////////////////////////////////////////////////////////////////////
class ErrorDialog extends Dialog {
Frame_class parent;
String message;
public ErrorDialog(Frame_class parent, String message) {
super(parent, "Error", true);
setBackground(Color.yellow);
this.parent = parent;
this.message = message;
Panel p;
p = new Panel();
p.add(new Label(message));
p.setFont(new Font("System", Font.BOLD, 12));
add("Center", p);
Dimension d;
d = parent.size();
reshape(200, 50, 420, 100);
setResizable(false);
}
public boolean handleEvent(Event event) {
switch (event.id) {
case Event.WINDOW_DESTROY:
dispose();
parent.tx1.requestFocus();
return (true);
}
return (false);
}
}
class TEDialog extends Dialog {
Frame_class parent;
String message;
public TEDialog(Frame_class parent, String message) {
super(parent, "TextEditor 1.0", true);
setBackground(Color.yellow);
this.parent = parent;
this.message = message;
TextArea p;
p = new TextArea();
p.setText(message);
p.setFont(new Font("System", Font.BOLD, 12));
add("Center", p);
p.setEditable(false);
Dimension d;
d = parent.size();
reshape(200, 50, 500, 300);
//setResizable(false);
}
public boolean handleEvent(Event event) {
switch (event.id) {
case Event.WINDOW_DESTROY:
dispose();
parent.tx1.requestFocus();
return (true);
}
return (false);
}
}
/////////////////////////////////////////////////////////////////////////////////
class MyWindowAdapter extends WindowAdapter {// MyWindowAdapter class
Frame_class fc1;
public MyWindowAdapter(Frame_class fc1) {
this.fc1 = fc1;
}
public void windowClosing(WindowEvent we) {
if (Frame_class.window_counter == 0) {
System.exit(0);
} else {
fc1.setVisible(false);
}
--Frame_class.window_counter;
}
}//end MyWindowAdapter class
////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
//main() function class
/////////////////////////////////////////////////////////////////////////////////
public class T_Editor { //open brace of T_Editor class
T_Editor(){
Frame f1 = new Frame_class(" Text Editor 1.0 By Rajagopal Neelakantan");
//f1.setVisible(true);
Dimension d;
d = Toolkit.getDefaultToolkit().getScreenSize();
f1.setSize(d.width, d.height);
}
public static void main(String args[]) { //open brace of main() fun.
Frame f1 = new Frame_class(" Text Editor 1.0 By Rajagopal Neelakantan");
//f1.setVisible(true);
Dimension d;
d = Toolkit.getDefaultToolkit().getScreenSize();
f1.setSize(d.width, d.height);
}//close brace of main() fun.
}//close brace of T_Editor class
/////////////////////////////////////////////////////////////////////////////////
|
[
"gokcse@gmail.com"
] |
gokcse@gmail.com
|
359c6234835f0da6837dddef87a57612f689ae46
|
28b53390d7d529cfee724bbcb8e7e41634cd4d71
|
/src/main/java/dev/banksalad/stock/global/error/exception/EmptyStockException.java
|
e3be73486a1f5389a8e777f365f535562a2be421
|
[] |
no_license
|
wooody92/stock-algorithm
|
442f5e8e6ae4b48f855f3296cbcae4639b9bdd91
|
fec4d61a1f8231cf0ee5d80b6fa46764fa0b2cc6
|
refs/heads/master
| 2023-04-25T06:07:11.934674
| 2021-05-21T07:40:20
| 2021-05-21T07:40:20
| 324,359,648
| 4
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 238
|
java
|
package dev.banksalad.stock.global.error.exception;
public class EmptyStockException extends StockApiException {
public EmptyStockException() {
}
public EmptyStockException(String message) {
super(message);
}
}
|
[
"pkower4@naver.com"
] |
pkower4@naver.com
|
3de895171fa5f0dd6b1b5a56c7d245aef16ec2fc
|
d392357fc736efb98e200beeeb2f362adcd2491f
|
/src/edu/asu/stratego/tests/ClientGameManagerTest.java
|
4f93f45ac445c6c51c0f2627a607e2ef62bf7bda
|
[] |
no_license
|
dwmille3/SER216-Stratego
|
5bfd1c1b7a6fd4e87e08c8d122cffe57525a991b
|
8c33e406afeecacb11e59bf7f0c43c00ff559c8d
|
refs/heads/master
| 2021-01-10T12:23:16.846051
| 2016-04-29T06:06:54
| 2016-04-29T06:06:54
| 55,561,669
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,231
|
java
|
package edu.asu.stratego.tests;
import edu.asu.stratego.game.ClientSocket;
import edu.asu.stratego.game.ServerGameManager;
import org.junit.Test;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import static org.junit.Assert.assertEquals;
public class ClientGameManagerTest {
private void startPseudoClient() throws Exception {
new Thread(() -> {
try {
Thread.sleep(200);
ClientSocket.connect("localhost", 4212);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}).start();
}
private boolean startPseudoServer() throws Exception {
try {
ServerSocket listener = new ServerSocket(4212);
startPseudoClient();
startPseudoClient();
Socket playerOne = listener.accept();
Socket playerTwo = listener.accept();
new ServerGameManager(playerOne, playerTwo, 0);
return true;
} catch (Exception e) {
return false;
}
}
@Test
public void testConnectToServer() throws Exception {
assertEquals(startPseudoServer(), true);
}
}
|
[
"dwmille3@asu.edu"
] |
dwmille3@asu.edu
|
c84ceffcbefc8ddbc31d5e3e2061cdf41d7c6d72
|
30a74502076eebb6fc9c3bebd23e2979946fe945
|
/Bridge/src/com/test3/CommonMessage.java
|
d81f57ce834cb90c00babc8f98480a21e4e6f897
|
[] |
no_license
|
PlumpMath/designpattern-46
|
6d5b7f5580da27e5f599aec4d76dde3b472b8a93
|
77b6d9f9f4a3123bbfed1475409cba59257403af
|
refs/heads/master
| 2021-01-20T09:32:13.700080
| 2014-06-10T04:41:43
| 2014-06-10T04:41:43
| null | 0
| 0
| null | null | null | null |
GB18030
|
Java
| false
| false
| 349
|
java
|
package com.test3;
public class CommonMessage extends AbstractMessage {
public CommonMessage(MessageImplementor impl) {
super(impl);
}
public void sendMessage(String message, String toUser) {
//对于普通消息,什么都不干,直接调用父类的方法,把消息发送出去就可以了
super.sendMessage(message, toUser);
}
}
|
[
"raingxm@163.com"
] |
raingxm@163.com
|
ee404de394339386dec009ebba375fae3a916d27
|
8727b1cbb8ca63d30340e8482277307267635d81
|
/PolarServer/src/com/game/summonpet/bean/SummonPetDetailInfo.java
|
3f7efbf2ee6db3eaa6fd4a5e7ee18ba542aafc6f
|
[] |
no_license
|
taohyson/Polar
|
50026903ded017586eac21a7905b0f1c6b160032
|
b0617f973fd3866bed62da14f63309eee56f6007
|
refs/heads/master
| 2021-05-08T12:22:18.884688
| 2015-12-11T01:44:18
| 2015-12-11T01:44:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 6,021
|
java
|
package com.game.summonpet.bean;
import java.util.List;
import java.util.ArrayList;
import com.game.message.Bean;
import org.apache.mina.core.buffer.IoBuffer;
/**
* @author Commuication Auto Maker
*
* @version 1.0.0
*
* 召唤怪祥细信息类
*/
public class SummonPetDetailInfo extends Bean {
//召唤怪Id
private long petId;
//召唤怪模板Id
private int petModelId;
//召唤怪等级
private int level;
//召唤怪HP
private int hp;
//召唤怪最大HP
private int maxHp;
//召唤怪MP
private int mp;
//召唤怪最大MP
private int maxMp;
//召唤怪SP
private int sp;
//召唤怪最大SP
private int maxSp;
//召唤怪速度
private int speed;
// //出战状态,1出战 0不出战
// private byte showState;
//
// //死亡时间 如果出战状态且未死亡则返回0 否则返回秒级时间
// private int dieTime;
//
// //合体次数
// private int htCount;
//
// //今日合体次数
// private int dayCount;
//
// //合体冷确时间
// private int htCoolDownTime;
//技能列表
private List<com.game.skill.bean.SkillInfo> skillInfos = new ArrayList<com.game.skill.bean.SkillInfo>();
//合体加成
// private List<com.game.player.bean.PlayerAttributeItem> htAddition = new ArrayList<com.game.player.bean.PlayerAttributeItem>();
/**
* 写入字节缓存
*/
public boolean write(IoBuffer buf){
//召唤怪Id
writeLong(buf, this.petId);
//召唤怪模板Id
writeInt(buf, this.petModelId);
//召唤怪等级
writeInt(buf, this.level);
//召唤怪HP
writeInt(buf, this.hp);
//召唤怪最大HP
writeInt(buf, this.maxHp);
//召唤怪MP
writeInt(buf, this.mp);
//召唤怪最大MP
writeInt(buf, this.maxMp);
//召唤怪SP
writeInt(buf, this.sp);
//召唤怪最大SP
writeInt(buf, this.maxSp);
//召唤怪速度
writeInt(buf, this.speed);
//技能列表
writeShort(buf, skillInfos.size());
for (int i = 0; i < skillInfos.size(); i++) {
writeBean(buf, skillInfos.get(i));
}
return true;
}
/**
* 读取字节缓存
*/
public boolean read(IoBuffer buf){
//召唤怪Id
this.petId = readLong(buf);
//召唤怪模板Id
this.petModelId = readInt(buf);
//召唤怪等级
this.level = readInt(buf);
//召唤怪HP
this.hp = readInt(buf);
//召唤怪最大HP
this.maxHp = readInt(buf);
//召唤怪MP
this.mp = readInt(buf);
//召唤怪最大MP
this.maxMp = readInt(buf);
//召唤怪SP
this.sp = readInt(buf);
//召唤怪最大SP
this.maxSp = readInt(buf);
//召唤怪速度
this.speed = readInt(buf);
//技能列表
int skillInfos_length = readShort(buf);
for (int i = 0; i < skillInfos_length; i++) {
skillInfos.add((com.game.skill.bean.SkillInfo)readBean(buf, com.game.skill.bean.SkillInfo.class));
}
return true;
}
/**
* get 召唤怪Id
* @return
*/
public long getPetId(){
return petId;
}
/**
* set 召唤怪Id
*/
public void setPetId(long petId){
this.petId = petId;
}
/**
* get 召唤怪模板Id
* @return
*/
public int getPetModelId(){
return petModelId;
}
/**
* set 召唤怪模板Id
*/
public void setPetModelId(int petModelId){
this.petModelId = petModelId;
}
/**
* get 召唤怪等级
* @return
*/
public int getLevel(){
return level;
}
/**
* set 召唤怪等级
*/
public void setLevel(int level){
this.level = level;
}
/**
* get 召唤怪HP
* @return
*/
public int getHp(){
return hp;
}
/**
* set 召唤怪HP
*/
public void setHp(int hp){
this.hp = hp;
}
/**
* get 召唤怪最大HP
* @return
*/
public int getMaxHp(){
return maxHp;
}
/**
* set 召唤怪最大HP
*/
public void setMaxHp(int maxHp){
this.maxHp = maxHp;
}
/**
* get 召唤怪MP
* @return
*/
public int getMp(){
return mp;
}
/**
* set 召唤怪MP
*/
public void setMp(int mp){
this.mp = mp;
}
/**
* get 召唤怪最大MP
* @return
*/
public int getMaxMp(){
return maxMp;
}
/**
* set 召唤怪最大MP
*/
public void setMaxMp(int maxMp){
this.maxMp = maxMp;
}
/**
* get 召唤怪SP
* @return
*/
public int getSp(){
return sp;
}
/**
* set 召唤怪SP
*/
public void setSp(int sp){
this.sp = sp;
}
/**
* get 召唤怪最大SP
* @return
*/
public int getMaxSp(){
return maxSp;
}
/**
* set 召唤怪最大SP
*/
public void setMaxSp(int maxSp){
this.maxSp = maxSp;
}
/**
* get 召唤怪速度
* @return
*/
public int getSpeed(){
return speed;
}
/**
* set 召唤怪速度
*/
public void setSpeed(int speed){
this.speed = speed;
}
/**
* get 技能列表
* @return
*/
public List<com.game.skill.bean.SkillInfo> getSkillInfos(){
return skillInfos;
}
/**
* set 技能列表
*/
public void setSkillInfos(List<com.game.skill.bean.SkillInfo> skillInfos){
this.skillInfos = skillInfos;
}
@Override
public String toString(){
StringBuffer buf = new StringBuffer("[");
//召唤怪Id
buf.append("petId:" + petId +",");
//召唤怪模板Id
buf.append("petModelId:" + petModelId +",");
//召唤怪等级
buf.append("level:" + level +",");
//召唤怪HP
buf.append("hp:" + hp +",");
//召唤怪最大HP
buf.append("maxHp:" + maxHp +",");
//召唤怪MP
buf.append("mp:" + mp +",");
//召唤怪最大MP
buf.append("maxMp:" + maxMp +",");
//召唤怪SP
buf.append("sp:" + sp +",");
//召唤怪最大SP
buf.append("maxSp:" + maxSp +",");
//召唤怪速度
buf.append("speed:" + speed +",");
//技能列表
buf.append("skillInfos:{");
for (int i = 0; i < skillInfos.size(); i++) {
buf.append(skillInfos.get(i).toString() +",");
}
if(buf.charAt(buf.length()-1)==',') buf.deleteCharAt(buf.length()-1);
buf.append("},");
if(buf.charAt(buf.length()-1)==',') buf.deleteCharAt(buf.length()-1);
buf.append("},");
if(buf.charAt(buf.length()-1)==',') buf.deleteCharAt(buf.length()-1);
buf.append("]");
return buf.toString();
}
}
|
[
"zhuyuanbiao@ZHUYUANBIAO.rd.com"
] |
zhuyuanbiao@ZHUYUANBIAO.rd.com
|
ed00b765e0fffa5c5fc508fdc0e5947b203b01dc
|
9dae38286b0d430a2c33eab688926a43c8661c3a
|
/src/main/java/net/minecraft/block/BlockBasePressurePlate.java
|
625c2d88678988de330d446efea14e1a8e7247ad
|
[] |
no_license
|
SkidJava/Orbit-1.12.2
|
a4cd3cb11f5a245168c20ae211bbd156668485e5
|
41d445d1f5ba99b826ee3b57552539e0caaf9a37
|
refs/heads/master
| 2022-04-25T21:12:53.403324
| 2020-04-28T17:37:16
| 2020-04-28T17:37:16
| 258,465,036
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 7,396
|
java
|
package net.minecraft.block;
import java.util.Random;
import javax.annotation.Nullable;
import net.minecraft.block.material.EnumPushReaction;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.BlockFaceShape;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public abstract class BlockBasePressurePlate extends Block
{
/** The bounding box for the pressure plate pressed state */
protected static final AxisAlignedBB PRESSED_AABB = new AxisAlignedBB(0.0625D, 0.0D, 0.0625D, 0.9375D, 0.03125D, 0.9375D);
protected static final AxisAlignedBB UNPRESSED_AABB = new AxisAlignedBB(0.0625D, 0.0D, 0.0625D, 0.9375D, 0.0625D, 0.9375D);
/**
* This bounding box is used to check for entities in a certain area and then determine the pressed state.
*/
protected static final AxisAlignedBB PRESSURE_AABB = new AxisAlignedBB(0.125D, 0.0D, 0.125D, 0.875D, 0.25D, 0.875D);
protected BlockBasePressurePlate(Material materialIn)
{
this(materialIn, materialIn.getMaterialMapColor());
}
protected BlockBasePressurePlate(Material materialIn, MapColor mapColorIn)
{
super(materialIn, mapColorIn);
this.setCreativeTab(CreativeTabs.REDSTONE);
this.setTickRandomly(true);
}
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos)
{
boolean flag = this.getRedstoneStrength(state) > 0;
return flag ? PRESSED_AABB : UNPRESSED_AABB;
}
/**
* How many theWorld ticks before ticking
*/
public int tickRate(World worldIn)
{
return 20;
}
@Nullable
public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos)
{
return NULL_AABB;
}
/**
* Used to determine ambient occlusion and culling when rebuilding chunks for render
*/
public boolean isOpaqueCube(IBlockState state)
{
return false;
}
public boolean isFullCube(IBlockState state)
{
return false;
}
public boolean isPassable(IBlockAccess worldIn, BlockPos pos)
{
return true;
}
/**
* Return true if an entity can be spawned inside the block (used to get the thePlayer's bed spawn location)
*/
public boolean canSpawnInBlock()
{
return true;
}
public boolean canPlaceBlockAt(World worldIn, BlockPos pos)
{
return this.canBePlacedOn(worldIn, pos.down());
}
/**
* Called when a neighboring block was changed and marks that this state should perform any checks during a neighbor
* change. Cases may include when redstone power is updated, cactus blocks popping off due to a neighboring solid
* block, etc.
*/
public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos p_189540_5_)
{
if (!this.canBePlacedOn(worldIn, pos.down()))
{
this.dropBlockAsItem(worldIn, pos, state, 0);
worldIn.setBlockToAir(pos);
}
}
private boolean canBePlacedOn(World worldIn, BlockPos pos)
{
return worldIn.getBlockState(pos).isFullyOpaque() || worldIn.getBlockState(pos).getBlock() instanceof BlockFence;
}
/**
* Called randomly when setTickRandomly is set to true (used by e.g. crops to grow, etc.)
*/
public void randomTick(World worldIn, BlockPos pos, IBlockState state, Random random)
{
}
public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand)
{
if (!worldIn.isRemote)
{
int i = this.getRedstoneStrength(state);
if (i > 0)
{
this.updateState(worldIn, pos, state, i);
}
}
}
/**
* Called When an Entity Collided with the Block
*/
public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn)
{
if (!worldIn.isRemote)
{
int i = this.getRedstoneStrength(state);
if (i == 0)
{
this.updateState(worldIn, pos, state, i);
}
}
}
/**
* Updates the pressure plate when stepped on
*/
protected void updateState(World worldIn, BlockPos pos, IBlockState state, int oldRedstoneStrength)
{
int i = this.computeRedstoneStrength(worldIn, pos);
boolean flag = oldRedstoneStrength > 0;
boolean flag1 = i > 0;
if (oldRedstoneStrength != i)
{
state = this.setRedstoneStrength(state, i);
worldIn.setBlockState(pos, state, 2);
this.updateNeighbors(worldIn, pos);
worldIn.markBlockRangeForRenderUpdate(pos, pos);
}
if (!flag1 && flag)
{
this.playClickOffSound(worldIn, pos);
}
else if (flag1 && !flag)
{
this.playClickOnSound(worldIn, pos);
}
if (flag1)
{
worldIn.scheduleUpdate(new BlockPos(pos), this, this.tickRate(worldIn));
}
}
protected abstract void playClickOnSound(World worldIn, BlockPos color);
protected abstract void playClickOffSound(World worldIn, BlockPos pos);
/**
* Called serverside after this block is replaced with another in Chunk, but before the Tile Entity is updated
*/
public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
{
if (this.getRedstoneStrength(state) > 0)
{
this.updateNeighbors(worldIn, pos);
}
super.breakBlock(worldIn, pos, state);
}
/**
* Notify block and block below of changes
*/
protected void updateNeighbors(World worldIn, BlockPos pos)
{
worldIn.notifyNeighborsOfStateChange(pos, this, false);
worldIn.notifyNeighborsOfStateChange(pos.down(), this, false);
}
public int getWeakPower(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side)
{
return this.getRedstoneStrength(blockState);
}
public int getStrongPower(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side)
{
return side == EnumFacing.UP ? this.getRedstoneStrength(blockState) : 0;
}
/**
* Can this block provide power. Only wire currently seems to have this change based on its state.
*/
public boolean canProvidePower(IBlockState state)
{
return true;
}
public EnumPushReaction getMobilityFlag(IBlockState state)
{
return EnumPushReaction.DESTROY;
}
protected abstract int computeRedstoneStrength(World worldIn, BlockPos pos);
protected abstract int getRedstoneStrength(IBlockState state);
protected abstract IBlockState setRedstoneStrength(IBlockState state, int strength);
public BlockFaceShape func_193383_a(IBlockAccess p_193383_1_, IBlockState p_193383_2_, BlockPos p_193383_3_, EnumFacing p_193383_4_)
{
return BlockFaceShape.UNDEFINED;
}
}
|
[
"skidjava@gmail.com"
] |
skidjava@gmail.com
|
c79e9076e2ee10f59a61b3e44e11201e0264a300
|
b55cb34a6b4a7357df01800b4546fafa38b69211
|
/mangguo_service/mangguo_service_goods/src/main/java/com/mangguo/goods/controller/AlbumController.java
|
d4493f20e8ac360b423bc2348bdce453117f992e
|
[] |
no_license
|
LoveRabbit007/mangguo
|
25002d305612170a63764aefa1f5ce748f387705
|
76abd3003bea240e533f90c6dee5c1cab8df3ac0
|
refs/heads/master
| 2023-02-18T11:24:34.921036
| 2020-12-28T15:15:14
| 2020-12-28T15:15:14
| 324,715,630
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,767
|
java
|
package com.mangguo.goods.controller;
import com.mangguo.entity.PageResult;
import com.mangguo.entity.Result;
import com.mangguo.entity.StatusCode;
import com.mangguo.goods.pojo.Album;
import com.mangguo.goods.service.AlbumService;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@CrossOrigin
@RequestMapping("/album")
public class AlbumController {
@Autowired
private AlbumService albumService;
/**
* 查询全部数据
* @return
*/
@GetMapping
public Result findAll(){
List<Album> albumList = albumService.findAll();
return new Result(true, StatusCode.OK,"查询成功",albumList) ;
}
/***
* 根据ID查询数据
* @param id
* @return
*/
@GetMapping("/{id}")
public Result findById(@PathVariable Long id){
Album album = albumService.findById(id);
return new Result(true,StatusCode.OK,"查询成功",album);
}
/***
* 新增数据
* @param album
* @return
*/
@PostMapping
public Result add(@RequestBody Album album){
albumService.add(album);
return new Result(true,StatusCode.OK,"添加成功");
}
/***
* 修改数据
* @param album
* @param id
* @return
*/
@PutMapping(value="/{id}")
public Result update(@RequestBody Album album,@PathVariable Long id){
album.setId(id);
albumService.update(album);
return new Result(true,StatusCode.OK,"修改成功");
}
/***
* 根据ID删除品牌数据
* @param id
* @return
*/
@DeleteMapping(value = "/{id}" )
public Result delete(@PathVariable Long id){
albumService.delete(id);
return new Result(true,StatusCode.OK,"删除成功");
}
/***
* 多条件搜索品牌数据
* @param searchMap
* @return
*/
@GetMapping(value = "/search" )
public Result findList(@RequestParam Map searchMap){
List<Album> list = albumService.findList(searchMap);
return new Result(true,StatusCode.OK,"查询成功",list);
}
/***
* 分页搜索实现
* @param searchMap
* @param page
* @param size
* @return
*/
@GetMapping(value = "/search/{page}/{size}" )
public Result findPage(@RequestParam Map searchMap, @PathVariable int page, @PathVariable int size){
Page<Album> pageList = albumService.findPage(searchMap, page, size);
PageResult pageResult=new PageResult(pageList.getTotal(),pageList.getResult());
return new Result(true,StatusCode.OK,"查询成功",pageResult);
}
}
|
[
"914196980@qq.com"
] |
914196980@qq.com
|
06ed169a6e3a64206ce6edb51be5b7b0fa32b455
|
f0b4725fdff90bc654a91797594a28787af61551
|
/后端/weixingxiaocx/src/main/java/cn/bdqn/mbg/model/UserStateTypeExample.java
|
33d97bee9db715db4ae6211c92d5bb7a6a6daccd
|
[] |
no_license
|
TangHui-ops/myProject
|
dfc4cc574a9f3a7736eb1610603b08208153b2ee
|
f4f8821d5419316f06ebc4018e7afc0e68886176
|
refs/heads/master
| 2022-12-10T20:39:24.451742
| 2020-08-20T07:23:07
| 2020-08-20T07:23:07
| 288,932,767
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 13,482
|
java
|
package cn.bdqn.mbg.model;
import java.util.ArrayList;
import java.util.List;
public class UserStateTypeExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table user_state_type
*
* @mbggenerated Tue May 26 14:30:45 CST 2020
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table user_state_type
*
* @mbggenerated Tue May 26 14:30:45 CST 2020
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table user_state_type
*
* @mbggenerated Tue May 26 14:30:45 CST 2020
*/
protected List<Criteria> oredCriteria;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_state_type
*
* @mbggenerated Tue May 26 14:30:45 CST 2020
*/
public UserStateTypeExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_state_type
*
* @mbggenerated Tue May 26 14:30:45 CST 2020
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_state_type
*
* @mbggenerated Tue May 26 14:30:45 CST 2020
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_state_type
*
* @mbggenerated Tue May 26 14:30:45 CST 2020
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_state_type
*
* @mbggenerated Tue May 26 14:30:45 CST 2020
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_state_type
*
* @mbggenerated Tue May 26 14:30:45 CST 2020
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_state_type
*
* @mbggenerated Tue May 26 14:30:45 CST 2020
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_state_type
*
* @mbggenerated Tue May 26 14:30:45 CST 2020
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_state_type
*
* @mbggenerated Tue May 26 14:30:45 CST 2020
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_state_type
*
* @mbggenerated Tue May 26 14:30:45 CST 2020
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_state_type
*
* @mbggenerated Tue May 26 14:30:45 CST 2020
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table user_state_type
*
* @mbggenerated Tue May 26 14:30:45 CST 2020
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andUserStIdIsNull() {
addCriterion("user_st_id is null");
return (Criteria) this;
}
public Criteria andUserStIdIsNotNull() {
addCriterion("user_st_id is not null");
return (Criteria) this;
}
public Criteria andUserStIdEqualTo(Integer value) {
addCriterion("user_st_id =", value, "userStId");
return (Criteria) this;
}
public Criteria andUserStIdNotEqualTo(Integer value) {
addCriterion("user_st_id <>", value, "userStId");
return (Criteria) this;
}
public Criteria andUserStIdGreaterThan(Integer value) {
addCriterion("user_st_id >", value, "userStId");
return (Criteria) this;
}
public Criteria andUserStIdGreaterThanOrEqualTo(Integer value) {
addCriterion("user_st_id >=", value, "userStId");
return (Criteria) this;
}
public Criteria andUserStIdLessThan(Integer value) {
addCriterion("user_st_id <", value, "userStId");
return (Criteria) this;
}
public Criteria andUserStIdLessThanOrEqualTo(Integer value) {
addCriterion("user_st_id <=", value, "userStId");
return (Criteria) this;
}
public Criteria andUserStIdIn(List<Integer> values) {
addCriterion("user_st_id in", values, "userStId");
return (Criteria) this;
}
public Criteria andUserStIdNotIn(List<Integer> values) {
addCriterion("user_st_id not in", values, "userStId");
return (Criteria) this;
}
public Criteria andUserStIdBetween(Integer value1, Integer value2) {
addCriterion("user_st_id between", value1, value2, "userStId");
return (Criteria) this;
}
public Criteria andUserStIdNotBetween(Integer value1, Integer value2) {
addCriterion("user_st_id not between", value1, value2, "userStId");
return (Criteria) this;
}
public Criteria andUserStNameIsNull() {
addCriterion("user_st_name is null");
return (Criteria) this;
}
public Criteria andUserStNameIsNotNull() {
addCriterion("user_st_name is not null");
return (Criteria) this;
}
public Criteria andUserStNameEqualTo(String value) {
addCriterion("user_st_name =", value, "userStName");
return (Criteria) this;
}
public Criteria andUserStNameNotEqualTo(String value) {
addCriterion("user_st_name <>", value, "userStName");
return (Criteria) this;
}
public Criteria andUserStNameGreaterThan(String value) {
addCriterion("user_st_name >", value, "userStName");
return (Criteria) this;
}
public Criteria andUserStNameGreaterThanOrEqualTo(String value) {
addCriterion("user_st_name >=", value, "userStName");
return (Criteria) this;
}
public Criteria andUserStNameLessThan(String value) {
addCriterion("user_st_name <", value, "userStName");
return (Criteria) this;
}
public Criteria andUserStNameLessThanOrEqualTo(String value) {
addCriterion("user_st_name <=", value, "userStName");
return (Criteria) this;
}
public Criteria andUserStNameLike(String value) {
addCriterion("user_st_name like", value, "userStName");
return (Criteria) this;
}
public Criteria andUserStNameNotLike(String value) {
addCriterion("user_st_name not like", value, "userStName");
return (Criteria) this;
}
public Criteria andUserStNameIn(List<String> values) {
addCriterion("user_st_name in", values, "userStName");
return (Criteria) this;
}
public Criteria andUserStNameNotIn(List<String> values) {
addCriterion("user_st_name not in", values, "userStName");
return (Criteria) this;
}
public Criteria andUserStNameBetween(String value1, String value2) {
addCriterion("user_st_name between", value1, value2, "userStName");
return (Criteria) this;
}
public Criteria andUserStNameNotBetween(String value1, String value2) {
addCriterion("user_st_name not between", value1, value2, "userStName");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table user_state_type
*
* @mbggenerated do_not_delete_during_merge Tue May 26 14:30:45 CST 2020
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table user_state_type
*
* @mbggenerated Tue May 26 14:30:45 CST 2020
*/
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
[
"2936186365@qq.com"
] |
2936186365@qq.com
|
4dc5a5998aab43e9eb0d40b3a5915a9f60315a39
|
be73270af6be0a811bca4f1710dc6a038e4a8fd2
|
/crash-reproduction-moho/results/XRENDERING-418-18-26-MOEAD-WeightedSum:TestLen:CallDiversity/org/xwiki/rendering/internal/parser/xhtml/wikimodel/XWikiCommentHandler_ESTest.java
|
561ac14ed194312da7f010356cb01e7b3fdd623d
|
[] |
no_license
|
STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application
|
cf118b23ecb87a8bf59643e42f7556b521d1f754
|
3bb39683f9c343b8ec94890a00b8f260d158dfe3
|
refs/heads/master
| 2022-07-29T14:44:00.774547
| 2020-08-10T15:14:49
| 2020-08-10T15:14:49
| 285,804,495
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 596
|
java
|
/*
* This file was automatically generated by EvoSuite
* Wed Apr 08 05:26:22 UTC 2020
*/
package org.xwiki.rendering.internal.parser.xhtml.wikimodel;
import org.junit.Test;
import static org.junit.Assert.*;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true)
public class XWikiCommentHandler_ESTest extends XWikiCommentHandler_ESTest_scaffolding {
@Test
public void notGeneratedAnyTest() {
// EvoSuite did not generate any tests
}
}
|
[
"pouria.derakhshanfar@gmail.com"
] |
pouria.derakhshanfar@gmail.com
|
8d5f53000165f5546fc887830617bb15484d300c
|
deeb65a3da64f945d1eb5046858639d3cfbd0156
|
/Main17270.java
|
7beb0634f4e71d2d8b1041361103df028ce6d003
|
[] |
no_license
|
lovinix/BOJ_java
|
54e4a68d44977a9ee427e3047a7c7f4ce6af9d17
|
4e3e538869031821560391ff28db162fb30e2dd9
|
refs/heads/master
| 2022-08-18T05:19:45.506481
| 2019-05-22T16:07:12
| 2019-05-22T16:07:12
| 93,701,679
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,746
|
java
|
import java.io.*;
import java.util.*;
public class Main {
private static List<Edge>[] graph;
private static int V;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
V = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
graph = new ArrayList[V + 1];
for (int i = 1; i <= V; i++)
graph[i] = new ArrayList<Edge>();
while (M-- > 0) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
int w = Integer.parseInt(st.nextToken());
graph[u].add(new Edge(v, w));
graph[v].add(new Edge(u, w));
}
st = new StringTokenizer(br.readLine());
int J = Integer.parseInt(st.nextToken());
int S = Integer.parseInt(st.nextToken());
int[] jh = dijkstra(J);
int[] sh = dijkstra(S);
int cost = Integer.MAX_VALUE;
int candidate = Integer.MAX_VALUE;
int answer = -1;
for (int v = V; v >= 1; v--) {
if (v == J || v == S || jh[v] == Integer.MAX_VALUE || sh[v] == Integer.MAX_VALUE)
continue;
cost = Math.min(cost, jh[v] + sh[v]);
}
for (int v = V; v >= 1; v--) {
if (v == J || v == S || jh[v] == Integer.MAX_VALUE || sh[v] == Integer.MAX_VALUE)
continue;
if (cost != jh[v] + sh[v] || jh[v] > sh[v])
continue;
if (candidate >= jh[v]) {
candidate = jh[v];
answer = v;
}
}
System.out.print(answer);
}
private static int[] dijkstra(int start) {
Queue<Edge> pq = new PriorityQueue<>((o1,o2)->o1.weight-o2.weight);
int[] dist = new int[V + 1];
Arrays.fill(dist, Integer.MAX_VALUE);
pq.add(new Edge(start, 0));
dist[start] = 0;
while (!pq.isEmpty()) {
Edge u = pq.poll();
if (u.weight > dist[u.vertex])
continue;
for (Edge v : graph[u.vertex]) {
int cost = u.weight + v.weight;
if (cost < dist[v.vertex]) {
dist[v.vertex] = cost;
pq.add(new Edge(v.vertex, cost));
}
}
}
return dist;
}
private static class Edge {
public int vertex, weight;
public Edge(int vertex, int weight) {
this.vertex = vertex;
this.weight = weight;
}
}
}
|
[
"sylph0606@gmail.com"
] |
sylph0606@gmail.com
|
d59ace00863b191d46a9dedb7ed7042d318699ff
|
cb1eb50e84ab60b1625a498d85ec4702dbc0cbc8
|
/EventBusDemo/eventbuslib/src/androidTest/java/longtianlove/eventbuslib/ExampleInstrumentedTest.java
|
3c6a93f747909aa933d8fb9590a46be24fc3a997
|
[] |
no_license
|
longtianlove-workDemo/MVP
|
8aa320ad30ed02ba06534529bedf1b180202aeb4
|
14e99576207aaee4026eeda80ec9e706d2d83f76
|
refs/heads/master
| 2021-01-17T12:59:26.169918
| 2017-02-28T06:57:41
| 2017-02-28T06:57:41
| 62,885,550
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 757
|
java
|
package longtianlove.eventbuslib;
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.*;
/**
* Instrumentation 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("longtianlove.eventbuslib.test", appContext.getPackageName());
}
}
|
[
"wangbinlong@58ganji.com"
] |
wangbinlong@58ganji.com
|
839988e707283961d3dfa6f215cd475c452be0bf
|
283b04588c197c46a04f846b408a6a820b689307
|
/app/src/main/java/com/cookandroid/blahblar/VideoListAdapter.java
|
27b0b94063f79df3724f8af08d2c0378aeb0de2e
|
[] |
no_license
|
cupucharm/BlahBlah
|
f9a2e4ac9c1a6671378c38bc61f0f98e1321a159
|
a3319bd2cb4e883e32813549878f876038bb4464
|
refs/heads/master
| 2021-02-11T03:42:15.131574
| 2020-03-02T18:57:37
| 2020-03-02T18:57:37
| 244,449,692
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 6,904
|
java
|
package com.cookandroid.blahblar;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.util.ArrayList;
public class VideoListAdapter extends RecyclerView.Adapter<VideoListViewHolder> {
String id, name, phone, today, title;
String dataname;
private ArrayList<VideoListData> verticalDatas;
public void setData(ArrayList<VideoListData> list, String dn){
verticalDatas = list;
dataname = dn;
}
@Override
public VideoListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// 사용할 아이템의 뷰를 생성해준다.
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_videolist_item, parent, false);
VideoListViewHolder holder = new VideoListViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(VideoListViewHolder holder, final int position) {
final VideoListData data = verticalDatas.get(position);
holder.name.setText(data.getText());
holder.img.setImageResource(data.getImg());
holder.img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(dataname=="d1" && position==0) {
title="The Good Place";
Intent intent1 = new Intent(view.getContext(), VideoLearnGP.class);
intent1.putExtra("id", id);
intent1.putExtra("name", name);
intent1.putExtra("phone", phone);
intent1.putExtra("today", today);
intent1.putExtra("title", title);
Log.d("비디오리스트어답터..", id + " " + name + " " + phone + " " + today+" "+title);
view.getContext().startActivity(intent1);
}
else if(dataname=="d1" && position==1) {
title="Set It Up";
Intent intent2 = new Intent(view.getContext(), VideoLearnSS.class);
intent2.putExtra("id", id);
intent2.putExtra("name", name);
intent2.putExtra("phone", phone);
intent2.putExtra("today", today);
intent2.putExtra("title", title);
Log.d("비디오리스트어답터..", id + " " + name + " " + phone + " " + today+" "+title);
view.getContext().startActivity(intent2);
}
else if(dataname=="d1" && position==2) {
title="Ruth & Alex";
Intent intent2 = new Intent(view.getContext(), VideoLearnBK.class);
intent2.putExtra("id", id);
intent2.putExtra("name", name);
intent2.putExtra("phone", phone);
intent2.putExtra("today", today);
intent2.putExtra("title", title);
Log.d("비디오리스트어답터..", id + " " + name + " " + phone + " " + today+" "+title);
view.getContext().startActivity(intent2);
}
else if(dataname=="d2" && position==0) {
title="Pokemon Detective Pikachu";
Intent intent3 = new Intent(view.getContext(), VideoLearnActivity.class);
intent3.putExtra("id", id);
intent3.putExtra("name", name);
intent3.putExtra("phone", phone);
intent3.putExtra("today", today);
intent3.putExtra("title", title);
Log.d("비디오리스트어답터..", id + " " + name + " " + phone + " " + today+" "+title);
view.getContext().startActivity(intent3);
}
else if(dataname=="d2" && position==1) {
title="Midnight in Paris";
Intent intent3 = new Intent(view.getContext(), VideoLearnMP.class);
intent3.putExtra("id", id);
intent3.putExtra("name", name);
intent3.putExtra("phone", phone);
intent3.putExtra("today", today);
intent3.putExtra("title", title);
Log.d("비디오리스트어답터..", id + " " + name + " " + phone + " " + today+" "+title);
view.getContext().startActivity(intent3);
}
else if(dataname=="d3" && position==0) {
title="Intern";
Intent intent4 = new Intent(view.getContext(), VideoLearnIT.class);
intent4.putExtra("id", id);
intent4.putExtra("name", name);
intent4.putExtra("phone", phone);
intent4.putExtra("today", today);
intent4.putExtra("title", title);
Log.d("비디오리스트어답터..", id + " " + name + " " + phone + " " + today+" "+title);
view.getContext().startActivity(intent4);
}
else if(dataname=="d3" && position==1) {
title="The Big Short";
Intent intent4 = new Intent(view.getContext(), VideoLearnBS.class);
intent4.putExtra("id", id);
intent4.putExtra("name", name);
intent4.putExtra("phone", phone);
intent4.putExtra("today", today);
intent4.putExtra("title", title);
Log.d("비디오리스트어답터..", id + " " + name + " " + phone + " " + today+" "+title);
view.getContext().startActivity(intent4);
}
else if(dataname=="d4" && position==0) {
title="Toy Story4";
Intent intent4 = new Intent(view.getContext(), VideoLearnTS.class);
intent4.putExtra("id", id);
intent4.putExtra("name", name);
intent4.putExtra("phone", phone);
intent4.putExtra("today", today);
intent4.putExtra("title", title);
Log.d("비디오리스트어답터..", id + " " + name + " " + phone + " " + today+" "+title);
view.getContext().startActivity(intent4);
}
}
});
}
@Override
public int getItemCount() {
return verticalDatas.size();
}
public void getData(String id, String name, String phone, String today) {
this.id=id;
this.name=name;
this.phone=phone;
this.today=today;
}
}
|
[
"tnwlssl0729@naver.com"
] |
tnwlssl0729@naver.com
|
98e77187af59c31f35e4e1d698741b91b30aa4b4
|
fdd394a1a9f4861fd7ab4013abb296faf9c6cc2f
|
/functional/movie-service/src/main/java/com/microservice/movie/model/Actor.java
|
cae41ab9200cac31e28bf961869aaabc7de23e31
|
[
"MIT"
] |
permissive
|
dendy-senapartha/1StopClickMicroservice
|
6a2bfc1dca16b14377226984171892f4f5e60b53
|
701bb45dfefc4bd997460fcf10aad697dc4ef71f
|
refs/heads/master
| 2022-12-07T08:21:04.694865
| 2020-01-10T02:11:49
| 2020-01-10T02:11:49
| 203,491,211
| 0
| 0
| null | 2022-11-24T09:35:08
| 2019-08-21T02:33:18
|
Java
|
UTF-8
|
Java
| false
| false
| 601
|
java
|
package com.microservice.movie.model;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Data;
import javax.persistence.*;
/*
* Created by dendy-prtha on 17/05/2019.
* actor
*/
@Entity
@Table(name = "actor")
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@Data
public class Actor {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
}
|
[
"wb-ikadekden434525"
] |
wb-ikadekden434525
|
569cbc5458798e1035b9ba5600dc530440a4488e
|
1164b69e0dcc9657fe5fa7a15228f4c4925dc966
|
/src/main/java/com/myfirstapirest/model/Product.java
|
c74827f7e6215b3d82e8d79d951493e7ab785e3e
|
[] |
no_license
|
kevinthicke/First-api-rest-with-Spring
|
9b89aa9d4b05db4d4234b226f611129960cd5de4
|
d653dda88beb9dd1ef2518e3a4b2179c7e8dc362
|
refs/heads/master
| 2020-06-17T01:46:36.926904
| 2019-07-09T11:31:25
| 2019-07-09T11:31:25
| 195,759,076
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,015
|
java
|
package com.myfirstapirest.model;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Product {
private @Id @GeneratedValue(strategy = GenerationType.AUTO)
long id;
private @Column(name = "NAME") String name;
private @Column(name = "PRICE") String price;
private @Column(name = "STATE") boolean state;
public Product() {
this.state = true;
}
public Product(String name, String price) {
this();
this.name = name;
this.price = price;
}
public boolean isState() {
return state;
}
public void setState(boolean state) {
this.state = state;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
|
[
"kevin.cabreramarrero@plexus.es"
] |
kevin.cabreramarrero@plexus.es
|
b879f233eb9b2aa86e1777acf1d8743aba1f934d
|
0e9d71c6683f6b33f8a7ff33b1d310386244097c
|
/app/src/main/java/com/example/hellosearch/ImagesAdapter.java
|
4b0f7b13e6e4e2555a8b44ef8bbd55f8ce8b37ff
|
[] |
no_license
|
madhavc/HelloSearch
|
4c6f5ec510aa13aeb51ff6ccbc09f08083cc992e
|
14074fb83636c3ff4b1e8ac6600c534a12981c50
|
refs/heads/master
| 2020-04-27T08:23:29.216219
| 2015-09-02T21:21:22
| 2015-09-02T21:21:22
| 41,827,724
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 3,700
|
java
|
package com.example.hellosearch;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.example.hellosearch.model.Business;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by Madhav Chhura on 8/30/15.
*/
public class ImagesAdapter extends RecyclerView.Adapter<ImagesAdapter.ImageHolder> {
private static final int TYPE_IMAGE = 1;
private static final int TYPE_MORE_BUTTON = 2;
private MoreImagesCallback moreImagesCallback;
public List<Business> businesses;
private OnItemClickListener itemClickListener;
public ImagesAdapter(List<Business> images) {
super();
this.businesses = images;
}
@Override
public ImageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int layoutResourceId = R.layout.images_grid_view;
View view = LayoutInflater.from(parent.getContext()).inflate(layoutResourceId, parent, false);
ImageHolder holder = new ImageHolder(view);
holder.root = view;
holder.image = (ImageView) view.findViewById(R.id.images_grid_image);
return holder;
}
@Override
public void onBindViewHolder(final ImageHolder holder, final int position) {
switch (getItemViewType(position)) {
case TYPE_IMAGE:
final Business business = businesses.get(position);
holder.root.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (itemClickListener != null) {
itemClickListener.onItemClick(holder.root, position);
}
}
});
Picasso.with(holder.image.getContext()).load(business.image_url).into(holder.image);
holder.image.setContentDescription(business.businessName);
break;
case TYPE_MORE_BUTTON:
holder.root.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (moreImagesCallback != null) {
moreImagesCallback.onMoreImagesPressed();
}
}
});
holder.image.setImageResource(R.drawable.more);
holder.image.setContentDescription("More");
}
}
@Override
public int getItemCount() {
if(businesses != null) {
if (businesses.isEmpty()) {
return 0;
} else {
return businesses.size() + 1;
}
}
return 0;
}
@Override
public int getItemViewType(int position) {
if (position < businesses.size()) {
return TYPE_IMAGE;
} else {
return TYPE_MORE_BUTTON;
}
}
public void setOnItemClickListener(OnItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
public void setMoreImagesCallback(MoreImagesCallback callback) {
this.moreImagesCallback = callback;
}
public static class ImageHolder extends RecyclerView.ViewHolder {
public View root;
public ImageView image;
public ImageHolder(View itemView) {
super(itemView);
}
}
public interface MoreImagesCallback {
void onMoreImagesPressed();
}
}
|
[
"madhav@tokbox.com"
] |
madhav@tokbox.com
|
2e4d9ed9675312a0ab323c5f93b65fb5c018826b
|
4850cad431feca26975d4905f9ed6702e3acda12
|
/src/main/java/rendering/ship/ShipMeshView.java
|
7a68884708427a1e0a3fe717b18494dcd38d2d60
|
[] |
no_license
|
brianries/xwingduel
|
d8b03fc49dd51c5d46b86b48c79d9f67428507db
|
84bafcfdc52127b77010a3e7032d12807b1a37f3
|
refs/heads/master
| 2021-01-10T12:52:22.083069
| 2016-08-23T03:45:21
| 2016-08-23T03:45:21
| 47,158,207
| 0
| 3
| null | 2015-12-02T13:57:50
| 2015-12-01T01:51:53
|
Java
|
UTF-8
|
Java
| false
| false
| 376
|
java
|
package rendering.ship;
import javafx.scene.shape.Mesh;
import javafx.scene.shape.MeshView;
/**
* Created by Brian on 2/2/2016.
*/
public class ShipMeshView extends MeshView implements ShipTokenPart {
public ShipMeshView(Mesh mesh) {
super(mesh);
}
@Override
public ShipToken getShipToken() {
return (ShipToken) this.getParent();
}
}
|
[
"briantries@gmail.com"
] |
briantries@gmail.com
|
84c652b187d0ac47634506891371ac8f97929ea0
|
eda07fffe3c10dbc60606204a21ab1c678ff5d04
|
/java/kadai27_yasuma(9:22提出分)/WebLesson/src/Reg/RegistServlet.java
|
e592ee402a0c7046ebbe7a31a980a0c5b53e18ef
|
[] |
no_license
|
wakasa51/kadai27_yasuma
|
7afc680b2fdedf0305feed5754dd8ff91c41674c
|
7113216f5edb5d27df82f1b71fbec554701bf1ce
|
refs/heads/master
| 2021-01-20T07:27:24.099640
| 2017-09-25T11:56:55
| 2017-09-25T11:56:55
| 101,537,888
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,417
|
java
|
package Reg;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class RegistServlet extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{
res.setCharacterEncoding("UTF-8"); //文字化け対策
HttpSession session = req.getSession(true);
session.setAttribute("english", req.getParameter("english"));
session.setAttribute("japanese", req.getParameter("japanese"));
String english = req.getParameter("english");
String japanese = req.getParameter("japanese");
ArrayList<Word> words = new ArrayList<Word>();
Word word = new Word(english, japanese);
words.add(word);
WordDAO adddata = new WordDAO();
adddata.registWords(words);
int i = words.size();
WordDAO wdao = new WordDAO();
List<Word> dbword = wdao.getWords();
int j = dbword.size();
session.setAttribute("i", i);
session.setAttribute("j", j);
req.getRequestDispatcher("result.jsp").forward(req, res);
//
// //セッションの情報を破棄
// session.removeAttribute("id");
// session.removeAttribute("pass");
//
// //セッションそのものを破棄
// session.invalidate();
}
}
|
[
"y.takashi51@gmail.com"
] |
y.takashi51@gmail.com
|
d8cf26972b6bf04748ed134ce542fc084d545b0a
|
1b906519a1003617fb66ae462f1528efee3a3fb4
|
/app/src/main/java/com/tixon/morse/MyApplication.java
|
3d861360470df4d5090f933ef8f11be4acb745d7
|
[] |
no_license
|
TikhonOsipov/Morse
|
9027c6a2d78be3fcce2dab12be55e36615790d64
|
4513197b544a654408f16180987181ee8a27b40e
|
refs/heads/master
| 2021-01-10T15:18:29.244914
| 2020-07-02T09:55:00
| 2020-07-02T09:55:00
| 55,626,267
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 742
|
java
|
package com.tixon.morse;
import android.app.Application;
import android.app.FragmentManager;
import android.content.Context;
import android.os.Vibrator;
import android.view.inputmethod.InputMethodManager;
/**
* Created by tikhon.osipov on 08.04.2016.
*/
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onTerminate() {
super.onTerminate();
}
public InputMethodManager getInputMethodManager() {
return (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
}
public Vibrator getVibrator() {
return (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
}
}
|
[
"tikhon.osipov@hiq.ru"
] |
tikhon.osipov@hiq.ru
|
ddb2de908151032e00f230ca6689f54ce7991ff6
|
755f6d696f3a2938c9764c886ad1b4a76218ff64
|
/ekilex-app/src/main/java/eki/ekilex/data/db/udt/records/TypeMeaningWordRecord.java
|
21b286d761c3c4c2d16a0b12c7e40ff302b6a4cf
|
[] |
no_license
|
tonisnurk/ekilex
|
f86eedc0e46ba1b634ca7b3f1820f9ea670a9ae4
|
16523945f53e02db301a1aa847a5373ca409fff8
|
refs/heads/master
| 2020-12-23T02:30:44.911257
| 2020-01-29T12:05:17
| 2020-01-29T12:05:17
| 237,005,295
| 0
| 0
| null | 2020-01-29T14:44:00
| 2020-01-29T14:43:59
| null |
UTF-8
|
Java
| false
| true
| 15,874
|
java
|
/*
* This file is generated by jOOQ.
*/
package eki.ekilex.data.db.udt.records;
import eki.ekilex.data.db.udt.TypeMeaningWord;
import java.math.BigDecimal;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record14;
import org.jooq.Row14;
import org.jooq.impl.UDTRecordImpl;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.11.9"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class TypeMeaningWordRecord extends UDTRecordImpl<TypeMeaningWordRecord> implements Record14<Long, Long, Long, String, BigDecimal, TypeGovernmentRecord[], String[], String, Long, String, Integer, String, String[], String> {
private static final long serialVersionUID = -2132560674;
/**
* Setter for <code>public.type_meaning_word.lexeme_id</code>.
*/
public void setLexemeId(Long value) {
set(0, value);
}
/**
* Getter for <code>public.type_meaning_word.lexeme_id</code>.
*/
public Long getLexemeId() {
return (Long) get(0);
}
/**
* Setter for <code>public.type_meaning_word.meaning_id</code>.
*/
public void setMeaningId(Long value) {
set(1, value);
}
/**
* Getter for <code>public.type_meaning_word.meaning_id</code>.
*/
public Long getMeaningId() {
return (Long) get(1);
}
/**
* Setter for <code>public.type_meaning_word.mw_lexeme_id</code>.
*/
public void setMwLexemeId(Long value) {
set(2, value);
}
/**
* Getter for <code>public.type_meaning_word.mw_lexeme_id</code>.
*/
public Long getMwLexemeId() {
return (Long) get(2);
}
/**
* Setter for <code>public.type_meaning_word.mw_lex_complexity</code>.
*/
public void setMwLexComplexity(String value) {
set(3, value);
}
/**
* Getter for <code>public.type_meaning_word.mw_lex_complexity</code>.
*/
public String getMwLexComplexity() {
return (String) get(3);
}
/**
* Setter for <code>public.type_meaning_word.mw_lex_weight</code>.
*/
public void setMwLexWeight(BigDecimal value) {
set(4, value);
}
/**
* Getter for <code>public.type_meaning_word.mw_lex_weight</code>.
*/
public BigDecimal getMwLexWeight() {
return (BigDecimal) get(4);
}
/**
* Setter for <code>public.type_meaning_word.mw_lex_governments</code>.
*/
public void setMwLexGovernments(TypeGovernmentRecord... value) {
set(5, value);
}
/**
* Getter for <code>public.type_meaning_word.mw_lex_governments</code>.
*/
public TypeGovernmentRecord[] getMwLexGovernments() {
return (TypeGovernmentRecord[]) get(5);
}
/**
* Setter for <code>public.type_meaning_word.mw_lex_register_codes</code>.
*/
public void setMwLexRegisterCodes(String... value) {
set(6, value);
}
/**
* Getter for <code>public.type_meaning_word.mw_lex_register_codes</code>.
*/
public String[] getMwLexRegisterCodes() {
return (String[]) get(6);
}
/**
* Setter for <code>public.type_meaning_word.mw_lex_value_state_code</code>.
*/
public void setMwLexValueStateCode(String value) {
set(7, value);
}
/**
* Getter for <code>public.type_meaning_word.mw_lex_value_state_code</code>.
*/
public String getMwLexValueStateCode() {
return (String) get(7);
}
/**
* Setter for <code>public.type_meaning_word.word_id</code>.
*/
public void setWordId(Long value) {
set(8, value);
}
/**
* Getter for <code>public.type_meaning_word.word_id</code>.
*/
public Long getWordId() {
return (Long) get(8);
}
/**
* Setter for <code>public.type_meaning_word.word</code>.
*/
public void setWord(String value) {
set(9, value);
}
/**
* Getter for <code>public.type_meaning_word.word</code>.
*/
public String getWord() {
return (String) get(9);
}
/**
* Setter for <code>public.type_meaning_word.homonym_nr</code>.
*/
public void setHomonymNr(Integer value) {
set(10, value);
}
/**
* Getter for <code>public.type_meaning_word.homonym_nr</code>.
*/
public Integer getHomonymNr() {
return (Integer) get(10);
}
/**
* Setter for <code>public.type_meaning_word.lang</code>.
*/
public void setLang(String value) {
set(11, value);
}
/**
* Getter for <code>public.type_meaning_word.lang</code>.
*/
public String getLang() {
return (String) get(11);
}
/**
* Setter for <code>public.type_meaning_word.word_type_codes</code>.
*/
public void setWordTypeCodes(String... value) {
set(12, value);
}
/**
* Getter for <code>public.type_meaning_word.word_type_codes</code>.
*/
public String[] getWordTypeCodes() {
return (String[]) get(12);
}
/**
* Setter for <code>public.type_meaning_word.aspect_code</code>.
*/
public void setAspectCode(String value) {
set(13, value);
}
/**
* Getter for <code>public.type_meaning_word.aspect_code</code>.
*/
public String getAspectCode() {
return (String) get(13);
}
// -------------------------------------------------------------------------
// Record14 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row14<Long, Long, Long, String, BigDecimal, TypeGovernmentRecord[], String[], String, Long, String, Integer, String, String[], String> fieldsRow() {
return (Row14) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row14<Long, Long, Long, String, BigDecimal, TypeGovernmentRecord[], String[], String, Long, String, Integer, String, String[], String> valuesRow() {
return (Row14) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Long> field1() {
return TypeMeaningWord.LEXEME_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Long> field2() {
return TypeMeaningWord.MEANING_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Long> field3() {
return TypeMeaningWord.MW_LEXEME_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field4() {
return TypeMeaningWord.MW_LEX_COMPLEXITY;
}
/**
* {@inheritDoc}
*/
@Override
public Field<BigDecimal> field5() {
return TypeMeaningWord.MW_LEX_WEIGHT;
}
/**
* {@inheritDoc}
*/
@Override
public Field<TypeGovernmentRecord[]> field6() {
return TypeMeaningWord.MW_LEX_GOVERNMENTS;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String[]> field7() {
return TypeMeaningWord.MW_LEX_REGISTER_CODES;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field8() {
return TypeMeaningWord.MW_LEX_VALUE_STATE_CODE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Long> field9() {
return TypeMeaningWord.WORD_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field10() {
return TypeMeaningWord.WORD;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field11() {
return TypeMeaningWord.HOMONYM_NR;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field12() {
return TypeMeaningWord.LANG;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String[]> field13() {
return TypeMeaningWord.WORD_TYPE_CODES;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field14() {
return TypeMeaningWord.ASPECT_CODE;
}
/**
* {@inheritDoc}
*/
@Override
public Long component1() {
return getLexemeId();
}
/**
* {@inheritDoc}
*/
@Override
public Long component2() {
return getMeaningId();
}
/**
* {@inheritDoc}
*/
@Override
public Long component3() {
return getMwLexemeId();
}
/**
* {@inheritDoc}
*/
@Override
public String component4() {
return getMwLexComplexity();
}
/**
* {@inheritDoc}
*/
@Override
public BigDecimal component5() {
return getMwLexWeight();
}
/**
* {@inheritDoc}
*/
@Override
public TypeGovernmentRecord[] component6() {
return getMwLexGovernments();
}
/**
* {@inheritDoc}
*/
@Override
public String[] component7() {
return getMwLexRegisterCodes();
}
/**
* {@inheritDoc}
*/
@Override
public String component8() {
return getMwLexValueStateCode();
}
/**
* {@inheritDoc}
*/
@Override
public Long component9() {
return getWordId();
}
/**
* {@inheritDoc}
*/
@Override
public String component10() {
return getWord();
}
/**
* {@inheritDoc}
*/
@Override
public Integer component11() {
return getHomonymNr();
}
/**
* {@inheritDoc}
*/
@Override
public String component12() {
return getLang();
}
/**
* {@inheritDoc}
*/
@Override
public String[] component13() {
return getWordTypeCodes();
}
/**
* {@inheritDoc}
*/
@Override
public String component14() {
return getAspectCode();
}
/**
* {@inheritDoc}
*/
@Override
public Long value1() {
return getLexemeId();
}
/**
* {@inheritDoc}
*/
@Override
public Long value2() {
return getMeaningId();
}
/**
* {@inheritDoc}
*/
@Override
public Long value3() {
return getMwLexemeId();
}
/**
* {@inheritDoc}
*/
@Override
public String value4() {
return getMwLexComplexity();
}
/**
* {@inheritDoc}
*/
@Override
public BigDecimal value5() {
return getMwLexWeight();
}
/**
* {@inheritDoc}
*/
@Override
public TypeGovernmentRecord[] value6() {
return getMwLexGovernments();
}
/**
* {@inheritDoc}
*/
@Override
public String[] value7() {
return getMwLexRegisterCodes();
}
/**
* {@inheritDoc}
*/
@Override
public String value8() {
return getMwLexValueStateCode();
}
/**
* {@inheritDoc}
*/
@Override
public Long value9() {
return getWordId();
}
/**
* {@inheritDoc}
*/
@Override
public String value10() {
return getWord();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value11() {
return getHomonymNr();
}
/**
* {@inheritDoc}
*/
@Override
public String value12() {
return getLang();
}
/**
* {@inheritDoc}
*/
@Override
public String[] value13() {
return getWordTypeCodes();
}
/**
* {@inheritDoc}
*/
@Override
public String value14() {
return getAspectCode();
}
/**
* {@inheritDoc}
*/
@Override
public TypeMeaningWordRecord value1(Long value) {
setLexemeId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypeMeaningWordRecord value2(Long value) {
setMeaningId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypeMeaningWordRecord value3(Long value) {
setMwLexemeId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypeMeaningWordRecord value4(String value) {
setMwLexComplexity(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypeMeaningWordRecord value5(BigDecimal value) {
setMwLexWeight(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypeMeaningWordRecord value6(TypeGovernmentRecord... value) {
setMwLexGovernments(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypeMeaningWordRecord value7(String... value) {
setMwLexRegisterCodes(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypeMeaningWordRecord value8(String value) {
setMwLexValueStateCode(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypeMeaningWordRecord value9(Long value) {
setWordId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypeMeaningWordRecord value10(String value) {
setWord(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypeMeaningWordRecord value11(Integer value) {
setHomonymNr(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypeMeaningWordRecord value12(String value) {
setLang(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypeMeaningWordRecord value13(String... value) {
setWordTypeCodes(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypeMeaningWordRecord value14(String value) {
setAspectCode(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypeMeaningWordRecord values(Long value1, Long value2, Long value3, String value4, BigDecimal value5, TypeGovernmentRecord[] value6, String[] value7, String value8, Long value9, String value10, Integer value11, String value12, String[] value13, String value14) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
value6(value6);
value7(value7);
value8(value8);
value9(value9);
value10(value10);
value11(value11);
value12(value12);
value13(value13);
value14(value14);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached TypeMeaningWordRecord
*/
public TypeMeaningWordRecord() {
super(TypeMeaningWord.TYPE_MEANING_WORD);
}
/**
* Create a detached, initialised TypeMeaningWordRecord
*/
public TypeMeaningWordRecord(Long lexemeId, Long meaningId, Long mwLexemeId, String mwLexComplexity, BigDecimal mwLexWeight, TypeGovernmentRecord[] mwLexGovernments, String[] mwLexRegisterCodes, String mwLexValueStateCode, Long wordId, String word, Integer homonymNr, String lang, String[] wordTypeCodes, String aspectCode) {
super(TypeMeaningWord.TYPE_MEANING_WORD);
set(0, lexemeId);
set(1, meaningId);
set(2, mwLexemeId);
set(3, mwLexComplexity);
set(4, mwLexWeight);
set(5, mwLexGovernments);
set(6, mwLexRegisterCodes);
set(7, mwLexValueStateCode);
set(8, wordId);
set(9, word);
set(10, homonymNr);
set(11, lang);
set(12, wordTypeCodes);
set(13, aspectCode);
}
}
|
[
"yogesh.sharma@tripledev.ee"
] |
yogesh.sharma@tripledev.ee
|
81e29aa47490ee4569ed2514c303e89f23bde45b
|
93837a1c3a25a80c355878442269d97e6afff096
|
/src/test/java/com/tc/shop/ShopadminApplicationTests.java
|
87b8abd0aea5b207ca82fe52ecb9db74f20b3e80
|
[] |
no_license
|
Gemmmm/ShopAdmin
|
fefef4ff2cddd2b86e34a66317bf1aedc504786d
|
305bbdc3a7e841c883d50cf628e9d4fecd77546d
|
refs/heads/main
| 2023-02-10T18:01:53.758072
| 2021-01-07T02:06:07
| 2021-01-07T02:06:07
| 327,476,629
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 215
|
java
|
package com.tc.shop;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ShopadminApplicationTests {
@Test
void contextLoads() {
}
}
|
[
"1121382295@qq.com"
] |
1121382295@qq.com
|
7eb3dc30c10209e40c329867f91b8fc07bd7f9b2
|
f1a784c51ee6a59a0bbbd1da0c4bef3849191349
|
/src/main/java/com/scheduler/auth/RolePermissions.java
|
f8785b6599e69a378a4b35a15862abf92ab34f54
|
[] |
no_license
|
IlyaKontsevich/university-scheduler
|
31b7c91161863e1a45f96bfae5fc5bf3f73043bc
|
9caec1d0e7446b9c75f6111a8f56759cf1c1bec6
|
refs/heads/master
| 2023-05-07T09:06:44.107680
| 2021-05-08T13:46:45
| 2021-05-08T13:46:45
| 307,685,240
| 0
| 0
| null | 2021-05-26T09:46:24
| 2020-10-27T12:00:01
|
Java
|
UTF-8
|
Java
| false
| false
| 998
|
java
|
package com.scheduler.auth;
import com.scheduler.common.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
@Entity
@Data
@EqualsAndHashCode( callSuper = true )
@Table( name = "role_permissions" )
public class RolePermissions extends BaseEntity
{
@Id
@NotNull
@Column( name = "rp_id" )
private Long id;
@NotNull
@Column( name = "rp_name" )
private String name;
@NotNull
@Column( name = "un_id" )
private Long universityId;
@Column( name = "rp_created", updatable = false )
private LocalDateTime created;
@Column( name = "rp_modified" )
private LocalDateTime modified;
@NotNull
@ManyToOne( fetch = FetchType.LAZY )
@JoinColumn( name = "rol_id" )
private Role role;
@NotNull
@ManyToOne( fetch = FetchType.LAZY )
@JoinColumn( name = "per_id" )
private Permissions permissions;
}
|
[
"ikantsevich@exadel.com"
] |
ikantsevich@exadel.com
|
315c8c23efdb067f4c3323078d975f82223c862b
|
4082835d52d668dfa6fce72bb97df156805bcd53
|
/src/com/javarush/test/level17/lesson10/home02/Beach.java
|
b948603a075fada5d0c38909cf8a926d9c172eef
|
[] |
no_license
|
Arkadiu/JavaRush
|
00cd04072fa1af70020d03510b9694f565423aec
|
c467f58c433b99a7374e11c60a83d30860ae866a
|
refs/heads/master
| 2021-06-25T18:14:15.204111
| 2017-04-17T18:32:06
| 2017-04-17T18:32:06
| 57,323,182
| 0
| 2
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,550
|
java
|
package com.javarush.test.level17.lesson10.home02;
/* Comparable
Реализуйте интерфейс Comparable<Beach> в классе Beach, который будет использоваться нитями.
*/
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
public class Beach implements Comparable<Beach>{
private String name; //название
private float distance; //расстояние
private int quality; //качество
public Beach(String name, float distance, int quality) {
this.name = name;
this.distance = distance;
this.quality = quality;
}
public synchronized String getName() {
return name;
}
public synchronized void setName(String name) {
this.name = name;
}
public synchronized float getDistance() {
return distance;
}
public synchronized void setDistance(float distance) {
this.distance = distance;
}
public synchronized int getQuality() {
return quality;
}
public synchronized void setQuality(int quality) {
this.quality = quality;
}
@Override
public synchronized int compareTo(Beach beach)
{
int nameParam = name.compareTo(getName());
int distParam = (int) (distance - beach.getDistance());
int qualParam = - quality + beach.getQuality();
int result = 10000 * nameParam + 100 * distParam + qualParam; //Объекты сравниваются по 3 параметрам
//Независимо друг от друга
return result;
}
public static void main(String []args){
ArrayList<Beach> beaches = new ArrayList<Beach>();
Beach beach1 = new Beach("Сосенки", 1f, 5);
Beach beach2 = new Beach("Ижевскк", 1.5f, 5);
Beach beach3 = new Beach("Воронеж", 1.4f, 6);
Beach beach4 = new Beach("Шампань", 1.3f, 8);
Beach beach5 = new Beach("Берегъа", 5.0f, 10);
Beach beach[] = {beach1, beach2, beach3, beach4, beach5};
Arrays.sort(beach);
for (Beach x : beach){
beaches.add(x);
System.out.println(x.getName() + "/" + x.getDistance() + "/" + x.getQuality());
}
System.out.println(beach[1].compareTo(beach[2]));
System.out.println(beach[2].compareTo(beach[3]));
System.out.println(beach[1].compareTo(beach[3]));
}
}
|
[
"ntfs2002@gmail.com"
] |
ntfs2002@gmail.com
|
1e935741f64efc13d391e563888b82ed0724d401
|
4fbc0e2fafb6c59e9041c9650271ef6ffbdceea4
|
/Paradigmas_Programacao_16_17/Ficha7_PP/src/Pizzas/PizzaDemo.java
|
282e65bacde97ca2bfd31385a9941a1352fd7bde
|
[] |
no_license
|
Carlos8150075/Engenharia_informatica
|
9eabf91ae6e92d9fca10bf30e8bfd076743bbb8b
|
5d7e6ef03bc66bef740d3c03ec964717c90197e7
|
refs/heads/master
| 2020-04-02T13:26:19.543816
| 2018-05-22T10:33:21
| 2018-05-22T10:33:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,428
|
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 Pizzas;
import Pizzas.Enums.TamanhoPizza;
/**
*
* @author Bernardo
*/
public class PizzaDemo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
PizzaIngredients[] ingrediente = new PizzaIngredients[]{
new PizzaIngredients(1, "Fiambre", "30 Gramas"),
new PizzaIngredients(2, "Cogumelos", "20 Gramas"),
new PizzaIngredients(3, "Pimento", "12 Gramas"),
new PizzaIngredients(4, "Ananas", "9 Gramas")
};
Pizza[] pizzas = new Pizza[]{
new Pizza(1, "Fiambre", "Pizza de fiambre", 19.50, TamanhoPizza.PizzaSize.BIG),
new Pizza(2, "Especial", "Pizza Especial", 20.00, TamanhoPizza.PizzaSize.KING)
};
pizzas[0].addIngrediente(ingrediente[0]);
pizzas[0].addIngrediente(ingrediente[2]);
pizzas[0].addIngrediente(ingrediente[3]);
pizzas[1].addIngrediente(ingrediente[1]);
pizzas[1].addIngrediente(ingrediente[3]);
pizzas[1].addIngrediente(ingrediente[0]);
pizzas[0].removeIngrediente(1);
pizzas[1].removeIngrediente(4);
for (Pizza pizza : pizzas) {
System.out.println(pizza);
}
}
}
|
[
"8150060@estg.ipp.pt"
] |
8150060@estg.ipp.pt
|
777d597f7b9cb3286b351fb24e1fd0e1b0834e80
|
3fc630c23b9ccf174858750541cd8ec5cbdf4487
|
/RestCiCdTestApp/src/main/java/com/logesh/results/DirectoryListingController.java
|
146d49a5beb68bb5ebdeb4d84bc99547ccfbf44e
|
[] |
no_license
|
LogeshLohit/restcicdtest
|
3523ed8048dd9d295bddb23ca469b9db17e779bc
|
5fc04003f23aab68097e4065000b9e66e3412ab3
|
refs/heads/main
| 2023-02-12T20:29:08.413089
| 2021-01-14T10:34:07
| 2021-01-14T10:34:07
| 300,670,626
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,256
|
java
|
package com.logesh.results;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DirectoryListingController {
private final String outputDirectory = "D:\\My works\\Verizon Projects\\FETCH-QUERY-RESULTS\\output\\";
@GetMapping("getFile")
public ResponseEntity<Object> getFileByName(@RequestParam("name") String fileName) {
if (!fileName.toLowerCase().endsWith(".txt"))
fileName = fileName.concat(".txt");
// CREATE DIR IF NOT EXISTS
String fileLocation = StringUtils.join(outputDirectory, fileName);
if (!Files.exists(Paths.get(fileLocation))) {
return ResponseEntity.ok().body("File Not Found!");
}
InputStreamResource resource = null;
try {
resource = new InputStreamResource(new FileInputStream(fileLocation));
} catch (Exception e) {
e.printStackTrace();
}
HttpHeaders header = new HttpHeaders();
header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
header.add("Cache-Control", "no-cache, no-store, must-revalidate");
header.add("Pragma", "no-cache");
header.add("Expires", "0");
return ResponseEntity.ok().headers(header).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
}
@GetMapping("listFiles")
public String getAllFileNames() {
// CREATE DIR IF NOT EXISTS
List<String> allFiles = FileUtils.listFiles(Paths.get(outputDirectory).toFile(), null, false).stream()
.map(File::getName).collect(Collectors.toList());
return allFiles.isEmpty() ? StringUtils.join("-- No Files Found -- ,EMPTY DIRECTORY")
: StringUtils.join(allFiles, ", ");
}
}
|
[
"logesh.jeppiaar@gmail.com"
] |
logesh.jeppiaar@gmail.com
|
d724a6689a5fa2cab98439e494b543d4a5e7e0b8
|
937a3f8b34683ed013b91bf5b3bef453ea87e74d
|
/movie2/src/main/java/com/spring/movie/Producto.java
|
6c358fcf33d9adf681ea9b4936a920ae022934ab
|
[] |
no_license
|
MatiasRosales/Matias
|
2748e571c04c8969ccf022d19a23127aa2ac7e26
|
865a161fbc1b9be9324cfb34f09cc0bb33eeacaa
|
refs/heads/master
| 2022-12-21T05:33:58.944603
| 2020-02-12T20:59:33
| 2020-02-12T20:59:33
| 235,803,534
| 0
| 0
| null | 2022-12-16T01:02:01
| 2020-01-23T13:45:55
|
Java
|
UTF-8
|
Java
| false
| false
| 2,512
|
java
|
package com.spring.movie;
public class Producto {
private int id;
private String titulo;
private String genero;
private String categoria;
private int anio;
private String origen;
private String artista;
private String album;
private int episodios;
private int temporadas;
private int puntaje;
public Producto() {
}
public Producto(int id,String titulo,String genero,String categoria, int anio, String origen,String artista, String album,int episodios,int temporadas,int puntaje) {
this.id = id;
this.titulo = titulo;
this.genero = genero;
this.categoria = categoria;
this.anio = anio;
this.origen = origen;
this.artista = artista;
this.album = album;
this.episodios = episodios;
this.temporadas = temporadas;
this.puntaje = puntaje;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getGenero() {
return genero;
}
public void setGenero(String genero) {
this.genero = genero;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
public int getAnio() {
return anio;
}
public void setAnio(int anio) {
this.anio = anio;
}
public String getOrigen() {
return origen;
}
public void setOrigen(String origen) {
this.origen = origen;
}
public String getArtista() {
return artista;
}
public void setArtista(String artista) {
this.artista = artista;
}
public String getAlbum() {
return album;
}
public void setAlbum(String album) {
this.album = album;
}
public int getEpisodios() {
return episodios;
}
public void setEpisodios(int episodios) {
this.episodios = episodios;
}
public int getTemporadas() {
return temporadas;
}
public void setTemporadas(int temporadas) {
this.temporadas = temporadas;
}
public int getPuntaje() {
return puntaje;
}
public void setPuntaje(int puntaje) {
this.puntaje = puntaje;
}
}
|
[
"matias.rosales97@hotmail.com"
] |
matias.rosales97@hotmail.com
|
31bedb9ec30f0289b589e62fbabd563fc6b8e37a
|
684cb79f39d15a54808b4a28af8a5c4829b1679a
|
/dang/src/main/java/com/sunztech/admin/dang/ui/utils/utils2/TextUtilTools.java
|
5584640d14c0fdafaa1091a8166cf22f2e364259
|
[] |
no_license
|
jiayazhou1992/MyApplication
|
1e0d861d4655d03d1b1c2ee8124e69411e00959d
|
f905b24508ce3ff7bdc84eb70cbc390700b468aa
|
refs/heads/master
| 2021-01-23T06:39:29.679752
| 2018-07-16T15:11:10
| 2018-07-16T15:11:10
| 94,738,921
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,916
|
java
|
package com.sunztech.admin.dang.ui.utils.utils2;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by 刘大军 on 2015/12/24.
*/
public class TextUtilTools {
/**
* 关键字高亮显示
*
* @param key 需要高亮的关键字
* @param text 需要显示的文字
* @return spannable 处理完后的结果,记得不要toString(),否则没有效果
*/
public static SpannableStringBuilder highlight(Context context,int color,String text, String key) {
SpannableStringBuilder spannable = new SpannableStringBuilder(text);
CharacterStyle span = null;
Pattern p = Pattern.compile(key);
Matcher m = p.matcher(text);
while (m.find()) {
span = new ForegroundColorSpan(context.getResources().getColor(color));// 需要重复!
spannable.setSpan(span, m.start(), m.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return spannable;
}
/**
* @author 刘大军
* created at
* 只允许字母和数字 String regEx = "[^a-zA-Z0-9]"
*/
// 清除掉所有特殊字符
public static String stringContent(String text, String key) {
String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……& amp;*()——+|{}【】‘;:”“’。,、?]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(text);
return m.replaceAll("").trim();
}
public static String stringRegexContent(String text){
String regex="[\n|\r|\t|]";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
return m.replaceAll("").trim();
}
}
|
[
"1184545990@qq.com"
] |
1184545990@qq.com
|
fd4be6a293e72ee58534e623a9d41cdcb1d7ee73
|
cec32b8cca77f996f7acc052d5f1a50982ee1950
|
/src/main/java/com/ezsyncxz/efficiency/socket/BxServerSocket.java
|
9fbdee6af2f1a6cb9c8659f8bb55a695243081bf
|
[] |
no_license
|
bizipoopoo/efficiency
|
d285829c0f6b1ea64ef3f4c14b1d95fba3469318
|
43943deb9891ac6655fbf3431b21ac90d9159a8a
|
refs/heads/master
| 2021-01-14T07:02:12.217594
| 2020-03-04T03:07:10
| 2020-03-04T03:07:10
| 242,634,050
| 4
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,131
|
java
|
package com.ezsyncxz.efficiency.socket;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 接收文件服务
* @author admin_Hzw
*
*/
public class BxServerSocket {
/**
* 工程main方法
* @param args
*/
public static void main(String[] args) {
try {
final ServerSocket server = new ServerSocket(48123);
Thread th = new Thread(new Runnable() {
public void run() {
while (true) {
try {
System.out.println("开始监听...");
/*
* 如果没有访问它会自动等待
*/
Socket socket = server.accept();
System.out.println("有链接");
receiveFile(socket);
} catch (Exception e) {
System.out.println("服务器异常");
e.printStackTrace();
}
}
}
});
th.run(); //启动线程运行
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
}
/**
* 接收文件方法
* @param socket
* @throws IOException
*/
public static void receiveFile(Socket socket) throws IOException {
byte[] inputByte = null;
int length = 0;
DataInputStream dis = null;
FileOutputStream fos = null;
try {
try {
dis = new DataInputStream(socket.getInputStream());
int len = dis.readInt();
byte[] bytes = new byte[len];
dis.read(bytes);
java.lang.String filePath = new java.lang.String(bytes);
fos = new FileOutputStream(new File(filePath));
inputByte = new byte[1024];
System.out.println("开始接收数据...");
while ((length = dis.read(inputByte)) > 0) {
fos.write(inputByte, 0, length);
fos.flush();
}
System.out.println("完成接收:"+"");
} finally {
if (fos != null)
fos.close();
if (dis != null)
dis.close();
if (socket != null)
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void write(byte[] data, String path){
}
public static byte[] getCheckSUm(String path){
return new byte[0];
}
}
|
[
"icebearbearbearbear@gmail.com"
] |
icebearbearbearbear@gmail.com
|
814f754a00a581d249ef182141644a7342e67d87
|
027c0c52ab66f181be386217c91a28188dd3a4d2
|
/dhis-2/dhis-services/dhis-service-core/src/test/java/org/hisp/dhis/source/SourceStoreTest.java
|
3e75b49889a0c0ca244855d9ff2d0c9ba8624448
|
[
"BSD-3-Clause"
] |
permissive
|
rubendw/dhis2
|
96f3af9fb4fa0f9d421b39098ad7aa4096c82af3
|
b9f5272ea001020717e4fc630ddb9f145b95d6ef
|
refs/heads/master
| 2022-02-15T08:35:43.775194
| 2009-03-04T15:10:07
| 2009-03-04T15:10:07
| 142,915
| 1
| 0
| null | 2022-01-21T23:21:45
| 2009-03-04T15:13:23
|
Java
|
UTF-8
|
Java
| false
| false
| 4,578
|
java
|
package org.hisp.dhis.source;
/*
* Copyright (c) 2004-2007, University of Oslo
* 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 HISP project 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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.
*/
import org.hisp.dhis.DhisSpringTest;
/**
* @author Torgeir Lorange Ostby
* @version $Id: SourceStoreTest.java 3200 2007-03-29 11:51:17Z torgeilo $
*/
public class SourceStoreTest
extends DhisSpringTest
{
private SourceStore sourceStore;
// -------------------------------------------------------------------------
// Set up/tear down
// -------------------------------------------------------------------------
public void setUpTest()
throws Exception
{
sourceStore = (SourceStore) getBean( SourceStore.ID );
}
// -------------------------------------------------------------------------
// Tests
// -------------------------------------------------------------------------
public void testSource()
throws Exception
{
String sourceAName = "DummySourceA";
String sourceBName = "DummySourceB";
Source sourceA = new DummySource( sourceAName );
Source sourceB = new DummySource( sourceBName );
assertEquals( 0, sourceStore.getAllSources().size() );
assertEquals( 0, sourceStore.getAllSources( DummySource.class ).size() );
int sourceAId = sourceStore.addSource( sourceA );
DummySource sourceAA = sourceStore.getSource( sourceAId );
assertEquals( sourceAId, sourceAA.getId() );
assertEquals( sourceAName, sourceAA.getName() );
assertEquals( 1, sourceStore.getAllSources().size() );
assertEquals( 1, sourceStore.getAllSources( DummySource.class ).size() );
int sourceBId = sourceStore.addSource( sourceB );
DummySource sourceBB = sourceStore.getSource( sourceBId );
assertEquals( sourceBId, sourceBB.getId() );
assertEquals( sourceBName, sourceBB.getName() );
assertEquals( 2, sourceStore.getAllSources().size() );
assertEquals( 2, sourceStore.getAllSources( DummySource.class ).size() );
try
{
sourceStore.addSource( new DummySource( sourceAName ) );
fail();
}
catch ( Exception e )
{
// Expected
}
sourceAName = "DummySourceAA";
sourceAA.setName( sourceAName );
sourceStore.updateSource( sourceAA );
sourceAA = sourceStore.getSource( sourceAId );
assertEquals( sourceAId, sourceAA.getId() );
assertEquals( sourceAName, sourceAA.getName() );
assertEquals( 2, sourceStore.getAllSources().size() );
sourceStore.deleteSource( sourceAA );
assertNull( sourceStore.getSource( sourceAId ) );
assertEquals( 1, sourceStore.getAllSources().size() );
sourceBB = sourceStore.getSource( sourceBId);
sourceStore.deleteSource( sourceBB );
assertNull( sourceStore.getSource( sourceBId ) );
assertEquals( 0, sourceStore.getAllSources().size() );
}
}
|
[
"oddmunds@leia.ifi.uio.no"
] |
oddmunds@leia.ifi.uio.no
|
d8545965d29e9f870ea4eb1ab853ba0c6073ce2d
|
551e65e3d34c30609e419787f967bc1b06caacac
|
/TeRKClient/code/java/prototypingplayground/src/PrototypingPlayground.java
|
332a88c718aaa338cf27ce8947518e3258fb0539
|
[] |
no_license
|
CMU-CREATE-Lab/terk-legacy
|
c4ccdd8dd0e310e44d3c74ab6eaa3904f5ae5274
|
16f7e460f4f7a3bcd6a0cc3107a1bcaacf612cc5
|
refs/heads/master
| 2021-01-19T11:51:31.891500
| 2011-05-26T19:48:11
| 2011-05-26T19:48:11
| 40,053,894
| 0
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 24,954
|
java
|
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;
import edu.cmu.ri.createlab.TeRK.userinterface.GUIConstants;
import edu.cmu.ri.mrpl.TeRK.QwerkState;
import edu.cmu.ri.mrpl.TeRK.client.components.framework.BaseGUIClient;
import edu.cmu.ri.mrpl.TeRK.client.components.framework.GUIClientHelperEventHandlerAdapter;
import edu.cmu.ri.mrpl.TeRK.client.components.services.QwerkController;
import edu.cmu.ri.mrpl.TeRK.client.components.userinterface.video.VideoStreamEventListener;
import edu.cmu.ri.mrpl.swing.AbstractTimeConsumingAction;
import edu.cmu.ri.mrpl.swing.ImageFormat;
import edu.cmu.ri.mrpl.swing.SavePictureActionListener;
import edu.cmu.ri.mrpl.swing.SpringLayoutUtilities;
import edu.cmu.ri.mrpl.util.ArrayUtils;
import org.apache.log4j.Logger;
/**
* @author Chris Bartley (bartley@cmu.edu)
*/
public final class PrototypingPlayground extends BaseGUIClient
{
private static final Logger LOG = Logger.getLogger(PrototypingPlayground.class);
/** The application name (appears in the title bar) */
private static final String APPLICATION_NAME = "Prototyping Playground";
/** Properties file used to setup Ice for this application */
private static final String ICE_DIRECT_CONNECT_PROPERTIES_FILE = "/PrototypingPlayground.direct-connect.ice.properties";
private static final String ICE_RELAY_PROPERTIES_FILE = "/PrototypingPlayground.relay.ice.properties";
/** Dimensions used for spacing out GUI elements */
private static final Dimension SPACER_DIMENSIONS = new Dimension(5, 5);
/** Line separator, used for appending messages to the message area */
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
/** Number of programmable buttons and text fields */
private static final int NUM_BUTTONS_AND_TEXT_FIELDS = 8;
/** Number of columns to display in the text fields */
private static final int TEXT_FIELD_COLUMNS = 10;
/** Number of frames between each fps computation */
private static final int FPS_FRAME_COUNT = 10;
private static final int FPS_FRAME_COUNT_TIMES_1000 = 1000 * FPS_FRAME_COUNT;
public static void main(final String[] args)
{
//Schedule a job for the event-dispatching thread: creating and showing this application's GUI.
SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
new PrototypingPlayground();
}
});
}
/** Programmable buttons */
private final JButton[] buttons = new JButton[NUM_BUTTONS_AND_TEXT_FIELDS];
private final JTextField[] textFields = new JTextField[NUM_BUTTONS_AND_TEXT_FIELDS];
/** buttons */
private final JButton savePictureButton = GUIConstants.createButton("Save Picture", true);
private final JButton pauseResumeVideoButton = GUIConstants.createButton("Start Video");
private final JButton clearMessageAreaButton = GUIConstants.createButton("Clear", true);
private final JLabel framesPerSecondLabel = GUIConstants.createLabel("0 fps");
private boolean isVideoStreamPaused = true;
private long fpsTimestamp = 0;
private int fpsCount = 0;
private float fps = 0;
private final FPSDisplayRunnable fpsDisplayRunnable = new FPSDisplayRunnable();
/** Date formatter, used for time-stamping messages in the message area */
private final SimpleDateFormat dateFormatter = new SimpleDateFormat("HH:mm:ss,SSS: ");
// text area for messages
private final JTextArea messageTextArea = new JTextArea(16, 50);
private PrototypingPlayground()
{
super(APPLICATION_NAME, ICE_RELAY_PROPERTIES_FILE, ICE_DIRECT_CONNECT_PROPERTIES_FILE);
setGUIClientHelperEventHandler(
new GUIClientHelperEventHandlerAdapter()
{
public void executeAfterRelayLogin()
{
appendMessage("Logged in to relay.");
}
public void executeAfterRelayLogout()
{
appendMessage("Logged out from relay.");
}
public void executeBeforeDisconnectingFromQwerk()
{
appendMessage("Disconnecting from qwerk...");
super.executeBeforeDisconnectingFromQwerk();
}
public void executeAfterEstablishingConnectionToQwerk(final String qwerkUserId)
{
appendMessage("Connected to qwerk " + qwerkUserId);
isVideoStreamPaused = true;
}
public void executeAfterDisconnectingFromQwerk(final String qwerkUserId)
{
appendMessage("Disconnected from qwerk " + qwerkUserId);
fps = 0;
updateFramesPerSecondLabel();
}
public void toggleGUIElementState(final boolean isConnectedToQwerk)
{
for (int i = 0; i < NUM_BUTTONS_AND_TEXT_FIELDS; i++)
{
buttons[i].setEnabled(isConnectedToQwerk);
textFields[i].setEnabled(isConnectedToQwerk);
}
messageTextArea.setEnabled(isConnectedToQwerk);
pauseResumeVideoButton.setEnabled(isConnectedToQwerk);
pauseResumeVideoButton.setText("Start Video");
}
});
// CONFIGURE GUI ELEMENTS ========================================================================================
// create and configure the buttons and text fields
for (int i = 0; i < NUM_BUTTONS_AND_TEXT_FIELDS; i++)
{
final JButton button = new JButton();
button.setFont(GUIConstants.FONT_SMALL);
button.setEnabled(false);
button.setOpaque(false);// required for Macintosh
buttons[i] = button;
textFields[i] = new JTextField(TEXT_FIELD_COLUMNS);
final Dimension fieldSize = new Dimension(textFields[i].getWidth(), textFields[i].getHeight());
textFields[i].setMaximumSize(fieldSize);
textFields[i].setEnabled(false);
}
// set up the message text area
messageTextArea.setFont(new Font("Monospaced", 0, 10));
messageTextArea.setLineWrap(true);
messageTextArea.setWrapStyleWord(true);
messageTextArea.setEditable(false);
messageTextArea.setEnabled(false);
final JScrollPane messageTextAreaScrollPane = new JScrollPane(messageTextArea,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
// add action listeners to the buttons
buttons[0].setText("Get State");
buttons[0].addActionListener(new GetQwerkStateAction());
buttons[1].setText("Move Motor X");
buttons[1].addActionListener(new MoveMotorAction(1));
buttons[2].setText("Move Servo 0");
buttons[2].addActionListener(new MoveServoAction(2, 0));
buttons[3].setText("Set Dig Out X On");
buttons[3].addActionListener(new SingleDigitalOutAction(3, true));
buttons[4].setText("Set Dig Out X Off");
buttons[4].addActionListener(new SingleDigitalOutAction(4, false));
buttons[5].setText("Speed Test");
buttons[5].addActionListener(new SpeedTestAction());
buttons[6].setText("Your Code");
buttons[7].setText("Your Code");
savePictureButton.addActionListener(new SavePictureActionListener(this, getVideoStreamViewport().getComponent(), ImageFormat.JPEG));
pauseResumeVideoButton.addActionListener(new PauseResumeVideoAction());
clearMessageAreaButton.addActionListener(
new ActionListener()
{
public void actionPerformed(final ActionEvent actionEvent)
{
messageTextArea.setText("");
}
});
// compute and display frames per second
getVideoStreamPlayer().addVideoStreamEventListener(
new VideoStreamEventListener()
{
public void handleFrame(final byte[] frameData)
{
fpsCount++;
if (fpsCount == FPS_FRAME_COUNT)
{
final long elapsedMilliseconds = System.currentTimeMillis() - fpsTimestamp;
fps = FPS_FRAME_COUNT_TIMES_1000 / (float)elapsedMilliseconds;
updateFramesPerSecondLabel();
fpsTimestamp = System.currentTimeMillis();
fpsCount = 0;
}
}
});
updateFramesPerSecondLabel();
// LAYOUT GUI ELEMENTS ===========================================================================================
// create a JPanel to hold the buttons and text fields
final JPanel buttonsAndTextFieldsPanel = new JPanel(new SpringLayout());
for (int i = 0; i < NUM_BUTTONS_AND_TEXT_FIELDS; i++)
{
buttonsAndTextFieldsPanel.add(buttons[i]);
buttonsAndTextFieldsPanel.add(Box.createRigidArea(SPACER_DIMENSIONS));
buttonsAndTextFieldsPanel.add(textFields[i]);
}
SpringLayoutUtilities.makeCompactGrid(buttonsAndTextFieldsPanel,
NUM_BUTTONS_AND_TEXT_FIELDS, 3, // rows, cols
0, 0, // initX, initY
0, 5);// xPad, yPad
// create a JPanel to hold the buttons, text fields, and color panel
final JPanel videoButtonsPanel = new JPanel(new SpringLayout());
videoButtonsPanel.add(savePictureButton);
videoButtonsPanel.add(Box.createRigidArea(new Dimension(10, 10)));
videoButtonsPanel.add(pauseResumeVideoButton);
videoButtonsPanel.add(Box.createGlue());
videoButtonsPanel.add(framesPerSecondLabel);
SpringLayoutUtilities.makeCompactGrid(videoButtonsPanel,
1, 5, // rows, cols
0, 0, // initX, initY
0, 0);// xPad, yPad
// create a JPanel to hold the buttons, text fields, and color panel
final JPanel videoPanel = new JPanel(new SpringLayout());
videoPanel.add(getVideoStreamViewportComponent());
videoPanel.add(Box.createRigidArea(SPACER_DIMENSIONS));
videoPanel.add(videoButtonsPanel);
SpringLayoutUtilities.makeCompactGrid(videoPanel,
3, 1, // rows, cols
0, 0, // initX, initY
0, 0);// xPad, yPad
// create a JPanel to hold video port and the buttons
final JPanel controlsPanel = new JPanel(new SpringLayout());
controlsPanel.add(getConnectDisconnectButton());
controlsPanel.add(getConnectionStatePanel());
controlsPanel.add(videoPanel);
controlsPanel.add(buttonsAndTextFieldsPanel);
SpringLayoutUtilities.makeCompactGrid(controlsPanel,
2, 2, // rows, cols
0, 0, // initX, initY
10, 10);// xPad, yPad
// create a JPanel to hold video port and the buttons
final JPanel messageAreaButtonsPanel = new JPanel(new SpringLayout());
messageAreaButtonsPanel.add(Box.createGlue());
messageAreaButtonsPanel.add(clearMessageAreaButton);
SpringLayoutUtilities.makeCompactGrid(messageAreaButtonsPanel,
1, 2, // rows, cols
0, 0, // initX, initY
0, 0);// xPad, yPad
// create a JPanel to hold video port and the buttons
final JPanel messageArea = new JPanel(new SpringLayout());
messageArea.add(messageTextAreaScrollPane);
messageArea.add(messageAreaButtonsPanel);
SpringLayoutUtilities.makeCompactGrid(messageArea,
2, 1, // rows, cols
0, 0, // initX, initY
0, 5);// xPad, yPad
// Layout the main content pane using SpringLayout
getMainContentPane().setLayout(new SpringLayout());
getMainContentPane().add(controlsPanel);
getMainContentPane().add(messageArea);
SpringLayoutUtilities.makeCompactGrid(getMainContentPane(),
2, 1, // rows, cols
10, 10, // initX, initY
10, 10);// xPad, yPad
// ADDITIONAL GUI ELEMENT CONFIGURATION ==========================================================================
// pack the window so the GUI elements are properly sized
pack();
// limit the text area's size (must do this AFTER the call to pack())
final Dimension messageTextAreaScrollPaneDimensions = new Dimension(messageTextArea.getWidth(), messageTextArea.getHeight());
messageTextAreaScrollPane.setPreferredSize(messageTextAreaScrollPaneDimensions);
messageTextAreaScrollPane.setMinimumSize(messageTextAreaScrollPaneDimensions);
messageTextAreaScrollPane.setMaximumSize(new Dimension(10000, messageTextArea.getHeight()));
pack();
setLocationRelativeTo(null);// center the window on the screen
setVisible(true);
}
private void updateFramesPerSecondLabel()
{
SwingUtilities.invokeLater(fpsDisplayRunnable);
}
/** Appends the given <code>message</code> to the message text area */
private void appendMessage(final String message)
{
SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
messageTextArea.append(dateFormatter.format(new Date()) + message + LINE_SEPARATOR);
messageTextArea.setCaretPosition(messageTextArea.getDocument().getLength());
}
});
}
/** Retrieves the value from the specified text field as an <code>int</code>. */
@SuppressWarnings({"UnusedCatchParameter"})
private int getTextFieldValueAsInt(final int textFieldIndex)
{
final int i;
final String str = getTextFieldValueAsString(textFieldIndex);
try
{
i = Integer.parseInt(str);
}
catch (NumberFormatException e)
{
appendMessage("NumberFormatException while trying to convert [" + str + "] into an int. Returning 0 instead.");
return 0;
}
return i;
}
/** Retrieves the value from the specified text field as a {@link String}. */
@SuppressWarnings({"UnusedCatchParameter"})
private String getTextFieldValueAsString(final int textFieldIndex)
{
if (SwingUtilities.isEventDispatchThread())
{
final String textFieldValue;
try
{
final String text1 = textFields[textFieldIndex].getText();
textFieldValue = (text1 != null) ? text1.trim() : null;
}
catch (Exception e)
{
appendMessage("Exception while getting the value from text field " + textFieldIndex + ". Returning null instead.");
return null;
}
return textFieldValue;
}
else
{
final String[] textFieldValue = new String[1];
try
{
SwingUtilities.invokeAndWait(
new Runnable()
{
public void run()
{
textFieldValue[0] = textFields[textFieldIndex].getText();
}
});
}
catch (Exception e)
{
LOG.error("Exception while getting the value from text field " + textFieldIndex, e);
appendMessage("Exception while getting the value from text field " + textFieldIndex + ". Returning null instead.");
return null;
}
return textFieldValue[0];
}
}
private class PauseResumeVideoAction extends AbstractTimeConsumingAction
{
private PauseResumeVideoAction()
{
super(PrototypingPlayground.this);
}
protected void executeGUIActionBefore()
{
PrototypingPlayground.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
if (isVideoStreamPaused)
{
pauseResumeVideoButton.setText("Pause Video");
}
else
{
pauseResumeVideoButton.setText("Resume Video");
}
}
protected Object executeTimeConsumingAction()
{
if (isVideoStreamPaused)
{
getVideoStreamPlayer().resumeVideoStream();
}
else
{
getVideoStreamPlayer().pauseVideoStream();
}
return null;
}
protected void executeGUIActionAfter(final Object resultOfTimeConsumingAction)
{
isVideoStreamPaused = !isVideoStreamPaused;
PrototypingPlayground.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
fpsTimestamp = System.currentTimeMillis();
fpsCount = 0;
fps = 0;
updateFramesPerSecondLabel();
}
}
private final class GetQwerkStateAction extends AbstractTimeConsumingAction
{
private GetQwerkStateAction()
{
super(PrototypingPlayground.this);
}
protected Object executeTimeConsumingAction()
{
return getQwerkController().getQwerkState();
}
protected void executeGUIActionAfter(final Object resultOfTimeConsumingAction)
{
// read the values from QwerkState and format it nicely for display in the message area
final QwerkState state = (QwerkState)resultOfTimeConsumingAction;
if (state != null)
{
final StringBuffer s = new StringBuffer("Qwerk State:" + LINE_SEPARATOR);
if (state.analogIn != null)
{
s.append(" Analog Inputs: ").append(ArrayUtils.arrayToString(state.analogIn.analogInValues)).append(LINE_SEPARATOR);
}
if (state.button != null)
{
s.append(" Button State: ").append(state.button.buttonStates[0]).append(LINE_SEPARATOR);
}
if (state.digitalIn != null)
{
s.append(" Digital Inputs: ").append(ArrayUtils.arrayToString(state.digitalIn.digitalInStates)).append(LINE_SEPARATOR);
}
if (state.motor != null)
{
s.append(" Motor Currents: ").append(ArrayUtils.arrayToString(state.motor.motorCurrents)).append(LINE_SEPARATOR);
s.append(" Motor Positions: ").append(ArrayUtils.arrayToString(state.motor.motorPositions)).append(LINE_SEPARATOR);
s.append(" Motor Velocities: ").append(ArrayUtils.arrayToString(state.motor.motorVelocities)).append(LINE_SEPARATOR);
s.append(" Motor Done: ").append(ArrayUtils.arrayToString(state.motor.motorDone)).append(LINE_SEPARATOR);
}
if (state.servo != null)
{
s.append(" Servo Positions: ").append(ArrayUtils.arrayToString(state.servo.servoPositions)).append(LINE_SEPARATOR);
}
if (state.battery != null)
{
s.append(" Battery Voltage: ").append(state.battery.batteryVoltage).append(LINE_SEPARATOR);
}
// display the state in the message area
appendMessage(s.toString());
}
else
{
appendMessage("QwerkState is null!");
}
}
}
private final class MoveMotorAction extends AbstractTimeConsumingAction
{
private final int buttonIndex;
private MoveMotorAction(final int buttonIndex)
{
super(PrototypingPlayground.this);
this.buttonIndex = buttonIndex;
}
protected Object executeTimeConsumingAction()
{
// get the motor index
final int motorIndex = getTextFieldValueAsInt(buttonIndex);
// set the motor velocity
getQwerkController().getMotorService().setMotorVelocity(20000, motorIndex);
// sleep for 5 seconds
try
{
Thread.sleep(5000);
}
catch (InterruptedException e1)
{
LOG.error("InterruptedException while sleeping", e1);
}
// stop the motor
getQwerkController().getMotorService().stopMotors(motorIndex);
return null;
}
}
private final class MoveServoAction extends AbstractTimeConsumingAction
{
private final int buttonIndex;
private final int servoIndex;
private MoveServoAction(final int buttonIndex, final int servoIndex)
{
super(PrototypingPlayground.this);
this.buttonIndex = buttonIndex;
this.servoIndex = servoIndex;
}
protected Object executeTimeConsumingAction()
{
// get the desired servo position
final int servoPosition = getTextFieldValueAsInt(buttonIndex);
// set the servo position
getQwerkController().getServoService().setPosition(servoIndex, servoPosition);
return null;
}
}
private final class SingleDigitalOutAction extends AbstractTimeConsumingAction
{
private final boolean digitalOutState;
private final int buttonIndex;
private SingleDigitalOutAction(final int buttonIndex, final boolean digitalOutState)
{
super(PrototypingPlayground.this);
this.buttonIndex = buttonIndex;
this.digitalOutState = digitalOutState;
}
protected Object executeTimeConsumingAction()
{
// get the desired digital out port
final int digitalOutPort = getTextFieldValueAsInt(buttonIndex);
appendMessage("Sending [" + digitalOutState + "] to digital out port [" + digitalOutPort + "]...");
// set the digital out
getQwerkController().getDigitalOutService().setOutputs(digitalOutState, digitalOutPort);
appendMessage("Done sending digital out command!");
return null;
}
}
private class SpeedTestAction extends AbstractTimeConsumingAction
{
private static final int NUM_CALLS = 50;
private SpeedTestAction()
{
super(PrototypingPlayground.this);
}
protected Object executeTimeConsumingAction()
{
final long[] millisecondsPerCall = new long[NUM_CALLS];
final QwerkController qwerkController = getQwerkController();
for (int i = 0; i < NUM_CALLS; i++)
{
final long startTime = System.currentTimeMillis();
qwerkController.getQwerkState();
final long endTime = System.currentTimeMillis();
millisecondsPerCall[i] = endTime - startTime;
}
return millisecondsPerCall;
}
protected void executeGUIActionAfter(final Object resultOfTimeConsumingAction)
{
final long[] millisecondsPerCall = (long[])resultOfTimeConsumingAction;
final StringBuffer str = new StringBuffer("Milliseconds per call: " + LINE_SEPARATOR);
int sum = 0;
for (int i = 0; i < NUM_CALLS; i++)
{
str.append(" ").append(millisecondsPerCall[i]).append(LINE_SEPARATOR);
sum += millisecondsPerCall[i];
}
str.append(" Total: ").append(sum).append(" ms");
str.append(" Average: ").append(sum / (double)NUM_CALLS).append(" ms");
appendMessage(str.toString());
}
}
private final class FPSDisplayRunnable implements Runnable
{
private final NumberFormat decimalFormatter = new DecimalFormat("#,##0.0");
public void run()
{
PrototypingPlayground.this.framesPerSecondLabel.setText(decimalFormatter.format(fps) + " fps");
}
}
}
|
[
"garthabrindoid@d0be9c17-995f-9cf9-1220-f3b097b0743e"
] |
garthabrindoid@d0be9c17-995f-9cf9-1220-f3b097b0743e
|
72fde31f012995a081d62683f1673982b50bfe0a
|
678a3d58c110afd1e9ce195d2f20b2531d45a2e0
|
/sources/com/airbnb/android/lib/views/RatingCell.java
|
980f9b65ed2ad7becf2d1920a4961f184a825885
|
[] |
no_license
|
jasonnth/AirCode
|
d1c37fb9ba3d8087efcdd9fa2103fb85d13735d5
|
d37db1baa493fca56f390c4205faf5c9bbe36604
|
refs/heads/master
| 2020-07-03T08:35:24.902940
| 2019-08-12T03:34:56
| 2019-08-12T03:34:56
| 201,842,970
| 0
| 2
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 3,165
|
java
|
package com.airbnb.android.lib.views;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.airbnb.android.lib.C0880R;
import com.airbnb.android.utils.ViewUtils;
import com.airbnb.p027n2.utils.ViewLibUtils;
import java.text.DecimalFormat;
public class RatingCell extends FrameLayout {
@BindView
View divider;
@BindView
RatingBar ratingBar;
@BindView
View ratingBarContainer;
private final DecimalFormat ratingFormatter = new DecimalFormat("0.0");
@BindView
TextView ratingText;
@BindView
TextView titleTextView;
private enum RatingStyle {
FiveStarBar,
TextWithSingleStar
}
public RatingCell(Context context) {
super(context);
init(null);
}
public RatingCell(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public RatingCell(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
private void init(AttributeSet attrs) {
LayoutInflater.from(getContext()).inflate(C0880R.layout.view_rating_cell, this);
ButterKnife.bind((View) this);
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, C0880R.styleable.RatingCell, 0, 0);
if (a != null) {
String titleText = a.getString(C0880R.styleable.RatingCell_title);
boolean showDivder = a.getBoolean(C0880R.styleable.RatingCell_lib_showDivider, true);
RatingStyle ratingStyle = RatingStyle.values()[a.getInt(C0880R.styleable.RatingCell_ratingStyle, RatingStyle.FiveStarBar.ordinal())];
ViewLibUtils.setVisibleIf(this.ratingText, RatingStyle.TextWithSingleStar.equals(ratingStyle));
ViewLibUtils.setVisibleIf(this.ratingBar, RatingStyle.FiveStarBar.equals(ratingStyle));
setTitle(titleText);
setDividerEnabled(showDivder);
a.recycle();
}
}
}
public void setRating(float rating) {
if (this.ratingBar.getVisibility() == 0) {
this.ratingBar.setRating(rating);
} else {
this.ratingText.setText(this.ratingFormatter.format((double) rating));
}
}
public void setDividerEnabled(boolean showDivder) {
ViewUtils.setVisibleIf(this.divider, showDivder);
}
public void setTitle(String titleText) {
this.titleTextView.setText(titleText);
}
public void setTitle(int titleRes) {
this.titleTextView.setText(titleRes);
}
public void setHorizontalPadding(int horizontalPadding) {
int padding = getResources().getDimensionPixelOffset(horizontalPadding);
this.ratingBarContainer.setPadding(0, 0, padding, 0);
this.titleTextView.setPadding(padding, 0, 0, 0);
}
}
|
[
"thanhhuu2apc@gmail.com"
] |
thanhhuu2apc@gmail.com
|
0cac19df90571b137c18a13e559e5659ca0d34f0
|
a43eaa81b5e06dbfcae87a61f35d956406065d5b
|
/addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/SessionHelper.java
|
4139424259119707546a19f2c283caa49cdcb901
|
[
"Apache-2.0"
] |
permissive
|
ekatanaev/java_first_lesson
|
7658939a6e2647621314b206b020189d43faea7f
|
57b6ac3185d2e8ad8812c9e230ec755fe7acf72a
|
refs/heads/master
| 2021-01-12T08:25:57.049690
| 2017-02-16T15:23:39
| 2017-02-16T15:23:39
| 76,577,552
| 0
| 0
| null | 2017-01-11T16:40:28
| 2016-12-15T16:40:39
|
Java
|
UTF-8
|
Java
| false
| false
| 497
|
java
|
package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
/**
* Created by e.katanaev on 11.01.2017.
*/
public class SessionHelper extends HelperBase {
public SessionHelper(WebDriver wd) {
super(wd);
}
public void login(String username, String password) {
type(By.name("user"), username);
type(By.name("pass"), password);
click(By.id("LoginForm"));
click(By.xpath("//form[@id='LoginForm']/input[3]"));
}
}
|
[
"evgenykatanaev@gmail.com"
] |
evgenykatanaev@gmail.com
|
ec3d2035a11497240506247eaf7389aa20416c79
|
60f4b232f9010c9ca9508810e8e859a48e844483
|
/src/main/java/org/agave/client/auth/OAuth.java
|
65134426e461f061195923e37ccf4752f7378509
|
[] |
no_license
|
deardooley/agave-java-sdk
|
0ea9e0c1dc393fe2727d5f4b0c1fc8139db22d4b
|
6a06f7bcceb77483298b0de3173e3b309f499052
|
refs/heads/master
| 2021-01-19T23:57:07.683893
| 2017-04-22T07:43:29
| 2017-04-22T07:43:29
| 89,052,276
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 681
|
java
|
package org.agave.client.auth;
import java.util.Map;
import java.util.List;
import org.agave.client.Pair;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2017-04-18T09:43:56.622Z")
public class OAuth implements Authentication {
private String accessToken;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
if (accessToken != null) {
headerParams.put("Authorization", "Bearer " + accessToken);
}
}
}
|
[
"dooley@tacc.utexas.edu"
] |
dooley@tacc.utexas.edu
|
aa99aeea13e56e8ba56b14542bd6142187c0610a
|
6ce6cacff3a1b8debf0cea70c65e9c0ea84f50eb
|
/src/kr/htw398/searchimage/DownloadImageTask.java
|
c5a10e8d2e6a2526135310e202293dd7a1966bea
|
[] |
no_license
|
htw398/searchImagebyhtw
|
98ac75d5362c93855135c090650b6758154e46ad
|
6b6959737ce1e77ed47bd7c7584bc8136d77351e
|
refs/heads/master
| 2020-06-02T14:21:40.973866
| 2013-11-27T08:46:35
| 2013-11-27T08:46:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,026
|
java
|
package kr.htw398.searchimage;
import java.io.InputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
/**
* @author kenu
* code referred from: http://stackoverflow.com/a/12088203/510222
*/
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
@Override
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
@Override
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
|
[
"htw398@gmail.com"
] |
htw398@gmail.com
|
20235bc2b31c2d0e4fd3f4421e1a0550079ad742
|
ad8cb30031963eaa8a67fe91146043ae59238603
|
/wlgdo-web-hido/src/main/java/com/wlgdo/hido/domain/UserPo.java
|
a301e9dce02c800d5192ab7af5fd247e35687a58
|
[] |
no_license
|
wligang/wlgdo
|
82b69c0c7cea1ee075477b771d74c208d335d218
|
0b67c566243aad55bd6c7855bed968fb67cc2c76
|
refs/heads/master
| 2022-03-26T22:31:34.700625
| 2019-12-23T15:53:03
| 2019-12-23T15:53:03
| 113,079,396
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,245
|
java
|
package com.wlgdo.hido.domain;
import java.util.Date;
public class UserPo {
private String uid;
private String accname;
private String password;
private String declaration;
private String email;
private String url;
private String phone;
private String gender;
private String nick;
private String hobby;
private Date ctime;
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getAccname() {
return accname;
}
public void setAccname(String accname) {
this.accname = accname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDeclaration() {
return declaration;
}
public void setDeclaration(String declaration) {
this.declaration = declaration;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public Date getCtime() {
return ctime;
}
public void setCtime(Date ctime) {
this.ctime = ctime;
}
@Override
public String toString() {
return "UserPo [uid=" + uid + ", accname=" + accname + ", password=" + password + ", declaration=" + declaration
+ ", email=" + email + ", phone=" + phone + ", gender=" + gender + ", nick=" + nick + ", hobby=" + hobby
+ ", ctime=" + ctime + "]";
}
}
|
[
"wang_lg@suixingpay.com"
] |
wang_lg@suixingpay.com
|
7586007bb5cd1e81444c5a72b19814bb7efdd9af
|
f6c2aec7e8e0227daf23166227bf7e6a0c3e16e1
|
/Improve/Access-specifiers/src/Private/com/zemoso/A.java
|
04d0dd36c86a4d606804210a3e534f4afd81911c
|
[] |
no_license
|
jayanth-1/Problem-solving
|
bf1294ae04630a22393080551974dc6db566bc07
|
21b549cdd8076dabae41ff5a85d5d1c88535ef26
|
refs/heads/master
| 2020-03-26T01:07:37.599505
| 2018-09-10T12:09:26
| 2018-09-10T12:09:26
| 144,352,803
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 291
|
java
|
package Private.com.zemoso;
public class A {
private void print(){
System.out.println("Hi world!!");
}
void display(){
System.out.println("This is display method");
}
public void show(){
System.out.println("This is show method");
}
}
|
[
"apoorjayanth1@gmail.com"
] |
apoorjayanth1@gmail.com
|
1d482fbc4d7a18869677ce519e61c71f2c4c31bb
|
ebbc1faf0aba826ffa02f8bea24dfeb01646a6ab
|
/Test/com/lehuo/ui/ScoreMarketActivityTest.java
|
9947a7db3d3449cef30b62b87945b393794999a0
|
[] |
no_license
|
jacknoerror/lehuoRepo
|
bcc279b99fc0a5b9048fb37c4e9fc7bae125ec8f
|
cf56c4d8e5e60dc756824d91ca68cf222245fe1e
|
refs/heads/master
| 2016-09-06T15:54:26.692099
| 2015-01-04T03:15:15
| 2015-01-04T03:15:15
| 19,365,050
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,334
|
java
|
package com.lehuo.ui;
import android.content.Intent;
import android.os.SystemClock;
import android.test.ActivityInstrumentationTestCase2;
import com.lehuozu.data.MyData;
import com.lehuozu.ui.courier.DeliverListActivity;
import com.lehuozu.ui.product.ProductListActivity;
import com.lehuozu.ui.tab.my.MyCouponActivity;
import com.lehuozu.ui.tab.my.ScoreMarcketActivity;
import com.lehuozu.ui.tab.order.ConfirmOrderActivity;
import com.lehuozu.vo.Category;
import com.lehuozu.vo.User;
public class ScoreMarketActivityTest extends ActivityInstrumentationTestCase2<ScoreMarcketActivity> {
public ScoreMarketActivityTest(){
super(ScoreMarcketActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
setActivityIntent(new Intent());
}
@Override
public void setActivityIntent(Intent i) {
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// i.putExtra(NetConst.EXTRA_PHONE, "15888889999");
User user = new User();
user.setUser_id(18);
MyData.data().setCurrentUser(user);
super.setActivityIntent(i);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testPCTest() {
// fail("Not yet implemented");
// assertEquals(2, );
assertNotNull(getActivity());
SystemClock.sleep(1000*120);
}
}
|
[
"jackinpeace@gmail.com"
] |
jackinpeace@gmail.com
|
6ab5325ce9261fc0f2e47ab467c3651a22de0b7a
|
558df4cc0edfa11e917ee7f6aede586cd8587fac
|
/Electricos/src/cats/SerNotVent.java
|
d7eab9a39ba6e4f784e34b67347ed0966a93b456
|
[] |
no_license
|
njmube/SOSDev
|
58ed1bbac2bdb91536b20017713127741f944ab8
|
7b9d44de6ec1d61ae7f6bf18184f4b51b55972c0
|
refs/heads/master
| 2020-06-10T12:22:45.426839
| 2015-12-18T17:45:14
| 2015-12-18T17:45:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 67,589
|
java
|
//Paquete
package cats;
//Importaciones
import java.awt.Color;
import java.awt.Cursor;
import static ptovta.Princip.bIdle;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import ptovta.Star;
import ptovta.Login;
/*Clase para controlar las series de las notas de crédito*/
public class SerNotVent extends javax.swing.JFrame
{
/*Declara variables de instancia*/
private String sSerOriG;
private String sDescOriG;
private String sConsecOriG;
/*Declara contadores globales*/
private int iContCellEd;
private int iContFi;
/*Variable que contiene el borde actual*/
private Border bBordOri;
/*Para controlar si seleccionar todo o deseleccionarlo de la tabla*/
private boolean bSel;
/*Constructor sin argumentos*/
public SerNotVent()
{
/*Inicaliza los componentes gráficos*/
initComponents();
/*Establece el botón por default*/
this.getRootPane().setDefaultButton(jBNew);
/*Para que no se muevan las columnas*/
jTab.getTableHeader().setReorderingAllowed(false);
/*Esconde el link de ayuda*/
jLAyu.setVisible(false);
/*Centra la ventana*/
this.setLocationRelativeTo(null);
/*Inicialmente esta deseleccionada la tabla*/
bSel = false;
/*Establece el titulo de la ventana con El usuario, la fecha y hora*/
this.setTitle("Series notas de crédito, Usuario: <" + Login.sUsrG + "> " + Login.sFLog);
//Establece el ícono de la forma
Star.vSetIconFram(this);
/*Para que la tabla este ordenada al mostrarce y al dar clic en el nombre de la columna*/
TableRowSorter trs = new TableRowSorter<>((DefaultTableModel)jTab.getModel());
jTab.setRowSorter(trs);
trs.setSortsOnUpdates(true);
/*Pon el foco del teclado en el campo de la ser*/
jTSer.grabFocus();
/*Establece el tamaño de las columnas de la tabla de series*/
jTab.getColumnModel().getColumn(0).setPreferredWidth(20);
jTab.getColumnModel().getColumn(2).setPreferredWidth(250);
/*Activa en la tabla que se usen normamente las teclas de tabulador*/
jTab.setFocusTraversalKeys(java.awt.KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
jTab.setFocusTraversalKeys(java.awt.KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);
/*Inicializa el contador de filas en uno*/
iContFi = 1;
/*Incializa el contador del cell editor*/
iContCellEd = 1;
/*Obtén todas las series de la base de datos y cargalas en la tabla*/
vCargSer();
/*Crea el listener para la tabla de series, para cuando se modifique una celda guardarlo en la base de datos el cambio*/
PropertyChangeListener pr = new PropertyChangeListener()
{
@Override
public void propertyChange(PropertyChangeEvent event)
{
/*Obtén la propiedad que a sucedio en el control*/
String pro = event.getPropertyName();
/*Si el evento fue por entrar en una celda de la tabla*/
if("tableCellEditor".equals(pro))
{
/*Si el contador de cell editor está en 1 entonces que lea el valor original que estaba ya*/
if(iContCellEd==1)
{
/*Si no hay selecciòn entonces regresa*/
if(jTab.getSelectedRow()==-1)
return;
/*Obtiene algunos datos originales*/
sSerOriG = jTab.getValueAt(jTab.getSelectedRow(), 1).toString();
sDescOriG = jTab.getValueAt(jTab.getSelectedRow(), 2).toString();
sConsecOriG = jTab.getValueAt(jTab.getSelectedRow(), 3).toString();
/*Aumenta el cell editor para saber que ya va de salida*/
++iContCellEd;
}
/*Else, el contador de cell editor es 2, osea que va de salida*/
else
{
/*Reinicia el contador*/
iContCellEd = 1;
/*Coloca los valores originales*/
jTab.setValueAt(sSerOriG, jTab.getSelectedRow(), 1);
/*Obtén algunos datos de la fila nuevos*/
String sDescrip = jTab.getValueAt(jTab.getSelectedRow(), 2).toString();
String sConsec = jTab.getValueAt(jTab.getSelectedRow(), 3).toString();
/*Si la descripción es cadena vacia entonces*/
if(sDescrip.compareTo("")==0)
{
/*La descripción será la original*/
sDescrip = sDescOriG;
/*Coloca la descripción correcta en la fila*/
jTab.setValueAt(sDescrip, jTab.getSelectedRow(), 2);
}
/*Si el consecutivo no es un número entonces*/
try
{
/*Intenta convertirlo a double*/
Double.parseDouble(sConsec);
/*Deja el valor absoluto solamente*/
sConsec = Integer.toString(new Double(Math.abs(Double.parseDouble(sConsec))).intValue());
/*Colocalo en su lugar*/
jTab.setValueAt(sConsec, jTab.getSelectedRow(), 3);
}
catch(NumberFormatException expnNumForm)
{
/*Coloca en la fila el consecutivo original que tenía y regresa*/
jTab.setValueAt(sConsecOriG, jTab.getSelectedRow(), 3);
return;
}
//Abre la base de datos
Connection con = Star.conAbrBas(true, false);
//Si hubo error entonces regresa
if(con==null)
return;
//Declara variables de la base de datos
Statement st;
ResultSet rs;
String sQ;
/*Si lo que se modificó fue el consecutivo entonces*/
if(sConsec.compareTo(sConsecOriG)!=0)
{
/*Comprueba si el folio ya esta usado por medio de la serie en alguna venta de tickets*/
try
{
sQ = "SELECT noser FROM vtas WHERE noser = '" + sSerOriG + "' AND norefer = " + sConsec + " AND tipdoc = 'NOTC'";
st = con.createStatement();
rs = st.executeQuery(sQ);
/*Si hay datos, entonces si existe esta ser para alguna venta*/
if(rs.next())
{
//Cierra la base de datos
if(Star.iCierrBas(con)==-1)
return;
/*Mensajea*/
JOptionPane.showMessageDialog(null, "Este consecutivo ya fue asignado a alguna nota de crédito, no se puede modificar.", "Series", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(Star.sRutIconAd)));
/*Coloca en la fila el consecutivo original que tenía y regresa*/
jTab.setValueAt(sConsecOriG, jTab.getSelectedRow(), 3);
return;
}
}
catch(SQLException expnSQL)
{
//Procesa el error y regresa
Star.iErrProc(this.getClass().getName() + " " + expnSQL.getMessage(), Star.sErrSQL, expnSQL.getStackTrace(), con);
return;
}
}/*Fin de if(sConsec.compareTo(sConsecOriG)!=0)*/
/*Actualiza en la base de datos la serie y el consecutivo*/
try
{
sQ = "UPDATE consecs SET "
+ "consec = " + sConsec.replace("'", "''") + ", "
+ "descrip = '" + sDescrip.replace("'", "''").replace(",", "") + "', "
+ "fmod = now(), "
+ "estac = '" + Login.sUsrG.replace("'", "''") + "', "
+ "sucu = '" + Star.sSucu.replace("'", "''") + "', "
+ "nocaj = '" + Star.sNoCaj.replace("'", "''") + "' "
+ "WHERE ser = '" + sSerOriG.replace("'", "''") + "' AND tip = 'NOTC'";
st = con.createStatement();
st.executeUpdate(sQ);
}
catch(SQLException expnSQL)
{
//Procesa el error y regresa
Star.iErrProc(this.getClass().getName() + " " + expnSQL.getMessage(), Star.sErrSQL, expnSQL.getStackTrace(), con);
return;
}
//Cierra la base de datos
Star.iCierrBas(con);
}/*Fin de else*/
}/*Fin de if("tableCellEditor".equals(property)) */
}/*Fin de public void propertyChange(PropertyChangeEvent event) */
};
/*Establece el listener para la tabla de series*/
jTab.addPropertyChangeListener(pr);
}/*Fin de public Marcs() */
/*Obtén todas las series de la base de datos y cargalas en la tabla*/
private void vCargSer()
{
//Abre la base de datos
Connection con = Star.conAbrBas(true, false);
//Si hubo error entonces regresa
if(con==null)
return;
/*Crea el modelo para cargar cadenas en el*/
DefaultTableModel te = (DefaultTableModel)jTab.getModel();
//Declara variables de la base de datos
Statement st;
ResultSet rs;
String sQ;
/*Trae todas las series de la base de datos y cargalos en la tabla*/
try
{
sQ = "SELECT ser, descrip, consec FROM consecs WHERE tip = 'NOTC'";
st = con.createStatement();
rs = st.executeQuery(sQ);
/*Si hay datos*/
while(rs.next())
{
/*Agregalo a la tabla*/
Object nu[] = {iContFi, rs.getString("ser"), rs.getString("descrip"), rs.getString("consec")};
te.addRow(nu);
/*Aumenta en uno el contador de filas en uno*/
++iContFi;
}
}
catch(SQLException expnSQL)
{
//Procesa el error y regresa
Star.iErrProc(this.getClass().getName() + " " + expnSQL.getMessage(), Star.sErrSQL, expnSQL.getStackTrace(), con);
return;
}
//Cierra la base de datos
Star.iCierrBas(con);
}/*Fin de private void vCargSer()*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jP1 = new javax.swing.JPanel();
jBDel = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jBSal = new javax.swing.JButton();
jTSer = new javax.swing.JTextField();
jBNew = new javax.swing.JButton();
jTConsec = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
jTab = new javax.swing.JTable();
jBBusc = new javax.swing.JButton();
jTBusc = new javax.swing.JTextField();
jBMostT = new javax.swing.JButton();
jTDescrip = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jBTab1 = new javax.swing.JButton();
jLAyu = new javax.swing.JLabel();
jBTod = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setResizable(false);
addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
formMouseDragged(evt);
}
public void mouseMoved(java.awt.event.MouseEvent evt) {
formMouseMoved(evt);
}
});
addMouseWheelListener(new java.awt.event.MouseWheelListener() {
public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
formMouseWheelMoved(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
jP1.setBackground(new java.awt.Color(255, 255, 255));
jP1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jP1KeyPressed(evt);
}
});
jP1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jBDel.setBackground(new java.awt.Color(255, 255, 255));
jBDel.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
jBDel.setForeground(new java.awt.Color(0, 102, 0));
jBDel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/del.png"))); // NOI18N
jBDel.setText("Borrar");
jBDel.setToolTipText("Borrar Serie(s) (Ctrl+SUPR)");
jBDel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jBDel.setNextFocusableComponent(jBSal);
jBDel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jBDelMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jBDelMouseExited(evt);
}
});
jBDel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBDelActionPerformed(evt);
}
});
jBDel.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jBDelKeyPressed(evt);
}
});
jP1.add(jBDel, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 70, 100, 30));
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel1.setText("*Descripción:");
jP1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 10, 150, -1));
jBSal.setBackground(new java.awt.Color(255, 255, 255));
jBSal.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
jBSal.setForeground(new java.awt.Color(0, 102, 0));
jBSal.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/sal.png"))); // NOI18N
jBSal.setText("Salir");
jBSal.setToolTipText("Salir (ESC)");
jBSal.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jBSal.setNextFocusableComponent(jTSer);
jBSal.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jBSalMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jBSalMouseExited(evt);
}
});
jBSal.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBSalActionPerformed(evt);
}
});
jBSal.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jBSalKeyPressed(evt);
}
});
jP1.add(jBSal, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 100, 100, 30));
jTSer.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 255)));
jTSer.setNextFocusableComponent(jTConsec);
jTSer.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTSerFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTSerFocusLost(evt);
}
});
jTSer.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTSerKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTSerKeyTyped(evt);
}
});
jP1.add(jTSer, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 30, 90, 20));
jBNew.setBackground(new java.awt.Color(255, 255, 255));
jBNew.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
jBNew.setForeground(new java.awt.Color(0, 102, 0));
jBNew.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/agre.png"))); // NOI18N
jBNew.setText("Nuevo");
jBNew.setToolTipText("Nueva Serie (Ctrl+N)");
jBNew.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jBNew.setNextFocusableComponent(jTab);
jBNew.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jBNewMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jBNewMouseExited(evt);
}
});
jBNew.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBNewActionPerformed(evt);
}
});
jBNew.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jBNewKeyPressed(evt);
}
});
jP1.add(jBNew, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 30, 90, 20));
jTConsec.setText("1");
jTConsec.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 255)));
jTConsec.setNextFocusableComponent(jTDescrip);
jTConsec.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTConsecFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTConsecFocusLost(evt);
}
});
jTConsec.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTConsecActionPerformed(evt);
}
});
jTConsec.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTConsecKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
jTConsecKeyTyped(evt);
}
});
jP1.add(jTConsec, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 30, 90, 20));
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel3.setText("*Serie:");
jP1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, 100, -1));
jTab.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"No.", "Serie", "Descripción Serie", "Consecutivo"
}
) {
boolean[] canEdit = new boolean [] {
false, true, true, true
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTab.setGridColor(new java.awt.Color(255, 255, 255));
jTab.setNextFocusableComponent(jBBusc);
jTab.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
jTab.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTabKeyPressed(evt);
}
});
jScrollPane2.setViewportView(jTab);
jP1.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 70, 470, 250));
jBBusc.setBackground(new java.awt.Color(255, 255, 255));
jBBusc.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
jBBusc.setForeground(new java.awt.Color(0, 102, 0));
jBBusc.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/busc5.png"))); // NOI18N
jBBusc.setText("Buscar F3");
jBBusc.setName(""); // NOI18N
jBBusc.setNextFocusableComponent(jTBusc);
jBBusc.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jBBuscMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jBBuscMouseExited(evt);
}
});
jBBusc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBBuscActionPerformed(evt);
}
});
jBBusc.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jBBuscKeyPressed(evt);
}
});
jP1.add(jBBusc, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 320, 140, 20));
jTBusc.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 255)));
jTBusc.setNextFocusableComponent(jBMostT);
jTBusc.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTBuscFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTBuscFocusLost(evt);
}
});
jTBusc.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTBuscKeyPressed(evt);
}
});
jP1.add(jTBusc, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 320, 190, 20));
jBMostT.setBackground(new java.awt.Color(255, 255, 255));
jBMostT.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
jBMostT.setForeground(new java.awt.Color(0, 102, 0));
jBMostT.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/mostt.png"))); // NOI18N
jBMostT.setText("Mostrar F4");
jBMostT.setToolTipText("Mostrar Nuevamente todos los Registros");
jBMostT.setNextFocusableComponent(jBDel);
jBMostT.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jBMostTMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jBMostTMouseExited(evt);
}
});
jBMostT.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBMostTActionPerformed(evt);
}
});
jBMostT.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jBMostTKeyPressed(evt);
}
});
jP1.add(jBMostT, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 320, 140, 20));
jTDescrip.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 255)));
jTDescrip.setNextFocusableComponent(jBNew);
jTDescrip.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTDescripFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTDescripFocusLost(evt);
}
});
jTDescrip.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTDescripKeyPressed(evt);
}
});
jP1.add(jTDescrip, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 30, 260, 20));
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel4.setText("*Consecutivo:");
jP1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 10, 110, -1));
jBTab1.setBackground(new java.awt.Color(0, 153, 153));
jBTab1.setToolTipText("Mostrar Tabla en Grande");
jBTab1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBTab1ActionPerformed(evt);
}
});
jBTab1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jBTab1KeyPressed(evt);
}
});
jP1.add(jBTab1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, 10, 20));
jLAyu.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
jLAyu.setForeground(new java.awt.Color(0, 51, 204));
jLAyu.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLAyu.setText("http://Ayuda en Lìnea");
jLAyu.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jLAyuMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jLAyuMouseExited(evt);
}
});
jP1.add(jLAyu, new org.netbeans.lib.awtextra.AbsoluteConstraints(486, 330, 120, 30));
jBTod.setBackground(new java.awt.Color(255, 255, 255));
jBTod.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
jBTod.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/marct.png"))); // NOI18N
jBTod.setText("Marcar todo");
jBTod.setToolTipText("Marcar Todos los Registros de la Tabla (Alt+T)");
jBTod.setNextFocusableComponent(jTab);
jBTod.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jBTodMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jBTodMouseExited(evt);
}
});
jBTod.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBTodActionPerformed(evt);
}
});
jBTod.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jBTodKeyPressed(evt);
}
});
jP1.add(jBTod, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 52, 130, 18));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jP1, javax.swing.GroupLayout.DEFAULT_SIZE, 609, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jP1, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
/*Cuando se presiona el botón de borrar*/
private void jBDelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBDelActionPerformed
/*Si no hay selección en la tabla no puede seguir*/
if(jTab.getSelectedRow()==-1)
{
/*Mensajea*/
JOptionPane.showMessageDialog(null, "No has seleccionado una serie de la tabla para borrar.", "Borrar Serie", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(Star.sRutIconAd)));
/*Coloca el foco del teclado en la tabla y regres*/
jTab.grabFocus();
return;
}
/*Preguntar al usuario si esta seguro de querer borrar*/
Object[] op = {"Si","No"};
int iRes = JOptionPane.showOptionDialog(this, "¿Seguro que quiere borrar la(s) ser(s)?", "Borrar Serie", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(Star.sRutIconDu)), op, op[0]);
if(iRes== JOptionPane.NO_OPTION || iRes== JOptionPane.CANCEL_OPTION)
return;
//Abre la base de datos
Connection con = Star.conAbrBas(true, false);
//Si hubo error entonces regresa
if(con==null)
return;
/*Para saber si hubo cambios*/
boolean bMod = false;
//Declara variables de la base de datos
Statement st;
ResultSet rs;
String sQ;
/*Recorre toda la selección del usuario*/
int iSel[] = jTab.getSelectedRows();
DefaultTableModel tm = (DefaultTableModel)jTab.getModel();
for(int x = iSel.length - 1; x >= 0; x--)
{
/*Comprueba si esta ser existe en alguna venta*/
try
{
sQ = "SELECT noser FROM vtas WHERE noser = '" + jTab.getValueAt(iSel[x], 1).toString() + "'";
st = con.createStatement();
rs = st.executeQuery(sQ);
/*Si hay datos, entonces si existe esta ser asociado a alguna venta*/
if(rs.next())
{
/*Mensajea y continua*/
JOptionPane.showMessageDialog(null, "Ya esta esta serie: " + jTab.getValueAt(iSel[x], 1).toString() + " asignada a alguna venta, no se puede eliminar.", "Series", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(Star.sRutIconAd)));
continue;
}
}
catch(SQLException expnSQL)
{
//Procesa el error y regresa
Star.iErrProc(this.getClass().getName() + " " + expnSQL.getMessage(), Star.sErrSQL, expnSQL.getStackTrace(), con);
return;
}
/*Borra la serie*/
try
{
sQ = "DELETE FROM consecs WHERE ser = '" + jTab.getValueAt(iSel[x], 1).toString() + "' AND tip = 'NOTC'";
st = con.createStatement();
st.executeUpdate(sQ);
}
catch(SQLException expnSQL)
{
//Procesa el error y regresa
Star.iErrProc(this.getClass().getName() + " " + expnSQL.getMessage(), Star.sErrSQL, expnSQL.getStackTrace(), con);
return;
}
/*Coloca la bandera para saber que si hubo cambios*/
bMod = true;
/*Borralo de la tabla*/
tm.removeRow(iSel[x]);
/*Resta en uno el contador de filas el contador de filas en uno*/
--iContFi;
}/*Fin de for(int x = 0; x < iSel.length; x++)*/
//Cierra la base de datos
if(Star.iCierrBas(con)==-1)
return;
/*Mensajea de éxito si hubo modificaciones*/
if(bMod)
JOptionPane.showMessageDialog(null, "Serie(s) borrada(s) con éxito.", "Series", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(Star.sRutIconAd)));
}//GEN-LAST:event_jBDelActionPerformed
/*Cuando se presiona una tecla en el formulario*/
private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
//Llama a la función escalable
vKeyPreEsc(evt);
}//GEN-LAST:event_formKeyPressed
/*Cuando se presiona una tecla en el botón de borrar*/
private void jBDelKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jBDelKeyPressed
//Llama a la función escalable
vKeyPreEsc(evt);
}//GEN-LAST:event_jBDelKeyPressed
/*Cuando se presiona una tecla en el panel*/
private void jP1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jP1KeyPressed
//Llama a la función escalable
vKeyPreEsc(evt);
}//GEN-LAST:event_jP1KeyPressed
/*Cuando se presiona el botón de salir*/
private void jBSalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBSalActionPerformed
/*Pregunta al usuario si esta seguro de salir*/
Object[] op = {"Si","No"};
if((JOptionPane.showOptionDialog(this, "¿Seguro que quieres salir?", "Salir", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(Star.sRutIconDu)), op, op[0])) == JOptionPane.YES_OPTION)
{
/*Llama al recolector de basura y cierra la forma*/
System.gc();
this.dispose();
}
}//GEN-LAST:event_jBSalActionPerformed
/*Cuando se presiona una tecla en el botón salir*/
private void jBSalKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jBSalKeyPressed
//Llama a la función escalable
vKeyPreEsc(evt);
}//GEN-LAST:event_jBSalKeyPressed
/*Cuando se presiona una tecla en el botón de agregar*/
private void jBNewKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jBNewKeyPressed
//Llama a la función escalable
vKeyPreEsc(evt);
}//GEN-LAST:event_jBNewKeyPressed
/*Cuando se presiona una tecla en el campo de edición de series*/
private void jTSerKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTSerKeyPressed
//Llama a la función escalable
vKeyPreEsc(evt);
}//GEN-LAST:event_jTSerKeyPressed
/*Cuando se gana el foco del teclado en el campo de edición de la ser*/
private void jTSerFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTSerFocusGained
/*Selecciona todo el texto cuando gana el foco*/
jTSer.setSelectionStart(0);jTSer.setSelectionEnd(jTSer.getText().length());
}//GEN-LAST:event_jTSerFocusGained
/*Cuando se presiona una tecla en el campo de descripción de ser*/
private void jTConsecKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTConsecKeyPressed
//Llama a la función escalable
vKeyPreEsc(evt);
}//GEN-LAST:event_jTConsecKeyPressed
/*Cuando se presiona una tecla en la tabla de series*/
private void jTabKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTabKeyPressed
//Llama a la función escalable
vKeyPreEsc(evt);
}//GEN-LAST:event_jTabKeyPressed
/*Cuando se gana el foco del teclado en el campo de edición de texto de descripción de la ser*/
private void jTConsecFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTConsecFocusGained
/*Selecciona todo el texto cuando gana el foco*/
jTConsec.setSelectionStart(0);jTConsec.setSelectionEnd(jTConsec.getText().length());
}//GEN-LAST:event_jTConsecFocusGained
/*Cuando se pierde el foco del teclado en el campo de la ser*/
private void jTSerFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTSerFocusLost
/*Coloca el caret en la posiciòn 0*/
jTSer.setCaretPosition(0);
/*Coloca el borde negro si tiene datos, caso contrario de rojo*/
if(jTSer.getText().compareTo("")!=0)
jTSer.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204,204,255)));
/*Si el campo excede la cantidad de caes permitidos recortalo*/
if(jTSer.getText().length()> 30)
jTSer.setText(jTSer.getText().substring(0, 30));
}//GEN-LAST:event_jTSerFocusLost
/*Cuando se pierde el foco del teclado en el campo de descripción*/
private void jTConsecFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTConsecFocusLost
/*Coloca el caret en la posiciòn 0*/
jTConsec.setCaretPosition(0);
/*Coloca el borde negro si tiene datos, caso contrario de rojo*/
if(jTConsec.getText().compareTo("")!=0)
jTConsec.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204,204,255)));
/*Si el campo excede la cantidad de caes permitidos recortalo*/
if(jTConsec.getText().length()> 21)
jTConsec.setText(jTConsec.getText().substring(0, 21));
/*Si el campo es cadena vacia entonces que sea 0*/
if(jTConsec.getText().compareTo("")==0)
jTConsec.setText("0");
}//GEN-LAST:event_jTConsecFocusLost
/*Cuando se presiona el botón de agregar*/
private void jBNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBNewActionPerformed
/*Si hay cadena vacia en el campo de la ser no puede continuar*/
if(jTSer.getText().replace(" ", "").trim().compareTo("")==0)
{
/*Coloca el borde rojo*/
jTSer.setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.RED));
/*Mensajea*/
JOptionPane.showMessageDialog(null, "La serie esta vacia.", "Campo vacio", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(Star.sRutIconAd)));
/*Pon el foco del teclado en el campo de edición y regresa*/
jTSer.grabFocus();
return;
}
/*Lee el folio de la ser que ingreso el usuario*/
String sConsec;
sConsec = jTConsec.getText();
/*Si hay cadena vacia en el consecutivo de la ser no puede continuar*/
if(sConsec.compareTo("")==0)
{
/*Coloca el borde rojo*/
jTConsec.setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.RED));
/*Mensajea*/
JOptionPane.showMessageDialog(null, "El campo del consecutivo esta vacio.", "Campo vacio", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(Star.sRutIconAd)));
/*Pon el foco del teclado en el campo de edición y regresa*/
jTConsec.grabFocus();
return;
}
/*Si hay cadena vacia en el campo de descripción de la ser no puede continuar*/
if(jTDescrip.getText().trim().compareTo("")==0)
{
/*Coloca el borde rojo*/
jTDescrip.setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.RED));
/*Mensajea*/
JOptionPane.showMessageDialog(null, "El campo de descripción de la ser esta vacio.", "Campo vacio", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(Star.sRutIconAd)));
/*Pon el foco del teclado en el campo de edición y regresa*/
jTDescrip.grabFocus();
return;
}
/*Pregunta al usuario si están bien los datos*/
Object[] op = {"Si","No"};
int iRes = JOptionPane.showOptionDialog(this, "¿Seguro que están bien los datos?", "Agregar serie", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(Star.sRutIconDu)), op, op[0]);
if(iRes== JOptionPane.NO_OPTION || iRes== JOptionPane.CANCEL_OPTION)
return;
//Abre la base de datos
Connection con = Star.conAbrBas(true, false);
//Si hubo error entonces regresa
if(con==null)
return;
//Declara variables de la base de datos
Statement st;
ResultSet rs;
String sQ;
/*Checa si la serie ya existe en la base de datos*/
try
{
sQ = "SELECT ser FROM consecs WHERE ser = '" + jTSer.getText().replace(" ", "").trim() + "' AND tip = 'NOTC'";
st = con.createStatement();
rs = st.executeQuery(sQ);
/*Si hay datos entonces si existe*/
if(rs.next())
{
//Cierra la base de datos
if(Star.iCierrBas(con)==-1)
return;
/*Coloca el borde rojo*/
jTSer.setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.RED));
/*Avisa al usuario*/
JOptionPane.showMessageDialog(null, "La serie: " + jTSer.getText().replace(" ", "").trim() + " ya existe.", "Registro Existente", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(Star.sRutIconAd)));
/*Pon el foco del teclado en el campo de la ser y regresa*/
jTSer.grabFocus();
return;
}
}
catch(SQLException expnSQL)
{
//Procesa el error y regresa
Star.iErrProc(this.getClass().getName() + " " + expnSQL.getMessage(), Star.sErrSQL, expnSQL.getStackTrace(), con);
return;
}
/*Guarda los datos en la base de datos*/
try
{
sQ = "INSERT INTO consecs( tip, ser, Descrip, consec, estac, sucu, nocaj) " +
"VALUES( 'NOTC', '" + jTSer.getText().replace(" ", "").replace(",", "").replace("'", "''").trim() + "', '" + jTDescrip.getText().trim().replace("'", "''").replace(",", "") + "'," + sConsec.replace("'", "''") + ", '" + Login.sUsrG.replace("'", "''") + "', '" + Star.sSucu.replace("'", "''") + "', '" + Star.sNoCaj.replace("'", "''") + "')";
st = con.createStatement();
st.executeUpdate(sQ);
}
catch(SQLException expnSQL)
{
//Procesa el error y regresa
Star.iErrProc(this.getClass().getName() + " " + expnSQL.getMessage(), Star.sErrSQL, expnSQL.getStackTrace(), con);
return;
}
//Cierra la base de datos
if(Star.iCierrBas(con)==-1)
return;
/*Agrega el registro de la ser en la tabla*/
DefaultTableModel te = (DefaultTableModel)jTab.getModel();
Object nu[] = {iContFi, jTSer.getText().replace(" ", "").trim(), jTDescrip.getText().trim(), sConsec};
te.addRow(nu);
/*Aumenta en uno el contador de filas en uno*/
++iContFi;
/*Pon el foco del teclado en el campo del código de la ser*/
jTSer.grabFocus();
/*Resetea los campos*/
jTSer.setText ("");
jTDescrip.setText ("");
jTConsec.setText ("0");
/*Mensajea de éxito*/
JOptionPane.showMessageDialog(null, "Serie: " + jTSer.getText().replace(" ", "").trim() + " agregada con éxito.", "Exito al agregar", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(Star.sRutIconAd)));
}//GEN-LAST:event_jBNewActionPerformed
/*Cuando se tipea una tecla en el campo de código de ser*/
private void jTSerKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTSerKeyTyped
/*Si el carácter introducido es minúscula entonces colocalo en el campo con mayúsculas*/
if(Character.isLowerCase(evt.getKeyChar()))
evt.setKeyChar(Character.toUpperCase(evt.getKeyChar()));
}//GEN-LAST:event_jTSerKeyTyped
/*Cuando se tipea una tecla en el campo de descripción de ser*/
private void jTConsecKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTConsecKeyTyped
/*Comprueba que el carácter este en los límites permitidos para numeración*/
if(((evt.getKeyChar() < '0') || (evt.getKeyChar() > '9')) && (evt.getKeyChar() != '\b') && (evt.getKeyChar() != '.'))
evt.consume();
}//GEN-LAST:event_jTConsecKeyTyped
/*Cuando se presiona una tecla en el botón de buscar*/
private void jBBuscKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jBBuscKeyPressed
//Llama a la función escalable
vKeyPreEsc(evt);
}//GEN-LAST:event_jBBuscKeyPressed
/*Cuando se gana el foco del teclado en el campo de buscar*/
private void jTBuscFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTBuscFocusGained
/*Establece el botón por default*/
this.getRootPane().setDefaultButton(jBBusc);
/*Selecciona todo el texto cuando gana el foco*/
jTBusc.setSelectionStart(0);jTBusc.setSelectionEnd(jTBusc.getText().length());
}//GEN-LAST:event_jTBuscFocusGained
/*Cuando se presiona una tecla en el campo de buscar*/
private void jTBuscKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTBuscKeyPressed
/*Si se presionó enter entonces presiona el botón de búsqueda y regresa*/
if(evt.getKeyCode() == KeyEvent.VK_ENTER)
{
jBBusc.doClick();
return;
}
//Llama a la función escalable
vKeyPreEsc(evt);
}//GEN-LAST:event_jTBuscKeyPressed
/*Cuando se presiona una tecla en el botón de mostrar todo*/
private void jBMostTKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jBMostTKeyPressed
//Llama a la función escalable
vKeyPreEsc(evt);
}//GEN-LAST:event_jBMostTKeyPressed
/*Función para mostrar los elementos actualizados en la tabla*/
private void vCargT()
{
/*Borra todos los item en la tabla*/
DefaultTableModel dm = (DefaultTableModel)jTab.getModel();
dm.setRowCount(0);
/*Resetea el contador de filas*/
iContFi = 1;
/*Obtén todas las series de la base de datos y cargalas en la tabla*/
vCargSer();
/*Vuelve a poner el foco del teclaod en el campo de buscar*/
jTBusc.grabFocus();
}
/*Cuando se presiona el botón de mostrar todo*/
private void jBMostTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBMostTActionPerformed
/*Función para mostrar los elementos actualizados en la tabla*/
vCargT();
}//GEN-LAST:event_jBMostTActionPerformed
/*Cuando se presiona el botón de buscar*/
private void jBBuscActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBBuscActionPerformed
/*Si el campo de buscar esta vacio no puede seguir*/
if(jTBusc.getText().compareTo("")==0)
{
/*Coloca el borde rojo*/
jTBusc.setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.RED));
/*Mensajea*/
JOptionPane.showMessageDialog(null, "El campo de búsqueda esta vacio.", "Campo vacio", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().getResource(Star.sRutIconAd)));
/*Coloca el foco del teclado en el campo de búsqueda y regresa*/
jTBusc.grabFocus();
return;
}
//Abre la base de datos
Connection con = Star.conAbrBas(true, false);
//Si hubo error entonces regresa
if(con==null)
return;
/*Borra todos los item en la tabla de series*/
DefaultTableModel dm = (DefaultTableModel)jTab.getModel();
dm.setRowCount(0);
/*Resetea el contador de filas*/
iContFi = 1;
//Declara variables de la base de datos
Statement st;
ResultSet rs;
String sQ;
/*Obtiene de la base de datos todoas las series*/
try
{
sQ = "SELECT ser, descrip, consec FROM consecs WHERE tip = 'NOTC' AND (ser LIKE('%" + jTBusc.getText().replace(" ", "%") + "%') OR descrip LIKE('%" + jTBusc.getText().replace(" ", "%") + "%') OR consec LIKE('%" + jTBusc.getText().replace(" ", "%") + "%'))";
st = con.createStatement();
rs = st.executeQuery(sQ);
/*Si hay datos*/
while(rs.next())
{
/*Cargalos en la tabla*/
DefaultTableModel te = (DefaultTableModel)jTab.getModel();
Object nu[] = {iContFi, rs.getString("ser"), rs.getString("descrip"), rs.getString("consec")};
te.addRow(nu);
/*Aumenta en uno el contador de filas*/
++iContFi;
}
}
catch(SQLException expnSQL)
{
//Procesa el error y regresa
Star.iErrProc(this.getClass().getName() + " " + expnSQL.getMessage(), Star.sErrSQL, expnSQL.getStackTrace(), con);
return;
}
//Cierra la base de datos
if(Star.iCierrBas(con)==-1)
return;
/*Vuelve a poner el foco del teclado en el campo de buscar*/
jTBusc.grabFocus();
}//GEN-LAST:event_jBBuscActionPerformed
/*Cuando se gana el foco del teclado en el campo de descripción*/
private void jTDescripFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTDescripFocusGained
/*Selecciona todo el texto cuando gana el foco*/
jTDescrip.setSelectionStart(0);jTDescrip.setSelectionEnd(jTDescrip.getText().length());
}//GEN-LAST:event_jTDescripFocusGained
/*Cuando se pierde el foco del teclado en el campo de la descripción*/
private void jTDescripFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTDescripFocusLost
/*Coloca el caret en la posiciòn 0*/
jTDescrip.setCaretPosition(0);
/*Coloca el borde negro si tiene datos, caso contrario de rojo*/
if(jTDescrip.getText().compareTo("")!=0)
jTDescrip.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204,204,255)));
/*Si el campo excede la cantidad de caes permitidos recortalo*/
if(jTDescrip.getText().length()> 255)
jTDescrip.setText(jTDescrip.getText().substring(0, 255));
}//GEN-LAST:event_jTDescripFocusLost
/*Cuando se presiona una tecla en el campo de la descripción*/
private void jTDescripKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTDescripKeyPressed
//Llama a la función escalable
vKeyPreEsc(evt);
}//GEN-LAST:event_jTDescripKeyPressed
/*Cuando se mueve la rueda del ratón en la forma*/
private void formMouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_formMouseWheelMoved
/*Pon la bandera para saber que ya hubó un evento y no se desloguie*/
bIdle = true;
}//GEN-LAST:event_formMouseWheelMoved
/*Cuando se arrastra el ratón en la forma*/
private void formMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseDragged
/*Pon la bandera para saber que ya hubó un evento y no se desloguie*/
bIdle = true;
}//GEN-LAST:event_formMouseDragged
/*Cuando se mueve el ratón en la forma*/
private void formMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseMoved
/*Pon la bandera para saber que ya hubó un evento y no se desloguie*/
bIdle = true;
}//GEN-LAST:event_formMouseMoved
/*Cuando se presiona el botón de ver tabla*/
private void jBTab1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBTab1ActionPerformed
//Muestra la tabla maximizada
Star.vMaxTab(jTab);
}//GEN-LAST:event_jBTab1ActionPerformed
/*Cuando se presiona una tecla en el botón de ver tabla*/
private void jBTab1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jBTab1KeyPressed
//Llama a la función escalable
vKeyPreEsc(evt);
}//GEN-LAST:event_jBTab1KeyPressed
/*Cuando el mouse entra en el botón de búscar*/
private void jBBuscMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBBuscMouseEntered
/*Cambia el color del fondo del botón*/
jBBusc.setBackground(Star.colBot);
/*Guardar el borde original que tiene el botón*/
bBordOri = jBBusc.getBorder();
/*Aumenta el grosor del botón*/
jBBusc.setBorder(new LineBorder(Color.GREEN, 3));
}//GEN-LAST:event_jBBuscMouseEntered
/*Cuando el mouse sale del botón de búscar*/
private void jBBuscMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBBuscMouseExited
/*Cambia el color del fondo del botón al original*/
jBBusc.setBackground(Star.colOri);
/*Coloca el borde que tenía*/
jBBusc.setBorder(bBordOri);
}//GEN-LAST:event_jBBuscMouseExited
/*Cuando el mouse entra en el campo del link de ayuda*/
private void jLAyuMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLAyuMouseEntered
/*Cambia el cursor del ratón*/
this.setCursor( new Cursor(Cursor.HAND_CURSOR));
}//GEN-LAST:event_jLAyuMouseEntered
/*Cuando el mouse sale del campo del link de ayuda*/
private void jLAyuMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLAyuMouseExited
/*Cambia el cursor del ratón al que tenía*/
this.setCursor( new Cursor(Cursor.DEFAULT_CURSOR));
}//GEN-LAST:event_jLAyuMouseExited
/*Cuando se presiona el botón de seleccionar todo*/
private void jBTodActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBTodActionPerformed
/*Si la tabla no contiene elementos entonces regresa*/
if(jTab.getRowCount()==0)
return;
/*Si están seleccionados los elementos en la tabla entonces*/
if(bSel)
{
/*Coloca la bandera y deseleccionalos*/
bSel = false;
jTab.clearSelection();
}
/*Else deseleccionalos y coloca la bandera*/
else
{
bSel = true;
jTab.setRowSelectionInterval(0, jTab.getModel().getRowCount()-1);
}
}//GEN-LAST:event_jBTodActionPerformed
/*Cuando se presiona una tecla en el botón de seleccionar todo*/
private void jBTodKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jBTodKeyPressed
//Llama a la función escalable
vKeyPreEsc(evt);
}//GEN-LAST:event_jBTodKeyPressed
/*Cuando se esta saliendo de la forma*/
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
/*Presiona el botón de salir*/
jBSal.doClick();
}//GEN-LAST:event_formWindowClosing
/*Cuando el mouse entra en el botón específico*/
private void jBNewMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBNewMouseEntered
/*Cambia el color del fondo del botón*/
jBNew.setBackground(Star.colBot);
}//GEN-LAST:event_jBNewMouseEntered
/*Cuando el mouse entra en el botón específico*/
private void jBTodMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBTodMouseEntered
/*Cambia el color del fondo del botón*/
jBTod.setBackground(Star.colBot);
}//GEN-LAST:event_jBTodMouseEntered
/*Cuando el mouse entra en el botón específico*/
private void jBDelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBDelMouseEntered
/*Cambia el color del fondo del botón*/
jBDel.setBackground(Star.colBot);
}//GEN-LAST:event_jBDelMouseEntered
/*Cuando el mouse entra en el botón específico*/
private void jBSalMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBSalMouseEntered
/*Cambia el color del fondo del botón*/
jBSal.setBackground(Star.colBot);
}//GEN-LAST:event_jBSalMouseEntered
/*Cuando el mouse entra en el botón específico*/
private void jBMostTMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBMostTMouseEntered
/*Cambia el color del fondo del botón*/
jBMostT.setBackground(Star.colBot);
}//GEN-LAST:event_jBMostTMouseEntered
/*Cuando el mouse sale del botón específico*/
private void jBNewMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBNewMouseExited
/*Cambia el color del fondo del botón al original*/
jBNew.setBackground(Star.colOri);
}//GEN-LAST:event_jBNewMouseExited
/*Cuando el mouse sale del botón específico*/
private void jBTodMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBTodMouseExited
/*Cambia el color del fondo del botón al original*/
jBTod.setBackground(Star.colOri);
}//GEN-LAST:event_jBTodMouseExited
/*Cuando el mouse sale del botón específico*/
private void jBDelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBDelMouseExited
/*Cambia el color del fondo del botón al original*/
jBDel.setBackground(Star.colOri);
}//GEN-LAST:event_jBDelMouseExited
/*Cuando el mouse sale del botón específico*/
private void jBSalMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBSalMouseExited
/*Cambia el color del fondo del botón al original*/
jBSal.setBackground(Star.colOri);
}//GEN-LAST:event_jBSalMouseExited
/*Cuando el mouse sale del botón específico*/
private void jBMostTMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jBMostTMouseExited
/*Cambia el color del fondo del botón al original*/
jBMostT.setBackground(Star.colOri);
}//GEN-LAST:event_jBMostTMouseExited
/*Cuando se pierde el foco del teclado en el control de bùsqueda*/
private void jTBuscFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTBuscFocusLost
/*Establece el botón por default*/
this.getRootPane().setDefaultButton(jBNew);
/*Coloca el caret en la posiciòn 0*/
jTBusc.setCaretPosition(0);
/*Coloca el borde negro si tiene datos, caso contrario de rojo*/
if(jTBusc.getText().compareTo("")!=0)
jTBusc.setBorder(javax.swing.BorderFactory.createLineBorder(new Color(204,204,255)));
}//GEN-LAST:event_jTBuscFocusLost
private void jTConsecActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTConsecActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTConsecActionPerformed
/*Función escalable para cuando se presiona una tecla en el módulo*/
void vKeyPreEsc(java.awt.event.KeyEvent evt)
{
/*Pon la bandera para saber que ya hubó un evento y no se desloguie*/
bIdle = true;
/*Si se presiona la tecla de escape presiona el botón de salir*/
if(evt.getKeyCode() == KeyEvent.VK_ESCAPE)
jBSal.doClick();
/*Else if se presiona Alt + T entonces presiona el botón de marcar todo*/
else if(evt.isAltDown() && evt.getKeyCode() == KeyEvent.VK_T)
jBTod.doClick();
/*Si se presiona CTRL + SUP entonces presiona el botón de borrar*/
else if(evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_DELETE)
jBDel.doClick();
/*Si se presiona CTRL + N entonces presiona el botón de nuevo*/
else if(evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_N)
jBNew.doClick();
/*Si se presiona F3 presiona el botón de búscar*/
else if(evt.getKeyCode() == KeyEvent.VK_F3)
jBBusc.doClick();
/*Else if se presiona Alt + F4 entonces presiona el botón de salir*/
else if(evt.isAltDown() && evt.getKeyCode() == KeyEvent.VK_F4)
jBSal.doClick();
/*Si se presiona F4 presiona el botón de mostrar todo*/
else if(evt.getKeyCode() == KeyEvent.VK_F4)
jBMostT.doClick();
}/*Fin de void vKeyPreEsc(java.awt.event.KeyEvent evt)*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jBBusc;
private javax.swing.JButton jBDel;
private javax.swing.JButton jBMostT;
private javax.swing.JButton jBNew;
private javax.swing.JButton jBSal;
private javax.swing.JButton jBTab1;
private javax.swing.JButton jBTod;
private javax.swing.JLabel jLAyu;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jP1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextField jTBusc;
private javax.swing.JTextField jTConsec;
private javax.swing.JTextField jTDescrip;
private javax.swing.JTextField jTSer;
private javax.swing.JTable jTab;
// End of variables declaration//GEN-END:variables
}/*Fin de public class Clientes extends javax.swing.JFrame */
|
[
"cesar.martinez@sos-soft.com"
] |
cesar.martinez@sos-soft.com
|
db084d5065375498d7288b851ae633a20184a4a8
|
9a76251be56b36b21a72ef43952be06c3093f0a6
|
/Begin/Begin32.java
|
5299897eb5bf22974ffd31c519f4171e46294300
|
[] |
no_license
|
UmedjonD/TestTasks
|
5cf6da22cc36d1ba018f61d6d964c6dbd182912c
|
d9e5ab6c25050969fa2c8c6a1646c035b3fb2432
|
refs/heads/master
| 2023-03-24T17:46:52.615146
| 2021-03-23T13:10:44
| 2021-03-23T13:10:44
| 348,784,277
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 402
|
java
|
package Begin;
import java.util.Scanner;
public class Begin32 {
public static void main(String[] args) {
double Tf, Tc;
Scanner scanner = new Scanner(System.in);
System.out.println("temperatura v gradusah selsii ");
Tc = scanner.nextDouble();
Tf = 9/5*Tc+32;
System.out.println("Znacheniya temperatury v gradusaah frangeyta ravno " + Tf);
}
}
|
[
"Lazerr_94@mail.ru"
] |
Lazerr_94@mail.ru
|
19db3a7e6c92b2c430d8dc853b135133ab4eb6ee
|
cb7ad37d2f0729b2575b28f923ec9bb2f24cc762
|
/el&jstl_test/src/com/hyb/web/filter/LoginFilter.java
|
4bcaafe8b21a35d534c700985e64e74892055301
|
[] |
no_license
|
hyb-store/javaweb
|
fac43b0b79cc401c3e2398d78b8128c6d2346246
|
5065b7190dad810fdd48baeadd74024a03ca9501
|
refs/heads/master
| 2023-04-07T00:23:40.877359
| 2021-03-29T12:33:14
| 2021-03-29T12:33:14
| 321,599,370
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,684
|
java
|
package com.hyb.web.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* 完成登录验证的过滤器
*/
@WebFilter("/*")
public class LoginFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//0.强制转换
HttpServletRequest request = (HttpServletRequest) req;
//1.获取资源请求路径
String uri = request.getRequestURI();
//2.判断是否包含登录相关资源路径,要注意排除掉 css/js/图片/验证码等资源
if(uri.contains("/login.jsp") || uri.contains("/loginServlet") || uri.contains("/css/") || uri.contains("/js/") || uri.contains("/fonts/") || uri.contains("/checkCodeServlet") ){
//包含,用户就是想登录。放行
chain.doFilter(req, resp);
}else{
//不包含,需要验证用户是否登录
//3.从获取session中获取user
Object user = request.getSession().getAttribute("user");
if(user != null){
//登录了。放行
chain.doFilter(req, resp);
}else{
//没有登录。跳转登录页面
request.setAttribute("login_msg","您尚未登录,请登录");
}
}
//chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
public void destroy() {
}
}
|
[
"3063687049@qq.com"
] |
3063687049@qq.com
|
e3171debccc530c53d806d102e94b6dcb2c0832f
|
7213d24cdfd1a4e34cbea9f0822db1247d096d4d
|
/pw-server/src/main/java/ru/pw/java/security/CustomChainFilter.java
|
c2a1d0f61d98de5727cbcd860e5a6183a4005612
|
[] |
no_license
|
WebJavaLion/p_w_
|
b966e97414790d512a20e1abbb8ca0cf8fb22ae6
|
fc453e9d6ae234ac1c878148431ba8b039c9ae46
|
refs/heads/master
| 2022-10-01T21:46:26.962971
| 2020-07-10T10:29:06
| 2020-07-10T10:29:06
| 218,363,786
| 0
| 0
| null | 2022-09-08T01:04:04
| 2019-10-29T19:10:02
|
Java
|
UTF-8
|
Java
| false
| false
| 845
|
java
|
package ru.pw.java.security;
import org.springframework.security.core.context.SecurityContextHolder;
import javax.servlet.*;
import java.io.IOException;
public class CustomChainFilter implements Filter {
String name;
public CustomChainFilter(String s) {
name = s;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
System.out.println(name);
System.out.println(SecurityContextHolder.getContext().getAuthentication());
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
|
[
"lev-2222@yandex.ru"
] |
lev-2222@yandex.ru
|
39cfbc16c980c36bacaae8f598a14f6d57cd275e
|
acd10791b1b0a30684d8616b0c58741c8769f12b
|
/redis-delay-queue/src/main/java/io/biteeniu/redis/delay/queue/Consumer.java
|
5e68866bbeea3e6d0d44955c5cf0a3020d3a745a
|
[] |
no_license
|
biteeniu/java-base-example
|
7091e4a167d5c4465a70c0657c50ae2bf8bc2353
|
33320a9c249de9036dd093a5604554e6a18a97a1
|
refs/heads/master
| 2020-03-22T09:17:09.151284
| 2018-08-06T08:53:28
| 2018-08-06T08:53:28
| 139,827,072
| 0
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,697
|
java
|
package io.biteeniu.redis.delay.queue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.Iterator;
import java.util.Set;
/**
* 消息消费者
* @author luzhanghong
* @date 2018-07-19 15:32
*/
public class Consumer implements Runnable {
private final static Logger LOGGER = LoggerFactory.getLogger(Consumer.class);
private final Jedis jedis;
public Consumer(JedisPool jedisPool) {
this.jedis = jedisPool.getResource();
}
@Override
public void run() {
synchronized (this) {
while (true) {
long timestamp = System.currentTimeMillis();
Set<String> jobs = jedis.zrangeByScore("JOB_BUCKET", 0, timestamp, 0, 5);
if (jobs.isEmpty()) {
// 没有任务的时候休眠100ms,避免
try {
this.wait(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
}
Iterator<String> iterator = jobs.iterator();
while (iterator.hasNext()) {
// 在这里处理任务
String id = iterator.next();
LOGGER.info("Consumer received job: {} -- delete ...", id);
jedis.zrem("JOB_BUCKET", id);
}
}
}
}
private void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
[
"dash@senthink.com"
] |
dash@senthink.com
|
81b4a90dc61e044e5586d1f5891e1f1d8e003fc6
|
b002763a28a435e9a212c1d4eea8e19ccf464213
|
/MyJavaProject/src/com/constructor/Employee.java
|
e15918e29dec9c48c73529909f302642a393b145
|
[] |
no_license
|
shashi123664/MyjavaProject
|
eb38114048cde5e6a77a577306148e7ac9657ca9
|
b1da4d7fa17d4436d9c71088bbff0a0e047629c7
|
refs/heads/master
| 2020-08-31T04:29:39.425810
| 2019-11-18T06:03:59
| 2019-11-18T06:03:59
| 218,589,102
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 551
|
java
|
package com.constructor;
class Employee {
String name;
double salary;
int id;
Employee(String name,double salary,int id)
{
this.name=name;
this.salary=salary;
this.id=id;
}
public static void main(String[] args) {
Employee emp1=new Employee("dileep",20000,1014);
System.out.println("name : "+ emp1.name + " salary : "+ emp1.salary + " id : "+ emp1.id);
Employee emp2=new Employee("udyan",20000,1015);
System.out.println("name : "+ emp2.name + " salary : "+ emp2.salary + " id : "+ emp2.id);
}
}
|
[
"SHASHI@DESKTOP-1I84TR0"
] |
SHASHI@DESKTOP-1I84TR0
|
3ced048e205bf17ef8bc8bbce69ab897c64ca917
|
978b444463d0a59bc95313ae625ccd7c98e70e0c
|
/workspace/fr.cnes.sitools.core/src/fr/cnes/sitools/plugins/resources/model/ResourceParameterType.java
|
2fe3221e2e4e98c0595898f3a011bd3d768f50f2
|
[] |
no_license
|
bfiorito/core-v2
|
8e92c88a99f3cb262bc21617718c940ff93d0bc1
|
f36dd81bc16cebe24c6c60303f92f5897226c00b
|
refs/heads/master
| 2021-01-16T00:47:17.753746
| 2013-06-11T14:45:10
| 2013-06-11T14:45:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,878
|
java
|
/*******************************************************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package fr.cnes.sitools.plugins.resources.model;
/**
* Parameter types for Parameterized resources
*
* @author m.marseille (AKKA Technologies)
*/
public enum ResourceParameterType {
// BEGIN ADDED FROM SvaParameterType
// A remplacer par l'utilisation du valueType xs:dataset.column.name ou xs:dictionary
/**
* A parameter IN is read only
*/
@Deprecated
PARAMETER_IN,
/**
* A parameter OUT is write only
*/
@Deprecated
PARAMETER_OUT,
/**
* A parameter INOUT is readable and writable
*/
@Deprecated
PARAMETER_INOUT,
// END ADDED FROM SvaParameterType
/**
* Attach type for url attachments
*/
PARAMETER_ATTACHMENT,
/**
* Intern Parameters for resource bean specificity
*/
PARAMETER_INTERN,
/**
* Parameter to be set up by the final user before service call, use default otherwise
*/
PARAMETER_USER_INPUT,
/**
* Parameter used only in the client interface
*/
PARAMETER_USER_GUI
}
|
[
"b.fiorito@akka.eu"
] |
b.fiorito@akka.eu
|
777fb7165e886903740303c384f883d1d2db2906
|
9ce6f5d8a8f2d586d02c5bfabb4d249c9cee9dfa
|
/src/main/java/com/njfu/bysj/oerts/controller/OnlineQAController.java
|
de7391f2f90af1ecff010260976c57708471716d
|
[] |
no_license
|
xuzhiyan/oerts-server
|
2f1493ef5bbab24c70af9075c647d33ebe1c8a4c
|
c34806441238da3228dd319d15f6b846761ec43e
|
refs/heads/master
| 2020-03-07T15:09:46.161581
| 2018-06-02T15:28:44
| 2018-06-02T15:28:44
| 127,547,108
| 2
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,419
|
java
|
/**
* @FileName: OnlineQAController.java
* @Description: TODO
*
* @author 徐至彦
* @version V1.0
* @Date 2018年4月29日 下午7:57:35
*
*/
package com.njfu.bysj.oerts.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.njfu.bysj.oerts.entity.JsonResult;
import com.njfu.bysj.oerts.entity.OnlineQAEntity;
import com.njfu.bysj.oerts.service.OnlineQAService;
import com.njfu.bysj.oerts.utils.JsonUtil;
/**
* @ClassName: OnlineQAController
* @Description: TODO
*
* @author: 徐至彦
* @date: 2018年4月29日 下午7:57:35
*
*/
@RestController
public class OnlineQAController {
@Autowired
private OnlineQAService onlineQAService;
@GetMapping("/onlineqa/question/common")
public JsonResult getCommonQuestion() {
return JsonUtil.success(onlineQAService.getCommonQuestion());
}
@GetMapping("/onlineqa/question/{question}")
public JsonResult getAnswerByKey(@PathVariable String question) {
OnlineQAEntity result = onlineQAService.getAnswerByKey(question);
if (result.getQuestionAnswer() == null) {
return JsonUtil.failed("找不到相关答案,请换一种方式询问!");
} else {
return JsonUtil.success(result);
}
}
}
|
[
"37604467+xuzhiyan@users.noreply.github.com"
] |
37604467+xuzhiyan@users.noreply.github.com
|
7c1f7b21b402c1ec9c80271ba925355c157edf29
|
e59db84b4e82306b39f9259f3d3ea3c46cd8889c
|
/src/main/java/in/ankushs/linode4j/model/profile/AuthorizedAppsPageImpl.java
|
40509f8a34e9747f4222d14f1b77efdf212a47f1
|
[
"MIT"
] |
permissive
|
jordancole18/linode4j
|
90b7629a6a35c69f543e2409aec93e0d09c2f4c6
|
163e8d34df9ac78215213c7624c8f97245f18d61
|
refs/heads/master
| 2021-09-05T02:42:37.300176
| 2018-01-23T18:24:15
| 2018-01-23T18:24:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 710
|
java
|
package in.ankushs.linode4j.model.profile;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import in.ankushs.linode4j.model.interfaces.Page;
import lombok.Data;
import java.util.Set;
/**
* Created by ankushsharma on 22/12/17.
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public final class AuthorizedAppsPageImpl implements Page<AuthorizedApp> {
@JsonProperty("pages")
private final Integer totalPages;
@JsonProperty("page")
private final Integer currentPageCount;
@JsonProperty("results")
private final Integer totalResults;
@JsonProperty("data")
private final Set<AuthorizedApp> content;
}
|
[
"ankush.s@adsizzlergroup.com"
] |
ankush.s@adsizzlergroup.com
|
0601a27df9cfaaf84d288f0314671e668e5c96c3
|
5e7c4257c0d5180ed63c2b37e2badb770ad65a4b
|
/gmall-api/src/main/java/com/baizhi/gmall/pms/entity/Product.java
|
4bc3445b2a51e6dddb92de45840f774535a697db
|
[] |
no_license
|
28899121390/gmall-parent
|
1067abbab415b9153ad73ab9cecd5f48f7b04d70
|
5366a965df02dae94b661e174a6d6dbf601cfc12
|
refs/heads/master
| 2023-08-10T08:12:43.638661
| 2020-01-03T07:06:51
| 2020-01-03T07:06:52
| 230,357,271
| 0
| 0
| null | 2023-07-23T01:21:12
| 2019-12-27T02:16:27
|
Java
|
UTF-8
|
Java
| false
| false
| 5,434
|
java
|
package com.baizhi.gmall.pms.entity;
import java.math.BigDecimal;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* 商品信息
* </p>
*
* @author htf
* @since 2019-12-27
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("pms_product")
@ApiModel(value="Product对象", description="商品信息")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("brand_id")
private Long brandId;
@TableField("product_category_id")
private Long productCategoryId;
@TableField("feight_template_id")
private Long feightTemplateId;
@TableField("product_attribute_category_id")
private Long productAttributeCategoryId;
@TableField("name")
private String name;
@TableField("pic")
private String pic;
@ApiModelProperty(value = "货号")
@TableField("product_sn")
private String productSn;
@ApiModelProperty(value = "删除状态:0->未删除;1->已删除")
@TableField("delete_status")
private Integer deleteStatus;
@ApiModelProperty(value = "上架状态:0->下架;1->上架")
@TableField("publish_status")
private Integer publishStatus;
@ApiModelProperty(value = "新品状态:0->不是新品;1->新品")
@TableField("new_status")
private Integer newStatus;
@ApiModelProperty(value = "推荐状态;0->不推荐;1->推荐")
@TableField("recommand_status")
private Integer recommandStatus;
@ApiModelProperty(value = "审核状态:0->未审核;1->审核通过")
@TableField("verify_status")
private Integer verifyStatus;
@ApiModelProperty(value = "排序")
@TableField("sort")
private Integer sort;
@ApiModelProperty(value = "销量")
@TableField("sale")
private Integer sale;
@TableField("price")
private BigDecimal price;
@ApiModelProperty(value = "促销价格")
@TableField("promotion_price")
private BigDecimal promotionPrice;
@ApiModelProperty(value = "赠送的成长值")
@TableField("gift_growth")
private Integer giftGrowth;
@ApiModelProperty(value = "赠送的积分")
@TableField("gift_point")
private Integer giftPoint;
@ApiModelProperty(value = "限制使用的积分数")
@TableField("use_point_limit")
private Integer usePointLimit;
@ApiModelProperty(value = "副标题")
@TableField("sub_title")
private String subTitle;
@ApiModelProperty(value = "商品描述")
@TableField("description")
private String description;
@ApiModelProperty(value = "市场价")
@TableField("original_price")
private BigDecimal originalPrice;
@ApiModelProperty(value = "库存")
@TableField("stock")
private Integer stock;
@ApiModelProperty(value = "库存预警值")
@TableField("low_stock")
private Integer lowStock;
@ApiModelProperty(value = "单位")
@TableField("unit")
private String unit;
@ApiModelProperty(value = "商品重量,默认为克")
@TableField("weight")
private BigDecimal weight;
@ApiModelProperty(value = "是否为预告商品:0->不是;1->是")
@TableField("preview_status")
private Integer previewStatus;
@ApiModelProperty(value = "以逗号分割的产品服务:1->无忧退货;2->快速退款;3->免费包邮")
@TableField("service_ids")
private String serviceIds;
@TableField("keywords")
private String keywords;
@TableField("note")
private String note;
@ApiModelProperty(value = "画册图片,连产品图片限制为5张,以逗号分割")
@TableField("album_pics")
private String albumPics;
@TableField("detail_title")
private String detailTitle;
@TableField("detail_desc")
private String detailDesc;
@ApiModelProperty(value = "产品详情网页内容")
@TableField("detail_html")
private String detailHtml;
@ApiModelProperty(value = "移动端网页详情")
@TableField("detail_mobile_html")
private String detailMobileHtml;
@ApiModelProperty(value = "促销开始时间")
@TableField("promotion_start_time")
private Date promotionStartTime;
@ApiModelProperty(value = "促销结束时间")
@TableField("promotion_end_time")
private Date promotionEndTime;
@ApiModelProperty(value = "活动限购数量")
@TableField("promotion_per_limit")
private Integer promotionPerLimit;
@ApiModelProperty(value = "促销类型:0->没有促销使用原价;1->使用促销价;2->使用会员价;3->使用阶梯价格;4->使用满减价格;5->限时购")
@TableField("promotion_type")
private Integer promotionType;
@ApiModelProperty(value = "品牌名称")
@TableField("brand_name")
private String brandName;
@ApiModelProperty(value = "商品分类名称")
@TableField("product_category_name")
private String productCategoryName;
}
|
[
"2889921390@qq.com"
] |
2889921390@qq.com
|
0d6542ef1441cb39e43ed5eaa0bb3b7985fe1472
|
f932bc7baf8cfcdbd3764d70927d90f18fc1e32c
|
/common/src/main/java/org/glowroot/common/model/MutableQuery.java
|
21b2b653cc97f274c7770cece316072acb153d74
|
[
"Apache-2.0"
] |
permissive
|
chakra-coder/glowroot
|
e459ee825e0d55dbaede9e526b558236d3357504
|
1aad8e83013c48c77814eac7b42d711cae2e8751
|
refs/heads/master
| 2021-06-04T04:22:43.452703
| 2016-09-08T07:10:20
| 2016-09-08T07:10:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 2,429
|
java
|
/*
* Copyright 2015-2016 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.glowroot.common.model;
import javax.annotation.Nullable;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Doubles;
public class MutableQuery {
static final Ordering<MutableQuery> byTotalDurationDesc = new Ordering<MutableQuery>() {
@Override
public int compare(MutableQuery left, MutableQuery right) {
return Doubles.compare(right.getTotalDurationNanos(), left.getTotalDurationNanos());
}
};
private final String truncatedQueryText;
private final @Nullable String fullQueryTextSha1;
private double totalDurationNanos;
private long executionCount;
private boolean hasTotalRows;
private long totalRows;
MutableQuery(String truncatedQueryText, @Nullable String fullQueryTextSha1) {
this.truncatedQueryText = truncatedQueryText;
this.fullQueryTextSha1 = fullQueryTextSha1;
}
public String getTruncatedQueryText() {
return truncatedQueryText;
}
public @Nullable String getFullQueryTextSha1() {
return fullQueryTextSha1;
}
public double getTotalDurationNanos() {
return totalDurationNanos;
}
public long getExecutionCount() {
return executionCount;
}
public boolean hasTotalRows() {
return hasTotalRows;
}
public long getTotalRows() {
return totalRows;
}
void addToTotalDurationNanos(double totalDurationNanos) {
this.totalDurationNanos += totalDurationNanos;
}
void addToExecutionCount(long executionCount) {
this.executionCount += executionCount;
}
void addToTotalRows(boolean hasTotalRows, long totalRows) {
if (hasTotalRows) {
this.hasTotalRows = true;
this.totalRows += totalRows;
}
}
}
|
[
"trask.stalnaker@gmail.com"
] |
trask.stalnaker@gmail.com
|
9350eaf6e951bb1fb58a464cab30f4a4bdd887ad
|
d89ecc592aaec62ded78787472680c114092b2a4
|
/main/src/cgeo/geocaching/maps/routing/RouteSortActivity.java
|
2c715b1f95a4a517ba6be81a9bb3987c92e0d86d
|
[
"Apache-2.0"
] |
permissive
|
0xflotus/cgeo
|
af80a66719078473b0ebed83952cfd274cedf526
|
730b1ee93dba6e4833bb9922e51c0d6399837136
|
refs/heads/master
| 2022-11-23T23:29:45.765694
| 2020-08-02T17:04:31
| 2020-08-02T17:04:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 5,809
|
java
|
package cgeo.geocaching.maps.routing;
import cgeo.geocaching.R;
import cgeo.geocaching.activity.AbstractActivity;
import cgeo.geocaching.enumerations.CacheListType;
import cgeo.geocaching.enumerations.CoordinatesType;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.models.IWaypoint;
import cgeo.geocaching.models.Waypoint;
import cgeo.geocaching.storage.DataStore;
import cgeo.geocaching.utils.AndroidRxUtils;
import cgeo.geocaching.utils.Formatter;
import cgeo.geocaching.utils.MapMarkerUtils;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import io.reactivex.rxjava3.schedulers.Schedulers;
public class RouteSortActivity extends AbstractActivity {
private ArrayAdapter<RouteItem> routeItemAdapter;
private ArrayList<RouteItem> routeItems;
private ListView listView;
private boolean changed = false;
private int lastActivatedPosition = -1;
@Override
public void onCreate(@Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme();
setTitle(getString(R.string.map_sort_individual_route));
routeItems = DataStore.loadRoute();
routeItemAdapter = new ArrayAdapter<RouteItem>(this, 0, routeItems) {
@SuppressLint("SetTextI18n")
@NonNull
public View getView(final int position, final View convertView, @NonNull final ViewGroup parent) {
View v = convertView;
if (null == convertView) {
v = getLayoutInflater().inflate(R.layout.twotexts_twobuttons_item, null, false);
((ImageButton) v.findViewById(R.id.button_left)).setImageResource(R.drawable.ic_menu_up);
((ImageButton) v.findViewById(R.id.button_right)).setImageResource(R.drawable.ic_menu_down);
}
final RouteItem routeItem = routeItems.get(position);
final IWaypoint data = routeItem.getType() == CoordinatesType.CACHE ? DataStore.loadCache(routeItem.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB) : DataStore.loadWaypoint(routeItem.getId());
final TextView title = v.findViewById(R.id.title);
final TextView detail = v.findViewById(R.id.detail);
if (null == data) {
title.setText(routeItem.getGeocode());
detail.setText(R.string.route_item_not_yet_loaded);
} else {
title.setText(data.getName());
if (routeItem.getType() == CoordinatesType.CACHE) {
assert data instanceof Geocache;
detail.setText(Formatter.formatCacheInfoLong((Geocache) data));
title.setCompoundDrawablesWithIntrinsicBounds(MapMarkerUtils.getCacheMarker(res, (Geocache) data, CacheListType.OFFLINE).getDrawable(), null, null, null);
} else {
assert data instanceof Waypoint;
final Geocache cache = DataStore.loadCache(data.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB);
detail.setText(data.getGeocode() + Formatter.SEPARATOR + cache.getName());
title.setCompoundDrawablesWithIntrinsicBounds(data.getWaypointType().markerId, 0, 0, 0);
}
}
title.setOnLongClickListener(v1 -> delete(position));
detail.setOnLongClickListener(v1 -> delete(position));
final View buttonUp = v.findViewById(R.id.button_left);
buttonUp.setVisibility(position > 0 ? View.VISIBLE : View.INVISIBLE);
buttonUp.setOnClickListener(vUp -> swap(position, position - 1));
final ImageButton buttonDown = v.findViewById(R.id.button_right);
buttonDown.setVisibility(position < routeItems.size() - 1 ? View.VISIBLE : View.INVISIBLE);
buttonDown.setOnClickListener(vDown -> swap(position, position + 1));
return v;
}
};
listView = new ListView(this);
setContentView(listView);
listView.setAdapter(routeItemAdapter);
}
private void swap(final int position1, final int position2) {
Collections.swap(routeItems, position1, position2);
routeItemAdapter.notifyDataSetChanged();
changed = true;
invalidateOptionsMenu();
}
private boolean delete(final int position) {
routeItems.remove(position);
routeItemAdapter.notifyDataSetChanged();
changed = true;
invalidateOptionsMenu();
return true;
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.route_sort, menu);
menu.findItem(R.id.save_sorted_route).setVisible(changed);
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (item.getItemId() == R.id.save_sorted_route) {
AndroidRxUtils.andThenOnUi(Schedulers.io(), () -> DataStore.saveRoute(routeItems), () -> {
changed = false;
invalidateOptionsMenu();
Toast.makeText(this, R.string.sorted_route_saved, Toast.LENGTH_SHORT).show();
});
return true;
}
return false;
}
}
|
[
"github@moving-bits.net"
] |
github@moving-bits.net
|
9a5d8773ba1e37ae145fae0add26ecc979814a5b
|
3369881f1d4301316525769ae87ca36adb15094f
|
/AttendenceTracker-0.0.1-SNAPSHOT/src/main/java/com/trivecta/attendencetracker/model/entity/SubContractor.java
|
21804d5c207644fa21f00234bdf6bbb52a3b26ad
|
[] |
no_license
|
uvaisTrivecta/ConstructionApp
|
5f74ad38ca4e85a26d2194fe93aeb2dcde3353d1
|
9a542b78ec380c2c89704b08c9491903fd3e1319
|
refs/heads/master
| 2020-06-21T19:31:46.654192
| 2016-12-17T11:16:03
| 2016-12-17T11:16:03
| 94,205,078
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 3,318
|
java
|
package com.trivecta.attendencetracker.model.entity;
import java.io.Serializable;
import java.math.BigInteger;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
/**
* The persistent class for the sub_contractors database table.
*
*/
@Entity
@Table(name="SUB_CONTRACTORS")
@NamedQuery(name="SubContractor.findAll", query="SELECT s FROM SubContractor s")
public class SubContractor implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private int createdBy;
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
private int modifiedBy;
@Temporal(TemporalType.TIMESTAMP)
private Date modifiedDate;
private String name;
private String primaryContactName;
private BigInteger primaryContactNo;
//bi-directional many-to-one association to LabourSubContractor
@OneToMany(mappedBy="subContractor")
private List<LabourSubContractor> labourSubContractors;
//bi-directional many-to-one association to Address
@ManyToOne
@JoinColumn(name="addressId")
private Address address;
public SubContractor() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public int getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(int createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return this.creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public int getModifiedBy() {
return this.modifiedBy;
}
public void setModifiedBy(int modifiedBy) {
this.modifiedBy = modifiedBy;
}
public Date getModifiedDate() {
return this.modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPrimaryContactName() {
return this.primaryContactName;
}
public void setPrimaryContactName(String primaryContactName) {
this.primaryContactName = primaryContactName;
}
public BigInteger getPrimaryContactNo() {
return this.primaryContactNo;
}
public void setPrimaryContactNo(BigInteger primaryContactNo) {
this.primaryContactNo = primaryContactNo;
}
public List<LabourSubContractor> getLabourSubContractors() {
return this.labourSubContractors;
}
public void setLabourSubContractors(List<LabourSubContractor> labourSubContractors) {
this.labourSubContractors = labourSubContractors;
}
public LabourSubContractor addLabourSubContractor(LabourSubContractor labourSubContractor) {
getLabourSubContractors().add(labourSubContractor);
labourSubContractor.setSubContractor(this);
return labourSubContractor;
}
public LabourSubContractor removeLabourSubContractor(LabourSubContractor labourSubContractor) {
getLabourSubContractors().remove(labourSubContractor);
labourSubContractor.setSubContractor(null);
return labourSubContractor;
}
public Address getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
}
|
[
"psuganya.mdu@gmail.com"
] |
psuganya.mdu@gmail.com
|
77f2262bf005c53e461329d06b5bce893d1388d9
|
9c07cc08cbed5615d441865a129ceacf1479757b
|
/VITAMIN/src/main/java/com/vitamin/dao/UserDAO.java
|
b577337e966f12119fc1d1eb9dffc9194efa6e73
|
[] |
no_license
|
jongjs1206/team
|
ac7817877686db1957241fecad607c82aa09c1b5
|
7c9b02f53eea6d7b4f725ccc1dd281836965632b
|
refs/heads/master
| 2023-03-18T01:31:32.778427
| 2021-02-22T03:19:41
| 2021-02-22T03:19:41
| 326,368,184
| 0
| 1
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 787
|
java
|
package com.vitamin.dao;
import java.util.List;
import com.vitamin.domain.UserVO;
public interface UserDAO {
/**
* 로그인 확인 기능 구현
*/
UserVO idCheck_Login(UserVO vo);
List<UserVO> alluser();
List<UserVO> userSerach(String keyselects, String accountsearch, String rankselect, String gradeselect);
public int blackchange(String blackid,String blackstate);
public int rankchange(String rankid, String rankstate);
public String userpay(String id);
//회원가입
public void userJoin(UserVO vo) throws Exception;
//회원정보 수정
public void userUpdate(UserVO vo)throws Exception;
//회원 정보 조회
UserVO getuserinfo(String id);
//회원 탈퇴
public void userDelete(UserVO vo)throws Exception;
}
|
[
"jjs@DESKTOP-P70BAC4"
] |
jjs@DESKTOP-P70BAC4
|
ccf17af3dfbf0045e311fb4c0f2d7dc53f777043
|
caddb232d85a8b47d2b2b3696c0387e1f3a4ce52
|
/sysnutri/backend/desafio/src/main/java/br/com/desafio/model/Paciente.java
|
b58f1b4313fb55c62c0586fa09d2aaa797c89168
|
[] |
no_license
|
MarcusSilva22/projetos
|
76a133f610ecf9fa72765b70828ed100dc8664c8
|
fdd4e7f4a038a20a39075d59e77ffa320b6aa7cc
|
refs/heads/master
| 2023-08-24T12:56:06.559822
| 2021-09-16T19:04:08
| 2021-09-16T19:04:08
| 407,282,760
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 770
|
java
|
package br.com.desafio.model;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.*;
@Entity
@Table(name="tb_paciente")
@PrimaryKeyJoinColumn(name="id")
public class Paciente extends Usuario implements Serializable {
private static final long serialVersionUID = 35953318573591016L;
@Column(name="nome")
private String nome;
@Column(name="dataNascimento")
private Date dataNascimento;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
|
[
"marcus.fms@gmail.com"
] |
marcus.fms@gmail.com
|
ff0c997fc9657b331ca6e84ce647ccbd5f7fda19
|
4ae5b5ae64cfead56f5ad7d7ab419195ff5d4bf3
|
/src/com/javarush/test/level03/lesson06/task03/Solution.java
|
60679792693ac1506fb17f22660c19803b10b429
|
[] |
no_license
|
OlenaSoboleva/JavaRushHomeWork
|
98cd9115e191942afb8a749663781c726d8d26c4
|
55e028608dff413760b1af5feba5b7b6d9f59afa
|
refs/heads/master
| 2020-04-10T21:47:23.667640
| 2018-12-11T09:05:33
| 2018-12-11T09:05:33
| 161,306,570
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,478
|
java
|
package com.javarush.test.level03.lesson06.task03;
/* Семь цветов радуги
Создать 7 объектов, чтобы на экран вывелись 7 цветов радуги (ROYGBIV).
Каждый объект при создании выводит на экран определенный цвет.
*/
public class Solution
{
public static void main(String[] args)
{
Red red=new Red();
Orange orange=new Orange();
Yellow yellow=new Yellow();
Green green=new Green();
Blue blue=new Blue();
Indigo indigo=new Indigo();
Violet violet=new Violet();
}
public static class Red
{
public Red() {
System.out.println("Red");
}
}
public static class Orange
{
public Orange() {
System.out.println("Orange");
}
}
public static class Yellow
{
public Yellow() {
System.out.println("Yellow");
}
}
public static class Green
{
public Green() {
System.out.println("Green");
}
}
public static class Blue
{
public Blue() {
System.out.println("Blue");
}
}
public static class Indigo
{
public Indigo() {
System.out.println("Indigo");
}
}
public static class Violet
{
public Violet() {
System.out.println("Violet");
}
}
}
|
[
"selena.soboleva@gmail.com"
] |
selena.soboleva@gmail.com
|
8861beb3e5271ba00995abf8a2926c6c0462ae47
|
af58eabf5360cb82082e1b0590696b627118d5a3
|
/app-main/src/main/java/com/zhongmei/bty/dinner/Listener/DishOptListener.java
|
b2c59fec953539c6ae64fe53d4a649d9278b88bd
|
[] |
no_license
|
sengeiou/marketing-app
|
f4b670f3996ba190decd2f1b8e4a276eb53b8b2a
|
278f3da95584e2ab7d97dff1a067db848e70a9f3
|
refs/heads/master
| 2020-06-07T01:51:25.743676
| 2019-06-20T08:58:28
| 2019-06-20T08:58:28
| 192,895,799
| 0
| 1
| null | 2019-06-20T09:59:09
| 2019-06-20T09:59:08
| null |
UTF-8
|
Java
| false
| false
| 442
|
java
|
package com.zhongmei.bty.dinner.Listener;
import com.zhongmei.bty.basemodule.orderdish.bean.DishDataItem;
import com.zhongmei.yunfu.db.enums.PrintOperationOpType;
import java.util.List;
/**
* @Date: 2018/2/8
* @Description:
* @Version: 1.0
*/
public interface DishOptListener {
void onSuccess(PrintOperationOpType type, List<DishDataItem> dataItems);
void onFail(PrintOperationOpType type, List<DishDataItem> dataItems);
}
|
[
"yangyuanping_cd@shishike.com"
] |
yangyuanping_cd@shishike.com
|
a7201de43df05c0b9a722ea93aac833e5123595c
|
d236cae79d049b85f84d25095d2e1fae5fc525b3
|
/src/main/java/io/github/mariazevedo88/financialjavaapi/model/statistic/Statistic.java
|
c3f0e66c6b5abdcf8c2df63ca59b87e449beae7c
|
[
"MIT"
] |
permissive
|
Spring-Boot-Framework/financial-java-api
|
7e89035be744f81a50cb1d5df2f85fcda1fc6991
|
109ab3805e5c821407bf62a2806cbdbc8125c79a
|
refs/heads/master
| 2022-12-19T21:23:39.584892
| 2020-09-25T06:04:35
| 2020-09-25T06:04:35
| 296,247,388
| 1
| 4
|
MIT
| 2020-09-25T06:04:36
| 2020-09-17T07:09:17
| null |
UTF-8
|
Java
| false
| false
| 1,818
|
java
|
package io.github.mariazevedo88.financialjavaapi.model.statistic;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.modelmapper.ModelMapper;
import io.github.mariazevedo88.financialjavaapi.dto.model.statistic.StatisticDTO;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
* Class that implements the Statistic structure.
*
* @author Mariana Azevedo
* @since 01/04/2020
*/
@Entity
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "statistics")
public class Statistic implements Serializable {
private static final long serialVersionUID = -7804600023031651840L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "transactions_sum")
private BigDecimal sum;
@Column(name = "transactions_avg")
private BigDecimal avg;
@Column(name = "transactions_max")
private BigDecimal max;
@Column(name = "transactions_min")
private BigDecimal min;
@Column(name = "transactions_count")
private long count;
public Statistic (BigDecimal sum, BigDecimal avg, BigDecimal max, BigDecimal min, long count) {
this.sum = sum;
this.avg = avg;
this.max = max;
this.min = min;
this.count = count;
}
/**
* Method to convert an Statistic entity to an Statistic DTO.
*
* @author Mariana Azevedo
* @since 03/04/2020
*
* @param statistic
* @return a <code>StatisticDTO</code> object
*/
public StatisticDTO convertEntityToDTO() {
return new ModelMapper().map(this, StatisticDTO.class);
}
}
|
[
"mariana@bsi.ufla.br"
] |
mariana@bsi.ufla.br
|
9addcb3d5065e1e24c93f7f4ebafbc7ae0ca68d6
|
d254e76a3eda46e8c3be7ea359970b1ecc3d3829
|
/src/com/actionpattern/mediatorpattern/ConcreteMediator.java
|
241a58d73f611d85f2612f8cb41686257efef31d
|
[] |
no_license
|
chinese2015/designpattern
|
1663aaa14d37451162b7637729c7ef5e51cb1016
|
ea4906eb7ecccaf5dfbea38e666c59f4635178e4
|
refs/heads/main
| 2023-02-25T21:55:59.205345
| 2021-02-01T16:21:05
| 2021-02-01T16:21:05
| 328,346,170
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 694
|
java
|
package com.actionpattern.mediatorpattern;
public class ConcreteMediator extends Mediator {
private Colleague concreteConlleague1;
private Colleague concreteConlleague2;
public void setConcreteConlleague1(Colleague concreteConlleague1) {
this.concreteConlleague1 = concreteConlleague1;
}
public void setConcreteConlleague2(Colleague concreteConlleague2) {
this.concreteConlleague2 = concreteConlleague2;
}
public void sendMessage(Colleague colleague, String message) {
if(colleague==concreteConlleague1){
concreteConlleague2.notify(message);
}else{
concreteConlleague1.notify(message);
}
}
}
|
[
"huaxia2002@gmail.com"
] |
huaxia2002@gmail.com
|
530d787eaa3c32b9f1a0eb874f44c38944d717f2
|
2d5e54e4dd6612aeb19904fcdf8757680c5bfd79
|
/core.session/src/org/modelio/vcore/session/impl/transactions/events/UndoModelChangeActionVisitor.java
|
31ecc4d4c89b10806cb6adf667d4dd20378b0684
|
[] |
no_license
|
mondo-project/hawk-modelio
|
1ef504dde30ce4e43b5db8d7936adbc04851e058
|
4da0f70dfeddb0451eec8b2f361586e07ad3dab9
|
refs/heads/master
| 2021-01-10T06:09:58.281311
| 2015-11-06T11:08:15
| 2015-11-06T11:08:15
| 45,675,632
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 10,071
|
java
|
/*
* Copyright 2013 Modeliosoft
*
* This file is part of Modelio.
*
* Modelio is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Modelio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Modelio. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.modelio.vcore.session.impl.transactions.events;
import com.modeliosoft.modelio.javadesigner.annotations.objid;
import org.modelio.vcore.session.impl.transactions.Transaction;
import org.modelio.vcore.session.impl.transactions.smAction.AppendDependencyAction;
import org.modelio.vcore.session.impl.transactions.smAction.CreateElementAction;
import org.modelio.vcore.session.impl.transactions.smAction.DeleteElementAction;
import org.modelio.vcore.session.impl.transactions.smAction.EraseDependencyAction;
import org.modelio.vcore.session.impl.transactions.smAction.IAction;
import org.modelio.vcore.session.impl.transactions.smAction.MoveDependencyAction;
import org.modelio.vcore.session.impl.transactions.smAction.SetAttributeAction;
import org.modelio.vcore.session.impl.transactions.smAction.smActionInteractions.IActionVisitor;
import org.modelio.vcore.smkernel.SmObjectData;
import org.modelio.vcore.smkernel.SmObjectImpl;
import org.modelio.vcore.smkernel.mapi.MObject;
import org.modelio.vcore.smkernel.meta.SmDependency;
@objid ("01f42120-0000-0142-0000-000000000000")
class UndoModelChangeActionVisitor implements IActionVisitor {
@objid ("01f42120-0000-0193-0000-000000000000")
private ModelChangeEvent event;
@objid ("01f42120-0000-01ab-0000-000000000000")
private StatusChangeEvent statusEvent;
@objid ("01f42120-0000-014a-0000-000000000000")
public UndoModelChangeActionVisitor(ModelChangeEvent event, StatusChangeEvent statusEvent) {
this.event = event;
this.statusEvent = statusEvent;
}
@objid ("01f42120-0000-0154-0000-000000000000")
@Override
public void visitTransaction(final Transaction tr) {
// simply visit the actions of the transaction
for (IAction a : tr.getActions()) {
a.accept(this);
}
}
@objid ("01f42120-0000-015d-0000-000000000000")
@Override
public void visitCreateElementAction(final CreateElementAction action) {
// note: in 'undo' operations, creating an object is always applied to a
// previously deleted object
// therefore let's call the refered object 'deleted'
SmObjectImpl deleted = action.getRefered();
// Get the old parent that can be found in the erase list
MObject oldParent = this.event.erasedElements.get(deleted);
if (oldParent != null) {
this.event.deletedElements.put(deleted, oldParent);
// Remove the now useless erase event
this.event.erasedElements.remove(deleted);
}
// // Get the old parent that can be found in the erase list
// std::map<SmObjectImpl, SmObjectImpl>::iterator found =
// event.erasedElements.find(refered);
// if ( found != event.erasedElements.end() )
// {
// event.deletedElements [refered] = found.second;
// // Remove the now useless erase event
// event.erasedElements.erase(found);
// }
}
@objid ("01f42120-0000-0166-0000-000000000000")
@Override
public void visitDeleteElementAction(final DeleteElementAction action) {
// note: in 'undo' operations, deleting an object is always applied to a
// previously created object
// therefore let's call the refered object 'created'
SmObjectImpl created = action.getRefered();
// A created element cannot have already been created, thereby
// permitting the new object
// to be stored without test
this.event.createdElements.add(created);
}
@objid ("01f42120-0000-016f-0000-000000000000")
@Override
public void visitSetAttributeAction(final SetAttributeAction action) {
SmObjectImpl refered = action.getRefered();
// Forget created then deleted elements
if (refered.isDeleted())
return;
// If the element is already in the list of created elements, it has not
// to be added
if (this.event.createdElements.contains(refered))
return;
if (action.getAtt() == SmObjectData.Metadata.statusAtt()) {
// populate the status change event
long oldStatus = (long) action.getOldValue();
long newStatus = refered.getData().getStatus();
this.statusEvent.add(refered, oldStatus, newStatus);
} else {
// If the element is already in the list of updated elements, it has
// not to be added
if (this.event.updatedElements.contains(refered) == false) {
// If the element already is in the list of created elements, it
// has not to be added
if (this.event.createdElements.contains(refered) == false)
this.event.updatedElements.add(refered);
}
}
}
@objid ("01f42120-0000-0178-0000-000000000000")
@Override
public void visitEraseDependencyAction(final EraseDependencyAction theEraseDependencyAction) {
SmObjectImpl ref = theEraseDependencyAction.getRef();
SmObjectImpl refered = theEraseDependencyAction.getRefered();
SmDependency dep = theEraseDependencyAction.getDep();
// Forget operations on deleted elements
if (refered == null || ref.isDeleted() || refered.isDeleted())
return;
if (dep.isPartOf() ) {
// If the element is already in the list of created elements, it has
// not to be added
if (this.event.createdElements.contains(refered))
return;
if (this.event.updatedElements.contains(refered) == false) {
this.event.updatedElements.add(refered);
}
}
}
@objid ("01f42120-0000-0181-0000-000000000000")
@Override
public void visitAppendDependencyAction(final AppendDependencyAction theAppendDependencyAction) {
SmObjectImpl target = theAppendDependencyAction.getRef();
SmObjectImpl src = theAppendDependencyAction.getRefered();
SmDependency dep = theAppendDependencyAction.getDep();
if (target == null || src == null)
return;
// Only composition dependencies are managed
if (isComponentDependency(dep)) {
// If the element is in the created element list, that means it has
// not to be declared as moved
// because it is already declared as created.
if (this.event.createdElements.contains(target))
return;
// If the element already is in the erase relation, that means the
// element has been moved
// under another element (in the same transaction)..., which has not
// to be managed because
// the main point is the old parent of the moved element that
// exactly corresponds to the
// first erase dependency
if (this.event.erasedElements.containsKey(target))
return;
// If the element has been removed then readded to the same owner,
// it is a false move.
if (target.isValid() && target.getCompositionOwner() == src)
return;
if ( target.isDeleted()) {
this.event.deletedElements.put(target, src);
} else {
// If the relation did not exist, it has to be created : the key
// corresponds to the
// child element (that has been moved) and the value corresponds
// to the old/current owner
// of this element
this.event.erasedElements.put(target, src);
// It can be a move, so the movedElements list is filled with
// the old owner.
this.event.movedElements.put(target, src);
}
} else if (dep.isPartOf()) {
if (this.event.updatedElements.contains(src) == false) {
this.event.updatedElements.add(src);
}
}
}
@objid ("01f42120-0000-018a-0000-000000000000")
@Override
public void visitMoveDependencyAction(final MoveDependencyAction theMoveDependencyAction) {
SmObjectImpl refered = theMoveDependencyAction.getRefered();
// Forget operations on deleted elements
if (refered.isDeleted())
return;
// If the element is already in the list of created elements, it has not
// to be added
if (this.event.createdElements.contains(refered))
return;
// If the element already is in the list of updated elements, it has not
// to be added
if (this.event.updatedElements.contains(refered) == false) {
// If the element already is in the list of created elements, it has
// not to be added
if (this.event.createdElements.contains(refered) == false)
this.event.updatedElements.add(refered);
}
}
@objid ("01f42120-0000-2182-0000-000000000000")
private static boolean isComponentDependency(SmDependency dep) {
return dep.isComponent(); // TODO fix it
}
}
|
[
"antonio.garcia-dominguez@york.ac.uk"
] |
antonio.garcia-dominguez@york.ac.uk
|
2c0352e6d5637b418a2c0483064e675341938651
|
060b67492950d29b1f09b86e8347ea9aaea8c6a2
|
/src/main/java/com/mali/ds/graph/bfs/BusRoutes.java
|
deeb8743e363ab3be6499511048e67e8be34396d
|
[] |
no_license
|
mali-nadfrss/My-new-project
|
f1352929e2e5c30d89b5c78dfa73771ad72281b4
|
515b029883bd65b22b854c60d03eb1b7b3a38118
|
refs/heads/master
| 2023-08-03T09:16:02.492372
| 2023-07-05T06:36:47
| 2023-07-05T06:36:47
| 231,365,274
| 0
| 0
| null | 2022-10-23T02:29:41
| 2020-01-02T11:10:09
|
Java
|
UTF-8
|
Java
| false
| false
| 1,043
|
java
|
package com.mali.ds.graph.bfs;
import java.util.*;
/* Hard
* https://leetcode.com/problems/bus-routes/*/
public class BusRoutes {
public static int numBusesToDestination(int[][] routes, int source, int target) {
//todo
Map<Integer, Set<Integer>> stops = new HashMap<>();
for (int i = 0; i < routes.length; i++) {
for (int j = 0; j < routes[i].length; j++) {
stops.computeIfAbsent(routes[i][j], v -> new HashSet<>());
stops.get(routes[i][j]).add(i);
}
}
int ans = -1;
Queue<Integer> queue = new LinkedList<>();
for (int i : stops.get(source)) {
for (int j = 0; j < routes[i].length; j++) {
if (routes[i][j] != source) {
queue.add(routes[i][j]);
}
while (!queue.isEmpty()){
for (int k : stops.get(queue.poll())) {
// if (k !)
}
}
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(numBusesToDestination(new int[][] {{1, 2, 7}, {3, 6, 7}}, 1, 6));
}
}
|
[
"nmali@modeln.com"
] |
nmali@modeln.com
|
9675be0ae6d4f521e541297c2eaaba90d7348170
|
56d865b47836f3d725de38a2cfcbadbabdae5fe6
|
/src/main/java/kr/ac/daegu/jspmvc/biz/LoginSignUpCmd.java
|
6f76e055913c2fb092869788c4d46cd7e9e91227
|
[] |
no_license
|
dwc04112/jspmvcPublic
|
c56797bd686038c8aea9b9f97bc0f1534c60f070
|
c1db14ffe603041773866a808b36129f9b37335d
|
refs/heads/master
| 2023-08-06T19:16:31.002487
| 2021-09-15T02:11:06
| 2021-09-15T02:11:06
| 404,287,984
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,495
|
java
|
package kr.ac.daegu.jspmvc.biz;
import kr.ac.daegu.jspmvc.common.PasswordEncoder;
import kr.ac.daegu.jspmvc.model.MemberDAO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.UUID;
public class LoginSignUpCmd implements BoardCmd {
@Override
public boolean execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String password = request.getParameter("password");
// 0. password encoding (hashing)
String generatedSalt = String.valueOf(UUID.randomUUID());
String encodedPassword = PasswordEncoder.getEncodedPassword(password, generatedSalt);
MemberDAO memberDAO = new MemberDAO();
try {
// 1. id가 unique한지 아닌지 검사 (db에서 input들어온 id로 검색 한 count 1 이상인지?)
if(memberDAO.existCount(id) > 0) {
return false;
}
// 2. member insert를 위한 최고 id값 을 가져와야함.
int newId = memberDAO.getNewId();
// 3. mId, id, encodedPassword insert
memberDAO.postLoginData(newId, id, encodedPassword, generatedSalt);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return true;
}
}
|
[
"dwc04112@gmail.com"
] |
dwc04112@gmail.com
|
39fb6fc8c465734a5b23974fc0d53dfe887f05e3
|
df149d05f3145353bdb4955355d72451dc0aba5b
|
/src/test/java/com/etermax/conversations/test/integration/SyncMessagesTest.java
|
b4af84f9b858501570b958d89c17fc07177efb9c
|
[] |
no_license
|
LucianoBernal/feeds_api
|
788526291481dcad841ceed90a5824e1891f5071
|
bd763e6bd381a2b2d35052a5358c2287b7d3ffd1
|
refs/heads/master
| 2016-09-13T06:44:23.483434
| 2016-04-27T20:32:30
| 2016-04-27T20:32:30
| 57,245,394
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 7,258
|
java
|
package com.etermax.conversations.test.integration;
import com.etermax.conversations.adapter.ConversationAdapter;
import com.etermax.conversations.adapter.MessageAdapter;
import com.etermax.conversations.adapter.SynchronizationAdapter;
import com.etermax.conversations.dto.AddressedMessageCreationDTO;
import com.etermax.conversations.dto.SyncDTO;
import com.etermax.conversations.error.ClientException;
import com.etermax.conversations.error.GetUserDataException;
import com.etermax.conversations.factory.ConversationRepositoryFactory;
import com.etermax.conversations.resource.ConversationResource;
import com.etermax.conversations.resource.MessagesResource;
import com.etermax.conversations.resource.SyncResource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class SyncMessagesTest {
Lock sequential = new ReentrantLock();
@Before
public void setUp(){
sequential.lock();
}
@After
public void tearDown(){
sequential.unlock();
}
@Test
public void testSyncMessagesWithInvalidDate() {
//Given
ConversationRepositoryFactory conversationRepositoryFactory = Given.givenAConversationRepositoryFactory();
ConversationAdapter conversationAdapter = Given.givenAConversationAdapter(conversationRepositoryFactory);
SynchronizationAdapter synchronizationAdapter = Given.givenASynchronizationAdapter(
conversationRepositoryFactory);
MessageAdapter messageAdapter = Given.givenAMessageAdapter(conversationRepositoryFactory);
MessagesResource messagesResource = givenAMessagesResource(messageAdapter);
ConversationResource conversationResource = new ConversationResource(conversationAdapter);
SyncResource syncMessagesResource = new SyncResource(synchronizationAdapter);
AddressedMessageCreationDTO addressedMessageCreationDTO = givenAMessageCreationDTO();
//When
messagesResource
.saveMessage(addressedMessageCreationDTO);
conversationResource.getConversation("1");
assertThatThrownBy(() -> syncMessagesResource.getConversationSync(1l, "abc", "A2")).isInstanceOf(
ClientException.class)
.hasCauseInstanceOf(GetUserDataException.class).hasRootCauseInstanceOf(NumberFormatException.class);
}
@Test
public void testSyncMessagesWithFutureDate() {
//Given
ConversationRepositoryFactory conversationRepositoryFactory = Given.givenAConversationRepositoryFactory();
ConversationAdapter conversationAdapter = Given.givenAConversationAdapter(conversationRepositoryFactory);
SynchronizationAdapter synchronizationAdapter = Given.givenASynchronizationAdapter(
conversationRepositoryFactory);
MessageAdapter messageAdapter = Given.givenAMessageAdapter(conversationRepositoryFactory);
MessagesResource messagesResource = givenAMessagesResource(messageAdapter);
ConversationResource conversationResource = new ConversationResource(conversationAdapter);
SyncResource syncMessagesResource = new SyncResource(synchronizationAdapter);
AddressedMessageCreationDTO addressedMessageCreationDTO = givenAMessageCreationDTO();
//When
messagesResource.saveMessage(addressedMessageCreationDTO);
conversationResource.getConversation("1");
Given.flushRepository(conversationRepositoryFactory);
List<SyncDTO> syncDTOs = syncMessagesResource.getConversationSync(1l, "16725668400000", "A2"); //1/6/2500
//Then
assertThat(syncDTOs.size()).isEqualTo(0);
}
@Test
public void testSyncHasMore() {
//Given
ConversationRepositoryFactory conversationRepositoryFactory = Given.givenAConversationRepositoryFactory();
ConversationAdapter conversationAdapter = Given.givenAConversationAdapter(conversationRepositoryFactory);
SynchronizationAdapter synchronizationAdapter = Given.givenASynchronizationAdapter(
conversationRepositoryFactory);
MessageAdapter messageAdapter = Given.givenAMessageAdapter(conversationRepositoryFactory);
MessagesResource messagesResource = givenAMessagesResource(messageAdapter);
ConversationResource conversationResource = new ConversationResource(conversationAdapter);
SyncResource syncMessagesResource = new SyncResource(synchronizationAdapter);
AddressedMessageCreationDTO addressedMessageCreationDTO = givenAMessageCreationDTO();
//When
messagesResource.saveMessage(addressedMessageCreationDTO);
Given.flushRepository(conversationRepositoryFactory);
messagesResource.saveMessage(addressedMessageCreationDTO);
messagesResource.saveMessage(addressedMessageCreationDTO);
messagesResource.saveMessage(addressedMessageCreationDTO);
conversationResource.getConversation("1");
Given.flushRepository(conversationRepositoryFactory);
List<SyncDTO> syncDTOs = syncMessagesResource.getConversationSync(1l, "947127600000", "A2"); //1/6/2000
SyncDTO syncDTO = syncDTOs.get(0);
//Then
assertThat(syncDTOs.size()).isEqualTo(1);
assertThat(syncDTO.getHasMore().getHasMore()).isEqualTo(true);
assertThat(syncDTO.getHasMore().getTotalMessages()).isEqualTo(2);
assertThat(syncDTO.getConversationId()).isEqualTo("1");
assertThat(syncDTO.getConversationData().size()).isEqualTo(2);
}
@Test
public void testSyncNoMore() {
//Given
ConversationRepositoryFactory conversationRepositoryFactory = Given.givenAConversationRepositoryFactory();
ConversationAdapter conversationAdapter = Given.givenAConversationAdapter(conversationRepositoryFactory);
SynchronizationAdapter synchronizationAdapter = Given.givenASynchronizationAdapter(
conversationRepositoryFactory);
MessageAdapter messageAdapter = Given.givenAMessageAdapter(conversationRepositoryFactory);
MessagesResource messagesResource = givenAMessagesResource(messageAdapter);
ConversationResource conversationResource = new ConversationResource(conversationAdapter);
SyncResource syncMessagesResource = new SyncResource(synchronizationAdapter);
AddressedMessageCreationDTO addressedMessageCreationDTO = givenAMessageCreationDTO();
//When
messagesResource.saveMessage(addressedMessageCreationDTO);
conversationResource.getConversation("1");
Given.flushRepository(conversationRepositoryFactory);
List<SyncDTO> syncDTOs = syncMessagesResource.getConversationSync(1l, "947127600000", "A2");
SyncDTO syncDTO = syncDTOs.get(0);
//Then
assertThat(syncDTOs.size()).isEqualTo(1);
assertThat(syncDTO.getHasMore().getHasMore()).isEqualTo(false);
assertThat(syncDTO.getHasMore().getTotalMessages()).isEqualTo(0);
assertThat(syncDTO.getConversationId()).isEqualTo("1");
assertThat(syncDTO.getConversationData().size()).isEqualTo(1);
}
private MessagesResource givenAMessagesResource(MessageAdapter messageAdapter) {
return new MessagesResource(messageAdapter);
}
private AddressedMessageCreationDTO givenAMessageCreationDTO() {
AddressedMessageCreationDTO addressedMessageCreationDTO = new AddressedMessageCreationDTO();
addressedMessageCreationDTO.setText("Bla");
addressedMessageCreationDTO.setSenderId(1l);
addressedMessageCreationDTO.setReceiverId(2l);
addressedMessageCreationDTO.setApplication("A2");
return addressedMessageCreationDTO;
}
}
|
[
"luciano.bernal@etermax.com"
] |
luciano.bernal@etermax.com
|
70a05e1d92123208fd73598efccfafdec0aadf69
|
4db17f8d057b9fc19d6a3c1a357333ca173a9ae3
|
/src/main/java/org/markdownwriterfx/util/ActionUtils.java
|
8dd6856de0e28c22eec3eba048b4ad633959bbef
|
[
"BSD-2-Clause"
] |
permissive
|
andreas-oberheim/universal-markup-editor
|
46982c1dda07114e1a5b529a00cdafad1f7a2aeb
|
bd6bbaea26cc9d39e6310bc2270419cbb5c89b07
|
refs/heads/master
| 2021-01-17T15:58:03.152382
| 2016-08-20T21:39:26
| 2016-08-20T21:39:26
| 66,168,975
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 3,751
|
java
|
/*
* Copyright (c) 2015 Karl Tauber <karl at jformdesigner dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* o 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "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 THE COPYRIGHT
* HOLDER OR CONTRIBUTORS 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.markdownwriterfx.util;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Separator;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.ToolBar;
import javafx.scene.control.Tooltip;
import de.jensd.fx.glyphs.fontawesome.utils.FontAwesomeIconFactory;
/**
* Action utilities
*
* @author Karl Tauber
*/
public class ActionUtils
{
public static Menu createMenu(String text, Action... actions) {
return new Menu(text, null, createMenuItems(actions));
}
public static MenuItem[] createMenuItems(Action... actions) {
MenuItem[] menuItems = new MenuItem[actions.length];
for (int i = 0; i < actions.length; i++) {
menuItems[i] = (actions[i] != null)
? createMenuItem(actions[i])
: new SeparatorMenuItem();
}
return menuItems;
}
public static MenuItem createMenuItem(Action action) {
MenuItem menuItem = new MenuItem(action.text);
if (action.accelerator != null)
menuItem.setAccelerator(action.accelerator);
if (action.icon != null)
menuItem.setGraphic(FontAwesomeIconFactory.get().createIcon(action.icon));
menuItem.setOnAction(action.action);
if (action.disable != null)
menuItem.disableProperty().bind(action.disable);
return menuItem;
}
public static ToolBar createToolBar(Action... actions) {
return new ToolBar(createToolBarButtons(actions));
}
public static Node[] createToolBarButtons(Action... actions) {
Node[] buttons = new Node[actions.length];
for (int i = 0; i < actions.length; i++) {
buttons[i] = (actions[i] != null)
? createToolBarButton(actions[i])
: new Separator();
}
return buttons;
}
public static Button createToolBarButton(Action action) {
Button button = new Button();
button.setGraphic(FontAwesomeIconFactory.get().createIcon(action.icon, "1.2em"));
String tooltip = action.text;
if (tooltip.endsWith("..."))
tooltip = tooltip.substring(0, tooltip.length() - 3);
if (action.accelerator != null)
tooltip += " (" + action.accelerator.getDisplayText() + ')';
button.setTooltip(new Tooltip(tooltip));
button.setFocusTraversable(false);
button.setOnAction(action.action);
if (action.disable != null)
button.disableProperty().bind(action.disable);
return button;
}
}
|
[
"karl@jformdesigner.com"
] |
karl@jformdesigner.com
|
12fd5ad2d898c29a298444b88737ae4368285ff5
|
3cce330a3b21ac4d93be515e4a30ef91aa946f97
|
/app/src/main/java/com/example/beacon_hunters/LoginTabFragment.java
|
33f2e667e5122a43f5456ef90e8402a3727a074f
|
[] |
no_license
|
AbdulFaiz123/Beacon-Hunters
|
b49780c3bedaa283e45dae1add68e93cae6345fd
|
a3d521e584a18e807e7ba052613fc85affd6ffa0
|
refs/heads/master
| 2023-03-20T01:47:09.169720
| 2021-03-16T17:07:55
| 2021-03-16T17:07:55
| 346,682,734
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,621
|
java
|
package com.example.beacon_hunters;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class LoginTabFragment extends Fragment {
EditText email,pass;
TextView forgetPass;
Button login;
float v = 0;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.login_tab_fragment,container,false);
email = root.findViewById(R.id.email);
pass = root.findViewById(R.id.pass);
forgetPass = root.findViewById(R.id.forget_pass);
login = root.findViewById(R.id.button);
email.setTranslationX(800);
pass.setTranslationX(800);
forgetPass.setTranslationX(800);
login.setTranslationX(800);
email.setAlpha(v);
pass.setAlpha(v);
forgetPass.setAlpha(v);
login.setAlpha(v);
email.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
pass.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(500).start();
forgetPass.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(500).start();
login.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(700).start();
return root;
}
}
|
[
"53165415+AbdulFaiz123@users.noreply.github.com"
] |
53165415+AbdulFaiz123@users.noreply.github.com
|
c505681795fe63168c73ca0ece06169d6e26b296
|
10bbb49b8b82e67f8aae8568321d5677500738d9
|
/goja-wxchat/src/main/java/com/jfinal/weixin/sdk/msg/out/OutVideoMsg.java
|
32a4c6d6c27af8260b71fa44b62125738142fbb6
|
[
"MIT"
] |
permissive
|
shootboss/goja
|
178acc8f6e7b76863bda556d8fb742649b141ec6
|
1d6aef9c6cd13728f7601ee126d38276a3f1efb5
|
refs/heads/master
| 2021-01-22T20:08:23.456712
| 2014-11-15T15:21:34
| 2014-11-15T15:21:34
| 26,850,053
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,834
|
java
|
/**
* Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.jfinal.weixin.sdk.msg.out;
import com.jfinal.weixin.sdk.msg.in.InMsg;
/**
回复视频消息
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType><![CDATA[video]]></MsgType>
<Video>
<MediaId><![CDATA[media_id]]></MediaId>
<Title><![CDATA[title]]></Title>
<Description><![CDATA[description]]></Description>
</Video>
</xml>
*/
public class OutVideoMsg extends OutMsg {
public static final String TEMPLATE =
"<xml>\n" +
"<ToUserName><![CDATA[${__msg.toUserName}]]></ToUserName>\n" +
"<FromUserName><![CDATA[${__msg.fromUserName}]]></FromUserName>\n" +
"<CreateTime>${__msg.createTime}</CreateTime>\n" +
"<MsgType><![CDATA[${__msg.msgType}]]></MsgType>\n" +
"<Video>\n" +
"<MediaId><![CDATA[${__msg.mediaId}]]></MediaId>\n" +
"<Title><![CDATA[${(__msg.title)!}]]></Title>\n" +
"<Description><![CDATA[${(__msg.description)!}]]></Description>\n" +
"</Video>\n" +
"</xml>";
private String mediaId;
private String title; // 不是必须
private String description; // 不是必须
public OutVideoMsg() {
this.msgType = "video";
}
public OutVideoMsg(InMsg inMsg) {
super(inMsg);
this.msgType = "video";
}
public String getMediaId() {
return mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
[
"poplar1123@gmail.com"
] |
poplar1123@gmail.com
|
9e90d549195591dce43b163e5dfc003068a42364
|
aeb1c78ba5060b28c8839890f8c05071bb5ba2d9
|
/core/com/xsc/lottery/task/ticket/.svn/text-base/TicketTreatmentWork.java.svn-base
|
7a64de34fb7793661898961859cd798190fb4ae0
|
[] |
no_license
|
THEMING/TZLottery
|
425de1b8c3e19318de238153ec3a3d88ef28af71
|
bb7484deb7b11b97bbef26b96cef40a1f01a704c
|
refs/heads/master
| 2021-01-18T13:50:32.011316
| 2017-03-22T01:17:20
| 2017-03-22T01:17:20
| 24,556,080
| 6
| 6
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 24,793
|
package com.xsc.lottery.task.ticket;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import org.hibernate.StaleObjectStateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException;
import com.xsc.lottery.entity.business.AdminMobile;
import com.xsc.lottery.entity.business.LotteryTerm;
import com.xsc.lottery.entity.business.Order;
import com.xsc.lottery.entity.business.OrderQueue;
import com.xsc.lottery.entity.business.PlanItem;
import com.xsc.lottery.entity.business.TermTypeConfig;
import com.xsc.lottery.entity.business.Ticket;
import com.xsc.lottery.entity.business.SmsLog.SmsLogType;
import com.xsc.lottery.entity.enumerate.LotteryType;
import com.xsc.lottery.entity.enumerate.OrderStatus;
import com.xsc.lottery.entity.enumerate.SendTicketPlat;
import com.xsc.lottery.entity.enumerate.TicketSPStatus;
import com.xsc.lottery.entity.enumerate.TicketStatus;
import com.xsc.lottery.java.common.CommonScheduledThreadPoolExecutor;
import com.xsc.lottery.java.common.SystemWarningNotify;
import com.xsc.lottery.service.business.AdminMobileService;
import com.xsc.lottery.service.business.LotteryOrderService;
import com.xsc.lottery.service.business.LotteryPlanService;
import com.xsc.lottery.service.business.OrderQueueService;
import com.xsc.lottery.service.business.SmsLogService;
import com.xsc.lottery.service.business.TermConfigService;
import com.xsc.lottery.task.email.Email369TaskExcutor;
import com.xsc.lottery.task.message.MessageTaskExcutor;
import com.xsc.lottery.util.DateUtil;
public abstract class TicketTreatmentWork implements ApplicationListener
{
// 用于计时,避免重复发送短信 至少5分钟一次
private Calendar xtTime = Calendar.getInstance();
@Autowired
private LotteryOrderService orderService;
@Autowired
private SmsLogService smsLogService;
@Autowired
private LotteryPlanService planService;
@Autowired
private TicketBusinessFactory ticketBusinessFactory;
@Autowired
private TermConfigService termConfigService;
@Autowired
private Email369TaskExcutor email369TaskExcutor;
@Autowired
private OrderQueueService orderQueueService;
@Autowired
private MessageTaskExcutor messageTaskExcutor;
@Autowired
private AdminMobileService adminMobileService;
/** 待拆票队列 */
protected LinkedBlockingQueue<Order> takerQueue = new LinkedBlockingQueue<Order>();
/** 待送票队列 */
protected LinkedBlockingQueue<Order> deliveQueue = new LinkedBlockingQueue<Order>();
/** 待送票二级队列 */
protected LinkedBlockingQueue<Order> deliveSecondLevelQueue = new LinkedBlockingQueue<Order>();
/** 待检票队列 */
protected LinkedBlockingQueue<Order> checkQueue = new LinkedBlockingQueue<Order>();
/** 待查SP的ticket队列 */
protected LinkedBlockingQueue<Ticket> checkSPTicketQueue = new LinkedBlockingQueue<Ticket>();
protected Logger logger = LoggerFactory.getLogger(this.getClass());
protected boolean start = false;
protected TicketCheckBucket bucket = new TicketCheckBucket();
public abstract SendTicketPlat getTicketPlat();
public abstract void putOrderToQueue(Order order);
/** 拆票 */
protected abstract List<Ticket> takeTicket(Order order,
List<PlanItem> planItems) throws Exception;
/** 到orderqueue取出相应的order */
protected abstract List<OrderQueue> getOrderQueue() throws Exception;
/** 删除orderqueue中status=1的值 */
protected abstract void deleteOrderQueue(List<OrderQueue> allList) throws Exception;
/** 检查中奖奖金比对 */
public abstract String getJiangjin(Ticket ticket);
/** 获取开奖结果 */
public abstract void getOpenResult(LotteryTerm term);
/** 获取当期中奖订单 */
public abstract List<winTicketDis> getWinTicketByTerm(LotteryTerm term);
/** 送票 */
protected abstract void deliveTicket(Ticket ticket);
/** 批量送票 */
protected abstract void deliveTicket(List<Ticket> tickets);
/** 检票 */
protected abstract void checkTicket(Ticket ticket);
/** 批量检票 */
protected abstract void checkTicket(List<Ticket> tickets);
/** 判断是否可以往对方送票 */
protected abstract boolean allowed(LotteryTerm term);
/** 检查成功出票的SP值 */
protected abstract void checkTicketSP(Ticket ticket);
/** 注册 */
@SuppressWarnings("unused")
@PostConstruct
private void register()
{
ticketBusinessFactory.registerTreatmentTicketInMap(this);
}
protected TermTypeConfig getTermTypeConfig(LotteryType lotteryType)
{
return termConfigService.getConfigByType(lotteryType);
}
protected void take(Order order)
{
try {
order = orderService.findById(order.getId());
List<PlanItem> planItems = planService.getPlanItemByPlanID(order.getPlan().getId());
List<Ticket> tickets = takeTicket(order, planItems);
orderService.saveSuccessTakeTicket(order, tickets, getTicketPlat().name());// 方案状态 ------ 委托中
addDelive(order);// 拆完票放入一级拆票队列
}
catch (Exception e) {
String description = getTicketPlat().name() + " 队列拆票异常, 请查看日志";
logger.info(description, e);
SystemWarningNotify.addWarningDescription(description);
}
}
private void delive(Order order)
{
// 快开奖了,没送出去的不送了,立即交给检票队列
if (order.getType().equals(LotteryType.竞彩足球) || order.getType().equals(LotteryType.竞彩篮球)) {
if(order.getLastMatch().getOpenPrizeTime() == null ||
order.getLastMatch().getOpenPrizeTime().before(DateUtil.now())) {
addCheck(order, 0);
return;
}
}
else if (order.getTerm().getOpenPrizeTime().before(DateUtil.now())) {
addCheck(order, 0);
return;
}
// 不受的话,延时一会后放到二级出票队列再试
if (!allowed(order.getTerm())) {
addSecondDelive(order, 90);
return;
}
List<Ticket> tickets = orderService.getTicketByOrder(order);
int i = 0;
for (Ticket ticket : tickets) {
if (ticket.getStatus().equals(TicketStatus.未送票)) {
if (i < 500) {
deliveTicket(ticket);
if (!ticket.getStatus().equals(TicketStatus.未送票)) {
orderService.saveTicket(ticket);
}
} else
break;
i++;
}
}
// 查一下所有票,是不是都出票了
if (isAllDelived(tickets)) {// 全部出票,则去检票
order.setStatus(OrderStatus.出票中);
orderService.save(order);
if (isAllChecked(tickets)) {
addCheck(order, 0);
}
else {
addCheck(order, 30);
}
}
else {
// 否则,放到二级出票队列再出票
addSecondDelive(order, 20);
}
}
/**
* 检查票 到了开奖时间还在出票的票置为出票失败
*/
private void check(Order order)
{
List<Ticket> tickets = orderService.getTicketByOrder(order);
List<Ticket> returnTickets = new ArrayList<Ticket>();
boolean timeout = false;
if (order.getType().equals(LotteryType.竞彩足球) || order.getType().equals(LotteryType.竞彩篮球)) {
if(order.getLastMatch().getOpenPrizeTime() == null ||
order.getLastMatch().getOpenPrizeTime().before(DateUtil.now())) {
timeout = true;
}
}
else if(order.getTerm().getOpenPrizeTime().before(DateUtil.now())) {
timeout = true;
}
if (timeout) {
logger.info("方案编号为:" + order.getPlan().getNumberNo() + "的票出票时间超于开奖时间");
xtTime.add(Calendar.MINUTE, 5);
Calendar c = Calendar.getInstance();
if (xtTime.compareTo(c) < 0) {
String str = "【一彩票网】用户名为:" + order.getCustomer().getNickName() + "购买的" + order.getTerm().getTermNo() + "期" + order.getType() + ",订单ID为:"+ order.getId() +",订单号为:" + order.getPlan().getNumberNo() + "的订单,开奖时间到仍在出票中!";
System.out.println("5分钟一次:" + c.getTime());
List<AdminMobile> adminMobiles = adminMobileService.getAllAdminMobile();
for (AdminMobile adminMobile : adminMobiles) {
smsLogService.saveSmsLog(adminMobile.getMobile(), str, null,SmsLogType.WARN);
//messageTaskExcutor.addNotifySM(adminMobile.getMobile(), str);
}
xtTime = c;
xtTime.add(Calendar.MINUTE, 5);
}
return;
// 可以看是不是有退票了
/*
for (Ticket ticket : tickets) {
if(!ticket.getStatus().equals(TicketStatus.已出票)) {
ticket.setStatus(TicketStatus.出票失败);
ticket.setOtherMsg("出票超过开奖时间");
orderService.saveTicket(ticket);
returnTickets.add(ticket);
}
}
*/
}
else {
int times = tickets.size() / 50;
for(int i = 0; i < times; i++) {
List<Ticket> tics = tickets.subList(50*i, 50*(i+1));
checkTicket(tics);
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
logger.info("check sleep exception");
}
}
List<Ticket> tics = tickets.subList(50*times, tickets.size());
checkTicket(tics);
for (Ticket ticket : tickets) {
if (!ticket.getStatus().equals(TicketStatus.出票中)) {
//(1)如果已经出票,并且需要检查赔率,设置检查赔率状态
boolean bNeedToCheckSP = false;
if (ticket.getStatus().equals(TicketStatus.已出票)) {
if(needToCheckSP(ticket))
{
bNeedToCheckSP = true;
ticket.setSpstatus(TicketSPStatus.需要检查SP);
}
}
//(2)出票状态改变,需要保存
orderService.saveTicket(ticket);
//(3)已经出票,并且需要检查赔率,加入赔率检查列表,去检查赔率。
//该段不能和(1)合并,以防检查赔率比保存Ticket更快。
if(bNeedToCheckSP)
{
addCheckSP(ticket, 0);
}
}
}
if (!isAllChecked(tickets)) {// 如果存在没检票的,过一会再检
addCheck(order, 30);
return;
}
// 可以看是不是有退票了
for (Ticket ticket : tickets) {
if (!ticket.getStatus().equals(TicketStatus.已出票)) {
returnTickets.add(ticket);
}
}
}
finishTicketBusiness(order, returnTickets);
OrderStatus oStatus = order.getStatus();
if(oStatus == OrderStatus.出票失败 || oStatus == OrderStatus.部分出票成功)
{
email369TaskExcutor.addNotifyOrder(order);
}
}
// 完成注单的票务业务
public void finishTicketBusiness(Order order, List<Ticket> returnTickets)
{
try {
orderService.finishTicketBusiness(order, returnTickets);
if(order!=null&&order.getStatus()!=null&&(OrderStatus.出票失败.equals(order.getStatus())||OrderStatus.出票成功.equals(order.getStatus())||OrderStatus.部分出票成功.equals(order.getStatus()))){
orderService.sendOrderDetailEmail(order);
}
}
catch (Exception e) {
if (e instanceof HibernateOptimisticLockingFailureException
|| e.getClass().getName().equals(
StaleObjectStateException.class.getName())) {
try {
Thread.sleep(1000);
}
catch (InterruptedException e1) {
}
finishTicketBusiness(order, returnTickets);
e.printStackTrace();
}
}
}
public void addTaker(Order order)
{
takerQueue.offer(order);
}
private void addDelive(Order order)
{
deliveQueue.offer(order);
}
private boolean isAllDelived(List<Ticket> tickets)
{
for (Ticket t : tickets) {
if (t.getStatus().equals(TicketStatus.未送票)) {
return false;
}
}
return true;
}
private boolean isAllChecked(List<Ticket> tickets)
{
for (Ticket t : tickets) {
if (t.getStatus().equals(TicketStatus.出票中)) {
return false;
}
}
return true;
}
private void addSecondDelive(final Order order, int delay)
{
Runnable task = new Runnable()
{
public void run()
{
deliveSecondLevelQueue.offer(order);
}
};
CommonScheduledThreadPoolExecutor.getInstance().schedule(task, delay,
TimeUnit.SECONDS);
}
private void addCheck(final Order order, int delay)
{
Runnable task = new Runnable()
{
public void run()
{
checkQueue.offer(order);
}
};
CommonScheduledThreadPoolExecutor.getInstance().schedule(task, delay,
TimeUnit.SECONDS);
}
public void onApplicationEvent(ApplicationEvent event)
{
if (event instanceof ContextRefreshedEvent && !start) {
logger.info("{} 处理票进程启动........", this.getTicketPlat().name());
CommonScheduledThreadPoolExecutor.getInstance().execute(
createTakerTask());
CommonScheduledThreadPoolExecutor.getInstance().execute(
createDeliveTask());
CommonScheduledThreadPoolExecutor.getInstance().execute(
createCheckTask());
CommonScheduledThreadPoolExecutor.getInstance().execute(
createSecondLevelDeliveTask());
CommonScheduledThreadPoolExecutor.getInstance().execute(
createCheckSPTask());
start = true;
}
}
/** 拆票队列线程 */
private Runnable createTakerTask()
{
return new Runnable()
{
public void run()
{
logger.info(getTicketPlat().name() + " 拆票队列启动!");
while (true) {
try {
Calendar thetime=Calendar.getInstance();
List<OrderQueue> allList=null;
//6-7 delay to send ticket
if((thetime.get(Calendar.HOUR_OF_DAY)!=6)&&(thetime.get(Calendar.HOUR_OF_DAY)!=7))
{
allList = getOrderQueue();
}
if(allList == null || allList.size() == 0)
{
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else
{
deleteOrderQueue(allList);
}
}
catch (Exception e) {
String description = getTicketPlat().name() + " 队列拆票异常,请查看日志";
logger.info(description, e);
SystemWarningNotify.addWarningDescription(description);
}
}
}
};
}
/** 送票队列线程 */
private Runnable createDeliveTask()
{
List<Order> orders = orderService.getOrderByStatusAndTicketBusinessName(
OrderStatus.待出票, getTicketPlat().name());
for (Order order : orders) {
deliveQueue.offer(order);
}
return new Runnable()
{
public void run()
{
logger.info(getTicketPlat().name() + " 送票队列启动!");
while (true) {
Order order = null;
try {
order = deliveQueue.take();
delive(order);
}
catch (Exception e) {
if(order.getStatus().equals(OrderStatus.待出票)) {
addSecondDelive(order, 90);
}
String description = getTicketPlat().name()
+ " 送票队列异常,请查看日志";
logger.info(description, e);
SystemWarningNotify.addWarningDescription(description);
}
}
}
};
}
/** 送票队列线程 */
private Runnable createSecondLevelDeliveTask()
{
return new Runnable()
{
public void run()
{
logger.info(getTicketPlat().name() + " 二级送票队列启动!");
while (true) {
Order order = null;
try {
order = deliveSecondLevelQueue.take();
delive(order);
}
catch (Exception e) {
if(order.getStatus().equals(OrderStatus.待出票)) {
addSecondDelive(order, 90);
}
String description = getTicketPlat().name()
+ " 二级送队列异常,请查看日志";
logger.info(description, e);
SystemWarningNotify.addWarningDescription(description);
}
}
}
};
}
/** 检票队列线程 */
private Runnable createCheckTask()
{
List<Order> orders = orderService.getOrderByStatusAndTicketBusinessName(
OrderStatus.出票中, getTicketPlat().name());
for (Order order : orders) {
checkQueue.offer(order);
}
return new Runnable()
{
public void run()
{
logger.info(getTicketPlat().name() + " 检票队列启动!");
while (true) {
try {
Order order = checkQueue.take();
check(order);
}
catch (Exception e) {
String description = getTicketPlat().name()+ " 检票队列异常,请查看日志";
logger.info(description, e);
SystemWarningNotify.addWarningDescription(description);
}
}
}
};
}
/** 竞彩检查即时SP线程 */
private Runnable createCheckSPTask()
{
List<Ticket> tickets = orderService.getTicketsNeedCheckSP();
for (Ticket ticket : tickets) {
checkSPTicketQueue.offer(ticket);
}
return new Runnable()
{
public void run()
{
logger.info(getTicketPlat().name() + " 检查赔率线程启动!");
while (true) {
try {
Ticket ticket = checkSPTicketQueue.take();
checkSP(ticket);
}
catch (Exception e) {
String description = getTicketPlat().name()
+ " 二级送队列异常,请查看日志";
logger.info(description, e);
SystemWarningNotify.addWarningDescription(description);
}
}
}
};
}
private void checkSP(Ticket ticket)
{
checkTicketSP(ticket);
if (ticket.getRatio() != null) {
ticket.setSpstatus(TicketSPStatus.获取SP成功);
orderService.saveTicket(ticket);
}
else{
addCheckSP(ticket, 30);
}
}
private boolean needToCheckSP(final Ticket ticket)
{
boolean flag = false;
if((ticket.getType().equals(LotteryType.竞彩足球) || ticket.getType().equals(LotteryType.竞彩篮球)) && ticket.getRatio() == null)
{
flag = true;
}
return flag;
/*
if (ticket.getType().equals(LotteryType.竞彩足球) &&
ticket.getRatio() == null &&
!ticket.getContent().split("\\|")[2].split("\\*")[0].equals("1")) { // 非单场过关
return true;
}
if (ticket.getType().equals(LotteryType.竞彩足球) &&
ticket.getRatio() == null &&
ticket.getContent().split("\\|")[0].equals("CBF")&&
ticket.getContent().split("\\|")[2].split("\\*")[0].equals("1")) { // 单场过关
return true;
}
if (ticket.getType().equals(LotteryType.竞彩篮球) &&
ticket.getRatio() == null &&
!ticket.getContent().split("\\|")[2].split("\\*")[0].equals("1")) { // 非单场过关
return true;
}
if (ticket.getType().equals(LotteryType.竞彩篮球) &&
ticket.getRatio() == null &&
ticket.getContent().split("\\|")[0].equals("SFC")&&
ticket.getContent().split("\\|")[2].split("\\*")[0].equals("1")) { // 单场过关
return true;
}
return false;
*/
}
private void addCheckSP(final Ticket ticket, int delay)
{
Runnable task = new Runnable()
{
public void run()
{
if(needToCheckSP(ticket))
{
checkSPTicketQueue.offer(ticket);
}
}
};
CommonScheduledThreadPoolExecutor.getInstance().schedule(task, delay,
TimeUnit.SECONDS);
}
public class winTicketDis
{
public String getOrderId()
{
return orderId;
}
public void setOrderId(String orderId)
{
this.orderId = orderId;
}
public BigDecimal getWinMoney()
{
return winMoney;
}
public void setWinMoney(BigDecimal winMoney)
{
this.winMoney = winMoney;
}
public BigDecimal getTaxMoney()
{
return taxMoney;
}
public void setTaxMoney(BigDecimal taxMoney)
{
this.taxMoney = taxMoney;
}
public winTicketDis(String orderId, BigDecimal winMoney,
BigDecimal taxMoney)
{
this.orderId = orderId;// 订单表ID
this.winMoney = winMoney;
this.taxMoney = taxMoney;
}
private String orderId;
private BigDecimal winMoney = BigDecimal.ZERO;;
private BigDecimal taxMoney = BigDecimal.ZERO;;
}
//从把order放进orderqueue中
/*
public void putOrderToQueue(Order order)
{
OrderQueue orderQueue = new OrderQueue();
orderQueue.setOrderId(order.getId());
orderQueue.setStatus(0);
orderQueue.setSendTicketPlat(0);
orderQueueService.save(orderQueue);
}
*/
//修改orderqueue的相应的状态
public void changeStatus(Long orderId, int status)
{
OrderQueue orderQueue = orderQueueService.getOrderQueueByOrderId(orderId);
if(orderQueue == null)
{
return;
}
else
{
orderQueue.setStatus(status);
orderQueueService.save(orderQueue);
}
}
/**
* <pre>
* 期次查询
* </pre>
* @param type 玩法
*/
protected abstract void queryTerm(LotteryType type);
}
|
[
"306081148@qq.com"
] |
306081148@qq.com
|
|
53dae582e462a2d37f4847659e6882f9f2c2b3dc
|
837c0a513668863f66c49a0127cce9cf81699870
|
/Day2/TimeTracker/src/main/java/edu/timetracker/service/TimeKeeper.java
|
b4f9da1a99141ffb4320006e84ca2e71f568b751
|
[] |
no_license
|
HiddenLeafVillage/TDD-Session
|
e7a40142e7c3a124c63203e4c26e4c47bb6e762b
|
a13c88072c401e02104a3fe608c8e0c487c470c4
|
refs/heads/master
| 2022-06-22T22:50:44.347140
| 2020-02-05T03:24:42
| 2020-02-05T03:24:42
| 237,813,108
| 0
| 0
| null | 2022-05-20T21:24:39
| 2020-02-02T18:04:27
|
Java
|
UTF-8
|
Java
| false
| false
| 1,305
|
java
|
package edu.timetracker.service;
import static edu.timetracker.persistence.Persistence.timeRecord;
import static java.util.Optional.ofNullable;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.UUID;
import edu.timetracker.model.TimeInfo;
import edu.timetracker.model.User;
public class TimeKeeper {
private UserService userService;
public TimeKeeper(UserService userService) {
super();
this.userService = userService;
}
public void startAt(UUID id, LocalDateTime start) {
User user = userService.findUser(id).orElseThrow(NoSuchElementException::new);
timeRecord.put(id, new TimeInfo(UUID.randomUUID(), start, user));
}
public void endAt(UUID id, LocalDateTime end) {
TimeInfo timeInfo = getTimeInfo(id).orElseThrow(NoSuchElementException::new);
timeInfo.setEndTime(end);
timeRecord.put(id, timeInfo);
}
public Optional<TimeInfo> getTimeInfo(UUID id) {
return ofNullable(timeRecord.get(id));
}
public RewardService getRewardStatus(UUID id) {
TimeInfo info = getTimeInfo(id).orElseThrow(NoSuchElementException::new);
long elapsedTime = info.getStartTime().until(info.getEndTime(), ChronoUnit.MINUTES);
return RewardFacotry.getReward(elapsedTime);
}
}
|
[
"esiddharth1894@gmail.com"
] |
esiddharth1894@gmail.com
|
f18185b5351466d6a5c7a9c7c3a6bf27b6e9ec02
|
f1bfc3990efdd015fad6ef37923c0a3ff69bd56f
|
/src/io/match/gui/center/match/MatchRow.java
|
575df71b93dbb2a7f1423a79819c6662da3a1225
|
[] |
no_license
|
minhhoangtcu/Match
|
c49a8511f27fcc7896496e9ebd5c666790b45800
|
34f3621282c15187e2d6798835a3291c0c1d854b
|
refs/heads/master
| 2021-01-10T06:42:39.526146
| 2016-03-28T21:23:57
| 2016-03-28T21:23:57
| 50,064,859
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,453
|
java
|
package io.match.gui.center.match;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleStringProperty;
public class MatchRow {
private final SimpleStringProperty studentName;
private final SimpleStringProperty facultyName;
private final SimpleDoubleProperty probability;
public MatchRow(String studentName, String facultyName, double probability) {
this.studentName = new SimpleStringProperty(studentName);
this.facultyName = new SimpleStringProperty(facultyName);
this.probability = new SimpleDoubleProperty(probability);
}
public String getStudentName() {
return studentName.get();
}
public void setStudentName(String studentName) {
this.studentName.set(studentName);
}
public SimpleStringProperty studentNameProperty() {
return studentName;
}
public String getFacultyName() {
return facultyName.get();
}
public void setFacultyName(String facultyName) {
this.facultyName.set(facultyName);
}
public SimpleStringProperty facultyNameProperty() {
return facultyName;
}
public double getProbability() {
return probability.get();
}
public void setProbability(double probability) {
this.probability.set(probability);
}
public SimpleDoubleProperty probabilityProperty() {
return probability;
}
}
|
[
"antonxuanquang@yahoo.com"
] |
antonxuanquang@yahoo.com
|
1998403231bc4903c6633584aed330a00c8ea4be
|
fbc97617fa679de8678c4bea7ffc5c8ecdcf539c
|
/SubSupper.java
|
33582dfdb105cd7688f1c2b67a228c4b730b4d38
|
[] |
no_license
|
AshwinRajvanshi/Basic-java
|
7634c442ba60b06ab91f7505ab2ffaf35bf8baf2
|
a1f3cea0d5146ff3714d90c72944184ff1817f83
|
refs/heads/master
| 2021-01-01T18:15:25.733262
| 2017-07-25T09:22:23
| 2017-07-25T09:22:23
| 98,288,236
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 569
|
java
|
class SubSupper{
public static void main (String s[]) {
SubSupper ss = new SubSupper();
ss.method();
}
public void method (){
Sub sub=new Sub ();
sub.display();
System.out.println("This is practice Session ");
}
class Super{
int num = 20;
public void display(){
System.out.println("How are you ? ");
}
}
class Sub extends Super {
int num=10 ;
public void display ( ){
System.out.println("I'm Fine ");
super.display();
}
}
}
|
[
"aswinrajvanshi@gmail.com"
] |
aswinrajvanshi@gmail.com
|
bd088ddadef112f251372cb5a83a8577904c538a
|
63a9f496209254f0dc44a235e8637d07066828c4
|
/src/com/witkey/service/MailService.java
|
792d72021835557dca9ebf3aad85d20ea6ce09ce
|
[] |
no_license
|
laisanxin/witkeyServer
|
6142c5f576695ca8a539fb9d457f631a3e30c485
|
35389786842b20d1832b924bc4c1ee4956535974
|
refs/heads/master
| 2020-03-12T22:42:10.083604
| 2018-04-25T05:00:40
| 2018-04-25T05:00:40
| 130,814,394
| 0
| 0
| null | null | null | null |
GB18030
|
Java
| false
| false
| 2,973
|
java
|
package com.witkey.service;
import java.util.Date;
import java.util.Properties;
import java.util.Map;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import org.springframework.stereotype.Service;
@Service
public class MailService {
public static final String SMTPSERVER = "smtp.163.com";
public static final String SMTPPORT = "465";
public static final String ACCOUT = "laisanxinll@163.com";
public static final String PWD = "wy13758813110";
private String receiveMail;
private String sendContent;
public void sendMail(String receiveMail, String sendContent) throws Exception{
this.receiveMail = receiveMail;
this.sendContent = sendContent;
// 创建邮件配置
Properties props = new Properties();
props.setProperty("a", "b");
props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
props.setProperty("mail.smtp.host", SMTPSERVER); // 发件人的邮箱的 SMTP 服务器地址
props.setProperty("mail.smtp.port", SMTPPORT);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
props.setProperty("mail.smtp.ssl.enable", "true");// 开启ssl
// 根据邮件配置创建会话,注意session别导错包
Session session = Session.getDefaultInstance(props);
// 开启debug模式,可以看到更多详细的输入日志
//session.setDebug(true);
//创建邮件
MimeMessage message = createEmail(session);
//获取传输通道
Transport transport = session.getTransport();
transport.connect(SMTPSERVER, ACCOUT, PWD);
//连接,并发送邮件
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
private MimeMessage createEmail(Session session) throws Exception {
// 根据会话创建邮件
MimeMessage msg = new MimeMessage(session);
// address邮件地址, personal邮件昵称, charset编码方式
InternetAddress fromAddress = new InternetAddress(ACCOUT,
"校园Witkey", "utf-8");
// 设置发送邮件方
msg.setFrom(fromAddress);
InternetAddress receiveAddress = new InternetAddress(
receiveMail, "test", "utf-8");
// 设置邮件接收方
msg.setRecipient(RecipientType.TO, receiveAddress);
// 设置邮件标题
msg.setSubject("邮箱验证", "utf-8");
msg.setText(sendContent);
// 设置显示的发件时间
msg.setSentDate(new Date());
// 保存设置
msg.saveChanges();
return msg;
}
}
|
[
"1255490926@qq.com"
] |
1255490926@qq.com
|
a1185c2a5043035a2d55de29ed85903002b67350
|
78e9273c9ccc19248acef3ec7cf64edff305aeae
|
/app/src/main/java/com/example/ticketunion/presenter/impl/TicketPresentImpl.java
|
858537d131435af8e86211af66432e06775177ad
|
[
"Apache-2.0"
] |
permissive
|
tttttz/TicketUnion
|
42ed5589a321fedcd657808bf92e589e343ed55a
|
2bb771417c8a9b4e8eddde348e6f476f94e65aaa
|
refs/heads/master
| 2022-10-16T14:53:54.911853
| 2020-06-08T15:23:23
| 2020-06-08T15:23:23
| 264,622,949
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 3,666
|
java
|
package com.example.ticketunion.presenter.impl;
import com.example.ticketunion.model.Api;
import com.example.ticketunion.model.domain.TicketParams;
import com.example.ticketunion.model.domain.TicketResult;
import com.example.ticketunion.presenter.ITicketPresenter;
import com.example.ticketunion.utils.LogUtil;
import com.example.ticketunion.utils.RetrofitManager;
import com.example.ticketunion.utils.UrlUtils;
import com.example.ticketunion.view.ITicketPagerCallback;
import java.net.HttpURLConnection;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
/**
* @ProjectName: TicketUnion
* @Author: Tz
* @CreateDate: 2020/5/26 16:34
* God bless my code!
*/
public class TicketPresentImpl implements ITicketPresenter {
private String mCover;
private TicketResult mResult;
enum LoadState {
LOADING, SUCCESS, ERROR, NONE
}
private LoadState mCurrentState = LoadState.NONE;
private ITicketPagerCallback mCallback = null;
@Override
public void getTicket(String title, String url, String cover) {
onTicketLoading();
mCover = cover;
LogUtil.d(this, "title ==> " + title);
LogUtil.d(this, "url ==> " + url);
LogUtil.d(this, "cover ==> " + cover);
//获得的url需要前面加上https:
String targetUrl = UrlUtils.getTicketUrl(url);
Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
Api api = retrofit.create(Api.class);
TicketParams ticketParams = new TicketParams(targetUrl, title);
Call<TicketResult> task = api.getTicket(ticketParams);
task.enqueue(new Callback<TicketResult>() {
@Override
public void onResponse(Call<TicketResult> call, Response<TicketResult> response) {
int code = response.code();
LogUtil.d(TicketPresentImpl.this, "ticket code ==> " + code);
if (code == HttpURLConnection.HTTP_OK) {
mResult = response.body();
LogUtil.d(TicketPresentImpl.this, "result ==> " + mResult);
onTicketLoadSuccess();
} else {
onLoadTickError();
}
}
@Override
public void onFailure(Call<TicketResult> call, Throwable t) {
onLoadTickError();
}
});
}
private void onTicketLoadSuccess() {
if (mCallback != null) {
mCallback.onTicketLoaded(mCover, mResult);
} else {
mCurrentState = LoadState.SUCCESS;
}
}
private void onLoadTickError() {
if (mCallback != null) {
mCallback.onError();
} else {
mCurrentState = LoadState.ERROR;
}
}
@Override
public void registerViewCallback(ITicketPagerCallback callback) {
this.mCallback = callback;
if (mCurrentState != LoadState.NONE) {
//说明状态已经变了
//更新UI
if (mCurrentState == LoadState.SUCCESS) {
onTicketLoadSuccess();
} else if (mCurrentState == LoadState.ERROR) {
onLoadTickError();
} else if (mCurrentState == LoadState.LOADING) {
onTicketLoading();
}
}
}
private void onTicketLoading() {
if (mCallback != null) {
mCallback.onLoading();
} else {
mCurrentState = LoadState.LOADING;
}
}
@Override
public void unregisterViewCallback(ITicketPagerCallback callback) {
this.mCallback = null;
}
}
|
[
"894661727@qq.com"
] |
894661727@qq.com
|
eed58bf106f781df1a2c39da2091f338578299b7
|
2a88516340c27a78eaac7e36f6a345dcbfd42afc
|
/teachersupport/src/main/java/com/nokia/teachersupport/person/ContactController.java
|
1601dfab57505b28d220043444aaf185f0bddd22
|
[] |
no_license
|
jakubpw/TeacherSupportApp1
|
fa5e5a2e0444dfcffba6ac69c04fbecd4e9ed6c9
|
5c247d96d0e1e237455f4b8d218122cfab7583da
|
refs/heads/master
| 2020-03-25T02:00:04.802943
| 2018-08-02T08:54:31
| 2018-08-02T08:54:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 794
|
java
|
package com.nokia.teachersupport.person;
import com.nokia.teachersupport.currentUser.CurrentUser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Objects;
@Controller
public class ContactController {
/* To cos to tak naprawde nie zwraca string tylko tutaj mamy parsowanie calej str html na string jakby
* strone index on nam zparsuje na string ktory jest czytelny dla app */
@GetMapping("/teacherSupportContact")
String contact(Model model){
model.addAttribute("currentUserName",Objects.requireNonNull(CurrentUser.getCurrentUserName()));
return "teacherSupportContact";
}
}
|
[
"karolina.makowska.ext@nokia.com"
] |
karolina.makowska.ext@nokia.com
|
8b55aa6ff537c41d1bf680161fbcfb61149fcbf3
|
d4e0a234b39a82a4c928e103330c42e66125fdfb
|
/src/main/java/ch/tralala/StaticShit.java
|
4adcd9dcd2a48c3d607b036d69d23fc182c1e896
|
[] |
no_license
|
hadoken79/jitPackCamelTest
|
5495a71d9161e170476dce9acbbeeba287a79863
|
17a68d17a5027c6e57cbf1128d499181cbf44017
|
refs/heads/main
| 2023-07-27T10:15:24.762933
| 2021-08-28T07:00:36
| 2021-08-28T07:00:36
| 400,508,116
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 107
|
java
|
package ch.tralala;
public class StaticShit {
public static int addprop(){
return 42;
}
}
|
[
"linus.pauls@irix.ch"
] |
linus.pauls@irix.ch
|
7dcf6c1b5a42494553b3e8e836f4750c0a9714f6
|
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
|
/eclipsejdt_cluster/52042/src_1.java
|
9215afbd48918fa970b0cce04222d93518b161fd
|
[] |
no_license
|
martinezmatias/GenPat-data-C3
|
63cfe27efee2946831139747e6c20cf952f1d6f6
|
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
|
refs/heads/master
| 2022-04-25T17:59:03.905613
| 2020-04-15T14:41:34
| 2020-04-15T14:41:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 292,683
|
java
|
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.core.tests.dom;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Map;
import junit.framework.Test;
import org.eclipse.jdt.core.dom.*;
// testing
public class ASTTest extends org.eclipse.jdt.core.tests.junit.extension.TestCase {
class CheckPositionsMatcher extends ASTMatcher {
public CheckPositionsMatcher() {
// include doc tags
super(true);
}
private void checkPositions(Object source, Object destination) {
assertTrue(source instanceof ASTNode);
assertTrue(destination instanceof ASTNode);
int startPosition = ((ASTNode)source).getStartPosition();
if (startPosition != -1) {
assertTrue(startPosition == ((ASTNode)destination).getStartPosition());
}
int length = ((ASTNode)source).getLength();
if (length != 0) {
assertTrue(length == ((ASTNode)destination).getLength());
}
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(AnnotationTypeDeclaration, Object)
* @since 3.0
*/
public boolean match(AnnotationTypeDeclaration node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(AnnotationTypeMemberDeclaration, Object)
* @since 3.0
*/
public boolean match(AnnotationTypeMemberDeclaration node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(AnonymousClassDeclaration, Object)
*/
public boolean match(AnonymousClassDeclaration node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(ArrayAccess, Object)
*/
public boolean match(ArrayAccess node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(ArrayCreation, Object)
*/
public boolean match(ArrayCreation node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(ArrayInitializer, Object)
*/
public boolean match(ArrayInitializer node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(ArrayType, Object)
*/
public boolean match(ArrayType node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(AssertStatement, Object)
*/
public boolean match(AssertStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(Assignment, Object)
*/
public boolean match(Assignment node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(Block, Object)
*/
public boolean match(Block node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(BlockComment, Object)
* @since 3.0
*/
public boolean match(BlockComment node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(BooleanLiteral, Object)
*/
public boolean match(BooleanLiteral node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(BreakStatement, Object)
*/
public boolean match(BreakStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(CastExpression, Object)
*/
public boolean match(CastExpression node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(CatchClause, Object)
*/
public boolean match(CatchClause node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(CharacterLiteral, Object)
*/
public boolean match(CharacterLiteral node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(ClassInstanceCreation, Object)
*/
public boolean match(ClassInstanceCreation node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(CompilationUnit, Object)
*/
public boolean match(CompilationUnit node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(ConditionalExpression, Object)
*/
public boolean match(ConditionalExpression node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(ConstructorInvocation, Object)
*/
public boolean match(ConstructorInvocation node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(ContinueStatement, Object)
*/
public boolean match(ContinueStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(DoStatement, Object)
*/
public boolean match(DoStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(EmptyStatement, Object)
*/
public boolean match(EmptyStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(EnhancedForStatement, Object)
* @since 3.0
*/
public boolean match(EnhancedForStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(EnumConstantDeclaration, Object)
* @since 3.0
*/
public boolean match(EnumConstantDeclaration node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(ExpressionStatement, Object)
*/
public boolean match(ExpressionStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(FieldAccess, Object)
*/
public boolean match(FieldAccess node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(FieldDeclaration, Object)
*/
public boolean match(FieldDeclaration node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(ForStatement, Object)
*/
public boolean match(ForStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(IfStatement, Object)
*/
public boolean match(IfStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(ImportDeclaration, Object)
*/
public boolean match(ImportDeclaration node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(InfixExpression, Object)
*/
public boolean match(InfixExpression node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(Initializer, Object)
*/
public boolean match(Initializer node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(InstanceofExpression, Object)
*/
public boolean match(InstanceofExpression node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(Javadoc, Object)
*/
public boolean match(Javadoc node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(LabeledStatement, Object)
*/
public boolean match(LabeledStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(LineComment, Object)
* @since 3.0
*/
public boolean match(LineComment node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(MarkerAnnotation, Object)
* @since 3.0
*/
public boolean match(MarkerAnnotation node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(MemberRef, Object)
* @since 3.0
*/
public boolean match(MemberRef node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(MemberValuePair, Object)
* @since 3.0
*/
public boolean match(MemberValuePair node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(MethodDeclaration, Object)
*/
public boolean match(MethodDeclaration node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(MethodInvocation, Object)
*/
public boolean match(MethodInvocation node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(MethodRef, Object)
* @since 3.0
*/
public boolean match(MethodRef node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(MethodRefParameter, Object)
* @since 3.0
*/
public boolean match(MethodRefParameter node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(Modifier, Object)
* @since 3.0
*/
public boolean match(Modifier node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(NormalAnnotation, Object)
* @since 3.0
*/
public boolean match(NormalAnnotation node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(NullLiteral, Object)
*/
public boolean match(NullLiteral node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(NumberLiteral, Object)
*/
public boolean match(NumberLiteral node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(PackageDeclaration, Object)
*/
public boolean match(PackageDeclaration node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(ParameterizedType, Object)
* @since 3.0
*/
public boolean match(ParameterizedType node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(ParenthesizedExpression, Object)
*/
public boolean match(ParenthesizedExpression node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(PostfixExpression, Object)
*/
public boolean match(PostfixExpression node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(PrefixExpression, Object)
*/
public boolean match(PrefixExpression node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(PrimitiveType, Object)
*/
public boolean match(PrimitiveType node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(QualifiedName, Object)
*/
public boolean match(QualifiedName node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(QualifiedType, Object)
* @since 3.0
*/
public boolean match(QualifiedType node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(ReturnStatement, Object)
*/
public boolean match(ReturnStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(SimpleName, Object)
*/
public boolean match(SimpleName node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(SimpleType, Object)
*/
public boolean match(SimpleType node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(SingleMemberAnnotation, Object)
* @since 3.0
*/
public boolean match(SingleMemberAnnotation node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(SingleVariableDeclaration, Object)
*/
public boolean match(SingleVariableDeclaration node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(StringLiteral, Object)
*/
public boolean match(StringLiteral node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(SuperConstructorInvocation, Object)
*/
public boolean match(SuperConstructorInvocation node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(SuperFieldAccess, Object)
*/
public boolean match(SuperFieldAccess node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(SuperMethodInvocation, Object)
*/
public boolean match(SuperMethodInvocation node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(SwitchCase, Object)
*/
public boolean match(SwitchCase node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(SwitchStatement, Object)
*/
public boolean match(SwitchStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(SynchronizedStatement, Object)
*/
public boolean match(SynchronizedStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(TagElement, Object)
* @since 3.0
*/
public boolean match(TagElement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(TextElement, Object)
* @since 3.0
*/
public boolean match(TextElement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(ThisExpression, Object)
*/
public boolean match(ThisExpression node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(ThrowStatement, Object)
*/
public boolean match(ThrowStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(TryStatement, Object)
*/
public boolean match(TryStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(TypeDeclaration, Object)
*/
public boolean match(TypeDeclaration node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(TypeDeclarationStatement, Object)
*/
public boolean match(TypeDeclarationStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(TypeLiteral, Object)
*/
public boolean match(TypeLiteral node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(TypeParameter, Object)
* @since 3.0
*/
public boolean match(TypeParameter node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(VariableDeclarationExpression, Object)
*/
public boolean match(VariableDeclarationExpression node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(VariableDeclarationFragment, Object)
*/
public boolean match(VariableDeclarationFragment node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(VariableDeclarationStatement, Object)
*/
public boolean match(VariableDeclarationStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(WhileStatement, Object)
*/
public boolean match(WhileStatement node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
/**
* @see org.eclipse.jdt.core.dom.ASTMatcher#match(WildcardType, Object)
* @since 3.0
*/
public boolean match(WildcardType node, Object other) {
checkPositions(node, other);
return super.match(node, other);
}
}
public static Test suite() {
junit.framework.TestSuite suite = new junit.framework.TestSuite(ASTTest.class.getName());
Class c = ASTTest.class;
Method[] methods = c.getMethods();
for (int i = 0, max = methods.length; i < max; i++) {
if (methods[i].getName().startsWith("test")) { //$NON-NLS-1$
suite.addTest(new ASTTest(methods[i].getName(), AST.JLS2));
suite.addTest(new ASTTest(methods[i].getName(), AST.JLS3));
}
}
return suite;
}
AST ast;
int API_LEVEL;
public ASTTest(String name, int apiLevel) {
super(name);
this.API_LEVEL = apiLevel;
}
protected void setUp() throws Exception {
super.setUp();
ast = AST.newAST(this.API_LEVEL);
}
protected void tearDown() throws Exception {
ast = null;
super.tearDown();
}
public String getName() {
String name = super.getName();
switch (this.API_LEVEL) {
case AST.JLS2:
name = "JLS2 - " + name;
break;
case AST.JLS3:
name = "JLS3 - " + name;
break;
}
return name;
}
/**
* Snippets that show how to...
*/
public void testExampleSnippets() {
{
AST localAst = AST.newAST(ast.apiLevel());
CompilationUnit cu = localAst.newCompilationUnit();
// package com.example;
PackageDeclaration pd = localAst.newPackageDeclaration();
pd.setName(localAst.newName(new String[]{"com", "example"})); //$NON-NLS-1$ //$NON-NLS-2$
cu.setPackage(pd);
assertTrue(pd.getRoot() == cu);
// import java.io;*;
ImportDeclaration im1 = localAst.newImportDeclaration();
im1.setName(localAst.newName(new String[]{"java", "io"})); //$NON-NLS-1$ //$NON-NLS-2$
im1.setOnDemand(true);
cu.imports().add(im1);
assertTrue(im1.getRoot() == cu);
// import java.util.List;
ImportDeclaration im2 = localAst.newImportDeclaration();
im2.setName(localAst.newName(new String[]{"java", "util", "List"})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
im2.setOnDemand(false);
cu.imports().add(im2);
assertTrue(im2.getRoot() == cu);
// /** Spec. \n @deprecated Use {@link #foo() bar} instead. */public class MyClass {}
TypeDeclaration td = localAst.newTypeDeclaration();
if (ast.apiLevel() == AST.JLS2) {
td.setModifiers(Modifier.PUBLIC);
} else {
td.modifiers().add(localAst.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
}
td.setInterface(false);
td.setName(localAst.newSimpleName("MyClass")); //$NON-NLS-1$
{
Javadoc jd = localAst.newJavadoc();
TagElement tg0 = localAst.newTagElement();
jd.tags().add(tg0);
TextElement tx1 = localAst.newTextElement();
tx1.setText("Spec."); //$NON-NLS-1$
tg0.fragments().add(tx1);
TagElement tg1 = localAst.newTagElement();
tg1.setTagName(TagElement.TAG_DEPRECATED);
jd.tags().add(tg1);
TextElement tx2 = localAst.newTextElement();
tx2.setText("Use "); //$NON-NLS-1$
tg1.fragments().add(tx2);
TagElement tg2 = localAst.newTagElement();
tg2.setTagName(TagElement.TAG_LINK);
tg1.fragments().add(tg2);
MethodRef mr1 = localAst.newMethodRef();
mr1.setName(localAst.newSimpleName("foo"));
tg2.fragments().add(mr1);
TextElement tx3 = localAst.newTextElement();
tx3.setText("bar"); //$NON-NLS-1$
tg2.fragments().add(tx3);
TextElement tx4 = localAst.newTextElement();
tx2.setText(" instead."); //$NON-NLS-1$
tg1.fragments().add(tx4);
}
cu.types().add(td);
assertTrue(td.getRoot() == cu);
// private static boolean DEBUG = true;
VariableDeclarationFragment f1 = localAst.newVariableDeclarationFragment();
f1.setName(localAst.newSimpleName("DEBUG")); //$NON-NLS-1$
f1.setInitializer(localAst.newBooleanLiteral(true));
FieldDeclaration fd = localAst.newFieldDeclaration(f1);
fd.setType(localAst.newPrimitiveType(PrimitiveType.BOOLEAN));
if (ast.apiLevel() == AST.JLS2) {
fd.setModifiers(Modifier.PRIVATE | Modifier.FINAL);
} else {
fd.modifiers().add(localAst.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD));
fd.modifiers().add(localAst.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
}
td.bodyDeclarations().add(fd);
assertTrue(fd.getRoot() == cu);
// public static void main();
MethodDeclaration md = localAst.newMethodDeclaration();
if (ast.apiLevel() == AST.JLS2) {
md.setModifiers(Modifier.PUBLIC | Modifier.STATIC);
md.setReturnType(localAst.newPrimitiveType(PrimitiveType.VOID));
} else {
md.modifiers().add(localAst.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
md.modifiers().add(localAst.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
md.setReturnType2(localAst.newPrimitiveType(PrimitiveType.VOID));
}
md.setConstructor(false);
md.setName(localAst.newSimpleName("main")); //$NON-NLS-1$
td.bodyDeclarations().add(md);
assertTrue(md.getRoot() == cu);
// String[] args
SingleVariableDeclaration a1 = localAst.newSingleVariableDeclaration();
a1.setType(localAst.newArrayType(
localAst.newSimpleType(localAst.newSimpleName("String")))); //$NON-NLS-1$
a1.setName(localAst.newSimpleName("args")); //$NON-NLS-1$
md.parameters().add(a1);
assertTrue(a1.getRoot() == cu);
// {}
Block b = localAst.newBlock();
md.setBody(b);
assertTrue(b.getRoot() == cu);
// System.out.println("hello world");
MethodInvocation e = localAst.newMethodInvocation();
e.setExpression(localAst.newName(new String[] {"System", "out"})); //$NON-NLS-1$ //$NON-NLS-2$
e.setName(localAst.newSimpleName("println")); //$NON-NLS-1$
StringLiteral h = localAst.newStringLiteral();
h.setLiteralValue("hello world"); //$NON-NLS-1$
e.arguments().add(h);
b.statements().add(localAst.newExpressionStatement(e));
assertTrue(e.getRoot() == cu);
assertTrue(h.getRoot() == cu);
// new String[len];
ArrayCreation ac1 = localAst.newArrayCreation();
ac1.setType(
localAst.newArrayType(
localAst.newSimpleType(localAst.newSimpleName("String")))); //$NON-NLS-1$
ac1.dimensions().add(localAst.newSimpleName("len")); //$NON-NLS-1$
b.statements().add(localAst.newExpressionStatement(ac1));
assertTrue(ac1.getRoot() == cu);
// new double[7][24][];
ArrayCreation ac2 = localAst.newArrayCreation();
ac2.setType(
localAst.newArrayType(
localAst.newPrimitiveType(PrimitiveType.DOUBLE), 3));
ac2.dimensions().add(localAst.newNumberLiteral("7")); //$NON-NLS-1$
ac2.dimensions().add(localAst.newNumberLiteral("24")); //$NON-NLS-1$
b.statements().add(localAst.newExpressionStatement(ac2));
assertTrue(ac2.getRoot() == cu);
// new int[] {1, 2};
ArrayCreation ac3 = localAst.newArrayCreation();
ac3.setType(
localAst.newArrayType(
localAst.newPrimitiveType(PrimitiveType.INT)));
ArrayInitializer ai = localAst.newArrayInitializer();
ac3.setInitializer(ai);
ai.expressions().add(localAst.newNumberLiteral("1")); //$NON-NLS-1$
ai.expressions().add(localAst.newNumberLiteral("2")); //$NON-NLS-1$
b.statements().add(localAst.newExpressionStatement(ac3));
assertTrue(ac3.getRoot() == cu);
assertTrue(ai.getRoot() == cu);
// new String(10);
ClassInstanceCreation cr1 = localAst.newClassInstanceCreation();
if (ast.apiLevel() == AST.JLS2) {
cr1.setName(localAst.newSimpleName("String")); //$NON-NLS-1$
} else {
cr1.setType(localAst.newSimpleType(localAst.newSimpleName("String"))); //$NON-NLS-1$
}
cr1.arguments().add(localAst.newNumberLiteral("10")); //$NON-NLS-1$
b.statements().add(localAst.newExpressionStatement(cr1));
assertTrue(cr1.getRoot() == cu);
// new Listener() {public void handleEvent() {} };
ClassInstanceCreation cr2 = localAst.newClassInstanceCreation();
AnonymousClassDeclaration ad1 = localAst.newAnonymousClassDeclaration();
cr2.setAnonymousClassDeclaration(ad1);
if (ast.apiLevel() == AST.JLS2) {
cr2.setName(localAst.newSimpleName("Listener")); //$NON-NLS-1$
} else {
cr2.setType(localAst.newSimpleType(localAst.newSimpleName("Listener"))); //$NON-NLS-1$
}
MethodDeclaration md0 = localAst.newMethodDeclaration();
if (ast.apiLevel() == AST.JLS2) {
md0.setModifiers(Modifier.PUBLIC);
} else {
md0.modifiers().add(localAst.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
}
md0.setName(localAst.newSimpleName("handleEvent")); //$NON-NLS-1$
md0.setBody(localAst.newBlock());
ad1.bodyDeclarations().add(md0);
b.statements().add(localAst.newExpressionStatement(cr2));
assertTrue(cr2.getRoot() == cu);
assertTrue(md0.getRoot() == cu);
assertTrue(ad1.getRoot() == cu);
}
}
abstract class Property {
/**
* Indicates whether this property is compulsory, in that every node
* must have a value at all times.
*/
private boolean compulsory;
private Class nodeType;
private String propertyName;
/**
* Creates a new property with the given name.
*/
Property(String propertyName, boolean compulsory, Class nodeType) {
this.propertyName = propertyName;
this.compulsory = compulsory;
this.nodeType = nodeType;
}
/**
* Returns a sample node of a type suitable for storing
* in this property.
*
* @param targetAST the target AST
* @param parented <code>true</code> if the sample should be
* parented, and <code>false</code> if unparented
* @return a sample node
*/
public abstract ASTNode sample(AST targetAST, boolean parented);
/**
* Returns examples of node of types unsuitable for storing
* in this property.
* <p>
* This implementation returns an empty list. Subclasses
* should reimplement to specify counter-examples.
* </p>
*
* @param targetAST the target AST
* @return a list of counter-example nodes
*/
public ASTNode[] counterExamples(AST targetAST) {
return new ASTNode[] {};
}
/**
* Returns a sample node of a type suitable for storing
* in this property. The sample embeds the node itself.
* <p>
* For instance, for an Expression-valued property of a given
* Statement, this method returns an Expression that embeds
* this Statement node (as a descendent).
* </p>
* <p>
* Returns <code>null</code> if such an embedding is impossible.
* For instance, for an Name-valued property of a given
* Statement, this method returns <code>null</code> because
* an Expression cannot be embedded in a Name.
* </p>
* <p>
* This implementation returns <code>null</code>. Subclasses
* should reimplement to specify an embedding.
* </p>
*
* @return a sample node that embeds the given node,
* and <code>null</code> if such an embedding is impossible
*/
public ASTNode wrap() {
return null;
}
/**
* Undoes the effects of a previous <code>wrap</code>.
* <p>
* This implementation does nothing. Subclasses
* should reimplement if they reimplement <code>wrap</code>.
* </p>
*
* @return a sample node that embeds the given node,
* and <code>null</code> if such an embedding is impossible
*/
public void unwrap() {
}
/**
* Returns whether this property is compulsory, in that every node
* must have a value at all times.
*
* @return <code>true</code> if the property is compulsory,
* and <code>false</code> if the property may be null
*/
public final boolean isCompulsory() {
return compulsory;
}
/**
* Returns the value of this property.
* <p>
* This implementation throws an unchecked exception. Subclasses
* should reimplement.
* </p>
*
* @return the property value, or <code>null</code> if no value
*/
public ASTNode get() {
throw new RuntimeException("get not implemented"); //$NON-NLS-1$
}
/**
* Sets or clears the value of this property.
* <p>
* This implementation throws an unchecked exception. Subclasses
* should reimplement.
* </p>
*
* @param value the property value, or <code>null</code> if no value
*/
public void set(ASTNode value) {
throw new RuntimeException("get(" + value + ") not implemented"); //$NON-NLS-1$ //$NON-NLS-2$
}
public String toString() {
return "Property(" + this.propertyName + ", " + this.compulsory + ", " + this.nodeType + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
}
/**
* Exercises the given property of the given node.
*
* @param node the node to test
* @param prop the property descriptor
*/
void genericPropertyTest(ASTNode node, Property prop) {
ASTNode x1 = prop.sample(node.getAST(), false);
prop.set(x1);
assertTrue(prop.get() == x1);
assertTrue(x1.getParent() == node);
// check handling of null
if (prop.isCompulsory()) {
try {
prop.set(null);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
} else {
long previousCount = node.getAST().modificationCount();
prop.set(null);
assertTrue(prop.get() == null);
assertTrue(node.getAST().modificationCount() > previousCount);
}
// check that a child from a different AST is detected
try {
AST newAST = AST.newAST(node.getAST().apiLevel());
prop.set(prop.sample(newAST, false));
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
// check that a child with a parent is detected
try {
ASTNode b1 = prop.sample(node.getAST(), true);
prop.set(b1); // bogus: already has parent
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
// check that a cycle is detected
assertTrue(node.getParent() == null);
ASTNode s1 = null;
try {
s1 = prop.wrap();
if (s1 != null) {
prop.set(s1); // bogus: creates a cycle
assertTrue(false);
}
} catch (RuntimeException e) {
// pass
} finally {
if (s1 != null) {
prop.unwrap();
assertTrue(node.getParent() == null);
}
}
// check that a child of the wrong type is detected
ASTNode b1[] = prop.counterExamples(node.getAST());
for (int i = 0; i < b1.length; i++) {
try {
prop.set(b1[i]); // bogus: wrong type
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
}
}
/**
* Exercises the given property of the given node.
*
* @param node the node to test
* @param children the node to test
* @param prop the property descriptor
*/
void genericPropertyListTest(ASTNode node, List children, Property prop) {
// wipe the slate clean
children.clear();
assertTrue(children.size() == 0);
// add a child
ASTNode x1 = prop.sample(node.getAST(), false);
long previousCount = node.getAST().modificationCount();
children.add(x1);
assertTrue(node.getAST().modificationCount() > previousCount);
assertTrue(children.size() == 1);
assertTrue(children.get(0) == x1);
assertTrue(x1.getParent() == node);
// add a second child
ASTNode x2 = prop.sample(node.getAST(), false);
previousCount = node.getAST().modificationCount();
children.add(x2);
assertTrue(node.getAST().modificationCount() > previousCount);
assertTrue(children.size() == 2);
assertTrue(children.get(0) == x1);
assertTrue(children.get(1) == x2);
assertTrue(x1.getParent() == node);
assertTrue(x2.getParent() == node);
// remove the first child
previousCount = node.getAST().modificationCount();
children.remove(0);
assertTrue(node.getAST().modificationCount() > previousCount);
assertTrue(children.size() == 1);
assertTrue(children.get(0) == x2);
assertTrue(x1.getParent() == null);
assertTrue(x2.getParent() == node);
// remove the remaining child
previousCount = node.getAST().modificationCount();
children.remove(x2);
assertTrue(node.getAST().modificationCount() > previousCount);
assertTrue(children.size() == 0);
assertTrue(x1.getParent() == null);
assertTrue(x2.getParent() == null);
// check that null is never allowed
try {
children.add(null);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
// check that a child from a different AST is detected
try {
AST newAST = AST.newAST(node.getAST().apiLevel());
children.add(prop.sample(newAST, false));
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
// check that a child with a parent is detected
try {
ASTNode b1 = prop.sample(node.getAST(), true);
children.add(b1); // bogus: already has parent
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
// check that a cycle is detected
assertTrue(node.getParent() == null);
ASTNode s1 = null;
try {
s1 = prop.wrap();
if (s1 != null) {
children.add(s1); // bogus: creates a cycle
assertTrue(false);
}
} catch (RuntimeException e) {
// pass
} finally {
if (s1 != null) {
prop.unwrap();
assertTrue(node.getParent() == null);
}
}
// check that a child of the wrong type is detected
ASTNode b1[] = prop.counterExamples(node.getAST());
for (int i = 0; i < b1.length; i++) {
try {
children.add(b1[i]); // bogus: wrong type
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
}
}
public void testAST() {
assertTrue(AST.JLS2 == 2);
assertTrue(AST.JLS3 == 3);
AST a0 = new AST(); // deprecated, but still 2.0
assertTrue(a0.apiLevel() == AST.JLS2);
AST a1 = new AST(new HashMap()); // deprecated, but still 2.0
assertTrue(a1.apiLevel() == AST.JLS2);
AST a2 = AST.newAST(AST.JLS2);
assertTrue(a2.apiLevel() == AST.JLS2);
AST a3 = AST.newAST(AST.JLS3);
assertTrue(a3.apiLevel() == AST.JLS3);
// modification count is always non-negative
assertTrue(ast.modificationCount() >= 0);
// modification count increases for node creations
long previousCount = ast.modificationCount();
SimpleName x = ast.newSimpleName("first"); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
// modification count does not increase for reading node attributes
previousCount = ast.modificationCount();
x.getIdentifier();
x.getParent();
x.getRoot();
x.getAST();
x.getFlags();
x.getStartPosition();
x.getLength();
x.equals(x);
assertTrue(ast.modificationCount() == previousCount);
// modification count does not increase for reading or writing properties
previousCount = ast.modificationCount();
x.getProperty("any"); //$NON-NLS-1$
x.setProperty("any", "value"); // N.B. //$NON-NLS-1$ //$NON-NLS-2$
x.properties();
assertTrue(ast.modificationCount() == previousCount);
// modification count increases for changing node attributes
previousCount = ast.modificationCount();
x.setIdentifier("second"); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
x.setFlags(0);
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
x.setSourceRange(-1,0);
assertTrue(ast.modificationCount() > previousCount);
}
public void testWellKnownBindings() {
// well known bindings
String[] wkbs = {
"byte", "char", "short", "int", "long", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
"boolean", "float", "double", "void", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
"java.lang.Class", //$NON-NLS-1$
"java.lang.Cloneable", //$NON-NLS-1$
"java.lang.Error", //$NON-NLS-1$
"java.lang.Exception", //$NON-NLS-1$
"java.lang.Object", //$NON-NLS-1$
"java.lang.RuntimeException", //$NON-NLS-1$
"java.lang.String", //$NON-NLS-1$
"java.lang.StringBuffer", //$NON-NLS-1$
"java.lang.Throwable", //$NON-NLS-1$
"java.io.Serializable", //$NON-NLS-1$
"java.lang.Boolean", //$NON-NLS-1$
"java.lang.Byte", //$NON-NLS-1$
"java.lang.Character", //$NON-NLS-1$
"java.lang.Double", //$NON-NLS-1$
"java.lang.Float", //$NON-NLS-1$
"java.lang.Integer", //$NON-NLS-1$
"java.lang.Long", //$NON-NLS-1$
"java.lang.Short", //$NON-NLS-1$
"java.lang.Void", //$NON-NLS-1$
};
// no-so-well-known bindings
String[] nwkbs = {
"verylong", //$NON-NLS-1$
"java.lang.Math", //$NON-NLS-1$
"com.example.MyCode", //$NON-NLS-1$
};
// none of the well known bindings resolve in a plain AST
for (int i = 0; i<wkbs.length; i++) {
assertTrue(ast.resolveWellKnownType(wkbs[i]) == null);
}
// none of the no so well known bindings resolve either
for (int i = 0; i<nwkbs.length; i++) {
assertTrue(ast.resolveWellKnownType(nwkbs[i]) == null);
}
}
public void testSimpleName() {
long previousCount = ast.modificationCount();
SimpleName x = ast.newSimpleName("foo"); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue("foo".equals(x.getIdentifier())); //$NON-NLS-1$
assertTrue("foo".equals(x.getFullyQualifiedName())); //$NON-NLS-1$
assertTrue(x.getNodeType() == ASTNode.SIMPLE_NAME);
assertTrue(x.isDeclaration() == false);
assertTrue(x.structuralPropertiesForType() == SimpleName.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
previousCount = ast.modificationCount();
x.setIdentifier("bar"); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
assertTrue("bar".equals(x.getIdentifier())); //$NON-NLS-1$
assertTrue("bar".equals(x.getFullyQualifiedName())); //$NON-NLS-1$
// check that property cannot be set to null
try {
x.setIdentifier(null);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
// check that property cannot be set to keyword or reserved work
String[] reserved =
new String[] {
"true", "false", "null", // literals //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"abstract", "default", "if", "private", "this", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
"boolean", "do", "implements", "protected", "throw", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
"break", "double", "import", "public", "throws", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
"byte", "else", "instanceof", "return", "transient", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
"case", "extends", "int", "short", "try", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
"catch", "final", "interface", "static", "void", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
"char", "finally", "long", "strictfp", "volatile", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
"class", "float", "native", "super", "while", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
"const", "for", "new", "switch", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
"continue", "goto", "package", "synchronized"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
for (int i=0; i<reserved.length; i++) {
try {
x.setIdentifier(reserved[i]);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
}
// check that "assert" is not considered a keyword
// "assert" only became a keyword in J2SE 1.4 and we do *not* want to
// preclude the AST API from being used to analyze pre-1.4 code
x.setIdentifier("assert"); //$NON-NLS-1$
// check that "enum" is not considered a keyword
// "enum" only became a keyword in J2SE 1.5 and we do *not* want to
// preclude the AST API from being used to analyze pre-1.5 code
x.setIdentifier("enum"); //$NON-NLS-1$
// check that isDeclaration works
QualifiedName y = ast.newQualifiedName(ast.newSimpleName("a"), x); //$NON-NLS-1$
assertTrue(x.isDeclaration() == false);
y.setName(ast.newSimpleName("b")); //$NON-NLS-1$
assertTrue(x.isDeclaration() == false);
TypeDeclaration td = ast.newTypeDeclaration();
td.setName(x);
assertTrue(x.isDeclaration() == true);
td.setName(ast.newSimpleName("b")); //$NON-NLS-1$
assertTrue(x.isDeclaration() == false);
MethodDeclaration md = ast.newMethodDeclaration();
md.setName(x);
assertTrue(x.isDeclaration() == true);
md.setName(ast.newSimpleName("b")); //$NON-NLS-1$
assertTrue(x.isDeclaration() == false);
SingleVariableDeclaration vd = ast.newSingleVariableDeclaration();
vd.setName(x);
assertTrue(x.isDeclaration() == true);
vd.setName(ast.newSimpleName("b")); //$NON-NLS-1$
assertTrue(x.isDeclaration() == false);
VariableDeclarationFragment fd = ast.newVariableDeclarationFragment();
fd.setName(x);
assertTrue(x.isDeclaration() == true);
fd.setName(ast.newSimpleName("b")); //$NON-NLS-1$
assertTrue(x.isDeclaration() == false);
if (ast.apiLevel() >= AST.JLS3) {
AnnotationTypeDeclaration atd = ast.newAnnotationTypeDeclaration();
atd.setName(x);
assertTrue(x.isDeclaration() == true);
atd.setName(ast.newSimpleName("b")); //$NON-NLS-1$
assertTrue(x.isDeclaration() == false);
}
if (ast.apiLevel() >= AST.JLS3) {
AnnotationTypeMemberDeclaration atmd = ast.newAnnotationTypeMemberDeclaration();
atmd.setName(x);
assertTrue(x.isDeclaration() == true);
atmd.setName(ast.newSimpleName("b")); //$NON-NLS-1$
assertTrue(x.isDeclaration() == false);
}
}
public void testQualifiedName() {
long previousCount = ast.modificationCount();
final QualifiedName x = ast.newQualifiedName(
ast.newSimpleName("q"), //$NON-NLS-1$
ast.newSimpleName("i")); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getQualifier().getParent() == x);
assertTrue(x.getName().getParent() == x);
assertTrue(x.getName().isDeclaration() == false);
assertTrue(x.getNodeType() == ASTNode.QUALIFIED_NAME);
assertTrue("q.i".equals(x.getFullyQualifiedName())); //$NON-NLS-1$
assertTrue(x.structuralPropertiesForType() == QualifiedName.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Qualifier", true, Name.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
QualifiedName result = targetAst.newQualifiedName(
targetAst.newSimpleName("a"), //$NON-NLS-1$
targetAst.newSimpleName("b")); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
QualifiedName s1 = ast.newQualifiedName(x, ast.newSimpleName("z")); //$NON-NLS-1$
return s1;
}
public void unwrap() {
QualifiedName s1 = (QualifiedName) x.getParent();
s1.setQualifier(ast.newSimpleName("z")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getQualifier();
}
public void set(ASTNode value) {
x.setQualifier((Name) value);
}
});
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
// test fullyQualifiedName on nested names
Name q0 = ast.newName(new String[] {"a", "bb", "ccc", "dddd", "eeeee", "ffffff"});
assertTrue("a.bb.ccc.dddd.eeeee.ffffff".equals(q0.getFullyQualifiedName())); //$NON-NLS-1$
}
public void testNullLiteral() {
long previousCount = ast.modificationCount();
NullLiteral x = ast.newNullLiteral();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getNodeType() == ASTNode.NULL_LITERAL);
assertTrue(x.structuralPropertiesForType() == NullLiteral.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
}
public void testBooleanLiteral() {
long previousCount = ast.modificationCount();
BooleanLiteral x = ast.newBooleanLiteral(true);
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.booleanValue() == true);
assertTrue(x.getNodeType() == ASTNode.BOOLEAN_LITERAL);
assertTrue(x.structuralPropertiesForType() == BooleanLiteral.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
previousCount = ast.modificationCount();
x.setBooleanValue(false);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.booleanValue() == false);
previousCount = ast.modificationCount();
x.setBooleanValue(true);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.booleanValue() == true);
}
public void testStringLiteral() {
long previousCount = ast.modificationCount();
// check 0-arg factory first
StringLiteral x = ast.newStringLiteral();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue("\"\"".equals(x.getEscapedValue())); //$NON-NLS-1$
assertTrue("".equals(x.getLiteralValue())); //$NON-NLS-1$
assertTrue(x.getNodeType() == ASTNode.STRING_LITERAL);
assertTrue(x.structuralPropertiesForType() == StringLiteral.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
previousCount = ast.modificationCount();
x.setEscapedValue("\"bye\""); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
assertTrue("\"bye\"".equals(x.getEscapedValue())); //$NON-NLS-1$
assertTrue("bye".equals(x.getLiteralValue())); //$NON-NLS-1$
previousCount = ast.modificationCount();
x.setLiteralValue("hi"); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
assertTrue("\"hi\"".equals(x.getEscapedValue())); //$NON-NLS-1$
assertTrue("hi".equals(x.getLiteralValue())); //$NON-NLS-1$
previousCount = ast.modificationCount();
x.setLiteralValue("\\012\\015"); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
assertEquals("different", "\"\\\\012\\\\015\"", x.getEscapedValue()); //$NON-NLS-1$
assertTrue("\\012\\015".equals(x.getLiteralValue())); //$NON-NLS-1$
previousCount = ast.modificationCount();
x.setLiteralValue("\012\015"); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
assertTrue("\n\r".equals(x.getLiteralValue())); //$NON-NLS-1$
assertEquals("different", "\"\\n\\r\"", x.getEscapedValue()); //$NON-NLS-1$
// check that property cannot be set to null
try {
x.setEscapedValue(null);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
// check that property cannot be set to null
try {
x.setLiteralValue(null);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
}
public void testStringLiteralUnicode() {
AST localAst = AST.newAST(ast.apiLevel());
StringLiteral literal = localAst.newStringLiteral();
literal.setEscapedValue("\"hello\\u0026\\u0050worl\\u0064\""); //$NON-NLS-1$
assertTrue(literal.getLiteralValue().equals("hello&Pworld")); //$NON-NLS-1$
localAst = AST.newAST(ast.apiLevel());
literal = localAst.newStringLiteral();
literal.setEscapedValue("\"hello\\nworld\""); //$NON-NLS-1$
assertTrue(literal.getLiteralValue().equals("hello\nworld")); //$NON-NLS-1$
localAst = AST.newAST(ast.apiLevel());
literal = localAst.newStringLiteral();
literal.setLiteralValue("hello\nworld"); //$NON-NLS-1$
assertTrue(literal.getLiteralValue().equals("hello\nworld")); //$NON-NLS-1$
localAst = AST.newAST(ast.apiLevel());
literal = localAst.newStringLiteral();
literal.setLiteralValue("\n"); //$NON-NLS-1$
assertTrue(literal.getEscapedValue().equals("\"\\n\"")); //$NON-NLS-1$
assertTrue(literal.getLiteralValue().equals("\n")); //$NON-NLS-1$
localAst = AST.newAST(ast.apiLevel());
literal = localAst.newStringLiteral();
literal.setEscapedValue("\"hello\\\"world\""); //$NON-NLS-1$
assertTrue(literal.getLiteralValue().equals("hello\"world")); //$NON-NLS-1$
localAst = AST.newAST(ast.apiLevel());
literal = localAst.newStringLiteral();
literal.setLiteralValue("hello\\u0026world"); //$NON-NLS-1$
assertTrue(literal.getLiteralValue().equals("hello\\u0026world")); //$NON-NLS-1$
localAst = AST.newAST(ast.apiLevel());
literal = localAst.newStringLiteral();
literal.setLiteralValue("hello\\u0026world"); //$NON-NLS-1$
assertTrue(literal.getEscapedValue().equals("\"hello\\\\u0026world\"")); //$NON-NLS-1$
localAst = AST.newAST(ast.apiLevel());
literal = localAst.newStringLiteral();
literal.setLiteralValue("\\u0001"); //$NON-NLS-1$
assertTrue(literal.getEscapedValue().equals("\"\\\\u0001\"")); //$NON-NLS-1$
}
public void testCharacterLiteral() {
long previousCount = ast.modificationCount();
CharacterLiteral x = ast.newCharacterLiteral();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getEscapedValue().startsWith("\'")); //$NON-NLS-1$
assertTrue(x.getEscapedValue().endsWith("\'")); //$NON-NLS-1$
assertTrue(x.getNodeType() == ASTNode.CHARACTER_LITERAL);
assertTrue(x.structuralPropertiesForType() == CharacterLiteral.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
previousCount = ast.modificationCount();
x.setEscapedValue("\'z\'"); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
assertTrue("\'z\'".equals(x.getEscapedValue())); //$NON-NLS-1$
assertTrue(x.charValue() == 'z');
// test other factory method
previousCount = ast.modificationCount();
CharacterLiteral y = ast.newCharacterLiteral();
assertTrue(ast.modificationCount() > previousCount);
assertTrue(y.getAST() == ast);
assertTrue(y.getParent() == null);
String v = y.getEscapedValue();
assertTrue(v.length() >= 3 && v.charAt(0) == '\'' & v.charAt(v.length()-1 ) == '\'');
// check that property cannot be set to null
try {
x.setEscapedValue(null);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
// test escaped characters
// b, t, n, f, r, ", ', \, 0, 1, 2, 3, 4, 5, 6, or 7
try {
x.setEscapedValue("\'\\b\'"); //$NON-NLS-1$
x.setEscapedValue("\'\\t\'"); //$NON-NLS-1$
x.setEscapedValue("\'\\n\'"); //$NON-NLS-1$
x.setEscapedValue("\'\\f\'"); //$NON-NLS-1$
x.setEscapedValue("\'\\\"\'"); //$NON-NLS-1$
x.setEscapedValue("\'\\'\'"); //$NON-NLS-1$
x.setEscapedValue("\'\\\\\'"); //$NON-NLS-1$
x.setEscapedValue("\'\\0\'"); //$NON-NLS-1$
x.setEscapedValue("\'\\1\'"); //$NON-NLS-1$
x.setEscapedValue("\'\\2\'"); //$NON-NLS-1$
x.setEscapedValue("\'\\3\'"); //$NON-NLS-1$
x.setEscapedValue("\'\\4\'"); //$NON-NLS-1$
x.setEscapedValue("\'\\5\'"); //$NON-NLS-1$
x.setEscapedValue("\'\\6\'"); //$NON-NLS-1$
x.setEscapedValue("\'\\7\'"); //$NON-NLS-1$
x.setEscapedValue("\'\\u0041\'"); //$NON-NLS-1$
assertTrue(x.charValue() == 'A');
} catch(IllegalArgumentException e) {
assertTrue(false);
}
x.setCharValue('\u0041');
assertTrue(x.getEscapedValue().equals("\'A\'")); //$NON-NLS-1$
x.setCharValue('\t');
assertTrue(x.getEscapedValue().equals("\'\\t\'")); //$NON-NLS-1$
x.setEscapedValue("\'\\\\\'"); //$NON-NLS-1$
assertTrue(x.getEscapedValue().equals("\'\\\\\'")); //$NON-NLS-1$
assertTrue(x.charValue() == '\\');
x.setEscapedValue("\'\\\'\'"); //$NON-NLS-1$
assertTrue(x.getEscapedValue().equals("\'\\\'\'")); //$NON-NLS-1$
assertTrue(x.charValue() == '\'');
x.setCharValue('\'');
assertTrue(x.getEscapedValue().equals("\'\\\'\'")); //$NON-NLS-1$
assertTrue(x.charValue() == '\'');
x.setCharValue('\\');
assertTrue(x.getEscapedValue().equals("\'\\\\\'")); //$NON-NLS-1$
assertTrue(x.charValue() == '\\');
}
public void testNumberLiteral() {
long previousCount = ast.modificationCount();
NumberLiteral x = ast.newNumberLiteral("1234"); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue("1234".equals(x.getToken())); //$NON-NLS-1$
assertTrue(x.getNodeType() == ASTNode.NUMBER_LITERAL);
assertTrue(x.structuralPropertiesForType() == NumberLiteral.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
// test other factory method
previousCount = ast.modificationCount();
NumberLiteral y = ast.newNumberLiteral();
assertTrue(ast.modificationCount() > previousCount);
assertTrue(y.getAST() == ast);
assertTrue(y.getParent() == null);
assertTrue("0".equals(y.getToken())); //$NON-NLS-1$
final String[] samples =
{ "0", "1", "1234567890", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"0L", "1L", "1234567890L", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"0l", "1l", "1234567890l", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"077", "0177", "012345670", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"077L", "0177L", "012345670L", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"077l", "0177l", "012345670l", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"0x00", "0x1", "0x0123456789ABCDEF", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"0x00L", "0x1L", "0x0123456789ABCDEFL", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"0x00l", "0x1l", "0x0123456789ABCDEFl", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
"1e1f", "2.f", ".3f", "0f", "3.14f", "6.022137e+23f", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
"1e1", "2.", ".3", "0.0", "3.14", "1e-9d", "1e137", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
};
for (int i = 0; i < samples.length; i++) {
previousCount = ast.modificationCount();
x.setToken(samples[i]);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(samples[i].equals(x.getToken()));
}
// check that property cannot be set to null
try {
x.setToken(null);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
}
public void testSimpleType() {
long previousCount = ast.modificationCount();
final SimpleType x = ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getName().getParent() == x);
assertTrue(x.isSimpleType());
assertTrue(!x.isArrayType());
assertTrue(!x.isPrimitiveType());
assertTrue(!x.isParameterizedType());
assertTrue(!x.isQualifiedType());
assertTrue(!x.isWildcardType());
assertTrue(x.getNodeType() == ASTNode.SIMPLE_TYPE);
assertTrue(x.structuralPropertiesForType() == SimpleType.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Name", true, Name.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("a"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((Name) value);
}
});
}
public void testPrimitiveType() {
long previousCount = ast.modificationCount();
PrimitiveType x = ast.newPrimitiveType(PrimitiveType.INT);
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getPrimitiveTypeCode().equals(PrimitiveType.INT));
assertTrue(!x.isSimpleType());
assertTrue(!x.isArrayType());
assertTrue(x.isPrimitiveType());
assertTrue(!x.isParameterizedType());
assertTrue(!x.isQualifiedType());
assertTrue(!x.isWildcardType());
assertTrue(x.getNodeType() == ASTNode.PRIMITIVE_TYPE);
assertTrue(x.structuralPropertiesForType() == PrimitiveType.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
// check the names of the primitive type codes
assertTrue(PrimitiveType.BYTE.toString().equals("byte")); //$NON-NLS-1$
assertTrue(PrimitiveType.INT.toString().equals("int")); //$NON-NLS-1$
assertTrue(PrimitiveType.BOOLEAN.toString().equals("boolean")); //$NON-NLS-1$
assertTrue(PrimitiveType.CHAR.toString().equals("char")); //$NON-NLS-1$
assertTrue(PrimitiveType.SHORT.toString().equals("short")); //$NON-NLS-1$
assertTrue(PrimitiveType.LONG.toString().equals("long")); //$NON-NLS-1$
assertTrue(PrimitiveType.FLOAT.toString().equals("float")); //$NON-NLS-1$
assertTrue(PrimitiveType.DOUBLE.toString().equals("double")); //$NON-NLS-1$
assertTrue(PrimitiveType.VOID.toString().equals("void")); //$NON-NLS-1$
PrimitiveType.Code[] known = {
PrimitiveType.BOOLEAN,
PrimitiveType.BYTE,
PrimitiveType.CHAR,
PrimitiveType.INT,
PrimitiveType.SHORT,
PrimitiveType.LONG,
PrimitiveType.FLOAT,
PrimitiveType.DOUBLE,
PrimitiveType.VOID,
};
// check all primitive type codes are distinct
for (int i = 0; i < known.length; i++) {
for (int j = 0; j < known.length; j++) {
assertTrue(i == j || !known[i].equals(known[j]));
}
}
// check all primitive type codes work
for (int i = 0; i < known.length; i++) {
previousCount = ast.modificationCount();
x.setPrimitiveTypeCode(known[i]);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getPrimitiveTypeCode().equals(known[i]));
}
// ensure null does not work as a primitive type code
try {
x.setPrimitiveTypeCode(null);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
// check toCode lookup of primitive type code by name
for (int i = 0; i < known.length; i++) {
String name = known[i].toString();
assertTrue(PrimitiveType.toCode(name).equals(known[i]));
}
assertTrue(PrimitiveType.toCode("not-a-type") == null); //$NON-NLS-1$
}
public void testArrayType() {
SimpleName x1 = ast.newSimpleName("String"); //$NON-NLS-1$
SimpleType x2 = ast.newSimpleType(x1);
long previousCount = ast.modificationCount();
final ArrayType x = ast.newArrayType(x2);
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getComponentType().getParent() == x);
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
assertTrue(!x.isSimpleType());
assertTrue(x.isArrayType());
assertTrue(!x.isPrimitiveType());
assertTrue(!x.isParameterizedType());
assertTrue(!x.isQualifiedType());
assertTrue(!x.isWildcardType());
assertTrue(x.getNodeType() == ASTNode.ARRAY_TYPE);
assertTrue(x.structuralPropertiesForType() == ArrayType.propertyDescriptors(ast.apiLevel()));
assertTrue(x.getDimensions() == 1);
assertTrue(x.getElementType() == x2);
genericPropertyTest(x, new Property("ComponentType", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result = targetAst.newSimpleType(
targetAst.newSimpleName("a")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode wrap() {
ArrayType result = ast.newArrayType(x);
return result;
}
public void unwrap() {
ArrayType a = (ArrayType) x.getParent();
a.setComponentType(ast.newPrimitiveType(PrimitiveType.INT));
}
public ASTNode get() {
return x.getComponentType();
}
public void set(ASTNode value) {
x.setComponentType((Type) value);
}
});
x.setComponentType(
ast.newArrayType(ast.newPrimitiveType(PrimitiveType.INT), 4));
assertTrue(x.getDimensions() == 5);
assertTrue(x.getElementType().isPrimitiveType());
}
public void testParameterizedType() {
if (ast.apiLevel() == AST.JLS2) {
// node type introduced in 3.0 API
try {
ast.newParameterizedType(ast.newSimpleType(ast.newSimpleName("String"))); //$NON-NLS-1$
assertTrue(false);
} catch (UnsupportedOperationException e) {
// pass
}
return;
}
long previousCount = ast.modificationCount();
Type t = ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$
final ParameterizedType x = ast.newParameterizedType(t);
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getType() == t);
assertTrue(x.getType().getParent() == x);
assertTrue(!x.isSimpleType());
assertTrue(!x.isArrayType());
assertTrue(!x.isPrimitiveType());
assertTrue(x.isParameterizedType());
assertTrue(!x.isQualifiedType());
assertTrue(!x.isWildcardType());
assertTrue(x.getNodeType() == ASTNode.PARAMETERIZED_TYPE);
assertTrue(x.typeArguments().size() == 0);
assertTrue(x.structuralPropertiesForType() == ParameterizedType.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Type", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result =
targetAst.newSimpleType(
targetAst.newSimpleName("a")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode wrap() {
ParameterizedType s1 = ast.newParameterizedType(x); //$NON-NLS-1$
return s1;
}
public void unwrap() {
ParameterizedType s1 = (ParameterizedType) x.getParent();
s1.setType(ast.newSimpleType(ast.newSimpleName("z"))); //$NON-NLS-1$
}
public ASTNode get() {
return x.getType();
}
public void set(ASTNode value) {
x.setType((Type) value);
}
});
genericPropertyListTest(x, x.typeArguments(),
new Property("Arguments", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
PrimitiveType result = targetAst.newPrimitiveType(PrimitiveType.INT);
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode wrap() {
// return Type that embeds x
ParameterizedType s1 = ast.newParameterizedType(ast.newSimpleType(ast.newSimpleName("foo"))); //$NON-NLS-1$
s1.typeArguments().add(x);
return s1;
}
public void unwrap() {
ParameterizedType s1 = (ParameterizedType) x.getParent();
s1.typeArguments().remove(x);
}
});
}
public void testQualifiedType() {
if (ast.apiLevel() == AST.JLS2) {
// node type introduced in 3.0 API
try {
ast.newQualifiedType(
ast.newSimpleType(ast.newSimpleName("q")), //$NON-NLS-1$
ast.newSimpleName("i")); //$NON-NLS-1$
assertTrue(false);
} catch (UnsupportedOperationException e) {
// pass
}
return;
}
long previousCount = ast.modificationCount();
final QualifiedType x = ast.newQualifiedType(
ast.newSimpleType(ast.newSimpleName("q")), //$NON-NLS-1$
ast.newSimpleName("i")); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getQualifier().getParent() == x);
assertTrue(x.getName().getParent() == x);
assertTrue(x.getName().isDeclaration() == false);
assertTrue(x.getNodeType() == ASTNode.QUALIFIED_TYPE);
assertTrue(!x.isSimpleType());
assertTrue(!x.isArrayType());
assertTrue(!x.isPrimitiveType());
assertTrue(!x.isParameterizedType());
assertTrue(x.isQualifiedType());
assertTrue(!x.isWildcardType());
assertTrue(x.structuralPropertiesForType() == QualifiedType.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Qualifier", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result =
targetAst.newSimpleType(
targetAst.newSimpleName("a")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode wrap() {
QualifiedType s1 = ast.newQualifiedType(x, ast.newSimpleName("z")); //$NON-NLS-1$
return s1;
}
public void unwrap() {
QualifiedType s1 = (QualifiedType) x.getParent();
s1.setQualifier(ast.newSimpleType(ast.newSimpleName("z"))); //$NON-NLS-1$
}
public ASTNode get() {
return x.getQualifier();
}
public void set(ASTNode value) {
x.setQualifier((Type) value);
}
});
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
}
public void testWildcardType() {
if (ast.apiLevel() == AST.JLS2) {
// node type introduced in 3.0 API
try {
ast.newWildcardType();
assertTrue(false);
} catch (UnsupportedOperationException e) {
// pass
}
return;
}
long previousCount = ast.modificationCount();
final WildcardType x = ast.newWildcardType();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getBound() == null);
assertTrue(x.isUpperBound() == true);
assertTrue(x.getNodeType() == ASTNode.WILDCARD_TYPE);
assertTrue(!x.isSimpleType());
assertTrue(!x.isArrayType());
assertTrue(!x.isPrimitiveType());
assertTrue(!x.isParameterizedType());
assertTrue(!x.isQualifiedType());
assertTrue(x.isWildcardType());
assertTrue(x.structuralPropertiesForType() == WildcardType.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
// make sure that isUpperBound works
Type b = ast.newPrimitiveType(PrimitiveType.BYTE);
x.setBound(b);
x.setUpperBound(false);
assertTrue(x.isUpperBound() == false);
x.setUpperBound(true);
assertTrue(x.isUpperBound() == true);
x.setBound(null);
x.setUpperBound(false);
assertTrue(x.isUpperBound() == false);
x.setUpperBound(true);
assertTrue(x.isUpperBound() == true);
// make sure that setBound(Type,boolean) works
x.setBound(b, false);
assertTrue(x.getBound() == b);
assertTrue(x.isUpperBound() == false);
x.setBound(null, true);
assertTrue(x.getBound() == null);
assertTrue(x.isUpperBound() == true);
x.setBound(b, true);
assertTrue(x.getBound() == b);
assertTrue(x.isUpperBound() == true);
x.setBound(null, false);
assertTrue(x.getBound() == null);
assertTrue(x.isUpperBound() == false);
genericPropertyTest(x, new Property("Bound", false, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result =
targetAst.newSimpleType(
targetAst.newSimpleName("a")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode wrap() {
WildcardType s1 = ast.newWildcardType();
s1.setBound(x);
return s1;
}
public void unwrap() {
WildcardType s1 = (WildcardType) x.getParent();
s1.setBound(null);
}
public ASTNode get() {
return x.getBound();
}
public void set(ASTNode value) {
x.setBound((Type) value);
}
});
}
public void testPackageDeclaration() {
long previousCount = ast.modificationCount();
final PackageDeclaration x = ast.newPackageDeclaration();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
if (ast.apiLevel() >= AST.JLS3) {
assertTrue(x.getJavadoc() == null);
assertTrue(x.annotations().isEmpty());
}
assertTrue(x.getName().getParent() == x);
assertTrue(x.getNodeType() == ASTNode.PACKAGE_DECLARATION);
assertTrue(x.structuralPropertiesForType() == PackageDeclaration.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
if (ast.apiLevel() >= AST.JLS3) {
genericPropertyTest(x, new Property("Javadoc", false, Javadoc.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Javadoc result = targetAst.newJavadoc();
if (parented) {
targetAst.newInitializer().setJavadoc(result);
}
return result;
}
public ASTNode get() {
return x.getJavadoc();
}
public void set(ASTNode value) {
x.setJavadoc((Javadoc) value);
}
});
genericPropertyListTest(x, x.annotations(), new Property("Annotations", true, Annotation.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
MarkerAnnotation result = targetAst.newMarkerAnnotation();
if (parented) {
PackageDeclaration pd = targetAst.newPackageDeclaration();
pd.annotations().add(result);
}
return result;
}
});
}
genericPropertyTest(x, new Property("Name", true, Name.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("a"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((Name) value);
}
});
}
public void testImportDeclaration() {
long previousCount = ast.modificationCount();
final ImportDeclaration x = ast.newImportDeclaration();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.isOnDemand() == false);
if (ast.apiLevel() >= AST.JLS3) {
assertTrue(x.isStatic() == false);
}
assertTrue(x.getName().getParent() == x);
assertTrue(x.getNodeType() == ASTNode.IMPORT_DECLARATION);
assertTrue(x.structuralPropertiesForType() == ImportDeclaration.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Name", true, Name.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("a"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((Name) value);
}
});
previousCount = ast.modificationCount();
x.setOnDemand(false);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.isOnDemand() == false);
previousCount = ast.modificationCount();
x.setOnDemand(true);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.isOnDemand() == true);
if (ast.apiLevel() >= AST.JLS3) {
x.setStatic(true);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.isStatic() == true);
}
}
public void testCompilationUnit() {
long previousCount = ast.modificationCount();
final CompilationUnit x = ast.newCompilationUnit();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getPackage() == null);
assertTrue(x.imports().size() == 0);
assertTrue(x.types().size() == 0);
assertTrue(x.getNodeType() == ASTNode.COMPILATION_UNIT);
assertTrue(x.structuralPropertiesForType() == CompilationUnit.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tClientProperties(x);
genericPropertyTest(x, new Property("Package", false, PackageDeclaration.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
PackageDeclaration result = targetAst.newPackageDeclaration();
if (parented) {
CompilationUnit cu = targetAst.newCompilationUnit();
cu.setPackage(result);
}
return result;
}
public ASTNode get() {
return x.getPackage();
}
public void set(ASTNode value) {
x.setPackage((PackageDeclaration) value);
}
});
genericPropertyListTest(x, x.imports(), new Property("Imports", true, ImportDeclaration.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
ImportDeclaration result = targetAst.newImportDeclaration();
if (parented) {
CompilationUnit cu = targetAst.newCompilationUnit();
cu.imports().add(result);
}
return result;
}
});
genericPropertyListTest(x, x.types(), new Property("Types", true, AbstractTypeDeclaration.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
TypeDeclaration result = targetAst.newTypeDeclaration();
if (parented) {
CompilationUnit cu = targetAst.newCompilationUnit();
cu.types().add(result);
}
return result;
}
});
// check that TypeDeclarations in body are classified correctly
TypeDeclaration t1 = ast.newTypeDeclaration();
x.types().add(t1);
assertTrue(t1.isLocalTypeDeclaration() == false);
assertTrue(t1.isMemberTypeDeclaration() == false);
assertTrue(t1.isPackageMemberTypeDeclaration() == true);
}
public void testCompilationUnitLineNumberTable() {
// TO RUN THIS TEST YOU MUST TEMPORARILY MAKE PUBLIC
// THE METHOD CompilationUnit.setLineEndTable
// final CompilationUnit x = ast.newCompilationUnit();
//
// // table starts off empty
// for (int i= -10; i < 10; i++) {
// assertTrue(x.lineNumber(i) == 1);
// }
//
// // supply a simple line table to test
// String s = "AA\nBBB\nCC\nDDDD\nEEE";
// assertTrue(s.length() == 18); // cross check
// int le[] = new int[5];
// le[0] = s.indexOf('\n');
// le[1] = s.indexOf('\n', le[0] + 1);
// le[2] = s.indexOf('\n', le[1] + 1);
// le[3] = s.indexOf('\n', le[2] + 1);
// le[4] = s.length() - 1;
// long previousCount = ast.modificationCount();
// x.setLineEndTable(le);
// assertTrue(ast.modificationCount() > previousCount);
//
// assertTrue(x.lineNumber(0) == 1);
// assertTrue(x.lineNumber(1) == 1);
// assertTrue(x.lineNumber(2) == 1);
// assertTrue(x.lineNumber(3) == 2);
// assertTrue(x.lineNumber(4) == 2);
// assertTrue(x.lineNumber(5) == 2);
// assertTrue(x.lineNumber(6) == 2);
// assertTrue(x.lineNumber(7) == 3);
// assertTrue(x.lineNumber(8) == 3);
// assertTrue(x.lineNumber(9) == 3);
// assertTrue(x.lineNumber(10) == 4);
// assertTrue(x.lineNumber(11) == 4);
// assertTrue(x.lineNumber(12) == 4);
// assertTrue(x.lineNumber(13) == 4);
// assertTrue(x.lineNumber(14) == 4);
// assertTrue(x.lineNumber(15) == 5);
// assertTrue(x.lineNumber(16) == 5);
// assertTrue(x.lineNumber(17) == 5);
//
// assertTrue(x.lineNumber(18) == 1);
// assertTrue(x.lineNumber(100) == 1);
// assertTrue(x.lineNumber(1000000) == 1);
// assertTrue(x.lineNumber(-1) == 1);
// assertTrue(x.lineNumber(-100) == 1);
// assertTrue(x.lineNumber(-1000000) == 1);
//
// // slam table back to none
// x.setLineEndTable(new int[0]);
// for (int i= -10; i < 10; i++) {
// assertTrue(x.lineNumber(i) == 1);
// }
}
public void testTypeDeclaration() {
long previousCount = ast.modificationCount();
final TypeDeclaration x = ast.newTypeDeclaration();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
if (ast.apiLevel() == AST.JLS2) {
assertTrue(x.getModifiers() == Modifier.NONE);
assertTrue(x.getSuperclass() == null);
assertTrue(x.superInterfaces().size() == 0);
} else {
assertTrue(x.modifiers().size() == 0);
assertTrue(x.typeParameters().size() == 0);
assertTrue(x.getSuperclassType() == null);
assertTrue(x.superInterfaceTypes().size() == 0);
}
assertTrue(x.isInterface() == false);
assertTrue(x.getName().getParent() == x);
assertTrue(x.getName().isDeclaration() == true);
assertTrue(x.getJavadoc() == null);
assertTrue(x.bodyDeclarations().size()== 0);
assertTrue(x.getNodeType() == ASTNode.TYPE_DECLARATION);
assertTrue(x.structuralPropertiesForType() == TypeDeclaration.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
previousCount = ast.modificationCount();
x.setInterface(true);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.isInterface() == true);
if (ast.apiLevel() == AST.JLS2) {
int legal = Modifier.PUBLIC | Modifier.PROTECTED
| Modifier.PRIVATE | Modifier.ABSTRACT | Modifier.STATIC
| Modifier.FINAL | Modifier.STRICTFP;
previousCount = ast.modificationCount();
x.setModifiers(legal);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getModifiers() == legal);
previousCount = ast.modificationCount();
x.setModifiers(Modifier.NONE);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getModifiers() == Modifier.NONE);
}
tJavadocComment(x);
tModifiers(x);
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
if (ast.apiLevel() >= AST.JLS3) {
genericPropertyListTest(x, x.typeParameters(),
new Property("TypeParameters", true, TypeParameter.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
TypeParameter result = targetAst.newTypeParameter();
if (parented) {
targetAst.newMethodDeclaration().typeParameters().add(result);
}
return result;
}
});
}
if (ast.apiLevel() == AST.JLS2) {
genericPropertyTest(x, new Property("Superclass", false, Name.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getSuperclass();
}
public void set(ASTNode value) {
x.setSuperclass((Name) value);
}
});
}
if (ast.apiLevel() == AST.JLS2) {
genericPropertyListTest(x, x.superInterfaces(),
new Property("SuperInterfaces", true, Name.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
});
}
if (ast.apiLevel() >= AST.JLS3) {
genericPropertyTest(x, new Property("SuperclassType", false, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result = targetAst.newSimpleType(targetAst.newSimpleName("foo")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode get() {
return x.getSuperclassType();
}
public void set(ASTNode value) {
x.setSuperclassType((Type) value);
}
});
}
if (ast.apiLevel() >= AST.JLS3) {
genericPropertyListTest(x, x.superInterfaceTypes(),
new Property("SuperInterfaceTypes", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result = targetAst.newSimpleType(targetAst.newSimpleName("foo")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
});
}
genericPropertyListTest(x, x.bodyDeclarations(),
new Property("BodyDeclarations", true, BodyDeclaration.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
TypeDeclaration result = targetAst.newTypeDeclaration();
if (parented) {
CompilationUnit cu = targetAst.newCompilationUnit();
cu.types().add(result);
}
return result;
}
public ASTNode wrap() {
TypeDeclaration s1 = x.getAST().newTypeDeclaration();
s1.bodyDeclarations().add(x);
return s1;
}
public void unwrap() {
TypeDeclaration s1 = (TypeDeclaration) x.getParent();
s1.bodyDeclarations().remove(x);
}
});
// check special bodyDeclaration methods
x.bodyDeclarations().clear();
FieldDeclaration f1 = ast.newFieldDeclaration(ast.newVariableDeclarationFragment());
FieldDeclaration f2 = ast.newFieldDeclaration(ast.newVariableDeclarationFragment());
MethodDeclaration m1 = ast.newMethodDeclaration();
MethodDeclaration m2 = ast.newMethodDeclaration();
TypeDeclaration t1 = ast.newTypeDeclaration();
TypeDeclaration t2 = ast.newTypeDeclaration();
EnumConstantDeclaration c1 = null;
EnumConstantDeclaration c2 = null;
if (ast.apiLevel() >= AST.JLS3) {
c1 = ast.newEnumConstantDeclaration();
c2 = ast.newEnumConstantDeclaration();
x.bodyDeclarations().add(c1);
x.bodyDeclarations().add(c2);
}
x.bodyDeclarations().add(ast.newInitializer());
x.bodyDeclarations().add(f1);
x.bodyDeclarations().add(ast.newInitializer());
x.bodyDeclarations().add(f2);
x.bodyDeclarations().add(ast.newInitializer());
x.bodyDeclarations().add(t1);
x.bodyDeclarations().add(ast.newInitializer());
x.bodyDeclarations().add(m1);
x.bodyDeclarations().add(ast.newInitializer());
x.bodyDeclarations().add(m2);
x.bodyDeclarations().add(ast.newInitializer());
x.bodyDeclarations().add(t2);
x.bodyDeclarations().add(ast.newInitializer());
List fs = Arrays.asList(x.getFields());
assertTrue(fs.size() == 2);
assertTrue(fs.contains(f1));
assertTrue(fs.contains(f2));
List ms = Arrays.asList(x.getMethods());
assertTrue(ms.size() == 2);
assertTrue(ms.contains(m1));
assertTrue(ms.contains(m2));
List ts = Arrays.asList(x.getTypes());
assertTrue(ts.size() == 2);
assertTrue(ts.contains(t1));
assertTrue(ts.contains(t2));
// check that TypeDeclarations in body are classified correctly
assertTrue(t1.isLocalTypeDeclaration() == false);
assertTrue(t1.isMemberTypeDeclaration() == true);
assertTrue(t1.isPackageMemberTypeDeclaration() == false);
}
public void testEnumDeclaration() {
if (ast.apiLevel() == AST.JLS2) {
// node type introduced in 3.0 API
try {
ast.newEnumDeclaration();
assertTrue(false);
} catch (UnsupportedOperationException e) {
// pass
}
return;
}
long previousCount = ast.modificationCount();
final EnumDeclaration x = ast.newEnumDeclaration();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.modifiers().size() == 0);
assertTrue(x.getName().getParent() == x);
assertTrue(x.getName().isDeclaration() == true);
assertTrue(x.getJavadoc() == null);
assertTrue(x.superInterfaceTypes().size() == 0);
assertTrue(x.enumConstants().size()== 0);
assertTrue(x.bodyDeclarations().size()== 0);
assertTrue(x.getNodeType() == ASTNode.ENUM_DECLARATION);
assertTrue(x.structuralPropertiesForType() == EnumDeclaration.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
previousCount = ast.modificationCount();
tJavadocComment(x);
tModifiers(x);
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
genericPropertyListTest(x, x.superInterfaceTypes(),
new Property("SuperInterfaceTypes", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result = targetAst.newSimpleType(targetAst.newSimpleName("foo")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
});
genericPropertyListTest(x, x.enumConstants(),
new Property("EnumConstants", true, EnumConstantDeclaration.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
EnumConstantDeclaration result = targetAst.newEnumConstantDeclaration();
if (parented) {
// use fact that EnumConstantDeclaration is also a BodyDeclaration
TypeDeclaration d = targetAst.newTypeDeclaration();
d.bodyDeclarations().add(result);
}
return result;
}
public ASTNode wrap() {
EnumConstantDeclaration s1 = x.getAST().newEnumConstantDeclaration();
AnonymousClassDeclaration anonymousClassDeclaration = x.getAST().newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(anonymousClassDeclaration);
anonymousClassDeclaration.bodyDeclarations().add(x);
return s1;
}
public void unwrap() {
AnonymousClassDeclaration anonymousClassDeclaration = (AnonymousClassDeclaration) x.getParent();
if (anonymousClassDeclaration != null) {
anonymousClassDeclaration.bodyDeclarations().remove(x);
}
}
});
genericPropertyListTest(x, x.bodyDeclarations(),
new Property("BodyDeclarations", true, BodyDeclaration.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
TypeDeclaration result = targetAst.newTypeDeclaration();
if (parented) {
CompilationUnit cu = targetAst.newCompilationUnit();
cu.types().add(result);
}
return result;
}
public ASTNode wrap() {
TypeDeclaration s1 = x.getAST().newTypeDeclaration();
s1.bodyDeclarations().add(x);
return s1;
}
public void unwrap() {
TypeDeclaration s1 = (TypeDeclaration) x.getParent();
s1.bodyDeclarations().remove(x);
}
});
// check special bodyDeclaration methods
x.bodyDeclarations().clear();
EnumConstantDeclaration c1 = ast.newEnumConstantDeclaration();
EnumConstantDeclaration c2 = ast.newEnumConstantDeclaration();
FieldDeclaration f1 = ast.newFieldDeclaration(ast.newVariableDeclarationFragment());
FieldDeclaration f2 = ast.newFieldDeclaration(ast.newVariableDeclarationFragment());
MethodDeclaration m1 = ast.newMethodDeclaration();
MethodDeclaration m2 = ast.newMethodDeclaration();
TypeDeclaration t1 = ast.newTypeDeclaration();
TypeDeclaration t2 = ast.newTypeDeclaration();
x.enumConstants().add(c1);
x.enumConstants().add(c2);
x.bodyDeclarations().add(f1);
x.bodyDeclarations().add(f2);
x.bodyDeclarations().add(m1);
x.bodyDeclarations().add(m2);
x.bodyDeclarations().add(t1);
x.bodyDeclarations().add(t2);
// check that TypeDeclarations in body are classified correctly
assertTrue(t1.isLocalTypeDeclaration() == false);
assertTrue(t1.isMemberTypeDeclaration() == true);
assertTrue(t1.isPackageMemberTypeDeclaration() == false);
}
/** @deprecated Only to suppress warnings for refs to bodyDeclarations. */
// TODO (jeem) - remove deprecation after 3.1 M4
public void testEnumConstantDeclaration() {
if (ast.apiLevel() == AST.JLS2) {
// node type introduced in 3.0 API
try {
ast.newEnumConstantDeclaration();
assertTrue(false);
} catch (UnsupportedOperationException e) {
// pass
}
return;
}
long previousCount = ast.modificationCount();
final EnumConstantDeclaration x = ast.newEnumConstantDeclaration();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getName().getParent() == x);
assertTrue(x.getName().isDeclaration() == true);
assertTrue(x.getJavadoc() == null);
assertTrue(x.arguments().size()== 0);
assertTrue(x.bodyDeclarations().size()== 0);
assertTrue(x.getAnonymousClassDeclaration() == null);
assertTrue(x.modifiers().size() == 0);
assertTrue(x.getNodeType() == ASTNode.ENUM_CONSTANT_DECLARATION);
assertTrue(x.structuralPropertiesForType() == EnumConstantDeclaration.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tJavadocComment(x);
tModifiers(x);
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
genericPropertyListTest(x, x.arguments(),
new Property("Arguments", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
AnonymousClassDeclaration s1 = x.getAST().newAnonymousClassDeclaration();
s1.bodyDeclarations().add(x);
return s1;
}
public void unwrap() {
AnonymousClassDeclaration s1 = (AnonymousClassDeclaration) x.getParent();
s1.bodyDeclarations().remove(x);
}
});
// TODO (jeem) - after 3.1 M4 remove mention of bodyDeclarations
genericPropertyListTest(x, x.bodyDeclarations(),
new Property("BodyDeclarations", true, BodyDeclaration.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
TypeDeclaration result = targetAst.newTypeDeclaration();
if (parented) {
CompilationUnit cu = targetAst.newCompilationUnit();
cu.types().add(result);
}
return result;
}
public ASTNode wrap() {
EnumConstantDeclaration s1 = x.getAST().newEnumConstantDeclaration();
s1.bodyDeclarations().add(x);
return s1;
}
public void unwrap() {
EnumConstantDeclaration s1 = (EnumConstantDeclaration) x.getParent();
s1.bodyDeclarations().remove(x);
}
});
// check that TypeDeclarations in body are classified correctly
x.bodyDeclarations().clear();
TypeDeclaration t1 = ast.newTypeDeclaration();
x.bodyDeclarations().add(t1);
assertTrue(t1.isLocalTypeDeclaration() == false);
assertTrue(t1.isMemberTypeDeclaration() == true);
assertTrue(t1.isPackageMemberTypeDeclaration() == false);
genericPropertyTest(x, new Property("AnonymousClassDeclaration", false, AnonymousClassDeclaration.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
AnonymousClassDeclaration result = targetAst.newAnonymousClassDeclaration();
if (parented) {
targetAst.newClassInstanceCreation().setAnonymousClassDeclaration(result);
}
return result;
}
public ASTNode wrap() {
// return AnonymousClassDeclaration that embeds x
AnonymousClassDeclaration s0 = x.getAST().newAnonymousClassDeclaration();
EnumDeclaration s1 = x.getAST().newEnumDeclaration();
s0.bodyDeclarations().add(s1);
s1.bodyDeclarations().add(x);
return s0;
}
public void unwrap() {
EnumDeclaration s1 = (EnumDeclaration) x.getParent();
s1.bodyDeclarations().remove(x);
}
public ASTNode get() {
return x.getAnonymousClassDeclaration();
}
public void set(ASTNode value) {
x.setAnonymousClassDeclaration((AnonymousClassDeclaration) value);
}
});
// check that TypeDeclarations in body are classified correctly
x.setAnonymousClassDeclaration(null);
AnonymousClassDeclaration w0 = ast.newAnonymousClassDeclaration();
x.setAnonymousClassDeclaration(w0);
TypeDeclaration w1 = ast.newTypeDeclaration();
w0.bodyDeclarations().add(w1);
assertTrue(w1.isLocalTypeDeclaration() == false);
assertTrue(w1.isMemberTypeDeclaration() == true);
assertTrue(w1.isPackageMemberTypeDeclaration() == false);
}
public void testTypeParameter() {
if (ast.apiLevel() == AST.JLS2) {
// node type introduced in 3.0 API
try {
ast.newTypeParameter();
assertTrue(false);
} catch (UnsupportedOperationException e) {
// pass
}
return;
}
long previousCount = ast.modificationCount();
final TypeParameter x = ast.newTypeParameter();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getName().getParent() == x);
assertTrue(x.getNodeType() == ASTNode.TYPE_PARAMETER);
assertTrue(x.typeBounds().size() == 0);
assertTrue(x.structuralPropertiesForType() == TypeParameter.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("a"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
genericPropertyListTest(x, x.typeBounds(),
new Property("TypeBounds", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Type result = targetAst.newSimpleType(targetAst.newSimpleName("foo"));
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
});
}
public void testSingleVariableDeclaration() {
long previousCount = ast.modificationCount();
final SingleVariableDeclaration x = ast.newSingleVariableDeclaration();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
if (ast.apiLevel() == AST.JLS2) {
assertTrue(x.getModifiers() == Modifier.NONE);
} else {
assertTrue(x.modifiers().size() == 0);
assertTrue(x.isVarargs() == false);
}
assertTrue(x.getName().getParent() == x);
assertTrue(x.getName().isDeclaration() == true);
assertTrue(x.getType().getParent() == x);
assertTrue(x.getExtraDimensions() == 0);
assertTrue(x.getInitializer() == null);
assertTrue(x.getNodeType() == ASTNode.SINGLE_VARIABLE_DECLARATION);
assertTrue(x.structuralPropertiesForType() == SingleVariableDeclaration.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
if (ast.apiLevel() == AST.JLS2) {
int legal = Modifier.PUBLIC | Modifier.PROTECTED
| Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL
| Modifier.TRANSIENT | Modifier.VOLATILE;
previousCount = ast.modificationCount();
x.setModifiers(legal);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getModifiers() == legal);
previousCount = ast.modificationCount();
x.setModifiers(Modifier.NONE);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getModifiers() == Modifier.NONE);
}
previousCount = ast.modificationCount();
x.setExtraDimensions(1);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getExtraDimensions() == 1);
previousCount = ast.modificationCount();
x.setExtraDimensions(0);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getExtraDimensions() == 0);
if (ast.apiLevel() >= AST.JLS3) {
previousCount = ast.modificationCount();
x.setVarargs(true);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.isVarargs() == true);
previousCount = ast.modificationCount();
x.setVarargs(false);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.isVarargs() == false);
}
if (ast.apiLevel() >= AST.JLS3) {
genericPropertyListTest(x, x.modifiers(), new Property("Modifiers", true, IExtendedModifier.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Modifier result = targetAst.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
if (parented) {
TypeDeclaration pd = targetAst.newTypeDeclaration();
pd.modifiers().add(result);
}
return result;
}
public ASTNode wrap() {
SingleMemberAnnotation s1 = x.getAST().newSingleMemberAnnotation();
ClassInstanceCreation s2 = x.getAST().newClassInstanceCreation();
AnonymousClassDeclaration s3 = x.getAST().newAnonymousClassDeclaration();
MethodDeclaration s4 = x.getAST().newMethodDeclaration();
SingleVariableDeclaration s5 = x.getAST().newSingleVariableDeclaration();
s1.setValue(s2);
s2.setAnonymousClassDeclaration(s3);
s3.bodyDeclarations().add(s4);
s4.parameters().add(s5);
s5.modifiers().add(x);
return s1;
}
public void unwrap() {
SingleVariableDeclaration s5 = (SingleVariableDeclaration) x.getParent();
s5.modifiers().remove(x);
}
});
// check that getModifiers() tracks changes to modifiers()
x.modifiers().clear();
assertTrue(x.getModifiers() == Modifier.NONE);
Modifier[] allMods = allModifiers();
// one at a time
for (int i = 0 ; i < allMods.length; i++) {
x.modifiers().add(allMods[i]);
assertTrue(x.getModifiers() == allMods[i].getKeyword().toFlagValue());
x.modifiers().remove(allMods[i]);
assertTrue(x.getModifiers() == Modifier.NONE);
}
// all at same time
for (int i = 0 ; i < allMods.length; i++) {
x.modifiers().add(allMods[i]);
}
int flags = x.getModifiers();
for (int i = 0 ; i < allMods.length; i++) {
assertTrue((flags & allMods[i].getKeyword().toFlagValue()) != 0);
}
}
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
genericPropertyTest(x, new Property("Type", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result = targetAst.newSimpleType(
targetAst.newSimpleName("foo")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode get() {
return x.getType();
}
public void set(ASTNode value) {
x.setType((Type) value);
}
});
genericPropertyTest(x, new Property("Initializer", false, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return an Expression that embeds x
CatchClause s1 = ast.newCatchClause();
s1.setException(x);
return s1;
}
public void unwrap() {
CatchClause s1 = (CatchClause) x.getParent();
s1.setException(ast.newSingleVariableDeclaration());
}
public ASTNode get() {
return x.getInitializer();
}
public void set(ASTNode value) {
x.setInitializer((Expression) value);
}
});
}
public void testVariableDeclarationFragment() {
long previousCount = ast.modificationCount();
final VariableDeclarationFragment x = ast.newVariableDeclarationFragment();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getName().getParent() == x);
assertTrue(x.getName().isDeclaration() == true);
assertTrue(x.getExtraDimensions() == 0);
assertTrue(x.getInitializer() == null);
assertTrue(x.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT);
assertTrue(x.structuralPropertiesForType() ==
VariableDeclarationFragment.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
previousCount = ast.modificationCount();
x.setExtraDimensions(1);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getExtraDimensions() == 1);
previousCount = ast.modificationCount();
x.setExtraDimensions(0);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getExtraDimensions() == 0);
// check that property cannot be set negative
try {
x.setExtraDimensions(-1);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
genericPropertyTest(x, new Property("Initializer", false, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return an Expression that embeds x
VariableDeclarationExpression s1 =
ast.newVariableDeclarationExpression(x);
return s1;
}
public void unwrap() {
VariableDeclarationExpression s1 =
(VariableDeclarationExpression) x.getParent();
s1.fragments().remove(x);
}
public ASTNode get() {
return x.getInitializer();
}
public void set(ASTNode value) {
x.setInitializer((Expression) value);
}
});
}
public void testMethodDeclaration() {
long previousCount = ast.modificationCount();
final MethodDeclaration x = ast.newMethodDeclaration();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
if (ast.apiLevel() == AST.JLS2) {
assertTrue(x.getModifiers() == Modifier.NONE);
assertTrue(x.getReturnType().getParent() == x);
assertTrue(x.getReturnType().isPrimitiveType());
assertTrue(((PrimitiveType) x.getReturnType()).getPrimitiveTypeCode() == PrimitiveType.VOID);
} else {
assertTrue(x.modifiers().size() == 0);
assertTrue(x.typeParameters().size() == 0);
assertTrue(x.getReturnType2().getParent() == x);
assertTrue(x.getReturnType2().isPrimitiveType());
assertTrue(((PrimitiveType) x.getReturnType2()).getPrimitiveTypeCode() == PrimitiveType.VOID);
}
assertTrue(x.isConstructor() == false);
assertTrue(x.getName().getParent() == x);
assertTrue(x.getName().isDeclaration() == true);
assertTrue(x.getExtraDimensions() == 0);
assertTrue(x.getJavadoc() == null);
assertTrue(x.parameters().size() == 0);
assertTrue(x.thrownExceptions().size() == 0);
assertTrue(x.getBody() == null);
assertTrue(x.getNodeType() == ASTNode.METHOD_DECLARATION);
assertTrue(x.structuralPropertiesForType() ==
MethodDeclaration.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
previousCount = ast.modificationCount();
x.setConstructor(true);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.isConstructor() == true);
assertTrue(x.getName().isDeclaration() == false);
previousCount = ast.modificationCount();
x.setConstructor(false);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.isConstructor() == false);
if (ast.apiLevel() == AST.JLS2) {
previousCount = ast.modificationCount();
int legal = Modifier.PUBLIC | Modifier.PROTECTED
| Modifier.PRIVATE | Modifier.ABSTRACT | Modifier.STATIC
| Modifier.FINAL | Modifier.SYNCHRONIZED| Modifier.NATIVE
| Modifier.STRICTFP;
x.setModifiers(legal);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getModifiers() == legal);
previousCount = ast.modificationCount();
x.setModifiers(Modifier.NONE);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getModifiers() == Modifier.NONE);
}
previousCount = ast.modificationCount();
x.setExtraDimensions(1);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getExtraDimensions() == 1);
previousCount = ast.modificationCount();
x.setExtraDimensions(0);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getExtraDimensions() == 0);
tJavadocComment(x);
tModifiers(x);
if (ast.apiLevel() >= AST.JLS3) {
genericPropertyListTest(x, x.typeParameters(),
new Property("TypeParameters", true, TypeParameter.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
TypeParameter result = targetAst.newTypeParameter();
if (parented) {
targetAst.newMethodDeclaration().typeParameters().add(result);
}
return result;
}
});
}
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
if (ast.apiLevel() == AST.JLS2) {
genericPropertyTest(x, new Property("ReturnType", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result = targetAst.newSimpleType(
targetAst.newSimpleName("foo")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode get() {
return x.getReturnType();
}
public void set(ASTNode value) {
x.setReturnType((Type) value);
}
});
}
if (ast.apiLevel() >= AST.JLS3) {
genericPropertyTest(x, new Property("ReturnType2", false, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result = targetAst.newSimpleType(
targetAst.newSimpleName("foo")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode get() {
return x.getReturnType2();
}
public void set(ASTNode value) {
x.setReturnType2((Type) value);
}
});
}
genericPropertyListTest(x, x.parameters(),
new Property("Parameters", true, SingleVariableDeclaration.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SingleVariableDeclaration result = targetAst.newSingleVariableDeclaration();
if (parented) {
targetAst.newCatchClause().setException(result);
}
return result;
}
public ASTNode wrap() {
// return a SingleVariableDeclaration that embeds x
SingleVariableDeclaration s1 = ast.newSingleVariableDeclaration();
ClassInstanceCreation s2 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s2.setAnonymousClassDeclaration(a1);
s1.setInitializer(s2);
a1.bodyDeclarations().add(x);
return s1;
}
public void unwrap() {
AnonymousClassDeclaration a1 = (AnonymousClassDeclaration) x.getParent();
a1.bodyDeclarations().remove(x);
}
});
genericPropertyListTest(x, x.thrownExceptions(),
new Property("ThrownExceptions", true, Name.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
});
genericPropertyTest(x, new Property("Body", false, Block.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Block result = targetAst.newBlock();
if (parented) {
Block b2 = targetAst.newBlock();
b2.statements().add(result);
}
return result;
}
public ASTNode wrap() {
// return a Block that embeds x
Block s1 = ast.newBlock();
TypeDeclaration s2 = ast.newTypeDeclaration();
s1.statements().add(ast.newTypeDeclarationStatement(s2));
s2.bodyDeclarations().add(x);
return s1;
}
public void unwrap() {
TypeDeclaration s2 = (TypeDeclaration) x.getParent();
s2.bodyDeclarations().remove(x);
}
public ASTNode get() {
return x.getBody();
}
public void set(ASTNode value) {
x.setBody((Block) value);
}
});
if (ast.apiLevel() >= AST.JLS3) {
// check isVariableArity convenience method
x.parameters().clear();
assertTrue(!x.isVarargs()); // 0 params
x.parameters().add(ast.newSingleVariableDeclaration());
assertTrue(!x.isVarargs()); // 1 params
SingleVariableDeclaration v = ast.newSingleVariableDeclaration();
x.parameters().add(v);
assertTrue(!x.isVarargs()); // 2 param fixed arity
v.setVarargs(true);
assertTrue(x.isVarargs()); // 2 param fixed arity
x.parameters().add(ast.newSingleVariableDeclaration());
assertTrue(!x.isVarargs()); // only last param counts
}
}
public void testInitializer() {
long previousCount = ast.modificationCount();
final Initializer x = ast.newInitializer();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getJavadoc() == null);
if (ast.apiLevel() == AST.JLS2) {
assertTrue(x.getModifiers() == Modifier.NONE);
} else {
assertTrue(x.modifiers().size() == 0);
}
assertTrue(x.getBody().getParent() == x);
assertTrue(x.getBody().statements().size() == 0);
assertTrue(x.getNodeType() == ASTNode.INITIALIZER);
assertTrue(x.structuralPropertiesForType() ==
Initializer.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tJavadocComment(x);
tModifiers(x);
if (ast.apiLevel() == AST.JLS2) {
int legal = Modifier.STATIC;
previousCount = ast.modificationCount();
x.setModifiers(legal);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getModifiers() == legal);
previousCount = ast.modificationCount();
x.setModifiers(Modifier.NONE);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getModifiers() == Modifier.NONE);
}
genericPropertyTest(x, new Property("Body", true, Block.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Block result = targetAst.newBlock();
if (parented) {
Block b2 = targetAst.newBlock();
b2.statements().add(result);
}
return result;
}
public ASTNode wrap() {
// return Block that embeds x
Block s1 = ast.newBlock();
TypeDeclaration s2 = ast.newTypeDeclaration();
s1.statements().add(ast.newTypeDeclarationStatement(s2));
s2.bodyDeclarations().add(x);
return s1;
}
public void unwrap() {
TypeDeclaration s2 = (TypeDeclaration) x.getParent();
s2.bodyDeclarations().remove(x);
}
public ASTNode get() {
return x.getBody();
}
public void set(ASTNode value) {
x.setBody((Block) value);
}
});
}
/**
* @deprecated (not really - its just that Javadoc.get/setComment
* are deprecated, and this suppresses the extra warnings)
*/
public void testJavadoc() {
long previousCount = ast.modificationCount();
final Javadoc x = ast.newJavadoc();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
if (ast.apiLevel() == AST.JLS2) {
assertTrue(x.getComment().startsWith("/**")); //$NON-NLS-1$
assertTrue(x.getComment().endsWith("*/")); //$NON-NLS-1$
}
assertTrue(x.getNodeType() == ASTNode.JAVADOC);
assertTrue(!x.isBlockComment());
assertTrue(!x.isLineComment());
assertTrue(x.isDocComment());
assertTrue(x.tags().isEmpty());
assertTrue(x.getAlternateRoot() == null);
assertTrue(x.structuralPropertiesForType() ==
Javadoc.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
// check the constants
assertTrue(TagElement.TAG_AUTHOR.equals("@author")); //$NON-NLS-1$
assertTrue(TagElement.TAG_DEPRECATED.equals("@deprecated")); //$NON-NLS-1$
assertTrue(TagElement.TAG_DOCROOT.equals("@docRoot")); //$NON-NLS-1$
assertTrue(TagElement.TAG_EXCEPTION.equals("@exception")); //$NON-NLS-1$
assertTrue(TagElement.TAG_INHERITDOC.equals("@inheritDoc")); //$NON-NLS-1$
assertTrue(TagElement.TAG_LINK.equals("@link")); //$NON-NLS-1$
assertTrue(TagElement.TAG_LINKPLAIN.equals("@linkplain")); //$NON-NLS-1$
assertTrue(TagElement.TAG_PARAM.equals("@param")); //$NON-NLS-1$
assertTrue(TagElement.TAG_RETURN.equals("@return")); //$NON-NLS-1$
assertTrue(TagElement.TAG_SEE.equals("@see")); //$NON-NLS-1$
assertTrue(TagElement.TAG_SERIAL.equals("@serial")); //$NON-NLS-1$
assertTrue(TagElement.TAG_SERIALDATA.equals("@serialData")); //$NON-NLS-1$
assertTrue(TagElement.TAG_SERIALFIELD.equals("@serialField")); //$NON-NLS-1$
assertTrue(TagElement.TAG_SINCE.equals("@since")); //$NON-NLS-1$
assertTrue(TagElement.TAG_THROWS.equals("@throws")); //$NON-NLS-1$
assertTrue(TagElement.TAG_VALUE.equals("@value")); //$NON-NLS-1$
assertTrue(TagElement.TAG_VERSION.equals("@version")); //$NON-NLS-1$
if (ast.apiLevel() == AST.JLS2) {
final String[] samples =
{
"/** Hello there */", //$NON-NLS-1$
"/**\n * Line 1\n * Line 2\n */", //$NON-NLS-1$
"/***/", //$NON-NLS-1$
};
for (int i = 0; i < samples.length; i++) {
previousCount = ast.modificationCount();
x.setComment(samples[i]);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(samples[i].equals(x.getComment()));
}
final String[] badSamples =
{
null,
"", //$NON-NLS-1$
"/* */", //$NON-NLS-1$
"/**", //$NON-NLS-1$
"*/", //$NON-NLS-1$
};
// check that property cannot be set to clearly illegal things
for (int i = 0; i < badSamples.length; i++) {
try {
x.setComment(badSamples[i]);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
}
}
tAlternateRoot(x);
genericPropertyListTest(x, x.tags(),
new Property("Tags", true, TagElement.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
TagElement result = targetAst.newTagElement();
if (parented) {
Javadoc parent = targetAst.newJavadoc();
parent.tags().add(result);
}
return result;
}
public ASTNode[] counterExamples(AST targetAst) {
return new ASTNode[] {
targetAst.newEmptyStatement(),
targetAst.newCompilationUnit(),
targetAst.newTypeDeclaration(),
targetAst.newJavadoc(),
targetAst.newTextElement(),
targetAst.newMethodRef()
};
}
});
}
public void testBlockComment() {
long previousCount = ast.modificationCount();
final BlockComment x = ast.newBlockComment();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getNodeType() == ASTNode.BLOCK_COMMENT);
assertTrue(x.isBlockComment());
assertTrue(!x.isLineComment());
assertTrue(!x.isDocComment());
assertTrue(x.getAlternateRoot() == null);
assertTrue(x.structuralPropertiesForType() ==
BlockComment.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tAlternateRoot(x);
}
public void testLineComment() {
long previousCount = ast.modificationCount();
final LineComment x = ast.newLineComment();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getNodeType() == ASTNode.LINE_COMMENT);
assertTrue(!x.isBlockComment());
assertTrue(x.isLineComment());
assertTrue(!x.isDocComment());
assertTrue(x.getAlternateRoot() == null);
assertTrue(x.structuralPropertiesForType() ==
LineComment.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tAlternateRoot(x);
}
public void testTagElement() {
long previousCount = ast.modificationCount();
final TagElement x = ast.newTagElement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getNodeType() == ASTNode.TAG_ELEMENT);
assertTrue(x.getTagName() == null);
assertTrue(x.fragments().isEmpty());
assertTrue(x.structuralPropertiesForType() ==
TagElement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
// tagName property
previousCount = ast.modificationCount();
String s1 = new String("hello"); //$NON-NLS-1$
x.setTagName(s1);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getTagName() == s1);
previousCount = ast.modificationCount();
String s2 = new String("bye"); //$NON-NLS-1$
x.setTagName(s2);
assertTrue(x.getTagName() == s2);
assertTrue(ast.modificationCount() > previousCount);
x.setTagName(null);
assertTrue(x.getTagName() == null);
assertTrue(ast.modificationCount() > previousCount);
// check that fragments() can handle TagElement
genericPropertyListTest(x, x.fragments(),
new Property("Fragments", true, TagElement.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
TagElement result = targetAst.newTagElement();
if (parented) {
Javadoc parent = targetAst.newJavadoc();
parent.tags().add(result);
}
return result;
}
public ASTNode wrap() {
// return TagElement that embeds x
TagElement tagElement = ast.newTagElement();
tagElement.fragments().add(x);
return tagElement;
}
public void unwrap() {
TagElement tagElement = (TagElement) x.getParent();
tagElement.fragments().remove(x);
}
public ASTNode[] counterExamples(AST targetAst) {
return new ASTNode[] {
targetAst.newEmptyStatement(),
targetAst.newCompilationUnit(),
targetAst.newTypeDeclaration(),
targetAst.newJavadoc(),
};
}
});
// check that fragments() can handle Name
genericPropertyListTest(x, x.fragments(),
new Property("Fragments", true, Name.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
});
// check that fragments() can handle TextElement
genericPropertyListTest(x, x.fragments(),
new Property("Fragments", true, TextElement.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
TextElement result = targetAst.newTextElement();
if (parented) {
TagElement parent = targetAst.newTagElement();
parent.fragments().add(result);
}
return result;
}
});
// check that fragments() can handle MethodRef
genericPropertyListTest(x, x.fragments(),
new Property("Fragments", true, MethodRef.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
MethodRef result = targetAst.newMethodRef();
if (parented) {
TagElement parent = targetAst.newTagElement();
parent.fragments().add(result);
}
return result;
}
});
// check that fragments() can handle MemberRef
genericPropertyListTest(x, x.fragments(),
new Property("Fragments", true, MemberRef.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
MemberRef result = targetAst.newMemberRef();
if (parented) {
TagElement parent = targetAst.newTagElement();
parent.fragments().add(result);
}
return result;
}
});
}
public void testTextElement() {
long previousCount = ast.modificationCount();
final TextElement x = ast.newTextElement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getNodeType() == ASTNode.TEXT_ELEMENT);
assertTrue(x.getText().length() == 0);
assertTrue(x.structuralPropertiesForType() ==
TextElement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
// text property
previousCount = ast.modificationCount();
String s1 = new String("hello");
x.setText(s1);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getText() == s1);
previousCount = ast.modificationCount();
String s2 = new String("");
x.setText(s2);
assertTrue(x.getText() == s2);
assertTrue(ast.modificationCount() > previousCount);
// check that property cannot be set to null
previousCount = ast.modificationCount();
try {
x.setText(null);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
assertTrue(ast.modificationCount() == previousCount);
// check that property cannot include */
previousCount = ast.modificationCount();
try {
x.setText("this would be the */ end of it"); //$NON-NLS-1$
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
assertTrue(ast.modificationCount() == previousCount);
}
public void testMemberRef() {
long previousCount = ast.modificationCount();
final MemberRef x = ast.newMemberRef();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getNodeType() == ASTNode.MEMBER_REF);
assertTrue(x.getQualifier() == null);
assertTrue(x.getName().getParent() == x);
assertTrue(x.structuralPropertiesForType() ==
MemberRef.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Qualifier", false, Name.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
QualifiedName result = targetAst.newQualifiedName(
targetAst.newSimpleName("a"), //$NON-NLS-1$
targetAst.newSimpleName("b")); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getQualifier();
}
public void set(ASTNode value) {
x.setQualifier((Name) value);
}
});
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
}
public void testMethodRef() {
long previousCount = ast.modificationCount();
final MethodRef x = ast.newMethodRef();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getNodeType() == ASTNode.METHOD_REF);
assertTrue(x.getQualifier() == null);
assertTrue(x.getName().getParent() == x);
assertTrue(x.parameters().isEmpty());
assertTrue(x.structuralPropertiesForType() ==
MethodRef.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Qualifier", false, Name.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
QualifiedName result = targetAst.newQualifiedName(
targetAst.newSimpleName("a"), //$NON-NLS-1$
targetAst.newSimpleName("b")); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getQualifier();
}
public void set(ASTNode value) {
x.setQualifier((Name) value);
}
});
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
genericPropertyListTest(x, x.parameters(),
new Property("Parameters", true, MethodRefParameter.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
MethodRefParameter result = targetAst.newMethodRefParameter();
if (parented) {
MethodRef parent = targetAst.newMethodRef();
parent.parameters().add(result);
}
return result;
}
});
}
public void testMethodRefParameter() {
long previousCount = ast.modificationCount();
final MethodRefParameter x = ast.newMethodRefParameter();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getNodeType() == ASTNode.METHOD_REF_PARAMETER);
assertTrue(x.getType().getParent() == x);
assertTrue(x.getName() == null);
assertTrue(x.structuralPropertiesForType() ==
MethodRefParameter.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Type", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result = targetAst.newSimpleType(
targetAst.newSimpleName("foo")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode get() {
return x.getType();
}
public void set(ASTNode value) {
x.setType((Type) value);
}
});
genericPropertyTest(x, new Property("Name", false, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
}
public void testBlock() {
long previousCount = ast.modificationCount();
final Block x = ast.newBlock();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.statements().size() == 0);
assertTrue(x.getNodeType() == ASTNode.BLOCK);
assertTrue(x.structuralPropertiesForType() ==
Block.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
genericPropertyListTest(x, x.statements(),
new Property("Statements", true, Statement.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Block result = targetAst.newBlock();
if (parented) {
Block b2 = targetAst.newBlock();
b2.statements().add(result);
}
return result;
}
public ASTNode wrap() {
// return a Statement that embeds x
Block s1 = ast.newBlock();
s1.statements().add(x);
return s1;
}
public void unwrap() {
Block s2 = (Block) x.getParent();
s2.statements().remove(x);
}
});
}
public void testMethodInvocation() {
long previousCount = ast.modificationCount();
final MethodInvocation x = ast.newMethodInvocation();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
if (ast.apiLevel() >= AST.JLS3) {
assertTrue(x.typeArguments().isEmpty());
}
assertTrue(x.getName().getParent() == x);
assertTrue(x.getExpression() == null);
assertTrue(x.arguments().size() == 0);
assertTrue(x.getNodeType() == ASTNode.METHOD_INVOCATION);
assertTrue(x.structuralPropertiesForType() ==
MethodInvocation.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Expression", false, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("x")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
if (ast.apiLevel() >= AST.JLS3) {
genericPropertyListTest(x, x.typeArguments(),
new Property("TypeArguments", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Type result = targetAst.newSimpleType(targetAst.newSimpleName("X")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
});
}
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
genericPropertyListTest(x, x.arguments(),
new Property("Arguments", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("x")); //$NON-NLS-1$
}
});
}
public void testExpressionStatement() {
long previousCount = ast.modificationCount();
SimpleName x1 = ast.newSimpleName("foo"); //$NON-NLS-1$
final ExpressionStatement x = ast.newExpressionStatement(x1);
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getExpression() == x1);
assertTrue(x1.getParent() == x);
assertTrue(x.getNodeType() == ASTNode.EXPRESSION_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
ExpressionStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
genericPropertyTest(x, new Property("Expression", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
}
public void testVariableDeclarationStatement() {
VariableDeclarationFragment x1 = ast.newVariableDeclarationFragment();
long previousCount = ast.modificationCount();
final VariableDeclarationStatement x =
ast.newVariableDeclarationStatement(x1);
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
if (ast.apiLevel() == AST.JLS2) {
assertTrue(x.getModifiers() == Modifier.NONE);
} else {
assertTrue(x.modifiers().size() == 0);
}
assertTrue(x.getType() != null);
assertTrue(x.getType().getParent() == x);
assertTrue(x.fragments().size() == 1);
assertTrue(x.fragments().get(0) == x1);
assertTrue(x1.getParent() == x);
assertTrue(x.getNodeType() == ASTNode.VARIABLE_DECLARATION_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
VariableDeclarationStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
if (ast.apiLevel() == AST.JLS2) {
int legal = Modifier.FINAL;
previousCount = ast.modificationCount();
x.setModifiers(legal);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getModifiers() == legal);
previousCount = ast.modificationCount();
x.setModifiers(Modifier.NONE);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getModifiers() == Modifier.NONE);
}
if (ast.apiLevel() >= AST.JLS3) {
genericPropertyListTest(x, x.modifiers(), new Property("Modifiers", true, IExtendedModifier.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Modifier result = targetAst.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
if (parented) {
TypeDeclaration pd = targetAst.newTypeDeclaration();
pd.modifiers().add(result);
}
return result;
}
public ASTNode wrap() {
SingleMemberAnnotation s1 = x.getAST().newSingleMemberAnnotation();
ClassInstanceCreation s2 = x.getAST().newClassInstanceCreation();
AnonymousClassDeclaration s3 = x.getAST().newAnonymousClassDeclaration();
MethodDeclaration s4 = x.getAST().newMethodDeclaration();
Block s5 = x.getAST().newBlock();
VariableDeclarationFragment s6 = x.getAST().newVariableDeclarationFragment();
VariableDeclarationStatement s7 = x.getAST().newVariableDeclarationStatement(s6);
s1.setValue(s2);
s2.setAnonymousClassDeclaration(s3);
s3.bodyDeclarations().add(s4);
s4.setBody(s5);
s5.statements().add(s7);
s7.modifiers().add(x);
return s1;
}
public void unwrap() {
VariableDeclarationStatement s7 = (VariableDeclarationStatement) x.getParent();
s7.modifiers().remove(x);
}
});
// check that getModifiers() tracks changes to modifiers()
x.modifiers().clear();
assertTrue(x.getModifiers() == Modifier.NONE);
Modifier[] allMods = allModifiers();
// one at a time
for (int i = 0 ; i < allMods.length; i++) {
x.modifiers().add(allMods[i]);
assertTrue(x.getModifiers() == allMods[i].getKeyword().toFlagValue());
x.modifiers().remove(allMods[i]);
assertTrue(x.getModifiers() == Modifier.NONE);
}
// all at same time
for (int i = 0 ; i < allMods.length; i++) {
x.modifiers().add(allMods[i]);
}
int flags = x.getModifiers();
for (int i = 0 ; i < allMods.length; i++) {
assertTrue((flags & allMods[i].getKeyword().toFlagValue()) != 0);
}
}
genericPropertyTest(x, new Property("Type", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result = targetAst.newSimpleType(
targetAst.newSimpleName("foo")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode get() {
return x.getType();
}
public void set(ASTNode value) {
x.setType((Type) value);
}
});
genericPropertyListTest(x, x.fragments(),
new Property("VariableSpecifiers", true, VariableDeclarationFragment.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
VariableDeclarationFragment result = targetAst.newVariableDeclarationFragment();
if (parented) {
targetAst.newVariableDeclarationExpression(result);
}
return result;
}
public ASTNode wrap() {
// return VariableDeclarationFragment that embeds x
VariableDeclarationFragment s1 = ast.newVariableDeclarationFragment();
ClassInstanceCreation s0 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s0.setAnonymousClassDeclaration(a1);
s1.setInitializer(s0);
Initializer s2 = ast.newInitializer();
a1.bodyDeclarations().add(s2);
s2.getBody().statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
});
}
public void testTypeDeclarationStatement() {
AbstractTypeDeclaration x1 = ast.newTypeDeclaration();
long previousCount = ast.modificationCount();
final TypeDeclarationStatement x =
ast.newTypeDeclarationStatement(x1);
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
if (ast.apiLevel() == AST.JLS2) {
assertTrue(x.getTypeDeclaration() == x1);
} else {
assertTrue(x.getDeclaration() == x1);
}
assertTrue(x1.getParent() == x);
assertTrue(x.getNodeType() == ASTNode.TYPE_DECLARATION_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
TypeDeclarationStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
// check that TypeDeclaration inside is classified correctly
assertTrue(x1.isLocalTypeDeclaration() == true);
assertTrue(x1.isMemberTypeDeclaration() == false);
assertTrue(x1.isPackageMemberTypeDeclaration() == false);
tLeadingComment(x);
if (ast.apiLevel() == AST.JLS2) {
genericPropertyTest(x, new Property("TypeDeclaration", true, TypeDeclaration.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
TypeDeclaration result = targetAst.newTypeDeclaration();
if (parented) {
targetAst.newTypeDeclarationStatement(result);
}
return result;
}
public ASTNode wrap() {
// return TypeDeclaration that embeds x
TypeDeclaration s1 = ast.newTypeDeclaration();
MethodDeclaration s2 = ast.newMethodDeclaration();
s1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
public ASTNode get() {
return x.getTypeDeclaration();
}
public void set(ASTNode value) {
x.setTypeDeclaration((TypeDeclaration) value);
}
});
}
if (ast.apiLevel() >= AST.JLS3) {
genericPropertyTest(x, new Property("Declaration", true, AbstractTypeDeclaration.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
AbstractTypeDeclaration result = targetAst.newTypeDeclaration();
if (parented) {
targetAst.newTypeDeclarationStatement(result);
}
return result;
}
public ASTNode wrap() {
// return TypeDeclaration that embeds x
TypeDeclaration s1 = ast.newTypeDeclaration();
MethodDeclaration s2 = ast.newMethodDeclaration();
s1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
public ASTNode get() {
return x.getDeclaration();
}
public void set(ASTNode value) {
x.setDeclaration((AbstractTypeDeclaration) value);
}
});
}
}
public void testVariableDeclarationExpression() {
VariableDeclarationFragment x1 = ast.newVariableDeclarationFragment();
long previousCount = ast.modificationCount();
final VariableDeclarationExpression x =
ast.newVariableDeclarationExpression(x1);
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
if (ast.apiLevel() == AST.JLS2) {
assertTrue(x.getModifiers() == Modifier.NONE);
} else {
assertTrue(x.modifiers().size() == 0);
}
assertTrue(x.getType() != null);
assertTrue(x.getType().getParent() == x);
assertTrue(x.fragments().size() == 1);
assertTrue(x.fragments().get(0) == x1);
assertTrue(x1.getParent() == x);
assertTrue(x.getNodeType() == ASTNode.VARIABLE_DECLARATION_EXPRESSION);
assertTrue(x.structuralPropertiesForType() ==
VariableDeclarationExpression.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
if (ast.apiLevel() == AST.JLS2) {
int legal = Modifier.FINAL;
previousCount = ast.modificationCount();
x.setModifiers(legal);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getModifiers() == legal);
previousCount = ast.modificationCount();
x.setModifiers(Modifier.NONE);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getModifiers() == Modifier.NONE);
}
if (ast.apiLevel() >= AST.JLS3) {
genericPropertyListTest(x, x.modifiers(), new Property("Modifiers", true, IExtendedModifier.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Modifier result = targetAst.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
if (parented) {
TypeDeclaration pd = targetAst.newTypeDeclaration();
pd.modifiers().add(result);
}
return result;
}
public ASTNode wrap() {
SingleMemberAnnotation s1 = x.getAST().newSingleMemberAnnotation();
s1.setValue(x);
return s1;
}
public void unwrap() {
SingleMemberAnnotation s1 = (SingleMemberAnnotation) x.getParent();
s1.setValue(x.getAST().newNullLiteral());
}
});
// check that getModifiers() tracks changes to modifiers()
x.modifiers().clear();
assertTrue(x.getModifiers() == Modifier.NONE);
Modifier[] allMods = allModifiers();
// one at a time
for (int i = 0 ; i < allMods.length; i++) {
x.modifiers().add(allMods[i]);
assertTrue(x.getModifiers() == allMods[i].getKeyword().toFlagValue());
x.modifiers().remove(allMods[i]);
assertTrue(x.getModifiers() == Modifier.NONE);
}
// all at same time
for (int i = 0 ; i < allMods.length; i++) {
x.modifiers().add(allMods[i]);
}
int flags = x.getModifiers();
for (int i = 0 ; i < allMods.length; i++) {
assertTrue((flags & allMods[i].getKeyword().toFlagValue()) != 0);
}
}
genericPropertyTest(x, new Property("Type", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result = targetAst.newSimpleType(
targetAst.newSimpleName("foo")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode get() {
return x.getType();
}
public void set(ASTNode value) {
x.setType((Type) value);
}
});
genericPropertyListTest(x, x.fragments(),
new Property("VariableSpecifiers", true, VariableDeclarationFragment.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
VariableDeclarationFragment result = targetAst.newVariableDeclarationFragment();
if (parented) {
targetAst.newVariableDeclarationExpression(result);
}
return result;
}
public ASTNode wrap() {
// return VariableDeclarationFragment that embeds x
VariableDeclarationFragment s1 = ast.newVariableDeclarationFragment();
ClassInstanceCreation s0 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s0.setAnonymousClassDeclaration(a1);
s1.setInitializer(s0);
ForStatement s2 = ast.newForStatement();
s2.initializers().add(x);
Initializer s3 = ast.newInitializer();
a1.bodyDeclarations().add(s3);
s3.getBody().statements().add(s2);
return s1;
}
public void unwrap() {
ForStatement s2 = (ForStatement) x.getParent();
s2.initializers().remove(x);
}
});
}
public void testFieldDeclaration() {
VariableDeclarationFragment x1 = ast.newVariableDeclarationFragment();
long previousCount = ast.modificationCount();
final FieldDeclaration x = ast.newFieldDeclaration(x1);
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getJavadoc() == null);
if (ast.apiLevel() == AST.JLS2) {
assertTrue(x.getModifiers() == Modifier.NONE);
} else {
assertTrue(x.modifiers().size() == 0);
}
assertTrue(x.getType() != null);
assertTrue(x.getType().getParent() == x);
assertTrue(x.fragments().size() == 1);
assertTrue(x.fragments().get(0) == x1);
assertTrue(x1.getParent() == x);
assertTrue(x.getNodeType() == ASTNode.FIELD_DECLARATION);
assertTrue(x.structuralPropertiesForType() ==
FieldDeclaration.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
if (ast.apiLevel() == AST.JLS2) {
int legal = Modifier.PUBLIC | Modifier.PROTECTED
| Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL
| Modifier.TRANSIENT | Modifier.VOLATILE;
previousCount = ast.modificationCount();
x.setModifiers(legal);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getModifiers() == legal);
previousCount = ast.modificationCount();
x.setModifiers(Modifier.NONE);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getModifiers() == Modifier.NONE);
}
tJavadocComment(x);
tModifiers(x);
genericPropertyTest(x, new Property("Type", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result = targetAst.newSimpleType(
targetAst.newSimpleName("foo")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode get() {
return x.getType();
}
public void set(ASTNode value) {
x.setType((Type) value);
}
});
genericPropertyListTest(x, x.fragments(),
new Property("VariableSpecifiers", true, VariableDeclarationFragment.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
VariableDeclarationFragment result = targetAst.newVariableDeclarationFragment();
if (parented) {
targetAst.newVariableDeclarationStatement(result);
}
return result;
}
public ASTNode wrap() {
// return VariableDeclarationFragment that embeds x
VariableDeclarationFragment s1 = ast.newVariableDeclarationFragment();
ClassInstanceCreation s2 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s2.setAnonymousClassDeclaration(a1);
s1.setInitializer(s2);
a1.bodyDeclarations().add(x);
return s1;
}
public void unwrap() {
AnonymousClassDeclaration a1 = (AnonymousClassDeclaration) x.getParent();
a1.bodyDeclarations().remove(x);
}
});
}
public void testAssignment() {
long previousCount = ast.modificationCount();
final Assignment x = ast.newAssignment();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getOperator() == Assignment.Operator.ASSIGN);
assertTrue(x.getLeftHandSide().getParent() == x);
assertTrue(x.getRightHandSide().getParent() == x);
assertTrue(x.getNodeType() == ASTNode.ASSIGNMENT);
assertTrue(x.structuralPropertiesForType() ==
Assignment.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
previousCount = ast.modificationCount();
x.setOperator(Assignment.Operator.PLUS_ASSIGN);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getOperator() == Assignment.Operator.PLUS_ASSIGN);
assertTrue(Assignment.Operator.PLUS_ASSIGN
!= Assignment.Operator.ASSIGN);
// check the names of the primitive type codes
assertTrue(Assignment.Operator.ASSIGN.toString().equals("=")); //$NON-NLS-1$
assertTrue(Assignment.Operator.PLUS_ASSIGN.toString().equals("+=")); //$NON-NLS-1$
assertTrue(Assignment.Operator.MINUS_ASSIGN.toString().equals("-=")); //$NON-NLS-1$
assertTrue(Assignment.Operator.TIMES_ASSIGN.toString().equals("*=")); //$NON-NLS-1$
assertTrue(Assignment.Operator.DIVIDE_ASSIGN.toString().equals("/=")); //$NON-NLS-1$
assertTrue(Assignment.Operator.REMAINDER_ASSIGN.toString().equals("%=")); //$NON-NLS-1$
assertTrue(Assignment.Operator.LEFT_SHIFT_ASSIGN.toString().equals("<<=")); //$NON-NLS-1$
assertTrue(Assignment.Operator.RIGHT_SHIFT_SIGNED_ASSIGN.toString().equals(">>=")); //$NON-NLS-1$
assertTrue(Assignment.Operator.RIGHT_SHIFT_UNSIGNED_ASSIGN.toString().equals(">>>=")); //$NON-NLS-1$
assertTrue(Assignment.Operator.BIT_AND_ASSIGN.toString().equals("&=")); //$NON-NLS-1$
assertTrue(Assignment.Operator.BIT_OR_ASSIGN.toString().equals("|=")); //$NON-NLS-1$
assertTrue(Assignment.Operator.BIT_XOR_ASSIGN.toString().equals("^=")); //$NON-NLS-1$
Assignment.Operator[] known = {
Assignment.Operator.ASSIGN,
Assignment.Operator.PLUS_ASSIGN,
Assignment.Operator.MINUS_ASSIGN,
Assignment.Operator.TIMES_ASSIGN,
Assignment.Operator.DIVIDE_ASSIGN,
Assignment.Operator.REMAINDER_ASSIGN,
Assignment.Operator.LEFT_SHIFT_ASSIGN,
Assignment.Operator.RIGHT_SHIFT_SIGNED_ASSIGN,
Assignment.Operator.RIGHT_SHIFT_UNSIGNED_ASSIGN,
Assignment.Operator.BIT_AND_ASSIGN,
Assignment.Operator.BIT_OR_ASSIGN,
Assignment.Operator.BIT_XOR_ASSIGN,
};
// check all operators are distinct
for (int i = 0; i < known.length; i++) {
for (int j = 0; j < known.length; j++) {
assertTrue(i == j || !known[i].equals(known[j]));
}
}
// check all operators work
for (int i = 0; i < known.length; i++) {
previousCount = ast.modificationCount();
x.setOperator(known[i]);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getOperator().equals(known[i]));
}
// ensure null does not work as a primitive type code
try {
x.setOperator(null);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
// check toOperator lookup of operators by name
for (int i = 0; i < known.length; i++) {
String name = known[i].toString();
assertTrue(Assignment.Operator.toOperator(name).equals(known[i]));
}
assertTrue(Assignment.Operator.toOperator("not-an-op") == null); //$NON-NLS-1$
genericPropertyTest(x, new Property("LeftHandSide", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("x")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getLeftHandSide();
}
public void set(ASTNode value) {
x.setLeftHandSide((Expression) value);
}
});
genericPropertyTest(x, new Property("RightHandSide", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("x")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getRightHandSide();
}
public void set(ASTNode value) {
x.setRightHandSide((Expression) value);
}
});
}
/**
* @deprecated (Uses getLeadingComment() which is deprecated)
*/
public void testBreakStatement() {
long previousCount = ast.modificationCount();
final BreakStatement x = ast.newBreakStatement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getLabel() == null);
assertTrue(x.getLeadingComment() == null);
assertTrue(x.getNodeType() == ASTNode.BREAK_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
BreakStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
genericPropertyTest(x, new Property("Label", false, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getLabel();
}
public void set(ASTNode value) {
x.setLabel((SimpleName) value);
}
});
}
/**
* @deprecated (Uses getLeadingComment() which is deprecated)
*/
public void testContinueStatement() {
long previousCount = ast.modificationCount();
final ContinueStatement x = ast.newContinueStatement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getLabel() == null);
assertTrue(x.getLeadingComment() == null);
assertTrue(x.getNodeType() == ASTNode.CONTINUE_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
ContinueStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
genericPropertyTest(x, new Property("Label", false, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getLabel();
}
public void set(ASTNode value) {
x.setLabel((SimpleName) value);
}
});
}
/**
* @deprecated (Uses getLeadingComment() which is deprecated)
*/
public void testIfStatement() {
long previousCount = ast.modificationCount();
final IfStatement x = ast.newIfStatement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getLeadingComment() == null);
assertTrue(x.getExpression().getParent() == x);
assertTrue(x.getThenStatement().getParent() == x);
assertTrue(x.getThenStatement() instanceof Block);
assertTrue(((Block) x.getThenStatement()).statements().isEmpty());
assertTrue(x.getElseStatement() == null);
assertTrue(x.getNodeType() == ASTNode.IF_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
IfStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
genericPropertyTest(x, new Property("Expression", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
genericPropertyTest(x, new Property("ThenStatement", true, Statement.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Block result = targetAst.newBlock();
if (parented) {
Block b2 = targetAst.newBlock();
b2.statements().add(result);
}
return result;
}
public ASTNode wrap() {
// return a Statement that embeds x
Block s1 = ast.newBlock();
s1.statements().add(x);
return s1;
}
public void unwrap() {
Block s2 = (Block) x.getParent();
s2.statements().remove(x);
}
public ASTNode get() {
return x.getThenStatement();
}
public void set(ASTNode value) {
x.setThenStatement((Statement) value);
}
});
genericPropertyTest(x, new Property("ElseStatement", false, Statement.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Block result = targetAst.newBlock();
if (parented) {
Block b2 = targetAst.newBlock();
b2.statements().add(result);
}
return result;
}
public ASTNode wrap() {
// return a Statement that embeds x
Block s1 = ast.newBlock();
s1.statements().add(x);
return s1;
}
public void unwrap() {
Block s2 = (Block) x.getParent();
s2.statements().remove(x);
}
public ASTNode get() {
return x.getElseStatement();
}
public void set(ASTNode value) {
x.setElseStatement((Statement) value);
}
});
}
/**
* @deprecated (Uses getLeadingComment() which is deprecated)
*/
public void testWhileStatement() {
long previousCount = ast.modificationCount();
final WhileStatement x = ast.newWhileStatement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getLeadingComment() == null);
assertTrue(x.getExpression().getParent() == x);
assertTrue(x.getBody().getParent() == x);
assertTrue(x.getBody() instanceof Block);
assertTrue(((Block) x.getBody()).statements().isEmpty());
assertTrue(x.getNodeType() == ASTNode.WHILE_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
WhileStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
genericPropertyTest(x, new Property("Expression", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
genericPropertyTest(x, new Property("Body", true, Statement.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Block result = targetAst.newBlock();
if (parented) {
Block b2 = targetAst.newBlock();
b2.statements().add(result);
}
return result;
}
public ASTNode wrap() {
// return a Statement that embeds x
Block s1 = ast.newBlock();
s1.statements().add(x);
return s1;
}
public void unwrap() {
Block s2 = (Block) x.getParent();
s2.statements().remove(x);
}
public ASTNode get() {
return x.getBody();
}
public void set(ASTNode value) {
x.setBody((Statement) value);
}
});
}
/**
* @deprecated (Uses getLeadingComment() which is deprecated)
*/
public void testDoStatement() {
long previousCount = ast.modificationCount();
final DoStatement x = ast.newDoStatement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getLeadingComment() == null);
assertTrue(x.getExpression().getParent() == x);
assertTrue(x.getBody().getParent() == x);
assertTrue(x.getBody() instanceof Block);
assertTrue(((Block) x.getBody()).statements().isEmpty());
assertTrue(x.getNodeType() == ASTNode.DO_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
DoStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
genericPropertyTest(x, new Property("Expression", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
genericPropertyTest(x, new Property("Body", true, Statement.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Block result = targetAst.newBlock();
if (parented) {
Block b2 = targetAst.newBlock();
b2.statements().add(result);
}
return result;
}
public ASTNode wrap() {
// return a Statement that embeds x
Block s1 = ast.newBlock();
s1.statements().add(x);
return s1;
}
public void unwrap() {
Block s2 = (Block) x.getParent();
s2.statements().remove(x);
}
public ASTNode get() {
return x.getBody();
}
public void set(ASTNode value) {
x.setBody((Statement) value);
}
});
}
/**
* @deprecated (Uses getLeadingComment() which is deprecated)
*/
public void testTryStatement() {
long previousCount = ast.modificationCount();
final TryStatement x = ast.newTryStatement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getLeadingComment() == null);
assertTrue(x.getBody().getParent() == x);
assertTrue((x.getBody()).statements().isEmpty());
assertTrue(x.getFinally() == null);
assertTrue(x.catchClauses().size() == 0);
assertTrue(x.getNodeType() == ASTNode.TRY_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
TryStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
genericPropertyTest(x, new Property("Body", true, Block.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Block result = targetAst.newBlock();
if (parented) {
Block b2 = targetAst.newBlock();
b2.statements().add(result);
}
return result;
}
public ASTNode wrap() {
// return a Block that embeds x
Block s1 = ast.newBlock();
s1.statements().add(x);
return s1;
}
public void unwrap() {
Block s2 = (Block) x.getParent();
s2.statements().remove(x);
}
public ASTNode get() {
return x.getBody();
}
public void set(ASTNode value) {
x.setBody((Block) value);
}
});
genericPropertyListTest(x, x.catchClauses(),
new Property("CatchClauses", true, CatchClause.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
CatchClause result = targetAst.newCatchClause();
if (parented) {
TryStatement s1 = targetAst.newTryStatement();
s1.catchClauses().add(result);
}
return result;
}
public ASTNode wrap() {
// return CatchClause that embeds x
CatchClause s1 = ast.newCatchClause();
Block s2 = ast.newBlock();
s1.setBody(s2);
s2.statements().add(x);
return s1;
}
public void unwrap() {
Block s2 = (Block) x.getParent();
s2.statements().remove(x);
}
});
genericPropertyTest(x, new Property("Finally", false, Block.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Block result = targetAst.newBlock();
if (parented) {
Block b2 = targetAst.newBlock();
b2.statements().add(result);
}
return result;
}
public ASTNode wrap() {
// return a Block that embeds x
Block s1 = ast.newBlock();
s1.statements().add(x);
return s1;
}
public void unwrap() {
Block s2 = (Block) x.getParent();
s2.statements().remove(x);
}
public ASTNode get() {
return x.getFinally();
}
public void set(ASTNode value) {
x.setFinally((Block) value);
}
});
}
public void testCatchClause() {
long previousCount = ast.modificationCount();
final CatchClause x = ast.newCatchClause();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getBody().getParent() == x);
assertTrue(x.getBody().statements().isEmpty());
assertTrue(x.getException().getParent() == x);
assertTrue(x.getNodeType() == ASTNode.CATCH_CLAUSE);
assertTrue(x.structuralPropertiesForType() ==
CatchClause.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Exception", true, SingleVariableDeclaration.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SingleVariableDeclaration result = targetAst.newSingleVariableDeclaration();
if (parented) {
targetAst.newCatchClause().setException(result);
}
return result;
}
public ASTNode wrap() {
// return SingleVariableDeclaration that embeds x
SingleVariableDeclaration s1 = ast.newSingleVariableDeclaration();
ClassInstanceCreation s2 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s2.setAnonymousClassDeclaration(a1);
s1.setInitializer(s2);
MethodDeclaration s3 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s3);
Block s4 = ast.newBlock();
s3.setBody(s4);
TryStatement s5 = ast.newTryStatement();
s4.statements().add(s5);
s5.catchClauses().add(x);
return s1;
}
public void unwrap() {
TryStatement s5 = (TryStatement) x.getParent();
s5.catchClauses().remove(x);
}
public ASTNode get() {
return x.getException();
}
public void set(ASTNode value) {
x.setException((SingleVariableDeclaration) value);
}
});
genericPropertyTest(x, new Property("Body", true, Block.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Block result = targetAst.newBlock();
if (parented) {
Block b2 = targetAst.newBlock();
b2.statements().add(result);
}
return result;
}
public ASTNode wrap() {
// return a Block that embeds x
Block s1 = ast.newBlock();
TryStatement s2 = ast.newTryStatement();
s1.statements().add(s2);
s2.catchClauses().add(x);
return s1;
}
public void unwrap() {
TryStatement s2 = (TryStatement) x.getParent();
s2.catchClauses().remove(x);
}
public ASTNode get() {
return x.getBody();
}
public void set(ASTNode value) {
x.setBody((Block) value);
}
});
}
/**
* @deprecated (Uses getLeadingComment() which is deprecated)
*/
public void testEmptyStatement() {
long previousCount = ast.modificationCount();
final EmptyStatement x = ast.newEmptyStatement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getLeadingComment() == null);
assertTrue(x.getNodeType() == ASTNode.EMPTY_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
EmptyStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
}
/**
* Exercise the leadingComment property.
*
* @param x the statement to test
* @deprecated (Uses get/setLeadingComment() which is deprecated)
*/
void tLeadingComment(Statement x) {
// check that null is allowed
long previousCount = ast.modificationCount();
x.setLeadingComment(null);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getLeadingComment() == null);
// check that regular comment is allowed
previousCount = ast.modificationCount();
x.setLeadingComment("/* X */"); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getLeadingComment() == "/* X */"); //$NON-NLS-1$
// check that regular comment with line breaks is allowed
previousCount = ast.modificationCount();
x.setLeadingComment("/* X\n *Y\n */"); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getLeadingComment() == "/* X\n *Y\n */"); //$NON-NLS-1$
// check that end-of-line comment is allowed
previousCount = ast.modificationCount();
x.setLeadingComment("// X\n"); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getLeadingComment() == "// X\n"); //$NON-NLS-1$
// check that end-of-line comment without a line break at the end is allowed
previousCount = ast.modificationCount();
x.setLeadingComment("// X"); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getLeadingComment() == "// X"); //$NON-NLS-1$
// check that end-of-line comment with embedded end of line
// not allowed
try {
x.setLeadingComment("// X\n extra"); //$NON-NLS-1$
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
}
/**
* Exercise the javadoc property.
*
* @param x the body declaration to test
*/
void tJavadocComment(final BodyDeclaration x) {
genericPropertyTest(x, new Property("Javadoc", false, Javadoc.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Javadoc result = targetAst.newJavadoc();
if (parented) {
targetAst.newInitializer().setJavadoc(result);
}
return result;
}
public ASTNode get() {
return x.getJavadoc();
}
public void set(ASTNode value) {
x.setJavadoc((Javadoc) value);
}
});
}
/**
* Returns a list of all the different Modifier nodes.
*/
Modifier[] allModifiers() {
Modifier[] allMods = {
ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD),
ast.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD),
ast.newModifier(Modifier.ModifierKeyword.PROTECTED_KEYWORD),
ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD),
ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD),
ast.newModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD),
ast.newModifier(Modifier.ModifierKeyword.NATIVE_KEYWORD),
ast.newModifier(Modifier.ModifierKeyword.SYNCHRONIZED_KEYWORD),
ast.newModifier(Modifier.ModifierKeyword.TRANSIENT_KEYWORD),
ast.newModifier(Modifier.ModifierKeyword.VOLATILE_KEYWORD),
ast.newModifier(Modifier.ModifierKeyword.STRICTFP_KEYWORD)
};
return allMods;
}
/**
* Exercise the modifiers property.
*
* @param x the body declaration to test
*/
void tModifiers(final BodyDeclaration x) {
if (ast.apiLevel() == AST.JLS2) {
return;
}
genericPropertyListTest(x, x.modifiers(), new Property("Modifiers", true, IExtendedModifier.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Modifier result = targetAst.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
if (parented) {
TypeDeclaration pd = targetAst.newTypeDeclaration();
pd.modifiers().add(result);
}
return result;
}
public ASTNode wrap() {
SingleMemberAnnotation s1 = x.getAST().newSingleMemberAnnotation();
ClassInstanceCreation s2 = x.getAST().newClassInstanceCreation();
AnonymousClassDeclaration s3 = x.getAST().newAnonymousClassDeclaration();
MethodDeclaration s4 = x.getAST().newMethodDeclaration();
s1.setValue(s2);
s2.setAnonymousClassDeclaration(s3);
s3.bodyDeclarations().add(s4);
s4.modifiers().add(x);
return s1;
}
public void unwrap() {
MethodDeclaration s4 = (MethodDeclaration) x.getParent();
s4.modifiers().remove(x);
}
});
// check that getModifiers() tracks changes to modifiers()
x.modifiers().clear();
assertTrue(x.getModifiers() == Modifier.NONE);
Modifier[] allMods = allModifiers();
// one at a time
for (int i = 0 ; i < allMods.length; i++) {
x.modifiers().add(allMods[i]);
assertTrue(x.getModifiers() == allMods[i].getKeyword().toFlagValue());
x.modifiers().remove(allMods[i]);
assertTrue(x.getModifiers() == Modifier.NONE);
}
// all at same time
for (int i = 0 ; i < allMods.length; i++) {
x.modifiers().add(allMods[i]);
}
int flags = x.getModifiers();
for (int i = 0 ; i < allMods.length; i++) {
assertTrue((flags & allMods[i].getKeyword().toFlagValue()) != 0);
}
}
/**
* Exercise the alternateRoot property of a Comment.
*
* @param x the comment to test
* @since 3.0
*/
void tAlternateRoot(final Comment x) {
CompilationUnit cu = ast.newCompilationUnit();
long previousCount = ast.modificationCount();
x.setAlternateRoot(cu);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getAlternateRoot() == cu);
previousCount = ast.modificationCount();
x.setAlternateRoot(null);
assertTrue(x.getAlternateRoot() == null);
assertTrue(ast.modificationCount() > previousCount);
}
/**
* Exercise the client properties of a node.
*
* @param x the node to test
*/
void tClientProperties(ASTNode x) {
long previousCount = ast.modificationCount();
// a node initially has no properties
assertTrue(x.properties().size() == 0);
assertTrue(x.getProperty("1") == null); //$NON-NLS-1$
// clearing an unset property does not add it to list of known ones
x.setProperty("1", null); //$NON-NLS-1$
assertTrue(x.getProperty("1") == null); //$NON-NLS-1$
assertTrue(x.properties().size() == 0);
// setting an unset property does add it to the list of known ones
x.setProperty("1", "a1"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.getProperty("1") == "a1"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.properties().size() == 1);
Map.Entry[] m = (Map.Entry[]) x.properties().entrySet().toArray(new Map.Entry[1]);
assertTrue(m[0].getKey() == "1"); //$NON-NLS-1$
assertTrue(m[0].getValue() == "a1"); //$NON-NLS-1$
// setting an already set property just changes its value
x.setProperty("1", "a2"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.getProperty("1") == "a2"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.properties().size() == 1);
m = (Map.Entry[]) x.properties().entrySet().toArray(new Map.Entry[1]);
assertTrue(m[0].getKey() == "1"); //$NON-NLS-1$
assertTrue(m[0].getValue() == "a2"); //$NON-NLS-1$
// clearing a set property removes it from list of known ones
x.setProperty("1", null); //$NON-NLS-1$
assertTrue(x.getProperty("1") == null); //$NON-NLS-1$
assertTrue(x.properties().size() == 0);
// ========= test 2 and 3 properties
x.setProperty("1", "a1"); //$NON-NLS-1$ //$NON-NLS-2$
x.setProperty("2", "b1"); //$NON-NLS-1$ //$NON-NLS-2$
x.setProperty("3", "c1"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.getProperty("1") == "a1"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.getProperty("2") == "b1"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.getProperty("3") == "c1"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.properties().size() == 3);
assertTrue(x.properties().get("1") == "a1"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.properties().get("2") == "b1"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.properties().get("3") == "c1"); //$NON-NLS-1$ //$NON-NLS-2$
x.setProperty("1", "a2"); //$NON-NLS-1$ //$NON-NLS-2$
x.setProperty("2", "b2"); //$NON-NLS-1$ //$NON-NLS-2$
x.setProperty("3", "c2"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.getProperty("1") == "a2"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.getProperty("2") == "b2"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.getProperty("3") == "c2"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.properties().size() == 3);
assertTrue(x.properties().get("1") == "a2"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.properties().get("2") == "b2"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.properties().get("3") == "c2"); //$NON-NLS-1$ //$NON-NLS-2$
x.setProperty("2", null); //$NON-NLS-1$
assertTrue(x.getProperty("1") == "a2"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.getProperty("2") == null); //$NON-NLS-1$
assertTrue(x.getProperty("3") == "c2"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.properties().size() == 2);
assertTrue(x.properties().get("1") == "a2"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.properties().get("2") == null); //$NON-NLS-1$
assertTrue(x.properties().get("3") == "c2"); //$NON-NLS-1$ //$NON-NLS-2$
x.setProperty("1", null); //$NON-NLS-1$
assertTrue(x.getProperty("1") == null); //$NON-NLS-1$
assertTrue(x.getProperty("2") == null); //$NON-NLS-1$
assertTrue(x.getProperty("3") == "c2"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue(x.properties().size() == 1);
assertTrue(x.properties().get("1") == null); //$NON-NLS-1$
assertTrue(x.properties().get("2") == null); //$NON-NLS-1$
assertTrue(x.properties().get("3") == "c2"); //$NON-NLS-1$ //$NON-NLS-2$
// none of this is considered to have affected the AST
assertTrue(ast.modificationCount() == previousCount);
}
public void testReturnStatement() {
long previousCount = ast.modificationCount();
final ReturnStatement x = ast.newReturnStatement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getExpression() == null);
assertTrue(x.getNodeType() == ASTNode.RETURN_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
ReturnStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
genericPropertyTest(x, new Property("Expression", false, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
}
/**
* @deprecated (Uses getLeadingComment() which is deprecated)
*/
public void testThrowStatement() {
long previousCount = ast.modificationCount();
final ThrowStatement x = ast.newThrowStatement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getExpression().getParent() == x);
assertTrue(x.getLeadingComment() == null);
assertTrue(x.getNodeType() == ASTNode.THROW_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
ThrowStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
genericPropertyTest(x, new Property("Expression", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
}
/**
* @deprecated (Uses getLeadingComment() which is deprecated)
*/
public void testAssertStatement() {
long previousCount = ast.modificationCount();
final AssertStatement x = ast.newAssertStatement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getExpression().getParent() == x);
assertTrue(x.getMessage() == null);
assertTrue(x.getLeadingComment() == null);
assertTrue(x.getNodeType() == ASTNode.ASSERT_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
AssertStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
genericPropertyTest(x, new Property("Expression", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
genericPropertyTest(x, new Property("Message", false, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
public ASTNode get() {
return x.getMessage();
}
public void set(ASTNode value) {
x.setMessage((Expression) value);
}
});
}
/**
* @deprecated (Uses getLeadingComment() which is deprecated)
*/
public void testSwitchStatement() {
long previousCount = ast.modificationCount();
final SwitchStatement x = ast.newSwitchStatement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getExpression().getParent() == x);
assertTrue(x.statements().isEmpty());
assertTrue(x.getLeadingComment() == null);
assertTrue(x.getNodeType() == ASTNode.SWITCH_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
SwitchStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
genericPropertyTest(x, new Property("Expression", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
genericPropertyListTest(x, x.statements(),
new Property("Statements", true, Statement.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Block result = targetAst.newBlock();
if (parented) {
Block b2 = targetAst.newBlock();
b2.statements().add(result);
}
return result;
}
public ASTNode wrap() {
// return a Statement that embeds x
Block s1 = ast.newBlock();
s1.statements().add(x);
return s1;
}
public void unwrap() {
Block s2 = (Block) x.getParent();
s2.statements().remove(x);
}
});
}
/**
* @deprecated (Uses getLeadingComment() which is deprecated)
*/
public void testSwitchCase() {
long previousCount = ast.modificationCount();
final SwitchCase x = ast.newSwitchCase();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getExpression().getParent() == x);
assertTrue(x.getLeadingComment() == null);
assertTrue(!x.isDefault());
assertTrue(x.getNodeType() == ASTNode.SWITCH_CASE);
assertTrue(x.structuralPropertiesForType() ==
SwitchCase.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Expression", false, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
SwitchStatement s4 = ast.newSwitchStatement();
s3.statements().add(s4);
s4.statements().add(x);
return s1;
}
public void unwrap() {
SwitchStatement s4 = (SwitchStatement) x.getParent();
s4.statements().remove(x);
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
}
/**
* @deprecated (Uses getLeadingComment() which is deprecated)
*/
public void testSynchronizedStatement() {
long previousCount = ast.modificationCount();
final SynchronizedStatement x = ast.newSynchronizedStatement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getExpression().getParent() == x);
assertTrue(x.getBody().statements().isEmpty());
assertTrue(x.getLeadingComment() == null);
assertTrue(x.getNodeType() == ASTNode.SYNCHRONIZED_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
SynchronizedStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
genericPropertyTest(x, new Property("Expression", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
genericPropertyTest(x, new Property("Body", true, Block.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Block result = targetAst.newBlock();
if (parented) {
Block b2 = targetAst.newBlock();
b2.statements().add(result);
}
return result;
}
public ASTNode wrap() {
// return a Block that embeds x
Block s1 = ast.newBlock();
s1.statements().add(x);
return s1;
}
public void unwrap() {
Block s2 = (Block) x.getParent();
s2.statements().remove(x);
}
public ASTNode get() {
return x.getBody();
}
public void set(ASTNode value) {
x.setBody((Block) value);
}
});
}
/**
* @deprecated (Uses getLeadingComment() which is deprecated)
*/
public void testLabeledStatement() {
long previousCount = ast.modificationCount();
final LabeledStatement x = ast.newLabeledStatement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getLabel().getParent() == x);
assertTrue(x.getBody().getParent() == x);
assertTrue(x.getLeadingComment() == null);
assertTrue(x.getNodeType() == ASTNode.LABELED_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
LabeledStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
genericPropertyTest(x, new Property("Label", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getLabel();
}
public void set(ASTNode value) {
x.setLabel((SimpleName) value);
}
});
genericPropertyTest(x, new Property("Body", true, Statement.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Block result = targetAst.newBlock();
if (parented) {
Block b2 = targetAst.newBlock();
b2.statements().add(result);
}
return result;
}
public ASTNode wrap() {
// return a Statement that embeds x
Block s1 = ast.newBlock();
s1.statements().add(x);
return s1;
}
public void unwrap() {
Block s2 = (Block) x.getParent();
s2.statements().remove(x);
}
public ASTNode get() {
return x.getBody();
}
public void set(ASTNode value) {
x.setBody((Statement) value);
}
});
}
/**
* Walks the given AST and assigns properly-nested (but otherwise totally bogus)
* source ranges to all nodes.
*/
void assignSourceRanges(ASTNode target) {
final StringBuffer buffer = new StringBuffer();
final List stack = new ArrayList();
// pretend that every construct begins with "(" and ends with ")"
class PositionAssigner extends ASTVisitor {
PositionAssigner() {
// visit Javadoc.tags();
super(true);
}
public void preVisit(ASTNode node) {
int start = buffer.length();
buffer.append("(");
// push start position - popped by postVisit for same node
stack.add(new Integer(start));
}
public void postVisit(ASTNode node) {
// pop start position placed there by preVisit
int start = ((Integer) stack.remove(stack.size() - 1)).intValue();
buffer.append(")");
int length = buffer.length() - start;
node.setSourceRange(start, length);
}
}
target.accept(new PositionAssigner());
}
public void testClone() {
ASTNode x = SampleASTs.oneOfEach(ast);
assignSourceRanges(x);
assertTrue(x.subtreeMatch(new CheckPositionsMatcher(), x));
// same AST clone
ASTNode y = ASTNode.copySubtree(ast, x);
assertTrue(x.subtreeMatch(new CheckPositionsMatcher(), y));
assertTrue(y.subtreeMatch(new CheckPositionsMatcher(), x));
// different AST clone
AST newAST = AST.newAST(ast.apiLevel());
ASTNode z = ASTNode.copySubtree(newAST, x);
assertTrue(x.subtreeMatch(new CheckPositionsMatcher(), z));
assertTrue(z.subtreeMatch(new CheckPositionsMatcher(), x));
}
public void testNullResolve() {
ASTNode x = SampleASTs.oneOfEach(ast);
ASTVisitor v = new ASTVisitor(true) {
// NAMES
public boolean visit(SimpleName node) {
assertTrue(node.resolveBinding() == null);
return true;
}
public boolean visit(QualifiedName node) {
assertTrue(node.resolveBinding() == null);
return true;
}
// TYPES
public boolean visit(SimpleType node) {
assertTrue(node.resolveBinding() == null);
return true;
}
public boolean visit(ArrayType node) {
assertTrue(node.resolveBinding() == null);
return true;
}
public boolean visit(ParameterizedType node) {
assertTrue(node.resolveBinding() == null);
return true;
}
public boolean visit(PrimitiveType node) {
assertTrue(node.resolveBinding() == null);
return true;
}
public boolean visit(QualifiedType node) {
assertTrue(node.resolveBinding() == null);
return true;
}
public boolean visit(WildcardType node) {
assertTrue(node.resolveBinding() == null);
return true;
}
// EXPRESSIONS
public boolean visit(Assignment node) {
assertTrue(node.resolveTypeBinding() == null);
return true;
}
public boolean visit(ClassInstanceCreation node) {
assertTrue(node.resolveConstructorBinding() == null);
return true;
}
public boolean visit(ConstructorInvocation node) {
assertTrue(node.resolveConstructorBinding() == null);
return true;
}
public boolean visit(SuperConstructorInvocation node) {
assertTrue(node.resolveConstructorBinding() == null);
return true;
}
// MAJOR DECLARATIONS
public boolean visit(PackageDeclaration node) {
assertTrue(node.resolveBinding() == null);
return true;
}
public boolean visit(ImportDeclaration node) {
assertTrue(node.resolveBinding() == null);
return true;
}
public boolean visit(MethodDeclaration node) {
assertTrue(node.resolveBinding() == null);
return true;
}
public boolean visit(TypeDeclaration node) {
assertTrue(node.resolveBinding() == null);
return true;
}
public boolean visit(TypeDeclarationStatement node) {
assertTrue(node.resolveBinding() == null);
return true;
}
public boolean visit(SingleVariableDeclaration node) {
assertTrue(node.resolveBinding() == null);
return true;
}
public boolean visit(VariableDeclarationFragment node) {
assertTrue(node.resolveBinding() == null);
return true;
}
public boolean visit(EnumConstantDeclaration node) {
assertTrue(node.resolveVariable() == null);
return true;
}
};
x.accept(v);
}
/**
* @deprecated (Uses getLeadingComment() which is deprecated)
*/
public void testForStatement() {
long previousCount = ast.modificationCount();
final ForStatement x = ast.newForStatement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.initializers().isEmpty());
assertTrue(x.getExpression() == null);
assertTrue(x.updaters().isEmpty());
assertTrue(x.getBody().getParent() == x);
assertTrue(x.getBody() instanceof Block);
assertTrue(((Block) x.getBody()).statements().isEmpty());
assertTrue(x.getLeadingComment() == null);
assertTrue(x.getNodeType() == ASTNode.FOR_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
ForStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
genericPropertyListTest(x, x.initializers(),
new Property("Initializers", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
});
genericPropertyTest(x, new Property("Expression", false, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
genericPropertyListTest(x, x.updaters(),
new Property("Updaters", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
});
genericPropertyTest(x, new Property("Body", true, Statement.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Block result = targetAst.newBlock();
if (parented) {
Block b2 = targetAst.newBlock();
b2.statements().add(result);
}
return result;
}
public ASTNode wrap() {
// return a Statement that embeds x
Block s1 = ast.newBlock();
s1.statements().add(x);
return s1;
}
public void unwrap() {
Block s2 = (Block) x.getParent();
s2.statements().remove(x);
}
public ASTNode get() {
return x.getBody();
}
public void set(ASTNode value) {
x.setBody((Statement) value);
}
});
}
/**
* @deprecated (Uses getLeadingComment() which is deprecated)
*/
public void testEnhancedForStatement() {
if (ast.apiLevel() == AST.JLS2) {
// node type introduced in 3.0 API
try {
ast.newEnhancedForStatement();
assertTrue(false);
} catch (UnsupportedOperationException e) {
// pass
}
return;
}
long previousCount = ast.modificationCount();
final EnhancedForStatement x = ast.newEnhancedForStatement();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getParameter() != null);
assertTrue(x.getParameter().getParent() == x);
assertTrue(x.getExpression() != null);
assertTrue(x.getExpression().getParent() == x);
assertTrue(x.getBody().getParent() == x);
assertTrue(x.getBody() instanceof Block);
assertTrue(((Block) x.getBody()).statements().isEmpty());
assertTrue(x.getLeadingComment() == null);
assertTrue(x.getNodeType() == ASTNode.ENHANCED_FOR_STATEMENT);
assertTrue(x.structuralPropertiesForType() ==
EnhancedForStatement.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tLeadingComment(x);
genericPropertyTest(x, new Property("Parameter", true, SingleVariableDeclaration.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SingleVariableDeclaration result = targetAst.newSingleVariableDeclaration();
if (parented) {
CatchClause parent = targetAst.newCatchClause();
parent.setException(result);
}
return result;
}
public ASTNode get() {
return x.getParameter();
}
public void set(ASTNode value) {
x.setParameter((SingleVariableDeclaration) value);
}
});
genericPropertyTest(x, new Property("Expression", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST target, boolean parented) {
Expression result = target.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
target.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
}
public void testConstructorInvocation() {
long previousCount = ast.modificationCount();
final ConstructorInvocation x = ast.newConstructorInvocation();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
if (ast.apiLevel() >= AST.JLS3) {
assertTrue(x.typeArguments().isEmpty());
}
assertTrue(x.arguments().isEmpty());
assertTrue(x.getNodeType() == ASTNode.CONSTRUCTOR_INVOCATION);
assertTrue(x.structuralPropertiesForType() ==
ConstructorInvocation.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
if (ast.apiLevel() >= AST.JLS3) {
genericPropertyListTest(x, x.typeArguments(),
new Property("TypeArguments", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Type result = targetAst.newSimpleType(targetAst.newSimpleName("X")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
});
}
genericPropertyListTest(x, x.arguments(),
new Property("Arguments", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
});
}
public void testSuperConstructorInvocation() {
long previousCount = ast.modificationCount();
final SuperConstructorInvocation x = ast.newSuperConstructorInvocation();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getExpression() == null);
if (ast.apiLevel() >= AST.JLS3) {
assertTrue(x.typeArguments().isEmpty());
}
assertTrue(x.arguments().isEmpty());
assertTrue(x.getNodeType() == ASTNode.SUPER_CONSTRUCTOR_INVOCATION);
assertTrue(x.structuralPropertiesForType() ==
SuperConstructorInvocation.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Expression", false, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
if (ast.apiLevel() >= AST.JLS3) {
genericPropertyListTest(x, x.typeArguments(),
new Property("TypeArguments", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Type result = targetAst.newSimpleType(targetAst.newSimpleName("X")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
});
}
genericPropertyListTest(x, x.arguments(),
new Property("Arguments", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = ast.newClassInstanceCreation();
AnonymousClassDeclaration a1 = ast.newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(a1);
MethodDeclaration s2 = ast.newMethodDeclaration();
a1.bodyDeclarations().add(s2);
Block s3 = ast.newBlock();
s2.setBody(s3);
s3.statements().add(x);
return s1;
}
public void unwrap() {
Block s3 = (Block) x.getParent();
s3.statements().remove(x);
}
});
}
public void testThisExpression() {
long previousCount = ast.modificationCount();
final ThisExpression x = ast.newThisExpression();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getQualifier() == null);
assertTrue(x.getNodeType() == ASTNode.THIS_EXPRESSION);
assertTrue(x.structuralPropertiesForType() ==
ThisExpression.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Qualifier", false, Name.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
QualifiedName result = targetAst.newQualifiedName(
targetAst.newSimpleName("a"), //$NON-NLS-1$
targetAst.newSimpleName("b")); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getQualifier();
}
public void set(ASTNode value) {
x.setQualifier((Name) value);
}
});
}
public void testFieldAccess() {
long previousCount = ast.modificationCount();
final FieldAccess x = ast.newFieldAccess();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getName().getParent() == x);
assertTrue(x.getExpression().getParent() == x);
assertTrue(x.getNodeType() == ASTNode.FIELD_ACCESS);
assertTrue(x.structuralPropertiesForType() ==
FieldAccess.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Expression", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("fie")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
}
public void testSuperFieldAccess() {
long previousCount = ast.modificationCount();
final SuperFieldAccess x = ast.newSuperFieldAccess();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getName().getParent() == x);
assertTrue(x.getQualifier() == null);
assertTrue(x.getNodeType() == ASTNode.SUPER_FIELD_ACCESS);
assertTrue(x.structuralPropertiesForType() ==
SuperFieldAccess.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Qualifier", false, Name.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
QualifiedName result = targetAst.newQualifiedName(
targetAst.newSimpleName("a"), //$NON-NLS-1$
targetAst.newSimpleName("b")); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getQualifier();
}
public void set(ASTNode value) {
x.setQualifier((Name) value);
}
});
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
}
public void testSuperMethodInvocation() {
long previousCount = ast.modificationCount();
final SuperMethodInvocation x = ast.newSuperMethodInvocation();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
if (ast.apiLevel() >= AST.JLS3) {
assertTrue(x.typeArguments().isEmpty());
}
assertTrue(x.getName().getParent() == x);
assertTrue(x.getQualifier() == null);
assertTrue(x.arguments().isEmpty());
assertTrue(x.getNodeType() == ASTNode.SUPER_METHOD_INVOCATION);
assertTrue(x.structuralPropertiesForType() ==
SuperMethodInvocation.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Qualifier", false, Name.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
QualifiedName result = targetAst.newQualifiedName(
targetAst.newSimpleName("a"), //$NON-NLS-1$
targetAst.newSimpleName("b")); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getQualifier();
}
public void set(ASTNode value) {
x.setQualifier((Name) value);
}
});
if (ast.apiLevel() >= AST.JLS3) {
genericPropertyListTest(x, x.typeArguments(),
new Property("TypeArguments", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Type result = targetAst.newSimpleType(targetAst.newSimpleName("X")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
});
}
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
genericPropertyListTest(x, x.arguments(),
new Property("Arguments", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("x")); //$NON-NLS-1$
}
});
}
public void testTypeLiteral() {
long previousCount = ast.modificationCount();
final TypeLiteral x = ast.newTypeLiteral();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getType().getParent() == x);
assertTrue(x.getNodeType() == ASTNode.TYPE_LITERAL);
assertTrue(x.structuralPropertiesForType() ==
TypeLiteral.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Type", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result = targetAst.newSimpleType(
targetAst.newSimpleName("a")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode get() {
return x.getType();
}
public void set(ASTNode value) {
x.setType((Type) value);
}
});
}
public void testCastExpression() {
long previousCount = ast.modificationCount();
final CastExpression x = ast.newCastExpression();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getType().getParent() == x);
assertTrue(x.getExpression().getParent() == x);
assertTrue(x.getNodeType() == ASTNode.CAST_EXPRESSION);
assertTrue(x.structuralPropertiesForType() ==
CastExpression.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Type", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result = targetAst.newSimpleType(
targetAst.newSimpleName("a")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode get() {
return x.getType();
}
public void set(ASTNode value) {
x.setType((Type) value);
}
});
genericPropertyTest(x, new Property("Expression", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("fie")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
}
public void testPrefixExpression() {
long previousCount = ast.modificationCount();
final PrefixExpression x = ast.newPrefixExpression();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getOperand().getParent() == x);
assertTrue(x.getOperator() != null);
assertTrue(x.getNodeType() == ASTNode.PREFIX_EXPRESSION);
assertTrue(x.structuralPropertiesForType() ==
PrefixExpression.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
// Operator property - mandatory typesafe enumeration
// check the names of the operators
assertTrue(PrefixExpression.Operator.INCREMENT.toString().equals("++")); //$NON-NLS-1$
assertTrue(PrefixExpression.Operator.DECREMENT.toString().equals("--")); //$NON-NLS-1$
assertTrue(PrefixExpression.Operator.PLUS.toString().equals("+")); //$NON-NLS-1$
assertTrue(PrefixExpression.Operator.MINUS.toString().equals("-")); //$NON-NLS-1$
assertTrue(PrefixExpression.Operator.COMPLEMENT.toString().equals("~")); //$NON-NLS-1$
assertTrue(PrefixExpression.Operator.NOT.toString().equals("!")); //$NON-NLS-1$
PrefixExpression.Operator[] known = {
PrefixExpression.Operator.INCREMENT,
PrefixExpression.Operator.DECREMENT,
PrefixExpression.Operator.PLUS,
PrefixExpression.Operator.MINUS,
PrefixExpression.Operator.COMPLEMENT,
PrefixExpression.Operator.NOT,
};
// check all operators are distinct
for (int i = 0; i < known.length; i++) {
for (int j = 0; j < known.length; j++) {
assertTrue(i == j || !known[i].equals(known[j]));
}
}
// check all operators work
for (int i = 0; i < known.length; i++) {
previousCount = ast.modificationCount();
x.setOperator(known[i]);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getOperator().equals(known[i]));
}
// ensure null does not work as an operator
try {
x.setOperator(null);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
// check toOperator lookup of operator by name
for (int i = 0; i < known.length; i++) {
String name = known[i].toString();
assertTrue(PrefixExpression.Operator.toOperator(name).equals(known[i]));
}
assertTrue(PrefixExpression.Operator.toOperator("huh") == null); //$NON-NLS-1$
genericPropertyTest(x, new Property("Operand", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("fie")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getOperand();
}
public void set(ASTNode value) {
x.setOperand((Expression) value);
}
});
}
public void testPostfixExpression() {
long previousCount = ast.modificationCount();
final PostfixExpression x = ast.newPostfixExpression();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getOperand().getParent() == x);
assertTrue(x.getOperator() != null);
assertTrue(x.getNodeType() == ASTNode.POSTFIX_EXPRESSION);
assertTrue(x.structuralPropertiesForType() ==
PostfixExpression.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
// Operator property - mandatory typesafe enumeration
// check the names of the operators
assertTrue(PostfixExpression.Operator.INCREMENT.toString().equals("++")); //$NON-NLS-1$
assertTrue(PostfixExpression.Operator.DECREMENT.toString().equals("--")); //$NON-NLS-1$
PostfixExpression.Operator[] known = {
PostfixExpression.Operator.INCREMENT,
PostfixExpression.Operator.DECREMENT,
};
// check all operators are distinct
for (int i = 0; i < known.length; i++) {
for (int j = 0; j < known.length; j++) {
assertTrue(i == j || !known[i].equals(known[j]));
}
}
// check all operators work
for (int i = 0; i < known.length; i++) {
previousCount = ast.modificationCount();
x.setOperator(known[i]);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getOperator().equals(known[i]));
}
// ensure null does not work as an operator
try {
x.setOperator(null);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
// check toOperator lookup of operator by name
for (int i = 0; i < known.length; i++) {
String name = known[i].toString();
assertTrue(PostfixExpression.Operator.toOperator(name).equals(known[i]));
}
assertTrue(PostfixExpression.Operator.toOperator("huh") == null); //$NON-NLS-1$
genericPropertyTest(x, new Property("Operand", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("fie")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getOperand();
}
public void set(ASTNode value) {
x.setOperand((Expression) value);
}
});
}
public void testInfixExpression() {
long previousCount = ast.modificationCount();
final InfixExpression x = ast.newInfixExpression();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getLeftOperand().getParent() == x);
assertTrue(x.getOperator() != null);
assertTrue(x.getRightOperand().getParent() == x);
assertTrue(x.extendedOperands().isEmpty());
assertTrue(x.getNodeType() == ASTNode.INFIX_EXPRESSION);
assertTrue(x.structuralPropertiesForType() ==
InfixExpression.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
// Operator property - mandatory typesafe enumeration
// check the names of the operators
assertTrue(InfixExpression.Operator.TIMES.toString().equals("*")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.DIVIDE.toString().equals("/")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.REMAINDER.toString().equals("%")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.PLUS.toString().equals("+")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.MINUS.toString().equals("-")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.LEFT_SHIFT.toString().equals("<<")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.RIGHT_SHIFT_SIGNED.toString().equals(">>")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED.toString().equals(">>>")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.LESS.toString().equals("<")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.GREATER.toString().equals(">")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.LESS_EQUALS.toString().equals("<=")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.GREATER_EQUALS.toString().equals(">=")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.EQUALS.toString().equals("==")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.NOT_EQUALS.toString().equals("!=")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.XOR.toString().equals("^")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.OR.toString().equals("|")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.AND.toString().equals("&")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.CONDITIONAL_OR.toString().equals("||")); //$NON-NLS-1$
assertTrue(InfixExpression.Operator.CONDITIONAL_AND.toString().equals("&&")); //$NON-NLS-1$
InfixExpression.Operator[] known = {
InfixExpression.Operator.TIMES,
InfixExpression.Operator.DIVIDE,
InfixExpression.Operator.REMAINDER,
InfixExpression.Operator.PLUS,
InfixExpression.Operator.MINUS,
InfixExpression.Operator.LEFT_SHIFT,
InfixExpression.Operator.RIGHT_SHIFT_SIGNED,
InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED,
InfixExpression.Operator.LESS,
InfixExpression.Operator.GREATER,
InfixExpression.Operator.LESS_EQUALS,
InfixExpression.Operator.GREATER_EQUALS,
InfixExpression.Operator.EQUALS,
InfixExpression.Operator.NOT_EQUALS,
InfixExpression.Operator.XOR,
InfixExpression.Operator.OR,
InfixExpression.Operator.AND,
InfixExpression.Operator.CONDITIONAL_OR,
InfixExpression.Operator.CONDITIONAL_AND,
};
// check all operators are distinct
for (int i = 0; i < known.length; i++) {
for (int j = 0; j < known.length; j++) {
assertTrue(i == j || !known[i].equals(known[j]));
}
}
// check all operators work
for (int i = 0; i < known.length; i++) {
previousCount = ast.modificationCount();
x.setOperator(known[i]);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getOperator().equals(known[i]));
}
// ensure null does not work as an operator
try {
x.setOperator(null);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
// check toOperator lookup of operator by name
for (int i = 0; i < known.length; i++) {
String name = known[i].toString();
assertTrue(InfixExpression.Operator.toOperator(name).equals(known[i]));
}
assertTrue(InfixExpression.Operator.toOperator("huh") == null); //$NON-NLS-1$
genericPropertyTest(x, new Property("LeftOperand", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("fie")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getLeftOperand();
}
public void set(ASTNode value) {
x.setLeftOperand((Expression) value);
}
});
genericPropertyTest(x, new Property("RightOperand", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("fie")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getRightOperand();
}
public void set(ASTNode value) {
x.setRightOperand((Expression) value);
}
});
genericPropertyListTest(x, x.extendedOperands(),
new Property("ExtendedOperands", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("x")); //$NON-NLS-1$
}
});
}
public void testInstanceofExpression() {
long previousCount = ast.modificationCount();
final InstanceofExpression x = ast.newInstanceofExpression();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getLeftOperand().getParent() == x);
assertTrue(x.getRightOperand().getParent() == x);
assertTrue(x.getNodeType() == ASTNode.INSTANCEOF_EXPRESSION);
assertTrue(x.structuralPropertiesForType() ==
InstanceofExpression.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("LeftOperand", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("fie")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getLeftOperand();
}
public void set(ASTNode value) {
x.setLeftOperand((Expression) value);
}
});
genericPropertyTest(x, new Property("RightOperand", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Type result = localAst.newSimpleType(localAst.newSimpleName("Object")); //$NON-NLS-1$
if (parented) {
localAst.newArrayType(result);
}
return result;
}
public ASTNode wrap() {
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("fie")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getRightOperand();
}
public void set(ASTNode value) {
x.setRightOperand((Type) value);
}
});
}
public void testConditionalExpression() {
long previousCount = ast.modificationCount();
final ConditionalExpression x = ast.newConditionalExpression();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getExpression().getParent() == x);
assertTrue(x.getThenExpression().getParent() == x);
assertTrue(x.getElseExpression().getParent() == x);
assertTrue(x.getNodeType() == ASTNode.CONDITIONAL_EXPRESSION);
assertTrue(x.structuralPropertiesForType() ==
ConditionalExpression.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Expression", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("fie")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
genericPropertyTest(x, new Property("ThenExpression", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("fie")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getThenExpression();
}
public void set(ASTNode value) {
x.setThenExpression((Expression) value);
}
});
genericPropertyTest(x, new Property("ElseExpression", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("fie")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getElseExpression();
}
public void set(ASTNode value) {
x.setElseExpression((Expression) value);
}
});
}
public void testArrayAccess() {
long previousCount = ast.modificationCount();
final ArrayAccess x = ast.newArrayAccess();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getArray().getParent() == x);
assertTrue(x.getIndex().getParent() == x);
assertTrue(x.getNodeType() == ASTNode.ARRAY_ACCESS);
assertTrue(x.structuralPropertiesForType() ==
ArrayAccess.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Array", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("fie")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getArray();
}
public void set(ASTNode value) {
x.setArray((Expression) value);
}
});
genericPropertyTest(x, new Property("Index", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("fie")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getIndex();
}
public void set(ASTNode value) {
x.setIndex((Expression) value);
}
});
}
public void testArrayInitializer() {
long previousCount = ast.modificationCount();
final ArrayInitializer x = ast.newArrayInitializer();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.expressions().isEmpty());
assertTrue(x.getNodeType() == ASTNode.ARRAY_INITIALIZER);
assertTrue(x.structuralPropertiesForType() ==
ArrayInitializer.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyListTest(x, x.expressions(),
new Property("Expressions", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("x")); //$NON-NLS-1$
}
});
}
public void testClassInstanceCreation() {
long previousCount = ast.modificationCount();
final ClassInstanceCreation x = ast.newClassInstanceCreation();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getExpression() == null);
if (ast.apiLevel() == AST.JLS2) {
assertTrue(x.getName().getParent() == x);
} else {
assertTrue(x.typeArguments().isEmpty());
assertTrue(x.getType().getParent() == x);
}
assertTrue(x.arguments().isEmpty());
assertTrue(x.getAnonymousClassDeclaration() == null);
assertTrue(x.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION);
assertTrue(x.structuralPropertiesForType() ==
ClassInstanceCreation.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Expression", false, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("x")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
if (ast.apiLevel() >= AST.JLS3) {
genericPropertyListTest(x, x.typeArguments(),
new Property("TypeArguments", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
Type result = targetAst.newSimpleType(targetAst.newSimpleName("X")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
});
}
if (ast.apiLevel() == AST.JLS2) {
genericPropertyTest(x, new Property("Name", true, Name.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("a"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((Name) value);
}
});
}
if (ast.apiLevel() >= AST.JLS3) {
genericPropertyTest(x, new Property("Type", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result = targetAst.newSimpleType(targetAst.newSimpleName("foo")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode get() {
return x.getType();
}
public void set(ASTNode value) {
x.setType((Type) value);
}
});
}
genericPropertyListTest(x, x.arguments(),
new Property("Arguments", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("x")); //$NON-NLS-1$
}
});
genericPropertyTest(x, new Property("AnonymousClassDeclaration", false, AnonymousClassDeclaration.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
AnonymousClassDeclaration result = targetAst.newAnonymousClassDeclaration();
if (parented) {
targetAst.newClassInstanceCreation().setAnonymousClassDeclaration(result);
}
return result;
}
public ASTNode wrap() {
// return AnonymousClassDeclaration that embeds x
AnonymousClassDeclaration s0 = x.getAST().newAnonymousClassDeclaration();
VariableDeclarationFragment s1 = x.getAST().newVariableDeclarationFragment();
FieldDeclaration s2 = x.getAST().newFieldDeclaration(s1);
s0.bodyDeclarations().add(s2);
s1.setInitializer(x);
return s0;
}
public void unwrap() {
VariableDeclarationFragment s1 = (VariableDeclarationFragment) x.getParent();
s1.setInitializer(null);
}
public ASTNode get() {
return x.getAnonymousClassDeclaration();
}
public void set(ASTNode value) {
x.setAnonymousClassDeclaration((AnonymousClassDeclaration) value);
}
});
}
public void testAnonymousClassDeclaration() {
long previousCount = ast.modificationCount();
final AnonymousClassDeclaration x = ast.newAnonymousClassDeclaration();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.bodyDeclarations().isEmpty());
assertTrue(x.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION);
assertTrue(x.structuralPropertiesForType() ==
AnonymousClassDeclaration.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyListTest(x, x.bodyDeclarations(),
new Property("BodyDeclarations", true, BodyDeclaration.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
TypeDeclaration result = targetAst.newTypeDeclaration();
if (parented) {
CompilationUnit compilationUnit = targetAst.newCompilationUnit();
compilationUnit.types().add(result);
}
return result;
}
public ASTNode wrap() {
// return BodyDeclaration that embeds x
VariableDeclarationFragment s0 = x.getAST().newVariableDeclarationFragment();
FieldDeclaration s1 = x.getAST().newFieldDeclaration(s0);
ClassInstanceCreation s2= x.getAST().newClassInstanceCreation();
s0.setInitializer(s2);
s2.setAnonymousClassDeclaration(x);
return s1;
}
public void unwrap() {
ClassInstanceCreation s2 = (ClassInstanceCreation) x.getParent();
s2.setAnonymousClassDeclaration(null);
}
});
// check that TypeDeclarations in body are classified correctly
TypeDeclaration t1 = ast.newTypeDeclaration();
x.bodyDeclarations().add(t1);
assertTrue(t1.isLocalTypeDeclaration() == false);
assertTrue(t1.isMemberTypeDeclaration() == true);
assertTrue(t1.isPackageMemberTypeDeclaration() == false);
}
public void testArrayCreation() {
long previousCount = ast.modificationCount();
final ArrayCreation x = ast.newArrayCreation();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getType().getParent() == x);
assertTrue(x.dimensions().isEmpty());
assertTrue(x.getInitializer() == null);
assertTrue(x.getNodeType() == ASTNode.ARRAY_CREATION);
assertTrue(x.structuralPropertiesForType() ==
ArrayCreation.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Type", true, ArrayType.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
ArrayType result = targetAst.newArrayType(
targetAst.newSimpleType(targetAst.newSimpleName("a"))); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode get() {
return x.getType();
}
public void set(ASTNode value) {
x.setType((ArrayType) value);
}
});
genericPropertyListTest(x, x.dimensions(),
new Property("Dimensions", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("x")); //$NON-NLS-1$
}
});
genericPropertyTest(x, new Property("Initializer", false, ArrayInitializer.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
ArrayInitializer result = targetAst.newArrayInitializer();
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return ArrayInitializer that embeds x
ArrayInitializer s1 = ast.newArrayInitializer();
s1.expressions().add(x);
return s1;
}
public void unwrap() {
ArrayInitializer s1 = (ArrayInitializer) x.getParent();
s1.expressions().remove(x);
}
public ASTNode get() {
return x.getInitializer();
}
public void set(ASTNode value) {
x.setInitializer((ArrayInitializer) value);
}
});
}
public void testParenthesizedExpression() {
long previousCount = ast.modificationCount();
final ParenthesizedExpression x = ast.newParenthesizedExpression();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getExpression().getParent() == x);
assertTrue(x.getNodeType() == ASTNode.PARENTHESIZED_EXPRESSION);
assertTrue(x.structuralPropertiesForType() ==
ParenthesizedExpression.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Expression", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
ParenthesizedExpression s1 = ast.newParenthesizedExpression();
s1.setExpression(x);
return s1;
}
public void unwrap() {
ParenthesizedExpression s1 = (ParenthesizedExpression) x.getParent();
s1.setExpression(ast.newSimpleName("fie")); //$NON-NLS-1$
}
public ASTNode get() {
return x.getExpression();
}
public void set(ASTNode value) {
x.setExpression((Expression) value);
}
});
}
public void testAnnotationTypeDeclaration() {
if (ast.apiLevel() == AST.JLS2) {
// node type introduced in 3.0 API
try {
ast.newAnnotationTypeDeclaration();
assertTrue(false);
} catch (UnsupportedOperationException e) {
// pass
}
return;
}
long previousCount = ast.modificationCount();
final AnnotationTypeDeclaration x = ast.newAnnotationTypeDeclaration();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.modifiers().size() == 0);
assertTrue(x.getJavadoc() == null);
assertTrue(x.getName().getParent() == x);
assertTrue(x.getName().isDeclaration() == true);
assertTrue(x.bodyDeclarations().size()== 0);
assertTrue(x.getNodeType() == ASTNode.ANNOTATION_TYPE_DECLARATION);
assertTrue(x.structuralPropertiesForType() ==
AnnotationTypeDeclaration.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
previousCount = ast.modificationCount();
tJavadocComment(x);
tModifiers(x);
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
genericPropertyListTest(x, x.bodyDeclarations(),
new Property("BodyDeclarations", true, BodyDeclaration.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
AnnotationTypeMemberDeclaration result = targetAst.newAnnotationTypeMemberDeclaration();
if (parented) {
AnnotationTypeDeclaration atd = targetAst.newAnnotationTypeDeclaration();
atd.bodyDeclarations().add(result);
}
return result;
}
public ASTNode wrap() {
// return AnnotationTypeMemberDeclaration that embeds x
AnnotationTypeMemberDeclaration s1 = x.getAST().newAnnotationTypeMemberDeclaration();
ClassInstanceCreation s2 = x.getAST().newClassInstanceCreation();
AnonymousClassDeclaration s3 = x.getAST().newAnonymousClassDeclaration();
s1.setDefault(s2);
s2.setAnonymousClassDeclaration(s3);
s3.bodyDeclarations().add(x);
return s1;
}
public void unwrap() {
AnonymousClassDeclaration s3 = (AnonymousClassDeclaration) x.getParent();
s3.bodyDeclarations().remove(x);
}
});
// check that TypeDeclarations in body are classified correctly
assertTrue(x.isLocalTypeDeclaration() == false);
assertTrue(x.isMemberTypeDeclaration() == false);
assertTrue(x.isPackageMemberTypeDeclaration() == false);
// check special bodyDeclaration methods
TypeDeclaration t0 = ast.newTypeDeclaration();
AnnotationTypeDeclaration t1 = ast.newAnnotationTypeDeclaration();
t0.bodyDeclarations().add(t1);
assertTrue(t1.isLocalTypeDeclaration() == false);
assertTrue(t1.isMemberTypeDeclaration() == true);
assertTrue(t1.isPackageMemberTypeDeclaration() == false);
CompilationUnit t2 = ast.newCompilationUnit();
AnnotationTypeDeclaration t3 = ast.newAnnotationTypeDeclaration();
t2.types().add(t3);
assertTrue(t3.isLocalTypeDeclaration() == false);
assertTrue(t3.isMemberTypeDeclaration() == false);
assertTrue(t3.isPackageMemberTypeDeclaration() == true);
}
public void testAnnotationTypeMemberDeclaration() {
if (ast.apiLevel() == AST.JLS2) {
// node type introduced in 3.0 API
try {
ast.newAnnotationTypeMemberDeclaration();
assertTrue(false);
} catch (UnsupportedOperationException e) {
// pass
}
return;
}
long previousCount = ast.modificationCount();
final AnnotationTypeMemberDeclaration x = ast.newAnnotationTypeMemberDeclaration();
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.modifiers().size() == 0);
assertTrue(x.getName().getParent() == x);
assertTrue(x.getName().isDeclaration() == true);
assertTrue(x.getType().getParent() == x);
assertTrue(x.getJavadoc() == null);
assertTrue(x.getDefault() == null);
assertTrue(x.getNodeType() == ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION);
assertTrue(x.structuralPropertiesForType() ==
AnnotationTypeMemberDeclaration.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tJavadocComment(x);
tModifiers(x);
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
genericPropertyTest(x, new Property("Type", true, Type.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleType result = targetAst.newSimpleType(
targetAst.newSimpleName("foo")); //$NON-NLS-1$
if (parented) {
targetAst.newArrayType(result);
}
return result;
}
public ASTNode get() {
return x.getType();
}
public void set(ASTNode value) {
x.setType((Type) value);
}
});
genericPropertyTest(x, new Property("Default", false, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = x.getAST().newClassInstanceCreation();
AnonymousClassDeclaration s2 = x.getAST().newAnonymousClassDeclaration();
s1.setAnonymousClassDeclaration(s2);
s2.bodyDeclarations().add(x);
return s1;
}
public void unwrap() {
AnonymousClassDeclaration s2 = (AnonymousClassDeclaration) x.getParent();
s2.bodyDeclarations().remove(x);
}
public ASTNode get() {
return x.getDefault();
}
public void set(ASTNode value) {
x.setDefault((Expression) value);
}
});
}
public void testNormalAnnotation() {
if (ast.apiLevel() == AST.JLS2) {
// node type introduced in 3.0 API
try {
ast.newNormalAnnotation();
assertTrue(false);
} catch (UnsupportedOperationException e) {
// pass
}
return;
}
long previousCount = ast.modificationCount();
final NormalAnnotation x = ast.newNormalAnnotation(); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getTypeName().getParent() == x);
assertTrue(x.values().size() == 0);
assertTrue(x.isAnnotation());
assertTrue(!x.isModifier());
assertTrue(!x.isMarkerAnnotation());
assertTrue(x.isNormalAnnotation());
assertTrue(!x.isSingleMemberAnnotation());
assertTrue(x.getNodeType() == ASTNode.NORMAL_ANNOTATION);
assertTrue(x.structuralPropertiesForType() ==
NormalAnnotation.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tAnnotationName(x);
genericPropertyListTest(x, x.values(), new Property("Values", true, MemberValuePair.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
MemberValuePair result = targetAst.newMemberValuePair();
if (parented) {
NormalAnnotation ann = targetAst.newNormalAnnotation();
ann.values().add(result);
}
return result;
}
public ASTNode wrap() {
// return MemberValuePair that embeds x
MemberValuePair s1 = x.getAST().newMemberValuePair();
ClassInstanceCreation s2 = x.getAST().newClassInstanceCreation();
AnonymousClassDeclaration s3 = x.getAST().newAnonymousClassDeclaration();
MethodDeclaration s4 = x.getAST().newMethodDeclaration();
s1.setValue(s2);
s2.setAnonymousClassDeclaration(s3);
s3.bodyDeclarations().add(s4);
s4.modifiers().add(x);
return s1;
}
public void unwrap() {
MethodDeclaration s4 = (MethodDeclaration) x.getParent();
s4.modifiers().remove(x);
}
});
}
public void testMarkerAnnotation() {
if (ast.apiLevel() == AST.JLS2) {
// node type introduced in 3.0 API
try {
ast.newMarkerAnnotation();
assertTrue(false);
} catch (UnsupportedOperationException e) {
// pass
}
return;
}
long previousCount = ast.modificationCount();
final MarkerAnnotation x = ast.newMarkerAnnotation(); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getTypeName().getParent() == x);
assertTrue(x.isAnnotation());
assertTrue(!x.isModifier());
assertTrue(x.isMarkerAnnotation());
assertTrue(!x.isNormalAnnotation());
assertTrue(!x.isSingleMemberAnnotation());
assertTrue(x.getNodeType() == ASTNode.MARKER_ANNOTATION);
assertTrue(x.structuralPropertiesForType() ==
MarkerAnnotation.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tAnnotationName(x);
}
public void testSingleMemberAnnotation() {
if (ast.apiLevel() == AST.JLS2) {
// node type introduced in 3.0 API
try {
ast.newSingleMemberAnnotation();
assertTrue(false);
} catch (UnsupportedOperationException e) {
// pass
}
return;
}
long previousCount = ast.modificationCount();
final SingleMemberAnnotation x = ast.newSingleMemberAnnotation(); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getTypeName().getParent() == x);
assertTrue(x.isAnnotation());
assertTrue(!x.isModifier());
assertTrue(!x.isMarkerAnnotation());
assertTrue(!x.isNormalAnnotation());
assertTrue(x.isSingleMemberAnnotation());
assertTrue(x.getNodeType() == ASTNode.SINGLE_MEMBER_ANNOTATION);
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
tAnnotationName(x);
genericPropertyTest(x, new Property("Value", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = x.getAST().newClassInstanceCreation();
AnonymousClassDeclaration s2 = x.getAST().newAnonymousClassDeclaration();
MethodDeclaration s3 = x.getAST().newMethodDeclaration();
s1.setAnonymousClassDeclaration(s2);
s2.bodyDeclarations().add(s3);
s3.modifiers().add(x);
return s1;
}
public void unwrap() {
MethodDeclaration s3 = (MethodDeclaration) x.getParent();
s3.modifiers().remove(x);
}
public ASTNode get() {
return x.getValue();
}
public void set(ASTNode value) {
x.setValue((Expression) value);
}
});
}
public void testMemberValuePair() {
if (ast.apiLevel() == AST.JLS2) {
// node type introduced in 3.0 API
try {
ast.newMemberValuePair();
assertTrue(false);
} catch (UnsupportedOperationException e) {
// pass
}
return;
}
long previousCount = ast.modificationCount();
final MemberValuePair x = ast.newMemberValuePair(); //$NON-NLS-1$
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getName().getParent() == x);
assertTrue(x.getName().isDeclaration() == false);
assertTrue(x.getNodeType() == ASTNode.MEMBER_VALUE_PAIR);
assertTrue(x.structuralPropertiesForType() ==
MemberValuePair.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
genericPropertyTest(x, new Property("Name", true, SimpleName.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("a"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getName();
}
public void set(ASTNode value) {
x.setName((SimpleName) value);
}
});
genericPropertyTest(x, new Property("Value", true, Expression.class) { //$NON-NLS-1$
public ASTNode sample(AST localAst, boolean parented) {
Expression result = localAst.newSimpleName("foo"); //$NON-NLS-1$
if (parented) {
localAst.newExpressionStatement(result);
}
return result;
}
public ASTNode wrap() {
// return Expression that embeds x
ClassInstanceCreation s1 = x.getAST().newClassInstanceCreation();
AnonymousClassDeclaration s2 = x.getAST().newAnonymousClassDeclaration();
MethodDeclaration s3 = x.getAST().newMethodDeclaration();
NormalAnnotation s4 = x.getAST().newNormalAnnotation();
s1.setAnonymousClassDeclaration(s2);
s2.bodyDeclarations().add(s3);
s3.modifiers().add(s4);
s4.values().add(x);
return s1;
}
public void unwrap() {
NormalAnnotation s4 = (NormalAnnotation) x.getParent();
s4.values().remove(x);
}
public ASTNode get() {
return x.getValue();
}
public void set(ASTNode value) {
x.setValue((Expression) value);
}
});
}
/**
* Exercise the typeName property of an Annotation.
*
* @param x the annotation to test
* @since 3.0
*/
public void tAnnotationName(final Annotation x) {
genericPropertyTest(x, new Property("TypeName", true, Name.class) { //$NON-NLS-1$
public ASTNode sample(AST targetAst, boolean parented) {
SimpleName result = targetAst.newSimpleName("a"); //$NON-NLS-1$
if (parented) {
targetAst.newExpressionStatement(result);
}
return result;
}
public ASTNode get() {
return x.getTypeName();
}
public void set(ASTNode value) {
x.setTypeName((Name) value);
}
});
}
public void testModifiers() {
// check all modifiers match their JVM spec values
assertTrue(Modifier.ABSTRACT == 0x0400);
assertTrue(Modifier.FINAL == 0x0010);
assertTrue(Modifier.NATIVE == 0x0100);
assertTrue(Modifier.NONE == 0x0000);
assertTrue(Modifier.PRIVATE == 0x0002);
assertTrue(Modifier.PROTECTED == 0x0004);
assertTrue(Modifier.PUBLIC == 0x0001);
assertTrue(Modifier.STATIC == 0x0008);
assertTrue(Modifier.STRICTFP == 0x0800);
assertTrue(Modifier.SYNCHRONIZED == 0x0020);
assertTrue(Modifier.TRANSIENT == 0x0080);
assertTrue(Modifier.VOLATILE == 0x0040);
// check that all
final int[] mods =
{
Modifier.ABSTRACT,
Modifier.FINAL,
Modifier.NATIVE,
Modifier.PRIVATE,
Modifier.PROTECTED,
Modifier.PUBLIC,
Modifier.STATIC,
Modifier.STRICTFP,
Modifier.SYNCHRONIZED,
Modifier.TRANSIENT,
Modifier.VOLATILE,
};
for (int i=0; i< mods.length; i++) {
int m = mods[i];
assertTrue(Modifier.isAbstract(m) == (m == Modifier.ABSTRACT));
assertTrue(Modifier.isFinal(m) == (m == Modifier.FINAL));
assertTrue(Modifier.isNative(m) == (m == Modifier.NATIVE));
assertTrue(Modifier.isPrivate(m) == (m == Modifier.PRIVATE));
assertTrue(Modifier.isProtected(m) == (m == Modifier.PROTECTED));
assertTrue(Modifier.isPublic(m) == (m == Modifier.PUBLIC));
assertTrue(Modifier.isStatic(m) == (m == Modifier.STATIC));
assertTrue(Modifier.isStrictfp(m) == (m == Modifier.STRICTFP));
assertTrue(Modifier.isSynchronized(m) == (m == Modifier.SYNCHRONIZED));
assertTrue(Modifier.isTransient(m) == (m == Modifier.TRANSIENT));
assertTrue(Modifier.isVolatile(m) == (m == Modifier.VOLATILE));
}
if (ast.apiLevel() == AST.JLS2) {
// node type introduced in 3.0 API
try {
ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
assertTrue(false);
} catch (UnsupportedOperationException e) {
// pass
}
try {
ast.newModifiers(Modifier.NONE);
assertTrue(false);
} catch (UnsupportedOperationException e) {
// pass
}
// skip rest of tests
return;
}
// JLS3 only
long previousCount = ast.modificationCount();
final Modifier x = ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
assertTrue(ast.modificationCount() > previousCount);
previousCount = ast.modificationCount();
assertTrue(x.getAST() == ast);
assertTrue(x.getParent() == null);
assertTrue(x.getKeyword() == Modifier.ModifierKeyword.PUBLIC_KEYWORD);
assertTrue(x.getNodeType() == ASTNode.MODIFIER);
assertTrue(x.structuralPropertiesForType() ==
Modifier.propertyDescriptors(ast.apiLevel()));
// make sure that reading did not change modification count
assertTrue(ast.modificationCount() == previousCount);
// ModifierKeyword property - mandatory typesafe enumeration
// check the names of the modifiers
assertTrue(Modifier.ModifierKeyword.PUBLIC_KEYWORD.toString().equals("public")); //$NON-NLS-1$
assertTrue(Modifier.ModifierKeyword.PROTECTED_KEYWORD.toString().equals("protected")); //$NON-NLS-1$
assertTrue(Modifier.ModifierKeyword.PRIVATE_KEYWORD.toString().equals("private")); //$NON-NLS-1$
assertTrue(Modifier.ModifierKeyword.STATIC_KEYWORD.toString().equals("static")); //$NON-NLS-1$
assertTrue(Modifier.ModifierKeyword.ABSTRACT_KEYWORD.toString().equals("abstract")); //$NON-NLS-1$
assertTrue(Modifier.ModifierKeyword.FINAL_KEYWORD.toString().equals("final")); //$NON-NLS-1$
assertTrue(Modifier.ModifierKeyword.SYNCHRONIZED_KEYWORD.toString().equals("synchronized")); //$NON-NLS-1$
assertTrue(Modifier.ModifierKeyword.NATIVE_KEYWORD.toString().equals("native")); //$NON-NLS-1$
assertTrue(Modifier.ModifierKeyword.TRANSIENT_KEYWORD.toString().equals("transient")); //$NON-NLS-1$
assertTrue(Modifier.ModifierKeyword.VOLATILE_KEYWORD.toString().equals("volatile")); //$NON-NLS-1$
assertTrue(Modifier.ModifierKeyword.STRICTFP_KEYWORD.toString().equals("strictfp")); //$NON-NLS-1$
final Modifier.ModifierKeyword[] known = {
Modifier.ModifierKeyword.PUBLIC_KEYWORD,
Modifier.ModifierKeyword.PROTECTED_KEYWORD,
Modifier.ModifierKeyword.PRIVATE_KEYWORD,
Modifier.ModifierKeyword.STATIC_KEYWORD,
Modifier.ModifierKeyword.ABSTRACT_KEYWORD,
Modifier.ModifierKeyword.FINAL_KEYWORD,
Modifier.ModifierKeyword.SYNCHRONIZED_KEYWORD,
Modifier.ModifierKeyword.NATIVE_KEYWORD,
Modifier.ModifierKeyword.TRANSIENT_KEYWORD,
Modifier.ModifierKeyword.VOLATILE_KEYWORD,
Modifier.ModifierKeyword.STRICTFP_KEYWORD,
};
// check all modifiers are distinct
for (int i = 0; i < known.length; i++) {
for (int j = 0; j < known.length; j++) {
assertTrue(i == j || !known[i].equals(known[j]));
}
}
// check all modifiers work
for (int i = 0; i < known.length; i++) {
previousCount = ast.modificationCount();
x.setKeyword(known[i]);
assertTrue(ast.modificationCount() > previousCount);
assertTrue(x.getKeyword().equals(known[i]));
}
// ensure null does not work as an operator
try {
x.setKeyword(null);
assertTrue(false);
} catch (RuntimeException e) {
// pass
}
// check toKeyword lookup of modifier by name
for (int i = 0; i < known.length; i++) {
String name = known[i].toString();
assertTrue(Modifier.ModifierKeyword.toKeyword(name).equals(known[i]));
}
assertTrue(Modifier.ModifierKeyword.toKeyword("huh") == null); //$NON-NLS-1$
// check AST.newModifiers(flags)
for (int i = 0; i < mods.length; i++) {
int m = mods[i];
List result = ast.newModifiers(m);
assertEquals(1, result.size());
Modifier modNode = (Modifier) result.get(0);
assertEquals(m, modNode.getKeyword().toFlagValue());
}
// check AST.newModifiers ordering
final Modifier.ModifierKeyword[] expectedOrder = {
Modifier.ModifierKeyword.PUBLIC_KEYWORD,
Modifier.ModifierKeyword.PROTECTED_KEYWORD,
Modifier.ModifierKeyword.PRIVATE_KEYWORD,
Modifier.ModifierKeyword.ABSTRACT_KEYWORD,
Modifier.ModifierKeyword.STATIC_KEYWORD,
Modifier.ModifierKeyword.FINAL_KEYWORD,
Modifier.ModifierKeyword.SYNCHRONIZED_KEYWORD,
Modifier.ModifierKeyword.NATIVE_KEYWORD,
Modifier.ModifierKeyword.STRICTFP_KEYWORD,
Modifier.ModifierKeyword.TRANSIENT_KEYWORD,
Modifier.ModifierKeyword.VOLATILE_KEYWORD,
};
int all = 0;
for (int i = 0; i < mods.length; i++) {
all |= mods[i];
}
List result = ast.newModifiers(all);
assertEquals(expectedOrder.length, result.size());
for (int i = 0; i< expectedOrder.length; i++) {
assertEquals(expectedOrder[i], ((Modifier) result.get(i)).getKeyword());
}
}
public void testSubtreeBytes() {
ASTNode x = SampleASTs.oneOfEach(ast);
System.out.println("oneOfEach().subtreeBytes(): " + x.subtreeBytes());
assertTrue(x.subtreeBytes() > 0);
}
public void testNodeTypeConstants() {
// it would be a breaking API change to change the numeric values of
// public static final ints
assertTrue(ASTNode.ANONYMOUS_CLASS_DECLARATION == 1);
assertTrue(ASTNode.ARRAY_ACCESS == 2);
assertTrue(ASTNode.ARRAY_CREATION == 3);
assertTrue(ASTNode.ARRAY_INITIALIZER == 4);
assertTrue(ASTNode.ARRAY_TYPE == 5);
assertTrue(ASTNode.ASSERT_STATEMENT == 6);
assertTrue(ASTNode.ASSIGNMENT == 7);
assertTrue(ASTNode.BLOCK == 8);
assertTrue(ASTNode.BOOLEAN_LITERAL == 9);
assertTrue(ASTNode.BREAK_STATEMENT == 10);
assertTrue(ASTNode.CAST_EXPRESSION == 11);
assertTrue(ASTNode.CATCH_CLAUSE == 12);
assertTrue(ASTNode.CHARACTER_LITERAL == 13);
assertTrue(ASTNode.CLASS_INSTANCE_CREATION == 14);
assertTrue(ASTNode.COMPILATION_UNIT == 15);
assertTrue(ASTNode.CONDITIONAL_EXPRESSION == 16);
assertTrue(ASTNode.CONSTRUCTOR_INVOCATION == 17);
assertTrue(ASTNode.CONTINUE_STATEMENT == 18);
assertTrue(ASTNode.DO_STATEMENT == 19);
assertTrue(ASTNode.EMPTY_STATEMENT == 20);
assertTrue(ASTNode.EXPRESSION_STATEMENT == 21);
assertTrue(ASTNode.FIELD_ACCESS == 22);
assertTrue(ASTNode.FIELD_DECLARATION == 23);
assertTrue(ASTNode.FOR_STATEMENT == 24);
assertTrue(ASTNode.IF_STATEMENT == 25);
assertTrue(ASTNode.IMPORT_DECLARATION == 26);
assertTrue(ASTNode.INFIX_EXPRESSION == 27);
assertTrue(ASTNode.INITIALIZER == 28);
assertTrue(ASTNode.JAVADOC == 29);
assertTrue(ASTNode.LABELED_STATEMENT == 30);
assertTrue(ASTNode.METHOD_DECLARATION == 31);
assertTrue(ASTNode.METHOD_INVOCATION == 32);
assertTrue(ASTNode.NULL_LITERAL == 33);
assertTrue(ASTNode.NUMBER_LITERAL == 34);
assertTrue(ASTNode.PACKAGE_DECLARATION == 35);
assertTrue(ASTNode.PARENTHESIZED_EXPRESSION == 36);
assertTrue(ASTNode.POSTFIX_EXPRESSION == 37);
assertTrue(ASTNode.PREFIX_EXPRESSION == 38);
assertTrue(ASTNode.PRIMITIVE_TYPE == 39);
assertTrue(ASTNode.QUALIFIED_NAME == 40);
assertTrue(ASTNode.RETURN_STATEMENT == 41);
assertTrue(ASTNode.SIMPLE_NAME == 42);
assertTrue(ASTNode.SIMPLE_TYPE == 43);
assertTrue(ASTNode.SINGLE_VARIABLE_DECLARATION == 44);
assertTrue(ASTNode.STRING_LITERAL == 45);
assertTrue(ASTNode.SUPER_CONSTRUCTOR_INVOCATION == 46);
assertTrue(ASTNode.SUPER_FIELD_ACCESS == 47);
assertTrue(ASTNode.SUPER_METHOD_INVOCATION == 48);
assertTrue(ASTNode.SWITCH_CASE == 49);
assertTrue(ASTNode.SWITCH_STATEMENT == 50);
assertTrue(ASTNode.SYNCHRONIZED_STATEMENT == 51);
assertTrue(ASTNode.THIS_EXPRESSION == 52);
assertTrue(ASTNode.THROW_STATEMENT == 53);
assertTrue(ASTNode.TRY_STATEMENT == 54);
assertTrue(ASTNode.TYPE_DECLARATION == 55);
assertTrue(ASTNode.TYPE_DECLARATION_STATEMENT == 56);
assertTrue(ASTNode.TYPE_LITERAL == 57);
assertTrue(ASTNode.VARIABLE_DECLARATION_EXPRESSION == 58);
assertTrue(ASTNode.VARIABLE_DECLARATION_FRAGMENT == 59);
assertTrue(ASTNode.VARIABLE_DECLARATION_STATEMENT == 60);
assertTrue(ASTNode.WHILE_STATEMENT == 61);
assertTrue(ASTNode.INSTANCEOF_EXPRESSION == 62);
assertTrue(ASTNode.LINE_COMMENT == 63);
assertTrue(ASTNode.BLOCK_COMMENT == 64);
assertTrue(ASTNode.TAG_ELEMENT == 65);
assertTrue(ASTNode.TEXT_ELEMENT == 66);
assertTrue(ASTNode.MEMBER_REF == 67);
assertTrue(ASTNode.METHOD_REF == 68);
assertTrue(ASTNode.METHOD_REF_PARAMETER == 69);
assertTrue(ASTNode.ENHANCED_FOR_STATEMENT == 70);
assertTrue(ASTNode.ENUM_DECLARATION == 71);
assertTrue(ASTNode.ENUM_CONSTANT_DECLARATION == 72);
assertTrue(ASTNode.TYPE_PARAMETER == 73);
assertTrue(ASTNode.PARAMETERIZED_TYPE == 74);
assertTrue(ASTNode.QUALIFIED_TYPE == 75);
assertTrue(ASTNode.WILDCARD_TYPE == 76);
assertTrue(ASTNode.NORMAL_ANNOTATION == 77);
assertTrue(ASTNode.MARKER_ANNOTATION == 78);
assertTrue(ASTNode.SINGLE_MEMBER_ANNOTATION == 79);
assertTrue(ASTNode.MEMBER_VALUE_PAIR == 80);
assertTrue(ASTNode.ANNOTATION_TYPE_DECLARATION == 81);
assertTrue(ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION == 82);
assertTrue(ASTNode.MODIFIER == 83);
// ensure that all constants are distinct, positive, and small
// (this may seem paranoid, but this test did uncover a stupid bug!)
int[] all= {
ASTNode.ANNOTATION_TYPE_DECLARATION,
ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION,
ASTNode.ANONYMOUS_CLASS_DECLARATION,
ASTNode.ARRAY_ACCESS,
ASTNode.ARRAY_CREATION,
ASTNode.ARRAY_INITIALIZER,
ASTNode.ARRAY_TYPE,
ASTNode.ASSERT_STATEMENT,
ASTNode.ASSIGNMENT,
ASTNode.BLOCK,
ASTNode.BLOCK_COMMENT,
ASTNode.BOOLEAN_LITERAL,
ASTNode.BREAK_STATEMENT,
ASTNode.CAST_EXPRESSION,
ASTNode.CATCH_CLAUSE,
ASTNode.CHARACTER_LITERAL,
ASTNode.CLASS_INSTANCE_CREATION,
ASTNode.COMPILATION_UNIT,
ASTNode.CONDITIONAL_EXPRESSION,
ASTNode.CONSTRUCTOR_INVOCATION,
ASTNode.CONTINUE_STATEMENT,
ASTNode.DO_STATEMENT,
ASTNode.EMPTY_STATEMENT,
ASTNode.ENHANCED_FOR_STATEMENT,
ASTNode.ENUM_CONSTANT_DECLARATION,
ASTNode.ENUM_DECLARATION,
ASTNode.EXPRESSION_STATEMENT,
ASTNode.FIELD_ACCESS,
ASTNode.FIELD_DECLARATION,
ASTNode.FOR_STATEMENT,
ASTNode.IF_STATEMENT,
ASTNode.IMPORT_DECLARATION,
ASTNode.INFIX_EXPRESSION,
ASTNode.INSTANCEOF_EXPRESSION,
ASTNode.INITIALIZER,
ASTNode.JAVADOC,
ASTNode.LABELED_STATEMENT,
ASTNode.LINE_COMMENT,
ASTNode.MARKER_ANNOTATION,
ASTNode.MEMBER_REF,
ASTNode.MEMBER_VALUE_PAIR,
ASTNode.METHOD_DECLARATION,
ASTNode.METHOD_INVOCATION,
ASTNode.METHOD_REF,
ASTNode.METHOD_REF_PARAMETER,
ASTNode.MODIFIER,
ASTNode.NORMAL_ANNOTATION,
ASTNode.NULL_LITERAL,
ASTNode.NUMBER_LITERAL,
ASTNode.PACKAGE_DECLARATION,
ASTNode.PARAMETERIZED_TYPE,
ASTNode.PARENTHESIZED_EXPRESSION,
ASTNode.POSTFIX_EXPRESSION,
ASTNode.PREFIX_EXPRESSION,
ASTNode.PRIMITIVE_TYPE,
ASTNode.QUALIFIED_NAME,
ASTNode.QUALIFIED_TYPE,
ASTNode.RETURN_STATEMENT,
ASTNode.SIMPLE_NAME,
ASTNode.SIMPLE_TYPE,
ASTNode.SINGLE_MEMBER_ANNOTATION,
ASTNode.SINGLE_VARIABLE_DECLARATION,
ASTNode.STRING_LITERAL,
ASTNode.SUPER_CONSTRUCTOR_INVOCATION,
ASTNode.SUPER_FIELD_ACCESS,
ASTNode.SUPER_METHOD_INVOCATION,
ASTNode.SWITCH_CASE,
ASTNode.SWITCH_STATEMENT,
ASTNode.SYNCHRONIZED_STATEMENT,
ASTNode.TAG_ELEMENT,
ASTNode.TEXT_ELEMENT,
ASTNode.THIS_EXPRESSION,
ASTNode.THROW_STATEMENT,
ASTNode.TRY_STATEMENT,
ASTNode.TYPE_DECLARATION,
ASTNode.TYPE_DECLARATION_STATEMENT,
ASTNode.TYPE_LITERAL,
ASTNode.TYPE_PARAMETER,
ASTNode.VARIABLE_DECLARATION_EXPRESSION,
ASTNode.VARIABLE_DECLARATION_FRAGMENT,
ASTNode.VARIABLE_DECLARATION_STATEMENT,
ASTNode.WHILE_STATEMENT,
ASTNode.WILDCARD_TYPE,
};
int MIN = 1;
int MAX = 100;
Set s = new HashSet();
for (int i=0; i<all.length; i++) {
assertTrue(MIN <= all[i] && all[i] <= MAX);
s.add(new Integer(all[i]));
}
assertTrue(s.size() == all.length);
// ensure that Integers really do compare properly with equals
assertTrue(new Integer(1).equals(new Integer(1)));
}
}
|
[
"375833274@qq.com"
] |
375833274@qq.com
|
cf13b17b3121f9438129786c6f1724a3bf5bf8f2
|
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/33/33_f0eab8ff38d525893cd4aad3b5c31f0416b5676e/Torrent/33_f0eab8ff38d525893cd4aad3b5c31f0416b5676e_Torrent_s.java
|
aae372421f22c778dad031938c249bc03aed310a
|
[] |
no_license
|
zhongxingyu/Seer
|
48e7e5197624d7afa94d23f849f8ea2075bcaec0
|
c11a3109fdfca9be337e509ecb2c085b60076213
|
refs/heads/master
| 2023-07-06T12:48:55.516692
| 2023-06-22T07:55:56
| 2023-06-22T07:55:56
| 259,613,157
| 6
| 2
| null | 2023-06-22T07:55:57
| 2020-04-28T11:07:49
| null |
UTF-8
|
Java
| false
| false
| 11,350
|
java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.tracker.entity;
import com.tracker.backend.StringUtils;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.Vector;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.CascadeType;
import javax.persistence.Temporal;
/**
*
* @author bo
*/
@Entity
public class Torrent implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Primary key
*/
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
/**
* Primary key, 40-byte hex-representation of the info hash
* encoded as hex to make it easier with all the binary data
*/
@Id
@Column(length=40)
private String infoHash;
/**
* Name of the torrent
*/
private String name;
/**
* Description of the torrent contents
*/
private String description;
/**
* Date and time the torrent was added
*/
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date added;
/**
* Number of seeders seeding this torrent
*/
private Long numSeeders;
/**
* Number of leechers downloading this torrent
*/
private Long numLeechers;
/**
* Total number of peers on this torrent (seeders + leechers)
*/
private Long numPeers;
/**
* How many have completed this torrent over its lifetime
*/
private Long numCompleted;
/**
* Size of the torrent in bytes
*/
private Long torrentSize;
/**
* All peers connected with this torrent
* bi-directional relationship with the Peer Entity class
*/
@OneToMany(cascade = CascadeType.REMOVE, mappedBy = "torrent")
private Collection<Peer> peersData;
/**
* The peers that are seeding this torrent
* one-directional relationship with the Peer Entity class
*/
@OneToMany
private Collection<Peer> seedersData;
/**
* The peers that are leeching this torrent
* one-directional relationship with the Peer Entity class
*/
@OneToMany
private Collection<Peer> leechersData;
/**
* default constructor
*/
public Torrent() {
numCompleted = numLeechers = numPeers = numSeeders = (long)0;
peersData = new Vector<Peer>();
seedersData = new Vector<Peer>();
leechersData = new Vector<Peer>();
}
/**
* marks a leecher as completed (turns into a seed).
* This is necessary since removePeer() + addSeed() confuses JPA and it's
* mapping-table.
* @param p the leecher that has completed this torrent
* @return true if the leecher is on this torrent and has been changed to a
* seed, false if the peer is not a leecher of this torrent.
*/
public boolean leecherCompleted(Peer p) {
if(leechersData.contains(p)) {
leechersData.remove(p);
numLeechers--;
seedersData.add(p);
numSeeders++;
p.setSeed(true);
return true;
}
return false;
}
/**
* Gets the leechers data
* @return a Collection of Peers that are leeching this torrent
*/
public Collection<Peer> getLeechersData() {
return leechersData;
}
/**
* Adds a leecher to this torrent
* @param p a Peer that is leeching this torrent
* @return true if the peers is added as a leecher, false if the peer is
* already in the list of peers.
*/
public boolean addLeecher(Peer p) {
if(this.peersData.contains(p))
return(false);
p.setSeed(false);
this.leechersData.add(p);
numLeechers++;
this.addPeer(p);
return(true);
}
/**
* Removes a leecher from this torrent
* @param p the Peer to remove from the list of leechers
* @return true if the Peer was leeching this torrent and was successfully
* removed, false if the Peer was not leeching this torrent.
*/
private boolean removeLeecher(Peer p) {
if(this.leechersData.contains(p)) {
this.leechersData.remove(p);
numLeechers--;
return(true);
}
else
return(false);
}
/**
* Gets the size of the torrent in bytes
* @return the size of the torrent in bytes
*/
public Long getTorrentSize() {
return torrentSize;
}
/**
* sets the size of the torrent in bytes
* @param torrentSize the new size of the torrent
*/
public void setTorrentSize(Long torrentSize) {
this.torrentSize = torrentSize;
}
/**
* Gives the number of leechers
* @return the number of leechers this torrent has
*/
public Long getNumLeechers() {
return numLeechers;
}
/**
* sets the number of leechers
* @param numLeechers the number of leechers this torrent supposedly has
*/
public void setNumLeechers(Long numLeechers) {
this.numLeechers = numLeechers;
}
/**
* gets the data of the seeding peers
* @return a Collection of Peers that is currently seeding this torrent
*/
public Collection<Peer> getSeedersData() {
return seedersData;
}
/**
* adds a seed to this torrent
* @param p the Peer to add as a seed to this torrent
* @return true if the Peer is successfully added as a seed, false if the
* Peer is already seeding this torrent
*/
public boolean addSeeder(Peer p) {
if(this.seedersData.contains(p))
return(false);
p.setSeed(true);
this.seedersData.add(p);
numSeeders++;
this.addPeer(p);
return(true);
}
/**
* removes a seed from this torrent
* @param p the Peer to remove as a seed from this torrent
* @return true if the Peer is successfully removed, false if the Peer is
* not seeding this torrent or is not a peer of this torrent
*/
private boolean removeSeed(Peer p) {
if(this.seedersData.contains(p)) {
this.seedersData.remove(p);
numSeeders--;
return(true);
}
else
return(false);
}
/**
* gets the peer data for the given torrent
* @return a Collection of Peers that is all the peers connected with the
* torrent
*/
public Collection<Peer> getPeersData() {
return peersData;
}
/**
* adds a peer to the list of peers.
* private method only, use addSeeder() or addLeecher() for everyone else
* @param p the peer to add the the list
*/
private void addPeer(Peer p) {
this.peersData.add(p);
p.setTorrent(this);
numPeers++;
}
/**
* Removes a peer from the list of peers
* private method only, use removeSeed() or removeLeecher() for everyone
* else
* @param p the peer to remove from the list
* @return true if the peer has been removed, false if the peer is not
* on this torrent
*/
public boolean removePeer(Peer p) {
if(this.peersData.contains(p)) {
this.peersData.remove(p);
numPeers--;
if(p.isSeed())
return this.removeSeed(p);
else
return this.removeLeecher(p);
}
else
return(false);
}
public Long getNumPeers() {
return numPeers;
}
public void setNumPeers(Long numPeers) {
this.numPeers = numPeers;
}
public Long getNumSeeders() {
return numSeeders;
}
public void setNumSeeders(Long numSeeders) {
this.numSeeders = numSeeders;
}
public Long getNumCompleted() {
return numCompleted;
}
public void setNumCompleted(Long completed) {
this.numCompleted = completed;
}
public Date getAdded() {
return added;
}
public void setAdded(Date added) {
this.added = added;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* returns the hex representation of the info hash
* @return the hex string representing the info hash
*/
public String getInfoHash() {
return infoHash;
}
/**
* Takes the raw info hash supplied and turns it into a hex-string and sets
* the hex string.
* @param infoHash the raw info hash recevied.
* @return true if the info hash has been set, false if there is some error
*/
public boolean setInfoHash(String infoHash) {
// is the info hash raw?
if(infoHash.length() == 20) {
try {
byte[] b = new byte[20];
// charAt is used instead of getBytes, because getBytes insists on
// going through the whole encoding thing
for(int i = 0; i < b.length; i++) {
b[i] = (byte) infoHash.charAt(i);
}
this.infoHash = StringUtils.getHexString(b);
} catch (Exception ex) {
// something went wrong
return false;
}
// all good
return true;
} // if(length != 20)
// is the info hash already encoded?
if(infoHash.length() == 40) {
this.infoHash = infoHash;
return true;
}
return false;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public int hashCode() {
int hash = 0;
for(int i = 0; i < 20; i++) {
hash += infoHash.getBytes()[i] ^ 0x4F;
}
return hash;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Torrent)) {
return false;
}
Torrent other = (Torrent) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))
|| (this.infoHash == null && other.infoHash != null)
|| (this.infoHash != null && !this.infoHash.equals(other.infoHash))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entity.Torrent[id=" + id + ",info_hash=" + infoHash + ",name=" + name + "]";
}
}
|
[
"yuzhongxing88@gmail.com"
] |
yuzhongxing88@gmail.com
|
bea6d3bd18b0d0e521065f8cc4ae2d13d3c1c0c0
|
06b102d0f4d3669a30ff8b9480b816bf5a3bbaca
|
/elixir_beacon/src/main/java/org/ega_archive/elixirbeacon/dto/Error.java
|
2935f9cc14884d205ee182a097127811f69a928b
|
[
"Apache-2.0"
] |
permissive
|
albertcrowley/human-data-beacon
|
070aa7c03bd0d124c6954b7eef5c95a81c682362
|
3782f27ec76e199f58fb54161b2f78562a26b3e6
|
refs/heads/master
| 2021-04-30T04:01:31.766256
| 2018-02-14T15:46:43
| 2018-02-14T15:46:43
| 121,528,067
| 0
| 0
| null | 2018-02-14T15:46:44
| 2018-02-14T15:41:47
|
Java
|
UTF-8
|
Java
| false
| false
| 346
|
java
|
package org.ega_archive.elixirbeacon.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Builder;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Error {
// Numeric status code
private int errorCode;
// Error message
private String message;
}
|
[
"sabela.delatorre@crg.eu"
] |
sabela.delatorre@crg.eu
|
50b6b4748f979c33ee269ecdda25528a0af15e8b
|
e0e52e6945c6d0002f8148c41c6015af140cee6c
|
/Multithreading/Unlearning/src/A.java
|
9fd3b22976322e03f9a82d466f5aaec62af1fdcf
|
[] |
no_license
|
preetskhalsa97/OOP
|
efd23aec2a4f6a0e93bbf17c024d4d12dbc97620
|
85d62211b9a145691e84de712a0f3baf6896f892
|
refs/heads/master
| 2020-05-23T10:13:47.286046
| 2017-05-17T11:05:44
| 2017-05-17T11:05:44
| 80,405,589
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 287
|
java
|
public class A {
synchronized void foo(B b){
String name = Thread.currentThread().getName();
System.out.println(name+" entered A.foo");
try{
Thread.sleep(1000);
}catch (Exception e){
}
}
synchronized void last(){
System.out.println("Inside A.last()");
}
}
|
[
"preetskhalsa97@gmail.com"
] |
preetskhalsa97@gmail.com
|
575b588f6e176bea4163f340e810559454657f15
|
0f7ba09a83e20fc9ebf8b580317fee703b1b85a8
|
/Library_Management_System/RemoveBook.java
|
46e547ba63defcd8e63dc0b1aaf257f515f7eba4
|
[] |
no_license
|
IamYVJ/Library_Management_System
|
fc6c7e4f1e85d0a8c81f07597874026ef8c941f7
|
485e9cbd298c48c322f3765d75640d79e9b5f4ab
|
refs/heads/master
| 2021-02-26T02:05:22.298405
| 2020-03-06T18:18:46
| 2020-03-06T18:18:46
| 245,486,900
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 5,682
|
java
|
import java.sql.*;
import java.io.*;
class RemoveBook
{
String hist = "";
String driver = "net.ucanaccess.jdbc.UcanaccessDriver";
String location = "jdbc:ucanaccess://E:\\Yashvardhan\\Java\\ICSE EXTERNAL PROJECT\\LibraryDatabase.accdb";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
HistoryWrite HistoryWrite = new HistoryWrite();
void removeBook(String bookname, int bookid)
{
try
{
Class.forName(driver);
Connection conn=DriverManager.getConnection(location);
Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("SELECT (*) FROM Books");
while(rs.next())
{
if(rs.getInt("ID")==bookid)
{
if(rs.getString("Book_Name").equalsIgnoreCase(bookname))
{
if(rs.getString("Status").equals("AVAILABLE"))
{
HistoryWrite.writeToFile(rs.getString("Book_Name") + "(" + bookid + ") By " + rs.getString("Book_Author") + " Removed");
PreparedStatement ps = conn.prepareStatement("DELETE FROM Books WHERE ID = ?");
ps.setInt(1,bookid);
ps.executeUpdate();
System.out.print("\nBook Removed");
}
else
{
System.out.print("\nBook is borrowed");
System.out.print("\nDo you still want to remove the book?(Y/N):");
String c = br.readLine().toUpperCase().trim();
if(!c.equals(""))
{
if(c.charAt(0)=='Y')
{
hist = rs.getString("Book_Name") + " (" + bookid + ") By " + rs.getString("Book_Author") +" Removed ";
PreparedStatement ps = conn.prepareStatement("DELETE FROM Books WHERE ID = ?");
ps.setInt(1,bookid);
ps.executeUpdate();
ps.close();
memberUpdate(historyUpdate(bookid),bookid);
System.out.print("\nBook Removed");
}
else
{
System.out.print("\nBook Not Removed");
}
}
else
{
System.out.print("\nAnswer cannot be blank");
}
}
}
break;
}
}
rs.close();
st.close();
conn.close();
}
catch(Exception ex)
{
System.err.println("Exception: ");
System.err.println(ex.getMessage());
}
}
int historyUpdate(int bookid)
{
int memberid = 0;
try
{
Class.forName(driver);
Connection conn=DriverManager.getConnection(location);
Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("SELECT (*) FROM History");
while(rs.next())
{
if(rs.getInt("Book_ID")==bookid && rs.getString("Return_Date").equals("BORROWED"))
{
memberid = rs.getInt("Member_ID");
rs.updateString("Return_Date","REMOVED");
rs.updateRow();
break;
}
}
rs.close();
st.close();
conn.close();
}
catch(Exception ex)
{
System.err.println("Exception: ");
System.err.println(ex.getMessage());
}
finally
{
return memberid;
}
}
void memberUpdate(int memberid, int bookid)
{
try
{
Class.forName(driver);
Connection conn=DriverManager.getConnection(location);
Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("SELECT (*) FROM Members");
while(rs.next())
{
if(rs.getInt("ID")==memberid)
{
hist = hist + "(Book With Borrower: " + rs.getString("Member_Name") + "(" + rs.getString("Member_ID") + "))";
HistoryWrite.writeToFile(hist);
for(int i = 1; i<=5; i++)
{
if(rs.getInt("Slot_"+i)==bookid)
{
rs.updateInt("Slot_"+i,0);
rs.updateRow();
break;
}
}
break;
}
}
rs.close();
st.close();
conn.close();
Sort Sort = new Sort();
Sort.memberSort(memberid);
}
catch(Exception ex)
{
System.err.println("Exception: ");
System.err.println(ex.getMessage());
}
}
}
|
[
"yashvardhan18@yahoo.com"
] |
yashvardhan18@yahoo.com
|
b2ad89248226606d702460b77388f6cdcf89b068
|
f591b1a30be868fb4b9bb4e8167b9056a3574875
|
/onion-easy-orm-rdb/src/main/java/cc/kebei/ezorm/rdb/meta/parser/AbstractTableMetaParser.java
|
d1b043b48ba52690f12ad180ea375cd2dfb6b26c
|
[] |
no_license
|
keqingyuan/onion-easy-orm
|
efa16471eb55aad58618a6af9a2fa86aa6b6a8ec
|
cf7804bd0ad187de831f3ddb3f52027562a0f7be
|
refs/heads/master
| 2022-09-14T22:43:10.618239
| 2019-12-31T08:32:11
| 2019-12-31T08:32:11
| 187,639,100
| 0
| 0
| null | 2022-09-08T01:00:26
| 2019-05-20T12:46:57
|
Java
|
UTF-8
|
Java
| false
| false
| 6,303
|
java
|
package cc.kebei.ezorm.rdb.meta.parser;
import cc.kebei.ezorm.rdb.meta.expand.SimpleMapWrapper;
import cc.kebei.ezorm.rdb.render.dialect.Dialect;
import cc.kebei.ezorm.rdb.render.support.simple.SimpleSQL;
import lombok.SneakyThrows;
import cc.kebei.ezorm.core.ObjectWrapper;
import cc.kebei.ezorm.rdb.executor.SqlExecutor;
import cc.kebei.ezorm.rdb.meta.RDBColumnMetaData;
import cc.kebei.ezorm.rdb.meta.RDBTableMetaData;
import cc.kebei.utils.StringUtils;
import java.sql.JDBCType;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
public abstract class AbstractTableMetaParser implements TableMetaParser {
protected Map<String, JDBCType> jdbcTypeMap = new HashMap<>();
protected Map<JDBCType, Class> javaTypeMap = new HashMap<>();
protected String databaseName;
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public String getDatabaseName() {
return databaseName;
}
protected SqlExecutor sqlExecutor;
abstract Dialect getDialect();
public AbstractTableMetaParser(SqlExecutor sqlExecutor) {
this.sqlExecutor = sqlExecutor;
}
abstract String getTableMetaSql(String tname);
abstract String getTableCommentSql(String tname);
abstract String getAllTableSql();
abstract String getTableExistsSql();
@Override
public boolean tableExists(String name) {
try {
Map<String, Object> param = new HashMap<>();
param.put("table", name);
Map<String, Object> res = sqlExecutor.single(new SimpleSQL(getTableExistsSql(), param), new LowerCasePropertySimpleMapWrapper());
return res.get("total") != null && StringUtils.toInt(res.get("total")) > 0;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
@SneakyThrows
public RDBTableMetaData parse(String name) throws SQLException {
if (!tableExists(name)) return null;
RDBTableMetaData metaData = new RDBTableMetaData();
metaData.setName(name);
metaData.setAlias(name);
Map<String, Object> param = new HashMap<>();
param.put("table", name);
List<RDBColumnMetaData> metaDatas = sqlExecutor.list(new SimpleSQL(getTableMetaSql(name), param), new RDBColumnMetaDataWrapper());
metaDatas.forEach(metaData::addColumn);
Map<String, Object> comment = sqlExecutor.single(new SimpleSQL(getTableCommentSql(name), param), new LowerCasePropertySimpleMapWrapper());
if (null != comment && comment.get("comment") != null) {
metaData.setComment(String.valueOf(comment.get("comment")));
}
return metaData;
}
@Override
public List<RDBTableMetaData> parseAll() throws SQLException {
List<Map<String, Object>> tables = sqlExecutor.list(new SimpleSQL(getAllTableSql()), new LowerCasePropertySimpleMapWrapper());
return tables.stream()
.map(map -> (String) map.get("name"))
.filter(Objects::nonNull)
.map(name -> {
try {
return parse(name);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}).filter(Objects::nonNull)
.collect(Collectors.toList());
}
class LowerCasePropertySimpleMapWrapper extends SimpleMapWrapper {
@Override
public void wrapper(Map<String, Object> instance, int index, String attr, Object value) {
attr = attr.toLowerCase();
super.wrapper(instance, index, attr, value);
}
}
class RDBColumnMetaDataWrapper implements ObjectWrapper<RDBColumnMetaData> {
@Override
public Class<RDBColumnMetaData> getType() {
return RDBColumnMetaData.class;
}
@Override
public RDBColumnMetaData newInstance() {
return new RDBColumnMetaData();
}
@Override
public void wrapper(RDBColumnMetaData instance, int index, String attr, Object value) {
String stringValue;
if (value instanceof String) {
stringValue = ((String) value).toLowerCase();
} else {
stringValue = value == null ? "" : value.toString();
}
if (attr.equalsIgnoreCase("name")) {
instance.setName(stringValue);
instance.setProperty("old-name", stringValue);
} else if (attr.equalsIgnoreCase("comment")) {
instance.setComment(stringValue);
} else {
if (attr.toLowerCase().equals("not-null")) {
value = "1".equals(stringValue);
instance.setNotNull((boolean) value);
}
instance.setProperty(attr.toLowerCase(), value);
}
}
@Override
public boolean done(RDBColumnMetaData instance) {
String data_type = instance.getProperty("data_type").toString().toLowerCase();
int len = instance.getProperty("data_length").toInt();
int data_precision = instance.getProperty("data_precision").toInt();
int data_scale = instance.getProperty("data_scale").toInt();
instance.setLength(len);
instance.setPrecision(data_precision);
instance.setScale(data_scale);
JDBCType jdbcType;
try {
jdbcType = JDBCType.valueOf(data_type.toUpperCase());
} catch (Exception e) {
if (data_type.contains("("))
data_type = data_type.substring(0, data_type.indexOf("("));
jdbcType = jdbcTypeMap.get(data_type.toLowerCase());
if (jdbcType == null) {
jdbcType = JDBCType.valueOf(data_type.toUpperCase());
}
}
Class javaType = javaTypeMap.get(jdbcType);
instance.setJdbcType(jdbcType);
instance.setJavaType(javaType);
instance.setDataType(getDialect().buildDataType(instance));
return true;
}
}
}
|
[
"1209547238@qq.com"
] |
1209547238@qq.com
|
6853b58f294bf10ce877b6e44540073232f04110
|
ad27c67984206399e13546e111b5c81c0c201dce
|
/shopping_online/src/com/byzx/authority/dao/UserGroupMapper.java
|
c43fc60d5f394c37a6a9c6dcda2805ef467eeefe
|
[] |
no_license
|
SongYuan1995/shopStore
|
2b2febd7930dd71dfb2e33b6d429a9c5878e064e
|
3fb535812676f56bd1ec0c33fe15c52a330aa561
|
refs/heads/master
| 2020-07-26T06:11:10.178778
| 2019-09-15T08:37:18
| 2019-09-15T08:37:18
| 208,560,159
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,150
|
java
|
package com.byzx.authority.dao;
import java.util.List;
import java.util.Map;
import com.byzx.authority.vo.GroupRole;
import com.byzx.authority.vo.UserGroup;
public interface UserGroupMapper {
//列表展示页面和模糊查询共用的查询user_group表
public List<UserGroup> findGroupFuzzy(Map<String,Object> map);
//验证用户组名和用户组Code,用户组名称GroupName和groupCode是否唯一
public List<UserGroup> findGroupByGroupInfo(Map<String,Object> map);
//向user_group添加一条数据 -->
public Integer insertOneGroup(Map<String,Object> map);
//点击修改角色按钮
public Integer updateOneGroup(Map<String,Object> map);
//删除用户组
public Integer deleteUserGroup(UserGroup userGroup);
//启用/禁用用户组
public Integer enAndDisGroup(UserGroup userGroup);
//查询当前的用户组所对应的角色
public String findAllRoleIdString(Integer groupId);
//根据groupId删除当前用户组的所有角色
public Integer deleteThisGroupRoles(Integer groupId);
//根据groupId循环添加为该用户组分配的角色
public Integer insertRolesForGroup(GroupRole groupRole);
}
|
[
"838523504@qq.com"
] |
838523504@qq.com
|
35784cd74ca115ce0df879186cf435d192d756a3
|
26756671613b5ecfe1c13d0a8cb98c2678dfdde0
|
/code/client/android/src/main/java/com/github/blackbladeshiraishi/fm/moe/client/android/inject/PlaySongModule.java
|
0528166a6b64d6cb3c7bf3d11293f67568186e04
|
[
"Apache-2.0"
] |
permissive
|
BlackbladeShiraishi/moefm
|
d5673267c09949f44582c651edc5ca4712aaf0e0
|
714c2f07d2eb8d024b9d0c18ec4bc1c769567ba4
|
refs/heads/master
| 2021-05-02T12:38:47.469611
| 2017-02-21T04:38:11
| 2017-02-21T04:38:11
| 52,521,116
| 0
| 1
| null | 2016-11-04T03:10:38
| 2016-02-25T11:58:10
|
Java
|
UTF-8
|
Java
| false
| false
| 1,099
|
java
|
package com.github.blackbladeshiraishi.fm.moe.client.android.inject;
import com.github.blackbladeshiraishi.fm.moe.business.api.PlayList;
import com.github.blackbladeshiraishi.fm.moe.business.api.PlayService;
import com.github.blackbladeshiraishi.fm.moe.business.api.Player;
import com.github.blackbladeshiraishi.fm.moe.business.impl.core.api.DefaultPlayList;
import com.github.blackbladeshiraishi.fm.moe.business.impl.core.api.DefaultPlayService;
import com.github.blackbladeshiraishi.fm.moe.client.android.business.MediaPlayerWrapper;
import com.github.blackbladeshiraishi.fm.moe.client.android.business.MediaPlayers;
import dagger.Module;
import dagger.Provides;
@Module
public class PlaySongModule {
@Provides
@PlaySongScope
PlayList providePlayList() {
return new DefaultPlayList();
}
@Provides
@PlaySongScope
Player providePlayer() {
return new MediaPlayerWrapper(MediaPlayers.getMediaPlayerFactory());
}
@Provides
@PlaySongScope
PlayService providePlayService(PlayList playList, Player player) {
return new DefaultPlayService(playList, player);
}
}
|
[
"blackblade.shiraishi@outlook.com"
] |
blackblade.shiraishi@outlook.com
|
4de9d9f0cbadd4f174ee2ee5bcbe80598a6aae25
|
8638a2efe2168eaa536bd89ca5f6b87927d17118
|
/Atcoder/ABC56/TaskB/Main.java
|
9e372dce1600899eac5dc4dba4a7396d49ab0854
|
[] |
no_license
|
Simply-divine/Competitive
|
5c5e6418ddaceb8fae3c643a2e120b23a256b67c
|
0a7e720322a57fd95cff0d796640ac69a6f45cdc
|
refs/heads/master
| 2022-12-26T21:32:04.483818
| 2020-04-18T15:52:40
| 2020-04-18T15:52:40
| 256,789,554
| 1
| 1
| null | 2020-10-01T06:37:57
| 2020-04-18T15:37:30
|
C++
|
UTF-8
|
Java
| false
| false
| 1,202
|
java
|
import java.io.*;
import java.util.*;
public class Main{
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next(){
try{
while(st==null||!st.hasMoreElements()){
st = new StringTokenizer(br.readLine());
}
}catch(Exception e){
e.printStackTrace();
}
return st.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
public String nextLine(){
String s = "";
try{
s = br.readLine();
}catch(Exception e){
e.printStackTrace();
}
return s;
}
}
public static void main(String[] args){
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int w = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int moves = 0;
if(a<=b){
if(a+w<b){
moves = b-(a+w);
}
else{
moves = 0;
}
}
else{
if(b+w<a){
moves =a-(b+w);
}
}
out.println(moves);
out.flush();
out.close();
}
}
|
[
"hardikvu0204@gmail.com"
] |
hardikvu0204@gmail.com
|
d03db1fc84cebb28a4a02edfa55f7e92ea6fd2e1
|
22224923367df6ed5134f10e34e30982d4f6a75b
|
/ApoioTerritorioLS/src/br/com/nascisoft/apoioterritoriols/cadastro/client/presenter/CadastroPresenter.java
|
a71ea6e2371eec0a668d8ec1b3551932a2f94fcf
|
[] |
no_license
|
tiagonn/AppTerritorios
|
b976be98764a3f035b796d8b8ac315a8830e7e41
|
5b6642901867bd066f7c0fb3ca36be1154180f30
|
refs/heads/master
| 2021-09-11T16:48:51.471323
| 2017-12-26T11:09:22
| 2017-12-26T11:09:22
| 2,143,834
| 1
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 232
|
java
|
package br.com.nascisoft.apoioterritoriols.cadastro.client.presenter;
import com.google.gwt.user.client.ui.HasWidgets;
public abstract interface CadastroPresenter {
public abstract void go(final HasWidgets container);
}
|
[
"tiagonn@gmail.com"
] |
tiagonn@gmail.com
|
d2ad84dcd9aa815d5ce1b6f84cce8a60ba569270
|
4be2591e3b8776c6693ea1fd881471bf8ab539b4
|
/src/main/java/com/gsonkeno/jvmtraining/btrace/TracingScript.java
|
c785b7ab81967d6415252efebff4ab6a85b7753c
|
[] |
no_license
|
gsonkeno/jvm-training
|
104bf0ba88efe371b1fd76d60e568f20d1a92dae
|
219ddb3947459f30eed4d6e28384011970ae72d2
|
refs/heads/master
| 2020-04-03T05:57:37.984993
| 2018-11-04T08:03:02
| 2018-11-04T08:03:02
| 155,060,987
| 0
| 0
| null | null | null | null |
UTF-8
|
Java
| false
| false
| 1,303
|
java
|
package com.gsonkeno.jvmtraining.btrace;
import com.sun.btrace.annotations.*;
import static com.sun.btrace.BTraceUtils.*;
/**
* 调试脚本
*/
@BTrace
public class TracingScript {
@OnMethod(
clazz = "com.gsonkeno.jvmtraining.btrace.BTraceTest",
method = "add",
location = @Location(Kind.RETURN)
)
public static void func(@Self com.gsonkeno.jvmtraining.btrace.BTraceTest instance,
int a, int b, @Return int result){
println("调用堆栈:");
jstack();
println(strcat("方法参数A:", str(a)));
println(strcat("方法参数B:", str(b)));
println(strcat("方法结果:", str(result)));
}
// 最终在jvisualvm工具面板BTrace一栏中打印出来的内容,类似如下:
// 调用堆栈:
// com.gsonkeno.jvmtraining.btrace.BTraceTest.add(BTraceTest.java:9)
// com.gsonkeno.jvmtraining.btrace.BTraceTest.main(Unknown Source)
// 方法参数A:754
// 方法参数B:584
// 方法结果:1338
// 调用堆栈:
// com.gsonkeno.jvmtraining.btrace.BTraceTest.add(BTraceTest.java:9)
// com.gsonkeno.jvmtraining.btrace.BTraceTest.main(Unknown Source)
// 方法参数A:106
// 方法参数B:309
// 方法结果:415
}
|
[
"805940564@qq.com"
] |
805940564@qq.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.