hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
e0afe63800544e3e0fe67d0dfa6048e403a6aa5f | 838 | package com.jamasoftware.services.restclient.jamadomain.fields;
import com.jamasoftware.services.restclient.jamadomain.lazyresources.PickList;
import com.jamasoftware.services.restclient.jamadomain.values.MultiSelectFieldValue;
public class MultiSelectField extends JamaField {
private PickList pickList;
public PickList getPickList() {
return pickList;
}
public void setPickList(PickList pickList) {
this.pickList = pickList;
}
@Override
public MultiSelectFieldValue getValue() {
MultiSelectFieldValue multiSelectFieldValue = new MultiSelectFieldValue();
populateFieldValue(multiSelectFieldValue);
return multiSelectFieldValue;
}
public MultiSelectField(String type) {
super(type);
}
public MultiSelectField() {
super();
}
}
| 25.393939 | 84 | 0.724344 |
99277b0d070f96ea75a38887fc70445e188d07f2 | 2,648 | package lk.sliit.hotelManagement.entity.restaurant.counterOrder;
import lk.sliit.hotelManagement.entity.kitchen.FoodItem;
import javax.persistence.*;
@Entity
public class RestaurantCounterOrderDetail {
@EmbeddedId
private RestaurantCounterOrderDetailPK restaurantCounterOrderDetailPK;
private double quantity;
private double unitePrice;
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.DETACH, CascadeType.MERGE})
@JoinColumn(name = "restaurantCounterOrder", referencedColumnName = "orderId", insertable = false, updatable = false)
private RestaurantCounterOrder restaurantCounterOrder;
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.DETACH, CascadeType.MERGE})
@JoinColumn(name = "foodItemId", referencedColumnName = "itemId",insertable = false, updatable = false)
private FoodItem foodItem;
public RestaurantCounterOrderDetail(RestaurantCounterOrderDetailPK restaurantCounterOrderDetailPK, double quantity, double unitePrice) {
this.restaurantCounterOrderDetailPK = restaurantCounterOrderDetailPK;
this.quantity = quantity;
this.unitePrice = unitePrice;
}
public RestaurantCounterOrderDetail(int restaurantCounterOrder, int foodItemId, double quantity, double unitePrice) {
this.restaurantCounterOrderDetailPK = new RestaurantCounterOrderDetailPK(foodItemId,restaurantCounterOrder);
this.quantity = quantity;
this.unitePrice = unitePrice;
}
public RestaurantCounterOrderDetail() {
}
public double getQuantity() {
return quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public double getUnitePrice() {
return unitePrice;
}
public void setUnitePrice(double unitePrice) {
this.unitePrice = unitePrice;
}
public RestaurantCounterOrderDetailPK getRestaurantCounterOrderDetailPK() {
return restaurantCounterOrderDetailPK;
}
public void setRestaurantCounterOrderDetailPK(RestaurantCounterOrderDetailPK restaurantCounterOrderDetailPK) {
this.restaurantCounterOrderDetailPK = restaurantCounterOrderDetailPK;
}
public RestaurantCounterOrder getRestaurantCounterOrder() {
return restaurantCounterOrder;
}
public void setRestaurantCounterOrder(RestaurantCounterOrder restaurantCounterOrder) {
this.restaurantCounterOrder = restaurantCounterOrder;
}
public FoodItem getFoodItem() {
return foodItem;
}
public void setFoodItem(FoodItem foodItem) {
this.foodItem = foodItem;
}
}
| 33.1 | 140 | 0.752266 |
91b10ba73d02568f452b7924160e097437e11bce | 2,192 | package com.bx.erp.view.activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.bx.erp.R;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
/**
* Created by WPNA on 2020/2/26.
*/
public class ReportLoss_Fragment extends BaseFragment1 {
@BindView(R.id.category)
LinearLayout category;
@BindView(R.id.linear_bottom)
LinearLayout linearBottom;
@BindView(R.id.null_view)
View nullView;
@BindView(R.id.add_reportloss_page)
FrameLayout addReportlossPage;
Unbinder unbinder;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.reportloss_fragment, container, false);
unbinder = ButterKnife.bind(this, view);
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
@OnClick({R.id.add_reportloss, R.id.cancel})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.add_reportloss:
category.setVisibility(View.GONE);
linearBottom.setVisibility(View.GONE);
addReportlossPage.setVisibility(View.VISIBLE);
nullView.setVisibility(View.VISIBLE);
setAnimation(addReportlossPage);
break;
case R.id.cancel:
category.setVisibility(View.VISIBLE);
linearBottom.setVisibility(View.VISIBLE);
addReportlossPage.setVisibility(View.GONE);
nullView.setVisibility(View.GONE);
setAnimation(addReportlossPage);
break;
}
}
}
| 30.027397 | 132 | 0.68385 |
a0b71f83a2e13c57d2e5a628d27ac9ecd351f56a | 3,019 | package businesslayer;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import datalayer.DatabaseConnection;
/**
* AppData is a middleware designed to allow users interaction with the database
* without allowing them to utilize the database directly.
*
*/
public class AppData {
/**
* The ArrayList of Person objects that is used to pass the data between the
* GUI and the database.
*/
private List<Person> people = new ArrayList<Person>();
/**
* The AppData instance that must be created only once.
*/
private static AppData appData = null;
/**
* Default constructor for AppData Object
*/
private AppData() {
}
/**
* Tests to see if the AppData has been initialized, and whether or not the
* necessary tables have been created in the database. If AppData is null,
* it creates the instance, and if either the database or the table are
* non-existent, it creates those as well.
*
* @return The AppData Object being instantiated.
*/
public static AppData getAppData() {
if (appData == null) {
appData = new AppData();
}
try {
DatabaseConnection.createDatabase("customers");
DatabaseConnection.createTable("Person");
} catch (SQLException e) {
e.printStackTrace();
}
return appData;
}
/**
* Inserts a person into the first empty row with a unique identity key. The
* identity key is set by the database and is not alterable by the user.
*
* @param person
* The Person object being called
*/
public void insertPerson(Person person) {
people.add(person);
try {
DatabaseConnection.insertPerson(person);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Selects a row from the Person table in the database and creates a usable
* Person object in the application structure.
*
* @param name
* The data we wish to select from the database
*
*/
public List<Person> selectPerson(String name) {
people.clear();
try {
for (Person person : DatabaseConnection.selectPerson(name)) {
people.add(person);
}
} catch (SQLException e) {
e.printStackTrace();
}
return people;
}
/**
* Creates a usable Array List of Person Objects from the Person table in
* the database.
*
*/
public List<Person> findAllPeople() {
people.clear();
try {
for (Person person : DatabaseConnection.findAllPeople()) {
people.add(person);
}
} catch (SQLException e) {
e.printStackTrace();
}
return people;
}
/**
* Deletes a Person Object from the database by the row ID provided
*
* @param id
* The distinct ID number of the record being deleted.
*/
public String deletePerson(int id) {
String message = "";
try {
message = DatabaseConnection.deletePerson(id);
} catch (SQLException e) {
e.printStackTrace();
}
return message;
}
} | 22.362963 | 81 | 0.643922 |
dc2048b6582acc36a91e9692029c403bc0e613df | 651 | package sorting;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class T141 {
private static List<Integer> intersect(int[] a, int[] b) {
Set<Integer> res = new HashSet<>();
int i = 0;
int j = 0;
while (i < a.length && j < b.length) {
if (a[i] == b[j]) {
res.add(a[i]);
i++;
j++;
} else if (a[i] < b[j]) {
i++;
} else {
j++;
}
}
return new ArrayList<>(res);
}
public static void main(String[] args) {
int[] a = {2, 3, 3, 5, 5, 6, 7, 7, 8, 12};
int[] b = {5, 5, 6, 8, 8, 9, 10, 10};
System.out.println((intersect(a, b).toString()));
}
}
| 19.147059 | 59 | 0.537634 |
97bceaff465ae1e07f9dc7e03bfe43475e41a705 | 1,109 | package in.himanshugawari.codeforces;
//131A - cAPS lOCK
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CapsLock {
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
br.close();
int c=0,d=0;
for(int i=0;i<s.length();i++){
if(Character.isUpperCase(s.charAt(i))){
c++;
}
}
boolean isAllUpperCase=false;
if(c==s.length()){
isAllUpperCase=true;
}
for(int i=0;i<s.length();i++){
if(Character.isLowerCase(s.charAt(0))){
if(Character.isUpperCase(s.charAt(i))){
d++;
}
}
}
boolean isLowerUpperCase=false;
if(d==s.length()-1){
isLowerUpperCase=true;
}
if(isAllUpperCase || isLowerUpperCase){
for(int i=0;i<s.length();i++){
System.out.print(Character.isUpperCase(s.charAt(i))?Character.toLowerCase(s.charAt(i)):Character.toUpperCase(s.charAt(i)));
}
}else{
System.out.println(s);
}
}
} | 26.404762 | 131 | 0.620379 |
1799982c8d0c7e851ee1bc8153fb09a5c0ca8166 | 779 | package com.example.yogi.database_login;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by YOGI on 3/22/2018.
*/
public class MyCoreDataBase extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyData";
public static final int VERSION = 1;
public MyCoreDataBase(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(MyTableData.DETAILS.CREATE_STATEMENT);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(MyTableData.DETAILS.DELETE_STATEMENT);
onCreate(db);
}
} | 25.966667 | 78 | 0.722721 |
9d92bf3f080e82254886f45b45c22e8b1c423886 | 4,297 | package tech.iosd.gemselections.Handicrafts;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by anonymous on 19/6/17.
*/
public class HandPlatesFragment extends Fragment {
private ImageView _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(tech.iosd.gemselections.R.layout.frag_hand_plates, container, false);
_1 = (ImageView)view.findViewById(tech.iosd.gemselections.R.id.handplate1);
_2 = (ImageView)view.findViewById(tech.iosd.gemselections.R.id.handplate2);
_3 = (ImageView)view.findViewById(tech.iosd.gemselections.R.id.handplate3);
_4 = (ImageView)view.findViewById(tech.iosd.gemselections.R.id.handplate4);
_5 = (ImageView)view.findViewById(tech.iosd.gemselections.R.id.handplate5);
_6 = (ImageView)view.findViewById(tech.iosd.gemselections.R.id.handplate6);
_7 = (ImageView)view.findViewById(tech.iosd.gemselections.R.id.handplate7);
_8 = (ImageView)view.findViewById(tech.iosd.gemselections.R.id.handplate8);
_9 = (ImageView)view.findViewById(tech.iosd.gemselections.R.id.handplate9);
_10 = (ImageView)view.findViewById(tech.iosd.gemselections.R.id.handplate10);
_11 = (ImageView)view.findViewById(tech.iosd.gemselections.R.id.handplate11);
_12 = (ImageView)view.findViewById(tech.iosd.gemselections.R.id.handplate12);
return view;
}
private void loadImage() {
InputStream is;
try {
is = getActivity().getAssets().open("images/gold-painted-plates-tiels/Marble-Tile-GPP01.jpg");
_1.setImageBitmap(BitmapFactory.decodeStream(is));
is = getActivity().getAssets().open("images/gold-painted-plates-tiels/Marble-Tile-GPP02.jpg");
_2.setImageBitmap(BitmapFactory.decodeStream(is));
is = getActivity().getAssets().open("images/gold-painted-plates-tiels/Marble-Tile-GPP03.jpg");
_3.setImageBitmap(BitmapFactory.decodeStream(is));
is = getActivity().getAssets().open("images/gold-painted-plates-tiels/MarbleTile-GPP-04.jpg");
_4.setImageBitmap(BitmapFactory.decodeStream(is));
is = getActivity().getAssets().open("images/gold-painted-plates-tiels/MarbleTile-GPP-05.jpg");
_5.setImageBitmap(BitmapFactory.decodeStream(is));
is = getActivity().getAssets().open("images/gold-painted-plates-tiels/Marble-Tile-GPP-06.jpg");
_6.setImageBitmap(BitmapFactory.decodeStream(is));
is = getActivity().getAssets().open("images/gold-painted-plates-tiels/Marble-Tile-GPP-07.jpg");
_7.setImageBitmap(BitmapFactory.decodeStream(is));
is = getActivity().getAssets().open("images/gold-painted-plates-tiels/Marble-Tile-GPP-08.jpg");
_8.setImageBitmap(BitmapFactory.decodeStream(is));
is = getActivity().getAssets().open("images/gold-painted-plates-tiels/Marble-Tile-GPP-09.jpg");
_9.setImageBitmap(BitmapFactory.decodeStream(is));
is = getActivity().getAssets().open("images/gold-painted-plates-tiels/Marble-Tile-GPP-10.jpg");
_10.setImageBitmap(BitmapFactory.decodeStream(is));
is = getActivity().getAssets().open("images/gold-painted-plates-tiels/Marble-Tile-GPP-11.jpg");
_11.setImageBitmap(BitmapFactory.decodeStream(is));
is = getActivity().getAssets().open("images/gold-painted-plates-tiels/Marble-Tile-GPP-12.jpg");
_12.setImageBitmap(BitmapFactory.decodeStream(is));
}catch (IOException e){
e.printStackTrace();
}
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
loadImage();
getActivity().setTitle("Plates And Tiles");
}
}
| 46.706522 | 123 | 0.69374 |
dc4e5a2f2ddfd1bb008d1bb9f2c903bad3d6217f | 109 | package algorithms.anfis;
/**
*
* @author Mercedes Vald�s Vela
*/
public class LeastSquareEstimator {
}
| 10.9 | 35 | 0.697248 |
4c47404696d5c5439abc8d95f19f82056923801a | 8,201 | package com.trivadis.plsql.formatter.settings.tests.rules;
import com.trivadis.plsql.formatter.settings.ConfiguredTestFormatter;
import org.junit.jupiter.api.Test;
import java.io.IOException;
public class A16_line_break_for_multiline_parents extends ConfiguredTestFormatter {
@Test
public void single_line_select() {
var sql = """
select deptno, empno, ename from emp where empno > 7000 order by empno;
""";
formatAndAssert(sql);
}
@Test
public void multi_line_select() throws IOException {
var input = """
select deptno, empno, ename from emp
where empno > 7000 order by empno;
""";
var actual = formatter.format(input);
var expected = """
select deptno, empno, ename
from emp
where empno > 7000
order by empno;
""";
assertEquals(expected, actual);
}
@Test
public void single_line_insert() {
var sql = """
insert into t (c1, c2, c3) values ('1', '2', '3');
""";
formatAndAssert(sql);
}
@Test
public void multi_line_single_table_insert() throws IOException {
var input = """
insert into mytable t (a, b, c, d) values ('a', 'b', 'c', 'd') return a, b, c, d
into l_a, l_b, l_c, l_d log errors into mytable_errors ('bad') reject limit 10;
""";
var actual = formatter.format(input);
var expected = """
insert into mytable t (a, b, c, d)
values ('a', 'b', 'c', 'd')
return a, b, c, d
into l_a, l_b, l_c, l_d
log errors into mytable_errors ('bad') reject limit 10;
""";
assertEquals(expected, actual);
}
@Test
public void multi_line_multi_table_insert_all() throws IOException {
var input = """
insert all into t1 (c1, c2) values (c1, c2) into t2 (c1, c2) values (c1, c2)
into t3 (c1, c2) values (c1, c2) log errors
into mytable_errors ('bad') reject limit 10 select c1, c2 from t4;
""";
var actual = formatter.format(input);
var expected = """
insert all
into t1 (c1, c2)
values (c1, c2)
into t2 (c1, c2)
values (c1, c2)
into t3 (c1, c2)
values (c1, c2)
log errors
into mytable_errors ('bad') reject limit 10
select c1, c2 from t4;
""";
assertEquals(expected, actual);
}
@Test
public void multi_line_multi_table_insert_conditional() throws IOException {
var input = """
insert first when c5 = 1 then into t1 (c1, c2) values (c1, c2) when c3 > 2000 then into t2 (c1, c2)
values (c1, c2) when c7 < 1 and c3 > 1500 or (c8 > 7 or c5 > 2) then into t3 (c1, c2)
values (c1, c2) log errors into mytable_errors ('bad') reject limit 10
select c1, c2 from t4;
""";
var actual = formatter.format(input);
var expected = """
insert first
when c5 = 1 then
into t1 (c1, c2)
values (c1, c2)
when c3 > 2000 then
into t2 (c1, c2)
values (c1, c2)
when c7 < 1
and c3 > 1500
or (c8 > 7 or c5 > 2)
then
into t3 (c1, c2)
values (c1, c2)
log errors into mytable_errors ('bad') reject limit 10
select c1, c2 from t4;
""";
assertEquals(expected, actual);
}
@Test
public void single_line_delete() {
var sql = """
delete from t where 1 = 1 return c1 into l_c1 log errors into error_table reject limit 10;
""";
formatAndAssert(sql);
}
@Test
public void multi_line_delete() throws IOException {
var input = """
delete from t where 1 = 1 return c1 into l_c1 log errors into error_table
reject limit 10;
""";
var actual = formatter.format(input);
var expected = """
delete from t
where 1 = 1
return c1 into l_c1
log errors into error_table
reject limit 10;
""";
assertEquals(expected, actual);
}
@Test
public void multi_line_select_list() throws IOException {
var input = """
select deptno, empno, ename,
hiredate from emp;
""";
var actual = formatter.format(input);
var expected = """
select deptno,
empno,
ename,
hiredate
from emp;
""";
assertEquals(expected, actual);
}
@Test
public void multi_line_order_by_list() throws IOException {
var input = """
select * from emp order by deptno, empno, ename,
hiredate;
""";
var actual = formatter.format(input);
var expected = """
select *
from emp
order by deptno,
empno,
ename,
hiredate;
""";
assertEquals(expected, actual);
}
@Test
public void multi_line_group_by_list() throws IOException {
var input = """
select count(*) from emp group by deptno, empno, ename,
hiredate;
""";
var actual = formatter.format(input);
var expected = """
select count(*)
from emp
group by deptno,
empno,
ename,
hiredate;
""";
assertEquals(expected, actual);
}
@Test
public void multi_line_select_into() throws IOException {
var input = """
begin
select empno, ename, job, mgr, hiredate, sal, comm, deptno
into l_empno, l_ename, l_job, l_mgr, l_hiredate, l_sal, l_comm,
l_deptno
from emp;
end;
/
""";
var actual = formatter.format(input);
var expected = """
begin
select empno, ename, job, mgr, hiredate, sal, comm, deptno
into l_empno,
l_ename,
l_job,
l_mgr,
l_hiredate,
l_sal,
l_comm,
l_deptno
from emp;
end;
/
""";
assertEquals(expected, actual);
}
@Test
public void single_line_merge() {
var sql = """
merge into t using s on (s.id = t.id) when not matched then insert (t.id, t.c1) values (s.id, s.c1) where s.c3 = 3;
""";
formatAndAssert(sql);
}
@Test
public void multi_line_merge() throws IOException {
var input = """
merge into t
using s on (s.id = t.id) when not matched then insert (t.id, t.c1) values (s.id, s.c1) where s.c3 = 3;
""";
var actual = formatter.format(input);
var expected = """
merge into t
using s
on (s.id = t.id)
when not matched then
insert (t.id, t.c1)
values (s.id, s.c1)
where s.c3 = 3;
""";
assertEquals(expected, actual);
}
}
| 33.068548 | 131 | 0.451896 |
3082ecc50893ea56c959c18eaf643edb1867f1db | 1,012 | /**
* Given an array and a value, remove all instances of that value in place and
* return the new length.
*
* The order of elements can be changed. It doesn't matter what you leave
* beyond the new length.
*
* Tags: Array, Two pointers
*/
class RemoveElement {
public static void main(String[] args) {
RemoveElement r = new RemoveElement();
// int[] A = { 1 };
// int[] A = { 1, 2, 3, 4 };
int[] A = { 1, 2, 1 };
int elem = 1;
System.out.println(r.removeElement(A, elem));
}
/**
* Order is not important
* Just move the last elem to removed position
*/
public int removeElement(int[] A, int elem) {
if (A == null || A.length == 0) return 0;
int i = 0;
int j = A.length;
while (i < j) {
if (A[i] == elem) {
A[i] = A[j - 1]; // move last element
j--; // decrease length
} else i++; // move on
}
return j;
}
}
| 27.351351 | 79 | 0.500988 |
348163964c663813fbad11ebad850d592ea9606b | 3,330 | package com.cafe.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cafe.annotation.LoginRequired;
import com.cafe.dto.FollowDto;
import com.cafe.dto.LikeDto;
import com.cafe.service.FollowService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Authorization;
@CrossOrigin("*")
@RestController
@RequestMapping("/api/follow")
public class FollowController {
@Autowired
private FollowService service;
@ApiOperation(value = "이전에 팔로우 눌렀는지 체크(눌렀으면 1,안눌렀으면 0)", authorizations = { @Authorization(value="jwt_token") })
@GetMapping("/check/{uid}/{followingid}")
@LoginRequired
public int check(@PathVariable String uid, @PathVariable String followingid) {
FollowDto follow = new FollowDto();
follow.setUid(uid);
follow.setFollowingid(followingid);
return service.check(follow);
}
@ApiOperation(value = "팔로워 수")
@GetMapping("/count/follower/{followingid}")
public int countFollower(@PathVariable String followingid) {
System.out.println("count follower");
return service.countFollower(followingid);
}
@ApiOperation(value = "팔로잉 수")
@GetMapping("/count/following/{uid}")
public int countFollowing(@PathVariable String uid) {
System.out.println("count following");
return service.countFollowing(uid);
}
@ApiOperation(value = "팔로워 리스트")
@GetMapping("/list/follower/{followingid}")
public List<String> selectFollower(@PathVariable String followingid) {
System.out.println("select follower");
System.out.println("followingid: " + followingid);
List<String> follwerList = service.selectFollower(followingid);
for(String s: follwerList) {
System.out.println(s);
}
return follwerList;
}
@ApiOperation(value = "팔로잉 리스트")
@GetMapping("/list/following/{uid}")
public List<String> selectFollowing(@PathVariable String uid) {
System.out.println("select following");
System.out.println("uid: " + uid);
List<String> follwingList = service.selectFollowing(uid);
for(String s: follwingList) {
System.out.println(s);
}
return follwingList;
}
@ApiOperation(value = "팔로우 추가", authorizations = { @Authorization(value="jwt_token") })
@PostMapping
@LoginRequired
public String insert(@RequestBody FollowDto follow) {
System.out.println("insert follow");
if(service.insert(follow)>0) {
return "Success";
}
return "Failure";
}
@ApiOperation(value = "팔로우 삭제", authorizations = { @Authorization(value="jwt_token") })
@DeleteMapping("/delete/{uid}/{followingid}")
@LoginRequired
public String delete(@PathVariable String uid, @PathVariable String followingid) {
System.out.println("delete follow");
FollowDto follow = new FollowDto();
follow.setUid(uid);
follow.setFollowingid(followingid);
if(service.delete(follow)>0) {
return "Success";
}
return "Failure";
}
}
| 31.415094 | 113 | 0.755556 |
fa6c4ab954259c3799504247d7d146536a2e91b3 | 1,028 | package com.controller.before;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.po.Buser;
import com.service.before.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/register")
public String register(@ModelAttribute Buser buser,Model model, HttpSession session, String code) {
return userService.register(buser, model, session, code);
}
@RequestMapping("/login")
public String login(@ModelAttribute Buser buser,Model model, HttpSession session, String code) {
return userService.login(buser, model, session, code);
}
@RequestMapping("/exit")
public String exit(HttpSession session) {
session.invalidate();
return "forward:/before";
}
}
| 31.151515 | 100 | 0.79572 |
ea40b22d4947916bb66a5cab62f9755b041fcc9b | 8,362 | package com.example.jdocter.parstagram;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import static android.app.Activity.RESULT_OK;
public class CreateFragment extends Fragment {
private ImageView ivPostImage;
private Button btnShare;
private EditText etCaption;
private Bitmap bitmapPostImage;
private EditText etLocation;
interface Callback {
/**
* To be called when a post was successfully created.
*/
void onPostCreated();
}
/**
* It's a "mask" to our activity so that way we can update it, and not be tightly coupled to it.
*/
private Callback callback;
// private static final String imagePath = "/Users/jdocter/Downloads/twitter-logo.png";
// photo declarations
public String photoFileName = "photo.jpg";
static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 12345;
public final String APP_TAG = "MyCustomApp";
public File photoFile;
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Callback) {
callback = (Callback) context;
}
}
@Override
public void onDetach() {
super.onDetach();
callback = null;
}
// The onCreateView method is called when Fragment should create its View object hierarchy,
// either dynamically or via XML layout inflation.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
// Defines the xml file for the fragment
onLaunchCamera();
return inflater.inflate(R.layout.fragment_create, parent, false);
}
// This event is triggered soon after onCreateView().
// Any view setup should occur here. E.g., view lookups and attaching view listeners.
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Setup any handles to view objects here
// EditText etFoo = (EditText) view.findViewById(R.id.etFoo);
ivPostImage = view.findViewById(R.id.ivCreatePostImage);
btnShare = view.findViewById(R.id.btnShare);
etCaption = view.findViewById(R.id.etCaption);
etLocation = view.findViewById(R.id.etLocation);
btnShare.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String caption = etCaption.getText().toString();
final String location = etLocation.getText().toString();
final ParseUser user = ParseUser.getCurrentUser();
final File file;
// try converting bitmap to parsefile
try {
file = getImageFile(bitmapPostImage);
final ParseFile parseFile = new ParseFile(file);
// create post
createPost(caption, parseFile, user,location);
} catch (IOException e) {
Log.e("MainActivity","Bit map could not be converted to ParseFile");
e.printStackTrace();
}
}
});
}
// resizes bitmap and writes to file
public File getImageFile(Bitmap bitmap) throws IOException {
// Configure byte output stream
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
// Compress the image further
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
// Create a new file for the resized bitmap (`getPhotoFileUri` defined above)
File resizedUri = getPhotoFileUri(photoFileName + "_resized");
File resizedFile = new File(resizedUri.getPath());
resizedFile.createNewFile();
FileOutputStream fos = new FileOutputStream(resizedFile);
// Write the bytes of the bitmap to file
fos.write(bytes.toByteArray());
fos.close();
return resizedFile;
}
public void onLaunchCamera() {
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Create a File reference to access to future access
photoFile = getPhotoFileUri(photoFileName);
// wrap File object into a content provider
// required for API >= 24
// See https://guides.codepath.com/android/Sharing-Content-with-Intents#sharing-files-with-api-24-or-higher
Uri fileProvider = FileProvider.getUriForFile(getActivity(), "com.codepath.fileprovider", photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileProvider);
// If you call startActivityForResult() using an intent that no app can handle, your app will crash.
// So as long as the result is not null, it's safe to use the intent.
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
// Start the image capture intent to take photo
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
}
// Returns the File for a photo stored on disk given the fileName
public File getPhotoFileUri(String fileName) {
// Get safe storage directory for photos
// Use `getExternalFilesDir` on Context to access package-specific directories.
// This way, we don't need to request external read/write runtime permissions.
File mediaStorageDir = new File(getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES), APP_TAG);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()) {
Log.d(APP_TAG, "failed to create directory");
}
// Return the file target for the photo based on filename
File file = new File(mediaStorageDir.getPath() + File.separator + fileName);
return file;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// by this point we have the camera photo on disk
bitmapPostImage = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
// RESIZE BITMAP, see section below
BitmapScaler.scaleToFitWidth(bitmapPostImage, 300);
BitmapScaler.scaleToFitHeight(bitmapPostImage, 100);
// Load the taken image into a preview
ivPostImage.setImageBitmap(bitmapPostImage);
} else { // Result was a failure
Toast.makeText(getActivity(), "Picture wasn't taken!", Toast.LENGTH_SHORT).show();
}
}
}
// TODO
private void createPost(String caption, ParseFile image, ParseUser user, String location) {
final com.example.jdocter.parstagram.model.Post newPost = new com.example.jdocter.parstagram.model.Post();
newPost.setDescription(caption);
//newPost.setImage(image);
newPost.setUser(user);
newPost.setImage(image);
newPost.setLocationKey(location);
newPost.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e==null) {
Log.d("MainActivity", "Post success");
callback.onPostCreated();
} else {
Log.e("MainActivity", "Post Failure");
e.printStackTrace();
}
}
});
}
}
| 37.837104 | 116 | 0.654748 |
5b13f6e2056d2d9b326c8b800afec0800e743e1a | 269 | package de.jeha.j7.core;
/**
* @author jenshadlich@googlemail.com
*/
public enum OpState {
UP(true),
DOWN(false);
private final boolean up;
OpState(boolean up) {
this.up = up;
}
public boolean isUp() {
return up;
}
}
| 12.227273 | 37 | 0.561338 |
90699543b3187c9598b3ce0c04e480cbedaabeed | 540 | package com.mizo0203.hoshiguma.repo.line.messaging.data.template;
import com.mizo0203.hoshiguma.repo.line.messaging.data.action.Action;
public class ButtonTemplate extends Template {
public final String text;
public final Action[] actions;
public String thumbnailImageUrl;
public String imageAspectRatio;
public String imageSize;
public String imageBackgroundColor;
public String title;
public ButtonTemplate(String text, Action[] actions) {
super("buttons");
this.text = text;
this.actions = actions;
}
}
| 25.714286 | 69 | 0.762963 |
c9eda49f1166b592254047b78f18e35236683f97 | 593 | public void solve() {
int n = in.ni(), m = in.ni();
color = new int[m];
node = new int[n];
visited = new boolean[n];
graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int u = in.ni() - 1, v = in.ni() - 1;
graph.get(u).add(new Edge(i, v));
}
for (int u = 0; u < n; u++) {
if (!visited[u]) {
dfs(u);
}
}
out.println(cycle ? 2 : 1);
for (int i = 0; i < m; i++) {
out.print(color[i]);
out.print(' ');
}
} | 24.708333 | 45 | 0.403035 |
57a0e7337415f0fb5542e9c4467617bd8dda2ed8 | 543 | /**
* This interface has all of the bean info accessor methods.
*
* @Generated
*/
package org.netbeans.modules.portalpack.servers.websynergy.dd.lp.impl440;
public interface CustomUserAttributeInterface {
public void setName(int index, String value);
public String getName(int index);
public int sizeName();
public void setName(String[] value);
public String[] getName();
public int addName(String value);
public int removeName(String value);
public void setCustomClass(String value);
public String getCustomClass();
}
| 18.724138 | 73 | 0.74954 |
d2066cc70c93f7a69851072f04c13fec444a4def | 3,586 | //
// ========================================================================
// Copyright (c) 1995-2022 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.util;
import java.net.CookieManager;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Implementation of {@link CookieStore} that delegates to an instance created by {@link CookieManager}
* via {@link CookieManager#getCookieStore()}.
*/
public class HttpCookieStore implements CookieStore
{
private final CookieStore delegate;
public HttpCookieStore()
{
delegate = new CookieManager().getCookieStore();
}
@Override
public void add(URI uri, HttpCookie cookie)
{
delegate.add(uri, cookie);
}
@Override
public List<HttpCookie> get(URI uri)
{
return delegate.get(uri);
}
@Override
public List<HttpCookie> getCookies()
{
return delegate.getCookies();
}
@Override
public List<URI> getURIs()
{
return delegate.getURIs();
}
@Override
public boolean remove(URI uri, HttpCookie cookie)
{
return delegate.remove(uri, cookie);
}
@Override
public boolean removeAll()
{
return delegate.removeAll();
}
public static List<HttpCookie> matchPath(URI uri, List<HttpCookie> cookies)
{
if (cookies == null || cookies.isEmpty())
return Collections.emptyList();
List<HttpCookie> result = new ArrayList<>(4);
String path = uri.getPath();
if (path == null || path.trim().isEmpty())
path = "/";
for (HttpCookie cookie : cookies)
{
String cookiePath = cookie.getPath();
if (cookiePath == null)
{
result.add(cookie);
}
else
{
// RFC 6265, section 5.1.4, path matching algorithm.
if (path.equals(cookiePath))
{
result.add(cookie);
}
else if (path.startsWith(cookiePath))
{
if (cookiePath.endsWith("/") || path.charAt(cookiePath.length()) == '/')
result.add(cookie);
}
}
}
return result;
}
public static class Empty implements CookieStore
{
@Override
public void add(URI uri, HttpCookie cookie)
{
}
@Override
public List<HttpCookie> get(URI uri)
{
return Collections.emptyList();
}
@Override
public List<HttpCookie> getCookies()
{
return Collections.emptyList();
}
@Override
public List<URI> getURIs()
{
return Collections.emptyList();
}
@Override
public boolean remove(URI uri, HttpCookie cookie)
{
return false;
}
@Override
public boolean removeAll()
{
return false;
}
}
}
| 25.076923 | 103 | 0.539598 |
e2732a482d04a61602b9b3147dc722d253cbbdd3 | 838 | package com.charmyin.other;
import org.junit.Test;
public class TestValueAndReference {
void duplicate (int a, int b, int c)
{
a*=2;
b*=2;
c*=2;
}
void doubleString(String a, String b, String c){
a = a+a;
b+=b;
c+=c;
a="bbbbb";
}
@Test
public void main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
System.out.println("x="+x+";y="+y+";z="+z);
String a=new String("a"), b="b", c="c";
doubleString(a, b, c);
System.out.println("a="+a+";b="+b+";c="+c);
User user = new User();
user.name="name";
user.age="23";
changeUser(user);
System.out.println(user.name+user.age);
// cout << "x=" << x << ", y=" << y << ", z=" << z;
}
void changeUser(User user){
user.name="nonono";
user.age="yeyeye";
}
}
class User{
public String name ;
public String age;
} | 13.516129 | 52 | 0.540573 |
31e1796788dedd2eee46decc30ac25d86203f37f | 1,747 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.sdk.language;
import com.intellij.formatting.*;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.sdk.language.psi.SimpleTypes;
import org.jetbrains.annotations.*;
public class SimpleFormattingModelBuilder implements FormattingModelBuilder {
@NotNull
@Override
public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {
return FormattingModelProvider
.createFormattingModelForPsiFile(element.getContainingFile(),
new SimpleBlock(element.getNode(),
Wrap.createWrap(WrapType.NONE, false),
Alignment.createAlignment(),
createSpaceBuilder(settings)),
settings);
}
private static SpacingBuilder createSpaceBuilder(CodeStyleSettings settings) {
return new SpacingBuilder(settings, SimpleLanguage.INSTANCE)
.around(SimpleTypes.SEPARATOR)
.spaceIf(settings.getCommonSettings(SimpleLanguage.INSTANCE.getID()).SPACE_AROUND_ASSIGNMENT_OPERATORS)
.before(SimpleTypes.PROPERTY)
.none();
}
@Nullable
@Override
public TextRange getRangeAffectingIndent(PsiFile file, int offset, ASTNode elementAtOffset) {
return null;
}
}
| 43.675 | 140 | 0.631368 |
1007f631d7a66e9996dccf0655fabbd225c1ed66 | 192 | package PACKAGE_NAME;
public class Factorial {
public static Long factorial (int n) {
if (n == 0) {
return 1l;
}
return n * factorial(n - 1);
}
}
| 16 | 42 | 0.510417 |
da0c918efd0765912e8158c03c580359f737f8ba | 1,145 | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.viterium.viteriumwallet;
import android.util.Base64;
import android.app.Activity;
import android.app.Application;
import androidx.annotation.CallSuper;
import android.content.Context;
import androidx.multidex.MultiDex;
import io.flutter.view.FlutterMain;
/**
* Flutter implementation of {@link android.app.Application}, managing
* application-level global initializations.
*/
public class MultidexApplication extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
@Override
@CallSuper
public void onCreate() {
super.onCreate();
FlutterMain.startInitialization(this);
}
private Activity mCurrentActivity = null;
public Activity getCurrentActivity() {
return mCurrentActivity;
}
public void setCurrentActivity(Activity mCurrentActivity) {
this.mCurrentActivity = mCurrentActivity;
}
} | 26.627907 | 73 | 0.736245 |
2661a14696224932b8bb3e54a3444b06014bcc96 | 2,204 | package com.spotinst.sdkjava.model;
import com.fasterxml.jackson.annotation.JsonInclude;
/**
* @author Caduri Katzav
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiDeleteGroupRequest {
//region Members
private StatefulDeallocationConfig statefulDeallocation;
private AmiBackupConfig amiBackup;
private BeanstalkDeleteConfig beanstalk;
//endregion
//region Getters & Setters
public StatefulDeallocationConfig getStatefulDeallocation() {
return statefulDeallocation;
}
public void setStatefulDeallocation(StatefulDeallocationConfig statefulDeallocation) {
this.statefulDeallocation = statefulDeallocation;
}
public AmiBackupConfig getAmiBackup() {
return amiBackup;
}
public void setAmiBackup(AmiBackupConfig amiBackup) {
this.amiBackup = amiBackup;
}
public BeanstalkDeleteConfig getBeanstalk() {
return beanstalk;
}
public void setBeanstalk(BeanstalkDeleteConfig beanstalk) {
this.beanstalk = beanstalk;
}
//endregion
//region Builder class
public static class Builder {
private ApiDeleteGroupRequest deleteRequest;
private Builder() {
this.deleteRequest = new ApiDeleteGroupRequest();
}
public static ApiDeleteGroupRequest.Builder get() {
ApiDeleteGroupRequest.Builder builder = new ApiDeleteGroupRequest.Builder();
return builder;
}
public ApiDeleteGroupRequest.Builder setStatefulDeallocation(final StatefulDeallocationConfig statefulDeallocation) {
deleteRequest.setStatefulDeallocation(statefulDeallocation);
return this;
}
public ApiDeleteGroupRequest.Builder setAmiBackup(final AmiBackupConfig amiBackup) {
deleteRequest.setAmiBackup(amiBackup);
return this;
}
public ApiDeleteGroupRequest.Builder setBeanstalk(final BeanstalkDeleteConfig beanstalk) {
deleteRequest.setBeanstalk(beanstalk);
return this;
}
public ApiDeleteGroupRequest build() {
return deleteRequest;
}
}
//endregion
}
| 29 | 125 | 0.690109 |
750055f32212450bd446bbb753b104456ff45af3 | 2,568 | package com.chen.entity;
import java.io.Serializable;
import java.util.Date;
/**
* Created by handsome programmer.
* User: chen
* Date: 2019/3/11
* Time: 20:50
* Description: 商品类别
*
* @author chen
*/
public class ProductCategory extends Base implements Serializable {
/**
* 商品类别id
*/
private Integer productCategoryId;
/**
* 店铺id
*/
private Integer shopId;
/**
* 商品类别名称
*/
private String productCategoryName;
/**
* 商品类别描述
*/
private String productCategoryDescription;
/**
* 权重
*/
private Integer priority;
/**
* 创建时间
*/
private Date createTime;
/**
* 最后编辑时间
*/
private Date lastEditTime;
@Override
public String toString() {
return "ProductCategory{" +
"productCategoryId=" + productCategoryId +
", shopId=" + shopId +
", productCategoryName='" + productCategoryName + '\'' +
", productCategoryDescription='" + productCategoryDescription + '\'' +
", priority=" + priority +
", createTime=" + createTime +
", lastEditTime=" + lastEditTime +
'}';
}
public Integer getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(Integer productCategoryId) {
this.productCategoryId = productCategoryId;
}
public Integer getShopId() {
return shopId;
}
public void setShopId(Integer shopId) {
this.shopId = shopId;
}
public String getProductCategoryName() {
return productCategoryName;
}
public void setProductCategoryName(String productCategoryName) {
this.productCategoryName = productCategoryName;
}
public String getProductCategoryDescription() {
return productCategoryDescription;
}
public void setProductCategoryDescription(String productCategoryDescription) {
this.productCategoryDescription = productCategoryDescription;
}
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getLastEditTime() {
return lastEditTime;
}
public void setLastEditTime(Date lastEditTime) {
this.lastEditTime = lastEditTime;
}
}
| 21.4 | 86 | 0.607866 |
1f059396e02931e84958f6287a58150bbcbf1a36 | 19,812 | /*
* Copyright 2008-2020 Hippo B.V. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hippoecm.frontend.plugins.cms.admin.groups;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import javax.jcr.RepositoryException;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.extensions.breadcrumb.IBreadCrumbModel;
import org.apache.wicket.extensions.breadcrumb.IBreadCrumbParticipant;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.model.util.MapModel;
import org.hippoecm.frontend.dialog.Confirm;
import org.hippoecm.frontend.dialog.HippoForm;
import org.hippoecm.frontend.dialog.IDialogService;
import org.hippoecm.frontend.form.PostOnlyForm;
import org.hippoecm.frontend.model.ReadOnlyModel;
import org.hippoecm.frontend.plugin.IPluginContext;
import org.hippoecm.frontend.plugins.cms.admin.AdminBreadCrumbPanel;
import org.hippoecm.frontend.plugins.cms.admin.SecurityManagerHelper;
import org.hippoecm.frontend.plugins.cms.admin.permissions.PermissionBean;
import org.hippoecm.frontend.plugins.cms.admin.permissions.ViewDomainActionLink;
import org.hippoecm.frontend.plugins.cms.admin.permissions.ViewPermissionLinkLabel;
import org.hippoecm.frontend.plugins.cms.admin.userroles.DetachableUserRole;
import org.hippoecm.frontend.plugins.cms.admin.userroles.ViewUserRoleLinkLabel;
import org.hippoecm.frontend.plugins.cms.admin.users.DetachableUser;
import org.hippoecm.frontend.plugins.cms.admin.users.User;
import org.hippoecm.frontend.plugins.cms.admin.users.ViewUserLinkLabel;
import org.hippoecm.frontend.plugins.cms.admin.widgets.AjaxLinkLabel;
import org.hippoecm.frontend.plugins.standards.panelperspective.breadcrumb.PanelPluginBreadCrumbLink;
import org.hippoecm.frontend.session.UserSession;
import org.hippoecm.frontend.util.EventBusUtils;
import org.hippoecm.repository.api.HippoSession;
import org.onehippo.cms7.event.HippoEventConstants;
import org.onehippo.repository.security.SecurityConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bloomreach.xm.repository.security.AuthRole;
import com.bloomreach.xm.repository.security.DomainAuth;
import com.bloomreach.xm.repository.security.UserRole;
import com.bloomreach.xm.repository.security.UserRolesProvider;
/**
* Panel showing information regarding the groups.
*/
public class ViewGroupPanel extends AdminBreadCrumbPanel {
private static final Logger log = LoggerFactory.getLogger(ViewGroupPanel.class);
private final IPluginContext context;
private final Group group;
private final PermissionsListView permissionsListView;
private final GroupMembersListView groupMembersListView;
private final UserRolesListView userRolesListView;
private final AddUserRolePanel addUserRolePanel;
private final boolean isSecurityUserAdmin;
private final IDialogService dialogService;
public ViewGroupPanel(final String id, final IPluginContext context, final IBreadCrumbModel breadCrumbModel,
final Group group) {
super(id, breadCrumbModel);
this.context = context;
final HippoSession session = UserSession.get().getJcrSession();
isSecurityUserAdmin = session.isUserInRole(SecurityConstants.USERROLE_SECURITY_USER_ADMIN);
this.group = group;
dialogService = context.getService(IDialogService.class.getName(), IDialogService.class);
final IModel<Group> groupModel = Model.of(group);
add(new Label("view-group-panel-title", new StringResourceModel("group-view-title", this).setModel(groupModel)));
// actions
final PanelPluginBreadCrumbLink edit = new PanelPluginBreadCrumbLink("edit-group", breadCrumbModel) {
protected IBreadCrumbParticipant getParticipant(final String componentId) {
return new EditGroupPanel(componentId, breadCrumbModel, groupModel);
}
};
edit.setVisible(isSecurityUserAdmin && !group.isExternal() && !group.isSystem());
add(edit);
final PanelPluginBreadCrumbLink members = new PanelPluginBreadCrumbLink("set-group-members", breadCrumbModel) {
@Override
protected IBreadCrumbParticipant getParticipant(final String componentId) {
return new SetMembersPanel(componentId, breadCrumbModel, groupModel);
}
};
members.setVisible(isSecurityUserAdmin && !group.isExternal() && !group.isSystem());
add(members);
final AjaxLinkLabel deleteGroupLabel = new AjaxLinkLabel("delete-group", new ResourceModel("group-delete")) {
@Override
public void onClick(final AjaxRequestTarget target) {
final Confirm confirm = new Confirm(
getString("group-delete-title", groupModel),
getString("group-delete-text", groupModel)
).ok(() -> {
deleteGroup(group);
});
dialogService.show(confirm);
}
};
deleteGroupLabel.setVisible(isSecurityUserAdmin && !group.isExternal() && !group.isSystem());
add(deleteGroupLabel);
// common group properties
add(new Label("groupname", group.getGroupname())); // groups cannot be renamed, so no model needed
add(new Label("description", ReadOnlyModel.of(group::getDescription)));
userRolesListView = new UserRolesListView("userroles", context);
add(userRolesListView);
addUserRolePanel = new AddUserRolePanel("add-userroles");
addUserRolePanel.setVisible(isSecurityUserAdmin && !group.isSystem());
add(addUserRolePanel);
permissionsListView = new PermissionsListView("permissions");
add(permissionsListView);
final Label groupMembersLabel = new Label("group-members-label",
new StringResourceModel("group-members-label", this).setModel(groupModel));
add(groupMembersLabel);
groupMembersListView = new GroupMembersListView("groupmembers", context);
add(groupMembersListView);
// add form with markup id setter so it can be updated via ajax
final Form<?> form = new PostOnlyForm<>("back-form");
form.setOutputMarkupId(true);
add(form);
// add a cancel/back button
form.add(new AjaxButton("back-button") {
@Override
protected void onSubmit(final AjaxRequestTarget target, final Form form) {
// one up
final List<IBreadCrumbParticipant> all = breadCrumbModel.allBreadCrumbParticipants();
breadCrumbModel.setActive(all.get(all.size() - 2));
}
}.setDefaultFormProcessing(false));
}
@Override
public IModel<String> getTitle(Component component) {
return new StringResourceModel("group-view-title", component).setModel(Model.of(group));
}
@Override
public void onActivate(IBreadCrumbParticipant previous) {
super.onActivate(previous);
groupMembersListView.updateMembers();
}
private void deleteGroup(final Group groupToDelete) {
final String groupName = groupToDelete.getGroupname();
try {
groupToDelete.delete();
activateParentAndDisplayInfo(getString("group-removed", Model.of(groupToDelete)));
} catch (RepositoryException e) {
error(getString("group-remove-failed", Model.of(groupToDelete)));
log.error("Unable to delete group '{}' : ", groupName, e);
redraw();
}
}
/**
* Delete a member from the list of group members.
*
* @param userName The userName of the user which is a member of the Group.
*/
private void deleteGroupMembership(final String userName) {
try {
group.removeMembership(userName);
EventBusUtils.post("remove-user-from-group", HippoEventConstants.CATEGORY_GROUP_MANAGEMENT,
"removed user " + userName + " from group " + group.getGroupname());
info(getString("group-member-removed"));
} catch (RepositoryException e) {
error(getString("group-member-remove-failed"));
log.error("Failed to remove memberships", e);
}
redraw();
}
private void removeUserRole(final String userRoleToRemove) {
final MapModel nameModel = new MapModel<>(Collections.singletonMap("name", userRoleToRemove));
try {
group.removeUserRole(userRoleToRemove);
userRolesListView.updateUserRoles();
addUserRolePanel.updateUserRoleChoice();
EventBusUtils.post("remove-userrole", HippoEventConstants.CATEGORY_GROUP_MANAGEMENT,
String.format("removed user role '%s' from group '%s'", userRoleToRemove, group.getGroupname()));
info(getString("userrole-removed", nameModel));
} catch (RepositoryException e) {
error(getString("userrole-remove-failed"));
log.error("Failed to remove userrole", e);
}
redraw();
}
/**
* List view for showing the permissions of the group.
*/
private final class PermissionsListView extends ListView<PermissionBean> {
private final IModel<List<PermissionBean>> permissionBeansListModel =
new LoadableDetachableModel<List<PermissionBean>>() {
@Override
protected List<PermissionBean> load() {
return PermissionBean.forGroup(group);
}
};
PermissionsListView(final String id) {
super(id);
setDefaultModel(permissionBeansListModel);
setReuseItems(false);
}
@Override
protected void populateItem(final ListItem<PermissionBean> item) {
final PermissionBean permissionBean = item.getModelObject();
final DomainAuth domain = permissionBean.getDomain().getObject();
final AuthRole authRole = permissionBean.getAuthRole();
final String roleName = authRole.getRole();
item.add(new ViewDomainActionLink("securityDomain",context, ViewGroupPanel.this, permissionBean.getDomain(),
Model.of(domain.getName())));
item.add(new Label("domain-folder", domain.getFolderPath()));
item.add(new ViewPermissionLinkLabel("permission", permissionBean.getDomain(), authRole.getName(),
ViewGroupPanel.this, context));
item.add(new Label("role", roleName));
}
}
/**
* List view for the userroles.
*/
private final class UserRolesListView extends ListView<String> {
private final IPluginContext context;
UserRolesListView(final String id, final IPluginContext context) {
super(id, new ArrayList<>(group.getUserRoles()));
this.context = context;
setReuseItems(false);
}
@Override
protected void populateItem(final ListItem<String> item) {
UserRolesProvider userRolesProvider =
SecurityManagerHelper.getUserRolesProvider();
final String userRoleName = item.getModelObject();
final UserRole userRole = userRolesProvider.getRole(userRoleName);
if (userRole == null) {
item.add(new Label("name", Model.of(userRoleName)));
item.add(new Label("description"));
} else {
final DetachableUserRole userRoleModel = new DetachableUserRole(userRole);
item.add(new ViewUserRoleLinkLabel("name", userRoleModel, ViewGroupPanel.this, context));
item.add(new Label("description", Model.of(userRoleModel.getObject().getDescription())));
}
if (isSecurityUserAdmin && !group.isSystem()) {
item.add(new RemoveUserRoleActionLinkLabel("remove-userrole",
new ResourceModel("userrole-remove-action"), userRoleName));
} else {
item.add(new Label("remove-userrole", ""));
}
}
void updateUserRoles() {
setModelObject(group.getUserRoles());
}
private final class RemoveUserRoleActionLinkLabel extends AjaxLinkLabel {
private final String userRoleToRemove;
private RemoveUserRoleActionLinkLabel(final String id, final IModel<String> model, final String userRoleToRemove) {
super(id, model);
this.userRoleToRemove = userRoleToRemove;
}
@Override
public void onClick(final AjaxRequestTarget target) {
final MapModel nameModel = new MapModel<>(Collections.singletonMap("name", userRoleToRemove));
final Confirm confirm = new Confirm(
getString("userrole-remove-title", nameModel),
getString("userrole-remove-text", nameModel)
).ok(() -> {
removeUserRole(userRoleToRemove);
});
dialogService.show(confirm);
target.add(ViewGroupPanel.this);
}
}
}
private final class AddUserRolePanel extends Panel {
private final HippoForm hippoForm;
private final DropDownChoice<String> userRoleChoice;
private String selectedUserRole;
AddUserRolePanel(final String id) {
super(id);
setOutputMarkupId(true);
hippoForm = new HippoForm("form");
final AjaxButton submit = new AjaxButton("submit", hippoForm) {
@Override
protected void onSubmit(AjaxRequestTarget target, Form form) {
// clear old feedbacks prior showing new ones
hippoForm.clearFeedbackMessages();
final HippoSession hippoSession = UserSession.get().getJcrSession();
final MapModel nameModel = new MapModel<>(Collections.singletonMap("name", selectedUserRole));
try {
if (group != null && !group.getUserRoles().contains(selectedUserRole)) {
group.addUserRole(selectedUserRole);
EventBusUtils.post("add-userrole", HippoEventConstants.CATEGORY_GROUP_MANAGEMENT,
String.format("added user role '%s' to group '%s'", selectedUserRole, group.getGroupname()));
info(getString("userrole-added", nameModel));
}
userRolesListView.updateUserRoles();
updateUserRoleChoice();
} catch (RepositoryException e) {
error(getString("userrole-add-failed", nameModel));
log.error("Unable to add userrole '{}' : ", selectedUserRole, e);
}
redraw();
}
@Override
public boolean isEnabled() {
return selectedUserRole != null;
}
};
hippoForm.add(submit);
userRoleChoice = new DropDownChoice<>("userroles-select", new PropertyModel<>(this, "selectedUserRole"), getUserRoleChoices());
userRoleChoice.setNullValid(false);
userRoleChoice.add(new AjaxFormComponentUpdatingBehavior("change") {
@Override
protected void onUpdate(final AjaxRequestTarget target) {
target.add(submit);
}
});
hippoForm.add(userRoleChoice);
add(hippoForm);
}
List<String> getUserRoleChoices() {
return SecurityManagerHelper.getUserRolesProvider().getRoles().stream()
.map(UserRole::getName)
.filter(r -> !group.getUserRoles().contains(r))
.sorted()
.collect(Collectors.toList());
}
void updateUserRoleChoice() {
userRoleChoice.setChoices(getUserRoleChoices());
}
@SuppressWarnings("unused")
public void setSelectedUserRole(final String selectedUserRole) {
this.selectedUserRole = selectedUserRole;
}
}
/**
* List view for the group members.
*/
private final class GroupMembersListView extends ListView<DetachableUser> {
private final IPluginContext context;
GroupMembersListView(final String id, final IPluginContext context) {
super(id, group.getMembersAsDetachableUsers());
this.context = context;
setReuseItems(false);
}
@Override
protected void populateItem(final ListItem<DetachableUser> item) {
final DetachableUser detachableUser = item.getModelObject();
final User user = detachableUser.getUser();
item.add(new ViewUserLinkLabel("username", detachableUser, ViewGroupPanel.this, context));
final Component actionLinkLabel = new DeleteGroupMembershipActionLinkLabel("remove",
new ResourceModel("group-member-remove-action"), user);
actionLinkLabel.setVisible(isSecurityUserAdmin && !group.isExternal() && !group.isSystem());
item.add(actionLinkLabel);
}
void updateMembers() {
setModelObject(group.getMembersAsDetachableUsers());
}
private final class DeleteGroupMembershipActionLinkLabel extends AjaxLinkLabel {
private final User user;
private DeleteGroupMembershipActionLinkLabel(final String id, final IModel<String> model, final User user) {
super(id, model);
this.user = user;
}
@Override
public void onClick(final AjaxRequestTarget target) {
final Model<User> userModel = Model.of(user);
final Confirm confirm = new Confirm(
getString("group-delete-member-title", userModel),
getString("group-delete-member-text", userModel)
).ok(() -> {
deleteGroupMembership(user.getUsername());
updateMembers();
});
dialogService.show(confirm);
target.add(ViewGroupPanel.this);
}
}
}
}
| 43.735099 | 139 | 0.647941 |
3401c0dc8ecd761ce57b0c75a9ae1789919a38c1 | 1,851 | package com.globalhua.pay.web.portal.controller;
import com.globalhua.pay.common.web.vo.CommonResult;
import com.globalhua.pay.facade.account.service.AccountManagementFacade;
import com.globalhua.pay.web.portal.biz.SmsAuthCodeBiz;
import com.globalhua.pay.web.portal.dto.ResetPasswordRequest;
import com.globalhua.pay.web.portal.security.User;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* 个人设置
*/
@RestController
@RequestMapping("setting")
public class SettingsController {
@Resource
AccountManagementFacade accountManagementFacade;
@Resource
SmsAuthCodeBiz smsAuthCodeBiz;
/**
* 修改密码
*/
@PostMapping("resetPassword")
public CommonResult<Void> resetPassword(@RequestBody ResetPasswordRequest body,
@AuthenticationPrincipal User user) {
smsAuthCodeBiz.checkAuthCode(null,SmsAuthCodeBiz.BIZ_TYPE_RESET_PASSWORD,body.getAuthCode());
accountManagementFacade.resetPassword(user.getUsername(), body.getPassword());
return CommonResult.ok();
}
/**
* 修改支付密码
*/
@PostMapping("resetPayPassword")
public CommonResult<Void> resetPayPassword(@RequestBody ResetPasswordRequest body,
@AuthenticationPrincipal User user) {
smsAuthCodeBiz.checkAuthCode(null,SmsAuthCodeBiz.BIZ_TYPE_RESET_PAY_PASSWORD,body.getAuthCode());
accountManagementFacade.resetPayPassword(user.getUsername(), body.getPassword());
return CommonResult.ok();
}
}
| 36.294118 | 105 | 0.741221 |
9c894de1dcc7e753b791c27d7ec11563fc3fc13f | 1,242 | package com.telecominfraproject.wlan.equipment.models.events;
import java.util.Map;
import com.telecominfraproject.wlan.core.model.equipment.RadioType;
import com.telecominfraproject.wlan.equipment.models.CellSizeAttributes;
import com.telecominfraproject.wlan.equipment.models.Equipment;
public class EquipmentCellSizeAttributesChangedEvent extends EquipmentChangedEvent {
private static final long serialVersionUID = -5336592950746293096L;
private Map<RadioType, CellSizeAttributes> cellSizeAttributesMap;
public EquipmentCellSizeAttributesChangedEvent(Equipment equipment, Map<RadioType, CellSizeAttributes> cellSizeAttributesMap){
super(equipment);
setEquipmentChangeType(EquipmentChangeType.CellSizeAttributesOnly);
this.cellSizeAttributesMap = cellSizeAttributesMap;
}
/**
* Constructor used by JSON
*/
private EquipmentCellSizeAttributesChangedEvent() {
super();
}
public Map<RadioType, CellSizeAttributes> getCellSizeAttributesMap() {
return cellSizeAttributesMap;
}
public void setCellSizeAttributesMap(Map<RadioType, CellSizeAttributes> cellSizeAttributesMap) {
this.cellSizeAttributesMap = cellSizeAttributesMap;
}
}
| 35.485714 | 130 | 0.782609 |
92cff73b03760a4315ae6fe55bb59b49a4fd62b9 | 1,165 | package pt.tech4covid.service;
import pt.tech4covid.domain.Newsletter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.Optional;
/**
* Service Interface for managing {@link Newsletter}.
*/
public interface NewsletterService {
/**
* Save a newsletter.
*
* @param newsletter the entity to save.
* @return the persisted entity.
*/
Newsletter save(Newsletter newsletter);
/**
* Get all the newsletters.
*
* @param pageable the pagination information.
* @return the list of entities.
*/
Page<Newsletter> findAll(Pageable pageable);
/**
* Get all the newsletters with eager load of many-to-many relationships.
*
* @return the list of entities.
*/
Page<Newsletter> findAllWithEagerRelationships(Pageable pageable);
/**
* Get the "id" newsletter.
*
* @param id the id of the entity.
* @return the entity.
*/
Optional<Newsletter> findOne(Long id);
/**
* Delete the "id" newsletter.
*
* @param id the id of the entity.
*/
void delete(Long id);
}
| 21.981132 | 77 | 0.63691 |
ee5128935d5b80b8cf8347aed72261816169b04a | 1,400 | //
// Decompiled by Procyon v0.5.36
//
package org.apache.velocity.runtime.parser.node;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.runtime.parser.ParserVisitor;
import org.apache.velocity.runtime.parser.Parser;
public class ASTAndNode extends SimpleNode
{
public ASTAndNode(final int id) {
super(id);
}
public ASTAndNode(final Parser p, final int id) {
super(p, id);
}
public Object jjtAccept(final ParserVisitor visitor, final Object data) {
return visitor.visit(this, data);
}
public Object value(final InternalContextAdapter context) throws MethodInvocationException {
return new Boolean(this.evaluate(context));
}
public boolean evaluate(final InternalContextAdapter context) throws MethodInvocationException {
final Node left = this.jjtGetChild(0);
final Node right = this.jjtGetChild(1);
if (left == null || right == null) {
this.log.error(((left == null) ? "Left" : "Right") + " side of '&&' operation is null." + " Operation not possible. " + context.getCurrentTemplateName() + " [line " + this.getLine() + ", column " + this.getColumn() + "]");
return false;
}
return left.evaluate(context) && right.evaluate(context);
}
}
| 35 | 234 | 0.670714 |
484d8a02efb4a89cb5c287f4ca99a38f75139cb6 | 349 | package br.com.splessons.model;
import java.io.Serializable;
import org.joda.time.LocalDate;
import lombok.Getter;
import lombok.Setter;
public class SalaryPK implements Serializable {
private static final long serialVersionUID = 947904620353747182L;
@Getter
@Setter
private Long employee;
@Getter
@Setter
private LocalDate fromDate;
} | 16.619048 | 66 | 0.793696 |
b313a0c93ce17ac964e652fa9578bb11e5a5d475 | 381 | package br.com.symbiosyssolucoes.PharmaIntegration.repository;
import br.com.symbiosyssolucoes.PharmaIntegration.entity.Invoice;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface InvoiceRepository extends JpaRepository<Invoice, Long> {
Optional<List<Invoice>> findByStatus(String status);
}
| 25.4 | 73 | 0.824147 |
d77466a1b5ad5d251514fc84ca23c6d1b40091ac | 789 | package lab1.q3;
import java.util.*;
public class Q3 {
public static void main(String[] args) {
Function f = new Function();
int n, a = 1, b = 1, c = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter n value: ");
n = sc.nextInt();
f.nrcf(a, b, c, n);
f.rcf(a, b, c, n);
sc.close();
}
}
class Function {
void nrcf(int a, int b, int c, int n) {
for (int i = 1; i <= n - 2; i++) {
c = a + b;
a = b;
b = c;
}
a = b = 1;
System.out.println("nth value in the series using non recursive function is : " + c);
}
void rcf(int a, int b, int c, int n) {
if (n - 2 > 0) {
c = a + b;
a = b;
b = c;
rcf(a, b, c, n - 1);
return;
}
System.out.println("nth value in the series using recursive function is : " + c);
}
}
| 17.931818 | 87 | 0.531052 |
f3b82b827549f408e776db518989ddceb367bac2 | 719 | package com.authentication.model;
import java.sql.Time;
public interface IUsers
{
String getEmail();
void setEmail(String email);
String getUserId();
void setUserId(String userId);
String getUsername();
void setUsername(String username);
int getPlayerLevel();
void setPlayerLevel(int playerLevel);
String getPassword();
void setPassword(String password);
String getConPassword();
void setConPassword(String conPassword);
int getUserSessionFlag();
void setUserSessionFlag(int userSessionFlag);
int getActiveInTournament();
void setActiveInTournament(int activeInTournament);
String getLoginTime();
void setLoginTime(String loginTime);
}
| 20.542857 | 55 | 0.723227 |
32f7ff1fe049b1ebddd2879bdf4d43187ab544cf | 340 | package bluegreen.manager.client.aws;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class RdsSnapshotBluegreenIdTest
{
@Test
public void testToString()
{
assertEquals("bluegreen9theEnv9logicaldb9physicaldb",
new RdsSnapshotBluegreenId("theEnv", "logicaldb", "physicaldb").toString());
}
} | 22.666667 | 84 | 0.758824 |
d4024dd9404659ae1c25eed09f726b6d7a008805 | 1,948 | /*
* Copyright 2017 StoneHui
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.sch.calendar.recyclerview;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
/**
* Created by StoneHui on 17/2/24.
* <p>
* RecyclerView for page.
*/
public class PageRecyclerView extends RecyclerView {
private boolean canDrag = true;
private boolean canFling = false;
public PageRecyclerView(Context context) {
super(context);
}
/**
* Set drag enable for page.
*/
public void setCanDrag(boolean canDrag) {
this.canDrag = canDrag;
}
/**
* Return drag enable of page.
*/
public boolean canDrag() {
return canDrag;
}
/**
* Set fling enable for page.
*/
public void setCanFling(boolean canFling) {
this.canFling = canFling;
}
/**
* Return fling enable of page.
*/
public boolean canFling() {
return canFling;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
return canDrag && super.onInterceptTouchEvent(e);
}
@Override
public boolean onTouchEvent(MotionEvent e) {
return !canDrag || super.onTouchEvent(e);
}
@Override
public boolean fling(int velocityX, int velocityY) {
// no fling
return canFling && super.fling(velocityX, velocityY);
}
}
| 24.049383 | 101 | 0.660164 |
6c0b4e77df1c2730c00661ac30653055ee249517 | 16,690 | package priv.songxusheng.easystorer;
import android.content.Context;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class EasyStorer {
//region 单例
private EasyStorer(){}
private final static class InstanceHolder{
private static EasyStorer instance = null;
private synchronized static EasyStorer getInstance(){
if(instance==null) {
instance = new EasyStorer();
if(InstanceHolder.instance.lockHolder==null){
InstanceHolder.instance.lockHolder = new HashMap<>();
}
if(OBJECT_SAVE_PATH==null){
if(context == null)
throw new RuntimeException("You can't use EasyStorer without initializing it!\nYou should call EasyStorer.init() first in Application!:");
OBJECT_SAVE_PATH = context.getFilesDir().getAbsolutePath();
}
else{
File f = new File(OBJECT_SAVE_PATH+"/");
if(!f.exists()){
if(!f.getParentFile().exists())
f.getParentFile().mkdirs();
if(!f.exists())
throw new RuntimeException("You can't use EasyStorer path with an unreadable position!");
}
else if(!f.isDirectory())
throw new RuntimeException("You can't use EasyStorer path with a file!");
}
}
return instance;
}
}
private static final EasyStorer getInstance() {
return InstanceHolder.getInstance();
}
protected static final void releaseInstance(){//for test
ReentrantReadWriteLock.WriteLock lock = holderLock.writeLock();
lock.lock();
try {
if( InstanceHolder.instance == null) {
System.gc();
return;
}
Set<Map.Entry<String, Map<String, Map<String,ReentrantReadWriteLock> > > > groups = InstanceHolder.instance.lockHolder.entrySet();
for(Map.Entry<String, Map<String, Map<String,ReentrantReadWriteLock> > > group:groups){
Set<Map.Entry<String, Map<String,ReentrantReadWriteLock> > > tags = group.getValue().entrySet();
for(Map.Entry<String, Map<String,ReentrantReadWriteLock> > tag:tags){
Set<Map.Entry<String,ReentrantReadWriteLock> > clzs = tag.getValue().entrySet();
for(Map.Entry<String,ReentrantReadWriteLock> clz:clzs){
tag.getValue().remove(clz.getKey());
}
tag.getValue().clear();
group.getValue().remove(tag.getKey());
}
group.getValue().clear();
InstanceHolder.instance.lockHolder.remove(group.getKey());
}
InstanceHolder.instance.lockHolder.clear();
InstanceHolder.instance.lockHolder = null;
InstanceHolder.instance = null;
System.gc();
} finally {
lock.unlock();
}
}
//endregion
//region 锁
private volatile Map<String, Map<String, Map<String,ReentrantReadWriteLock> > > lockHolder = new HashMap<>();
private volatile static ReentrantReadWriteLock holderLock = new ReentrantReadWriteLock(true);
final private ReentrantReadWriteLock getLock(String group, String classPath, String tag){
ReentrantReadWriteLock.ReadLock lock = holderLock.readLock();//share&fair lock
lock.lock();
try {
Map<String, Map<String,ReentrantReadWriteLock> > mGroup = lockHolder.get(group);
Map<String,ReentrantReadWriteLock> mTag;
ReentrantReadWriteLock retLock;
if(mGroup == null){
synchronized (EasyStorer.class){
mGroup = lockHolder.get(group);
if(mGroup==null){
mGroup = new HashMap<>();
mTag = new HashMap<>();
retLock = new ReentrantReadWriteLock(true);
mTag.put(classPath,retLock);
mGroup.put(tag,mTag);
lockHolder.put(group,mGroup);
return retLock;
}
}
}
mTag = mGroup.get(tag);
if(mTag==null){
synchronized (mGroup){
mTag = mGroup.get(tag);
if(mTag == null){
mTag = new HashMap<>();//unique one
retLock = new ReentrantReadWriteLock(true);
mTag.put(classPath,retLock);
mGroup.put(tag,mTag);
return retLock;
}
}
}
retLock = mTag.get(classPath);
if(retLock==null){
synchronized (mTag){
retLock = mTag.get(classPath);
if(retLock==null){
retLock = new ReentrantReadWriteLock(true);
mTag.put(classPath,retLock);
}
}
}
return retLock;
} finally {
lock.unlock();
}
}
private final void removeLock(String group, String classPath, String tag){
ReentrantReadWriteLock.WriteLock lock = holderLock.writeLock();
lock.lock();
try {
Map<String, Map<String,ReentrantReadWriteLock> > mGroup = lockHolder.get(group);
if(mGroup == null) {
lockHolder.remove(group);
return;
}
synchronized (mGroup){
Map<String,ReentrantReadWriteLock> mTag = mGroup.get(tag);
if(mTag == null) return;
synchronized (mTag){
mTag.remove(classPath);
if(mTag.size()==0){
mGroup.remove(tag);
if(mGroup.size()==0){
lockHolder.remove(group);
}
}
}
}
} finally {
lock.unlock();
}
}
//endregion
//region 增删查
private static String OBJECT_SAVE_PATH = null;
private Object readObject(String tag,Object defaultValue,String readGroup){
if(!new File(String.format("%s/%s/%s/%s.es",OBJECT_SAVE_PATH,readGroup,defaultValue.getClass().getName().replaceAll("\\.", "/"),tag)).exists()) {
removeLock(readGroup,defaultValue.getClass().getName(),tag);
return defaultValue;
}
FileInputStream fis = null;
ObjectInputStream ois = null;
final ReentrantReadWriteLock.ReadLock lock = getLock(readGroup,defaultValue.getClass().getName(),tag).readLock();
lock.lock();
if(!getLock(readGroup,defaultValue.getClass().getName(),tag).readLock().equals(lock)){
lock.unlock();
return readObject(tag,defaultValue,readGroup);
}
try {
fis = new FileInputStream(String.format("%s/%s/%s/%s.es",OBJECT_SAVE_PATH,readGroup,defaultValue.getClass().getName().replaceAll("\\.", "/"),tag));
ois = new ObjectInputStream(fis);
return ois.readObject();
} catch (Exception e) {
} finally {
try { ois.close(); } catch (Exception e) { }
try { fis.close(); } catch (Exception e) { }
lock.unlock();
}
return defaultValue;
}
private boolean writeObject(String tag, Object obj, String group){
//declare variables
FileOutputStream fos = null;
ObjectOutputStream oos = null;
final ReentrantReadWriteLock.WriteLock lock = getLock(group,obj.getClass().getName(),tag).writeLock();
File wFile = null;
boolean flag = true;
lock.lock();
if(!getLock(group,obj.getClass().getName(),tag).writeLock().equals(lock)){
lock.unlock();
return writeObject(tag,obj,group);
}
try {
wFile = new File(String.format("%s/%s/%s/%s.es",OBJECT_SAVE_PATH,group,obj.getClass().getName().replaceAll("\\.", "/"),tag));
if(!wFile.getParentFile().exists()){
wFile.getParentFile().mkdirs();
}
if(!wFile.exists()){
wFile.createNewFile();
}
fos = new FileOutputStream(wFile);
oos =new ObjectOutputStream(fos);
oos.writeObject(obj);
} catch (Exception e) {
flag = false;
} finally {
try { oos.close(); } catch (Exception e) { }
try { fos.close(); } catch (Exception e) { }
try { if(!flag) wFile.delete(); } catch (Exception e) { }
lock.unlock();
}
return flag;
}
private boolean deleteOne(File f,final String group) {
boolean flag = true;
String fileName = f.getAbsolutePath();
String tag = new StringBuilder(f.getName().substring(0,f.getName().length()-".es".length())).toString();
File fCls = new File(OBJECT_SAVE_PATH+"/");
String className = new String(fileName.substring(fCls.getAbsolutePath().length()));
className = new String(className.substring(group.length()+2,className.length() - f.getName().length()-1)).replaceAll("\\/",".");
final ReentrantReadWriteLock.WriteLock lock = getLock(group,className,tag).writeLock();
lock.lock();
if(!getLock(group,className,tag).writeLock().equals(lock)){
lock.unlock();
return deleteOne(f,group);
}
try { f.delete(); } catch (Exception e) { flag = false; }
lock.unlock();
removeLock(group,className,tag);
return flag;
}
private boolean deleteGroup(File f,final String group){
boolean flag = true;
if(f!=null&&f.exists()){
File fs[] = f.listFiles();
if(fs!=null){
for(File _f:fs) {
flag &= deleteGroup(_f,group);
}
f.delete();
}
else {
flag &= deleteOne(f,group);
}
}
return flag;
}
private boolean deleteTag(File f,String group,String tag){
boolean flag = true;
if(f!=null&&f.exists()){
File fs[] = f.listFiles();
if(fs!=null){
for(File _f:fs) {
flag &= deleteTag(_f,group,tag);
}
f.delete();
}
else if(f.getName().equals(tag+".es")){
flag &= deleteOne(f,group);
}
}
return flag;
}
private boolean removeItem(String tag,String group){
return deleteTag(new File(String.format("%s/%s/",OBJECT_SAVE_PATH,group)),group,tag);
}
private boolean removeItem(String tag,Class clazz,String group){
final ReentrantReadWriteLock.WriteLock lock = getLock(group,clazz.getName(),tag).writeLock();
boolean flag = false;
lock.lock();
if(!getLock(group,clazz.getName(),tag).writeLock().equals(lock)){
lock.unlock();
return removeItem(tag,clazz,group);
}
try {
File f = new File(String.format("%s/%s/%s/%s.es",
OBJECT_SAVE_PATH,
group,
clazz.getName().replaceAll("\\.", "/"),tag));
flag = f.exists()?f.delete():true;
} catch (Exception e) {}
lock.unlock();
removeLock(group,clazz.getName().replaceAll("\\.", "/"),tag);
return flag;
}
private boolean clearAll(String group){
return deleteGroup(new File(String.format("%s/%s/", OBJECT_SAVE_PATH, group)),group);
}
//endregion
//region 检测初始化及是否实现Serializable接口
private static void CheckSerializable(final Class clazz,Set<String> classSet){
if(classSet.contains(clazz.getName())||clazz.isInterface()) return;
classSet.add(clazz.getName());
Log.e("CheckSerializable",clazz.getName());
if(!Serializable.class.isAssignableFrom(clazz)){
throw new RuntimeException(String.format("Class %s must implement Serializable!",clazz.getName()));
}
Set<Field> fields = new HashSet<>(new ArrayList(Arrays.asList(clazz.getFields())){{addAll(new ArrayList(Arrays.asList(clazz.getDeclaredFields())));}});
for(Field field:fields){
if(field.getDeclaringClass().isInterface()){
CheckSerializable(field.getDeclaringClass(),classSet);
continue;
}
if(classSet.contains(field.getType().getName())||field.getType().getName().startsWith("java.")){
continue;
}
if(!Serializable.class.isAssignableFrom(field.getType())){
throw new RuntimeException(String.format("Class %s must implement Serializable!",field.getType().getName()));
}
CheckSerializable(field.getType(),classSet);
}
}
private static void TraceCheck(Object obj){
CheckSerializable(obj.getClass(),new HashSet(new ArrayList(Arrays.asList(new String[]{
"int",
"short",
"long",
"double",
"char",
"byte",
"float",
"boolean",
"java.lang.Integer",
"java.lang.Short",
"java.lang.Long",
"java.lang.Double",
"java.lang.Character",
"java.lang.Byte",
"java.lang.Float",
"java.lang.Boolean",
"java.lang.Object"
}))));
}
//endregion
//region 静态公有函数
private static Context context = null;
public static void init(Context context){EasyStorer.context = context;}
public static void init(String savePath){ OBJECT_SAVE_PATH = savePath; }
/**
*
* @param tag 标签
* @param defaultValue 取不到时返回的值
* @param <T>
* @return 在默认库()中取出标签为tag且类型为T的对象
*/
public static <T> T get(String tag,T defaultValue){
return get(tag,defaultValue,null);
}
/**
*
* @param tag
* @param defaultValue
* @param group
* @param <T>
* @return
*/
public static <T> T get(String tag,T defaultValue,String group){
TraceCheck(defaultValue);
Object returnObject = getInstance().readObject(tag,defaultValue,group==null?"_Easy_Storer_":group);
return (T)(returnObject == null?defaultValue:returnObject);
}
/**
*
* @param tag
* @param obj
* @return
*/
public static boolean put(String tag,Object obj){
return put(tag,obj,null);
}
/**
*
* @param tag
* @param obj
* @param group
* @return
*/
public static boolean put(String tag,Object obj,String group){
TraceCheck(obj);
return getInstance().writeObject(tag,obj,group==null?"_Easy_Storer_":group);
}
/**
*
* @param tag
* @return
*/
public static boolean remove(String tag){
return remove(tag,"");
}
/**
*
* @param tag 标签
* @param group
* @return
*/
public static boolean remove(String tag,String group){
return getInstance().removeItem(tag,(group==null||"".equals(group))?"_Easy_Storer_":group);
}
/**
*
* @param tag
* @param clazz
* @return
*/
public static boolean remove(String tag,Class clazz){
return remove(tag,clazz,null);
}
/**
*
* @param tag
* @param clazz
* @param group
* @return
*/
public static boolean remove(String tag,Class clazz, String group){
return getInstance().removeItem(tag,clazz,group==null?"_Easy_Storer_":group);
}
public static boolean clear(){
return clear(null);
}
public static boolean clear(String group){
return getInstance().clearAll(group==null?"_Easy_Storer_":group);
}
//endregion
} | 35.285412 | 162 | 0.541043 |
386d238260e170c6ec578a783aabf06f9bb3791b | 2,058 | package com.hkbea.spring.mybatis.config;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@MapperScan(basePackages = {"io.jxxchallenger.spring.mybatis.mapper"})
@ComponentScan(basePackages = {"io.jxxchallenger.spring.mybatis.service"})
@EnableTransactionManagement
public class MybatisConfig {
@Bean(destroyMethod = "close")
public DataSource dateSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/books");
dataSource.setUsername("cwx566533");
dataSource.setPassword("123456");
return dataSource;
}
@Bean
public DataSourceTransactionManager transactionManager(DataSource dataSource) {
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
/**
* xml方式声明事务:transactionManager bean + tx:annotation-driven
* java confing方式声明事务: config类里创建 transactionManager bean + {@link org.springframework.transaction.annotation.EnableTransactionManagement @EnableTransactionManagement} 注解
* @param dataSource
* @return
*/
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource);
return sqlSessionFactory;
}
}
| 40.352941 | 176 | 0.748299 |
db68dbc62b65498e3186895399dc526f8c00cfa6 | 582 | package p05_military;
public abstract class SpecialisedSoldier extends Private implements ISpecialisedSoldier{
protected String corps;
public SpecialisedSoldier(int id, String firstName, String lastName, double salary, String corps) {
super(id, firstName, lastName, salary);
this.setCorps(corps);
}
@Override
public void setCorps(String corps) {
if (!"Airforces".equals(corps) && !"Marines".equals(corps)) {
throw new IllegalArgumentException("Skip line");
}else {
this.corps = corps;
}
}
}
| 29.1 | 103 | 0.656357 |
9de802ac3aabc766554399a4c122e8a3adeaaeb7 | 600 | package graphql.servlet;
import graphql.ExecutionInput;
import graphql.schema.GraphQLSchema;
import graphql.servlet.internal.GraphQLRequest;
/**
* @author Andrew Potter
*/
public class GraphQLSingleInvocationInput extends GraphQLInvocationInput {
private final GraphQLRequest request;
public GraphQLSingleInvocationInput(GraphQLRequest request, GraphQLSchema schema, GraphQLContext context, Object root) {
super(schema, context, root);
this.request = request;
}
public ExecutionInput getExecutionInput() {
return createExecutionInput(request);
}
}
| 25 | 124 | 0.76 |
768decbe3d89bd2ea2a1389ad2044b054a528cde | 1,583 | /*
* Copyright 2018-2021 Hazelcast, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.package com.theyawns.controller.launcher;
*
*/
package org.hazelcast.msfdemo.invsvc.events;
import org.hazelcast.msfdemo.invsvc.domain.Item;
import java.io.Serializable;
import java.util.function.UnaryOperator;
public class CompactionEvent extends InventoryEvent implements Serializable, UnaryOperator<Item> {
public CompactionEvent(String itemNumber, String description, String location,
String locationType, int qoh, int reserved, int atp) {
super(InventoryEventTypes.COMPACTION);
// TODO: Set all fields
}
@Override
public void publish() {
System.out.println("****** CompactionEvent.publish unimplemented!");
}
@Override // UnaryOperator<Account>
public Item apply(Item item) {
// TODO: set all fields
// item.setAcctNumber(super.getAccountNumber());
// item.setName(getAccountName());
// item.setBalance(super.getAmount());
return item;
}
}
| 33.680851 | 98 | 0.699937 |
643ad2070c210d8341044cb5b00df0d12d598c3b | 1,370 | /*
* Copyright (C) 2018 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 com.gitlab.summercattle.commons.db.sqlparser;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.ItemsListVisitor;
import net.sf.jsqlparser.expression.operators.relational.MultiExpressionList;
import net.sf.jsqlparser.expression.operators.relational.NamedExpressionList;
import net.sf.jsqlparser.statement.select.SubSelect;
public class ItemsListVisitorImpl implements ItemsListVisitor {
@Override
public void visit(SubSelect subSelect) {
}
@Override
public void visit(ExpressionList expressionList) {
}
@Override
public void visit(NamedExpressionList namedExpressionList) {
}
@Override
public void visit(MultiExpressionList multiExprList) {
}
} | 33.414634 | 77 | 0.788321 |
e35ead277d8b3b209e86c91c9f8ae6aefa9d6ace | 1,256 | package org.sitenv.service.ccda.smartscorecard.entities.inmemory;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "TEMPLATEIDSR21")
public class TemplateIdsR21 {
@Id
@Column(name = "ID")
private Integer Id;
@Column(name = "TEMPLATETITLE")
private String templateTitle;
@Column(name = "TEMPLATETYPE")
private String templateType;
@Column(name = "TEMPLATEID")
private String templateId;
@Column(name = "EXTENSION")
private String extension;
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
public String getTemplateTitle() {
return templateTitle;
}
public void setTemplateTitle(String templateTitle) {
this.templateTitle = templateTitle;
}
public String getTemplateType() {
return templateType;
}
public void setTemplateType(String templateType) {
this.templateType = templateType;
}
public String getTemplateId() {
return templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
}
| 18.202899 | 65 | 0.734076 |
4ba14819fc55d351f7d77642b011ed858d354fd5 | 16,733 | package rxf.shared;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.web.bindery.autobean.shared.AutoBean;
import com.google.web.bindery.autobean.shared.AutoBeanCodex;
import com.google.web.bindery.autobean.shared.AutoBeanFactory;
import com.google.web.bindery.autobean.shared.Splittable;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* usage:
* <pre>
* String dbSpec = "http://" + Window.Location.getHost() + "/api/campaigns";
* final PouchProxy campaigns = PouchProxy._create("campaigns");
* campaigns.replicateFrom(dbSpec, new AsyncCallback<PouchProxy>() {
*
* public void onFailure(Throwable caught) {
* }
* public void onSuccess(PouchProxy result) {
* campaigns.allDocs(new EnumMap<PouchProxy.AllDocOptions, Object>(PouchProxy.AllDocOptions.class) {{
* put(PouchProxy.AllDocOptions.include_docs, true);
* }}, new AsyncCallback<ViewResults.Results>() {
* public void onFailure(Throwable caught) {
* caught.fillInStackTrace();
* Window.alert(caught.getLocalizedMessage());
* }
* public void onSuccess(final ViewResults.Results result) {
*
* GWT.runAsync(new RunAsyncCallback() {
* public void onFailure(Throwable reason) {
*
* }
* public void onSuccess() {
* List<ViewResults.Results.Record> rows = result.getRows();
* int size = rows.size();
* ArrayList<Campaign> arr = new ArrayList<Campaign>();
* for (ViewResults.Results.Record r : rows) {
* Campaign doc = AutoBeanCodex.decode((ResFactory) GWT.create(ResFactory.class), Campaign.class, r.getDoc()).as();
* arr.add(doc);
* }
* CampaignView campaignView = new CampaignView();
* RootPanel.get().add(campaignView);
* campaignView.init(arr);
*
* }
* });
*
* }
* }
* );
* }
* });
* </pre>
*/
@SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
public class PouchProxy extends JavaScriptObject {
static PouchAutobeanFactory generic = GWT.create(PouchAutobeanFactory.class);
protected PouchProxy() {
}
public static native <P> JavaScriptObject wrapSuccesFailCallback(AsyncCallback<P> cb)/*-{
return $entry(function (e, r) {
var err = e, response = r;
if (err)
( cb.@com.google.gwt.user.client.rpc.AsyncCallback::onFailure(Ljava/lang/Throwable;)(@java.lang.Exception::new(Ljava/lang/String;)(JSON.stringify(err))));
else (cb.@com.google.gwt.user.client.rpc.AsyncCallback::onSuccess(Ljava/lang/Object;)(response))
})
}-*/;
public static final native JavaScriptObject parse(String json)
/*-{
return JSON.parse(json)
}-*/;
public static <T> void replicate(String from, String to, ReplicateOptions.ReplicateCall<T> options) {
Object encode = AutoBeanCodex.encode(generic.create(ReplicateOptions.class, options));
if (!GWT.isScript()) {
String payload = ((Splittable) encode).getPayload();
System.err.println("rep options: " + payload);
encode = parse(payload);
}
JSONObject jsonObject = new JSONObject((JavaScriptObject) encode);
if (null != options.getComplete()) {
jsonObject.put("complete", new JSONObject(wrapSuccesFailCallback(options.getComplete())));
}
if (null != options.getContinuous()) {
jsonObject.put("continuous", new JSONObject(wrapSuccesFailCallback(options.getContinuous())));
}
if (null != options.getOnChange()) {
jsonObject.put("onChange", new JSONObject(wrapSuccesFailCallback(options.getOnChange())));
}
_replicate(from, to, jsonObject.getJavaScriptObject());
}
public static native void _replicate(String from, String to, JavaScriptObject options)
/*-{
var replicate = $wnd.PouchDB.replicate(from, to, options);
}-*/;
public static native PouchProxy create(String dbSpec)
/*-{
return new $wnd.PouchDB(dbSpec)
}-*/;
public static void delete(String name) {
_delete(name);
}
public static native void _delete(String name)/*-{
$wnd.PouchDB.destroy(name);
}-*/;
public static native String b64decode(String a) /*-{
return window.atob(a);
}-*/;
/**
* <ul>
* Fetch multiple documents, deleted document are only included if options.keys is specified.
* <p/>
* <li> options.include_docs: Include the document in each row in the doc field
* <li> options.conflicts: Include conflicts in the _conflicts field of a doc
* <li> options.startkey & options.endkey: Get documents with keys in a certain range
* <li> options.descending: Reverse the order of the output table
* <li> options.keys: array of keys you want to get
* <ul><li> neither startkey nor endkey can be specified with this option
* <li> the rows are returned in the same order as the supplied "keys" array
* <li> the row for a deleted document will have the revision ID of the deletion, and an extra key "deleted":true in the "value" property
* <li> the row for a nonexistent document will just contain an "error" property with the value "not_found"
* </ul>
* <li> options.attachments: Include attachment data
*
* @param docId
* @param callback
* @param options
* @return
*/
public final void fetchDoc(String docId, AsyncCallback<Splittable> callback, FetchOptions options) {
// new JSONObject()
_fetchDoc(docId, callback, (null == options) ? JavaScriptObject.createObject()
: parse(AutoBeanCodex.encode(generic.fetchoptions(options)).getPayload()));
}
private native PouchProxy _fetchDoc(String docId, AsyncCallback<Splittable> callback,
JavaScriptObject options) /*-{
this.get(docId, options,
$entry(function (err, doc) {
var e = err;
var d = doc;
if (err) (callback.@com.google.gwt.user.client.rpc.AsyncCallback::onFailure(Ljava/lang/Throwable;))(e); else if (@com.google.gwt.core.client.GWT::isScript()()) (callback.@com.google.gwt.user.client.rpc.AsyncCallback::onSuccess(Ljava/lang/Object;))(d);
else (callback.@com.google.gwt.user.client.rpc.AsyncCallback::onSuccess(Ljava/lang/Object;))(@com.google.web.bindery.autobean.shared.impl.StringQuoter::split(Ljava/lang/String;)(JSON.stringify(d)));
}));
return this;
}-*/;
/**
* Create a new document or update an existing document. If the document already exists you must specify its revision _rev, otherwise a conflict will occur.
* <p/>
* There are some restrictions on valid property names of the documents, these are explained here.
*/
public final <T> PouchProxy put(AutoBean<T> t, AsyncCallback<String> cb) {
JavaScriptObject o;
if (!GWT.isScript()) {
// System.out.println(AutoBeanCodex.encode(t));
// System.out.println(AutoBeanCodex.encode(t).getPayload());
o = parse(AutoBeanCodex.encode(t).getPayload());
} else {
o = (JavaScriptObject) t;
}
return _put(o, cb);
}
/**
* Create a new document or update an existing document. If the document already exists you must specify its revision _rev, otherwise a conflict will occur.
* <p/>
* There are some restrictions on valid property names of the documents, these are explained here.
*/
public final <T> PouchProxy post(AutoBean<T> t, AsyncCallback<String> cb) {
JavaScriptObject o;
if (!GWT.isScript()) {
o = parse(AutoBeanCodex.encode(t).getPayload());
} else {
o = (JavaScriptObject) t;
}
return _post(o, cb);
}
protected final native PouchProxy _put(JavaScriptObject autobean, AsyncCallback<String> cb)
/*-{
this.put(autobean, $entry(function (err, response) {
var e = err, r = response;
if (err) (cb.@com.google.gwt.user.client.rpc.AsyncCallback::onFailure(Ljava/lang/Throwable;))(@java.io.IOException::new(Ljava/lang/String;))(JSON.stringify(e));
else
(cb.@com.google.gwt.user.client.rpc.AsyncCallback::onSuccess(Ljava/lang/Object;))(JSON.stringify(r));
}));
return this;
}-*/;
protected final native PouchProxy _post(JavaScriptObject autobean, AsyncCallback<String> cb)
/*-{
this.post(autobean,
$entry(
function (err, response) {
var e = err;
var r = response;
if (err)
(cb.@com.google.gwt.user.client.rpc.AsyncCallback::onFailure(Ljava/lang/Throwable;)(@java.io.IOException::new(Ljava/lang/String;))(JSON.stringify(e)));
else
(cb.@com.google.gwt.user.client.rpc.AsyncCallback::onSuccess(Ljava/lang/Object;))(JSON.stringify(r));
}));
return this;
}-*/;
public final PouchProxy allDocs(AllDocOptions options, final AsyncCallback<ViewResults.Results> cb) {
String alldocOptions;
alldocOptions =
null == options ? "{}" : AutoBeanCodex.encode(generic.allDocs(options)).getPayload();
_allDocs(alldocOptions, new AsyncCallback<JavaScriptObject>() {
public void onFailure(Throwable caught) {
Window.alert(caught.getMessage());
}
public void onSuccess(JavaScriptObject result) {
PouchAutobeanFactory resFactory = GWT.create(PouchAutobeanFactory.class);
Class<ViewResults.Results> resultsClass = ViewResults.Results.class;
AutoBean<ViewResults.Results> decode;
if (!GWT.isScript()) {
String x = new JSONObject(result).toString();
// System.err.println(x);
decode = AutoBeanCodex.decode(resFactory, resultsClass, x);
} else
decode = AutoBeanCodex.decode(resFactory, resultsClass, (Splittable) result.cast());
// System.err.println("decoded successfully");
cb.onSuccess(decode.as());
}
});
return this;
}
/**
* Fetch multiple documents, deleted document are only included if options.keys is specified.
*/
public final native void _allDocs(String alldocOptions, AsyncCallback<JavaScriptObject> cb)
/*-{
var parse = JSON.parse(alldocOptions);
this.allDocs(parse,
$entry(function (e1, r1) {
var e = e1, r = r1;
if (e) {
(cb.@com.google.gwt.user.client.rpc.AsyncCallback::onFailure(Ljava/lang/Throwable;)(@java.io.IOException::new(Ljava/lang/String;))(e.toSource()));
} else {
(cb.@com.google.gwt.user.client.rpc.AsyncCallback::onSuccess(Ljava/lang/Object;))(r);
}
}))
}-*/;
public interface PouchAutobeanFactory extends AutoBeanFactory {
AutoBean<ViewResults.Results> pouchResults();
AutoBean<ViewResults.Results> pouchResults(ViewResults.Results x);
AutoBean<AllDocOptions> allDocs();
AutoBean<AllDocOptions> allDocs(AllDocOptions a);
AutoBean<ReplicateOptions> replicateOptions();
AutoBean<FetchOptions> fetchoptions();
AutoBean<FetchOptions> fetchoptions(FetchOptions options);
}
public interface FetchOptions {
/**
* Fetch specific revision of a document. Defaults to winning revision (see couchdb guide.
*/
String getRev();
/**
* Include revision history of the document
*/
Boolean getRevs();
/**
* Include a list of revisions of the document, and their availability.
*/
List<String> getRevs_info();
/**
* Fetch all leaf revisions if openrevs="all" or fetch all leaf revisions specified in openrevs array. Leaves will be returned in the same order as specified in input array
*/
Splittable getOpen_revs();
/**
* If specified conflicting leaf revisions will be attached in _conflicts array
*/
Boolean getConflicts();
/**
* Include attachment data
*/
Boolean getAttachments();
/**
* Include sequence number of the revision in the database
*/
Boolean getLocal_seq();
/**
* An object of options to be sent to the ajax requester. In Node they are sent ver batim to request with the exception of:
* options.ajax.cache: Appends a random string to the end of all HTTP GET requests to avoid them being cached on IE. Set this to true to prevent this happening.
*/
Splittable getAjax();
}
interface PutOptions {
}
public interface ReplicateOptions {
/**
* undocumented
*/
Integer getBatch_size();
/**
* Reference a filter function from a design document to selectively get updates.
*/
String getFilter();
/**
* Query params send to the filter function.
*/
Set<String> getQuery_params();
/**
* Only replicate docs with these ids.
*/
Set<String> getDoc_ids();
/**
* Initialize the replication on the server. The response is the CouchDB POST _replicate response and is different from the PouchDB replication response. Also, Splittable get_onChange is not supported on server replications.
*/
Boolean getServer();
/**
* Create target database if it does not exist. Only for server replications.
*/
Boolean getCreateTarget();
interface ReplicateCall<T> extends ReplicateOptions {
/**
* Function called when all changes have been processed.
*/
AsyncCallback getComplete();
/**
* Function called on each change processed..
*/
AsyncCallback<T> getOnChange();
/**
* If true starts subscribing to future changes in the source database and continue replicating them.
*/
AsyncCallback<T> getContinuous();
}
}
public interface AllDocOptions {
/**
* Include the document in each row in the doc field
*/
boolean isInclude_docs();
/**
* Include conflicts in the _conflicts field of a doc
*/
boolean isConflicts();
/**
* Include attachment data
*/
boolean isAttachments();
/**
* Get documents with keys in a certain range descending: Reverse the order of the output table
*/
String getStartkey();
/**
* Get documents with keys in a certain range descending: Reverse the order of the output table
*/
String getEndkey();
/**
* array of keys you want to get
* neither startkey nor endkey can be specified with this option
* <p/>
* the rows are returned in the same order as the supplied "keys" array
* the row for a deleted document will have the revision ID of the deletion, and an extra id "deleted":true in the "value" property
* the row for a nonexistent document will just contain an "error" property with the value "not_found"
*/
Set<String> getKeys();
}
public interface ViewResults {
Map<String, String> getErr();
Results getResults();
interface Response {
boolean getOk();
String getId();
String getRev();
String getError();
}
/**
* {
* "total_rows": 1,
* "rows": [
* { "doc": { "_id": "0B3358C1-BA4B-4186-8795-9024203EB7DD", "_rev": "1-5782E71F1E4BF698FA3793D9D5A96393", "blog_post": "my blog post" }, "id": "0B3358C1-BA4B-4186-8795-9024203EB7DD", "id": "0B3358C1-BA4B-4186-8795-9024203EB7DD", "value": { "rev": "1-5782E71F1E4BF698FA3793D9D5A96393" } }
* ] }
*/
interface Results {
@AutoBean.PropertyName("total_rows")
double getTotalRows();
List<Record> getRows();
interface Record {
String getId();
Long getSeq();
String getKey();
List<Splittable> getChanges();
Splittable getValue();
Splittable getDoc();
}
}
}
public abstract static class AllAllDocOptions implements AllDocOptions {
public boolean isInclude_docs() {
return true;
}
}
}
| 34.572314 | 292 | 0.622483 |
3a04d2272a9523591ced928b08fa0a9b4cc73451 | 1,575 | package com.example.android.pets.data;
import android.net.Uri;
import android.provider.BaseColumns;
public final class PetContract
{
private PetContract() {}
public static final String CONTENT_AUTHORITY = "com.example.android.pets";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
public static final String PATH_PETS = "pets";
public static final class PetEntry implements BaseColumns
{
public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, PATH_PETS);
public static final String TABLE_NAME ="pets";
public static final String _ID =BaseColumns._ID;
public static final String COLUMN_PET_NAME ="name";
public static final String COLUMN_PET_BREED="breed";
public static final String COLUMN_PET_GENDER ="gender";
public static final String COLUMN_PET_WEIGHT ="weight";
public static final int GENDER_UNKNOWN =0;
public static final int GENDER_MALE =1;
public static final int GENDER_FEMALE =2;
/**
* Returns whether or not the given gender is {@link #GENDER_UNKNOWN}, {@link #GENDER_MALE},
* or {@link #GENDER_FEMALE}.
*/
public static boolean isValidGender(int gender) {
/* if (gender == GENDER_UNKNOWN || gender == GENDER_MALE || gender == GENDER_FEMALE) {
return true;
}
return false;*/
return gender == GENDER_UNKNOWN || gender == GENDER_MALE || gender == GENDER_FEMALE;
}
}
}
| 35 | 100 | 0.662857 |
5377eca1f390c5aa706cf24830016a87a98f21c3 | 1,741 | /**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.modules.coach.model;
import java.util.Map;
/**
*
* Initial date: 02.02.2015<br>
* @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
*
*/
public class SearchCoachedIdentityParams {
private String login;
private Integer status;
private Long identityKey;
private Map<String,String> userProperties;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Long getIdentityKey() {
return identityKey;
}
public void setIdentityKey(Long identityKey) {
this.identityKey = identityKey;
}
public Map<String, String> getUserProperties() {
return userProperties;
}
public void setUserProperties(Map<String, String> userProperties) {
this.userProperties = userProperties;
}
}
| 25.231884 | 82 | 0.715106 |
2c4169cc0c628229924e02f808dabb1a877db2b3 | 15,981 | /*
* Copyright 2010 James Pether Sörling
*
* 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.
*
* $Id$
* $HeadURL$
*/
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.02.24 at 11:26:40 PM CET
//
package com.hack23.cia.model.external.worldbank.countries.impl;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.jvnet.jaxb2_commons.lang.Equals;
import org.jvnet.jaxb2_commons.lang.EqualsStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import org.jvnet.jaxb2_commons.locator.util.LocatorUtils;
import com.hack23.cia.model.common.api.ModelObject;
/**
* The Class CountryElement.
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"iso2Code",
"countryName",
"region",
"adminregion",
"incomeLevel",
"lendingType",
"capitalCity",
"longitude",
"latitude"
})
@XmlRootElement(name = "country")
@Entity(name = "CountryElement")
@Table(name = "COUNTRY_ELEMENT")
@Inheritance(strategy = InheritanceType.JOINED)
public class CountryElement
implements ModelObject, Equals
{
/**
*
*/
private static final long serialVersionUID = 1L;
/** The iso 2 code. */
@XmlElement(required = true)
protected String iso2Code;
/** The country name. */
@XmlElement(name = "name", required = true)
protected String countryName;
/** The region. */
@XmlElement(required = true)
protected Region region;
/** The adminregion. */
@XmlElement(required = true)
protected Adminregion adminregion;
/** The income level. */
@XmlElement(required = true)
protected IncomeLevel incomeLevel;
/** The lending type. */
@XmlElement(required = true)
protected LendingType lendingType;
/** The capital city. */
@XmlElement(required = true)
protected String capitalCity;
/** The longitude. */
@XmlElement(required = true)
protected String longitude;
/** The latitude. */
@XmlElement(required = true)
protected String latitude;
/** The id. */
@XmlAttribute(name = "id")
protected String id;
/** The hjid. */
@XmlAttribute(name = "Hjid")
protected Long hjid;
/**
* Gets the iso 2 code.
*
* @return the iso 2 code
*/
@Basic
@Column(name = "ISO_2CODE")
public String getIso2Code() {
return iso2Code;
}
/**
* Sets the iso 2 code.
*
* @param value the new iso 2 code
*/
public void setIso2Code(final String value) {
this.iso2Code = value;
}
/**
* Gets the country name.
*
* @return the country name
*/
@Basic
@Column(name = "COUNTRY_NAME")
public String getCountryName() {
return countryName;
}
/**
* Sets the country name.
*
* @param value the new country name
*/
public void setCountryName(final String value) {
this.countryName = value;
}
/**
* Gets the region.
*
* @return the region
*/
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "value", column = @Column(name = "REGION_VALUE")),
@AttributeOverride(name = "id", column = @Column(name = "REGION_ID"))
})
public Region getRegion() {
return region;
}
/**
* Sets the region.
*
* @param value the new region
*/
public void setRegion(final Region value) {
this.region = value;
}
/**
* Gets the adminregion.
*
* @return the adminregion
*/
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "value", column = @Column(name = "ADMINREGION_VALUE")),
@AttributeOverride(name = "id", column = @Column(name = "ADMINREGION_ID"))
})
public Adminregion getAdminregion() {
return adminregion;
}
/**
* Sets the adminregion.
*
* @param value the new adminregion
*/
public void setAdminregion(final Adminregion value) {
this.adminregion = value;
}
/**
* Gets the income level.
*
* @return the income level
*/
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "value", column = @Column(name = "INCOME_LEVEL_VALUE")),
@AttributeOverride(name = "id", column = @Column(name = "INCOME_LEVEL_ID"))
})
public IncomeLevel getIncomeLevel() {
return incomeLevel;
}
/**
* Sets the income level.
*
* @param value the new income level
*/
public void setIncomeLevel(final IncomeLevel value) {
this.incomeLevel = value;
}
/**
* Gets the lending type.
*
* @return the lending type
*/
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "value", column = @Column(name = "LENDING_TYPE_VALUE")),
@AttributeOverride(name = "id", column = @Column(name = "LENDING_TYPE_ID"))
})
public LendingType getLendingType() {
return lendingType;
}
/**
* Sets the lending type.
*
* @param value the new lending type
*/
public void setLendingType(final LendingType value) {
this.lendingType = value;
}
/**
* Gets the capital city.
*
* @return the capital city
*/
@Basic
@Column(name = "CAPITAL_CITY")
public String getCapitalCity() {
return capitalCity;
}
/**
* Sets the capital city.
*
* @param value the new capital city
*/
public void setCapitalCity(final String value) {
this.capitalCity = value;
}
/**
* Gets the longitude.
*
* @return the longitude
*/
@Basic
@Column(name = "LONGITUDE")
public String getLongitude() {
return longitude;
}
/**
* Sets the longitude.
*
* @param value the new longitude
*/
public void setLongitude(final String value) {
this.longitude = value;
}
/**
* Gets the latitude.
*
* @return the latitude
*/
@Basic
@Column(name = "LATITUDE")
public String getLatitude() {
return latitude;
}
/**
* Sets the latitude.
*
* @param value the new latitude
*/
public void setLatitude(final String value) {
this.latitude = value;
}
/**
* Gets the id.
*
* @return the id
*/
@Basic
@Column(name = "ID")
public String getId() {
return id;
}
/**
* Sets the id.
*
* @param value the new id
*/
public void setId(final String value) {
this.id = value;
}
/**
* With iso 2 code.
*
* @param value the value
* @return the country element
*/
public CountryElement withIso2Code(final String value) {
setIso2Code(value);
return this;
}
/**
* With country name.
*
* @param value the value
* @return the country element
*/
public CountryElement withCountryName(final String value) {
setCountryName(value);
return this;
}
/**
* With region.
*
* @param value the value
* @return the country element
*/
public CountryElement withRegion(final Region value) {
setRegion(value);
return this;
}
/**
* With adminregion.
*
* @param value the value
* @return the country element
*/
public CountryElement withAdminregion(final Adminregion value) {
setAdminregion(value);
return this;
}
/**
* With income level.
*
* @param value the value
* @return the country element
*/
public CountryElement withIncomeLevel(final IncomeLevel value) {
setIncomeLevel(value);
return this;
}
/**
* With lending type.
*
* @param value the value
* @return the country element
*/
public CountryElement withLendingType(final LendingType value) {
setLendingType(value);
return this;
}
/**
* With capital city.
*
* @param value the value
* @return the country element
*/
public CountryElement withCapitalCity(final String value) {
setCapitalCity(value);
return this;
}
/**
* With longitude.
*
* @param value the value
* @return the country element
*/
public CountryElement withLongitude(final String value) {
setLongitude(value);
return this;
}
/**
* With latitude.
*
* @param value the value
* @return the country element
*/
public CountryElement withLatitude(final String value) {
setLatitude(value);
return this;
}
/**
* With id.
*
* @param value the value
* @return the country element
*/
public CountryElement withId(final String value) {
setId(value);
return this;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public final int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public final String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
/**
* Gets the hjid.
*
* @return the hjid
*/
@Id
@Column(name = "HJID")
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getHjid() {
return hjid;
}
/**
* Sets the hjid.
*
* @param value the new hjid
*/
public void setHjid(final Long value) {
this.hjid = value;
}
/* (non-Javadoc)
* @see org.jvnet.jaxb2_commons.lang.Equals#equals(org.jvnet.jaxb2_commons.locator.ObjectLocator, org.jvnet.jaxb2_commons.locator.ObjectLocator, java.lang.Object, org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy)
*/
public boolean equals(final ObjectLocator thisLocator, final ObjectLocator thatLocator, final Object object, final EqualsStrategy strategy) {
if ((object == null)||(this.getClass()!= object.getClass())) {
return false;
}
if (this == object) {
return true;
}
final CountryElement that = ((CountryElement) object);
{
String lhsIso2Code;
lhsIso2Code = this.getIso2Code();
String rhsIso2Code;
rhsIso2Code = that.getIso2Code();
if (!strategy.equals(LocatorUtils.property(thisLocator, "iso2Code", lhsIso2Code), LocatorUtils.property(thatLocator, "iso2Code", rhsIso2Code), lhsIso2Code, rhsIso2Code)) {
return false;
}
}
{
String lhsCountryName;
lhsCountryName = this.getCountryName();
String rhsCountryName;
rhsCountryName = that.getCountryName();
if (!strategy.equals(LocatorUtils.property(thisLocator, "countryName", lhsCountryName), LocatorUtils.property(thatLocator, "countryName", rhsCountryName), lhsCountryName, rhsCountryName)) {
return false;
}
}
{
Region lhsRegion;
lhsRegion = this.getRegion();
Region rhsRegion;
rhsRegion = that.getRegion();
if (!strategy.equals(LocatorUtils.property(thisLocator, "region", lhsRegion), LocatorUtils.property(thatLocator, "region", rhsRegion), lhsRegion, rhsRegion)) {
return false;
}
}
{
Adminregion lhsAdminregion;
lhsAdminregion = this.getAdminregion();
Adminregion rhsAdminregion;
rhsAdminregion = that.getAdminregion();
if (!strategy.equals(LocatorUtils.property(thisLocator, "adminregion", lhsAdminregion), LocatorUtils.property(thatLocator, "adminregion", rhsAdminregion), lhsAdminregion, rhsAdminregion)) {
return false;
}
}
{
IncomeLevel lhsIncomeLevel;
lhsIncomeLevel = this.getIncomeLevel();
IncomeLevel rhsIncomeLevel;
rhsIncomeLevel = that.getIncomeLevel();
if (!strategy.equals(LocatorUtils.property(thisLocator, "incomeLevel", lhsIncomeLevel), LocatorUtils.property(thatLocator, "incomeLevel", rhsIncomeLevel), lhsIncomeLevel, rhsIncomeLevel)) {
return false;
}
}
{
LendingType lhsLendingType;
lhsLendingType = this.getLendingType();
LendingType rhsLendingType;
rhsLendingType = that.getLendingType();
if (!strategy.equals(LocatorUtils.property(thisLocator, "lendingType", lhsLendingType), LocatorUtils.property(thatLocator, "lendingType", rhsLendingType), lhsLendingType, rhsLendingType)) {
return false;
}
}
{
String lhsCapitalCity;
lhsCapitalCity = this.getCapitalCity();
String rhsCapitalCity;
rhsCapitalCity = that.getCapitalCity();
if (!strategy.equals(LocatorUtils.property(thisLocator, "capitalCity", lhsCapitalCity), LocatorUtils.property(thatLocator, "capitalCity", rhsCapitalCity), lhsCapitalCity, rhsCapitalCity)) {
return false;
}
}
{
String lhsLongitude;
lhsLongitude = this.getLongitude();
String rhsLongitude;
rhsLongitude = that.getLongitude();
if (!strategy.equals(LocatorUtils.property(thisLocator, "longitude", lhsLongitude), LocatorUtils.property(thatLocator, "longitude", rhsLongitude), lhsLongitude, rhsLongitude)) {
return false;
}
}
{
String lhsLatitude;
lhsLatitude = this.getLatitude();
String rhsLatitude;
rhsLatitude = that.getLatitude();
if (!strategy.equals(LocatorUtils.property(thisLocator, "latitude", lhsLatitude), LocatorUtils.property(thatLocator, "latitude", rhsLatitude), lhsLatitude, rhsLatitude)) {
return false;
}
}
{
String lhsId;
lhsId = this.getId();
String rhsId;
rhsId = that.getId();
if (!strategy.equals(LocatorUtils.property(thisLocator, "id", lhsId), LocatorUtils.property(thatLocator, "id", rhsId), lhsId, rhsId)) {
return false;
}
}
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(final Object object) {
final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE;
return equals(null, null, object, strategy);
}
}
| 26.458609 | 215 | 0.626932 |
f62cac86f58a3fae439d3cf5dd059fccf7c42493 | 2,339 | package frc.robot.utils;
import java.util.*;
/**
* Object that holds DashboardConfig values.
* This stores a list of DashboardKeys that are enabled,
* and any DashboardKeys missing are considered disabled.
* To add more DashboardKeys, simply add another Enum constant in DashboardKey.java.
*
* Provided methods return this object for chaining functionality.
*
* By default, new instances of this object will have all DashboardKeys enabled.
* Use #onlyEnabled to enable only specifically inputted DashboardKeys.
*
* @see DashboardKey
*/
public class DashboardConfig
{
private EnumSet<DashboardKey> enabledDashboardKeys;
/**
* By default, all DashboardKeys are enabled
*/
public DashboardConfig()
{
this.enabledDashboardKeys = EnumSet.allOf(DashboardKey.class);
}
/**
* Returns true if the DashboardKey is enabled, and false otherwise. Used in the BitBucketsSubsystem#updateDashboard method to determine whether to actually push the Dashboard update.
* @param key DashboardKey to check.
* @return true if the DashboardKey is enabled, and false if not.
*/
public boolean isEnabled(DashboardKey key)
{
return this.enabledDashboardKeys.contains(key);
}
/**
* Enable certain DashboardKeys. Since they are stored as a Set, there won't be duplicates.
* @param enabled DashboardKeys to enable.
* @return DashboardConfig object, for chaining.
*/
public DashboardConfig addEnabled(DashboardKey... enabled)
{
this.enabledDashboardKeys.addAll(List.of(enabled));
return this;
}
/**
* Enable only the provided DashboardKeys. Note: THIS WILL DISABLE ALL OTHER DASHBOARDKEYS!
* @param enabled DashboardKeys to enable.
* @return DashboardConfig object, for chaining.
*/
public DashboardConfig onlyEnabled(DashboardKey... enabled)
{
this.enabledDashboardKeys = EnumSet.copyOf(List.of(enabled));
return this;
}
/**
* Disable certain DashboardKeys safely.
* @param disabled DashboardKeys to disable.
* @return DashboardConfig object, for chaining.
*/
public DashboardConfig addDisabled(DashboardKey... disabled)
{
this.enabledDashboardKeys.removeIf(d -> List.of(disabled).contains(d));
return this;
}
}
| 32.041096 | 187 | 0.699017 |
13aecf251496400fadc389c394832e581850ac0b | 2,408 | /*
* Copyright (C) 1999-2011 University of Connecticut Health Center
*
* Licensed under the MIT License (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.opensource.org/licenses/mit-license.php
*/
package cbit.image;
public class TiffTester
{
public static void main(String argv[]) {
if (argv.length!=1 && argv.length!=2){
// System.out.println("usage:");
// System.out.println(" java cbit.image.TiffTester filename [outfilename]");
// return;
int xsize = 100;
int ysize = 100;
int zsize = 1;
byte data[] = new byte[xsize*ysize*zsize];
for (int i=0;i<xsize;i++){
for (int j=0;j<ysize;j++){
for (int k=0;k<1;k++){
byte pixel = (byte)(64.0 + 63*Math.sin(((float)(i*j))/((xsize*ysize)/10)));
data[i+j*xsize+k*xsize*ysize] = pixel;
}
}
}
TiffImage img = new TiffImage(xsize, ysize, zsize, data);
try {
img.write("special.tif",ByteOrder.Unix);
System.out.println("generating test file <special.tif>");
System.out.println("normal usage:");
System.out.println(" java cbit.image.TiffTester filename [outfilename]");
}catch(Exception e){
e.printStackTrace();
return;
}
return;
}
//
// test reading via filename
//
TiffImage imgFile = new TiffImage();
try {
imgFile.read(new FileTiffInputSource(argv[0]));
}catch (Exception e){
e.printStackTrace();
System.out.println("failure reading Tiff file: " + argv[0]);
return;
}
//
// test reading via byte array
//
TiffImage imgByteArray = new TiffImage();
try {
java.io.File inputFile = new java.io.File(argv[0]);
java.io.DataInputStream dis = new java.io.DataInputStream(new java.io.FileInputStream(inputFile));
byte buffer[] = new byte[(int)inputFile.length()];
dis.readFully(buffer);
imgByteArray.read(new ByteArrayTiffInputSource(buffer));
}catch (Exception e){
e.printStackTrace();
System.out.println("failure reading Tiff file: " + argv[0]);
return;
}
if (argv.length==2){
try {
imgFile.write(argv[1]+".file.tif",ByteOrder.Unix);
imgByteArray.write(argv[1]+".byteArray.tif",ByteOrder.Unix);
}catch (Exception e){
e.printStackTrace();
System.out.println("failure writing Tiff file: " + argv[1]);
return;
}
}
}
}
| 29.012048 | 101 | 0.631645 |
82f366e9fdfe281b5aeb7577e0ae55235f08d98d | 763 | package com.baisi.spedometer.utiles;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Created by hanwenmao on 2018/3/8.
*/
public class NetUtils {
/**
* 判断网络连接是否有效(此时可传输数据)。
*
* @return boolean 不管wifi,还是mobile net,只有当前在连接状态(可有效传输数据)才返回true,反之false。
*/
public static boolean isConnected(Context context) {
NetworkInfo net = getConnectivityManager(context).getActiveNetworkInfo();
return net != null && net.isConnected();
}
/**
* 获取ConnectivityManager
*/
public static ConnectivityManager getConnectivityManager(Context context) {
return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
}
| 26.310345 | 92 | 0.706422 |
9e2fa395a1a7d895ec1c4089f92930632b63f9d8 | 380 | package betterquesting.api2.client.gui.panels;
import javax.annotation.Nonnull;
import java.util.List;
public interface IGuiCanvas extends IGuiPanel
{
void addPanel(IGuiPanel panel);
boolean removePanel(IGuiPanel panel);
@Nonnull
List<IGuiPanel> getChildren();
/**
* Removes all children and resets the canvas to its initial blank state
*/
void resetCanvas();
} | 21.111111 | 73 | 0.760526 |
430ec6557298591c7cdf75b28c9185d00eecf684 | 10,959 | /*
* $Id$
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.codebehind;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ObjectFactory;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.UnknownHandler;
import com.opensymphony.xwork2.XWorkException;
import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.config.entities.InterceptorLocator;
import com.opensymphony.xwork2.config.entities.PackageConfig;
import com.opensymphony.xwork2.config.entities.ResultConfig;
import com.opensymphony.xwork2.config.entities.ResultTypeConfig;
import com.opensymphony.xwork2.config.providers.InterceptorBuilder;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ClassLoaderUtil;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import javax.servlet.ServletContext;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Uses code-behind conventions to solve the two unknown problems.
*/
public class CodebehindUnknownHandler implements UnknownHandler {
protected String defaultPackageName;
protected ServletContext servletContext;
protected Map<String,ResultTypeConfig> resultsByExtension;
protected String templatePathPrefix;
protected Configuration configuration;
protected ObjectFactory objectFactory;
protected static final Logger LOG = LoggerFactory.getLogger(CodebehindUnknownHandler.class);
@Inject
public CodebehindUnknownHandler(@Inject("struts.codebehind.defaultPackage") String defaultPackage,
@Inject Configuration configuration) {
this.configuration = configuration;
this.defaultPackageName = defaultPackage;
resultsByExtension = new LinkedHashMap<String,ResultTypeConfig>();
PackageConfig parentPackage = configuration.getPackageConfig(defaultPackageName);
if (parentPackage == null) {
throw new ConfigurationException("Unknown parent package: "+parentPackage);
}
Map<String,ResultTypeConfig> results = parentPackage.getAllResultTypeConfigs();
resultsByExtension.put("jsp", results.get("dispatcher"));
resultsByExtension.put("vm", results.get("velocity"));
resultsByExtension.put("ftl", results.get("freemarker"));
}
@Inject("struts.codebehind.pathPrefix")
public void setPathPrefix(String prefix) {
this.templatePathPrefix=prefix;
}
@Inject
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
@Inject
public void setObjectFactory(ObjectFactory objectFactory) {
this.objectFactory = objectFactory;
}
public ActionConfig handleUnknownAction(String namespace, String actionName)
throws XWorkException {
String pathPrefix = determinePath(templatePathPrefix, namespace);
ActionConfig actionConfig = null;
for (String ext : resultsByExtension.keySet()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to locate unknown action template with extension ."+ext+" in directory "+pathPrefix);
}
String path = string(pathPrefix, actionName, "." , ext);
try {
if (locateTemplate(path) != null) {
actionConfig = buildActionConfig(path, namespace, actionName, resultsByExtension.get(ext));
break;
}
} catch (MalformedURLException e) {
LOG.warn("Unable to parse template path: "+path+", skipping...");
}
}
return actionConfig;
}
/** Create a new ActionConfig in the default package, with the default interceptor stack and a single result */
protected ActionConfig buildActionConfig(String path, String namespace, String actionName, ResultTypeConfig resultTypeConfig) {
final PackageConfig pkg = configuration.getPackageConfig(defaultPackageName);
return new ActionConfig.Builder(defaultPackageName, "execute", pkg.getDefaultClassRef())
.addInterceptors(InterceptorBuilder.constructInterceptorReference(new InterceptorLocator() {
public Object getInterceptorConfig(String name) {
return pkg.getAllInterceptorConfigs().get(name); // recurse package hiearchy
}
}, pkg.getFullDefaultInterceptorRef(),
Collections.EMPTY_MAP, null, objectFactory))
.addResultConfig(new ResultConfig.Builder(Action.SUCCESS, resultTypeConfig.getClassName())
.addParams(resultTypeConfig.getParams())
.addParam(resultTypeConfig.getDefaultResultParam(), path)
.build())
.build();
}
public Result handleUnknownResult(ActionContext actionContext, String actionName,
ActionConfig actionConfig, String resultCode) throws XWorkException {
Result result = null;
PackageConfig pkg = configuration.getPackageConfig(actionConfig.getPackageName());
String ns = pkg.getNamespace();
String pathPrefix = determinePath(templatePathPrefix, ns);
for (String ext : resultsByExtension.keySet()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to locate result with extension ."+ext+" in directory "+pathPrefix);
}
String path = string(pathPrefix, actionName, "-", resultCode, "." , ext);
try {
if (locateTemplate(path) != null) {
result = buildResult(path, resultCode, resultsByExtension.get(ext), actionContext);
break;
}
} catch (MalformedURLException e) {
LOG.warn("Unable to parse template path: "+path+", skipping...");
}
path = string(pathPrefix, actionName, "." , ext);
try {
if (locateTemplate(path) != null) {
result = buildResult(path, resultCode, resultsByExtension.get(ext), actionContext);
break;
}
} catch (MalformedURLException e) {
LOG.warn("Unable to parse template path: "+path+", skipping...");
}
}
return result;
}
protected Result buildResult(String path, String resultCode, ResultTypeConfig config, ActionContext invocationContext) {
ResultConfig resultConfig = new ResultConfig.Builder(resultCode, config.getClassName())
.addParams(config.getParams())
.addParam(config.getDefaultResultParam(), path)
.build();
try {
return objectFactory.buildResult(resultConfig, invocationContext.getContextMap());
} catch (Exception e) {
throw new XWorkException("Unable to build codebehind result", e, resultConfig);
}
}
protected String string(String... parts) {
StringBuilder sb = new StringBuilder();
for (String part : parts) {
sb.append(part);
}
return sb.toString();
}
protected String joinPaths(boolean leadingSlash, boolean trailingSlash, String... parts) {
StringBuilder sb = new StringBuilder();
if (leadingSlash) {
sb.append("/");
}
for (String part : parts) {
if (sb.length() > 0 && sb.charAt(sb.length()-1) != '/') {
sb.append("/");
}
sb.append(stripSlashes(part));
}
if (trailingSlash) {
if (sb.length() > 0 && sb.charAt(sb.length()-1) != '/') {
sb.append("/");
}
}
return sb.toString();
}
protected String determinePath(String prefix, String ns) {
return joinPaths(true, true, prefix, ns);
}
protected String stripLeadingSlash(String path) {
String result;
if (path != null) {
if (path.length() > 0) {
if (path.charAt(0) == '/') {
result = path.substring(1);
} else {
result = path;
}
} else {
result = path;
}
} else {
result = "";
}
return result;
}
protected String stripTrailingSlash(String path) {
String result;
if (path != null) {
if (path.length() > 0) {
if (path.charAt(path.length() - 1) == '/') {
result = path.substring(0, path.length()-1);
} else {
result = path;
}
} else {
result = path;
}
} else {
result = "";
}
return result;
}
protected String stripSlashes(String path) {
return stripLeadingSlash(stripTrailingSlash(path));
}
URL locateTemplate(String path) throws MalformedURLException {
URL template = servletContext.getResource(path);
if (template != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Loaded template '" + path + "' from servlet context.");
}
} else {
template = ClassLoaderUtil.getResource(stripLeadingSlash(path), getClass());
if (template != null && LOG.isDebugEnabled()) {
LOG.debug("Loaded template '" + stripLeadingSlash(path) + "' from class path.");
}
}
return template;
}
/**
* Not used
*/
public Object handleUnknownActionMethod(Object action, String methodName) throws NoSuchMethodException {
throw new NoSuchMethodException();
}
}
| 38.861702 | 131 | 0.623871 |
ba213ad215a2d0b722d0fa40d2c867fbd8f5dfcc | 1,131 | package org.apache.http.params;
@Deprecated
public interface HttpParams {
Object getParameter(String paramString);
HttpParams setParameter(String paramString, Object paramObject);
HttpParams copy();
boolean removeParameter(String paramString);
long getLongParameter(String paramString, long paramLong);
HttpParams setLongParameter(String paramString, long paramLong);
int getIntParameter(String paramString, int paramInt);
HttpParams setIntParameter(String paramString, int paramInt);
double getDoubleParameter(String paramString, double paramDouble);
HttpParams setDoubleParameter(String paramString, double paramDouble);
boolean getBooleanParameter(String paramString, boolean paramBoolean);
HttpParams setBooleanParameter(String paramString, boolean paramBoolean);
boolean isParameterTrue(String paramString);
boolean isParameterFalse(String paramString);
}
/* Location: C:\Users\Main\AppData\Roaming\StreamCraf\\updates\Launcher.jar!\org\apache\http\params\HttpParams.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ | 29.763158 | 129 | 0.768347 |
51d555edede88c9b958af85832a170f693c6a6f4 | 194 | package com.truelayer.java.merchantaccounts.entities;
import java.util.List;
import lombok.Value;
@Value
public class ListMerchantAccountsResponse {
private List<MerchantAccount> items;
}
| 19.4 | 53 | 0.809278 |
0e45ece143c895563904f51a6a2c6eca8665f5fe | 676 | package ru.task.clickerapplication.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.task.clickerapplication.service.ClickService;
@RestController
@RequiredArgsConstructor
public class Controller{
private final ClickService clickService;
@PostMapping(value = "/index")
public String incrementCounter() {
return clickService.increment();
}
@GetMapping(value ="/index")
public String getCounter() {
return clickService.getCounter();
}
} | 28.166667 | 62 | 0.773669 |
963be86ebfd0cd5a48b169242c34120c2be97d19 | 4,305 | /* DungeonDiver7: A Dungeon-Diving RPG
Copyright (C) 2021-present Eric Ahnell
Any questions should be directed to the author via email at: products@puttysoftware.com
*/
package com.puttysoftware.dungeondiver7.dungeon.objects;
import com.puttysoftware.dungeondiver7.DungeonDiver7;
import com.puttysoftware.dungeondiver7.dungeon.abstractobjects.AbstractMovableObject;
import com.puttysoftware.dungeondiver7.game.GameManager;
import com.puttysoftware.dungeondiver7.loaders.SoundConstants;
import com.puttysoftware.dungeondiver7.loaders.SoundLoader;
import com.puttysoftware.dungeondiver7.utilities.ActionConstants;
import com.puttysoftware.dungeondiver7.utilities.Direction;
import com.puttysoftware.dungeondiver7.utilities.DirectionResolver;
import com.puttysoftware.dungeondiver7.utilities.ArrowTypeConstants;
import com.puttysoftware.dungeondiver7.utilities.TypeConstants;
public class ArrowTurret extends AbstractMovableObject {
// Fields
private boolean autoMove;
private boolean canShoot;
// Constructors
public ArrowTurret() {
super(true);
this.setDirection(Direction.NORTH);
this.setFrameNumber(1);
this.activateTimer(1);
this.canShoot = true;
this.autoMove = false;
this.type.set(TypeConstants.TYPE_ANTI);
}
public void kill(final int locX, final int locY) {
if (this.canShoot) {
DungeonDiver7.getApplication().getGameManager().setLaserType(ArrowTypeConstants.LASER_TYPE_RED);
DungeonDiver7.getApplication().getGameManager().fireLaser(locX, locY, this);
this.canShoot = false;
}
}
@Override
public boolean canShoot() {
return true;
}
@Override
public void laserDoneAction() {
this.canShoot = true;
}
@Override
public boolean acceptTick(final int actionType) {
return actionType == ActionConstants.ACTION_MOVE;
}
@Override
public Direction laserEnteredAction(final int locX, final int locY, final int locZ, final int dirX, final int dirY,
final int laserType, final int forceUnits) {
final Direction baseDir = this.getDirection();
if (laserType == ArrowTypeConstants.LASER_TYPE_MISSILE || laserType == ArrowTypeConstants.LASER_TYPE_POWER) {
// Kill
final GameManager gm = DungeonDiver7.getApplication().getGameManager();
final DeadArrowTurret dat = new DeadArrowTurret();
dat.setSavedObject(this.getSavedObject());
dat.setDirection(baseDir);
gm.morph(dat, locX, locY, locZ, this.getLayer());
SoundLoader.playSound(SoundConstants.SOUND_ANTI_DIE);
return Direction.NONE;
} else if (laserType == ArrowTypeConstants.LASER_TYPE_STUNNER) {
// Stun
final GameManager gm = DungeonDiver7.getApplication().getGameManager();
final StunnedArrowTurret sat = new StunnedArrowTurret();
sat.setSavedObject(this.getSavedObject());
sat.setDirection(baseDir);
gm.morph(sat, locX, locY, locZ, this.getLayer());
SoundLoader.playSound(SoundConstants.SOUND_STUN);
return Direction.NONE;
} else {
final Direction sourceDir = DirectionResolver.resolveRelativeDirectionInvert(dirX, dirY);
if (sourceDir == baseDir) {
// Kill
final GameManager gm = DungeonDiver7.getApplication().getGameManager();
final DeadArrowTurret dat = new DeadArrowTurret();
dat.setSavedObject(this.getSavedObject());
dat.setDirection(baseDir);
gm.morph(dat, locX, locY, locZ, this.getLayer());
SoundLoader.playSound(SoundConstants.SOUND_ANTI_DIE);
return Direction.NONE;
} else {
return super.laserEnteredAction(locX, locY, locZ, dirX, dirY, laserType, forceUnits);
}
}
}
@Override
public void timerExpiredAction(final int locX, final int locY) {
if (this.getSavedObject().isOfType(TypeConstants.TYPE_ANTI_MOVER)) {
final Direction moveDir = this.getSavedObject().getDirection();
final int[] unres = DirectionResolver.unresolveRelativeDirection(moveDir);
if (GameManager.canObjectMove(locX, locY, unres[0], unres[1])) {
if (this.autoMove) {
this.autoMove = false;
DungeonDiver7.getApplication().getGameManager().updatePushedPosition(locX, locY, locX + unres[0],
locY + unres[1], this);
}
} else {
this.autoMove = true;
}
}
this.activateTimer(1);
}
@Override
public final int getStringBaseID() {
return 0;
}
@Override
public void playSoundHook() {
SoundLoader.playSound(SoundConstants.SOUND_PUSH_ANTI_TANK);
}
}
| 34.44 | 116 | 0.759117 |
a8e2f9063e3f71381d9799a95cb0fb2c11c9c3e8 | 1,054 | package net.michelison.homebitbot;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity implements View.OnClickListener {
private Button bitBotButton;
private Button listViewButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bitBotButton = findViewById(R.id.bitBotButton);
listViewButton = findViewById(R.id.listViewButton);
// dan set the listeners
bitBotButton.setOnClickListener(this);
listViewButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.bitBotButton:
startActivity(new Intent(this, BotActivity.class));
case R.id.listViewButton:
startActivity(new Intent(this, DropDownActivity.class));
}
}
}
| 27.025641 | 76 | 0.687856 |
617ac7062d2c9416249405c9dc0a0293588853bd | 2,576 | package drawer1;
import javax.swing.*;
import java.awt.*;
/**
* This class represents JFrames with a tool bar across the top containing
* three buttons labeled "Rect", "Square", and "Ellipse" and a canvas
* below for drawing. When the user clicks in the canvas, a rectangle,
* square, or ellipse is drawn, depending on the selected button,
* centered at the click.
*
* @author Dale Skrien
* @version 1.0 August 2005
*/
public class DrawingFrame extends JFrame
{
/**
* constructs but does not display a new DrawingFrame
*/
public DrawingFrame()
{
super("Drawing Application");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JComponent drawingCanvas = createDrawingCanvas();
add(drawingCanvas, BorderLayout.CENTER);
JToolBar toolbar = createToolbar(drawingCanvas);
add(toolbar, BorderLayout.NORTH);
}
/**
* creates the canvas (the part of the window below the tool bar)
* with certain attributes (size, background color, and border)
* @return the new JComponent that is the canvas
*/
private JComponent createDrawingCanvas()
{
JComponent drawingCanvas = new JPanel();
drawingCanvas.setPreferredSize(new Dimension(400, 300));
drawingCanvas.setBackground(Color.white);
drawingCanvas.setBorder(BorderFactory.createEtchedBorder());
return drawingCanvas;
}
/**
* creates the tool bar with the three buttons and creates a
* CanvasEditor that it registers as listener to the three buttons
* @return the new tool bar
* @param canvas the JComponent forming the drawing canvas
*/
private JToolBar createToolbar(JComponent canvas)
{
JToolBar toolbar = new JToolBar();
//add the buttons to the toolbar
JButton ellipseButton = new JButton("Ellipse");
toolbar.add(ellipseButton);
JButton squareButton = new JButton("Square");
toolbar.add(squareButton);
JButton rectButton = new JButton("Rect");
toolbar.add(rectButton);
//add the CanvasEditor listener to the canvas and to the buttons,
//with the ellipseButton initially selected
CanvasEditor canvasEditor = new CanvasEditor(ellipseButton);
ellipseButton.addActionListener(canvasEditor);
squareButton.addActionListener(canvasEditor);
rectButton.addActionListener(canvasEditor);
canvas.addMouseListener(canvasEditor);
return toolbar;
}
}
| 34.346667 | 75 | 0.662655 |
dffbf1e5ddcb576abe110da0454e21b2e8917acc | 1,108 | package phys2d.collisionLogic.spacePartitioning;
import java.awt.Graphics2D;
import java.util.ArrayList;
import phys2d.entities.shapes.Shape;
public abstract class SpacePartitioningTree {
protected final int DEPTH_CAP;
protected final int MAX_ITEMS;
/**
* Initializes the depth cap and maximum items per node, for this space
* partitioning tree.
*
* @param DEPTH_CAP the maximum depth of the tree.
* @param MAX_ITEMS the maximum items per node of the tree.
*/
protected SpacePartitioningTree(int DEPTH_CAP, int MAX_ITEMS) {
this.DEPTH_CAP = DEPTH_CAP;
this.MAX_ITEMS = MAX_ITEMS;
}
/**
* Insert the shape into the current node of this space partitioning tree.
*
* @param s the shape to insert.
*/
public abstract void insert(Shape s);
/**
* Cleans this tree by reseting it's children and items.
*/
public abstract void refresh();
public abstract ArrayList<Shape[]> getPossibleCollisions();
public abstract void draw(Graphics2D g2d);
}
| 26.380952 | 79 | 0.657942 |
0c2d5b5f92925f573eb3b2248f247a42d64ee7e7 | 148 | package rosetta;
public class MDC_DIM_X_G_PER_M_PER_SEC {
public static final String VALUE = "MDC_DIM_X_G_PER_M_PER_SEC";
}
| 16.444444 | 67 | 0.695946 |
9a4269e82f0e9c060747d7c86effc57532e6ce6d | 4,896 | package ie.gmit.sw;
import java.io.*;
import java.rmi.*;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServiceHandler extends HttpServlet {
private static final long serialVersionUID = 1L;
private String remoteHost = null;
private static long jobNumber = 0;
private static LinkedList<Request> InQueue;
private static Map<String, Resultator> OutQueue;
private static ExecutorService executor;
private final int EXECUTOR_POOL_SIZE = 10;
private boolean checkProcessed = false;
private String distance = "";
public void init() throws ServletException {
ServletContext ctx = getServletContext();
remoteHost = ctx.getInitParameter("RMI_SERVER"); //Reads the value from the <context-param> in web.xml
InQueue = new LinkedList<Request>();
OutQueue = new HashMap<String, Resultator>();
executor = Executors.newFixedThreadPool(EXECUTOR_POOL_SIZE);
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
//Initialize some request variables with the submitted form info. These are local to this method and thread safe...
String algorithm = req.getParameter("cmbAlgorithm");
String str1 = req.getParameter("txtS");
String str2 = req.getParameter("txtT");
String taskNumber = req.getParameter("frmTaskNumber");
StringService ss = null;
try {
ss = (StringService) Naming.lookup("rmi://localhost:1099/StringService");
} catch (NotBoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.print("<html><head><title>Distributed Systems Assignment</title>");
out.print("</head>");
out.print("<body>");
if (taskNumber == null){
taskNumber = new String("T" + jobNumber);
//Reset checkProcessed to false
checkProcessed = false;
// Create a new Request OBJECT
Request request = new Request(algorithm, str1, str2 , taskNumber);
// Add Task to in-queue
InQueue.add(request);
// Pass the Request Obj to a Worker Class (Thread)
Runnable worker = new Worker(InQueue, OutQueue, ss);
// Execute the Worker(EXECUTOR_POOL_SIZE)
executor.execute(worker);
jobNumber++;
}else{
// ELSE - Check outQueue for finished job
// Check HashMap
if (OutQueue.containsKey(taskNumber)) {
Resultator result = OutQueue.get(taskNumber);
//console print
System.out.println("\nChecking Status of Task No : " + taskNumber);
checkProcessed = result.isProcessed();
// if checkProcessed is True
if (checkProcessed == true) {
// Remove the processed item from HashMap by taskNumber
OutQueue.remove(taskNumber);
//Get the Result of the Current Task
distance = result.getResult();
//Console print
System.out.println("Task : " + taskNumber + " Removed from OutQueue");
System.out.println("\nDistance Between String (" + str1 + ") and String (" + str2 + ") = " + distance);
out.print("<font color=\"#993333\"><b>");
out.print("<br><br><center><h1>Job#: " + taskNumber + " has been processed</h1><center>");
out.print("<br>Distance was calculated as: " + distance);
out.print("<br>Algorithm: " + algorithm);
out.print("<br>String <i>one</i> : " + str1);
out.print("<br>String <i>two</i> : " + str2);
}
}
}
if(!checkProcessed){
out.print("<font color=\"#993333\"><b>");
out.print("<br><br><center><h1>Processing request for Job#: " + taskNumber + "</h1><center>");
out.print("<br><h3>Please wait....</h3><br>");
out.print("RMI Server is located at " + remoteHost);
out.print("<br>Algorithm: " + algorithm);
out.print("<br>String <i>one</i> : " + str1);
out.print("<br>String <i>two</i> : " + str2);
//put an if statement here to stop page refresh
out.print("<form name=\"frmRequestDetails\">");
out.print("<input name=\"cmbAlgorithm\" type=\"hidden\" value=\"" + algorithm + "\">");
out.print("<input name=\"txtS\" type=\"hidden\" value=\"" + str1 + "\">");
out.print("<input name=\"txtT\" type=\"hidden\" value=\"" + str2 + "\">");
out.print("<input name=\"frmTaskNumber\" type=\"hidden\" value=\"" + taskNumber + "\">");
out.print("</form>");
out.print("</body>");
out.print("</html>");
//this refreshes the page
out.print("<script>");
out.print("var wait=setTimeout(\"document.frmRequestDetails.submit();\", 10000);");
out.print("</script>");
}
//You can use this method to implement the functionality of an RMI client
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
} | 32.85906 | 117 | 0.656046 |
f4fc39d7b8b2cd69f64062f44413636f587aa2d0 | 451 | package com.example.vjobanputra.simpletodo;
/**
* Created by vjobanputra on 8/22/15.
*/
public class Priority {
static String[] options = {"High",
"Medium",
"Low"};
public static int getPosition(String s) {
for (int i = 0; i <= options.length; i++) {
if (options[i].equals(s)) {
return i;
}
}
return 0;
}
}
| 20.5 | 51 | 0.450111 |
1d3c11a904b7541e3f0cecb57c53cf4cb77c0cdd | 9,493 | package org.unfoldingword.tools.http;
import android.util.Base64;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
/**
* Represents a network request
*/
public abstract class Request {
private final URL url;
private final String requestMethod;
private String auth = null;
private String contentType = null;
private int responseCode = -1;
private String responseMessage = null;
private int ttl = 5000;
private OnProgressListener progressListener = null;
/**
* Prepare a new network request
* @param url The url that will receive the request
* @param requestMethod the method of request e.g. POST, GET, PUT, etc.
*/
public Request(URL url, String requestMethod) {
this.url = url;
this.requestMethod = requestMethod.toUpperCase();
}
/**
* Sets the authentication token for the request.
* The auth label will be "Bearer". Use {@link #setAuth(String, String)} to customize the label.
* @param token
*/
public void setAuth(String token) {
setAuth(token, "Bearer");
}
/**
* Sets the authentication for the request
* @param token
* @param label the auth label
*/
public void setAuth(String token, String label) {
this.auth = label + " " + token;
}
/**
* Sets the username and password used for authenticating the request.
* @param username
* @param password
*/
public void setCredentials(String username, String password) throws UnsupportedEncodingException {
String credentials = username + ":" + password;
String token = Base64.encodeToString(credentials.getBytes("UTF-8"), Base64.NO_WRAP);
setAuth(token, "Basic");
}
/**
* Sets the connection write and read timeout
* @param ttl the time allowed before the connection times out
*/
public void setTimeout(int ttl) {
this.ttl = ttl;
}
/**
* Sets the listener to receive progress updates
* @param listener a listener that will receive progress events
*/
public void setProgressListener(OnProgressListener listener) {
this.progressListener = listener;
}
/**
* Sets the token used for authenticating the post request
* Tokens take precedence over credentials
* Token authentication.
* @deprecated use {@link #setAuth(String)} instead
* @param token the authentication token
*/
public void setAuthentication(String token) {
setAuth(token, "token");
}
/**
* Sets the credentials used for authenticating the report
* Basic authentication.
* @deprecated use {@link #setCredentials(String, String)} instead
* @param username the username to be authenticated as
* @param password the password to authenticate with
*/
public void setAuthentication(String username, String password) {
try {
setCredentials(username, password);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
auth = null;
}
}
/**
* Sets the content type to be used in the request
* @param contentType the content type of the request
*/
public void setContentType(String contentType) {
this.contentType = contentType;
}
/**
* Creates a new connection object
* @return a connection object
* @throws IOException
*/
protected HttpURLConnection openConnection() throws IOException {
HttpURLConnection conn;
if(url.getProtocol().equals("https")) {
conn = (HttpsURLConnection)url.openConnection();
} else {
conn = (HttpURLConnection)url.openConnection();
}
if(this.auth != null) {
conn.setRequestProperty("Authorization", this.auth);
}
if(contentType != null) {
conn.setRequestProperty("Content-Type", contentType);
}
conn.setRequestMethod(requestMethod);
conn.setConnectTimeout(ttl);
conn.setReadTimeout(ttl);
try {
onConnected(conn);
} catch (IOException e) {
throw e;
} finally {
responseCode = conn.getResponseCode();
responseMessage = conn.getResponseMessage();
}
return conn;
}
/**
* Submits data to the connection.
* Such as in a POST or PUT request.
* @param connection the connection that will receive the data
* @param data the data to be sent
* @throws IOException
*/
protected void writeData(HttpURLConnection connection, String data) throws IOException {
connection.setDoOutput(true);
DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(data);
dos.flush();
dos.close();
}
/**
* Downloads the response to a file
* @param destination the file where the response will be downloaded to
* @throws IOException
*/
public final void download(File destination) throws IOException {
HttpURLConnection connection = openConnection();
int responseSize = connection.getContentLength();
destination.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(destination);
int updateInterval = 1048 * 50; // send an update each time some bytes have been downloaded
int updateQueue = 0;
int bytesRead = 0;
InputStream in = null;
try {
in = new BufferedInputStream(connection.getInputStream());
byte[] buffer = new byte[4096];
int n = 0;
while ((n = in.read(buffer)) != -1) {
bytesRead += n;
updateQueue += n;
out.write(buffer, 0, n);
// send updates
if (updateQueue >= updateInterval) {
updateQueue = 0;
publishProgress(responseSize, bytesRead);
}
}
publishProgress(responseSize, bytesRead);
} catch (Exception e) {
if(in != null) in.close();
out.close();
connection.disconnect();
if(destination.exists()) destination.delete();
throw e;
}
if(in != null) in.close();
out.close();
connection.disconnect();
}
/**
* Reads the response as a string
* @return the response string
* @throws IOException
*/
public final String read() throws IOException {
HttpURLConnection connection = openConnection();
int responseSize = connection.getContentLength();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int updateInterval = 1048 * 50; // send an update each time some bytes have been downloaded
int updateQueue = 0;
int bytesRead = 0;
BufferedInputStream in = null;
try {
in = new BufferedInputStream(connection.getInputStream());
int n = 0;
while ((n = in.read()) != -1) {
out.write((byte) n);
// send updates
if (updateQueue >= updateInterval) {
updateQueue = 0;
publishProgress(responseSize, bytesRead);
}
}
publishProgress(responseSize, bytesRead);
} catch (Exception e) {
throw e;
} finally {
if(in != null) in.close();
out.close();
connection.disconnect();
}
return out.toString("UTF-8");
}
/**
* Sends notifications to the progress listener
* @param totalBytes the total size of the payload
* @param bytesRead the number of bytes read
*/
private void publishProgress(long totalBytes, long bytesRead) {
if(progressListener == null) return;
if(totalBytes <= 0 || bytesRead <= 0) {
progressListener.onIndeterminate();
} else {
progressListener.onProgress(totalBytes, bytesRead);
}
}
/**
* Returns the response code for this request
* @return the request response code
*/
public int getResponseCode() {
return responseCode;
}
/**
* Returns the error message for this request
* @return an error message
*/
public String getResponseMessage() {
return responseMessage;
}
/**
* Allows subclasses to perform operations afer the connection has been opened.
* For example: writing data to the connection.
*
* @throws IOException
*/
protected abstract void onConnected(HttpURLConnection conn) throws IOException;
public interface OnProgressListener {
/**
* Receives progress events
* @param max the total number of items being processed
* @param progress the number of items that have been successfully processed
*/
void onProgress(long max, long progress);
/**
* Receives a notice that the progresss is indeterminate
*/
void onIndeterminate();
}
}
| 30.524116 | 102 | 0.6075 |
1d541e97b90b3ad5e3274dab23e79d71b1c93b53 | 1,339 | package org.vertx.java.core.sockjs;
import org.vertx.java.core.json.JsonObject;
/**
* A hook that you can use to receive various events on the EventBusBridge.<p>
*/
public interface EventBusBridgeHook {
/**
* The socket has been closed
* @param sock The socket
*/
void handleSocketClosed(SockJSSocket sock);
/**
* Client is sending or publishing on the socket
* @param sock The sock
* @param send if true it's a send else it's a publish
* @param msg The message
* @param address The address the message is being sent/published to
* @return true To allow the send/publish to occur, false otherwise
*/
boolean handleSendOrPub(SockJSSocket sock, boolean send, JsonObject msg, String address);
/**
* Called before client registers a handler
* @param sock The socket
* @param address The address
* @return true to let the registration occur, false otherwise
*/
boolean handlePreRegister(SockJSSocket sock, String address);
/**
* Called after client registers a handler
* @param sock The socket
* @param address The address
*/
void handlePostRegister(SockJSSocket sock, String address);
/**
* Client is unregistering a handler
* @param sock The socket
* @param address The address
*/
boolean handleUnregister(SockJSSocket sock, String address);
}
| 27.895833 | 91 | 0.709485 |
56d11c9b4dbfe20d77c1dd86201731f9de9125e4 | 249 | package org.esreport;
import org.elasticsearch.common.inject.AbstractModule;
public class ESReportPluginRestModule extends AbstractModule {
protected void configure() {
bind(ESReportPluginRestHandler.class).asEagerSingleton();
}
} | 24.9 | 65 | 0.779116 |
efc13e250bced252d28c54b08f8c4d6fd7cc983b | 17,881 | /*
* Copyright 2006-2016 Edward Smith
*
* 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 root.adt;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import junit.framework.TestCase;
import root.lang.StringExtractor;
import root.random.RNG;
import root.random.RNGKiss;
import root.random.SeedFactoryConstant;
/**
* Test the {@link ListArrayLong} class.
*
* @author Edward Smith
* @version 0.5
* @since 0.5
*/
public final class ListArrayLongTest extends TestCase {
private ListArrayLong list;
public ListArrayLongTest() {
super("ListArrayLong");
}
@Override
@Before
public void setUp() throws Exception {
this.list = new ListArrayLong();
}
@Test
public void testAdd() {
final long foo = "foo".hashCode();
assertEquals(0, this.list.size);
this.list.add(foo);
assertEquals(1, this.list.size);
assertEquals(foo, this.list.get(0));
this.list.add(foo);
assertEquals(2, this.list.size);
assertEquals(foo, this.list.get(1));
this.list.add(foo);
assertEquals(3, this.list.size);
assertEquals(foo, this.list.get(2));
this.list.add(foo);
assertEquals(4, this.list.size);
assertEquals(foo, this.list.get(3));
this.list.add(foo);
assertEquals(5, this.list.size);
assertEquals(foo, this.list.get(4));
this.list.add(foo);
assertEquals(6, this.list.size);
assertEquals(foo, this.list.get(5));
this.list.add(foo);
assertEquals(7, this.list.size);
assertEquals(foo, this.list.get(6));
this.list.add(foo);
assertEquals(8, this.list.size);
assertEquals(8, this.list.values.length);
assertEquals(foo, this.list.get(7));
this.list.add(foo);
assertEquals(9, this.list.size);
assertEquals(16, this.list.values.length);
assertEquals(foo, this.list.get(8));
}
@Test
public void testAddAllArray() {
final long[] array = { "foo".hashCode(), "bar".hashCode() };
assertEquals(0, this.list.size);
this.list.addAll(array, 0, 2);
assertEquals(2, this.list.size);
assertEquals(101574L, this.list.get(0));
assertEquals(97299L, this.list.get(1));
this.list.addAll(array, 0, 1);
assertEquals(3, this.list.size);
assertEquals(101574L, this.list.get(0));
assertEquals(97299L, this.list.get(1));
assertEquals(101574L, this.list.get(2));
this.list.addAll(array, 1, 1);
assertEquals(4, this.list.size);
assertEquals(101574L, this.list.get(0));
assertEquals(97299L, this.list.get(1));
assertEquals(101574L, this.list.get(2));
assertEquals(97299L, this.list.get(3));
}
@Test
public void testAddAllCollection() {
final List<Long> longList = new ArrayList<>();
longList.add(new Long("foo".hashCode()));
longList.add(new Long("bar".hashCode()));
assertEquals(0, this.list.size);
this.list.addAll(longList);
assertEquals(2, this.list.size);
assertEquals(101574L, this.list.get(0));
assertEquals(97299L, this.list.get(1));
this.list.addAll(longList);
assertEquals(4, this.list.size);
assertEquals(101574L, this.list.get(0));
assertEquals(97299L, this.list.get(1));
assertEquals(101574L, this.list.get(2));
assertEquals(97299L, this.list.get(3));
}
@Test
public void testAddAllCollectionWithIndex() {
assertEquals(0, this.list.size);
this.list.addAll(new long[] { "foo".hashCode(), "bar".hashCode() }, 0, 2);
assertEquals(2, this.list.size);
final List<Long> longList = new ArrayList<>();
longList.add(new Long("xyz".hashCode()));
longList.add(new Long("123".hashCode()));
this.list.addAll(1, longList);
assertEquals(4, this.list.size);
assertEquals(101574L, this.list.get(0));
assertEquals(119193L, this.list.get(1));
assertEquals(48690L, this.list.get(2));
assertEquals(97299L, this.list.get(3));
}
@Test
public void testAddWithIndex() {
assertEquals(0, this.list.size);
this.list.addAll(new long[] { "foo".hashCode(), "bar".hashCode() }, 0, 2);
assertEquals(2, this.list.size);
this.list.add(1, "xyz".hashCode());
assertEquals(3, this.list.size);
assertEquals(101574L, this.list.get(0));
assertEquals(119193L, this.list.get(1));
assertEquals(97299L, this.list.get(2));
}
@Test
public void testClear() {
assertEquals(0, this.list.size);
this.list.add("foo".hashCode());
assertEquals(1, this.list.size);
this.list.clear();
assertEquals(0, this.list.size);
}
@Test
public void testClone() {
this.list.addAll(new long[] { "foo".hashCode(), "bar".hashCode() }, 0, 2);
assertEquals(2, this.list.size);
assertEquals(101574L, this.list.get(0));
assertEquals(97299L, this.list.get(1));
final ListArrayLong l = this.list.clone();
assertEquals(2, l.size);
assertEquals(101574L, l.get(0));
assertEquals(97299L, l.get(1));
assertFalse(this.list == l);
}
@Test
public void testConstructorArray() {
final ListArrayLong l = new ListArrayLong("foo".hashCode(), "bar".hashCode());
assertEquals(2, l.size);
assertEquals(101574L, l.get(0));
assertEquals(97299L, l.get(1));
}
@Test
public void testConstructorCapacity() {
ListArrayLong l = new ListArrayLong(15);
assertEquals(0, l.size);
assertEquals(15, l.values.length);
// Test minimum capacity of 8
l = new ListArrayLong(7);
assertEquals(0, l.size);
assertEquals(8, l.values.length);
}
@Test
public void testConstructorCollection() {
final List<Long> longList = new ArrayList<>();
longList.add(new Long("foo".hashCode()));
longList.add(new Long("bar".hashCode()));
final ListArrayLong l = new ListArrayLong(longList);
assertEquals(2, l.size);
assertEquals(8, l.values.length);
assertEquals(101574L, l.get(0));
assertEquals(97299L, l.get(1));
}
@Test
public void testConstructorDefault() {
assertEquals(0, this.list.size);
assertEquals(8, this.list.values.length);
}
@Test
public void testContains() {
assertFalse(this.list.contains(101574L));
this.list.add("foo".hashCode());
assertTrue(this.list.contains(101574L));
}
@Test
public void testContainsAll() {
final List<Long> longList = new ArrayList<>();
longList.add(new Long("foo".hashCode()));
longList.add(new Long("bar".hashCode()));
assertFalse(this.list.containsAll(longList));
this.list.add("foo".hashCode());
assertFalse(this.list.containsAll(longList));
this.list.add("bar".hashCode());
assertTrue(this.list.containsAll(longList));
}
@Test
public void testContainsAny() {
final List<Long> longList = new ArrayList<>();
longList.add(new Long("foo".hashCode()));
longList.add(new Long("bar".hashCode()));
assertFalse(this.list.containsAny(longList));
this.list.add("bar".hashCode());
assertTrue(this.list.containsAny(longList));
}
public void testEcho() {
final long l = this.list.echo("foo".hashCode());
assertEquals(1, this.list.size);
assertEquals(101574L, this.list.get(0));
assertEquals(101574L, l);
}
@Test
public void testEquals() {
// Test equals() to a ListArrayLong
final ListArrayLong testListA = new ListArrayLong();
assertTrue(this.list.equals(testListA));
testListA.add("foo".hashCode());
assertFalse(this.list.equals(testListA));
this.list.add("foo".hashCode());
assertTrue(this.list.equals(testListA));
testListA.add("bar".hashCode());
assertFalse(this.list.equals(testListA));
this.list.add("bar".hashCode());
assertTrue(this.list.equals(testListA));
this.list.clear();
// Test equals() to a Collection<? extends Number>
final List<Integer> testListB = new ArrayList<>();
assertTrue(this.list.equals(testListB));
testListB.add("foo".hashCode());
assertFalse(this.list.equals(testListB));
this.list.add("foo".hashCode());
assertTrue(this.list.equals(testListB));
testListB.add("bar".hashCode());
assertFalse(this.list.equals(testListB));
this.list.add("bar".hashCode());
assertTrue(this.list.equals(testListB));
}
@Test
public void testExtract() {
final StringExtractor extractor = new StringExtractor();
this.list.extract(extractor);
assertEquals("[]", extractor.toString());
this.list.add("foo".hashCode());
extractor.clear();
this.list.extract(extractor);
assertEquals("[101574]", extractor.toString());
this.list.add("bar".hashCode());
extractor.clear();
this.list.extract(extractor);
assertEquals("[101574,97299]", extractor.toString());
}
@Test
public void testGet() {
assertEquals(0, this.list.get(0));
this.list.add("foo".hashCode());
assertEquals(101574L, this.list.get(0));
try {
this.list.get(8);
fail("Expected java.lang.ArrayIndexOutOfBoundsException was not thrown");
} catch (final ArrayIndexOutOfBoundsException e) {
}
}
@Test
public void testGetCapacity() {
assertEquals(8, this.list.getCapacity());
assertEquals(this.list.values.length, this.list.getCapacity());
this.list.addAll(new long[] { "foo".hashCode(), "bar".hashCode(), "xyz".hashCode(), "123".hashCode(), "foo".hashCode(), "bar".hashCode(),
"xyz".hashCode(), "123".hashCode(), "foo".hashCode() }, 0, 9);
assertEquals(13, this.list.getCapacity());
assertEquals(this.list.values.length, this.list.getCapacity());
}
@Test
public void testGetSize() {
assertEquals(0, this.list.getSize());
this.list.add("foo".hashCode());
assertEquals(1, this.list.getSize());
}
@Test
public void testGetValues() {
final long[] longArray = this.list.getValues();
assertTrue(longArray == this.list.values);
}
@Test
public void testHashCode() {
assertEquals(0, this.list.hashCode());
this.list.add("foo".hashCode());
assertEquals(101572, this.list.hashCode());
this.list.add("bar".hashCode());
assertEquals(157079, this.list.hashCode());
}
@Test
public void testIndexOf() {
assertEquals(-1, this.list.indexOf("bar".hashCode()));
this.list.add("foo".hashCode());
assertEquals(-1, this.list.indexOf("bar".hashCode()));
this.list.add("bar".hashCode());
assertEquals(1, this.list.indexOf("bar".hashCode()));
}
@Test
public void testInsert() {
assertEquals(0, this.list.size);
this.list.addAll(new long[] { "foo".hashCode(), "bar".hashCode() }, 0, 2);
assertEquals(2, this.list.size);
this.list.insert(1, "xyz".hashCode());
assertEquals(3, this.list.size);
assertEquals(101574L, this.list.get(0));
assertEquals(119193L, this.list.get(1));
assertEquals(97299L, this.list.get(2));
}
@Test
public void testInsertAll() {
assertEquals(0, this.list.size);
this.list.addAll(new long[] { "foo".hashCode(), "bar".hashCode() }, 0, 2);
assertEquals(2, this.list.size);
final List<Long> longList = new ArrayList<>();
longList.add(new Long("xyz".hashCode()));
longList.add(new Long("123".hashCode()));
this.list.insertAll(1, longList);
assertEquals(4, this.list.size);
assertEquals(101574L, this.list.get(0));
assertEquals(119193L, this.list.get(1));
assertEquals(48690L, this.list.get(2));
assertEquals(97299L, this.list.get(3));
}
@Test
public void testIsEmpty() {
assertTrue(this.list.isEmpty());
this.list.add("foo".hashCode());
assertFalse(this.list.isEmpty());
}
@Test
public void testLast() {
assertEquals(0L, this.list.last());
this.list.add("foo".hashCode());
assertEquals(101574L, this.list.last());
this.list.add("bar".hashCode());
assertEquals(97299L, this.list.last());
}
@Test
public void testLastIndexOf() {
assertEquals(-1, this.list.lastIndexOf("foo".hashCode()));
this.list.add("foo".hashCode());
assertEquals(0, this.list.lastIndexOf("foo".hashCode()));
this.list.add("bar".hashCode());
assertEquals(0, this.list.lastIndexOf("foo".hashCode()));
this.list.add("foo".hashCode());
assertEquals(2, this.list.lastIndexOf("foo".hashCode()));
}
@Test
public void testRandom() {
final RNG rng = new RNGKiss(new SeedFactoryConstant(857435, 2768, 984598, 3027694, 104));
assertEquals(0L, this.list.random(rng));
this.list.add("foo".hashCode());
this.list.add("bar".hashCode());
this.list.add("xyz".hashCode());
this.list.add("123".hashCode());
assertEquals(119193L, this.list.random(rng));
}
@Test
public void testRemoveAll() {
final List<Long> longList = new ArrayList<>();
longList.add(new Long("xyz".hashCode()));
longList.add(new Long("123".hashCode()));
assertFalse(this.list.removeAll(longList));
this.list.add("foo".hashCode());
this.list.add("bar".hashCode());
assertFalse(this.list.removeAll(longList));
longList.add(new Long("foo".hashCode()));
assertTrue(this.list.removeAll(longList));
assertEquals(1, this.list.size);
assertEquals(97299L, this.list.get(0));
}
@Test
public void testRemoveIndex() {
try {
this.list.remove(0);
fail("Expected root.validation.IndexOutOfBoundsException was not thrown");
} catch (final root.validation.IndexOutOfBoundsException e) {
assertEquals("Index: 0, Size: 0", e.getMessage());
}
this.list.add("foo".hashCode());
this.list.add("bar".hashCode());
final long l = this.list.remove(0);
assertEquals(101574L, l);
assertEquals(1, this.list.size);
assertEquals(97299L, this.list.get(0));
}
@Test
public void testRemoveValue() {
assertFalse(this.list.removeValue("foo".hashCode()));
this.list.add("foo".hashCode());
this.list.add("bar".hashCode());
assertFalse(this.list.removeValue("xyz".hashCode()));
assertTrue(this.list.removeValue("foo".hashCode()));
assertEquals(1, this.list.size);
assertEquals(97299L, this.list.get(0));
}
@Test
public void testReplace() {
assertFalse(this.list.replace("xyz".hashCode(), "123".hashCode()));
this.list.add("foo".hashCode());
this.list.add("bar".hashCode());
assertFalse(this.list.replace("xyz".hashCode(), "123".hashCode()));
assertTrue(this.list.replace("foo".hashCode(), "xyz".hashCode()));
assertEquals(2, this.list.size);
assertEquals(119193L, this.list.get(0));
assertEquals(97299L, this.list.get(1));
}
@Test
public void testRetainAll() {
final List<Long> longList = new ArrayList<>();
longList.add(new Long("foo".hashCode()));
longList.add(new Long("bar".hashCode()));
assertFalse(this.list.retainAll(longList));
this.list.add("foo".hashCode());
this.list.add("bar".hashCode());
assertFalse(this.list.retainAll(longList));
longList.set(0, new Long("xyz".hashCode()));
assertTrue(this.list.retainAll(longList));
assertEquals(1, this.list.size);
assertEquals(97299L, this.list.get(0));
assertEquals(0L, this.list.get(1));
}
@Test
public void testSet() {
try {
this.list.set(0, "xyz".hashCode());
fail("Expected root.validation.IndexOutOfBoundsException was not thrown");
} catch (final root.validation.IndexOutOfBoundsException e) {
assertEquals("Index: 0, Size: 0", e.getMessage());
}
this.list.add("foo".hashCode());
this.list.add("bar".hashCode());
final long l = this.list.set(1, "xyz".hashCode());
assertEquals(97299L, l);
assertEquals(2, this.list.size);
assertEquals(101574L, this.list.get(0));
assertEquals(119193L, this.list.get(1));
}
@Test
public void testShuffle() {
final RNG rng = new RNGKiss(new SeedFactoryConstant(37544, 2768, 7346, 3027694, 104));
this.list.add("foo".hashCode());
this.list.add("bar".hashCode());
this.list.add("xyz".hashCode());
this.list.add("123".hashCode());
this.list.shuffle(rng);
assertEquals(101574L, this.list.get(0));
assertEquals(48690L, this.list.get(1));
assertEquals(97299L, this.list.get(2));
assertEquals(119193L, this.list.get(3));
}
@Test
public void testSize() {
assertEquals(0, this.list.size());
this.list.add("foo".hashCode());
assertEquals(1, this.list.size());
}
@Test
public void testSubListFromIndex() {
try {
this.list.subList(1);
fail("Expected root.validation.IndexOutOfBoundsException was not thrown");
} catch (final root.validation.IndexOutOfBoundsException e) {
assertEquals("Index: 1, Size: 0", e.getMessage());
}
this.list.add("foo".hashCode());
this.list.add("bar".hashCode());
this.list.add("xyz".hashCode());
this.list.add("123".hashCode());
final ListArrayLong subList = this.list.subList(1);
assertEquals(3, subList.size);
assertEquals(97299L, subList.get(0));
assertEquals(119193L, subList.get(1));
assertEquals(48690L, subList.get(2));
}
@Test
public void testSubListFromIndexToIndex() {
try {
this.list.subList(1, 3);
fail("Expected root.validation.IndexOutOfBoundsException was not thrown");
} catch (final root.validation.IndexOutOfBoundsException e) {
assertEquals("Index: 3, Size: 0", e.getMessage());
}
this.list.add("foo".hashCode());
this.list.add("bar".hashCode());
this.list.add("xyz".hashCode());
this.list.add("123".hashCode());
final ListArrayLong subList = this.list.subList(1, 3);
assertEquals(2, subList.size);
assertEquals(97299L, subList.get(0));
assertEquals(119193L, subList.get(1));
}
@Test
public void testToArray() {
long[] array = this.list.toArray();
assertNotNull(array);
assertEquals(0, array.length);
this.list.add("foo".hashCode());
this.list.add("bar".hashCode());
array = this.list.toArray();
assertNotNull(array);
assertEquals(2, array.length);
assertEquals(101574L, array[0]);
assertEquals(97299L, array[1]);
}
@Test
public void testToString() {
assertEquals("[]", this.list.toString());
this.list.add("foo".hashCode());
assertEquals("[101574]", this.list.toString());
this.list.add("bar".hashCode());
assertEquals("[101574,97299]", this.list.toString());
}
} // End ListArrayLongTest
| 26.529674 | 139 | 0.688496 |
0779b3ec617776203db6096b22e8ec4e6bae0d83 | 5,899 | package endorphin.controller;
import endorphin.domain.User;
import endorphin.domain.UserLoginLog;
import endorphin.service.LoginLogService;
import endorphin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
/**
* UserController
*
* @author igaozp
* @version 1.0
* @since 2016
*/
@Controller
@RequestMapping("/user")
public class UserController {
private final UserService userService;
private final LoginLogService loginLogService;
@Autowired
public UserController(UserService userService, LoginLogService loginLogService) {
this.userService = userService;
this.loginLogService = loginLogService;
}
/**
* 用户登录
*
* @param loginUser 登录的用户
* @param request 请求
* @return 返回页面
*/
@RequestMapping(value = "/userLogin", method = RequestMethod.POST)
public String userLogin(User loginUser, HttpServletRequest request) {
// 通过用户名查找User对象
User user = userService.getUserByUserName(loginUser.getUserName());
String password = "";
if (user != null) {
password = userService.getPassword(user.getUserName());
}
// 判断登录信息是否正确
if (user != null && loginUser.getPassword().equals(password)) {
// 获取登录基本信息
String lastIp = request.getRemoteAddr();
String userName = user.getUserName();
Timestamp lastLoginTime = new Timestamp(System.currentTimeMillis());
// 更新用户信息
user.setLastIp(lastIp);
user.setLastLoginTime(lastLoginTime);
user.setCredit(5 + user.getCredit());
userService.updateUserByUserName(user);
// 更新用户登录日志
UserLoginLog userLoginLog = new UserLoginLog();
userLoginLog.setUserName(userName);
userLoginLog.setLoginIp(lastIp);
userLoginLog.setLoginDateTime(lastLoginTime);
loginLogService.addUserLoginLog(userLoginLog);
// 登陆成功,跳转到主页
request.getSession().setAttribute("username", user.getUserName());
return "redirect:/main";
}
// 登录失败,跳转页面
request.setAttribute("Msg", "登录失败");
return "error";
}
/**
* 用户注册
*
* @param userRegister 注册的用户
* @param request 请求
* @return 返回页面
*/
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String userRegister(User userRegister, HttpServletRequest request) {
User user = userRegister;
if (user != null) {
try {
String username = user.getUserName();
String ip = request.getRemoteAddr();
// 如果数据库中没有该用户,可以注册,否则跳转页面
if (userService.getUserByUserName(username) == null) {
// 添加用户
user.setLastIp(ip);
Timestamp createLoginTime = new Timestamp(System.currentTimeMillis());
user.setCreateTime(createLoginTime);
user.setLastLoginTime(createLoginTime);
userService.addUser(user);
// 添加用户登录日志
UserLoginLog userLoginLog = new UserLoginLog();
userLoginLog.setUserName(username);
userLoginLog.setLoginIp(ip);
userLoginLog.setLoginDateTime(createLoginTime);
loginLogService.addUserLoginLog(userLoginLog);
// 注册成功跳转
request.setAttribute("username", username);
return "index";
} else {
request.setAttribute("Msg", "注册失败,用户名已被占用!");
return "error";
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("Msg", "发生未知错误!");
return "error";
}
}
request.setAttribute("Msg", "发生未知错误!");
return "error";
}
/**
* 显示个人信息
*
* @param username 用户名
* @param request 请求
* @return 返回页面
*/
@RequestMapping(value = "/listUserInfo")
public String listUserInfo(String username, HttpServletRequest request) {
User user = userService.getUserByUserName(username);
request.setAttribute("user", user);
return "user/userInfo";
}
/**
* 修改个人信息页面
*
* @param username 用户名
* @param request 请求
* @return 返回页面
*/
@RequestMapping(value = "/userUpdateInfo", method = RequestMethod.GET)
public String userUpdateInfoPage(String username, HttpServletRequest request) {
User user = userService.getUserByUserName(username);
request.setAttribute("user", user);
return "user/userUpdateInfo";
}
/**
* 提交用户修改信息
*
* @param user 修改后的用户
* @param redirectAttributes 重定向
* @return 重定向页面
*/
@RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
public String updateUserInfo(User user, RedirectAttributes redirectAttributes) {
User newUser = user;
userService.updateUserByUserName(newUser);
redirectAttributes.addAttribute("username", newUser.getUserName());
return "redirect:listUserInfo";
}
/**
* 用户注销功能
*
* @param request 请求
* @return 返回页面
*/
@RequestMapping(value = "/loginOut")
public String loginOut(HttpServletRequest request) {
request.getSession().removeAttribute("username");
return "index";
}
}
| 31.545455 | 90 | 0.603323 |
4232d81e94cccdd5e0e55851539717c9d35ae643 | 1,753 | package com.baomidou.mybatisplus.toolkit;
/**
* <p>
* EscapeOfString ,数据库字符串转义
* </p>
*
* @author Caratacus
* @Date 2016-10-16
*/
public class StringEscape {
/**
* 字符串是否需要转义
*
* @param x
* @param stringLength
* @return
*/
private static boolean isEscapeNeededForString(String x, int stringLength) {
boolean needsHexEscape = false;
for (int i = 0; i < stringLength; ++i) {
char c = x.charAt(i);
switch (c) {
case '\\':
needsHexEscape = true;
break;
case '\'':
needsHexEscape = true;
break;
case '"': /* Better safe than sorry */
needsHexEscape = true;
break;
}
if (needsHexEscape) {
break; // no need to scan more
}
}
return needsHexEscape;
}
/**
* 转义字符串
*
* @param x
* @return
*/
public static String escapeString(String x) {
if (x.matches("\'(.+)\'")) {
x = x.substring(1, x.length() - 1);
}
String parameterAsString = x;
int stringLength = x.length();
if (isEscapeNeededForString(x, stringLength)) {
StringBuilder buf = new StringBuilder((int) (x.length() * 1.1));
//
// Note: buf.append(char) is _faster_ than appending in blocks,
// because the block append requires a System.arraycopy().... go
// figure...
//
for (int i = 0; i < stringLength; ++i) {
char c = x.charAt(i);
switch (c) {
case '\\':
buf.append('\\');
buf.append('\\');
break;
case '\'':
buf.append('\\');
buf.append('\'');
break;
case '"': /* Better safe than sorry */
buf.append('\\');
buf.append('"');
break;
default:
buf.append(c);
}
}
parameterAsString = buf.toString();
}
return "\'" + parameterAsString + "\'";
}
} | 16.695238 | 77 | 0.548203 |
753109090da79c8a4e1fabcab6ae6172f784db2f | 1,446 | package macrobase.analysis.stats;
import macrobase.analysis.stats.kernel.Kernel;
import org.apache.commons.math3.linear.ArrayRealVector;
import org.junit.Test;
import static org.junit.Assert.*;
public class EpanchnikovMultiplicativeKernelTest {
final double DOUBLE_ACCURACY = 0.00000000001;
@Test
public void testDensity() {
double[] vectorData = new double[1];
double density;
Kernel kernel = new macrobase.analysis.stats.kernel.EpanchnikovMulticativeKernel(1);
vectorData[0] = 2.0;
density = kernel.density(new ArrayRealVector(vectorData));
assertEquals(density, 0.0, DOUBLE_ACCURACY);
vectorData[0] = 1.0;
density = kernel.density(new ArrayRealVector(vectorData));
assertEquals(density, 0.0, DOUBLE_ACCURACY);
vectorData[0] = 0.0;
density = kernel.density(new ArrayRealVector(vectorData));
assertEquals(density, 0.75, DOUBLE_ACCURACY);
}
@Test
public void testNorm() {
double[] vectorData = new double[3];
double norm;
double density;
Kernel kernel = new macrobase.analysis.stats.kernel.EpanchnikovMulticativeKernel(3);
density = kernel.density(new ArrayRealVector(vectorData));
assertEquals(density, 0.421875, DOUBLE_ACCURACY);
norm = kernel.norm();
assertEquals(norm, 0.216, DOUBLE_ACCURACY);
}
}
| 31.434783 | 93 | 0.659751 |
fbd02f2d504deabd02babc8da23dacfb4924dcc1 | 400 | package me.ehp246.aufjms.core.endpoint.invokableresolvercase.case06;
import me.ehp246.aufjms.api.annotation.ForJmsType;
import me.ehp246.aufjms.api.annotation.Invoking;
import me.ehp246.aufjms.api.endpoint.InstanceScope;
/**
* Should scan as a bean.
*
* @author Lei Yang
*
*/
@ForJmsType(value = "Case06", scope = InstanceScope.BEAN)
public interface Case06 {
@Invoking
void m001();
}
| 22.222222 | 68 | 0.745 |
eb3ae74d4e0e897f7fbbe3c245ef2c0acb0c5673 | 8,404 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.address.generator.gui.tabs;
import burstcoin.address.generator.core.GeneratorConfig;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.text.Font;
import java.util.Arrays;
/**
* The type Generator config view.
*/
public class GeneratorConfigView
extends AnchorPane
{
/**
* The interface Callback.
*/
public interface Callback
{
/**
* On start.
*
* @param generatorConfig the generator config
*/
void onStart(GeneratorConfig generatorConfig);
}
/**
* Instantiates a new Generator config view.
*
* @param generatorConfig the generator config
* @param callback the callback
*/
public GeneratorConfigView(GeneratorConfig generatorConfig, Callback callback)
{
// <Label layoutX="28.0" layoutY="14.0" text="search config:">
// <font>
// <Font size="14.0" />
// </font>
// </Label>
Label searchConfigLabel = new Label("search config: (do NOT use: 1, I or O)");
searchConfigLabel.setLayoutX(28.0);
searchConfigLabel.setLayoutY(14.0);
searchConfigLabel.setFont(new Font(14.0));
getChildren().add(searchConfigLabel);
// <Label layoutX="96.0" layoutY="51.0" text="keys" />
Label keysLabel = new Label("keys");
keysLabel.setLayoutX(96.0);
keysLabel.setLayoutY(51.0);
getChildren().add(keysLabel);
String keys = "";
for(String key : generatorConfig.getKeys())
{
keys += key + ",";
}
keys = keys.substring(0, keys.length() - 1);
// <TextField layoutX="133.0" layoutY="47.0" prefHeight="25.0" prefWidth="439.0" />
TextField keysTextField = new TextField(keys);
keysTextField.setLayoutX(133.0);
keysTextField.setLayoutY(47.0);
keysTextField.setPrefHeight(25.0);
keysTextField.setPrefWidth(439.0);
getChildren().add(keysTextField);
// <Label layoutX="28.0" layoutY="109.0" text="system config:">
// <font>
// <Font size="14.0" />
// </font>
// </Label>
Label systemConfigLabel = new Label("system config:");
systemConfigLabel.setLayoutX(28.0);
systemConfigLabel.setLayoutY(109.0);
systemConfigLabel.setFont(new Font(14.0));
getChildren().add(systemConfigLabel);
// <Label layoutX="84.0" layoutY="141.0" text="threads" />
Label threadsLabel = new Label("threads");
threadsLabel.setLayoutX(84.0);
threadsLabel.setLayoutY(141.0);
getChildren().add(threadsLabel);
// <TextField layoutX="133.0" layoutY="137.0" prefHeight="25.0" prefWidth="133.0" />
TextField threadsTextField = new TextField(String.valueOf(generatorConfig.getThreads()));
threadsTextField.setLayoutX(133.0);
threadsTextField.setLayoutY(137.0);
threadsTextField.setPrefHeight(25.0);
threadsTextField.setPrefWidth(133.0);
getChildren().add(threadsTextField);
// <Label layoutX="349.0" layoutY="141.0" text="triesPerThread" />
Label triesPerThreadLabel = new Label("triesPerThread");
triesPerThreadLabel.setLayoutX(349.0);
triesPerThreadLabel.setLayoutY(141.0);
getChildren().add(triesPerThreadLabel);
// <TextField layoutX="439.0" layoutY="137.0" prefHeight="25.0" prefWidth="133.0" />
TextField triesPerThreadTextField = new TextField("");
triesPerThreadTextField.setLayoutX(439.0);
triesPerThreadTextField.setLayoutY(137.0);
triesPerThreadTextField.setText(String.valueOf(generatorConfig.getTriesPerThread()));
triesPerThreadTextField.setPrefHeight(25.0);
triesPerThreadTextField.setPrefWidth(133.0);
getChildren().add(triesPerThreadTextField);
// <Label layoutX="28.0" layoutY="197.0" text="password config:">
// <font>
// <Font size="14.0" />
// </font>
// </Label>
Label passwordConfigLabel = new Label("password config:");
passwordConfigLabel.setLayoutX(28.0);
passwordConfigLabel.setLayoutY(197.0);
passwordConfigLabel.setFont(new Font(14.0));
getChildren().add(passwordConfigLabel);
// <Label layoutX="51.0" layoutY="234.0" text="passwordSize" />
Label passwordSizeLabel = new Label("passwordSize");
passwordSizeLabel.setLayoutX(51.0);
passwordSizeLabel.setLayoutY(234.0);
getChildren().add(passwordSizeLabel);
// <TextField layoutX="133.0" layoutY="230.0" prefHeight="25.0" prefWidth="133.0" />
TextField passwordSizeTextField = new TextField(String.valueOf(generatorConfig.getPasswordLength()));
passwordSizeTextField.setLayoutX(133.0);
passwordSizeTextField.setLayoutY(230.0);
passwordSizeTextField.setPrefHeight(25.0);
passwordSizeTextField.setPrefWidth(133.0);
getChildren().add(passwordSizeTextField);
// <Label layoutX="43.0" layoutY="275.0" text="passwordPrefix" />
Label passwordPrefixLabel = new Label("passwordPrefix");
passwordPrefixLabel.setLayoutX(43.0);
passwordPrefixLabel.setLayoutY(275.0);
getChildren().add(passwordPrefixLabel);
// <TextField layoutX="133.0" layoutY="271.0" prefHeight="25.0" prefWidth="439.0" />
TextField passwordPrefixTextField = new TextField(generatorConfig.getPrefix());
passwordPrefixTextField.setLayoutX(133.0);
passwordPrefixTextField.setLayoutY(271.0);
passwordPrefixTextField.setPrefHeight(25.0);
passwordPrefixTextField.setPrefWidth(439.0);
getChildren().add(passwordPrefixTextField);
// <Label layoutX="37.0" layoutY="314.0" text="passwordPostfix" />
Label passwordPostfixLabel = new Label("passwordPostfix");
passwordPostfixLabel.setLayoutX(37.0);
passwordPostfixLabel.setLayoutY(314.0);
getChildren().add(passwordPostfixLabel);
// <TextField layoutX="133.0" layoutY="310.0" prefHeight="25.0" prefWidth="439.0" />
TextField passwordPostfixTextField = new TextField(generatorConfig.getPostfix());
passwordPostfixTextField.setLayoutX(133.0);
passwordPostfixTextField.setLayoutY(310.0);
passwordPostfixTextField.setPrefHeight(25.0);
passwordPostfixTextField.setPrefWidth(439.0);
getChildren().add(passwordPostfixTextField);
// <Button mnemonicParsing="false" text="Start" GridPane.columnIndex="1" GridPane.rowIndex="5" />
Button startButton = new Button(">> Start search! <<");
startButton.setLayoutX(133.0);
startButton.setLayoutY(360.0);
startButton.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent event)
{
callback.onStart(new GeneratorConfig(Arrays.asList(keysTextField.getText().trim().split(",")),
Integer.valueOf(threadsTextField.getText()),
Long.valueOf(triesPerThreadTextField.getText()),
Integer.valueOf(passwordSizeTextField.getText()),
passwordPrefixTextField.getText(),
passwordPostfixTextField.getText()));
}
});
getChildren().add(startButton);
}
}
| 39.455399 | 105 | 0.691813 |
dab11225264fd9784a9b10335fa42fbf408259ad | 5,803 | package com.lucky.watisrain.backend;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.lucky.watisrain.backend.data.Building;
import com.lucky.watisrain.backend.data.Location;
import com.lucky.watisrain.backend.data.Map;
import com.lucky.watisrain.backend.data.Path;
import com.lucky.watisrain.backend.data.Waypoint;
/**
* MapFactory generates a Map object given external input data.
*/
public class MapFactory {
/**
* Read a Map object given a Scanner pointed to the stream
*/
public static Map readMapFromScanner(Scanner scanner){
// removes empty lines and comments
scanner = preprocess(scanner);
Map map = new Map();
while(scanner.hasNext()){
String command = scanner.next();
// Delegate handling to sub-functions
switch(command){
case "location":
handleCommandLocation(map, scanner);
break;
case "passive_location":
handleCommandPassiveLocation(map, scanner);
break;
case "path":
handleCommandPath(map, scanner);
break;
default:
throw new RuntimeException("Invalid command: " + command);
}
}
scanner.close();
return map;
}
/*
* Location (actually a building)
*/
private static void handleCommandLocation(Map map, Scanner scanner){
String name = scanner.next();
int pos_x = scanner.nextInt();
int pos_y = scanner.nextInt();
int num_floors = 1;
int main_floor = 1;
boolean zero_indexed = false;
boolean selectable = true;
while(true){
if(!scanner.hasNext()) break;
String s = scanner.next();
if(s.equals(";")) break;
if(s.equals("floors")){
num_floors = scanner.nextInt();
}
if(s.equals("main_floor")){
main_floor = scanner.nextInt();
}
if(s.equals("has_basement")){
zero_indexed = true;
}
if(s.equals("unselectable")){
selectable = false;
}
}
Building building = new Building(name, new Waypoint(pos_x, pos_y), num_floors, main_floor, zero_indexed, selectable);
map.addBuilding(building);
}
/*
* Passive location. Simply [name] [x] [y].
*/
private static void handleCommandPassiveLocation(Map map, Scanner scanner){
String name = scanner.next();
int pos_x = scanner.nextInt();
int pos_y = scanner.nextInt();
map.addPassiveLocation(new Location(name,pos_x,pos_y, false));
}
/*
* Paths
*/
private static void handleCommandPath(Map map, Scanner scanner){
String name1 = scanner.next();
String name2 = scanner.next();
// Figure out where we are, approximately first. This location will have the
// correct waypoint, but may have the incorrect floor.
Location roughly_loc1 = map.getLocationByID(name1);
Location roughly_loc2 = map.getLocationByID(name2);
// We can have 0 or more "connects" commands. Store them in a list.
ArrayList<Integer> connect_floors1 = new ArrayList<>();
ArrayList<Integer> connect_floors2 = new ArrayList<>();
int pathType = Path.TYPE_OUTSIDE;
// Read waypoints
List<Waypoint> waypoints = new ArrayList<>();
waypoints.add(roughly_loc1.getPostion());
// Read until semicolon
while(true){
if(!scanner.hasNext()) break;
String s = scanner.next();
if(s.equals(";")) break;
if(s.equals("p")){
// add waypoint
int wx = scanner.nextInt();
int wy = scanner.nextInt();
waypoints.add(new Waypoint(wx,wy));
}
if(s.equals("type")){
String type_str = scanner.next();
switch(type_str){
case "inside":
pathType = Path.TYPE_INSIDE;
break;
case "indoor_tunnel":
pathType = Path.TYPE_INDOOR_TUNNEL;
break;
case "underground_tunnel":
pathType = Path.TYPE_UNDERGROUND_TUNNEL;
break;
case "briefly_outside":
pathType = Path.TYPE_BRIEFLY_OUTSIDE;
break;
}
}
if(s.equals("connects")){
connect_floors1.add(scanner.nextInt());
connect_floors2.add(scanner.nextInt());
}
}
waypoints.add(roughly_loc2.getPostion());
// No "connects" specified, then just link main floor to main floor
if(connect_floors1.isEmpty()){
int main_floor1 = 1;
int main_floor2 = 1;
Building build1 = map.getBuildingByID(name1);
Building build2 = map.getBuildingByID(name2);
if(build1 != null) main_floor1 = build1.getMainFloorNumber();
if(build2 != null) main_floor2 = build2.getMainFloorNumber();
connect_floors1.add(main_floor1);
connect_floors2.add(main_floor2);
}
// Add a path for each "connects"
for(int i=0; i<connect_floors1.size(); i++){
Location loc1 = map.getLocationByID(Util.makeBuildingAndFloor(name1, connect_floors1.get(i)));
Location loc2 = map.getLocationByID(Util.makeBuildingAndFloor(name2, connect_floors2.get(i)));
Path path = new Path(loc1,loc2);
path.setWaypoints(waypoints);
path.setPathType(pathType);
map.addPath(path);
}
}
// Preprocess to remove blank lines and comment lines
private static Scanner preprocess(Scanner prescanner){
StringBuilder sb = new StringBuilder();
while(prescanner.hasNextLine()){
String line = prescanner.nextLine();
if(line.trim().isEmpty() || line.charAt(0) == '#') continue;
sb.append(line + "\n");
}
// Actual scanner, don't worry about extraneous stuff anymore
return new Scanner(sb.toString());
}
/**
* Create a Map object from a specified File
*/
public static Map readMapFromFile(File infile)
throws FileNotFoundException{
return readMapFromScanner(
new Scanner(
new FileInputStream(infile)));
}
public static Map readMapFromStream(InputStream stream){
return readMapFromScanner(new Scanner(stream));
}
}
| 24.280335 | 119 | 0.678442 |
fcadfbe1f2e772a1f0a970095c086fc7166d7d7a | 1,208 | import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TakePutMonitor {
private final int M; //process count
private final int N; //buffer size
private final int[] howMany;
private final Condition[] cond;
private final Lock lock = new ReentrantLock();
public TakePutMonitor(int processCount , int bufferSize){
this.M = processCount;
this.N = bufferSize;
this.howMany = new int[M];
this.cond = new Condition[M];
for(int i =0 ; i< M ; i++){
this.cond[i] = lock.newCondition();
this.howMany[i]=0;
}
this.howMany[0]=N;
}
public void take(int id){
lock.lock();
try{
if(howMany[id]==0){
cond[id].await();
}
howMany[id]--;
}catch (InterruptedException e){e.printStackTrace();}
finally { lock.unlock(); }
}
public void put(int id){
lock.lock();
int index = (id+1)%M;
howMany[index]++;
cond[index].signal();
lock.unlock();
}
}
| 26.844444 | 62 | 0.539735 |
33e153acde22a9950e91280435359f1787146f41 | 1,000 | package hxy.dream.common.converter;
import hxy.dream.entity.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import java.util.HashMap;
import java.util.Map;
/**
* <p>
* 编码 -> 枚举 转化器工厂类
* </p>
*
* @description: 编码 -> 枚举 转化器工厂类
*/
public class IntegerCodeToEnumConverterFactory implements ConverterFactory<Integer, BaseEnum> {
private static final Map<Class, Converter> CONVERTERS = new HashMap<>();
/**
* 获取一个从 Integer 转化为 T 的转换器,T 是一个泛型,有多个实现
*
* @param targetType 转换后的类型
* @return 返回一个转化器
*/
@Override
public <T extends BaseEnum> Converter<Integer, T> getConverter(Class<T> targetType) {
Converter<Integer, T> converter = CONVERTERS.get(targetType);
if (converter == null) {
converter = new IntegerToEnumConverter<>(targetType);
CONVERTERS.put(targetType, converter);
}
return converter;
}
} | 27.777778 | 95 | 0.682 |
3f4c6b32f05c9b20f4d6c7da8347cd3300eee809 | 15,264 | package com.example.myapplication.Services;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import com.example.myapplication.Activities.UserNavgation;
import com.example.myapplication.R;
import com.example.myapplication.Utils.PrefUtils;
import com.example.myapplication.Utils.PushUtils;
import com.google.firebase.messaging.RemoteMessage;
import com.sendbird.android.SendBirdException;
import com.sendbird.android.SendBirdPushHandler;
import com.sendbird.android.SendBirdPushHelper;
import com.sendbird.calls.SendBirdCall;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicReference;
import static org.webrtc.ContextUtils.getApplicationContext;
public class MyFirebaseMessagingService /*extends FirebaseMessagingService*/extends SendBirdPushHandler {
public static final String NOTIFICATION_CHANNEL_ID = MyFirebaseMessagingService.class.getSimpleName();
private static final String TAG = "MyFirebaseMessagingServ";
private static final AtomicReference<String> pushToken = new AtomicReference<>();
String strMessage;
public static ArrayList<String> strArrList = new ArrayList<>();
public interface ITokenResult {
void onPushTokenReceived(String pushToken, SendBirdException e);
}
@Override
public void onNewToken(String token) {
pushToken.set(token);
}
@Override
protected boolean isUniquePushToken() {
return false;
}
public static void getPushToken(ITokenResult listener) {
String token = pushToken.get();
if (!TextUtils.isEmpty(token)) {
listener.onPushTokenReceived(token, null);
return;
}
SendBirdPushHelper.getPushToken((newToken, e) -> {
if (listener != null) {
listener.onPushTokenReceived(newToken, e);
}
if (e == null) {
pushToken.set(newToken);
}
});
if (SendBirdCall.getCurrentUser() != null) {
PushUtils.registerPushToken(getApplicationContext(), token, e -> {
if (e != null) {
Log.d(TAG, "registerPushTokenForCurrentUser() => e: " + e.getMessage());
}
});
} else {
PrefUtils.setPushToken(getApplicationContext(), token);
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onMessageReceived(Context context, RemoteMessage remoteMessage) {
Log.d(TAG, "[SendBirdCall Message] onMessageReceived() => " + remoteMessage.getData().toString());
if (SendBirdCall.handleFirebaseMessageData(remoteMessage.getData())) {
Log.d(TAG, "[SendBirdCall Message] onMessageReceived() => " + remoteMessage.getData().toString());
} else {
Log.d(TAG, "onMessageReceived() => From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "onMessageReceived() => Data: " + remoteMessage.getData().toString());
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "onMessageReceived() => Notification Body: " + remoteMessage.getNotification().getBody());
}
String channelUrl = null;
try {
JSONObject sendBird = new JSONObject(remoteMessage.getData().get("sendbird"));
JSONObject channel = (JSONObject) sendBird.get("channel");
channelUrl = (String) channel.get("channel_url");
} catch (JSONException e) {
e.printStackTrace();
}
strMessage = remoteMessage.getData().get("message");
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
if(strMessage.length()>0) {
strArrList.add(strMessage);
sendNotification(context, remoteMessage.getData().get("message"), channelUrl);
}
}
}
// @RequiresApi(api = Build.VERSION_CODES.M)
/* @Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
Log.d(TAG, "[SendBirdCall Message] onMessageReceived() => " + remoteMessage.getData().toString());
if (SendBirdCall.handleFirebaseMessageData(remoteMessage.getData())) {
Log.d(TAG, "[SendBirdCall Message] onMessageReceived() => " + remoteMessage.getData().toString());
} else {
Log.d(TAG, "onMessageReceived() => From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "onMessageReceived() => Data: " + remoteMessage.getData().toString());
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "onMessageReceived() => Notification Body: " + remoteMessage.getNotification().getBody());
}
String channelUrl = null;
try {
JSONObject sendBird = new JSONObject(remoteMessage.getData().get("sendbird"));
JSONObject channel = (JSONObject) sendBird.get("channel");
channelUrl = (String) channel.get("channel_url");
} catch (JSONException e) {
e.printStackTrace();
}
strMessage = remoteMessage.getData().get("message");
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
sendNotification(this, remoteMessage.getData().get("message"), channelUrl);
}
}*/
/* @Override
public void onNewToken(@NonNull String token) {
Log.d(TAG, "onNewToken(token: " + token + ")");
if (SendBirdCall.getCurrentUser() != null) {
PushUtils.registerPushToken(getApplicationContext(), token, e -> {
if (e != null) {
Log.d(TAG, "registerPushTokenForCurrentUser() => e: " + e.getMessage());
}
});
} else {
PrefUtils.setPushToken(getApplicationContext(), token);
}
}*/
/*@RequiresApi(api = Build.VERSION_CODES.M)
public void sendNotification(Context context, String messageBody, String channelUrl) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NotificationManager.class);
final String CHANNEL_ID = "CHANNEL_ID";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Build.VERSION_CODES.O
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, "CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH);
mChannel.setShowBadge(true);
notificationManager.createNotificationChannel(mChannel);
}
Intent intent = new Intent(context, UserNavgation.class);
intent.putExtra("URL", channelUrl);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 *//* Request code *//*, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.app_buzz_logo)
.setColor(Color.parseColor("#7469C4")) // small icon background color
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.app_buzz_logo))
.setColor(Color.parseColor("#7469C4"))
.setContentTitle(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setPriority(Notification.PRIORITY_DEFAULT)
.setDefaults(Notification.DEFAULT_ALL).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(pendingIntent);
notificationBuilder.setSound(RingtoneManager.getDefaultUri( RingtoneManager.TYPE_NOTIFICATION));
notificationManager.notify(0 *//* ID of notification *//*, notificationBuilder.build());
}*/
@RequiresApi(api = Build.VERSION_CODES.M)
public void sendNotification(Context context, String messageBody, String channelUrl) {
NotificationCompat.Builder notificationBuilder;
NotificationManager notifManager = null;
NotificationChannel mChannel = null;
CharSequence name = context.getString(R.string.app_name);
notifManager = (NotificationManager) context.getSystemService
(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationCompat.Builder builder;
Intent intent = new Intent(context, UserNavgation.class);
intent.putExtra("URL", channelUrl);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent;
int importance = NotificationManager.IMPORTANCE_HIGH;
mChannel = new NotificationChannel
("0", name, importance);
mChannel.setDescription(strArrList.get(0));
mChannel.enableVibration(true);
notifManager.createNotificationChannel(mChannel);
builder = new NotificationCompat.Builder(context, "0");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(context, 1251
, intent, PendingIntent.FLAG_UPDATE_CURRENT);
/* PendingIntent snoozePendingIntent = PendingIntent.getService(this
, 0, dismissIntent, 0);*/
/*NotificationCompat.Action dismissAction =
new NotificationCompat.Action.Builder(
R.mipmap.ic_tick,
getString(R.string.message_dismiss),
snoozePendingIntent)
.build();*/
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle()
.setBigContentTitle(context.getResources().getString(R.string.app_name))
.setSummaryText(getUnexpandedContentText(strArrList.size()));
for (int iCount = 0; iCount < strArrList.size(); iCount++) {
inboxStyle.addLine(strArrList.get(iCount));
}
builder.setSmallIcon(R.drawable.app_buzz_logo) // required
.setContentText(getUnexpandedContentText(strArrList.size())) // required
.setStyle(inboxStyle)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setNumber(strArrList.size())
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.app_buzz_logo))
/* .setBadgeIconType(R.mipmap.ic_launcher)*/
.setContentIntent(pendingIntent)
.setColor(Color.parseColor("#7469C4"))
.setSubText(Integer.toString(strArrList.size()))
/*.addAction(dismissAction)*/
.setSound(RingtoneManager.getDefaultUri
(RingtoneManager.TYPE_NOTIFICATION));
Notification notification = builder.build();
notifManager.notify(0, notification);
} else {
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
/* Intent intent = new Intent(this, ClubNewsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0 *//*Request code*//* , intent, 0);*/
Intent intent = new Intent(context, UserNavgation.class);
intent.putExtra("URL", channelUrl);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntentLow = PendingIntent.getActivity(context, 1251
, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.app_buzz_logo)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.app_buzz_logo))
.setContentTitle(context.getResources().getString(R.string.app_name))
.setContentText(getUnexpandedContentText(strArrList.size()))
.setAutoCancel(true)
.setNumber(strArrList.size())
.setSound(defaultSoundUri)
.setContentIntent(pendingIntentLow)
.setPriority(Notification.PRIORITY_HIGH)
.setStyle(getExpandedNotificationStyle(context, strArrList));
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
for (int iCount = 0; iCount < strArrList.size(); iCount++) {
if(strArrList.size()<7) {
inboxStyle.addLine(strArrList.get(iCount));
}
}
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
/**
* Create custom method to display notification like inbox style.
*/
private NotificationCompat.Style getExpandedNotificationStyle (Context context, ArrayList< String > names) {
NotificationCompat.InboxStyle expandedNotificationStyle = new NotificationCompat.InboxStyle();
expandedNotificationStyle.setBigContentTitle(context.getResources().getString(R.string.app_name));
/**
* There seems to be a bug in the notification display system where, unless you set
* summary text, single line expanded inbox state will not expand when the notif
* drawer is fully pulled down. However, it still works in the lock-screen.
*/
expandedNotificationStyle.setSummaryText(strArrList.size() + " messages received.");
for (String name : names) {
expandedNotificationStyle.addLine(name);
}
return expandedNotificationStyle;
}
/**
* Implements method for unExpanded content area.
*/
private String getUnexpandedContentText ( int numOfNotifications){
return numOfNotifications + " messages received";
}
}
| 45.428571 | 142 | 0.64164 |
06c432ccd4f06f595ece974adc24bb65bf2aae9d | 7,839 | package com.ckt.io.wifidirect.activity;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.ckt.io.wifidirect.R;
import com.ckt.io.wifidirect.fragment.DeviceDetailFragment;
import com.ckt.io.wifidirect.fragment.DeviceListFragment;
import com.ckt.io.wifidirect.fragment.WiFiDirectBroadcastReceiver;
/**
* Created by Lu on 2016/5/22.
*/
public class WiFiDirectActivity extends Activity implements WifiP2pManager.ChannelListener, DeviceListFragment.DeviceActionListener {
public static final String TAG = "wifidirectdemo";
private WifiP2pManager manager;
private boolean isWifiP2pEnabled = false;
private boolean retryChannel = false;
private final IntentFilter intentFilter = new IntentFilter();
private final IntentFilter intentFilter_update = new IntentFilter();
private WifiP2pManager.Channel channel;
private BroadcastReceiver receiver = null;
/**
* @param isWifiP2pEnabled the isWifiP2pEnabled to set
*/
public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) {
this.isWifiP2pEnabled = isWifiP2pEnabled;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_wifidirect);
// add necessary intent values to be matched.
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
intentFilter_update.addAction("UPDATE_PEERS");
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
}
/** register the BroadcastReceiver with the intent values to be matched */
@Override
public void onResume() {
super.onResume();
receiver = new WiFiDirectBroadcastReceiver(manager, channel,this);
registerReceiver(receiver, intentFilter);
registerReceiver(mbroadcastReceiver,intentFilter_update);
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
unregisterReceiver(mbroadcastReceiver);
}
/**
* Remove all peers and clear all fields. This is called on
* BroadcastReceiver receiving a state change event.
*/
BroadcastReceiver mbroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (!isWifiP2pEnabled) {
Toast.makeText(WiFiDirectActivity.this, "正在打开WIFI",
Toast.LENGTH_SHORT).show();
}
final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
fragment.onInitiateDiscovery();
manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Toast.makeText(WiFiDirectActivity.this, "正在搜索",
Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int reasonCode) {
Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
Toast.LENGTH_SHORT).show();
}
});
}
};
public void resetData() {
DeviceListFragment fragmentList = (DeviceListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getFragmentManager()
.findFragmentById(R.id.frag_detail);
if (fragmentList != null) {
fragmentList.clearPeers();
}
if (fragmentDetails != null) {
fragmentDetails.resetViews();
}
}
@Override
public void showDetails(WifiP2pDevice device) {
DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
.findFragmentById(R.id.frag_detail);
fragment.showDetails(device);
}
@Override
public void connect(WifiP2pConfig config) {
manager.connect(channel, config, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
// WiFiDirectBroadcastReceiver will notify us. Ignore for now.
}
@Override
public void onFailure(int reason) {
Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void disconnect() {
final DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
.findFragmentById(R.id.frag_detail);
fragment.resetViews();
manager.removeGroup(channel, new WifiP2pManager.ActionListener() {
@Override
public void onFailure(int reasonCode) {
Log.d(TAG, "Disconnect failed. Reason :" + reasonCode);
}
@Override
public void onSuccess() {
fragment.getView().setVisibility(View.GONE);
}
});
}
@Override
public void onChannelDisconnected() {
// we will try once more
if (manager != null && !retryChannel) {
Toast.makeText(this, "Channel lost. Trying again", Toast.LENGTH_LONG).show();
resetData();
retryChannel = true;
manager.initialize(this, getMainLooper(), this);
} else {
Toast.makeText(this,
"Severe! Channel is probably lost premanently. Try Disable/Re-Enable P2P.",
Toast.LENGTH_LONG).show();
}
}
@Override
public void cancelDisconnect() {
/*
* A cancel abort request by user. Disconnect i.e. removeGroup if
* already connected. Else, request WifiP2pManager to abort the ongoing
* request
*/
if (manager != null) {
final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
if (fragment.getDevice() == null
|| fragment.getDevice().status == WifiP2pDevice.CONNECTED) {
disconnect();
} else if (fragment.getDevice().status == WifiP2pDevice.AVAILABLE
|| fragment.getDevice().status == WifiP2pDevice.INVITED) {
manager.cancelConnect(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Toast.makeText(WiFiDirectActivity.this, "Aborting connection",
Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int reasonCode) {
Toast.makeText(WiFiDirectActivity.this,
"Connect abort request failed. Reason Code: " + reasonCode,
Toast.LENGTH_SHORT).show();
}
});
}
}
}
} | 34.995536 | 133 | 0.620742 |
71d67d17a349af92b238f07330caafa83e18b9f0 | 629 | // Created by Aurimas A. Nausedas on 13/01/21.
// Updated by Aurimas A. Nausedas on 07/11/21.
//
package aurimas.oops.level2;
import java.util.ArrayList;
public class Book {
private int id;
private String name;
private String author;
private ArrayList<Review> reviews = new ArrayList<>();
public Book(int id, String name, String author) {
this.id = id;
this.name = name;
this.author = author;
}
public void addReview(Review review) {
this.reviews.add(review);
}
@Override
public String toString() {
return String.format("id - %d, name - %s, author - %s, reviews = %s", id, name, author, reviews);
}
}
| 20.290323 | 99 | 0.682035 |
219ed54165a1949700f23bee368829e390eea259 | 375 | package botservice.util;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
* Entity Manager Producer
*/
@SuppressWarnings("unused")
public class EntityManagerProducer {
@Produces
@PersistenceContext
@SuppressWarnings("unused")
private EntityManager em;
}
| 19.736842 | 45 | 0.736 |
c881e0b972dc18fea424538c1ebf6ca002f78471 | 1,344 | package io.cucumber.core.event;
import org.apiguardian.api.API;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
@API(status = API.Status.STABLE)
public final class SnippetsSuggestedEvent extends TimeStampedEvent {
private final String uri;
private final List<Location> stepLocations;
private final List<String> snippets;
public SnippetsSuggestedEvent(Instant timeInstant, String uri, List<Location> stepLocations, List<String> snippets) {
super(timeInstant);
this.uri = Objects.requireNonNull(uri);
this.stepLocations = Objects.requireNonNull(stepLocations);
this.snippets = Collections.unmodifiableList(Objects.requireNonNull(snippets));
}
public String getUri() {
return uri;
}
public List<Location> getStepLocations() {
return stepLocations;
}
public List<String> getSnippets() {
return snippets;
}
public static final class Location {
private final int line;
private final int column;
public Location(int line, int column) {
this.line = line;
this.column = column;
}
public int getLine() {
return line;
}
public int getColumn() {
return column;
}
}
}
| 24.888889 | 121 | 0.654018 |
ba104186f3aa8732cccf546de28dc342abce4dce | 1,369 | package com.blamejared.controlling.mixin;
import com.blamejared.controlling.client.gui.ControlsSettingsGuiNew;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.options.ControlsOptionsScreen;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(MinecraftClient.class)
public class OpenGuiMixin {
@Shadow
public Screen currentScreen;
@Inject(method = "openScreen", at = @At("HEAD"))
private void dummyGenerateRefmap(Screen screen, CallbackInfo ci) {
// NO-OP this injection is only here to generate the refmap
}
@ModifyVariable(method = "openScreen", at = @At("HEAD"), argsOnly = true)
private Screen upgradeControlScreen(Screen opened) {
// Swap the control options screen with our own instance whenever something tries to open one
if(opened != null && ControlsOptionsScreen.class.equals(opened.getClass())) {
return new ControlsSettingsGuiNew(this.currentScreen, MinecraftClient.getInstance().options);
}
return opened;
}
}
| 40.264706 | 105 | 0.758218 |
88f5338b36518d2ac93f5748b4477e65dd5f5ced | 182 | package jge;
public abstract class Scene {
protected Camera camera;
public Scene() {
}
public void init() {
}
public abstract void update(float dt);
}
| 10.705882 | 42 | 0.60989 |
3c04eeda3c4b9aa9497709e5ca6d38d757700276 | 2,009 | ////////////////////////////////////////////////////////////////////////////////
//
// Created by NUebele on 18.10.2018.
//
// Copyright (c) 2006 - 2018 FORCAM GmbH. All rights reserved.
////////////////////////////////////////////////////////////////////////////////
package com.forcam.na.ffwebservices.model.shift;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* WS model to create a staff member shift.
*/
@ApiModel(value = "createStaffMemberShiftProperties")
@JsonPropertyOrder({ "staffMemberId", "shift", "shiftTypeId" })
public class CreateStaffMemberShiftPropertiesWSModel {
// ------------------------------------------------------------------------
// members
// ------------------------------------------------------------------------
/** Staff member ID. */
private String mStaffMemberId;
/** The shift model */
private ShiftWSModel mShift = new ShiftWSModel();
/** Shift type unique id. */
private String mShiftTypeId;
// ------------------------------------------------------------------------
// getters/setters
// ------------------------------------------------------------------------
@ApiModelProperty(value = "UUID of the staff member", position = 1)
public void setStaffMemberId(String staffMemberId) {
mStaffMemberId = staffMemberId;
}
public String getStaffMemberId() {
return mStaffMemberId;
}
@ApiModelProperty(value = "The respective shift including its breaks", position = 2)
public void setShift(ShiftWSModel shift) {
mShift = shift;
}
public ShiftWSModel getShift() {
return mShift;
}
@ApiModelProperty(value = "UUID of the shift type", required = true, position = 3)
public void setShiftTypeId(String shiftTypeId) {
mShiftTypeId = shiftTypeId;
}
public String getShiftTypeId() {
return mShiftTypeId;
}
} | 31.390625 | 88 | 0.526132 |
bca3addb7198475672e04490d6dcf10d66001c93 | 1,631 | package com.speechpro.vk.onepassplugin.ui.startverification;
import com.avaya.sce.callflow.extension.DataConnectorCodeGenerator;
import com.avaya.sce.callflow.extension.DataConnectorFlowItem;
public class StartCodeGen extends DataConnectorCodeGenerator {
public StringBuilder generateConnectorItem(DataConnectorFlowItem item,
int indentLevel) {
StringBuilder sb = new StringBuilder();
StartFlowItem callOnePassServer = (StartFlowItem) item;
String personConstValue = callOnePassServer.getProperty(StartFlowItem.PROP_ID_CONST);
String personVarValue = callOnePassServer.getProperty(StartFlowItem.PROP_ID_VAR);
String personVar;
boolean personIsConstant;
if(personConstValue.equals("") == true){
personIsConstant = false;
personVar = personVarValue;
}else{
personIsConstant = true;
personVar = personConstValue;
}
indent(sb, indentLevel,
"actions.add(new onepassplugin.StartingVerification(\"");
sb.append(callOnePassServer.getProperty(StartFlowItem.PROP_PASSWORD_VAR));
sb.append("\", \"");
sb.append(callOnePassServer.getProperty(StartFlowItem.PROP_PASSWORD_VARFIELD));
sb.append("\", \"");
sb.append(callOnePassServer.getProperty(StartFlowItem.PROP_VERIFICATIONID_VAR));
sb.append("\", \"");
sb.append(callOnePassServer.getProperty(StartFlowItem.PROP_VERIFICATIONID_VARFIELD));
sb.append("\", \"");
sb.append(personVar);
sb.append("\", \"");
sb.append(callOnePassServer.getProperty(StartFlowItem.PROP_ID_VARFIELD));
sb.append("\" ," + Boolean.toString(personIsConstant));
sb.append(").setDebugId(" + item.getFlowObjectId() + "));");
return sb;
}
}
| 36.244444 | 87 | 0.763335 |
424b235cb01ff3fd2b00947c62f7dfa3e2cf3a3e | 887 | package ch.ethz.systems.netbench.xpt.aifo.ports.FIFO;
import ch.ethz.systems.netbench.core.log.SimulationLogger;
import ch.ethz.systems.netbench.core.network.Link;
import ch.ethz.systems.netbench.core.network.NetworkDevice;
import ch.ethz.systems.netbench.core.network.OutputPort;
import ch.ethz.systems.netbench.core.run.infrastructure.OutputPortGenerator;
public class FIFOOutputPortGenerator extends OutputPortGenerator {
private final long maxQueueSize;
public FIFOOutputPortGenerator(long maxQueueSize) {
this.maxQueueSize = maxQueueSize;
SimulationLogger.logInfo("Port", "FIFO(maxQueueSize=" + maxQueueSize + ")");
}
@Override
public OutputPort generate(NetworkDevice ownNetworkDevice, NetworkDevice towardsNetworkDevice, Link link) {
return new FIFOOutputPort(ownNetworkDevice, towardsNetworkDevice, link, maxQueueSize);
}
}
| 35.48 | 111 | 0.78354 |
e5c999c2d38329c28f1fad2bb1fcd42b4130501e | 86 | /**
* Contains the jobs to execute by the cron.
*/
package org.encuestame.core.cron; | 21.5 | 44 | 0.709302 |
deb37bac80edb390607f0eabcea5414537d21230 | 12,044 | /*
* Copyright 2003 - 2015 The eFaps Team
*
* 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.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.efaps.esjp.timereport.listener;
import java.math.BigDecimal;
import java.util.Properties;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.db.CachedPrintQuery;
import org.efaps.db.Instance;
import org.efaps.db.MultiPrintQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.db.SelectBuilder;
import org.efaps.esjp.ci.CITimeReport;
import org.efaps.esjp.common.AbstractCommon;
import org.efaps.esjp.timereport.util.Timereport;
import org.efaps.esjp.timereport.util.TimereportSettings;
import org.efaps.util.EFapsException;
import org.joda.time.DateTime;
/**
* TODO comment!
*
* @author The eFaps Team
* @version $Id: $
*/
@EFapsUUID("be7bb3ea-2e4d-43bb-8dc7-173d18573aca")
@EFapsApplication("eFapsApp-TimeReport")
public abstract class AbstractOnPayroll_Base
extends AbstractCommon
{
private Instance emplInst;
private DateTime date;
private DateTime dueDate;
protected TimeBean getTimeBean(final Parameter _parameter)
throws EFapsException
{
final TimeBean ret = new TimeBean();
final QueryBuilder queryBldr = new QueryBuilder(CITimeReport.EmployeeTimeCardPosition);
queryBldr.addType(CITimeReport.EmployeeAbsencePosition);
add2QueryBldr(_parameter, queryBldr);
final MultiPrintQuery multi = queryBldr.getCachedPrint4Request();
final SelectBuilder selAbsenceInst = SelectBuilder.get()
.linkto(CITimeReport.EmployeeTimeCardPosition.AttrDefLinkAbstract).instance();
multi.addSelect(selAbsenceInst);
multi.addAttribute(CITimeReport.EmployeeTimeCardPosition.LaborTime,
CITimeReport.EmployeeTimeCardPosition.ExtraLaborTime,
CITimeReport.EmployeeTimeCardPosition.NightLaborTime,
CITimeReport.EmployeeTimeCardPosition.HolidayLaborTime);
multi.execute();
while (multi.next()) {
if (multi.getCurrentInstance().getType().isCIType(CITimeReport.EmployeeAbsencePosition)) {
final Instance absenceInst = multi.getSelect(selAbsenceInst);
if (absenceInst != null && absenceInst.isValid()) {
analyzeAbsence(_parameter, ret, absenceInst);
}
} else {
ret.addLaborTime(multi.<Object[]>getAttribute(CITimeReport.EmployeeTimeCardPosition.LaborTime));
ret.addExtraLaborTime(multi.<Object[]>getAttribute(
CITimeReport.EmployeeTimeCardPosition.ExtraLaborTime));
ret.addNightLaborTime(multi.<Object[]>getAttribute(
CITimeReport.EmployeeTimeCardPosition.NightLaborTime));
ret.addHolidayLaborTime(multi
.<Object[]>getAttribute(CITimeReport.EmployeeTimeCardPosition.HolidayLaborTime));
}
}
return ret;
}
protected abstract void analyzeAbsence(final Parameter _parameter,
final TimeBean _bean,
final Instance _absenceInst)
throws EFapsException;
protected void addTimeFromSysConf(final Parameter _parameter,
final TimeBean _bean,
final Instance _absenceInst,
final String _key)
throws EFapsException
{
final CachedPrintQuery print = CachedPrintQuery.get4Request(_absenceInst);
print.addAttribute(CITimeReport.AttributeDefinitionAbsenceReason.MappingKey);
print.execute();
final String key = print.getAttribute(CITimeReport.AttributeDefinitionAbsenceReason.MappingKey);
_bean.addLaborTime(getTimeFromSysConf(_parameter, key + "." + _key + "." + "LT"));
_bean.addExtraLaborTime(getTimeFromSysConf(_parameter, key + "." + _key + "." + "ELT"));
_bean.addNightLaborTime(getTimeFromSysConf(_parameter, key + "." + _key + "." + "NLT"));
_bean.addHolidayLaborTime(getTimeFromSysConf(_parameter, key + "." + _key + "." + "HLT"));
}
protected BigDecimal getTimeFromSysConf(final Parameter _parameter,
final String _key)
throws EFapsException
{
BigDecimal ret = BigDecimal.ZERO;
final Properties properties = Timereport.getSysConfig().getAttributeValueAsProperties(
TimereportSettings.ABSENCECONFIG, true);
if (properties.containsKey(_key)) {
ret = new BigDecimal(properties.getProperty(_key));
}
return ret;
}
/**
* @param _parameter
*/
protected abstract void add2QueryBldr(final Parameter _parameter,
final QueryBuilder _queryBldr)
throws EFapsException;
public static class TimeBean
{
private BigDecimal laborTime;
private BigDecimal extraLaborTime;
private BigDecimal nightLaborTime;
private BigDecimal holidayLaborTime;
public void addLaborTime(final Object[] _valueWithUom)
{
if (this.laborTime == null) {
this.laborTime = BigDecimal.ZERO;
}
this.laborTime = this.laborTime.add((BigDecimal) _valueWithUom[0]);
}
public void addLaborTime(final BigDecimal _laborTime)
{
if (this.laborTime == null) {
this.laborTime = BigDecimal.ZERO;
}
this.laborTime = this.laborTime.add(_laborTime);
}
public void addExtraLaborTime(final Object[] _valueWithUom)
{
if (this.extraLaborTime == null) {
this.extraLaborTime = BigDecimal.ZERO;
}
this.extraLaborTime = this.extraLaborTime.add((BigDecimal) _valueWithUom[0]);
}
public void addExtraLaborTime(final BigDecimal _laborTime)
{
if (this.extraLaborTime == null) {
this.extraLaborTime = BigDecimal.ZERO;
}
this.extraLaborTime = this.extraLaborTime.add(_laborTime);
}
public void addNightLaborTime(final Object[] _valueWithUom)
{
if (this.nightLaborTime == null) {
this.nightLaborTime = BigDecimal.ZERO;
}
this.nightLaborTime = this.nightLaborTime.add((BigDecimal) _valueWithUom[0]);
}
public void addNightLaborTime(final BigDecimal _laborTime)
{
if (this.nightLaborTime == null) {
this.nightLaborTime = BigDecimal.ZERO;
}
this.nightLaborTime = this.nightLaborTime.add(_laborTime);
}
public void addHolidayLaborTime(final Object[] _valueWithUom)
{
if (this.holidayLaborTime == null) {
this.holidayLaborTime = BigDecimal.ZERO;
}
this.holidayLaborTime = this.holidayLaborTime.add((BigDecimal) _valueWithUom[0]);
}
public void addHolidayLaborTime(final BigDecimal _laborTime)
{
if (this.holidayLaborTime == null) {
this.holidayLaborTime = BigDecimal.ZERO;
}
this.holidayLaborTime = this.holidayLaborTime.add(_laborTime);
}
/**
* Getter method for the instance variable {@link #laborTime}.
*
* @return value of instance variable {@link #laborTime}
*/
public BigDecimal getLaborTime()
{
return this.laborTime;
}
/**
* Setter method for instance variable {@link #laborTime}.
*
* @param _laborTime value for instance variable {@link #laborTime}
*/
public void setLaborTime(final BigDecimal _laborTime)
{
this.laborTime = _laborTime;
}
/**
* Getter method for the instance variable {@link #extraLaborTime}.
*
* @return value of instance variable {@link #extraLaborTime}
*/
public BigDecimal getExtraLaborTime()
{
return this.extraLaborTime;
}
/**
* Setter method for instance variable {@link #extraLaborTime}.
*
* @param _extraLaborTime value for instance variable
* {@link #extraLaborTime}
*/
public void setExtraLaborTime(final BigDecimal _extraLaborTime)
{
this.extraLaborTime = _extraLaborTime;
}
/**
* Getter method for the instance variable {@link #nightLaborTime}.
*
* @return value of instance variable {@link #nightLaborTime}
*/
public BigDecimal getNightLaborTime()
{
return this.nightLaborTime;
}
/**
* Setter method for instance variable {@link #nightLaborTime}.
*
* @param _nightLaborTime value for instance variable
* {@link #nightLaborTime}
*/
public void setNightLaborTime(final BigDecimal _nightLaborTime)
{
this.nightLaborTime = _nightLaborTime;
}
/**
* Getter method for the instance variable {@link #holidayLaborTime}.
*
* @return value of instance variable {@link #holidayLaborTime}
*/
public BigDecimal getHolidayLaborTime()
{
return this.holidayLaborTime;
}
/**
* Setter method for instance variable {@link #holidayLaborTime}.
*
* @param _holidayLaborTime value for instance variable
* {@link #holidayLaborTime}
*/
public void setHolidayLaborTime(final BigDecimal _holidayLaborTime)
{
this.holidayLaborTime = _holidayLaborTime;
}
}
/**
* Getter method for the instance variable {@link #emplInst}.
*
* @return value of instance variable {@link #emplInst}
*/
public Instance getEmplInst()
{
return this.emplInst;
}
/**
* Setter method for instance variable {@link #emplInst}.
*
* @param _emplInst value for instance variable {@link #emplInst}
*/
public void setEmplInst(final Instance _emplInst)
{
this.emplInst = _emplInst;
}
/**
* Getter method for the instance variable {@link #date}.
*
* @return value of instance variable {@link #date}
*/
public DateTime getDate()
{
return this.date;
}
/**
* Setter method for instance variable {@link #date}.
*
* @param _date value for instance variable {@link #date}
*/
public void setDate(final DateTime _date)
{
this.date = _date;
}
/**
* Getter method for the instance variable {@link #dueDate}.
*
* @return value of instance variable {@link #dueDate}
*/
public DateTime getDueDate()
{
return this.dueDate;
}
/**
* Setter method for instance variable {@link #dueDate}.
*
* @param _dueDate value for instance variable {@link #dueDate}
*/
public void setDueDate(final DateTime _dueDate)
{
this.dueDate = _dueDate;
}
}
| 33.926761 | 113 | 0.610594 |
71fa94137411ca24d122f5eec79def810fa5efb0 | 2,016 | package com.sjarno.norascoffeeshop.controllers;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.sjarno.norascoffeeshop.models.UserAccount;
import com.sjarno.norascoffeeshop.services.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserAccountController {
@Autowired
private UserAccountService userAccountService;
/* Update username */
@PutMapping("/update-username")
public ResponseEntity<?> updateUsername(@RequestBody String newUsername) {
Map<String, String> result = new HashMap<>();
try {
UserAccount user = userAccountService.updateUsername(newUsername);
result.put("username", user.getUsername());
return new ResponseEntity<Map<String, String>>(result, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<String>(e.getMessage(), HttpStatus.UNPROCESSABLE_ENTITY);
}
}
/* Update password */
@PutMapping("/update-password")
public ResponseEntity<?> updatePassword(
@RequestParam String newPassword,
@RequestParam String oldPassword) {
Map<String, UserAccount> result = new HashMap<>();
try {
UserAccount updatedAccount = userAccountService.updatePassword(newPassword, oldPassword);
result.put("user", updatedAccount);
return new ResponseEntity<Map<String, UserAccount>>(result, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<String>(e.getMessage(), HttpStatus.UNPROCESSABLE_ENTITY);
}
}
}
| 36 | 101 | 0.720734 |
5214efcbc906aeef135ed29694142982ed5bb9d3 | 18,576 | /*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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.kuali.kra.iacuc.actions.amendrenew;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.kuali.kra.iacuc.IacucProtocol;
import org.kuali.kra.iacuc.IacucProtocolDocument;
import org.kuali.kra.iacuc.actions.IacucProtocolAction;
import org.kuali.kra.iacuc.actions.IacucProtocolActionType;
import org.kuali.kra.iacuc.actions.IacucProtocolStatus;
import org.kuali.kra.iacuc.questionnaire.IacucProtocolModuleQuestionnaireBean;
import org.kuali.kra.protocol.ProtocolBase;
import org.kuali.kra.protocol.actions.ProtocolActionBase;
import org.kuali.kra.protocol.actions.amendrenew.ProtocolAmendRenewModuleBase;
import org.kuali.kra.protocol.actions.amendrenew.ProtocolAmendRenewServiceImplBase;
import org.kuali.kra.protocol.actions.amendrenew.ProtocolAmendRenewalBase;
import org.kuali.kra.protocol.actions.amendrenew.ProtocolAmendmentBean;
import org.kuali.coeus.common.questionnaire.framework.answer.ModuleQuestionnaireBean;
import org.kuali.rice.krad.util.GlobalVariables;
/**
* The ProtocolBase Amendment/Renewal Service Implementation.
*/
public class IacucProtocolAmendRenewServiceImpl extends ProtocolAmendRenewServiceImplBase implements IacucProtocolAmendRenewService {
protected static final String CONTINUATION_ID = "C";
protected static final String CONTINUATION_NEXT_VALUE = "nextContinuationValue";
protected static final String CONTINUATION = "Continuation";
@Override
protected void addModules(ProtocolBase protocol, ProtocolAmendmentBean amendmentBean) {
ProtocolAmendRenewalBase amendmentEntry = protocol.getProtocolAmendRenewal();
if (amendmentBean.getGeneralInfo()) {
amendmentEntry.addModule(createModule(amendmentEntry, IacucProtocolModule.GENERAL_INFO));
} else {
protocol.merge(protocolFinderDao.findCurrentProtocolByNumber(protocol.getAmendedProtocolNumber()), IacucProtocolModule.GENERAL_INFO);
amendmentEntry.removeModule(IacucProtocolModule.GENERAL_INFO);
}
if (amendmentBean.getAddModifyAttachments()) {
amendmentEntry.addModule(createModule(amendmentEntry, IacucProtocolModule.ADD_MODIFY_ATTACHMENTS));
} else {
protocol.merge(protocolFinderDao.findCurrentProtocolByNumber(protocol.getAmendedProtocolNumber()), IacucProtocolModule.ADD_MODIFY_ATTACHMENTS);
amendmentEntry.removeModule(IacucProtocolModule.ADD_MODIFY_ATTACHMENTS);
}
if (amendmentBean.getAreasOfResearch()) {
amendmentEntry.addModule(createModule(amendmentEntry, IacucProtocolModule.AREAS_OF_RESEARCH));
} else {
protocol.merge(protocolFinderDao.findCurrentProtocolByNumber(protocol.getAmendedProtocolNumber()), IacucProtocolModule.AREAS_OF_RESEARCH);
amendmentEntry.removeModule(IacucProtocolModule.AREAS_OF_RESEARCH);
}
if (amendmentBean.getFundingSource()) {
amendmentEntry.addModule(createModule(amendmentEntry, IacucProtocolModule.FUNDING_SOURCE));
} else {
protocol.merge(protocolFinderDao.findCurrentProtocolByNumber(protocol.getAmendedProtocolNumber()), IacucProtocolModule.FUNDING_SOURCE);
amendmentEntry.removeModule(IacucProtocolModule.FUNDING_SOURCE);
}
if (amendmentBean.getProtocolOrganizations()) {
amendmentEntry.addModule(createModule(amendmentEntry, IacucProtocolModule.PROTOCOL_ORGANIZATIONS));
} else {
protocol.merge(protocolFinderDao.findCurrentProtocolByNumber(protocol.getAmendedProtocolNumber()), IacucProtocolModule.PROTOCOL_ORGANIZATIONS);
amendmentEntry.removeModule(IacucProtocolModule.PROTOCOL_ORGANIZATIONS);
}
if (amendmentBean.getProtocolReferencesAndOtherIdentifiers()) {
amendmentEntry.addModule(createModule(amendmentEntry, IacucProtocolModule.PROTOCOL_REFERENCES));
} else {
protocol.merge(protocolFinderDao.findCurrentProtocolByNumber(protocol.getAmendedProtocolNumber()), IacucProtocolModule.PROTOCOL_REFERENCES);
amendmentEntry.removeModule(IacucProtocolModule.PROTOCOL_REFERENCES);
}
if (amendmentBean.getSubjects()) {
amendmentEntry.addModule(createModule(amendmentEntry, IacucProtocolModule.SUBJECTS));
} else {
protocol.merge(protocolFinderDao.findCurrentProtocolByNumber(protocol.getAmendedProtocolNumber()), IacucProtocolModule.SUBJECTS);
amendmentEntry.removeModule(IacucProtocolModule.SUBJECTS);
}
if (amendmentBean.getSpecialReview()) {
amendmentEntry.addModule(createModule(amendmentEntry, IacucProtocolModule.SPECIAL_REVIEW));
} else {
protocol.merge(protocolFinderDao.findCurrentProtocolByNumber(protocol.getAmendedProtocolNumber()), IacucProtocolModule.SPECIAL_REVIEW);
amendmentEntry.removeModule(IacucProtocolModule.SPECIAL_REVIEW);
}
if (amendmentBean.getOthers()) {
amendmentEntry.addModule(createModule(amendmentEntry, IacucProtocolModule.OTHERS));
} else {
protocol.merge(protocolFinderDao.findCurrentProtocolByNumber(protocol.getAmendedProtocolNumber()), IacucProtocolModule.OTHERS);
amendmentEntry.removeModule(IacucProtocolModule.OTHERS);
}
if (amendmentBean.getProtocolPermissions()) {
amendmentEntry.addModule(createModule(amendmentEntry, IacucProtocolModule.PROTOCOL_PERMISSIONS));
} else {
protocol.merge(protocolFinderDao.findCurrentProtocolByNumber(protocol.getAmendedProtocolNumber()), IacucProtocolModule.PROTOCOL_PERMISSIONS);
amendmentEntry.removeModule(IacucProtocolModule.PROTOCOL_PERMISSIONS);
}
if (amendmentBean.getQuestionnaire()) {
amendmentEntry.addModule(createModule(amendmentEntry, IacucProtocolModule.QUESTIONNAIRE));
} else {
removeEditedQuestionaire(protocol);
amendmentEntry.removeModule(IacucProtocolModule.QUESTIONNAIRE);
}
if (((IacucProtocolAmendmentBean)amendmentBean).getThreers()) {
amendmentEntry.addModule(createModule(amendmentEntry, IacucProtocolModule.THREE_RS));
} else {
protocol.merge(protocolFinderDao.findCurrentProtocolByNumber(protocol.getAmendedProtocolNumber()), IacucProtocolModule.THREE_RS);
amendmentEntry.removeModule(IacucProtocolModule.THREE_RS);
}
if (((IacucProtocolAmendmentBean)amendmentBean).getSpeciesAndGroups()) {
amendmentEntry.addModule(createModule(amendmentEntry, IacucProtocolModule.SPECIES_GROUPS));
} else {
protocol.merge(protocolFinderDao.findCurrentProtocolByNumber(protocol.getAmendedProtocolNumber()), IacucProtocolModule.SPECIES_GROUPS);
amendmentEntry.removeModule(IacucProtocolModule.SPECIES_GROUPS);
}
if (((IacucProtocolAmendmentBean)amendmentBean).getProcedures()) {
amendmentEntry.addModule(createModule(amendmentEntry, IacucProtocolModule.PROCEDURES));
} else {
protocol.merge(protocolFinderDao.findCurrentProtocolByNumber(protocol.getAmendedProtocolNumber()), IacucProtocolModule.PROCEDURES);
amendmentEntry.removeModule(IacucProtocolModule.PROCEDURES);
}
if (((IacucProtocolAmendmentBean)amendmentBean).getProtocolExceptions()) {
amendmentEntry.addModule(createModule(amendmentEntry, IacucProtocolModule.EXCEPTIONS));
} else {
protocol.merge(protocolFinderDao.findCurrentProtocolByNumber(protocol.getAmendedProtocolNumber()), IacucProtocolModule.EXCEPTIONS);
amendmentEntry.removeModule(IacucProtocolModule.EXCEPTIONS);
}
if (amendmentBean.getProtocolPersonnel()) {
amendmentEntry.addModule(createModule(amendmentEntry, IacucProtocolModule.PROTOCOL_PERSONNEL));
} else {
protocol.merge(protocolFinderDao.findCurrentProtocolByNumber(protocol.getAmendedProtocolNumber()), IacucProtocolModule.PROTOCOL_PERSONNEL);
amendmentEntry.removeModule(IacucProtocolModule.PROTOCOL_PERSONNEL);
}
}
@Override
protected ProtocolActionBase getNewAmendmentProtocolActionInstanceHook(ProtocolBase protocol) {
return new IacucProtocolAction((IacucProtocol)protocol, IacucProtocolActionType.AMENDMENT_CREATED);
}
@Override
protected ProtocolActionBase getNewRenewalProtocolActionInstanceHook(ProtocolBase protocol) {
return new IacucProtocolAction((IacucProtocol)protocol, IacucProtocolActionType.RENEWAL_CREATED);
}
@Override
protected ProtocolActionBase getNewRenewalWithAmendmentProtocolActionInstanceHook(ProtocolBase protocol) {
return new IacucProtocolAction((IacucProtocol)protocol, IacucProtocolActionType.RENEWAL_WITH_AMENDMENT_CREATED);
}
@Override
protected ModuleQuestionnaireBean getNewProtocolModuleQuestionnaireBeanInstanceHook(ProtocolBase protocol) {
return new IacucProtocolModuleQuestionnaireBean((IacucProtocol) protocol);
}
@Override
protected String getAmendmentInProgressStatusHook() {
return IacucProtocolStatus.AMENDMENT_IN_PROGRESS;
}
@Override
protected String getRenewalInProgressStatusHook() {
return IacucProtocolStatus.RENEWAL_IN_PROGRESS;
}
protected List<String> getAllModuleTypeCodes() {
List<String> moduleTypeCodes = new ArrayList<String>();
moduleTypeCodes.add(IacucProtocolModule.GENERAL_INFO);
moduleTypeCodes.add(IacucProtocolModule.ADD_MODIFY_ATTACHMENTS);
moduleTypeCodes.add(IacucProtocolModule.AREAS_OF_RESEARCH);
moduleTypeCodes.add(IacucProtocolModule.FUNDING_SOURCE);
moduleTypeCodes.add(IacucProtocolModule.OTHERS);
moduleTypeCodes.add(IacucProtocolModule.PROTOCOL_ORGANIZATIONS);
moduleTypeCodes.add(IacucProtocolModule.PROTOCOL_PERSONNEL);
moduleTypeCodes.add(IacucProtocolModule.PROTOCOL_REFERENCES);
moduleTypeCodes.add(IacucProtocolModule.SPECIAL_REVIEW);
moduleTypeCodes.add(IacucProtocolModule.SUBJECTS);
moduleTypeCodes.add(IacucProtocolModule.PROTOCOL_PERMISSIONS);
moduleTypeCodes.add(IacucProtocolModule.QUESTIONNAIRE);
moduleTypeCodes.add(IacucProtocolModule.THREE_RS);
moduleTypeCodes.add(IacucProtocolModule.SPECIES_GROUPS);
moduleTypeCodes.add(IacucProtocolModule.PROCEDURES);
moduleTypeCodes.add(IacucProtocolModule.EXCEPTIONS);
return moduleTypeCodes;
}
@Override
protected Class<? extends ProtocolBase> getProtocolBOClassHook() {
return IacucProtocol.class;
}
@Override
protected ProtocolAmendRenewalBase getNewProtocolAmendRenewalInstanceHook() {
return new IacucProtocolAmendRenewal();
}
@Override
protected ProtocolAmendRenewModuleBase getNewProtocolAmendRenewModuleInstanceHook() {
return new IacucProtocolAmendRenewModule();
}
public String createContinuation (IacucProtocolDocument protocolDocument, String continuationSummary) throws Exception {
IacucProtocolDocument continuationProtocolDocument = null;
try {
//since the user probably doesn't have permission to create the document, we are going to add session variable so the document
//authorizer knows to approve the user for initiating the document
GlobalVariables.getUserSession().addObject(AMEND_RENEW_CONTINUATION_ALLOW_NEW_PROTOCOL_DOCUMENT, Boolean.TRUE);
continuationProtocolDocument = (IacucProtocolDocument)getProtocolCopyService().copyProtocol(protocolDocument, generateProtocolContinuationNumber(protocolDocument), true);
} finally {
GlobalVariables.getUserSession().removeObject(AMEND_RENEW_CONTINUATION_ALLOW_NEW_PROTOCOL_DOCUMENT);
}
continuationProtocolDocument.getProtocol().setInitialSubmissionDate(protocolDocument.getProtocol().getInitialSubmissionDate());
continuationProtocolDocument.getProtocol().setApprovalDate(protocolDocument.getProtocol().getApprovalDate());
continuationProtocolDocument.getProtocol().setExpirationDate(protocolDocument.getProtocol().getExpirationDate());
continuationProtocolDocument.getProtocol().setLastApprovalDate(protocolDocument.getProtocol().getLastApprovalDate());
continuationProtocolDocument.getProtocol().setProtocolStatusCode(IacucProtocolStatus.CONTINUATION_IN_PROGRESS);
continuationProtocolDocument.getProtocol().refreshReferenceObject(PROTOCOL_STATUS);
markProtocolAttachmentsAsFinalized(continuationProtocolDocument.getProtocol().getAttachmentProtocols());
IacucProtocolAction protocolAction = createCreateContinuationProtocolAction(protocolDocument.getIacucProtocol(),
continuationProtocolDocument.getIacucProtocol().getProtocolNumber());
protocolDocument.getProtocol().getProtocolActions().add(protocolAction);
// attributes are same for continuation. Let us use the same amendrenewal object here.
ProtocolAmendRenewalBase protocolAmendRenewal = createAmendmentRenewal(protocolDocument, continuationProtocolDocument, continuationSummary);
continuationProtocolDocument.getProtocol().setProtocolAmendRenewal(protocolAmendRenewal);
documentService.saveDocument(protocolDocument);
documentService.saveDocument(continuationProtocolDocument);
return continuationProtocolDocument.getDocumentNumber();
}
public String createContinuationWithAmendment(IacucProtocolDocument protocolDocument, ProtocolAmendmentBean amendmentBean) throws Exception {
IacucProtocolDocument continuationProtocolDocument = null;
try {
//since the user probably doesn't have permission to create the document, we are going to add session variable so the document
//authorizer knows to approve the user for initiating the document
GlobalVariables.getUserSession().addObject(AMEND_RENEW_CONTINUATION_ALLOW_NEW_PROTOCOL_DOCUMENT, Boolean.TRUE);
continuationProtocolDocument = (IacucProtocolDocument)getProtocolCopyService().copyProtocol(protocolDocument, generateProtocolContinuationNumber(protocolDocument), true);
} finally {
GlobalVariables.getUserSession().removeObject(AMEND_RENEW_CONTINUATION_ALLOW_NEW_PROTOCOL_DOCUMENT);
}
continuationProtocolDocument.getProtocol().setInitialSubmissionDate(protocolDocument.getProtocol().getInitialSubmissionDate());
continuationProtocolDocument.getProtocol().setApprovalDate(protocolDocument.getProtocol().getApprovalDate());
continuationProtocolDocument.getProtocol().setExpirationDate(protocolDocument.getProtocol().getExpirationDate());
continuationProtocolDocument.getProtocol().setLastApprovalDate(protocolDocument.getProtocol().getLastApprovalDate());
continuationProtocolDocument.getProtocol().setProtocolStatusCode(IacucProtocolStatus.CONTINUATION_IN_PROGRESS);
continuationProtocolDocument.getProtocol().refreshReferenceObject(PROTOCOL_STATUS);
markProtocolAttachmentsAsFinalized(continuationProtocolDocument.getProtocol().getAttachmentProtocols());
IacucProtocolAction protocolAction = createCreateContinuationProtocolAction(protocolDocument.getIacucProtocol(),
continuationProtocolDocument.getProtocol().getProtocolNumber());
protocolDocument.getProtocol().getProtocolActions().add(protocolAction);
return createAmendment(protocolDocument, continuationProtocolDocument, amendmentBean);
}
/**
* Generate the protocol number for an continuation. The protocol number for
* continuation is the original protocol's number appended with "Cxxx" where
* "xxx" is the next sequence number.
* @param protocolDocument
* @return
*/
protected String generateProtocolContinuationNumber(IacucProtocolDocument protocolDocument) {
return generateProtocolNumber(protocolDocument, CONTINUATION_ID, CONTINUATION_NEXT_VALUE);
}
/**
* Create a ProtocolBase Action indicating that a renewal has been created.
* @param protocol
* @param protocolNumber protocol number of the renewal
* @return a protocol action
*/
protected IacucProtocolAction createCreateContinuationProtocolAction(IacucProtocol protocol, String protocolNumber) {
IacucProtocolAction protocolAction = new IacucProtocolAction(protocol, IacucProtocolActionType.CONTINUATION);
protocolAction.setComments(CONTINUATION + "-" + protocolNumber.substring(11) + ": " + CREATED);
return protocolAction;
}
@SuppressWarnings("unchecked")
public Collection<IacucProtocol> getContinuations(String protocolNumber) throws Exception {
List<IacucProtocol> continuations = new ArrayList<IacucProtocol>();
Collection<IacucProtocol> protocols = (Collection<IacucProtocol>) kraLookupDao.findCollectionUsingWildCard(IacucProtocol.class, PROTOCOL_NUMBER, protocolNumber + CONTINUATION_ID + "%", true);
for (ProtocolBase protocol : protocols) {
IacucProtocolDocument protocolDocument = (IacucProtocolDocument) documentService.getByDocumentHeaderId(protocol.getProtocolDocument().getDocumentNumber());
continuations.add(protocolDocument.getIacucProtocol());
}
return continuations;
}
@Override
public List<ProtocolBase> getAmendmentAndRenewals(String protocolNumber) throws Exception {
List<ProtocolBase> protocols = super.getAmendmentAndRenewals(protocolNumber);
// let us add continuations (continuation is same as renewal)
protocols.addAll(getContinuations(protocolNumber));
return protocols;
}
}
| 57.333333 | 199 | 0.762382 |
07d020dc7efa4c57b602e42cd4de11ab156829bb | 32,430 | package gnu.expr;
import gnu.bytecode.Access;
import gnu.bytecode.ClassType;
import gnu.bytecode.CodeAttr;
import gnu.bytecode.Field;
import gnu.bytecode.Label;
import gnu.bytecode.Method;
import gnu.bytecode.PrimType;
import gnu.bytecode.Type;
import gnu.bytecode.Variable;
import gnu.mapping.Environment;
import gnu.mapping.EnvironmentKey;
import gnu.mapping.Location;
import gnu.mapping.Named;
import gnu.mapping.Namespace;
import gnu.mapping.OutPort;
import gnu.mapping.Symbol;
import gnu.mapping.WrappedException;
import gnu.math.IntNum;
import gnu.text.Char;
import gnu.text.SourceLocator;
public class Declaration implements SourceLocator {
static final int CAN_CALL = 4;
static final int CAN_READ = 2;
static final int CAN_WRITE = 8;
public static final long CLASS_ACCESS_FLAGS = 25820135424L;
public static final int EARLY_INIT = 536870912;
public static final long ENUM_ACCESS = 8589934592L;
public static final int EXPORT_SPECIFIED = 1024;
public static final int EXTERNAL_ACCESS = 524288;
public static final long FIELD_ACCESS_FLAGS = 32463912960L;
public static final int FIELD_OR_METHOD = 1048576;
public static final long FINAL_ACCESS = 17179869184L;
static final int INDIRECT_BINDING = 1;
public static final int IS_ALIAS = 256;
public static final int IS_CONSTANT = 16384;
public static final int IS_DYNAMIC = 268435456;
static final int IS_FLUID = 16;
public static final int IS_IMPORTED = 131072;
public static final int IS_NAMESPACE_PREFIX = 2097152;
static final int IS_SIMPLE = 64;
public static final int IS_SINGLE_VALUE = 262144;
public static final int IS_SYNTAX = 32768;
public static final int IS_UNKNOWN = 65536;
public static final long METHOD_ACCESS_FLAGS = 17431527424L;
public static final int MODULE_REFERENCE = 1073741824;
public static final int NONSTATIC_SPECIFIED = 4096;
public static final int NOT_DEFINING = 512;
public static final int PACKAGE_ACCESS = 134217728;
static final int PRIVATE = 32;
public static final int PRIVATE_ACCESS = 16777216;
public static final String PRIVATE_PREFIX = "$Prvt$";
public static final int PRIVATE_SPECIFIED = 16777216;
static final int PROCEDURE = 128;
public static final int PROTECTED_ACCESS = 33554432;
public static final int PUBLIC_ACCESS = 67108864;
public static final int STATIC_SPECIFIED = 2048;
public static final long TRANSIENT_ACCESS = 4294967296L;
public static final int TYPE_SPECIFIED = 8192;
static final String UNKNOWN_PREFIX = "loc$";
public static final long VOLATILE_ACCESS = 2147483648L;
static int counter;
public Declaration base;
public ScopeExp context;
int evalIndex;
public Field field;
String filename;
public ApplyExp firstCall;
protected long flags;
protected int id;
Method makeLocationMethod;
Declaration next;
Declaration nextCapturedVar;
int position;
Object symbol;
protected Type type;
protected Expression typeExp;
protected Expression value;
Variable var;
public void setCode(int code) {
if (code >= 0) {
throw new Error("code must be negative");
}
this.id = code;
}
public int getCode() {
return this.id;
}
public final Expression getTypeExp() {
if (this.typeExp == null) {
setType(Type.objectType);
}
return this.typeExp;
}
public final Type getType() {
if (this.type == null) {
setType(Type.objectType);
}
return this.type;
}
public final void setType(Type type2) {
this.type = type2;
if (this.var != null) {
this.var.setType(type2);
}
this.typeExp = QuoteExp.getInstance(type2);
}
public final void setTypeExp(Expression typeExp2) {
Type t;
this.typeExp = typeExp2;
if (typeExp2 instanceof TypeValue) {
t = ((TypeValue) typeExp2).getImplementationType();
} else {
t = Language.getDefaultLanguage().getTypeFor(typeExp2, false);
}
if (t == null) {
t = Type.pointer_type;
}
this.type = t;
if (this.var != null) {
this.var.setType(t);
}
}
public final String getName() {
if (this.symbol == null) {
return null;
}
return this.symbol instanceof Symbol ? ((Symbol) this.symbol).getName() : this.symbol.toString();
}
public final void setName(Object symbol2) {
this.symbol = symbol2;
}
public final Object getSymbol() {
return this.symbol;
}
public final void setSymbol(Object symbol2) {
this.symbol = symbol2;
}
public final Declaration nextDecl() {
return this.next;
}
public final void setNext(Declaration next2) {
this.next = next2;
}
public Variable getVariable() {
return this.var;
}
public final boolean isSimple() {
return (this.flags & 64) != 0;
}
public final void setSimple(boolean b) {
setFlag(b, 64);
if (this.var != null && !this.var.isParameter()) {
this.var.setSimple(b);
}
}
public final void setSyntax() {
setSimple(false);
setFlag(536920064);
}
public final ScopeExp getContext() {
return this.context;
}
/* access modifiers changed from: 0000 */
public void loadOwningObject(Declaration owner, Compilation comp) {
if (owner == null) {
owner = this.base;
}
if (owner != null) {
owner.load(null, 0, comp, Target.pushObject);
} else {
getContext().currentLambda().loadHeapFrame(comp);
}
}
/* JADX WARNING: type inference failed for: r26v0, types: [gnu.bytecode.Type] */
/* JADX WARNING: type inference failed for: r26v1, types: [gnu.bytecode.ClassType] */
/* JADX WARNING: type inference failed for: r26v2 */
/* JADX WARNING: type inference failed for: r2v5, types: [gnu.bytecode.Type] */
/* JADX WARNING: type inference failed for: r20v0, types: [gnu.bytecode.ClassType] */
/* JADX WARNING: type inference failed for: r0v78, types: [gnu.bytecode.ClassType] */
/* JADX WARNING: type inference failed for: r20v1 */
/* JADX WARNING: type inference failed for: r26v3 */
/* JADX WARNING: type inference failed for: r20v2, types: [gnu.bytecode.ClassType] */
/* JADX WARNING: type inference failed for: r0v88, types: [gnu.bytecode.ClassType] */
/* JADX WARNING: type inference failed for: r26v4 */
/* JADX WARNING: type inference failed for: r20v3 */
/* JADX WARNING: type inference failed for: r20v4 */
/* JADX WARNING: Multi-variable type inference failed */
/* JADX WARNING: Unknown variable types count: 8 */
public void load(AccessExp access, int flags2, Compilation comp, Target target) {
Method meth;
? r20;
if (!(target instanceof IgnoreTarget)) {
Declaration owner = access == null ? null : access.contextDecl();
if (isAlias() && (this.value instanceof ReferenceExp)) {
ReferenceExp rexp = (ReferenceExp) this.value;
Declaration orig = rexp.binding;
if (orig != null && (((flags2 & 2) == 0 || orig.isIndirectBinding()) && (owner == null || !orig.needsContext()))) {
orig.load(rexp, flags2, comp, target);
return;
}
}
if (!isFluid() || !(this.context instanceof FluidLetExp)) {
CodeAttr code = comp.getCode();
? type2 = getType();
if (isIndirectBinding() || (flags2 & 2) == 0) {
if (this.field != null) {
comp.usedClass(this.field.getDeclaringClass());
comp.usedClass(this.field.getType());
if (!this.field.getStaticFlag()) {
loadOwningObject(owner, comp);
code.emitGetField(this.field);
} else {
code.emitGetStatic(this.field);
}
} else if (!isIndirectBinding() || !comp.immediate || getVariable() != null) {
if (comp.immediate) {
Object val = getConstantValue();
if (val != null) {
comp.compileConstant(val, target);
return;
}
}
if (this.value == QuoteExp.undefined_exp || !ignorable() || ((this.value instanceof LambdaExp) && (((LambdaExp) this.value).outer instanceof ModuleExp))) {
Variable var2 = getVariable();
if ((this.context instanceof ClassExp) && var2 == null && !getFlag(128)) {
ClassExp cl = (ClassExp) this.context;
if (cl.isMakingClassPair()) {
Method getter = cl.type.getDeclaredMethod(ClassExp.slotToMethodName("get", getName()), 0);
cl.loadHeapFrame(comp);
code.emitInvoke(getter);
}
}
if (var2 == null) {
var2 = allocateVariable(code);
}
code.emitLoad(var2);
} else {
this.value.compile(comp, target);
return;
}
} else {
Environment env = Environment.getCurrent();
Symbol sym = this.symbol instanceof Symbol ? (Symbol) this.symbol : env.getSymbol(this.symbol.toString());
Object property = null;
if (isProcedureDecl() && comp.getLanguage().hasSeparateFunctionNamespace()) {
property = EnvironmentKey.FUNCTION;
}
comp.compileConstant(env.getLocation(sym, property), Target.pushValue(Compilation.typeLocation));
}
if (isIndirectBinding() && (flags2 & 2) == 0) {
if (access != null) {
String filename2 = access.getFileName();
if (filename2 != null) {
int line = access.getLineNumber();
if (line > 0) {
ClassType typeUnboundLocationException = ClassType.make("gnu.mapping.UnboundLocationException");
boolean isInTry = code.isInTry();
int column = access.getColumnNumber();
Label label = new Label(code);
label.define(code);
code.emitInvokeVirtual(Compilation.getLocationMethod);
Label endTry = new Label(code);
endTry.define(code);
Label endLabel = new Label(code);
endLabel.setTypes(code);
if (isInTry) {
code.emitGoto(endLabel);
} else {
code.setUnreachable();
}
int fragment_cookie = 0;
if (!isInTry) {
fragment_cookie = code.beginFragment(endLabel);
}
code.addHandler(label, endTry, typeUnboundLocationException);
code.emitDup((Type) typeUnboundLocationException);
code.emitPushString(filename2);
code.emitPushInt(line);
code.emitPushInt(column);
code.emitInvokeVirtual(typeUnboundLocationException.getDeclaredMethod("setLine", 3));
code.emitThrow();
if (isInTry) {
endLabel.define(code);
} else {
code.endFragment(fragment_cookie);
}
type2 = Type.pointer_type;
}
}
}
code.emitInvokeVirtual(Compilation.getLocationMethod);
type2 = Type.pointer_type;
}
} else if (this.field == null) {
throw new Error("internal error: cannot take location of " + this);
} else {
boolean immediate = comp.immediate;
if (this.field.getStaticFlag()) {
? make = ClassType.make("gnu.kawa.reflect.StaticFieldLocation");
meth = make.getDeclaredMethod("make", immediate ? 1 : 2);
r20 = make;
} else {
? make2 = ClassType.make("gnu.kawa.reflect.FieldLocation");
meth = make2.getDeclaredMethod("make", immediate ? 2 : 3);
loadOwningObject(owner, comp);
r20 = make2;
}
if (immediate) {
comp.compileConstant(this);
} else {
comp.compileConstant(this.field.getDeclaringClass().getName());
comp.compileConstant(this.field.getName());
}
code.emitInvokeStatic(meth);
type2 = r20;
}
target.compileFromStack(comp, type2);
return;
}
this.base.load(access, flags2, comp, target);
}
}
public void compileStore(Compilation comp) {
CodeAttr code = comp.getCode();
if (isSimple()) {
code.emitStore(getVariable());
} else if (!this.field.getStaticFlag()) {
loadOwningObject(null, comp);
code.emitSwap();
code.emitPutField(this.field);
} else {
code.emitPutStatic(this.field);
}
}
public final Expression getValue() {
if (this.value == QuoteExp.undefined_exp) {
if (this.field != null && (this.field.getModifiers() & 24) == 24 && !isIndirectBinding()) {
try {
this.value = new QuoteExp(this.field.getReflectField().get(null));
} catch (Throwable th) {
}
}
} else if ((this.value instanceof QuoteExp) && getFlag(8192) && this.value.getType() != this.type) {
try {
Object val = ((QuoteExp) this.value).getValue();
Type t = getType();
this.value = new QuoteExp(t.coerceFromObject(val), t);
} catch (Throwable th2) {
}
}
return this.value;
}
public final void setValue(Expression value2) {
this.value = value2;
}
public final Object getConstantValue() {
Expression v = getValue();
if (!(v instanceof QuoteExp) || v == QuoteExp.undefined_exp) {
return null;
}
return ((QuoteExp) v).getValue();
}
public final boolean hasConstantValue() {
Expression v = getValue();
return (v instanceof QuoteExp) && v != QuoteExp.undefined_exp;
}
/* access modifiers changed from: 0000 */
public boolean shouldEarlyInit() {
return getFlag(536870912) || isCompiletimeConstant();
}
public boolean isCompiletimeConstant() {
return getFlag(16384) && hasConstantValue();
}
public final boolean needsExternalAccess() {
return (this.flags & 524320) == 524320 || (this.flags & 2097184) == 2097184;
}
public final boolean needsContext() {
return this.base == null && this.field != null && !this.field.getStaticFlag();
}
public final boolean getFlag(long flag) {
return (this.flags & flag) != 0;
}
public final void setFlag(boolean setting, long flag) {
if (setting) {
this.flags |= flag;
} else {
this.flags &= -1 ^ flag;
}
}
public final void setFlag(long flag) {
this.flags |= flag;
}
public final boolean isPublic() {
return (this.context instanceof ModuleExp) && (this.flags & 32) == 0;
}
public final boolean isPrivate() {
return (this.flags & 32) != 0;
}
public final void setPrivate(boolean isPrivate) {
setFlag(isPrivate, 32);
}
public short getAccessFlags(short defaultFlags) {
short flags2;
if (getFlag(251658240)) {
flags2 = 0;
if (getFlag(16777216)) {
flags2 = (short) 2;
}
if (getFlag(33554432)) {
flags2 = (short) (flags2 | 4);
}
if (getFlag(67108864)) {
flags2 = (short) (flags2 | 1);
}
} else {
flags2 = defaultFlags;
}
if (getFlag(VOLATILE_ACCESS)) {
flags2 = (short) (flags2 | 64);
}
if (getFlag(TRANSIENT_ACCESS)) {
flags2 = (short) (flags2 | 128);
}
if (getFlag(ENUM_ACCESS)) {
flags2 = (short) (flags2 | Access.ENUM);
}
if (getFlag(FINAL_ACCESS)) {
return (short) (flags2 | 16);
}
return flags2;
}
public final boolean isAlias() {
return (this.flags & 256) != 0;
}
public final void setAlias(boolean flag) {
setFlag(flag, 256);
}
public final boolean isFluid() {
return (this.flags & 16) != 0;
}
public final void setFluid(boolean fluid) {
setFlag(fluid, 16);
}
public final boolean isProcedureDecl() {
return (this.flags & 128) != 0;
}
public final void setProcedureDecl(boolean val) {
setFlag(val, 128);
}
public final boolean isNamespaceDecl() {
return (this.flags & 2097152) != 0;
}
public final boolean isIndirectBinding() {
return (this.flags & 1) != 0;
}
public final void setIndirectBinding(boolean indirectBinding) {
setFlag(indirectBinding, 1);
}
public void maybeIndirectBinding(Compilation comp) {
if ((isLexical() && !(this.context instanceof ModuleExp)) || this.context == comp.mainLambda) {
setIndirectBinding(true);
}
}
public final boolean getCanRead() {
return (this.flags & 2) != 0;
}
public final void setCanRead(boolean read) {
setFlag(read, 2);
}
public final void setCanRead() {
setFlag(true, 2);
if (this.base != null) {
this.base.setCanRead();
}
}
public final boolean getCanCall() {
return (this.flags & 4) != 0;
}
public final void setCanCall(boolean called) {
setFlag(called, 4);
}
public final void setCanCall() {
setFlag(true, 4);
if (this.base != null) {
this.base.setCanRead();
}
}
public final boolean getCanWrite() {
return (this.flags & 8) != 0;
}
public final void setCanWrite(boolean written) {
if (written) {
this.flags |= 8;
} else {
this.flags &= -9;
}
}
public final void setCanWrite() {
this.flags |= 8;
if (this.base != null) {
this.base.setCanRead();
}
}
public final boolean isThisParameter() {
return this.symbol == ThisExp.THIS_NAME;
}
public boolean ignorable() {
if (getCanRead() || isPublic()) {
return false;
}
if (getCanWrite() && getFlag(65536)) {
return false;
}
if (!getCanCall()) {
return true;
}
Expression value2 = getValue();
if (value2 == null || !(value2 instanceof LambdaExp)) {
return false;
}
LambdaExp lexp = (LambdaExp) value2;
if (!lexp.isHandlingTailCalls() || lexp.getInlineOnly()) {
return true;
}
return false;
}
public boolean needsInit() {
return !ignorable() && (this.value != QuoteExp.nullExp || this.base == null);
}
public boolean isStatic() {
if (this.field != null) {
return this.field.getStaticFlag();
}
if (getFlag(2048) || isCompiletimeConstant()) {
return true;
}
if (getFlag(4096)) {
return false;
}
LambdaExp lambda = this.context.currentLambda();
if (!(lambda instanceof ModuleExp) || !((ModuleExp) lambda).isStatic()) {
return false;
}
return true;
}
public final boolean isLexical() {
return (this.flags & 268501008) == 0;
}
public static final boolean isUnknown(Declaration decl) {
return decl == null || decl.getFlag(65536);
}
public void noteValue(Expression value2) {
if (this.value == QuoteExp.undefined_exp) {
if (value2 instanceof LambdaExp) {
((LambdaExp) value2).nameDecl = this;
}
this.value = value2;
} else if (this.value != value2) {
if (this.value instanceof LambdaExp) {
((LambdaExp) this.value).nameDecl = null;
}
this.value = null;
}
}
protected Declaration() {
int i = counter + 1;
counter = i;
this.id = i;
this.value = QuoteExp.undefined_exp;
this.flags = 64;
this.makeLocationMethod = null;
}
public Declaration(Variable var2) {
this((Object) var2.getName(), var2.getType());
this.var = var2;
}
public Declaration(Object name) {
int i = counter + 1;
counter = i;
this.id = i;
this.value = QuoteExp.undefined_exp;
this.flags = 64;
this.makeLocationMethod = null;
setName(name);
}
public Declaration(Object name, Type type2) {
int i = counter + 1;
counter = i;
this.id = i;
this.value = QuoteExp.undefined_exp;
this.flags = 64;
this.makeLocationMethod = null;
setName(name);
setType(type2);
}
public Declaration(Object name, Field field2) {
this(name, field2.getType());
this.field = field2;
setSimple(false);
}
public void pushIndirectBinding(Compilation comp) {
CodeAttr code = comp.getCode();
code.emitPushString(getName());
if (this.makeLocationMethod == null) {
this.makeLocationMethod = Compilation.typeLocation.addMethod("make", new Type[]{Type.pointer_type, Type.string_type}, (Type) Compilation.typeLocation, 9);
}
code.emitInvokeStatic(this.makeLocationMethod);
}
public final Variable allocateVariable(CodeAttr code) {
if (!isSimple() || this.var == null) {
String vname = null;
if (this.symbol != null) {
vname = Compilation.mangleNameIfNeeded(getName());
}
if (!isAlias() || !(getValue() instanceof ReferenceExp)) {
this.var = this.context.getVarScope().addVariable(code, isIndirectBinding() ? Compilation.typeLocation : getType().getImplementationType(), vname);
} else {
Declaration base2 = followAliases(this);
this.var = base2 == null ? null : base2.var;
}
}
return this.var;
}
public final void setLocation(SourceLocator location) {
this.filename = location.getFileName();
setLine(location.getLineNumber(), location.getColumnNumber());
}
public final void setFile(String filename2) {
this.filename = filename2;
}
public final void setLine(int lineno, int colno) {
if (lineno < 0) {
lineno = 0;
}
if (colno < 0) {
colno = 0;
}
this.position = (lineno << 12) + colno;
}
public final void setLine(int lineno) {
setLine(lineno, 0);
}
public final String getFileName() {
return this.filename;
}
public String getPublicId() {
return null;
}
public String getSystemId() {
return this.filename;
}
public final int getLineNumber() {
int line = this.position >> 12;
if (line == 0) {
return -1;
}
return line;
}
public final int getColumnNumber() {
int column = this.position & 4095;
if (column == 0) {
return -1;
}
return column;
}
public boolean isStableSourceLocation() {
return true;
}
public void printInfo(OutPort out) {
StringBuffer sbuf = new StringBuffer();
printInfo(sbuf);
out.print(sbuf.toString());
}
public void printInfo(StringBuffer sbuf) {
sbuf.append(this.symbol);
sbuf.append('/');
sbuf.append(this.id);
sbuf.append("/fl:");
sbuf.append(Long.toHexString(this.flags));
if (ignorable()) {
sbuf.append("(ignorable)");
}
Expression tx = this.typeExp;
Type t = getType();
if (tx != null && !(tx instanceof QuoteExp)) {
sbuf.append("::");
sbuf.append(tx);
} else if (!(this.type == null || t == Type.pointer_type)) {
sbuf.append("::");
sbuf.append(t.getName());
}
if (this.base != null) {
sbuf.append("(base:#");
sbuf.append(this.base.id);
sbuf.append(')');
}
}
public String toString() {
return "Declaration[" + this.symbol + '/' + this.id + ']';
}
public static Declaration followAliases(Declaration decl) {
while (decl != null && decl.isAlias()) {
Expression declValue = decl.getValue();
if (declValue instanceof ReferenceExp) {
Declaration orig = ((ReferenceExp) declValue).binding;
if (orig == null) {
break;
}
decl = orig;
} else {
break;
}
}
return decl;
}
public void makeField(Compilation comp, Expression value2) {
setSimple(false);
makeField(comp.mainClass, comp, value2);
}
public void makeField(ClassType frameType, Compilation comp, Expression value2) {
String fname;
int nlength;
boolean external_access = needsExternalAccess();
int fflags = 0;
boolean isConstant = getFlag(16384);
boolean typeSpecified = getFlag(8192);
if (comp.immediate && (this.context instanceof ModuleExp) && !isConstant && !typeSpecified) {
setIndirectBinding(true);
}
if (isPublic() || external_access || comp.immediate) {
fflags = 0 | 1;
}
if (isStatic() || ((getFlag(268501008) && isIndirectBinding() && !isAlias()) || ((value2 instanceof ClassExp) && !((LambdaExp) value2).getNeedsClosureEnv()))) {
fflags |= 8;
}
if ((isIndirectBinding() || (isConstant && (shouldEarlyInit() || ((this.context instanceof ModuleExp) && ((ModuleExp) this.context).staticInitRun())))) && ((this.context instanceof ClassExp) || (this.context instanceof ModuleExp))) {
fflags |= 16;
}
Type ftype = getType().getImplementationType();
if (isIndirectBinding() && !ftype.isSubtype(Compilation.typeLocation)) {
ftype = Compilation.typeLocation;
}
if (!ignorable()) {
String fname2 = getName();
if (fname2 == null) {
fname = "$unnamed$0";
nlength = fname.length() - 2;
} else {
fname = Compilation.mangleNameIfNeeded(fname2);
if (getFlag(65536)) {
fname = UNKNOWN_PREFIX + fname;
}
if (external_access && !getFlag(1073741824)) {
fname = PRIVATE_PREFIX + fname;
}
nlength = fname.length();
}
int counter2 = 0;
while (frameType.getDeclaredField(fname) != null) {
counter2++;
fname = fname.substring(0, nlength) + '$' + counter2;
}
this.field = frameType.addField(fname, ftype, fflags);
if (value2 instanceof QuoteExp) {
Object val = ((QuoteExp) value2).getValue();
if (this.field.getStaticFlag() && val.getClass().getName().equals(ftype.getName())) {
Literal literal = comp.litTable.findLiteral(val);
if (literal.field == null) {
literal.assign(this.field, comp.litTable);
}
} else if ((ftype instanceof PrimType) || "java.lang.String".equals(ftype.getName())) {
if (val instanceof Char) {
val = IntNum.make(((Char) val).intValue());
}
this.field.setConstantValue(val, frameType);
return;
}
}
}
if (shouldEarlyInit()) {
return;
}
if (isIndirectBinding() || (value2 != null && !(value2 instanceof ClassExp))) {
BindingInitializer.create(this, value2, comp);
}
}
/* access modifiers changed from: 0000 */
public Location makeIndirectLocationFor() {
return Location.make(this.symbol instanceof Symbol ? (Symbol) this.symbol : Namespace.EmptyNamespace.getSymbol(this.symbol.toString().intern()));
}
public static Declaration getDeclarationFromStatic(String cname, String fname) {
Declaration decl = new Declaration((Object) fname, ClassType.make(cname).getDeclaredField(fname));
decl.setFlag(18432);
return decl;
}
public static Declaration getDeclarationValueFromStatic(String className, String fieldName, String name) {
try {
Object value2 = Class.forName(className).getDeclaredField(fieldName).get(null);
Declaration decl = new Declaration((Object) name, ClassType.make(className).getDeclaredField(fieldName));
decl.noteValue(new QuoteExp(value2));
decl.setFlag(18432);
return decl;
} catch (Exception ex) {
throw new WrappedException((Throwable) ex);
}
}
public static Declaration getDeclaration(Named proc) {
return getDeclaration(proc, proc.getName());
}
public static Declaration getDeclaration(Object proc, String name) {
Field procField = null;
if (name != null) {
Class procClass = PrimProcedure.getProcedureClass(proc);
if (procClass != null) {
procField = ((ClassType) Type.make(procClass)).getDeclaredField(Compilation.mangleNameIfNeeded(name));
}
}
if (procField != null) {
int fflags = procField.getModifiers();
if ((fflags & 8) != 0) {
Declaration decl = new Declaration((Object) name, procField);
decl.noteValue(new QuoteExp(proc));
if ((fflags & 16) == 0) {
return decl;
}
decl.setFlag(16384);
return decl;
}
}
return null;
}
}
| 35.059459 | 241 | 0.529356 |
9bb5c28b7c1ed4a51876f02cedc3e9e2c8a14d2e | 172 | package com.application.app.recipe.comment;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class RecipeCommentRequest {
private String comment;
}
| 15.636364 | 43 | 0.790698 |
36959b3546da903a72ee055b8bf0aa26084fdd39 | 388 | package com.ztgm.iot.dao;
import com.ztgm.iot.pojo.UserSceneLog;
public interface UserSceneLogMapper {
int deleteByPrimaryKey(String id);
int insert(UserSceneLog record);
int insertSelective(UserSceneLog record);
UserSceneLog selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(UserSceneLog record);
int updateByPrimaryKey(UserSceneLog record);
} | 22.823529 | 57 | 0.778351 |
81630ec224caf328e0e262b6003b3b8a295906b5 | 7,929 | /*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.reil.translators.arm;
import com.google.security.zynamics.reil.OperandSize;
import com.google.security.zynamics.reil.ReilHelpers;
import com.google.security.zynamics.reil.ReilInstruction;
import com.google.security.zynamics.reil.translators.ITranslationEnvironment;
import com.google.security.zynamics.reil.translators.InternalTranslationException;
import com.google.security.zynamics.reil.translators.TranslationHelpers;
import com.google.security.zynamics.zylib.disassembly.IInstruction;
import com.google.security.zynamics.zylib.disassembly.IOperandTreeNode;
import java.util.List;
public class ARMSelTranslator extends ARMBaseTranslator {
@Override
protected final void translateCore(final ITranslationEnvironment environment,
final IInstruction instruction, final List<ReilInstruction> instructions) {
final IOperandTreeNode registerOperand1 =
instruction.getOperands().get(0).getRootNode().getChildren().get(0);
final IOperandTreeNode registerOperand2 =
instruction.getOperands().get(1).getRootNode().getChildren().get(0);
final IOperandTreeNode registerOperand3 =
instruction.getOperands().get(2).getRootNode().getChildren().get(0);
final String targetRegister = (registerOperand1.getValue());
final String sourceRegister1 = (registerOperand2.getValue());
final String sourceRegister2 = (registerOperand3.getValue());
final OperandSize byteSize = OperandSize.BYTE;
final OperandSize dWordSize = OperandSize.DWORD;
final long baseOffset = (instruction.getAddress().toLong() * 0x100) + instructions.size();
new Processor() {
@Override
protected String[] process(final long offset, final String[] firstFour,
final String[] secondFour) {
final String firstFourMaskFour = environment.getNextVariableString();
final String firstFourMaskOne = environment.getNextVariableString();
final String firstFourMaskThree = environment.getNextVariableString();
final String firstFourMaskTwo = environment.getNextVariableString();
final String secondFourMaskFour = environment.getNextVariableString();
final String secondFourMaskOne = environment.getNextVariableString();
final String secondFourMaskThree = environment.getNextVariableString();
final String secondFourMaskTwo = environment.getNextVariableString();
final String tmpResult1 = environment.getNextVariableString();
final String tmpResult2 = environment.getNextVariableString();
final String tmpResult3 = environment.getNextVariableString();
final String tmpResult4 = environment.getNextVariableString();
final String tmpVal1 = environment.getNextVariableString();
final String tmpVal2 = environment.getNextVariableString();
final String tmpVal3 = environment.getNextVariableString();
final String tmpVal4 = environment.getNextVariableString();
final String tmpVal5 = environment.getNextVariableString();
final String tmpVal6 = environment.getNextVariableString();
final String tmpVal7 = environment.getNextVariableString();
final String tmpVal8 = environment.getNextVariableString();
long baseOffset = offset;
// Generate masks
instructions.add(ReilHelpers.createSub(baseOffset++, dWordSize, String.valueOf(0),
byteSize, "CPSR_GE_0", dWordSize, firstFourMaskOne));
instructions.add(ReilHelpers.createXor(baseOffset++, dWordSize, firstFourMaskOne,
dWordSize, String.valueOf(0xFFFFFFFFL), dWordSize, secondFourMaskOne));
instructions.add(ReilHelpers.createSub(baseOffset++, dWordSize, String.valueOf(0),
byteSize, "CPSR_GE_1", dWordSize, firstFourMaskTwo));
instructions.add(ReilHelpers.createXor(baseOffset++, dWordSize, firstFourMaskTwo,
dWordSize, String.valueOf(0xFFFFFFFFL), dWordSize, secondFourMaskTwo));
instructions.add(ReilHelpers.createSub(baseOffset++, dWordSize, String.valueOf(0),
byteSize, "CPSR_GE_2", dWordSize, firstFourMaskThree));
instructions.add(ReilHelpers.createXor(baseOffset++, dWordSize, firstFourMaskThree,
dWordSize, String.valueOf(0xFFFFFFFFL), dWordSize, secondFourMaskThree));
instructions.add(ReilHelpers.createSub(baseOffset++, dWordSize, String.valueOf(0),
byteSize, "CPSR_GE_3", dWordSize, firstFourMaskFour));
instructions.add(ReilHelpers.createXor(baseOffset++, dWordSize, firstFourMaskFour,
dWordSize, String.valueOf(0xFFFFFFFFL), dWordSize, secondFourMaskFour));
// apply masks
instructions.add(ReilHelpers.createAnd(baseOffset++, dWordSize, firstFour[0], dWordSize,
firstFourMaskOne, dWordSize, tmpVal1));
instructions.add(ReilHelpers.createAnd(baseOffset++, dWordSize, secondFour[0], dWordSize,
secondFourMaskOne, dWordSize, tmpVal2));
instructions.add(ReilHelpers.createAnd(baseOffset++, dWordSize, firstFour[1], dWordSize,
firstFourMaskOne, dWordSize, tmpVal3));
instructions.add(ReilHelpers.createAnd(baseOffset++, dWordSize, secondFour[1], dWordSize,
secondFourMaskOne, dWordSize, tmpVal4));
instructions.add(ReilHelpers.createAnd(baseOffset++, dWordSize, firstFour[2], dWordSize,
firstFourMaskOne, dWordSize, tmpVal5));
instructions.add(ReilHelpers.createAnd(baseOffset++, dWordSize, secondFour[2], dWordSize,
secondFourMaskOne, dWordSize, tmpVal6));
instructions.add(ReilHelpers.createAnd(baseOffset++, dWordSize, firstFour[2], dWordSize,
firstFourMaskOne, dWordSize, tmpVal7));
instructions.add(ReilHelpers.createAnd(baseOffset++, dWordSize, secondFour[2], dWordSize,
secondFourMaskOne, dWordSize, tmpVal8));
// get results
instructions.add(ReilHelpers.createOr(baseOffset++, dWordSize, tmpVal1, dWordSize, tmpVal2,
dWordSize, tmpResult1));
instructions.add(ReilHelpers.createOr(baseOffset++, dWordSize, tmpVal3, dWordSize, tmpVal4,
dWordSize, tmpResult2));
instructions.add(ReilHelpers.createOr(baseOffset++, dWordSize, tmpVal5, dWordSize, tmpVal6,
dWordSize, tmpResult3));
instructions.add(ReilHelpers.createOr(baseOffset++, dWordSize, tmpVal7, dWordSize, tmpVal8,
dWordSize, tmpResult4));
return new String[] {tmpResult1, tmpResult2, tmpResult3, tmpResult4};
}
}.generate(environment, baseOffset, 8, sourceRegister1, sourceRegister2, targetRegister,
instructions);
}
/**
* SEL{<cond>} <Rd>, <Rn>, <Rm>
*
* Operation:
*
* if ConditionPassed(cond) then Rd[7:0] = if GE[0] == 1 then Rn[7:0] else Rm[7:0] Rd[15:8] = if
* GE[1] == 1 then Rn[15:8] else Rm[15:8] Rd[23:16] = if GE[2] == 1 then Rn[23:16] else Rm[23:16]
* Rd[31:24] = if GE[3] == 1 then Rn[31:24] else Rm[31:24]
*/
@Override
public final void translate(final ITranslationEnvironment environment,
final IInstruction instruction, final List<ReilInstruction> instructions)
throws InternalTranslationException {
TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, "SEL");
translateAll(environment, instruction, "SEL", instructions);
}
}
| 52.86 | 99 | 0.730609 |
050fbf580012c490879d81d6341281c82d553f88 | 3,192 | package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.Valid;
/**
* BQFXConversionRetrieveOutputModelFXConversionInstanceAnalysis
*/
public class BQFXConversionRetrieveOutputModelFXConversionInstanceAnalysis {
private Object fXConversionInstanceAnalysisRecord = null;
private String fXConversionInstanceAnalysisReportType = null;
private String fXConversionInstanceAnalysisParameters = null;
private Object fXConversionInstanceAnalysisReport = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The inputs and results of the instance analysis that can be on-going, periodic and actual and projected
* @return fXConversionInstanceAnalysisRecord
**/
@JsonProperty("fXConversionInstanceAnalysisRecord")
public Object getFXConversionInstanceAnalysisRecord() {
return fXConversionInstanceAnalysisRecord;
}
public void setFXConversionInstanceAnalysisRecord(Object fXConversionInstanceAnalysisRecord) {
this.fXConversionInstanceAnalysisRecord = fXConversionInstanceAnalysisRecord;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Code general-info: The type of external performance analysis report available
* @return fXConversionInstanceAnalysisReportType
**/
@JsonProperty("fXConversionInstanceAnalysisReportType")
public String getFXConversionInstanceAnalysisReportType() {
return fXConversionInstanceAnalysisReportType;
}
public void setFXConversionInstanceAnalysisReportType(String fXConversionInstanceAnalysisReportType) {
this.fXConversionInstanceAnalysisReportType = fXConversionInstanceAnalysisReportType;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The selection parameters for the analysis (e.g. period, algorithm type)
* @return fXConversionInstanceAnalysisParameters
**/
@JsonProperty("fXConversionInstanceAnalysisParameters")
public String getFXConversionInstanceAnalysisParameters() {
return fXConversionInstanceAnalysisParameters;
}
public void setFXConversionInstanceAnalysisParameters(String fXConversionInstanceAnalysisParameters) {
this.fXConversionInstanceAnalysisParameters = fXConversionInstanceAnalysisParameters;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The external analysis report in any suitable form including selection filters where appropriate
* @return fXConversionInstanceAnalysisReport
**/
@JsonProperty("fXConversionInstanceAnalysisReport")
public Object getFXConversionInstanceAnalysisReport() {
return fXConversionInstanceAnalysisReport;
}
public void setFXConversionInstanceAnalysisReport(Object fXConversionInstanceAnalysisReport) {
this.fXConversionInstanceAnalysisReport = fXConversionInstanceAnalysisReport;
}
}
| 37.552941 | 228 | 0.816103 |
8d6b771696d962baddbcc096a729ff8e931e90c9 | 385 | package carpet.fakes;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
public interface RedstoneWireBlockInterface {
BlockState updateLogicPublic(Level world_1, BlockPos blockPos_1, BlockState blockState_1);
void setWiresGivePower(boolean wiresGivePower);
boolean getWiresGivePower();
}
| 32.083333 | 94 | 0.818182 |
dbe9670b3501c49df2352391e66d785eab066478 | 2,822 | /*
* MIT License
*
* Copyright (c) 2018 g4s8
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.g4s8.teletakes.fk;
import com.g4s8.teletakes.refl.ReflField;
import com.g4s8.teletakes.tk.TkEmpty;
import java.io.IOException;
import java.util.Collections;
import java.util.Optional;
import java.util.regex.Pattern;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.telegram.telegrambots.api.objects.EntityType;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.MessageEntity;
import org.telegram.telegrambots.api.objects.Update;
/**
* Test case for {@link FkCommand}.
*
* @since 1.0
* @checkstyle JavadocMethodCheck (500 lines)
*/
public final class FkCommandTest {
@Test
@DisplayName("FkCommand can match by patetrn")
public void matchByPattern() throws Exception {
MatcherAssert.assertThat(
new FkCommand(
Pattern.compile("^foo\\s\\d+"),
new TkEmpty()
).route(command("foo 42")),
Matchers.not(Matchers.equalTo(Optional.empty()))
);
}
private static Update command(final String command) throws IOException {
final Message message = new Message();
new ReflField(message, "text").write(command);
final MessageEntity entity = new MessageEntity();
new ReflField(entity, "offset").write(0);
new ReflField(entity, "type").write(EntityType.BOTCOMMAND);
new ReflField(message, "entities")
.write(Collections.singletonList(entity));
final Update update = new Update();
new ReflField(update, "message").write(message);
return update;
}
}
| 38.135135 | 80 | 0.717931 |
6da8633c4e2bdf06102b016dff5603255f1690e1 | 115,756 | package org.hl7.fhir.definitions.generators.specification;
/*
Copyright (c) 2011+, HL7, Inc
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 HL7 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 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.
*/
import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hl7.fhir.definitions.model.BindingSpecification;
import org.hl7.fhir.definitions.model.BindingSpecification.BindingMethod;
import org.hl7.fhir.definitions.model.CommonSearchParameter;
import org.hl7.fhir.definitions.model.ConstraintStructure;
import org.hl7.fhir.definitions.model.DefinedStringPattern;
import org.hl7.fhir.definitions.model.Definitions;
import org.hl7.fhir.definitions.model.ElementDefn;
import org.hl7.fhir.definitions.model.ImplementationGuideDefn;
import org.hl7.fhir.definitions.model.Invariant;
import org.hl7.fhir.definitions.model.Operation;
import org.hl7.fhir.definitions.model.OperationParameter;
import org.hl7.fhir.definitions.model.PrimitiveType;
import org.hl7.fhir.definitions.model.Profile;
import org.hl7.fhir.definitions.model.ProfiledType;
import org.hl7.fhir.definitions.model.ResourceDefn;
import org.hl7.fhir.definitions.model.SearchParameterDefn;
import org.hl7.fhir.definitions.model.SearchParameterDefn.CompositeDefinition;
import org.hl7.fhir.definitions.model.SearchParameterDefn.SearchType;
import org.hl7.fhir.definitions.model.TypeDefn;
import org.hl7.fhir.definitions.model.W5Entry;
import org.hl7.fhir.definitions.model.WorkGroup;
import org.hl7.fhir.definitions.uml.UMLAttribute;
import org.hl7.fhir.definitions.uml.UMLClass;
import org.hl7.fhir.definitions.uml.UMLClass.UMLClassType;
import org.hl7.fhir.definitions.uml.UMLModel;
import org.hl7.fhir.definitions.uml.UMLPackage;
import org.hl7.fhir.definitions.uml.UMLPrimitive;
import org.hl7.fhir.definitions.validation.FHIRPathUsage;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.exceptions.FHIRFormatError;
import org.hl7.fhir.igtools.spreadsheets.TypeParser;
import org.hl7.fhir.igtools.spreadsheets.TypeRef;
import org.hl7.fhir.r5.conformance.ProfileUtilities;
import org.hl7.fhir.r5.conformance.ProfileUtilities.ProfileKnowledgeProvider;
import org.hl7.fhir.r5.formats.FormatUtilities;
import org.hl7.fhir.r5.model.BooleanType;
import org.hl7.fhir.r5.model.Bundle;
import org.hl7.fhir.r5.model.Bundle.BundleEntryComponent;
import org.hl7.fhir.r5.model.CanonicalType;
import org.hl7.fhir.r5.model.CodeType;
import org.hl7.fhir.r5.model.Constants;
import org.hl7.fhir.r5.model.ContactDetail;
import org.hl7.fhir.r5.model.ContactPoint;
import org.hl7.fhir.r5.model.ContactPoint.ContactPointSystem;
import org.hl7.fhir.r5.model.ElementDefinition;
import org.hl7.fhir.r5.model.ElementDefinition.AggregationMode;
import org.hl7.fhir.r5.model.ElementDefinition.ConstraintSeverity;
import org.hl7.fhir.r5.model.ElementDefinition.DiscriminatorType;
import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionBaseComponent;
import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionBindingComponent;
import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionConstraintComponent;
import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionMappingComponent;
import org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionSlicingComponent;
import org.hl7.fhir.r5.model.ElementDefinition.PropertyRepresentation;
import org.hl7.fhir.r5.model.ElementDefinition.SlicingRules;
import org.hl7.fhir.r5.model.ElementDefinition.TypeRefComponent;
import org.hl7.fhir.r5.model.Enumerations;
import org.hl7.fhir.r5.model.Enumerations.BindingStrength;
import org.hl7.fhir.r5.model.Enumerations.FHIRVersion;
import org.hl7.fhir.r5.model.Enumerations.OperationParameterUse;
import org.hl7.fhir.r5.model.Enumerations.PublicationStatus;
import org.hl7.fhir.r5.model.Enumerations.SearchParamType;
import org.hl7.fhir.r5.model.Extension;
import org.hl7.fhir.r5.model.Factory;
import org.hl7.fhir.r5.model.InstantType;
import org.hl7.fhir.r5.model.Integer64Type;
import org.hl7.fhir.r5.model.IntegerType;
import org.hl7.fhir.r5.model.MarkdownType;
import org.hl7.fhir.r5.model.Meta;
import org.hl7.fhir.r5.model.Narrative;
import org.hl7.fhir.r5.model.Narrative.NarrativeStatus;
import org.hl7.fhir.r5.model.OperationDefinition;
import org.hl7.fhir.r5.model.OperationDefinition.OperationDefinitionParameterBindingComponent;
import org.hl7.fhir.r5.model.OperationDefinition.OperationDefinitionParameterComponent;
import org.hl7.fhir.r5.model.OperationDefinition.OperationKind;
import org.hl7.fhir.r5.model.SearchParameter;
import org.hl7.fhir.r5.model.SearchParameter.SearchComparator;
import org.hl7.fhir.r5.model.StringType;
import org.hl7.fhir.r5.model.StructureDefinition;
import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionDifferentialComponent;
import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionKind;
import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionMappingComponent;
import org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionSnapshotComponent;
import org.hl7.fhir.r5.model.StructureDefinition.TypeDerivationRule;
import org.hl7.fhir.r5.model.UriType;
import org.hl7.fhir.r5.utils.NarrativeGenerator;
import org.hl7.fhir.r5.utils.ToolingExtensions;
import org.hl7.fhir.r5.utils.TypesUtilities;
import org.hl7.fhir.tools.converters.MarkDownPreProcessor;
import org.hl7.fhir.tools.publisher.BuildWorkerContext;
import org.hl7.fhir.utilities.IniFile;
import org.hl7.fhir.utilities.StandardsStatus;
import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.validation.ValidationMessage;
import org.hl7.fhir.utilities.validation.ValidationMessage.IssueSeverity;
import org.hl7.fhir.utilities.validation.ValidationMessage.IssueType;
import org.hl7.fhir.utilities.validation.ValidationMessage.Source;
import org.hl7.fhir.utilities.xhtml.NodeType;
import org.hl7.fhir.utilities.xhtml.XhtmlNode;
public class ProfileGenerator {
public enum SnapShotMode {
None,
Resource,
DataType
}
private BuildWorkerContext context;
private Definitions definitions;
private List<FHIRPathUsage> fpUsages;
// status
// note that once we start slicing, the slices keep their own maps, but all share the master pathname list
private final Map<String, ElementDefinition> paths = new HashMap<String, ElementDefinition>();
private final List<String> pathNames = new ArrayList<String>();
private ProfileKnowledgeProvider pkp;
private Calendar genDate;
private FHIRVersion version;
private Bundle dataElements;
private String rootFolder;
private UMLPackage uml;
private static class SliceHandle {
private String name;
private Map<String, ElementDefinition> paths = new HashMap<String, ElementDefinition>();
}
public ProfileGenerator(Definitions definitions, BuildWorkerContext context, ProfileKnowledgeProvider pkp, Calendar genDate, FHIRVersion version, Bundle dataElements, List<FHIRPathUsage> fpUsages, String rootFolder, UMLModel uml) throws FHIRException {
super();
this.definitions = definitions;
this.context = context;
this.pkp = pkp;
this.genDate = genDate;
this.version = version;
this.dataElements = dataElements;
this.fpUsages = fpUsages;
this.rootFolder = rootFolder;
if (dataElements != null) {
for (BundleEntryComponent be : dataElements.getEntry()) {
if (be.getResource() instanceof StructureDefinition)
des.put(be.getResource().getId(), (StructureDefinition) be.getResource());
}
}
if (uml != null) {
if (!uml.hasPackage("core")) {
this.uml = uml.getPackage("core");
this.uml.getTypes().put("PrimitiveType", new UMLClass("PrimitiveType", UMLClassType.Class));
} else {
this.uml = uml.getPackage("core");
}
}
}
private Map<String, StructureDefinition> des = new HashMap<String, StructureDefinition>();
private static int extensionCounter;
private static int profileCounter = 0;
private void generateElementDefinition(StructureDefinition source, ElementDefinition ed, ElementDefinition parent) throws Exception {
String id = ed.getPath().replace("[x]", "X");
if (id.length() > 64)
id = id.substring(0, 64);
if (!id.contains("."))
return; // throw new Exception("Don't generate data element for root of resources or types");
if (!ed.hasType())
return; // throw new Exception("Don't generate data element for reference elements");
if (Utilities.existsInList(ed.getType().get(0).getCode(), "Element", "BackboneElement"))
return; // throw new Exception("Don't generate data element for elements that are not leaves");
StructureDefinition de;
if (des.containsKey(id)) {
de = des.get("de-"+id);
// do it again because we now have more information to generate with
de.getSnapshot().getElement().clear();
de.getExtension().clear();
} else {
de = new StructureDefinition();
de.setId("de-"+id);
des.put(id, de);
de.setUrl("http://hl7.org/fhir/StructureDefinition/"+de.getId());
if (de.getId().contains("."))
definitions.addNs(de.getUrl(), "Data Element "+ed.getPath(), definitions.getSrcFile(id.substring(0, id.indexOf(".")))+"-definitions.html#"+id);
if (dataElements != null)
dataElements.addEntry().setResource(de).setFullUrl(de.getUrl());
}
if (!de.hasMeta())
de.setMeta(new Meta());
de.getMeta().setLastUpdatedElement(new InstantType(genDate));
de.setVersion(Constants.VERSION);
de.setName(ed.getPath());
de.setStatus(PublicationStatus.DRAFT);
de.setExperimental(true);
de.setTitle(de.getName());
de.setDate(genDate.getTime());
de.setPublisher("HL7 FHIR Standard");
de.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.URL, "http://hl7.org/fhir"));
de.setDescription("Data Element for "+ed.getPath());
de.setPurpose("Data Elements are defined for each element to assist in questionnaire construction etc");
de.setFhirVersion(version);
de.setKind(StructureDefinitionKind.LOGICAL);
de.setType("DataElement");
de.setAbstract(false);
de.setType(de.getName());
de.setBaseDefinition("http://hl7.org/fhir/StructureDefinition/Element");
de.setDerivation(TypeDerivationRule.SPECIALIZATION);
de.getMapping().addAll(source.getMapping());
ElementDefinition ted = ed.copy();
de.getSnapshot().addElement(ted);
ted.makeBase();
}
private String tail(String path) {
int i = path.lastIndexOf(".");
return i < 0 ? path : path.substring(i + 1);
}
public StructureDefinition generate(PrimitiveType type) throws Exception {
genUml(type);
StructureDefinition p = new StructureDefinition();
p.setId(type.getCode());
p.setUrl("http://hl7.org/fhir/StructureDefinition/"+ type.getCode());
p.setKind(StructureDefinitionKind.PRIMITIVETYPE);
p.setAbstract(false);
p.setUserData("filename", type.getCode().toLowerCase());
p.setUserData("path", "datatypes.html#"+type.getCode());
p.setBaseDefinition("http://hl7.org/fhir/StructureDefinition/PrimitiveType");
p.setType(type.getCode());
p.setDerivation(TypeDerivationRule.SPECIALIZATION);
p.setFhirVersion(version);
p.setVersion(version.toCode());
ToolingExtensions.setStandardsStatus(p, StandardsStatus.NORMATIVE, "4.0.0");
ToolResourceUtilities.updateUsage(p, "core");
p.setName(type.getCode());
p.setPublisher("HL7 FHIR Standard");
p.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.URL, "http://hl7.org/fhir"));
p.setDescription("Base StructureDefinition for "+type.getCode()+" Type: "+type.getDefinition());
p.setDate(genDate.getTime());
p.setStatus(PublicationStatus.fromCode("active")); // normative now
Set<String> containedSlices = new HashSet<String>();
// first, the differential
p.setDifferential(new StructureDefinitionDifferentialComponent());
ElementDefinition ec = new ElementDefinition();
p.getDifferential().getElement().add(ec);
ec.setId(type.getCode());
ec.setPath(type.getCode());
ec.setShort("Primitive Type " +type.getCode());
ec.setDefinition(type.getDefinition());
ec.setComment(type.getComment());
ec.setMin(0);
ec.setMax("*");
ec = new ElementDefinition();
p.getDifferential().getElement().add(ec);
ec.setId(type.getCode()+".value");
ec.setPath(type.getCode()+".value");
ec.addRepresentation(PropertyRepresentation.XMLATTR);
ec.setShort("Primitive value for " +type.getCode());
ec.setDefinition("Primitive value for " +type.getCode());
ec.setMin(0);
ec.setMax("1");
TypeRefComponent t = ec.addType();
t.getFormatCommentsPre().add("Note: special primitive values have a FHIRPath system type. e.g. this is compiler magic (a)");
t.setCode(Constants.NS_SYSTEM_TYPE+type.getFHIRPathType());
ToolingExtensions.addUriExtension(t, ToolingExtensions.EXT_FHIR_TYPE, type.getCode());
if (!Utilities.noString(type.getRegex())) {
ToolingExtensions.addStringExtension(t, ToolingExtensions.EXT_REGEX, type.getRegex());
}
addSpecificDetails(type, ec);
reset();
// now. the snapshot
p.setSnapshot(new StructureDefinitionSnapshotComponent());
ElementDefinition ec1 = new ElementDefinition(true, ElementDefinition.NOT_MODIFIER, ElementDefinition.NOT_IN_SUMMARY);
p.getSnapshot().getElement().add(ec1);
ec1.setId(type.getCode());
ec1.setPath(type.getCode());
ec1.setShort("Primitive Type " +type.getCode());
ec1.setDefinition(type.getDefinition());
ec1.setComment(type.getComment());
ec1.setMin(0);
ec1.setMax("*");
ec1.makeBase();
addElementConstraints("Element", ec1);
ElementDefinition ec2 = new ElementDefinition(true, ElementDefinition.NOT_MODIFIER, ElementDefinition.NOT_IN_SUMMARY);
p.getSnapshot().getElement().add(ec2);
ec2.setId(type.getCode()+".id");
ec2.setPath(type.getCode()+".id");
ec2.addRepresentation(PropertyRepresentation.XMLATTR);
ec2.setDefinition("unique id for the element within a resource (for internal references)");
ec2.setMin(0);
ec2.setMax("1");
ec2.setShort("xml:id (or equivalent in JSON)");
TypeRefComponent tr = ec2.addType();
t.getFormatCommentsPre().add("Note: special primitive values have a FHIRPath system type. e.g. this is compiler magic (b)");
tr.setCode(Constants.NS_SYSTEM_TYPE+ "String");
ToolingExtensions.addUriExtension(tr, ToolingExtensions.EXT_FHIR_TYPE, "string");
generateElementDefinition(p, ec2, ec1);
ec2.makeBase("Element.id", 0, "1");
makeExtensionSlice("extension", p, p.getSnapshot(), null, type.getCode());
ElementDefinition ec3 = new ElementDefinition(true, ElementDefinition.NOT_MODIFIER, ElementDefinition.NOT_IN_SUMMARY);
p.getSnapshot().getElement().add(ec3);
ec3.setId(type.getCode()+".value");
ec3.setPath(type.getCode()+".value");
ec3.addRepresentation(PropertyRepresentation.XMLATTR);
ec3.setDefinition("The actual value");
ec3.setMin(0);
ec3.setMax("1");
ec3.setShort("Primitive value for " +type.getCode());
ec3.makeBase();
t = ec3.addType();
t.setCodeElement(new UriType());
t.getFormatCommentsPre().add("Note: special primitive values have a FHIRPath system type. e.g. this is compiler magic (c)");
t.setCode(Constants.NS_SYSTEM_TYPE+type.getFHIRPathType());
ToolingExtensions.addUriExtension(t, ToolingExtensions.EXT_FHIR_TYPE, type.getCode());
if (!Utilities.noString(type.getRegex()))
ToolingExtensions.addStringExtension(t, ToolingExtensions.EXT_REGEX, type.getRegex());
addSpecificDetails(type, ec3);
generateElementDefinition(p, ec3, ec);
containedSlices.clear();
addElementConstraintToSnapshot(p);
XhtmlNode div = new XhtmlNode(NodeType.Element, "div");
div.addText("to do");
p.setText(new Narrative());
p.getText().setStatus(NarrativeStatus.GENERATED);
p.getText().setDiv(div);
checkHasTypes(p);
return p;
}
public void genUml(PrimitiveType type) {
UMLClass c = uml.getClassByNameCreate(type.getCode());
c.setDocumentation(type.getDefinition());
c.setSpecialises(uml.getClassByName("PrimitiveType"));
String t = type.getSchemaType();
if (!t.startsWith("xs:"))
t = "xs:"+t;
if (!uml.hasPrimitive(t)) {
UMLPrimitive p = new UMLPrimitive(t);
uml.getTypes().put(t, p);
}
c.getAttributes().add(new UMLAttribute("value", "0", "1", uml.getTypes().get(t)));
}
public void genUml(DefinedStringPattern type) {
UMLClass c = uml.getClassByNameCreate(type.getCode());
c.setDocumentation(type.getDefinition());
c.setSpecialises(uml.getClassByNameCreate(type.getBase()));
}
public class ElementDefinitionConstraintSorter implements Comparator<ElementDefinitionConstraintComponent> {
@Override
public int compare(ElementDefinitionConstraintComponent arg0, ElementDefinitionConstraintComponent arg1) {
String k0 = arg0.getKey();
String k1 = arg1.getKey();
if (k0.contains("-") && k1.contains("-")) {
String p0 = k0.substring(0, k0.indexOf("-"));
String i0 = k0.substring(k0.indexOf("-")+1);
String p1 = k1.substring(0, k1.indexOf("-"));
String i1 = k1.substring(k1.indexOf("-")+1);
if (Utilities.isInteger(i0) && Utilities.isInteger(i1) && p0.equals(p1)) {
return Integer.compare(Integer.parseInt(i0), Integer.parseInt(i1));
}
}
return k0.compareTo(k1);
}
}
private void addElementConstraintToSnapshot(StructureDefinition sd) {
for (ElementDefinition ed : sd.getSnapshot().getElement())
addElementConstraint(sd, ed);
for (ElementDefinition ed : sd.getSnapshot().getElement())
addExtensionConstraint(sd, ed);
// to help with unit tests..
ElementDefinitionConstraintSorter edcs = new ElementDefinitionConstraintSorter();
for (ElementDefinition ed : sd.getSnapshot().getElement()) {
Collections.sort(ed.getConstraint(), edcs);
}
}
private boolean hasSystemType(ElementDefinition ed) {
for (TypeRefComponent t : ed.getType()) {
if (t.hasCode() && t.getCode().startsWith("http://hl7.org/fhirpath/System."))
return true;
}
return false;
}
private void addElementConstraints(String name, ElementDefinition ed) throws Exception {
if (definitions.hasPrimitiveType(name) || name.equals("Type") || name.equals("Logical"))
addElementConstraints("Element", ed);
else if (name.equals("Structure"))
addElementConstraints("BackboneElement", ed);
else {
ElementDefn element = definitions.getElementDefn(name);
if (!Utilities.noString(element.typeCode()))
addElementConstraints(element.typeCode(), ed);
convertConstraints(element, ed, name);
}
}
private void addSpecificDetails(PrimitiveType type, ElementDefinition ed) throws FHIRFormatError {
if (type.getCode().equals("integer")) {
ed.setMinValue(new IntegerType(-2147483648));
ed.setMaxValue(new IntegerType(2147483647));
}
if (type.getCode().equals("integer64")) {
ed.setMinValue(new Integer64Type(-9223372036854775808L));
ed.setMaxValue(new Integer64Type(9223372036854775807L));
}
if (type.getCode().equals("string")) {
ed.setMaxLength(1024 * 1024);
}
}
public StructureDefinition generateXhtml() throws Exception {
uml.getTypes().put("html:div", new UMLPrimitive("html:div"));
StructureDefinition p = new StructureDefinition();
p.setId("xhtml");
p.setUrl("http://hl7.org/fhir/StructureDefinition/xhtml");
p.setKind(StructureDefinitionKind.PRIMITIVETYPE);
p.setAbstract(false);
p.setUserData("filename", "xhtml");
p.setUserData("path", "narrative.html#xhtml");
p.setBaseDefinition("http://hl7.org/fhir/StructureDefinition/Element");
p.setType("xhtml");
p.setDerivation(TypeDerivationRule.SPECIALIZATION);
p.setFhirVersion(version);
p.setVersion(version.toCode());
ToolingExtensions.setStandardsStatus(p, StandardsStatus.NORMATIVE, "4.0.0");
ToolResourceUtilities.updateUsage(p, "core");
p.setName("xhtml");
p.setPublisher("HL7 FHIR Standard");
p.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.URL, "http://hl7.org/fhir"));
p.setDescription("Base StructureDefinition for xhtml Type");
p.setDate(genDate.getTime());
p.setStatus(PublicationStatus.fromCode("active"));
Set<String> containedSlices = new HashSet<String>();
// first, the differential
p.setDifferential(new StructureDefinitionDifferentialComponent());
ElementDefinition ec = new ElementDefinition();
p.getDifferential().getElement().add(ec);
ec.setId("xhtml");
ec.setPath("xhtml");
ec.setShort("Primitive Type " +"xhtml");
ec.setDefinition("XHTML");
ec.setMin(0);
ec.setMax("*");
ec = new ElementDefinition();
p.getDifferential().getElement().add(ec);
ec.setId("xhtml"+".extension");
ec.setPath("xhtml"+".extension");
ec.setMax("0");
ec = new ElementDefinition();
p.getDifferential().getElement().add(ec);
ec.setId("xhtml"+".value");
ec.setPath("xhtml"+".value");
ec.addRepresentation(PropertyRepresentation.XHTML);
ec.setShort("Actual xhtml");
ec.setDefinition("Actual xhtml");
ec.setMin(1);
ec.setMax("1");
TypeRefComponent t = ec.addType();
t.setCodeElement(new UriType());
t.getFormatCommentsPre().add("Note: special primitive values have a FHIRPath system type. e.g. this is compiler magic (d)");
t.setCode(Constants.NS_SYSTEM_TYPE+"String");
ToolingExtensions.addUriExtension(t, ToolingExtensions.EXT_FHIR_TYPE, "string");
reset();
// now. the snapshot
p.setSnapshot(new StructureDefinitionSnapshotComponent());
ElementDefinition ec1 = new ElementDefinition(true, ElementDefinition.NOT_MODIFIER, ElementDefinition.NOT_IN_SUMMARY);
p.getSnapshot().getElement().add(ec1);
ec1.setId("xhtml");
ec1.setPath("xhtml");
ec1.setShort("Primitive Type " +"xhtml");
ec1.setDefinition("XHTML");
ec1.setMin(0);
ec1.setMin(0);
ec1.setMax("*");
ec1.makeBase();
generateElementDefinition(p, ec1, null);
ElementDefinition ec2 = new ElementDefinition(true, ElementDefinition.NOT_MODIFIER, ElementDefinition.NOT_IN_SUMMARY);
p.getSnapshot().getElement().add(ec2);
ec2.setId("xhtml.id");
ec2.setPath("xhtml.id");
ec2.addRepresentation(PropertyRepresentation.XMLATTR);
ec2.setDefinition("unique id for the element within a resource (for internal references)");
ec2.setMin(0);
ec2.setMax("1");
ec2.setShort("xml:id (or equivalent in JSON)");
TypeRefComponent tr = ec2.addType();
t.getFormatCommentsPre().add("Note: special primitive values have a FHIRPath system type. e.g. this is compiler magic (e)");
tr.setCode(Constants.NS_SYSTEM_TYPE+ "String");
ToolingExtensions.addUriExtension(t, ToolingExtensions.EXT_FHIR_TYPE, "string");
generateElementDefinition(p, ec2, ec1);
ec2.makeBase("Element.id", 0, "1");
ElementDefinition ex = makeExtensionSlice("extension", p, p.getSnapshot(), null, "xhtml");
ex.setMax("0");
ElementDefinition ec3 = new ElementDefinition(true, ElementDefinition.NOT_MODIFIER, ElementDefinition.NOT_IN_SUMMARY);
p.getSnapshot().getElement().add(ec3);
ec3.setId("xhtml.value");
ec3.setPath("xhtml.value");
ec3.addRepresentation(PropertyRepresentation.XHTML);
ec3.setShort("Actual xhtml");
ec3.setDefinition("Actual xhtml");
ec3.setMin(1);
ec3.setMax("1");
t = ec3.addType();
t.setCodeElement(new UriType());
t.getFormatCommentsPre().add("Note: special primitive values have a FHIRPath system type. e.g. this is compiler magic (f)");
t.setCode(Constants.NS_SYSTEM_TYPE+"String");
ToolingExtensions.addUriExtension(t, ToolingExtensions.EXT_FHIR_TYPE, "string");
ec3.makeBase();
generateElementDefinition(p, ec3, ec);
containedSlices.clear();
addElementConstraintToSnapshot(p);
XhtmlNode div = new XhtmlNode(NodeType.Element, "div");
div.addText("to do");
p.setText(new Narrative());
p.getText().setStatus(NarrativeStatus.GENERATED);
p.getText().setDiv(div);
checkHasTypes(p);
return p;
}
private String prefix(String prefix, String value) {
if (value == null)
return prefix;
if (value.startsWith(prefix))
return value;
return prefix + value;
}
public StructureDefinition generate(DefinedStringPattern type) throws Exception {
genUml(type);
StructureDefinition p = new StructureDefinition();
p.setId(type.getCode());
p.setUrl("http://hl7.org/fhir/StructureDefinition/"+ type.getCode());
p.setBaseDefinition("http://hl7.org/fhir/StructureDefinition/"+ type.getBase());
p.setType(type.getCode());
p.setDerivation(TypeDerivationRule.SPECIALIZATION);
p.setKind(StructureDefinitionKind.PRIMITIVETYPE);
p.setAbstract(false);
p.setUserData("filename", type.getCode().toLowerCase());
p.setUserData("path", "datatypes.html#"+type.getCode());
p.setFhirVersion(version);
p.setVersion(version.toCode());
ToolingExtensions.setStandardsStatus(p, StandardsStatus.NORMATIVE, "4.0.0");
ToolResourceUtilities.updateUsage(p, "core");
p.setName(type.getCode());
p.setPublisher("HL7 FHIR Standard");
p.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.URL, "http://hl7.org/fhir"));
p.setDescription("Base StructureDefinition for "+type.getCode()+" type: "+type.getDefinition());
p.setDate(genDate.getTime());
p.setStatus(PublicationStatus.fromCode("active"));
Set<String> containedSlices = new HashSet<String>();
// first, the differential
p.setDifferential(new StructureDefinitionDifferentialComponent());
ElementDefinition ec1 = new ElementDefinition();
p.getDifferential().getElement().add(ec1);
ec1.setId(type.getCode());
ec1.setPath(type.getCode());
ec1.setShort("Primitive Type " +type.getCode());
ec1.setDefinition(type.getDefinition());
ec1.setComment(type.getComment());
ec1.setMin(0);
ec1.setMax("*");
ElementDefinition ec2 = new ElementDefinition();
p.getDifferential().getElement().add(ec2);
ec2.setId(type.getCode()+".value");
ec2.setPath(type.getCode()+".value");
ec2.addRepresentation(PropertyRepresentation.XMLATTR);
ec2.setShort("Primitive value for " +type.getCode());
ec2.setDefinition("Primitive value for " +type.getCode());
ec2.setMin(0);
ec2.setMax("1");
TypeRefComponent t = ec2.addType();
t.setCodeElement(new UriType());
t.getFormatCommentsPre().add("Note: special primitive values have a FHIRPath system type. e.g. this is compiler magic (g)");
t.setCode(Constants.NS_SYSTEM_TYPE+type.getFHIRPathType());
ToolingExtensions.addUriExtension(t, ToolingExtensions.EXT_FHIR_TYPE, type.getCode());
if (!Utilities.noString(type.getRegex())) {
ToolingExtensions.addStringExtension(t, ToolingExtensions.EXT_REGEX, type.getRegex());
}
reset();
// now. the snapshot
p.setSnapshot(new StructureDefinitionSnapshotComponent());
ElementDefinition ecA = new ElementDefinition(true, ElementDefinition.NOT_MODIFIER, ElementDefinition.NOT_IN_SUMMARY);
p.getSnapshot().getElement().add(ecA);
ecA.setId(type.getCode());
ecA.setPath(type.getCode());
ecA.setShort("Primitive Type " +type.getCode());
ecA.setDefinition(type.getDefinition());
ecA.setComment(type.getComment());
ecA.setMin(0);
ecA.setMax("*");
ecA.makeBase(type.getCode(), 0, "*");
addElementConstraints("Element", ecA);
ElementDefinition ecid = new ElementDefinition(true, ElementDefinition.NOT_MODIFIER, ElementDefinition.NOT_IN_SUMMARY);
p.getSnapshot().getElement().add(ecid);
ecid.setId(type.getCode()+".id");
ecid.setPath(type.getCode()+".id");
ecid.addRepresentation(PropertyRepresentation.XMLATTR);
ecid.setDefinition("unique id for the element within a resource (for internal references)");
ecid.setMin(0);
ecid.setMax("1");
ecid.setShort("xml:id (or equivalent in JSON)");
TypeRefComponent tr = ecid.addType();
tr.getFormatCommentsPre().add("Note: special primitive values have a FHIRPath system type. e.g. this is compiler magic (h)");
tr.setCode(Constants.NS_SYSTEM_TYPE+ "String");
ToolingExtensions.addUriExtension(tr, ToolingExtensions.EXT_FHIR_TYPE, "string");
ecid.makeBase("Element.id", 0, "1");
makeExtensionSlice("extension", p, p.getSnapshot(), null, type.getCode());
ElementDefinition ecB = new ElementDefinition(true, ElementDefinition.NOT_MODIFIER, ElementDefinition.NOT_IN_SUMMARY);
p.getSnapshot().getElement().add(ecB);
ecB.setPath(type.getCode()+".value");
ecB.setId(type.getCode()+".value");
ecB.addRepresentation(PropertyRepresentation.XMLATTR);
ecB.setDefinition("Primitive value for " +type.getCode());
ecB.setShort("Primitive value for " +type.getCode());
ecB.setMin(0);
ecB.setMax("1");
ecB.makeBase(type.getBase()+".value", 0, "1");
t = ecB.addType();
t.getFormatCommentsPre().add("Note: special primitive values have a FHIRPath system type. e.g. this is compiler magic (i)");
t.setCode(Constants.NS_SYSTEM_TYPE+"String");
ToolingExtensions.addUriExtension(t, ToolingExtensions.EXT_FHIR_TYPE, "string");
if (!Utilities.noString(type.getRegex()))
ToolingExtensions.addStringExtension(t, ToolingExtensions.EXT_REGEX, type.getRegex());
// generateElementDefinition(ecB, ecA);
containedSlices.clear();
addElementConstraintToSnapshot(p);
XhtmlNode div = new XhtmlNode(NodeType.Element, "div");
div.addText("to do");
p.setText(new Narrative());
p.getText().setStatus(NarrativeStatus.GENERATED);
p.getText().setDiv(div);
checkHasTypes(p);
return p;
}
public StructureDefinition generate(TypeDefn t) throws Exception {
genUml(t);
StructureDefinition p = new StructureDefinition();
p.setId(t.getName());
p.setUrl("http://hl7.org/fhir/StructureDefinition/"+ t.getName());
p.setKind(StructureDefinitionKind.COMPLEXTYPE);
p.setAbstract(t.isAbstractType());
p.setUserData("filename", t.getName().toLowerCase());
p.setUserData("path", definitions.getSrcFile(t.getName())+".html#"+t.getName());
assert !Utilities.noString(t.typeCode());
String b = (t.typeCode().equals("Type") ? "Element" : t.typeCode().equals("Structure") ? "BackboneElement" : t.typeCode());
if (!Utilities.noString(b)) {
p.setBaseDefinition("http://hl7.org/fhir/StructureDefinition/"+b);
p.setDerivation(TypeDerivationRule.SPECIALIZATION);
}
p.setType(t.getName());
p.setFhirVersion(version);
p.setVersion(version.toCode());
ToolingExtensions.setStandardsStatus(p, t.getStandardsStatus(), t.getNormativeVersion());
ToolResourceUtilities.updateUsage(p, "core");
p.setName(t.getName());
p.setPublisher("HL7 FHIR Standard");
p.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.URL, "http://hl7.org/fhir"));
p.setDescription("Base StructureDefinition for "+t.getName()+" Type: "+t.getDefinition());
p.setPurpose(t.getRequirements());
p.setDate(genDate.getTime());
p.setStatus(t.getStandardsStatus() == StandardsStatus.NORMATIVE ? PublicationStatus.fromCode("active") : PublicationStatus.fromCode("draft"));
Set<String> containedSlices = new HashSet<String>();
// first, the differential
p.setDifferential(new StructureDefinitionDifferentialComponent());
defineElement(null, p, p.getDifferential().getElement(), t, t.getName(), containedSlices, new ArrayList<ProfileGenerator.SliceHandle>(), SnapShotMode.None, true, "Element", b, false);
p.getDifferential().getElement().get(0).setIsSummaryElement(null);
reset();
// now. the snapshot
p.setSnapshot(new StructureDefinitionSnapshotComponent());
defineElement(null, p, p.getSnapshot().getElement(), t, t.getName(), containedSlices, new ArrayList<ProfileGenerator.SliceHandle>(), SnapShotMode.DataType, true, "Element", b, true);
for (ElementDefinition ed : p.getSnapshot().getElement())
if (ed.getBase().getPath().equals(ed.getPath()) && ed.getPath().contains("."))
generateElementDefinition(p, ed, getParent(ed, p.getSnapshot().getElement()));
containedSlices.clear();
addElementConstraintToSnapshot(p);
p.getDifferential().getElement().get(0).getType().clear();
p.getSnapshot().getElement().get(0).getType().clear();
p.getSnapshot().getElement().get(0).setIsSummaryElement(null);
XhtmlNode div = new XhtmlNode(NodeType.Element, "div");
div.addText("to do");
p.setText(new Narrative());
p.getText().setStatus(NarrativeStatus.GENERATED);
p.getText().setDiv(div);
checkHasTypes(p);
return p;
}
private void genUml(TypeDefn t) {
if (!uml.hasClass(t.getName())) {
UMLClass c = new UMLClass(t.getName(), UMLClassType.Class);
uml.getTypes().put(t.getName(), c);
}
UMLClass c = uml.getClassByName(t.getName());
c.setDocumentation(t.getDefinition());
if (!t.getTypes().isEmpty()) {
c.setSpecialises(uml.getClassByName(t.typeCodeNoParams()));
}
if (!c.hasAttributes()) {
for (ElementDefn e : t.getElements()) {
UMLAttribute a = null;
if (t.getTypes().isEmpty()) {
a = new UMLAttribute(e.getName(), Integer.toString(e.getMinCardinality()), Integer.toString(e.getMaxCardinality()), uml.getClassByNameCreate("Base"));
} else if (t.getTypes().size() == 1 && !isReference(t.getTypes().get(0).getName())) {
a = new UMLAttribute(e.getName(), Integer.toString(e.getMinCardinality()), Integer.toString(e.getMaxCardinality()), uml.getClassByNameCreate(e.typeCode()));
} else {
String tn = t.getTypes().get(0).getName();
boolean allSame = true;
for (int i = 1; i < t.getTypes().size(); i++) {
allSame = tn.equals(t.getTypes().get(i).getName());
}
if (allSame && isReference(tn)) {
a = new UMLAttribute(e.getName(), Integer.toString(e.getMinCardinality()), Integer.toString(e.getMaxCardinality()), uml.getClassByNameCreate(tn));
for (TypeRef tr : t.getTypes()) {
for (String p : tr.getParams()) {
a.getTargets().add(p);
}
}
} else {
boolean allPrimitive = true;
for (TypeRef tr : t.getTypes()) {
if (!definitions.hasPrimitiveType(tr.getName())) {
allPrimitive = false;
}
}
if (allPrimitive) {
a = new UMLAttribute(e.getName(), Integer.toString(e.getMinCardinality()), Integer.toString(e.getMaxCardinality()), uml.getClassByNameCreate("PrimitiveType"));
} else {
a = new UMLAttribute(e.getName(), Integer.toString(e.getMinCardinality()), Integer.toString(e.getMaxCardinality()), uml.getClassByNameCreate("DataType"));
}
for (TypeRef tr : t.getTypes()) {
a.getTypes().add(tr.getName());
for (String p : tr.getParams()) {
a.getTargets().add(p);
}
}
}
}
c.getAttributes().add(a);
}
}
}
private boolean isReference(String name) {
return name.equals("Reference") || name.equals("canonical") || name.equals("CodeableReference");
}
public StructureDefinition generate(ProfiledType pt, List<ValidationMessage> issues) throws Exception {
StructureDefinition p = new StructureDefinition();
p.setId(pt.getName());
p.setUrl("http://hl7.org/fhir/StructureDefinition/"+ pt.getName());
p.setBaseDefinition("http://hl7.org/fhir/StructureDefinition/"+pt.getBaseType());
p.setKind(StructureDefinitionKind.COMPLEXTYPE);
p.setType(pt.getBaseType());
p.setDerivation(TypeDerivationRule.CONSTRAINT);
p.setAbstract(false);
p.setUserData("filename", pt.getName().toLowerCase());
p.setUserData("path", "datatypes.html#"+pt.getName());
p.setFhirVersion(version);
p.setVersion(version.toCode());
ToolingExtensions.setStandardsStatus(p, StandardsStatus.NORMATIVE, "4.0.0");
p.setStatus(PublicationStatus.fromCode("active"));
ToolResourceUtilities.updateUsage(p, "core");
p.setName(pt.getName());
p.setPublisher("HL7 FHIR Standard");
p.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.URL, "http://hl7.org/fhir"));
p.setDescription("Base StructureDefinition for Type "+pt.getName()+": "+pt.getDefinition());
p.setDescription(pt.getDefinition());
p.setDate(genDate.getTime());
// first, the differential
p.setName(pt.getName());
ElementDefinition e = new ElementDefinition();
String idroot = e.getId();
e.setPath(pt.getBaseType());
// e.setSliceName(pt.getName());
e.setShort(pt.getDefinition());
e.setDefinition(preProcessMarkdown(pt.getDescription(), "??"));
e.setMin(0);
e.setMax("*");
e.setIsModifier(false);
String s = definitions.getTLAs().get(pt.getName().toLowerCase());
if (s == null)
throw new Exception("There is no TLA for '"+pt.getName()+"' in fhir.ini");
ElementDefinitionConstraintComponent inv = new ElementDefinitionConstraintComponent();
inv.setKey(s+"-1");
inv.setRequirements(pt.getInvariant().getRequirements());
inv.setSeverity(ConstraintSeverity.ERROR);
inv.setHuman(pt.getInvariant().getEnglish());
if (!"n/a".equals(pt.getInvariant().getExpression())) {
fpUsages.add(new FHIRPathUsage(pt.getName(), pt.getName(), pt.getName(), null, pt.getInvariant().getExpression()));
inv.setExpression(pt.getInvariant().getExpression());
}
inv.setXpath(pt.getInvariant().getXpath());
e.getConstraint().add(inv);
p.setDifferential(new StructureDefinitionDifferentialComponent());
p.getDifferential().getElement().add(e);
StructureDefinition base = getTypeSnapshot(pt.getBaseType());
if (!pt.getRules().isEmpty()) {
// need to generate a differential based on the rules.
// throw new Exception("todo");
for (String rule : pt.getRules().keySet()) {
String[] parts = rule.split("\\.");
String value = pt.getRules().get(rule);
ElementDefinition er = findElement(p.getDifferential(), pt.getBaseType()+'.'+parts[0]);
if (er == null) {
er = new ElementDefinition();
er.setId(pt.getBaseType()+':'+p.getId()+'.'+parts[0]);
er.setPath(pt.getBaseType()+'.'+parts[0]);
p.getDifferential().getElement().add(er);
}
if (parts[1].equals("min"))
er.setMin(Integer.parseInt(value));
else if (parts[1].equals("max"))
er.setMax(value);
else if (parts[1].equals("defn"))
er.setDefinition(preProcessMarkdown(value, "er"));
}
List<String> errors = new ArrayList<String>();
new ProfileUtilities(context, null, pkp).sortDifferential(base, p, p.getName(), errors, true);
for (String se : errors)
issues.add(new ValidationMessage(Source.ProfileValidator, IssueType.STRUCTURE, -1, -1, p.getUrl(), se, IssueSeverity.WARNING));
}
reset();
// now, the snapshot
new ProfileUtilities(context, issues, pkp).generateSnapshot(base, p, "http://hl7.org/fhir/StructureDefinition/"+pt.getBaseType(), "http://hl7.org/fhir", p.getName());
// for (ElementDefinition ed : p.getSnapshot().getElement())
// generateElementDefinition(ed, getParent(ed, p.getSnapshot().getElement()));
p.getDifferential().getElement().get(0).getType().clear();
p.getSnapshot().getElement().get(0).getType().clear();
XhtmlNode div = new XhtmlNode(NodeType.Element, "div");
div.addTag("h2").addText("Data type "+pt.getName());
div.addTag("p").addText(pt.getDefinition());
div.addTag("h3").addText("Rule");
div.addTag("p").addText(pt.getInvariant().getEnglish());
div.addTag("p").addText("XPath:");
div.addTag("blockquote").addTag("pre").addText(pt.getInvariant().getXpath());
p.setText(new Narrative());
p.getText().setStatus(NarrativeStatus.GENERATED);
p.getText().setDiv(div);
addElementConstraintToSnapshot(p);
new ProfileUtilities(context, issues, pkp).setIds(p, false);
checkHasTypes(p);
return p;
}
private ElementDefinition findElement(StructureDefinitionDifferentialComponent differential, String path) {
for (ElementDefinition ed : differential.getElement()) {
if (ed.getPath().equals(path))
return ed;
}
return null;
}
private ElementDefinition getParent(ElementDefinition e, List<ElementDefinition> elist) {
String p = e.getPath();
if (!p.contains("."))
return null;
p = p.substring(0, p.lastIndexOf("."));
int i = elist.indexOf(e);
i--;
while (i > -1) {
if (elist.get(i).getPath().equals(p)) {
return elist.get(i);
}
i--;
}
return null;
}
private StructureDefinition getTypeSnapshot(String baseType) throws Exception {
StructureDefinition p = definitions.getElementDefn(baseType).getProfile();
if (p != null && p.hasSnapshot())
return p;
throw new Exception("Unable to find snapshot for "+baseType);
}
public StructureDefinition generate(Profile pack, ResourceDefn r, String usage, boolean logical) throws Exception {
StructureDefinition p = new StructureDefinition();
p.setId(r.getRoot().getName());
p.setUrl("http://hl7.org/fhir/StructureDefinition/"+ r.getRoot().getName());
if (logical)
p.setKind(StructureDefinitionKind.LOGICAL);
else
p.setKind(StructureDefinitionKind.RESOURCE);
if (r.isInterface()) {
ToolingExtensions.addBooleanExtension(p, ToolingExtensions.EXT_RESOURCE_INTERFACE, true);
}
IniFile cini = new IniFile(Utilities.path(rootFolder, "temp", "categories.ini"));
String cat = cini.getStringProperty("category", r.getName());
if (!Utilities.noString(cat))
ToolingExtensions.setStringExtension(p, ToolingExtensions.EXT_RESOURCE_CATEGORY, cat);
p.setAbstract(r.isAbstract());
assert !Utilities.noString(r.getRoot().typeCode());
if (!Utilities.noString(r.getRoot().typeCode())) {
p.setBaseDefinition("http://hl7.org/fhir/StructureDefinition/"+r.getRoot().typeCode());
p.setDerivation(TypeDerivationRule.SPECIALIZATION);
// if (r.getTemplate() != null)
// ToolingExtensions.addStringExtension(p.getBaseDefinitionElement(), ToolingExtensions.EXT_CODE_GENERATION_PARENT, r.getTemplate().getName());
}
p.setType(r.getRoot().getName());
p.setUserData("filename", r.getName().toLowerCase());
p.setUserData("path", r.getName().toLowerCase()+".html");
p.setTitle(pack.metadata("display"));
p.setFhirVersion(version);
p.setVersion(version.toCode());
ToolingExtensions.setStandardsStatus(p, r.getStatus(), r.getNormativeVersion());
if (r.getFmmLevel() != null)
ToolingExtensions.addIntegerExtension(p, ToolingExtensions.EXT_FMM_LEVEL, Integer.parseInt(r.getFmmLevel()));
if (r.getSecurityCategorization() != null)
ToolingExtensions.addCodeExtension(p, ToolingExtensions.EXT_SEC_CAT, r.getSecurityCategorization().toCode());
ToolResourceUtilities.updateUsage(p, usage);
p.setName(r.getRoot().getName());
p.setPublisher("Health Level Seven International"+(r.getWg() == null ? "" : " ("+r.getWg().getName()+")"));
p.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.URL, "http://hl7.org/fhir"));
if (r.getWg() != null)
p.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.URL, r.getWg().getUrl()));
ToolingExtensions.setCodeExtension(p, ToolingExtensions.EXT_WORKGROUP, r.getWg().getCode());
p.setDescription(r.getDefinition());
p.setPurpose(r.getRoot().getRequirements());
if (!p.hasPurpose())
p.setPurpose(r.getRoot().getRequirements());
p.setDate(genDate.getTime());
p.setStatus(r.getStatus() == StandardsStatus.NORMATIVE ? PublicationStatus.fromCode("active") : PublicationStatus.fromCode("draft")); // DSTU
Set<String> containedSlices = new HashSet<String>();
// first, the differential
p.setDifferential(new StructureDefinitionDifferentialComponent());
defineElement(null, p, p.getDifferential().getElement(), r.getRoot(), r.getRoot().getName(), containedSlices, new ArrayList<ProfileGenerator.SliceHandle>(), SnapShotMode.None, true, "BackboneElement", r.getRoot().typeCode(), false);
reset();
// now. the snapshot'
p.setSnapshot(new StructureDefinitionSnapshotComponent());
defineElement(null, p, p.getSnapshot().getElement(), r.getRoot(), r.getRoot().getName(), containedSlices, new ArrayList<ProfileGenerator.SliceHandle>(), SnapShotMode.Resource, true, "BackboneElement", r.getRoot().typeCode(), true);
for (ElementDefinition ed : p.getSnapshot().getElement())
if (!ed.hasBase() && !logical)
generateElementDefinition(p, ed, getParent(ed, p.getSnapshot().getElement()));
if (!logical && !r.isInterface()) {
List<String> names = new ArrayList<String>();
names.addAll(r.getSearchParams().keySet());
Collections.sort(names);
// 1st, non composites
for (String pn : names) {
SearchParameterDefn sp = r.getSearchParams().get(pn);
if (sp.getType() != SearchType.composite)
pack.getSearchParameters().add(makeSearchParam(p, r.getName()+"-"+pn.replace("_", ""), r.getName(), sp, r));
}
for (String pn : names) {
SearchParameterDefn sp = r.getSearchParams().get(pn);
if (sp.getType() == SearchType.composite)
pack.getSearchParameters().add(makeSearchParam(p, r.getName()+"-"+pn.replace("_", ""), r.getName(), sp, r));
}
}
containedSlices.clear();
addElementConstraintToSnapshot(p);
p.getDifferential().getElement().get(0).getType().clear();
p.getSnapshot().getElement().get(0).getType().clear();
XhtmlNode div = new XhtmlNode(NodeType.Element, "div");
div.addText("to do");
p.setText(new Narrative());
p.getText().setStatus(NarrativeStatus.GENERATED);
p.getText().setDiv(div);
checkHasTypes(p);
return p;
}
private void reset() {
paths.clear();
}
public StructureDefinition generate(Profile pack, ConstraintStructure profile, ResourceDefn resource, String id, ImplementationGuideDefn usage, List<ValidationMessage> issues, ResourceDefn baseResource) throws Exception {
try {
return generate(pack, profile, resource, id, null, usage, issues, baseResource);
} catch (Exception e) {
throw new Exception("Error processing profile '"+id+"': "+e.getMessage(), e);
}
}
public StructureDefinition generate(Profile pack, ConstraintStructure profile, ResourceDefn resource, String id, String html, ImplementationGuideDefn usage, List<ValidationMessage> issues, ResourceDefn baseResource) throws Exception {
if (profile.getResource() != null)
return profile.getResource();
StructureDefinition p = new StructureDefinition();
p.setId(FormatUtilities.makeId(id));
p.setUrl("http://hl7.org/fhir/StructureDefinition/"+ id);
if (usage != null && !usage.isCore()) {
if (!id.startsWith(usage.getCode()+"-"))
throw new Exception("Error: "+id+" must start with "+usage.getCode()+"-");
}
if (!resource.getRoot().getTypes().isEmpty() && (resource.getRoot().getTypes().get(0).getProfile() != null))
p.setBaseDefinition(resource.getRoot().getTypes().get(0).getProfile());
else
p.setBaseDefinition("http://hl7.org/fhir/StructureDefinition/"+resource.getName());
if (definitions.hasType(resource.getName()))
p.setKind(StructureDefinitionKind.COMPLEXTYPE);
else
p.setKind(StructureDefinitionKind.RESOURCE);
p.setType(resource.getName());
p.setDerivation(TypeDerivationRule.CONSTRAINT);
p.setAbstract(false);
p.setUserData("filename", id);
p.setUserData("path", ((usage == null || usage.isCore()) ? "" : usage.getCode()+File.separator)+id+".html");
p.setTitle(pack.metadata("display"));
p.setFhirVersion(version);
p.setVersion(version.toCode());
if (pack.hasMetadata("summary-"+profile.getTitle()))
ToolingExtensions.addMarkdownExtension(p, "http://hl7.org/fhir/StructureDefinition/structuredefinition-summary", pack.metadata("summary-"+profile.getTitle()));
ToolResourceUtilities.updateUsage(p, usage.getCode());
p.setName(pack.metadata("name"));
p.setPublisher(pack.metadata("author.name"));
if (pack.hasMetadata("author.reference"))
p.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.URL, pack.metadata("author.reference")));
// <code> opt Zero+ Coding assist with indexing and finding</code>
p.setDescription(resource.getRoot().getShortDefn());
if (!p.hasDescriptionElement() && pack.hasMetadata("description"))
p.setDescription(preProcessMarkdown(pack.metadata("description"), "pack.description"));
p.setPurpose(resource.getRoot().getRequirements());
if (!p.hasPurpose() && pack.hasMetadata("requirements"))
p.setPurpose(pack.metadata("requirements"));
p.setExperimental(Utilities.existsInList(pack.metadata("Experimental"), "y", "Y", "true", "TRUE", "1"));
if (pack.hasMetadata("date"))
p.setDateElement(Factory.newDateTime(pack.metadata("date").substring(0, 10)));
else
p.setDate(genDate.getTime());
if (pack.hasMetadata("fmm-level"))
ToolingExtensions.addIntegerExtension(p, ToolingExtensions.EXT_FMM_LEVEL, Integer.parseInt(pack.getFmmLevel()));
else if (pack.hasMetadata("fmm"))
ToolingExtensions.addIntegerExtension(p, ToolingExtensions.EXT_FMM_LEVEL, Integer.parseInt(pack.metadata("fmm")));
else if (!Utilities.noString(resource.getFmmLevel()))
ToolingExtensions.addIntegerExtension(p, ToolingExtensions.EXT_FMM_LEVEL, Integer.parseInt(resource.getFmmLevel()));
else if (baseResource != null && !Utilities.noString(baseResource.getFmmLevel()))
ToolingExtensions.addIntegerExtension(p, ToolingExtensions.EXT_FMM_LEVEL, Integer.parseInt(baseResource.getFmmLevel()));
if (pack.hasMetadata("workgroup"))
ToolingExtensions.setCodeExtension(p, ToolingExtensions.EXT_WORKGROUP, pack.getWg());
else if (resource.getWg() != null)
ToolingExtensions.setCodeExtension(p, ToolingExtensions.EXT_WORKGROUP, resource.getWg().getCode());
else if (baseResource != null && baseResource.getWg() != null)
ToolingExtensions.setCodeExtension(p, ToolingExtensions.EXT_WORKGROUP, baseResource.getWg().getCode());
if (pack.hasMetadata("Standards-Status"))
ToolingExtensions.setStandardsStatus(p, StandardsStatus.fromCode(pack.metadata("Standards-Status")), null);
else
ToolingExtensions.setStandardsStatus(p, resource.getStatus(), null);
if (pack.hasMetadata("status"))
p.setStatus(PublicationStatus.fromCode(pack.metadata("status")));
if (pack.getMetadata().containsKey("code"))
for (String s : pack.getMetadata().get("code"))
if (!Utilities.noString(s))
p.getKeyword().add(Factory.makeCoding(s));
if (pack.hasMetadata("datadictionary"))
ToolingExtensions.setStringExtension(p, "http://hl7.org/fhir/StructureDefinition/datadictionary", pack.metadata("datadictionary"));
Set<String> containedSlices = new HashSet<String>();
p.setDifferential(new StructureDefinitionDifferentialComponent());
defineElement(pack, p, p.getDifferential().getElement(), resource.getRoot(), resource.getName(), containedSlices, new ArrayList<ProfileGenerator.SliceHandle>(), SnapShotMode.None, true, null, null, false);
List<String> names = new ArrayList<String>();
names.addAll(resource.getSearchParams().keySet());
Collections.sort(names);
for (String pn : names) {
pack.getSearchParameters().add(makeSearchParam(p, pack.getId()+"-"+resource.getName()+"-"+pn, resource.getName(), resource.getSearchParams().get(pn), resource));
}
StructureDefinition base = definitions.getSnapShotForBase(p.getBaseDefinition());
List<String> errors = new ArrayList<String>();
new ProfileUtilities(context, null, pkp).sortDifferential(base, p, p.getName(), errors, false);
for (String s : errors)
issues.add(new ValidationMessage(Source.ProfileValidator, IssueType.STRUCTURE, -1, -1, p.getUrl(), s, IssueSeverity.WARNING));
reset();
// ok, c is the differential. now we make the snapshot
new ProfileUtilities(context, issues, pkp).generateSnapshot(base, p, "http://hl7.org/fhir/StructureDefinition/"+p.getType(), "http://hl7.org/fhir", p.getName());
reset();
p.getDifferential().getElement().get(0).getType().clear();
p.getSnapshot().getElement().get(0).getType().clear();
addElementConstraintToSnapshot(p);
XhtmlNode div = new XhtmlNode(NodeType.Element, "div");
div.addText("to do");
p.setText(new Narrative());
p.getText().setStatus(NarrativeStatus.GENERATED);
p.getText().setDiv(div);
new ProfileUtilities(context, issues, pkp).setIds(p, false);
checkHasTypes(p);
return p;
}
private String preProcessMarkdown(String text, String location) throws Exception {
return MarkDownPreProcessor.process(definitions, context, null, text, location, null);
}
private SearchParamType getSearchParamType(SearchParameterDefn.SearchType type) {
switch (type) {
case number:
return SearchParamType.NUMBER;
case string:
return SearchParamType.STRING;
case date:
return SearchParamType.DATE;
case reference:
return SearchParamType.REFERENCE;
case token:
return SearchParamType.TOKEN;
case uri:
return SearchParamType.URI;
case composite:
return SearchParamType.COMPOSITE;
case quantity:
return SearchParamType.QUANTITY;
case special:
return SearchParamType.SPECIAL;
}
return null;
}
public SearchParameter makeSearchParam(StructureDefinition p, String id, String rn, SearchParameterDefn spd, ResourceDefn rd) throws Exception {
boolean shared;
boolean created = true;
SearchParameter sp;
if (definitions.getCommonSearchParameters().containsKey(rn+"::"+spd.getCode())) {
shared = true;
CommonSearchParameter csp = definitions.getCommonSearchParameters().get(rn+"::"+spd.getCode());
if (csp.getDefinition() == null) {
sp = new SearchParameter();
csp.setDefinition(sp);
sp.setId(csp.getId());
} else {
created = false;
sp = csp.getDefinition();
}
} else {
shared = false;
sp = new SearchParameter();
sp.setId(id.replace("[", "").replace("]", ""));
}
spd.setCommonId(sp.getId());
if (created) {
sp.setUrl("http://hl7.org/fhir/SearchParameter/"+sp.getId());
sp.setVersion(Constants.VERSION);
if (context.getSearchParameter(sp.getUrl()) != null)
throw new Exception("Duplicated Search Parameter "+sp.getUrl());
context.cacheResource(sp);
spd.setResource(sp);
definitions.addNs(sp.getUrl(), "Search Parameter: "+sp.getName(), rn.toLowerCase()+".html#search");
sp.setStatus(spd.getStandardsStatus() == StandardsStatus.NORMATIVE ? PublicationStatus.fromCode("active") : PublicationStatus.fromCode("draft"));
StandardsStatus sst = ToolingExtensions.getStandardsStatus(sp);
if (sst == null || (spd.getStandardsStatus() == null && spd.getStandardsStatus().isLowerThan(sst)))
ToolingExtensions.setStandardsStatus(sp, spd.getStandardsStatus(), spd.getNormativeVersion());
sp.setExperimental(p.getExperimental());
sp.setName(spd.getCode());
sp.setCode(spd.getCode());
sp.setDate(genDate.getTime());
sp.setPublisher(p.getPublisher());
for (ContactDetail tc : p.getContact()) {
ContactDetail t = sp.addContact();
if (tc.hasNameElement())
t.setNameElement(tc.getNameElement().copy());
for (ContactPoint ts : tc.getTelecom())
t.getTelecom().add(ts.copy());
}
if (!definitions.hasResource(p.getType()) && !p.getType().equals("Resource") && !p.getType().equals("DomainResource"))
throw new Exception("unknown resource type "+p.getType());
sp.setType(getSearchParamType(spd.getType()));
if (sp.getType() == SearchParamType.REFERENCE && spd.isHierarchy()) {
sp.addModifier(SearchParameter.SearchModifierCode.BELOW);
sp.addModifier(SearchParameter.SearchModifierCode.ABOVE);
}
if (shared) {
sp.setDescription("Multiple Resources: \r\n\r\n* ["+rn+"]("+rn.toLowerCase()+".html): " + spd.getDescription()+"\r\n");
} else
sp.setDescription(preProcessMarkdown(spd.getDescription(), "Search Description"));
if (!Utilities.noString(spd.getExpression()))
sp.setExpression(spd.getExpression());
// addModifiers(sp);
addComparators(sp);
String xpath = Utilities.noString(spd.getXPath()) ? new XPathQueryGenerator(this.definitions, null, null).generateXpath(spd.getPaths(), rn) : spd.getXPath();
if (xpath != null) {
if (xpath.contains("[x]"))
xpath = convertToXpath(xpath);
sp.setXpath(xpath);
sp.setXpathUsage(spd.getxPathUsage());
}
if (sp.getType() == SearchParamType.COMPOSITE) {
for (CompositeDefinition cs : spd.getComposites()) {
SearchParameterDefn cspd = findSearchParameter(rd, cs.getDefinition());
if (cspd != null)
sp.addComponent().setExpression(cs.getExpression()).setDefinition(cspd.getUrl());
else
sp.addComponent().setExpression(cs.getExpression()).setDefinition("http://hl7.org/fhir/SearchParameter/"+rn+"-"+cs.getDefinition());
}
sp.setMultipleOr(false);
}
sp.addBase(p.getType());
} else {
if (sp.getType() != getSearchParamType(spd.getType()))
throw new FHIRException("Type mismatch on common parameter: expected "+sp.getType().toCode()+" but found "+getSearchParamType(spd.getType()).toCode());
if (!sp.getDescription().contains("["+rn+"]("+rn.toLowerCase()+".html)"))
sp.setDescription(sp.getDescription()+"* ["+rn+"]("+rn.toLowerCase()+".html): " + spd.getDescription()+"\r\n");
// Extension ext = sp.addExtension().setUrl("http://hl7.org/fhir/StructureDefinition/SearchParameter-label");
// ext.addExtension("resource", new CodeType(spd.getDescription()));
// ext.addExtension("description", new MarkdownType(spd.getDescription()));
if (!Utilities.noString(spd.getExpression()) && !sp.getExpression().contains(spd.getExpression()))
sp.setExpression(sp.getExpression()+" | "+spd.getExpression());
String xpath = new XPathQueryGenerator(this.definitions, null, null).generateXpath(spd.getPaths(), rn);
if (xpath != null) {
if (xpath.contains("[x]"))
xpath = convertToXpath(xpath);
if (sp.getXpath() != null && !sp.getXpath().contains(xpath))
sp.setXpath(sp.getXpath()+" | " +xpath);
if (sp.getXpathUsage() != spd.getxPathUsage())
throw new FHIRException("Usage mismatch on common parameter: expected "+sp.getXpathUsage().toCode()+" but found "+spd.getxPathUsage().toCode());
}
boolean found = false;
for (CodeType ct : sp.getBase())
found = found || p.getType().equals(ct.asStringValue());
if (!found)
sp.addBase(p.getType());
}
spd.setUrl(sp.getUrl());
for(String target : spd.getWorkingTargets()) {
if("Any".equals(target) == true) {
for(String resourceName : definitions.sortedResourceNames()) {
boolean found = false;
for (CodeType st : sp.getTarget())
found = found || st.asStringValue().equals(resourceName);
if (!found)
sp.addTarget(resourceName);
}
}
else {
boolean found = false;
for (CodeType st : sp.getTarget())
found = found || st.asStringValue().equals(target);
if (!found)
sp.addTarget(target);
}
}
return sp;
}
private SearchParameterDefn findSearchParameter(ResourceDefn rd, String definition) {
for (SearchParameterDefn spd : rd.getSearchParams().values()) {
if (spd.getCode().equals(definition))
return spd;
}
return null;
}
private void addComparators(SearchParameter sp) {
if (sp.getType() == SearchParamType.NUMBER || sp.getType() == SearchParamType.DATE || sp.getType() == SearchParamType.QUANTITY) {
sp.addComparator(SearchComparator.EQ);
sp.addComparator(SearchComparator.NE);
sp.addComparator(SearchComparator.GT);
sp.addComparator(SearchComparator.GE);
sp.addComparator(SearchComparator.LT);
sp.addComparator(SearchComparator.LE);
sp.addComparator(SearchComparator.SA);
sp.addComparator(SearchComparator.EB);
sp.addComparator(SearchComparator.AP);
}
}
private void addModifiers(SearchParameter sp) {
sp.addModifier(org.hl7.fhir.r5.model.SearchParameter.SearchModifierCode.MISSING); // on everything
switch (sp.getType()) {
case STRING:
sp.addModifier(org.hl7.fhir.r5.model.SearchParameter.SearchModifierCode.EXACT);
sp.addModifier(org.hl7.fhir.r5.model.SearchParameter.SearchModifierCode.CONTAINS);
return;
case TOKEN:
sp.addModifier(org.hl7.fhir.r5.model.SearchParameter.SearchModifierCode.TEXT);
sp.addModifier(org.hl7.fhir.r5.model.SearchParameter.SearchModifierCode.NOT);
sp.addModifier(org.hl7.fhir.r5.model.SearchParameter.SearchModifierCode.IN);
sp.addModifier(org.hl7.fhir.r5.model.SearchParameter.SearchModifierCode.NOTIN);
sp.addModifier(org.hl7.fhir.r5.model.SearchParameter.SearchModifierCode.BELOW);
sp.addModifier(org.hl7.fhir.r5.model.SearchParameter.SearchModifierCode.ABOVE);
sp.addModifier(org.hl7.fhir.r5.model.SearchParameter.SearchModifierCode.OFTYPE);
return;
case REFERENCE:
sp.addModifier(org.hl7.fhir.r5.model.SearchParameter.SearchModifierCode.TYPE);
sp.addModifier(org.hl7.fhir.r5.model.SearchParameter.SearchModifierCode.IDENTIFIER);
if (isCircularReference(sp)) {
sp.addModifier(org.hl7.fhir.r5.model.SearchParameter.SearchModifierCode.BELOW);
sp.addModifier(org.hl7.fhir.r5.model.SearchParameter.SearchModifierCode.ABOVE);
}
return;
case URI:
sp.addModifier(org.hl7.fhir.r5.model.SearchParameter.SearchModifierCode.BELOW);
sp.addModifier(org.hl7.fhir.r5.model.SearchParameter.SearchModifierCode.ABOVE);
return;
// no modifiers for these
case NUMBER:
case DATE:
case COMPOSITE:
case QUANTITY:
case SPECIAL:
default:
return;
}
}
private boolean isCircularReference(SearchParameter sp) {
try {
ElementDefn e = definitions.getElementByPath(sp.getExpression().split("\\."), "search parameter analysis", true);
return e != null && e.hasHierarchy() && e.getHierarchy();
} catch (Exception e) {
return false;
}
}
private String convertToXpath(String xpath) {
String[] parts = xpath.split("\\/");
StringBuilder b = new StringBuilder();
boolean first = true;
for (String p : parts) {
if (first)
first = false;
else
b.append("/");
if (p.startsWith("f:")) {
String v = p.substring(2);
if (v.endsWith("[x]"))
b.append("*[starts-with(local-name(.), '"+v.replace("[x]", "")+"')]");
else
b.append(p);
}
else
b.append(p);
}
return b.toString();
}
private ElementDefinitionBindingComponent generateBinding(BindingSpecification src) throws Exception {
if (src == null)
return null;
ElementDefinitionBindingComponent dst = new ElementDefinitionBindingComponent();
dst.setDescription(src.getDefinition());
if (src.getBinding() != BindingMethod.Unbound) {
dst.setStrength(src.getStrength());
dst.setValueSet(buildValueSetReference(src));
if (src.hasMax()) {
dst.addExtension().setUrl("http://hl7.org/fhir/StructureDefinition/elementdefinition-maxValueSet").setValue(new CanonicalType(src.getMaxReference() != null ? src.getMaxReference() : src.getMaxValueSet().getUrl()));
}
} else {
dst.setStrength(BindingStrength.EXAMPLE);
}
dst.addExtension().setUrl("http://hl7.org/fhir/StructureDefinition/elementdefinition-bindingName").setValue(new StringType(src.getName()));
if (src.isShared())
dst.addExtension().setUrl("http://hl7.org/fhir/StructureDefinition/elementdefinition-isCommonBinding").setValue(new BooleanType(true));
return dst;
}
private String buildValueSetReference(BindingSpecification src) throws Exception {
String v = "";
if (src.getStrength() == BindingStrength.REQUIRED) {
if (src.getValueSet() != null && src.getValueSet().hasVersion()) {
v = "|"+src.getValueSet().getVersion();
} else {
v = "|"+version.toCode();
}
}
switch (src.getBinding()) {
case Unbound: return null;
case CodeList:
if (src.getValueSet()!= null)
return src.getValueSet().getUrl()+v;
else if (src.getReference().startsWith("#"))
return "http://hl7.org/fhir/ValueSet/"+src.getReference().substring(1)+v;
else
throw new Exception("not done yet");
case ValueSet:
if (!Utilities.noString(src.getReference()))
if (src.getReference().startsWith("http"))
return src.getReference()+v;
else if (src.getValueSet()!= null)
return src.getValueSet().getUrl()+v;
else if (src.getReference().startsWith("valueset-"))
return "http://hl7.org/fhir/ValueSet/"+src.getReference().substring(9)+v;
else
return "http://hl7.org/fhir/ValueSet/"+src.getReference()+v;
else
return null; // throw new Exception("not done yet");
case Special:
return "http://hl7.org/fhir/ValueSet/"+src.getReference().substring(1)+v;
default:
throw new Exception("not done yet");
}
}
/**
* note: snapshot implies that we are generating a resource or a data type; for other profiles, the snapshot is generated elsewhere
* @param isInterface
*/
private ElementDefinition defineElement(Profile ap, StructureDefinition p, List<ElementDefinition> elements, ElementDefn e, String path, Set<String> slices, List<SliceHandle> parentSlices, SnapShotMode snapshot, boolean root, String defType, String inheritedType, boolean defaults) throws Exception
{
boolean handleDiscriminator = true;
if (!Utilities.noString(e.getProfileName()) && !e.getDiscriminator().isEmpty() && !slices.contains(path)) {
handleDiscriminator = false;
// hey, we jumped straight into the slices with setting up the slicing (allowed in the spreadsheets, but not otherwise)
ElementDefinition slicer = new ElementDefinition();
elements.add(slicer);
slicer.setId(path);
slicer.setPath(path);
processDiscriminator(e, path, slicer);
if (e.getMaxCardinality() != null)
slicer.setMax(e.getMaxCardinality() == Integer.MAX_VALUE ? "*" : e.getMaxCardinality().toString());
slices.add(path);
}
// todo for task 12259
// if (ap != null) {
// String base = isImplicitTypeConstraint(path);
// if (base != null) {
// ElementDefinition typeConstrainer = new ElementDefinition(ElementDefinition.NOT_MODIFIER, ElementDefinition.NOT_IN_SUMMARY);
// elements.add(typeConstrainer);
// typeConstrainer.setId(base);
// typeConstrainer.setPath(base);
// String type = path.substring(base.length()-3);
// if (definitions.hasPrimitiveType(Utilities.uncapitalize(type)))
// type = Utilities.uncapitalize(type);
// typeConstrainer.addType().setCode(type);
// }
// }
ElementDefinition ce = new ElementDefinition(defaults, ElementDefinition.NOT_MODIFIER, ElementDefinition.NOT_IN_SUMMARY);
elements.add(ce);
// todo ce.setId(path.substring(path.indexOf(".")+1));
if (e.getStandardsStatus() != null)
ToolingExtensions.setStandardsStatus(ce, e.getStandardsStatus(), e.getNormativeVersion());
ce.setId(path);
ce.setPath(path);
if (e.isXmlAttribute())
ce.addRepresentation(PropertyRepresentation.XMLATTR);
List<SliceHandle> myParents = new ArrayList<ProfileGenerator.SliceHandle>();
myParents.addAll(parentSlices);
// If this element has a profile name, and this is the first of the
// slicing group, add a slicing group "entry" (= first slice member,
// which holds Slicing information)
if (e.hasDescriminator() || !Utilities.noString(e.getProfileName())) {
if (e.getDiscriminator().size() > 0 && !slices.contains(path) && handleDiscriminator) {
processDiscriminator(e, path, ce);
slices.add(path);
}
if (!Utilities.noString(e.getProfileName())) {
SliceHandle hnd = new SliceHandle();
hnd.name = path; // though this it not used?
myParents.add(hnd);
if (path.contains(".")) { // We don't want a slice name on the root
ce.setSliceName(e.getProfileName());
ce.setId(ce.getId()+":"+e.getProfileName());
}
}
}
if (Utilities.existsInList(ce.getPath(), "Element.extension", "DomainResource.extension", "DomainResource.modifierExtension") && !ce.hasSlicing() && !ce.hasSliceName()) {
ce.getSlicing().setDescription("Extensions are always sliced by (at least) url").setRules(SlicingRules.OPEN).addDiscriminator().setType(DiscriminatorType.VALUE).setPath("url");
}
if (!Utilities.noString(inheritedType) && snapshot != SnapShotMode.None) {
ElementDefn inh = definitions.getElementDefn(inheritedType);
buildDefinitionFromElement(path, ce, inh, ap, p, inheritedType, definitions.getBaseResources().containsKey(inheritedType) && definitions.getBaseResources().get(inheritedType).isInterface());
} else if (path.contains(".") && Utilities.noString(e.typeCode()) && snapshot != SnapShotMode.None) {
addElementConstraints(defType, ce);
}
buildDefinitionFromElement(path, ce, e, ap, p, null, false);
if (!Utilities.noString(e.getStatedType())) {
ToolingExtensions.addStringExtension(ce, "http://hl7.org/fhir/StructureDefinition/structuredefinition-explicit-type-name", e.getStatedType());
}
if (!root) {
if (e.typeCode().startsWith("@")) {
ce.setContentReference("#"+getIdForPath(elements, e.typeCode().substring(1)));
} else if (Utilities.existsInList(path, "Element.id", "Extension.url") || path.endsWith(".id")) {
TypeRefComponent tr = ce.addType();
tr.getFormatCommentsPre().add("Note: special primitive values have a FHIRPath system type. e.g. this is compiler magic (j)");
tr.setCode(Constants.NS_SYSTEM_TYPE+ "String");
if (path.equals("Extension.url")) {
ToolingExtensions.addUriExtension(tr, ToolingExtensions.EXT_FHIR_TYPE, "uri");
} else if (p.getKind() == StructureDefinitionKind.RESOURCE) {
ToolingExtensions.addUriExtension(tr, ToolingExtensions.EXT_FHIR_TYPE, "id");
} else {
ToolingExtensions.addUriExtension(tr, ToolingExtensions.EXT_FHIR_TYPE, "string");
}
} else {
List<TypeRef> expandedTypes = new ArrayList<TypeRef>();
for (TypeRef t : e.getTypes()) {
// Expand any Resource(A|B|C) references
if (t.hasParams() && !Utilities.existsInList(t.getName(), "Reference", "canonical", "CodeableReference")) {
throw new Exception("Only resource types can specify parameters. Path " + path + " in profile " + p.getName());
}
if(t.getParams().size() > 1)
{
if (t.getProfile() != null && t.getParams().size() !=1) {
throw new Exception("Cannot declare profile on a resource reference declaring multiple resource types. Path " + path + " in profile " + p.getName());
}
for (String param : t.getParams()) {
if (definitions.hasLogicalModel(param)) {
for (String pn : definitions.getLogicalModel(param).getImplementations()) {
TypeRef childType = new TypeRef(t.getName());
childType.getParams().add(pn);
childType.getAggregations().addAll(t.getAggregations());
expandedTypes.add(childType);
}
} else {
TypeRef childType = new TypeRef(t.getName());
childType.getParams().add(param);
childType.getAggregations().addAll(t.getAggregations());
expandedTypes.add(childType);
}
}
} else if (t.isWildcardType()) {
// this list is filled out manually because it may be running before the types referred to have been loaded
for (String n : TypesUtilities.wildcardTypes())
expandedTypes.add(new TypeRef(n));
} else if (!t.getName().startsWith("=")) {
if (definitions.isLoaded() && (!definitions.hasResource(t.getName()) && !definitions.hasType(t.getName())
&& !definitions.hasElementDefn(t.getName()) && !definitions.getBaseResources().containsKey(t.getName()) &&!t.getName().equals("xhtml") )) {
throw new Exception("Bad Type '"+t.getName()+"' at "+path+" in profile "+p.getUrl());
}
expandedTypes.add(t);
}
}
if (expandedTypes.isEmpty()) {
if (defType != null)
ce.addType().setCode(defType);
} else for (TypeRef t : expandedTypes) {
String profile = null;
String tc = null;
if (definitions.getConstraints().containsKey(t.getName())) {
ProfiledType pt = definitions.getConstraints().get(t.getName());
tc= pt.getBaseType();
profile = "http://hl7.org/fhir/StructureDefinition/"+pt.getName();
} else {
tc = t.getName();
profile = t.getProfile();
}
TypeRefComponent type = ce.getType(tc);
if (profile == null && t.hasParams()) {
profile = t.getParams().get(0);
}
if (t.getPatterns() != null) {
for (String s : t.getPatterns()) {
type.addExtension("http://hl7.org/fhir/StructureDefinition/elementdefinition-pattern", new CanonicalType("http://hl7.org/fhir/StructureDefinition/"+s));
}
}
if (profile != null) {
if (type.getWorkingCode().equals("Extension")) {
// check that the extension is being used correctly:
StructureDefinition ext = context.getExtensionStructure(null, profile);
if (ext == null) {
throw new Exception("Unable to resolve extension definition: " + profile);
}
boolean srcMod = ext.getSnapshot().getElement().get(0).getIsModifier();
boolean tgtMod = e.isModifier();
if (srcMod && !tgtMod)
throw new Exception("The extension '"+profile+"' is a modifier extension, but is being used as if it is not a modifier extension");
if (!srcMod && tgtMod)
throw new Exception("The extension '"+profile+"' is not a modifier extension, but is being used as if it is a modifier extension");
}
List<String> pr = new ArrayList<>();
if (profile.startsWith("http:") || profile.startsWith("#")) {
pr.add(profile);
} else if (definitions.hasLogicalModel(profile)) {
for (String pn : definitions.getLogicalModel(profile).getImplementations())
pr.add("http://hl7.org/fhir/StructureDefinition/" + pn);
} else
pr.add("http://hl7.org/fhir/StructureDefinition/" + (profile.equals("Any") ? "Resource" : profile));
if (type.getWorkingCode().equals("Reference") || type.getWorkingCode().equals("canonical") || type.getWorkingCode().equals("CodeableReference") ) {
for (String pn : pr) {
type.addTargetProfile(pn);
if (e.hasHierarchy())
ToolingExtensions.addBooleanExtension(type, ToolingExtensions.EXT_HIERARCHY, e.getHierarchy());
}
} else
for (String pn : pr) {
type.addProfile(pn);
}
}
for (String aggregation : t.getAggregations()) {
type.addAggregation(AggregationMode.fromCode(aggregation));
}
}
}
}
String w5 = translateW5(e.getW5());
if (w5 != null)
addMapping(p, ce, "http://hl7.org/fhir/fivews", w5, ap);
if (e.isTranslatable())
ce.addExtension("http://hl7.org/fhir/StructureDefinition/elementdefinition-translatable", new BooleanType(true));
if (!Utilities.noString(e.getOrderMeaning()))
ce.setOrderMeaning(e.getOrderMeaning());
if (e.hasBinding()) {
ce.setBinding(generateBinding(e.getBinding()));
}
if (snapshot != SnapShotMode.None && !e.getElements().isEmpty()) {
// makeExtensionSlice("extension", p, c, e, path);
// if (snapshot == SnapShotMode.Resource) {
// makeExtensionSlice("modifierExtension", p, c, e, path);
// if (!path.contains(".")) {
// c.getElement().add(createBaseDefinition(p, path, definitions.getBaseResources().get("Resource").getRoot().getElementByName("language")));
// c.getElement().add(createBaseDefinition(p, path, definitions.getBaseResources().get("DomainResource").getRoot().getElementByName("text")));
// c.getElement().add(createBaseDefinition(p, path, definitions.getBaseResources().get("DomainResource").getRoot().getElementByName("contained")));
// }
// }
}
if (defaults)
ce.makeBase();
Set<String> containedSlices = new HashSet<String>();
if (snapshot != SnapShotMode.None) {
if (!root && Utilities.noString(e.typeCode())) {
if (snapshot == SnapShotMode.Resource)
defineAncestorElements("BackboneElement", path, snapshot, containedSlices, p, elements, defType, defaults);
else
defineAncestorElements("Element", path, snapshot, containedSlices, p, elements, defType, defaults);
} else if (root && !Utilities.noString(e.typeCode()))
defineAncestorElements(e.typeCode(), path, snapshot, containedSlices, p, elements, defType, defaults);
}
for (ElementDefn child : e.getElements())
defineElement(ap, p, elements, child, path+"."+child.getName(), containedSlices, myParents, snapshot, false, defType, null, defaults);
return ce;
}
private String translateW5(String w5) {
if (w5 == null)
return null;
W5Entry e = definitions.getW5s().get(w5);
return e == null ? null : e.getFiveWs();
}
private String isImplicitTypeConstraint(String path) throws Exception {
if (!path.contains("."))
return null;
String t = path.substring(0, path.indexOf("."));
ElementDefn tt = definitions.getElementDefn(t);
return isImplicitTypeConstraint(tt.getName(), tt, path);
}
private String isImplicitTypeConstraint(String path, ElementDefn tt, String s) {
if (path.equals(s))
return null;
if (path.contains("[x]")) {
String base = path.substring(0, path.indexOf("["));
if (s.startsWith(base) && !s.substring(base.length()).contains("."))
return path;
}
if (s.equals(path+".extension"))
return null;
for (ElementDefn e : tt.getElements()) {
String ans = isImplicitTypeConstraint(path+"."+e.getName(), e, s);
if (ans != null)
return ans;
}
return null;
}
private void buildDefinitionFromElement(String path, ElementDefinition ce, ElementDefn e, Profile ap, StructureDefinition p, String inheritedType, boolean isInterface) throws Exception {
if (!Utilities.noString(e.getComments()))
ce.setComment(preProcessMarkdown(e.getComments(), "Element Comments"));
if (!Utilities.noString(e.getShortDefn()))
ce.setShort(e.getShortDefn());
if (!Utilities.noString(e.getDefinition())) {
ce.setDefinition(preProcessMarkdown(e.getDefinition(), "Element Definition"));
if (!Utilities.noString(e.getShortDefn()))
ce.setShort(e.getShortDefn());
}
if (path.contains(".") && !Utilities.noString(e.getRequirements()))
ce.setRequirements(preProcessMarkdown(e.getRequirements(), "Element Requirements"));
if (e.hasMustSupport())
ce.setMustSupport(e.isMustSupport());
if (!Utilities.noString(e.getMaxLength()))
ce.setMaxLength(Integer.parseInt(e.getMaxLength()));
// no purpose here
if (e.getMinCardinality() != null)
ce.setMin(e.getMinCardinality());
if (e.getMaxCardinality() != null)
ce.setMax(e.getMaxCardinality() == Integer.MAX_VALUE ? "*" : e.getMaxCardinality().toString());
// we don't know mustSupport here
if (e.hasModifier())
ce.setIsModifier(e.isModifier());
if (ce.getIsModifier())
ce.setIsModifierReason(e.getModifierReason());
// ce.setConformance(getType(e.getConformance()));
for (Invariant id : e.getStatedInvariants()) {
ce.addCondition(id.getId());
}
ce.setFixed(e.getFixed());
ce.setPattern(e.getPattern());
// ce.setDefaultValue(e.getDefaultValue());
ce.setMeaningWhenMissing(e.getMeaningWhenMissing());
if (e.getExample() != null)
ce.addExample().setLabel("General").setValue(e.getExample());
for (Integer i : e.getOtherExamples().keySet()) {
Extension ex = ce.addExtension();
ex.setUrl("http://hl7.org/fhir/StructureDefinition/structuredefinition-example");
ex.addExtension().setUrl("index").setValue(new StringType(i.toString()));
ex.addExtension().setUrl("exValue").setValue(e.getOtherExamples().get(i));
}
for (String s : e.getAliases())
ce.addAlias(s);
if (e.hasSummaryItem() && ce.getPath().contains("."))
ce.setIsSummaryElement(Factory.newBoolean(e.isSummary()));
for (String n : definitions.getMapTypes().keySet()) {
addMapping(p, ce, n, e.getMapping(n), null);
}
if (ap != null) {
for (String n : ap.getMappingSpaces().keySet()) {
addMapping(p, ce, n, e.getMapping(n), ap);
}
}
ToolingExtensions.addDisplayHint(ce, e.getDisplayHint());
if (!isInterface) {
convertConstraints(e, ce, inheritedType);
}
// we don't have anything to say about constraints on resources
}
private void convertConstraints(ElementDefn e, ElementDefinition ce, String source) throws FHIRException {
for (String in : e.getInvariants().keySet()) {
ElementDefinitionConstraintComponent con = new ElementDefinitionConstraintComponent();
Invariant inv = e.getInvariants().get(in);
con.setKey(inv.getId());
if (!con.hasKey()) {
profileCounter++;
con.setKey("prf-"+Integer.toString(profileCounter ));
}
con.setRequirements(inv.getRequirements());
if (Utilities.noString(inv.getSeverity()))
con.setSeverity(ConstraintSeverity.ERROR);
else if (inv.getSeverity().equals("best-practice")) {
con.setSeverity(ConstraintSeverity.WARNING);
ToolingExtensions.addBooleanExtension(con, ToolingExtensions.EXT_BEST_PRACTICE, true);
if (Utilities.noString(inv.getExplanation()))
throw new FHIRException("Best Practice Invariants need to have an explanation");
con.addExtension().setUrl(ToolingExtensions.EXT_BEST_PRACTICE_EXPLANATION).setValue(new MarkdownType(inv.getExplanation()));
} else
con.setSeverity(ConstraintSeverity.fromCode(inv.getSeverity()));
con.setHuman(inv.getEnglish());
con.setXpath(inv.getXpath());
con.setSource("http://hl7.org/fhir/StructureDefinition/"+source);
if (!"n/a".equals(inv.getExpression()))
con.setExpression(inv.getExpression());
ce.getConstraint().add(con);
}
}
private String getIdForPath(List<ElementDefinition> list, String path) throws Exception {
for (ElementDefinition ed : list)
if (ed.getPath().equals(path))
return ed.getId();
throw new Exception("Unable to resolve "+path);
}
private void processDiscriminator(ElementDefn e, String path, ElementDefinition ce) throws Exception {
ce.setSlicing(new ElementDefinitionSlicingComponent());
ce.getSlicing().setDescription(e.getSliceDescription());
String[] d = e.getDiscriminator().get(0).split("\\|");
if (d.length >= 1)
ce.getSlicing().addDiscriminator(ProfileUtilities.interpretR2Discriminator(d[0].trim(), false));
if (d.length >= 2)
ce.getSlicing().setOrdered(Boolean.parseBoolean(d[1].trim()));
else
ce.getSlicing().setOrdered(false);
if (d.length >= 3)
ce.getSlicing().setRules(SlicingRules.fromCode(d[2].trim()));
else
ce.getSlicing().setRules(SlicingRules.OPEN);
for (int i = 1; i < e.getDiscriminator().size(); i++) { // we've already process the first in the list
String s = e.getDiscriminator().get(i).trim();
if (s.contains("|"))
throw new Exception("illegal discriminator \""+s+"\" at "+path);
ce.getSlicing().addDiscriminator(ProfileUtilities.interpretR2Discriminator(s, false));
}
}
private String actualTypeName(String type) {
if (type.equals("Type"))
return "Element";
if (type.equals("Structure"))
return "BackboneElement";
return type;
}
private void defineAncestorElements(String type, String path, SnapShotMode snapshot, Set<String> containedSlices, StructureDefinition p, List<ElementDefinition> elements, String dt, boolean defaults) throws Exception {
ElementDefn e = definitions.getElementDefn(actualTypeName(type));
if (!Utilities.noString(e.typeCode()))
defineAncestorElements(e.typeCode(), path, snapshot, containedSlices, p, elements, dt, defaults);
if (!definitions.getBaseResources().containsKey(e.getName()) || !definitions.getBaseResources().get(e.getName()).isInterface()) {
for (ElementDefn child : e.getElements()) {
ElementDefinition ed = defineElement(null, p, elements, child, path+"."+child.getName(), containedSlices, new ArrayList<ProfileGenerator.SliceHandle>(), snapshot, false, dt, null, defaults);
if (!ed.hasBase())
ed.setBase(new ElementDefinitionBaseComponent());
ed.getBase().setPath(e.getName()+"."+child.getName());
if (child.getMinCardinality() != null)
ed.getBase().setMin(child.getMinCardinality());
if (child.getMaxCardinality() != null)
ed.getBase().setMax(child.getMaxCardinality() == Integer.MAX_VALUE ? "*" : child.getMaxCardinality().toString());
if (snapshot == SnapShotMode.DataType && ed.getPath().endsWith(".extension") && !ed.hasSlicing())
ed.getSlicing().setDescription("Extensions are always sliced by (at least) url").setRules(SlicingRules.OPEN).addDiscriminator().setType(DiscriminatorType.VALUE).setPath("url");
}
}
}
/*
* // resource
// domain resource
for (ElementDefn child : definitions.getBaseResources().get("DomainResource").getRoot().getElements())
defineElement(null, p, p.getSnapshot(), child, r.getRoot().getName()+"."+child.getName(), containedSlices, new ArrayList<ProfileGenerator.SliceHandle>(), SnapShotMode.Resource);
*/
/*
private String registerMapping(ConformancePackage ap, StructureDefinition p, String m) {
for (StructureDefinitionMappingComponent map : p.getMapping()) {
if (map.getUri().equals(m))
return map.getIdentity();
}
StructureDefinitionMappingComponent map = new StructureDefinitionMappingComponent();
MappingSpace space = definitions.getMapTypes().get(m);
if (space != null)
map.setIdentity(space.getId());
else
map.setIdentity("m" + Integer.toString(p.getMapping().size()+1));
map.setUri(m);
String name = ap.metadata(m+"-name");
if (Utilities.noString(name) && space != null)
name = space.getTitle();
if (!Utilities.noString(name))
map.setName(name);
String comments = ap.metadata(m+"-comments");
if (Utilities.noString(comments) && space != null)
comments = space.getPreamble();
if (!Utilities.noString(comments))
map.setComments(comments);
return map.getIdentity();
}
*/
private ElementDefinition addElementConstraint(StructureDefinition sd, ElementDefinition ed) {
if (!ed.getPath().contains(".") && sd.getKind() == StructureDefinitionKind.RESOURCE)
return ed;
if (hasSystemType(ed))
return ed;
if (isResource(ed))
return ed;
if (hasConstraint(ed, "ele-1"))
return ed;
ElementDefinitionConstraintComponent inv = ed.addConstraint();
inv.setKey("ele-1");
inv.setSeverity(ConstraintSeverity.ERROR);
inv.setHuman("All FHIR elements must have a @value or children");
inv.setExpression("hasValue() or (children().count() > id.count())");
inv.setXpath("@value|f:*|h:div");
inv.setSource("http://hl7.org/fhir/StructureDefinition/Element");
return ed;
}
private boolean isResource(ElementDefinition ed) {
for (TypeRefComponent t : ed.getType()) {
if ("Resource".equals(t.getCode()))
return true;
}
return false;
}
private ElementDefinition addExtensionConstraint(StructureDefinition sd, ElementDefinition ed) {
if (!typeIsExtension(ed))
return ed;
if (hasConstraint(ed, "ext-1"))
return ed;
ElementDefinitionConstraintComponent inv = ed.addConstraint();
inv.setKey("ext-1");
inv.setSeverity(ConstraintSeverity.ERROR);
inv.setHuman("Must have either extensions or value[x], not both");
inv.setExpression("extension.exists() != value.exists()");
inv.setXpath("exists(f:extension)!=exists(f:*[starts-with(local-name(.), \"value\")])");
inv.setSource("http://hl7.org/fhir/StructureDefinition/Extension");
return ed;
}
private boolean typeIsExtension(ElementDefinition ed) {
return ed.getType().size() == 1 && ed.getType().get(0).getCode().equals("Extension");
}
private boolean hasConstraint(ElementDefinition ed, String id) {
for (ElementDefinitionConstraintComponent inv : ed.getConstraint()) {
if (id.equals(inv.getKey()))
return true;
}
return false;
}
private ElementDefinition makeExtensionSlice(String extensionName, StructureDefinition p, StructureDefinitionSnapshotComponent c, ElementDefn e, String path) throws URISyntaxException, Exception {
ElementDefinition ex = createBaseDefinition(p, path, definitions.getBaseResources().get("DomainResource").getRoot().getElementByName(definitions, extensionName, false, false, null));
c.getElement().add(ex);
if (!ex.hasBase())
ex.setBase(new ElementDefinitionBaseComponent());
ex.getBase().setPath("Element.extension");
ex.getBase().setMin(0);
ex.getBase().setMax("*");
ElementDefinitionConstraintComponent inv = ex.addConstraint();
inv.setKey("ext-1");
inv.setSeverity(ConstraintSeverity.ERROR);
inv.setHuman("Must have either extensions or value[x], not both");
inv.setExpression("extension.exists() != value.exists()");
inv.setXpath("exists(f:extension)!=exists(f:*[starts-with(local-name(.), 'value')])");
inv.setSource("http://hl7.org/fhir/StructureDefinition/Extension");
return ex;
}
private void addMapping(StructureDefinition p, ElementDefinition definition, String target, String map, Profile pack) {
if (!Utilities.noString(map)) {
String id;
if (pack != null && pack.getMappingSpaces().containsKey(target))
id = pack.getMappingSpaces().get(target).getId();
else
id = definitions.getMapTypes().get(target).getId();
if (!mappingExists(p, id)) {
StructureDefinitionMappingComponent pm = new StructureDefinitionMappingComponent();
p.getMapping().add(pm);
pm.setIdentity(id);
pm.setUri(target);
if (pack != null && pack.getMappingSpaces().containsKey(target))
pm.setName(pack.getMappingSpaces().get(target).getTitle());
else
pm.setName(definitions.getMapTypes().get(target).getTitle());
}
boolean found = false;
for (ElementDefinitionMappingComponent m : definition.getMapping()) {
found = found || (m.getIdentity().equals(id) && m.getMap().equals(map));
}
if (!found) {
ElementDefinitionMappingComponent m = new ElementDefinitionMappingComponent();
m.setIdentity(id);
m.setMap(map);
definition.getMapping().add(m);
}
}
}
private boolean mappingExists(StructureDefinition p, String id) {
for (StructureDefinitionMappingComponent t : p.getMapping()) {
if (id.equals(t.getIdentity()))
return true;
}
return false;
}
private ElementDefinition createBaseDefinition(StructureDefinition p, String path, ElementDefn src) throws Exception {
ElementDefinition ce = new ElementDefinition(true, ElementDefinition.NOT_MODIFIER, ElementDefinition.NOT_IN_SUMMARY);
ce.setId(path+"."+src.getName());
ce.setPath(path+"."+src.getName());
ce.setShort(src.getShortDefn());
ce.setDefinition(preProcessMarkdown(src.getDefinition(), "ELement Definition"));
ce.setComment(preProcessMarkdown(src.getComments(), "Element Comments"));
ce.setRequirements(preProcessMarkdown(src.getRequirements(), "Element Reqiurements"));
for (String a : src.getAliases())
ce.addAlias(a);
ce.setMin(src.getMinCardinality());
if (src.getMaxCardinality() != null)
ce.setMax(src.getMaxCardinality() == Integer.MAX_VALUE ? "*" : src.getMaxCardinality().toString());
ce.getType(src.typeCode());
// this one should never be used
if (!Utilities.noString(src.getTypes().get(0).getProfile())) {
if (ce.getType().equals("Reference") || ce.getType().equals("canonical") || ce.getType().equals("CodeableReference") ) throw new Error("Should not happen");
ce.getType().get(0).addProfile(src.getTypes().get(0).getProfile());
}
// todo? conditions, constraints, binding, mapping
if (src.hasModifier())
ce.setIsModifier(src.isModifier());
if (ce.getIsModifier())
ce.setIsModifierReason(src.getModifierReason());
if (src.hasSummaryItem())
ce.setIsSummaryElement(Factory.newBoolean(src.isSummary()));
for (Invariant id : src.getStatedInvariants())
ce.addCondition(id.getId());
return ce;
}
public ConstraintStructure wrapProfile(StructureDefinition profile) throws Exception {
return new ConstraintStructure(profile, definitions.getUsageIG((String) profile.getUserData(ToolResourceUtilities.NAME_SPEC_USAGE), "generating profile "+profile.getId()), wg(ToolingExtensions.readStringExtension(profile, ToolingExtensions.EXT_WORKGROUP)), fmm(profile), profile.getExperimental());
}
private String fmm(StructureDefinition ed) {
return ToolingExtensions.readStringExtension(ed, ToolingExtensions.EXT_FMM_LEVEL); // default fmm level
}
private WorkGroup wg(String code) {
return definitions.getWorkgroups().get(code);
}
public void convertElements(ElementDefn src, StructureDefinition ed, String path) throws Exception {
ElementDefinition dst = new ElementDefinition();
if (!ed.hasDifferential())
ed.setDifferential(new StructureDefinitionDifferentialComponent());
ed.getDifferential().getElement().add(dst);
String thisPath = path == null ? "Extension" : path;
dst.setId(thisPath);
dst.setPath(thisPath);
if (!Utilities.noString(src.getProfileName()))
dst.setSliceName(src.getProfileName());
dst.setShort(src.getShortDefn());
dst.setDefinition(preProcessMarkdown(src.getDefinition(), "Element Definition"));
dst.setComment(preProcessMarkdown(src.getComments(), "Element Comments"));
if (src.getMaxCardinality() != null) {
if (src.getMaxCardinality() == Integer.MAX_VALUE)
dst.setMax("*");
else
dst.setMax(src.getMaxCardinality().toString());
}
if (src.getMinCardinality() != null)
dst.setMin(src.getMinCardinality());
if (src.getFixed() != null)
dst.setFixed(src.getFixed());
if (src.hasMustSupport())
dst.setMustSupport(src.isMustSupport());
if (src.hasModifier())
dst.setIsModifier(src.isModifier());
if (dst.getIsModifier())
dst.setIsModifierReason(src.getModifierReason());
if (src.hasSummaryItem() && dst.getPath().contains("."))
dst.setIsSummaryElement(Factory.newBoolean(src.isSummary()));
for (Invariant id : src.getStatedInvariants())
dst.addCondition(id.getId());
// dDst.
for (TypeRef t : src.getTypes()) {
if (t.hasParams()) {
for (String tp : t.getParams()) {
if (definitions.hasLogicalModel(tp)) {
for (String tpn : definitions.getLogicalModel(tp).getImplementations()) {
ElementDefinition.TypeRefComponent type = dst.getType(t.getName());
String pr = "http://hl7.org/fhir/StructureDefinition/"+tpn;
type.addTargetProfile(pr);
}
} else {
ElementDefinition.TypeRefComponent type = dst.getType(t.getName());
String pr = t.hasProfile() ? t.getProfile() :
// this should only happen if t.getParams().size() == 1
"http://hl7.org/fhir/StructureDefinition/"+(tp.equals("Any") ? "Resource" : tp);
if (type.getWorkingCode().equals("Reference") || type.getWorkingCode().equals("canonical") || type.getWorkingCode().equals("CodeableReference") )
type.addTargetProfile(pr);
else
type.addProfile(pr);
}
}
} else if (t.isWildcardType()) {
for (String n : TypesUtilities.wildcardTypes())
dst.getType(n);
} else {
if (definitions != null && definitions.getConstraints().containsKey(t.getName())) {
ProfiledType ct = definitions.getConstraints().get(t.getName());
ElementDefinition.TypeRefComponent type = dst.getType(ct.getBaseType());
type.addProfile("http://hl7.org/fhir/StructureDefinition/"+ct.getName());
} else if ("Extension.url".equals(path)) {
// juat don't populate it
// ElementDefinition.TypeRefComponent tt = dst.addType();
// tt.setCodeElement(new UriType());
// tt.getFormatCommentsPre().add("Note: special primitive values do not have an assigned type. e.g. this is compiler magic. XML, JSON and RDF types provided by extension");
// ToolingExtensions.addStringExtension(tt.getCodeElement(), ToolingExtensions.EXT_JSON_TYPE, "string");
// ToolingExtensions.addStringExtension(tt.getCodeElement(), ToolingExtensions.EXT_XML_TYPE, "xs:anyURI");
// ToolingExtensions.addStringExtension(tt.getCodeElement(), ToolingExtensions.EXT_RDF_TYPE, "xs:anyURI");
} else {
ElementDefinition.TypeRefComponent type = dst.getType(t.getName());
if (t.hasProfile())
if (type.getWorkingCode().equals("Reference") || type.getWorkingCode().equals("CodeableReference"))
type.addTargetProfile(t.getProfile());
else
type.addProfile(t.getProfile());
}
}
}
if (definitions != null) { // igtodo - catch this
for (String mu : definitions.getMapTypes().keySet()) {
if (src.hasMapping(mu)) {
addMapping(ed, dst, mu, src.getMapping(mu), null);
}
}
}
for (String in : src.getInvariants().keySet()) {
ElementDefinitionConstraintComponent con = new ElementDefinitionConstraintComponent();
Invariant inv = src.getInvariants().get(in);
con.setKey(inv.getId());
if (!con.hasKey()) {
extensionCounter++;
con.setKey("exd-"+Integer.toString(extensionCounter));
}
con.setRequirements(inv.getRequirements());
if (Utilities.noString(inv.getSeverity()))
con.setSeverity(ConstraintSeverity.ERROR);
else
con.setSeverity(ConstraintSeverity.fromCode(inv.getSeverity()));
con.setHuman(inv.getEnglish());
con.setXpath(inv.getXpath());
if (!"n/a".equals(inv.getExpression()))
con.setExpression(inv.getExpression());
dst.getConstraint().add(con);
}
if (src.hasBinding())
dst.setBinding(generateBinding(src.getBinding()));
if (src.getElements().isEmpty()) {
if (path == null)
throw new Exception("?error parsing extension");
} else {
ElementDefn url = src.getElements().get(0);
if (!url.getName().equals("url"))
throw new Exception("first child of extension should be 'url', not "+url.getName()+" for structure definition "+ed.getUrl());
convertElements(url, ed, thisPath+".url");
// this pair might leave elements out of order, but we're going to sort them later
if (!hasValue(src)) {
ElementDefn value = new ElementDefn();
value.setName("value[x]");
value.setMinCardinality(0);
value.setMaxCardinality(0);
convertElements(value, ed, thisPath+".value[x]");
} else {
ElementDefn ext = new ElementDefn();
ext.setName("extension"); // can't have an extension if you have a value
ext.setMaxCardinality(0);
convertElements(ext, ed, thisPath+".extension");
}
if (src.getElements().size() == 2 &&
src.getElements().get(0).getName().equals("url") &&
src.getElements().get(1).getName().equals("value[x]")) {
ElementDefn value = src.getElements().get(1);
value.setMinCardinality(1);
convertElements(value, ed, thisPath+".value[x]");
} else {
for (ElementDefn child : src.getElements()) {
if (child != url) {
if (child.getName().startsWith("value") && !child.getName().startsWith("valueSet"))
convertElements(child, ed, thisPath+"."+child.getName());
else {
if (child.getElements().size() == 0 || !child.getElements().get(0).getName().equals("url")) {
ElementDefn childUrl = new ElementDefn();
childUrl.setName("url");
childUrl.setXmlAttribute(true);
childUrl.getTypes().add(new TypeRef("uri"));
childUrl.setFixed(new UriType(child.getName()));
child.getElements().add(0, childUrl);
}
if (!hasValue(child)) {
ElementDefn value = new ElementDefn();
value.setName("value[x]");
value.setMinCardinality(0);
value.setMaxCardinality(0);
child.getElements().add(value);
}
convertElements(child, ed, thisPath+".extension");
}
}
}
}
}
}
private boolean hasValue(ElementDefn child) {
for (ElementDefn v : child.getElements()) {
if (v.getName().startsWith("value") && !child.getName().startsWith("valueSet"))
return true;
}
return false;
}
public OperationDefinition generate(String name, String id, String resourceName, Operation op, ResourceDefn rd) throws Exception {
OperationDefinition opd = new OperationDefinition();
op.setResource(opd);
if (Utilities.noString(op.getFmm()))
ToolingExtensions.addIntegerExtension(opd, ToolingExtensions.EXT_FMM_LEVEL, Integer.parseInt(rd.getFmmLevel()));
else
ToolingExtensions.addIntegerExtension(opd, ToolingExtensions.EXT_FMM_LEVEL, Integer.parseInt(op.getFmm()));
ToolingExtensions.setStandardsStatus(opd, op.getStandardsStatus() == null ? rd.getStatus() : op.getStandardsStatus(), op.getNormativeVersion());
opd.setId(FormatUtilities.makeId(id));
opd.setUrl("http://hl7.org/fhir/OperationDefinition/"+id);
opd.setName(op.getTitle());
opd.setVersion(Constants.VERSION);
opd.setPublisher("HL7 (FHIR Project)");
opd.addContact().getTelecom().add(org.hl7.fhir.r5.model.Factory.newContactPoint(ContactPointSystem.URL, "http://hl7.org/fhir"));
opd.getContact().get(0).getTelecom().add(org.hl7.fhir.r5.model.Factory.newContactPoint(ContactPointSystem.EMAIL, "fhir@lists.hl7.org"));
opd.setDescription(preProcessMarkdown(op.getDoco(), "Operation Documentation"));
opd.setStatus(op.getStandardsStatus() == StandardsStatus.NORMATIVE ? PublicationStatus.ACTIVE : PublicationStatus.DRAFT);
opd.setDate(genDate.getTime());
if (op.getKind().toLowerCase().equals("operation"))
opd.setKind(OperationKind.OPERATION);
else if (op.getKind().toLowerCase().equals("query"))
opd.setKind(OperationKind.QUERY);
else {
throw new Exception("Unrecognized operation kind: '" + op.getKind() + "' for operation " + name);
}
opd.setCode(op.getName());
opd.setComment(preProcessMarkdown(op.getFooter(), "Operation Comments"));
opd.setSystem(op.isSystem());
opd.addResource(resourceName);
opd.setType(op.isType());
opd.setInstance(op.isInstance());
if (op.getIdempotent() == null)
throw new Error("Operation "+opd.getId()+" is not marked as Idempotent or not");
for (OperationParameter p : op.getParameters()) {
produceOpParam(op.getName(), opd.getParameter(), p, null);
}
NarrativeGenerator gen = new NarrativeGenerator("", "", context);
gen.generate(opd, null);
return opd;
}
private void produceOpParam(String path, List<OperationDefinitionParameterComponent> opd, OperationParameter p, OperationParameterUse defUse) throws Exception {
OperationDefinitionParameterComponent pp = new OperationDefinitionParameterComponent();
pp.setName(p.getName());
if (p.getUse().equals("in"))
pp.setUse(OperationParameterUse.IN);
else if (p.getUse().equals("out"))
pp.setUse(OperationParameterUse.OUT);
else if (path.contains("."))
pp.setUse(defUse);
else
throw new Exception("Unable to determine parameter use: "+p.getUse()+" at "+path+"."+p.getName()); // but this is validated elsewhere
pp.setDocumentation(preProcessMarkdown(p.getDoc(), "Operation Parameter Doco"));
pp.setMin(p.getMin());
pp.setMax(p.getMax());
if (p.getBs() != null) {
if (p.getBs().hasMax())
throw new Error("Max binding not handled yet");
pp.setBinding(new OperationDefinitionParameterBindingComponent().setStrength(p.getBs().getStrength()).setValueSet(buildValueSetReference(p.getBs())));
}
if (!Utilities.noString(p.getProfile())) {
pp.addTargetProfile(p.getProfile());
}
opd.add(pp);
if (p.getFhirType().equals("Tuple")) {
for (OperationParameter part : p.getParts()) {
produceOpParam(path+"."+p.getName(), pp.getPart(), part, pp.getUse());
}
} else {
List<TypeRef> trs = new TypeParser().parse(p.getFhirType(), false, null, null, false);
if (trs.size() > 1) {
if (p.getSearchType() != null)
pp.setSearchType(SearchParamType.fromCode(p.getSearchType()));
pp.setType(Enumerations.FHIRAllTypes.fromCode("Element"));
for (TypeRef tr : trs) {
pp.addExtension(ToolingExtensions.EXT_ALLOWED_TYPE, new UriType(tr.getName()));
if (tr.getParams().size() > 0)
throw new Error("Multiple types for an operation parameter, where one is a reference, is not supported by the build tools");
}
} else {
TypeRef tr = trs.get(0);
if (definitions.getConstraints().containsKey(tr.getName())) {
ProfiledType pt = definitions.getConstraints().get(tr.getName());
pp.setType(Enumerations.FHIRAllTypes.fromCode(pt.getBaseType().equals("*") ? "Type" : pt.getBaseType()));
pp.addTargetProfile("http://hl7.org/fhir/StructureDefinition/"+pt.getName());
} else {
if (p.getSearchType() != null)
pp.setSearchType(SearchParamType.fromCode(p.getSearchType()));
pp.setType(Enumerations.FHIRAllTypes.fromCode(tr.getName().equals("*") ? "Type" : tr.getName()));
if (tr.getParams().size() == 1 && !tr.getParams().get(0).equals("Any"))
pp.addTargetProfile("http://hl7.org/fhir/StructureDefinition/"+tr.getParams().get(0));
}
}
}
}
private void checkHasTypes(StructureDefinition p) {
for (ElementDefinition ed : p.getSnapshot().getElement()) {
if (ed.getPath().contains(".")) {
if (!ed.hasType() && !ed.hasContentReference() && !(ed.getPath().equals("Resource") || ed.getPath().equals("Element")) && !ed.hasRepresentation())
throw new Error("No Type on "+ed.getPath());
} else {
if (ed.hasType())
throw new Error("Type on "+ed.getPath());
}
}
}
public StructureDefinition generateLogicalModel(ImplementationGuideDefn igd, ResourceDefn r) throws Exception {
StructureDefinition p = new StructureDefinition();
p.setId(r.getRoot().getName());
p.setUrl("http://hl7.org/fhir/StructureDefinition/"+ r.getRoot().getName());
p.setKind(StructureDefinitionKind.LOGICAL);
p.setAbstract(false);
p.setUserData("filename", r.getName().toLowerCase());
p.setUserData("path", igd.getPrefix()+ r.getName().toLowerCase()+".html");
p.setTitle(r.getName());
p.setFhirVersion(version);
p.setVersion(version.toCode());
p.setType(r.getRoot().getName());
ToolingExtensions.setStandardsStatus(p, r.getStatus(), null);
ToolResourceUtilities.updateUsage(p, igd.getCode());
p.setName(r.getRoot().getName());
p.setPublisher("Health Level Seven International"+(r.getWg() == null ? " "+igd.getCommittee() : " ("+r.getWg().getName()+")"));
p.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.URL, "http://hl7.org/fhir"));
if (r.getWg() != null) {
p.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.URL, r.getWg().getUrl()));
ToolingExtensions.setCodeExtension(p, ToolingExtensions.EXT_WORKGROUP, r.getWg().getCode());
}
p.setDescription("Logical Model: "+r.getDefinition());
p.setPurpose(r.getRoot().getRequirements());
if (!p.hasPurpose())
p.setPurpose(r.getRoot().getRequirements());
p.setDate(genDate.getTime());
p.setStatus(PublicationStatus.fromCode("draft")); // DSTU
Set<String> containedSlices = new HashSet<String>();
// first, the differential
p.setSnapshot(new StructureDefinitionSnapshotComponent());
defineElement(null, p, p.getSnapshot().getElement(), r.getRoot(), r.getRoot().getName(), containedSlices, new ArrayList<ProfileGenerator.SliceHandle>(), SnapShotMode.None, true, "Element", "Element", true);
addElementConstraintToSnapshot(p);
XhtmlNode div = new XhtmlNode(NodeType.Element, "div");
div.addText("to do");
p.setText(new Narrative());
p.getText().setStatus(NarrativeStatus.GENERATED);
p.getText().setDiv(div);
return p;
}
}
| 46.675806 | 303 | 0.662652 |
78fc1374294c59e71b44ad90aa0d21df85f1ffac | 3,757 | /*
* The MIT License
*
* Copyright 2017 yasshi2525 <https://twitter.com/yasshi2525>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.rushhourgame;
import java.io.Serializable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* エラー情報を格納するBean.
* @author yasshi2525 (https://twitter.com/yasshi2525)
*/
public class ErrorMessage implements Serializable{
private static final long serialVersionUID = 1L;
protected String titleId;
protected List<String> titleParams = new ArrayList<>();
protected String detailId;
protected List<String> detailParams = new ArrayList<>();
protected String actionId;
protected List<String> actionParams = new ArrayList<>();
public static final String NO_CONTENTS = "No Contents";
public ErrorMessage() {
this(null, null, null);
}
public ErrorMessage(String titleId, String detailId, String actionId) {
this.titleId = titleId;
this.detailId = detailId;
this.actionId = actionId;
}
public String buildTitle(RushHourResourceBundle prop, Locale locale) {
if (prop == null || titleId == null) {
return NO_CONTENTS;
}
return MessageFormat.format(prop.get(titleId, locale), titleParams.toArray());
}
public String buildDetail(RushHourResourceBundle prop, Locale locale) {
if (prop == null || detailId == null) {
return NO_CONTENTS;
}
return MessageFormat.format(prop.get(detailId, locale), detailParams.toArray());
}
public String buildAction(RushHourResourceBundle prop, Locale locale) {
if (prop == null || actionId == null) {
return NO_CONTENTS;
}
return MessageFormat.format(prop.get(actionId, locale), actionParams.toArray());
}
public String getTitleId() {
return titleId;
}
public void setTitleId(String titleId) {
this.titleId = titleId;
}
public List<String> getTitleParams() {
return titleParams;
}
public String getDetailId() {
return detailId;
}
public void setDetailId(String detailId) {
this.detailId = detailId;
}
public List<String> getDetailParams() {
return detailParams;
}
public String getActionId() {
return actionId;
}
public void setActionId(String actionId) {
this.actionId = actionId;
}
public List<String> getActionParams() {
return actionParams;
}
@Override
public String toString() {
return "ErrorMessage{" + "titleId=" + titleId + ", detailId=" + detailId + ", actionId=" + actionId + '}';
}
}
| 31.308333 | 114 | 0.678733 |
dd546f8fe957125bb5a51b19fee1ee8e5e71ba29 | 2,794 | package uk.gov.hmcts.ethos.replacement.docmosis.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import uk.gov.hmcts.et.common.model.ccd.CaseDetails;
import uk.gov.hmcts.ethos.replacement.docmosis.helpers.DynamicListHelper;
import uk.gov.hmcts.ethos.replacement.docmosis.helpers.dynamiclists.DynamicJudgements;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.util.Objects;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static uk.gov.hmcts.ethos.replacement.docmosis.helpers.dynamiclists.DynamicJudgements.NO_HEARINGS;
class JudgmentValidationServiceTest {
private JudgmentValidationService judgmentValidationService;
private CaseDetails caseDetails1;
@BeforeEach
void setup() throws Exception {
judgmentValidationService = new JudgmentValidationService();
caseDetails1 = generateCaseDetails("caseDetailsTest1.json");
}
private CaseDetails generateCaseDetails(String jsonFileName) throws Exception {
String json = new String(Files.readAllBytes(Paths.get(Objects.requireNonNull(getClass().getClassLoader()
.getResource(jsonFileName)).toURI())));
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(json, CaseDetails.class);
}
@Test
void populateJudgmentDateOfHearingTest() throws ParseException {
DynamicJudgements.dynamicJudgements(caseDetails1.getCaseData());
caseDetails1.getCaseData().getJudgementCollection().get(0).getValue().getDynamicJudgementHearing().setValue(caseDetails1.getCaseData().getJudgementCollection().get(0).getValue().getDynamicJudgementHearing().getListItems().get(0));
judgmentValidationService.validateJudgments(caseDetails1.getCaseData());
assertEquals("2019-11-01", caseDetails1.getCaseData().getJudgementCollection().get(0).getValue().getJudgmentHearingDate());
}
@Test
void populateJudgmentZeroHearings() throws ParseException {
var caseData = caseDetails1.getCaseData();
caseData.setHearingCollection(null);
DynamicJudgements.dynamicJudgements(caseData);
var dynamicValue = DynamicListHelper.getDynamicValue(NO_HEARINGS);
assertEquals(dynamicValue, caseData.getJudgementCollection().get(0).getValue().getDynamicJudgementHearing().getListItems().get(0));
judgmentValidationService.validateJudgments(caseDetails1.getCaseData());
assertNull(caseData.getJudgementCollection().get(0).getValue().getDynamicJudgementHearing());
assertNull(caseData.getJudgementCollection().get(0).getValue().getJudgmentHearingDate());
}
}
| 47.355932 | 238 | 0.774159 |
4e3794ededf58d64578316bb5c27c74df565e018 | 177 | package org.loomdev.api.entity.animal;
import org.loomdev.api.entity.monster.WaterAnimal;
/**
* Represents a Squid entity.
*/
public interface Squid extends WaterAnimal {
}
| 17.7 | 50 | 0.762712 |
7f9bbc087364f7ab5475d9a365ac9b75d2805c3e | 5,335 | package com.makotan.tools;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.*;
/**
* User: kuroeda.makoto
* Date: 13/11/13
* Time: 15:54
*/
public class LoadFromTemplate {
private Logger logger = LoggerFactory.getLogger(getClass());
public Template loadTemplate(String fileName) {
try(
FileInputStream fis = new FileInputStream(fileName)
) {
return loadTemplate(fis);
} catch (FileNotFoundException e) {
logger.error("file not found " + fileName , e);
} catch (IOException e) {
logger.error("io error " + fileName , e);
}
return null;
}
public Template loadTemplate(InputStream template) {
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode jsonNode = mapper.readTree(template);
return processNode(jsonNode);
} catch (IOException e) {
logger.error("format error " , e);
}
return null;
}
Template processNode(JsonNode node) {
Template template = new Template();
processNodeList(node , template.getParameters() , "Parameters");
logger.debug("Parameters {}" , template.getParameters());
JsonNode mappings = node.findPath("Mappings");
processNodeList(node, template.getMappings(), "Mappings");
logger.debug("Mappings {}" , template.getMappings());
JsonNode conditions = node.findPath("Conditions");
processNodeList(node, template.getConditions(), "Conditions");
logger.debug("Conditions {}" , template.getConditions());
JsonNode resources = node.findPath("Resources");
processNodeList(node, template.getResources(), "Resources");
logger.debug("Resources {}" , template.getResources());
JsonNode outputs = node.findPath("Outputs");
processNodeList(node, template.getOutputs(), "Outputs");
logger.debug("Outputs {}" , template.getOutputs());
return template;
}
void processNodeList(JsonNode node , List<Node> nodeList , String typeName) {
JsonNode parameters = node.findPath(typeName);
//logger.debug("{} {}" , typeName , parameters.toString());
Iterator<Map.Entry<String,JsonNode>> fields = parameters.fields();
while (fields.hasNext()) {
Map.Entry<String,JsonNode> entry = fields.next();
entry.getKey();
JsonNode value = entry.getValue();
Node pnode = new Node();
pnode.setName(entry.getKey());
pnode.setPosition(typeName);
if (value.findValue("Type") != null) {
pnode.setTypeName(value.findValue("Type").asText());
}
nodeList.add(pnode);
List<Edge> edgeList = traverseFindRefs(value);
for (Edge e : edgeList) {
e.setFromName(entry.getKey());
pnode.getEdgeList().add(e);
}
}
}
List<Edge> traverseFindRefs(JsonNode node) {
List<Edge> edgeList = new ArrayList<>();
Iterator<Map.Entry<String,JsonNode>> fields = node.fields();
while (fields.hasNext()) {
Map.Entry<String,JsonNode> entry = fields.next();
JsonNode child = entry.getValue();
//logger.debug("child {} value {}" , entry.getKey() , child);
if (child.asToken() == JsonToken.VALUE_STRING) {
logger.debug("child {} value {}" , entry.getKey() , child.asText());
addEdge(edgeList , entry.getKey() , child.asText());
}
edgeList.addAll(traverseFindRefs(child));
if (child.isArray()) {
Iterator<JsonNode> elements = child.elements();
while (elements.hasNext()) {
JsonNode n = elements.next();
if (n.asToken() == JsonToken.VALUE_STRING) {
logger.debug("child {} value {}" , entry.getKey() , n.asText());
addEdge(edgeList , entry.getKey() , n.asText());
}
edgeList.addAll(traverseFindRefs(n));
}
}
}
Iterator<JsonNode> elements = node.elements();
while (elements.hasNext()) {
JsonNode n = elements.next();
edgeList.addAll(traverseFindRefs(n));
}
return edgeList;
}
void addEdge(List<Edge> edgeList , String key , String txt) {
switch (key) {
case "Fn::Base64":
case "Fn::And":
case "Fn::Equals":
case "Fn::If":
case "Fn::Not":
case "Fn::Or":
case "Fn::FindInMap":
case "Fn::GetAZs":
case "Fn::Join":
case "Fn::GetAtt":
case "Fn::Select":
case "DependsOn":
case "Ref":
Edge e = new Edge();
e.setToName(txt);
e.setTitle(key);
edgeList.add(e);
default:
}
}
}
| 35.566667 | 88 | 0.557451 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.