text
stringlengths 10
2.72M
|
|---|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* KMetadataId generated by hbm2java
*/
public class KMetadataId implements java.io.Serializable {
private String metadataid;
private String metadatatype;
public KMetadataId() {
}
public KMetadataId(String metadataid, String metadatatype) {
this.metadataid = metadataid;
this.metadatatype = metadatatype;
}
public String getMetadataid() {
return this.metadataid;
}
public void setMetadataid(String metadataid) {
this.metadataid = metadataid;
}
public String getMetadatatype() {
return this.metadatatype;
}
public void setMetadatatype(String metadatatype) {
this.metadatatype = metadatatype;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof KMetadataId))
return false;
KMetadataId castOther = (KMetadataId) other;
return ((this.getMetadataid() == castOther.getMetadataid()) || (this.getMetadataid() != null
&& castOther.getMetadataid() != null && this.getMetadataid().equals(castOther.getMetadataid())))
&& ((this.getMetadatatype() == castOther.getMetadatatype())
|| (this.getMetadatatype() != null && castOther.getMetadatatype() != null
&& this.getMetadatatype().equals(castOther.getMetadatatype())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getMetadataid() == null ? 0 : this.getMetadataid().hashCode());
result = 37 * result + (getMetadatatype() == null ? 0 : this.getMetadatatype().hashCode());
return result;
}
}
|
package com.senon.leanstoragedemo.util;
/**
* Created by Senon on 2018/9/17.
*/
public class AppConfig {
public static final String TABLE_NAME = "nancy_next_term.db";
public static final int PRICE = 300;//单节课的价格
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.catalogversions.populator;
import de.hybris.platform.catalog.model.CatalogVersionModel;
import de.hybris.platform.cmsfacades.catalogversions.service.PageDisplayConditionService;
import de.hybris.platform.cmsfacades.data.CatalogVersionData;
import de.hybris.platform.cmsfacades.resolvers.sites.SiteThumbnailResolver;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import org.springframework.beans.factory.annotation.Required;
/**
* Populates a {@Link CatalogVersionData} dto from a {@Link CatalogVersionModel} item
*/
public class ContentCatalogVersionModelPopulator implements Populator<CatalogVersionModel, CatalogVersionData>
{
private SiteThumbnailResolver siteThumbnailResolver;
private PageDisplayConditionService pageDisplayConditionService;
@Override
public void populate(final CatalogVersionModel source, final CatalogVersionData target) throws ConversionException
{
getSiteThumbnailResolver().resolveHomepageThumbnailUrl(source)
.ifPresent(thumbnailUrl -> target.setThumbnailUrl(thumbnailUrl));
target.setPageDisplayConditions(getPageDisplayConditionService().getDisplayConditions(source));
}
protected SiteThumbnailResolver getSiteThumbnailResolver()
{
return siteThumbnailResolver;
}
@Required
public void setSiteThumbnailResolver(final SiteThumbnailResolver siteThumbnailResolver)
{
this.siteThumbnailResolver = siteThumbnailResolver;
}
protected PageDisplayConditionService getPageDisplayConditionService()
{
return pageDisplayConditionService;
}
@Required
public void setPageDisplayConditionService(final PageDisplayConditionService pageDisplayConditionService)
{
this.pageDisplayConditionService = pageDisplayConditionService;
}
}
|
package com.example.mvpclean.source;
import com.example.mvpclean.datas.HomeCategory;
import java.util.List;
import androidx.annotation.NonNull;
public interface CategoryDataSource {
interface LoadCallback{
void onDataLoaded(List<HomeCategory> categories);
void onDataNotAvailable();
}
void getCategories(@NonNull LoadCallback callback);
void deleteAllCategories();
void saveCategory(HomeCategory category);
void refreshCategories();
}
|
package cb.fragmentZigbee;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
public class MyThread extends Thread {
{
start(); // 类加载完成后直接启动
}
Handler handler;
@Override
public void run() {
while (true) {
Looper.prepare(); // 创建该线程的Looper对象
handler = new Handler(Looper.myLooper()) {
public void handleMessage(android.os.Message msg) {
Log.i("handleMessage", "" + msg.what);
};
};
Looper.loop(); // 这里是一个死循环
// 此后的代码无法执行
}
}
}
|
package com.nju.edu.cn.entity;
import javax.persistence.*;
import java.util.Date;
/**
* Created by shea on 2018/9/1.
* 一条评论,可以是单纯的评论,也可以是针对某一条评论的回复
*/
@Entity
@Table(name = "`comment`")
public class Comment {
@Id
@Column(name = "`comment_id`")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long commentId;
/**
* 评论者
*/
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "`user_key`")
private User user;
/**
* 评论者ID
*/
@Column(name = "`user_id`")
public Long userId;
/**
* 昵称
*/
@Column(name = "`nickname`")
private String userNickname;
/**
* 头像地址
*/
@Column(name = "`avatar`")
private String userAvatar;
/**
* 被评论的合约ID
*/
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "`contract_key`")
private Contract contract;
@Column(name = "`contract_id`")
private Long contractId;
/**
* 此条评论内容
*/
@Column(name = "`content`")
private String content;
/**
* 被回复的评论ID
*/
@Column(name = "`father_comment_id`")
private Long fatherCommentId;
/**
* 被回复的评论人
*/
@Column(name = "`father_comment_user_id`")
private Long fatherCommentUserId;
/**
* 被回复的评论内容
*/
@Column(name = "`father_comment_content`")
private String fatherCommentContent;
/**
* 被回复的评论人头像URL
*/
@Column(name = "`father_comment_user_avatar`")
private String fatherCommentUserAvatar;
/**
* 被回复的评论人昵称
*/
@Column(name = "`father_user_nickname`")
private String fatherUserNickname;
/**
* 此条评论创建时间
*/
@Column(name = "`create_time`")
private Date createTime;
@OneToOne(mappedBy = "comment")
@JoinColumn(name = "`message_key`")
private Message message;
@Column(name = "`message_id`")
private Long messageId;
public Long getCommentId() {
return commentId;
}
public void setCommentId(Long commentId) {
this.commentId = commentId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
this.setUserId(user.getUserId());
this.setUserNickname(user.getNickname());
this.setUserAvatar(user.getAvatar());
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUserNickname() {
return userNickname;
}
public void setUserNickname(String userNickname) {
this.userNickname = userNickname;
}
public String getUserAvatar() {
return userAvatar;
}
public void setUserAvatar(String userAvatar) {
this.userAvatar = userAvatar;
}
public Contract getContract() {
return contract;
}
public void setContract(Contract contract) {
this.contract = contract;
this.setContractId(contract.getContractId());
}
public Long getContractId() {
return contractId;
}
public void setContractId(Long contractId) {
this.contractId = contractId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public void setFatherComment(Comment fatherComment){
if(fatherComment!=null){
this.setFatherCommentContent(fatherComment.getContent());
this.setFatherCommentId(fatherComment.getCommentId());
this.setFatherCommentUserAvatar(fatherComment.getUserAvatar());
this.setFatherCommentUserId(fatherComment.getUserId());
this.setFatherUserNickname(fatherComment.getUserNickname());
}
}
public Long getFatherCommentId() {
return fatherCommentId;
}
public void setFatherCommentId(Long fatherCommentId) {
this.fatherCommentId = fatherCommentId;
}
public Long getFatherCommentUserId() {
return fatherCommentUserId;
}
public void setFatherCommentUserId(Long fatherCommentUserId) {
this.fatherCommentUserId = fatherCommentUserId;
}
public String getFatherCommentContent() {
return fatherCommentContent;
}
public void setFatherCommentContent(String fatherCommentContent) {
this.fatherCommentContent = fatherCommentContent;
}
public String getFatherCommentUserAvatar() {
return fatherCommentUserAvatar;
}
public void setFatherCommentUserAvatar(String fatherCommentUserAvatar) {
this.fatherCommentUserAvatar = fatherCommentUserAvatar;
}
public String getFatherUserNickname() {
return fatherUserNickname;
}
public void setFatherUserNickname(String fatherUserNickname) {
this.fatherUserNickname = fatherUserNickname;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
public Long getMessageId() {
return messageId;
}
public void setMessageId(Long messageId) {
this.messageId = messageId;
}
}
|
package JavaSwingGUI;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
public class Customers {
private String customerName;
private LocalDate DoB;
private String address;
private String phoneNum;
private String email;
private String paymentInfo;
private boolean active;
private double salesTaxPercentage;
public Customers() {
customerName = "";
DoB = null;
address = "";
phoneNum = "";
email = "";
paymentInfo = "";
active = false;
salesTaxPercentage = 0;
}
public Customers(String customerName, String birthday, String homeAddress, String phoneNumber,
String emailAddress, String payment, boolean active, double salesTaxPercentage) {
this.customerName = customerName;
setDateOfBirth(birthday);
address = homeAddress;
phoneNum = phoneNumber;
email = emailAddress;
paymentInfo = payment;
this.active = active;
this.salesTaxPercentage = salesTaxPercentage;
}
public String getCustomerName() {
return customerName;
}
public String getCustomerAddress() {
return address;
}
public String getCustomerPhoneNumber() {
return phoneNum;
}
public String getCustomerEmail() {
return email;
}
public String getCustomerPaymentInfo() {
return paymentInfo;
}
public LocalDate getDoB() {
return DoB;
}
public Customers getCustomer() {
return this;
}
public String getPhoneNum() {
return phoneNum;
}
public boolean isActive() {
return active;
}
public double getSalesTaxPercentage() {
return salesTaxPercentage;
}
public void setAddress(String address) {
this.address = address;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public void setDoB(LocalDate doB) {
DoB = doB;
}
public void setEmail(String email) {
this.email = email;
}
public void setActive(boolean active) {
this.active = active;
}
public void setPaymentInfo(String paymentInfo) {
this.paymentInfo = paymentInfo;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public void setSalesTaxPercentage(double salesTaxPercentage) {
this.salesTaxPercentage = salesTaxPercentage;
}
public void setDateOfBirth(LocalDate DoB) {
this.DoB = DoB;
}
public void setDateOfBirth(String dateOfBirth) {
this.DoB = LocalDate.parse(dateOfBirth, DateTimeFormatter.ofPattern("MM/dd/yyyy"));
}
public void setCustomer(String customerName, String birthday, String homeAddress, String phoneNumber,
String emailAddress, String payment, boolean active, double salesTaxPercentage) {
this.customerName = customerName;
setDateOfBirth(birthday);
address = homeAddress;
phoneNum = phoneNumber;
email = emailAddress;
paymentInfo = payment;
this.active = active;
this.salesTaxPercentage = salesTaxPercentage;
}
}
|
package main.model.events;
import main.Application;
import main.model.Day;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Created by gijin on 2017-12-06.
*/
public class GameEvent {
@FunctionalInterface
public interface Animation {
public void run(Object[] args);
}
Map<String, Animation> eventsMap;
public GameEvent() {
// wrap in runWithArguments and use a hash map specifying the argument types in an array
// uhhh then use reflection to invoke the named method
eventsMap = new HashMap<>();
eventsMap.put("update",(args) -> Application.getGameData().newValue(Integer.toString(Day.getDay())));
eventsMap.put("updateToText", (args) -> {Application.getGameData().newValue("Hey!"); Application.update();}); // not sure how to add params at this moment... maybe check a params thing? hm
eventsMap.put("replaceText", (args) -> Application.update());
eventsMap.put("crazyNumber", (args) -> {
int rand = new Random().nextInt();
Application.getGameData().newValue(Integer.toString(rand));
Application.update();});
}
public void run(String animationTitle) {
// if arguments is null
run(animationTitle, null);
}
public void run(String animationTitle, Object[] arguments) {
Animation animation = eventsMap.get(animationTitle.trim());
if (animation != null) {
animation.run(arguments);
} // should throw an exception... but okay
System.out.println(animationTitle);
}
}
|
import java.util.List;
public class BinaryNode {
Integer value;
private BinaryNode smaller;
private BinaryNode bigger;
private BinaryNode parent;
public BinaryNode(Integer value) {
this.value = value;
}
public boolean compareData(BinaryNode other) {
if(this.value.equals(other.value) &&
((this.smaller == null && other.smaller == null) || this.smaller.compareData(other.smaller) ) &&
((this.bigger == null && other.bigger == null) || this.bigger.compareData(other.bigger) )
) {
return true;
}
return false;
}
public int size(){
int sizeSmaller = (smaller != null) ? smaller.size() : 0;
int sizeBigger = (bigger != null) ? bigger.size() : 0;
return 1 + sizeSmaller + sizeBigger;
}
public Integer getValue(int index){
BinaryNode node = getNode(index);
return (node != null) ? node.value : null;
}
public BinaryNode getNode(int index) {
if(index > this.size() - 1) {
// exception out of borders
return null;
}
BinaryNode currentNode = getFirstNode();
for(int i=0; i<index; i++) {
currentNode = currentNode.next();
}
return currentNode;
}
public BinaryNode next() {
if(this.bigger != null){
return this.bigger.getFirstNode();
}else{
return getNextByParent(this, this.parent);
}
}
public BinaryNode getNextByParent(BinaryNode node, BinaryNode parent){
if(parent != null) {
if(parent.value > node.value){
return parent;
}else{
if(parent.parent != null){
return getNextByParent(node, parent.parent);
}
}
}
return null;
}
public void setSmaller(BinaryNode smaller){
this.smaller = smaller;
if(smaller != null){
smaller.parent = this;
}
}
public void setBigger(BinaryNode bigger) {
this.bigger = bigger;
if(bigger != null) {
bigger.parent = this;
}
}
public BinaryNode getFirstNode() {
BinaryNode currentNode = this;
while (currentNode.hasSmaller()) {
currentNode = currentNode.smaller;
}
return currentNode;
}
public boolean hasSmaller() {
return this.smaller != null;
}
public String print() {
StringBuilder sb = new StringBuilder();
sb.append(" ( ");
if(smaller != null) {
sb.append(smaller.print());
}
sb.append(value);
if(bigger != null) {
sb.append(bigger.print());
}
sb.append(" ) ");
return sb.toString();
}
@Override
public String toString() {
return "BinaryNode ("+ this.value +")";
}
public BinaryNode getSmaller() {
return smaller;
}
public BinaryNode getBigger() {
return bigger;
}
public BinaryNode getParent() {
return parent;
}
}
|
package com.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.Period;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.User;
import com.dao.Userdao;
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("uname");
String Emailid = request.getParameter("emailid");
String Dob = request.getParameter("dob");
String password = request.getParameter("pass");
PrintWriter out = response.getWriter();
int age = (Integer) request.getAttribute("Age");
User user = new User(username, Emailid, Dob, age, password);
Userdao userdao = new Userdao();
int i = userdao.adduser(user);
if (i > 0) {
redirect(request, response);
out.println("<center><h3>Registered Succesfully</center></h3>");
} else {
redirect(request, response);
out.println("<center><h3>Username already exists</h3></center>");
}
}
private void redirect(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.include(request, response);
}
}
|
package com.android.lvxin.listener;
/**
* @ClassName: OnErrorListener
* @Description: TODO
* @Author: lvxin
* @Date: 18/10/2016 15:12
*/
public interface OnErrorListener {
/**
*
*/
void onError(int what, int extra);
}
|
package com.ubuyquick.vendor;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.QuickContactBadge;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ubuyquick.vendor.adapter.ShopAdapter;
import com.ubuyquick.vendor.auth.LoginActivity;
import com.ubuyquick.vendor.model.Shop;
import com.ubuyquick.vendor.utils.UniversalImageLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "HomeActivity";
private FirebaseAuth mAuth;
private FirebaseFirestore db;
private DocumentReference vendorRef;
private TextView tv_email, tv_name, tv_phone, tv_aadhar, tv_pan, tv_verified, tv_status;
private Button btn_logout, btn_edit_profile, btn_add_shop;
private CircleImageView img_vendor;
private RecyclerView rv_shops;
private ShopAdapter shopAdapter;
private List<Shop> shops;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
initializeViews();
initialize();
}
private void loadShopList() {
shops.clear();
db.collection("vendors").document(mAuth.getCurrentUser().getPhoneNumber().substring(3)).collection("shops")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
shops.add(new Shop(document.get("shop_image_url").toString(),
document.get("shop_name").toString(),
document.get("shop_status").toString(),
document.get("shop_id").toString()));
}
shopAdapter.setShops(shops);
} else {
Toast.makeText(HomeActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
protected void onResume() {
super.onResume();
loadShopList();
}
private void initialize() {
mAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
ImageLoader.getInstance().init(new UniversalImageLoader(this).getConfig());
shopAdapter = new ShopAdapter(this);
rv_shops.setAdapter(shopAdapter);
shops = new ArrayList<>();
vendorRef = db.collection("vendors").document(mAuth.getCurrentUser().getPhoneNumber().substring(3));
vendorRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Map<String, Object> vendor = document.getData();
UniversalImageLoader.setImage(vendor.get("photo_url").toString(), img_vendor);
tv_email.setText(vendor.get("email").toString());
tv_name.setText(vendor.get("name").toString());
tv_phone.setText(vendor.get("phone").toString());
tv_pan.setText(vendor.get("pan_number").toString());
tv_aadhar.setText(vendor.get("aadhar_number").toString());
if ((boolean) vendor.get("verified")) {
tv_verified.setText("Verified Vendor");
} else {
tv_verified.setText("Not Verified");
}
}
}
}
});
btn_logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this);
builder.setMessage("Confirm Log Out?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(HomeActivity.this, LoginActivity.class));
finish();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
}).show();
}
});
btn_edit_profile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(HomeActivity.this, EditProfileActivity.class));
}
});
}
private void initializeViews() {
rv_shops = (RecyclerView) findViewById(R.id.rv_shops);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
tv_aadhar = (TextView) header.findViewById(R.id.tv_aadhar);
tv_name = (TextView) header.findViewById(R.id.tv_vendor_name);
tv_email = (TextView) header.findViewById(R.id.tv_email);
tv_phone = (TextView) header.findViewById(R.id.tv_phone);
tv_pan = (TextView) header.findViewById(R.id.tv_pan);
tv_verified = (TextView) header.findViewById(R.id.tv_verified);
img_vendor = (CircleImageView) header.findViewById(R.id.img_vendor);
btn_edit_profile = (Button) header.findViewById(R.id.btn_edit_profile);
btn_logout = (Button) header.findViewById(R.id.btn_logout);
btn_add_shop = (Button) findViewById(R.id.btn_add_shop);
btn_add_shop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(HomeActivity.this, AddShopActivity.class));
overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left);
}
});
tv_status = (TextView) findViewById(R.id.tv_status);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_logout) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(HomeActivity.this, LoginActivity.class));
finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
|
package enstabretagne.BE.AnalyseSousMarine;
import java.util.HashMap;
import java.util.Random;
import enstabretagne.BE.AnalyseSousMarine.Scenarios.AnalyseSousMarineScenario;
import enstabretagne.BE.AnalyseSousMarine.Scenarios.AnalyseSousMarineScenarioFeatures;
import enstabretagne.BE.AnalyseSousMarine.SimEntity.Artefact.EntityArtefactFeatures;
import enstabretagne.BE.AnalyseSousMarine.SimEntity.Artefact.EntityArtefactInit;
import enstabretagne.BE.AnalyseSousMarine.SimEntity.Bateau.EntityBateauFeature;
import enstabretagne.BE.AnalyseSousMarine.SimEntity.Bateau.EntityBateauInit;
import enstabretagne.BE.AnalyseSousMarine.SimEntity.MouvementSequenceur.EntityMouvementSequenceurFeature;
import enstabretagne.BE.AnalyseSousMarine.SimEntity.MouvementSequenceur.EntityMouvementSequenceurInit;
import enstabretagne.BE.AnalyseSousMarine.SimEntity.Ocean.EntityOceanFeature;
import enstabretagne.BE.AnalyseSousMarine.SimEntity.Ocean.EntityOceanInit;
import enstabretagne.BE.AnalyseSousMarine.SimEntity.SousMarin.EntitySousMarinFeature;
import enstabretagne.BE.AnalyseSousMarine.SimEntity.SousMarin.EntitySousMarinInit;
import enstabretagne.base.math.MoreRandom;
import enstabretagne.base.time.LogicalDateTime;
import enstabretagne.base.time.LogicalDuration;
import enstabretagne.monitor.implementation.MovableState;
import enstabretagne.simulation.components.ScenarioId;
import enstabretagne.simulation.core.IScenario;
import enstabretagne.simulation.core.IScenarioInstance;
import javafx.geometry.Point3D;
import javafx.scene.paint.Color;
public class ScenarioInstanceAnalyseSousMarine implements IScenarioInstance {
@Override
public IScenario getScenarioInstance() {
AnalyseSousMarineScenarioFeatures scenariFeatures = new AnalyseSousMarineScenarioFeatures("BSF");
//Création du navire et des points de passage
HashMap<String,Point3D> positionsCles = new HashMap<String, Point3D>();
positionsCles.put("start", new Point3D(0,0,0));
//Création sous marin
MovableState mstSousMarin = new MovableState(new Point3D(0,0,0), new Point3D(1,1,0), Point3D.ZERO, new Point3D(0,0,45.0), new Point3D(10,5,0.0), Point3D.ZERO);
EntityMouvementSequenceurInit msiSousMarin = new EntityMouvementSequenceurInit("MSI", mstSousMarin, 10, 100,2,8, positionsCles);
EntityMouvementSequenceurFeature featSousMarin = new EntityMouvementSequenceurFeature("MSF");
scenariFeatures.getSousMarins().put(new EntitySousMarinFeature("SousMarinF",5,3,Color.BLACK,featSousMarin), new EntitySousMarinInit("Sous marin Observation", msiSousMarin));
//Création bateau
positionsCles = new HashMap<String, Point3D>();
MovableState mstBateau = new MovableState(new Point3D(10,10,10), new Point3D(0,0,0), Point3D.ZERO, Point3D.ZERO, Point3D.ZERO, Point3D.ZERO);
EntityMouvementSequenceurInit msiBateau = new EntityMouvementSequenceurInit("MSI", mstBateau, 0, 0,0,0, positionsCles);
scenariFeatures.getBateaux().put(new EntityBateauFeature("BateauF",10,6,Color.RED), new EntityBateauInit("Bateau Observation", msiBateau));
// Variation du nombre d'artéfacts entre 30 et 40
int borneSupOcean = 9999;
int borneInfOcean=-10000;
int borneInfEpaisseur = -3000;
int borneSupEpaisseur = 0;
Random rand = new Random();
int nbreArtefact = rand.nextInt(40 - 30+1)+30;
int nbreSphere = (nbreArtefact*60)/100;
int nbreCylindre = (nbreArtefact*30)/100;
int nbreCubique = (nbreArtefact*10)/100;
// Création des artefacts sphériques
positionsCles = new HashMap<String, Point3D>();
for(int i=0;i<nbreSphere;i++)
{
int x = (int)rand.nextInt(borneSupOcean - (borneInfOcean) + 1) + borneInfOcean;
int y= (int) rand.nextInt(borneSupOcean - (borneInfOcean) + 1) + borneInfOcean;
int z = (int) rand.nextInt(borneSupEpaisseur - (borneInfEpaisseur) + 1) + borneInfEpaisseur;
MovableState mstArtefactSphere;
EntityMouvementSequenceurInit msiArtefactSphere;
mstArtefactSphere = new MovableState(new Point3D(x,y,z), Point3D.ZERO, Point3D.ZERO, Point3D.ZERO, Point3D.ZERO, Point3D.ZERO);
msiArtefactSphere= new EntityMouvementSequenceurInit("MSI", mstArtefactSphere, 0, 0,0,0, positionsCles);
scenariFeatures.getArtefacts().put(new EntityArtefactFeatures("Sph 1",5,1,3.0,1), new EntityArtefactInit("Sph "+i,msiArtefactSphere,Color.RED));
}
//Création artéfact cylindre
positionsCles = new HashMap<String, Point3D>();
for(int i=0;i<nbreCylindre;i++)
{
int x = (int)rand.nextInt(borneSupOcean - (borneInfOcean) + 1) + borneInfOcean;
int y= (int) rand.nextInt(borneSupOcean - (borneInfOcean) + 1) + borneInfOcean;
int z = (int) rand.nextInt(borneSupEpaisseur - (borneInfEpaisseur) + 1) + borneInfEpaisseur;
MovableState mstArtefactCubique;
EntityMouvementSequenceurInit msiArtefactCubique;
mstArtefactCubique = new MovableState(new Point3D(x,y,z), Point3D.ZERO, Point3D.ZERO, Point3D.ZERO, Point3D.ZERO, Point3D.ZERO);
msiArtefactCubique= new EntityMouvementSequenceurInit("MSI", mstArtefactCubique, 0, 0,0,0, positionsCles);
scenariFeatures.getArtefacts().put(new EntityArtefactFeatures("Cub 1",5,1,3.0,2), new EntityArtefactInit("Cub "+i,msiArtefactCubique,Color.YELLOW));
}
//Création artéfact cubique
positionsCles = new HashMap<String, Point3D>();
for(int i=0;i<nbreCubique;i++)
{
int x = (int)rand.nextInt(borneSupOcean - (borneInfOcean) + 1) + borneInfOcean;
int y= (int) rand.nextInt(borneSupOcean - (borneInfOcean) + 1) + borneInfOcean;
int z = (int) rand.nextInt(borneSupEpaisseur - (borneInfEpaisseur) + 1) + borneInfEpaisseur;
MovableState mstArtefactCylindre;
EntityMouvementSequenceurInit msiArtefactCyclindre;
mstArtefactCylindre = new MovableState(new Point3D(10*i,0,0), Point3D.ZERO, Point3D.ZERO, Point3D.ZERO, Point3D.ZERO, Point3D.ZERO);
msiArtefactCyclindre= new EntityMouvementSequenceurInit("MSI", mstArtefactCylindre, 0, 0,0,0, positionsCles);
scenariFeatures.getArtefacts().put(new EntityArtefactFeatures("Cyl 1",5,1,3.0,3), new EntityArtefactInit("Cyl "+i,msiArtefactCyclindre,Color.GREEN));
}
//Création du cube noir
positionsCles = new HashMap<String, Point3D>();
for(int i=0;i<1;i++)
{
int x = (int)rand.nextInt(borneSupOcean - (borneInfOcean) + 1) + borneInfOcean;
int y= (int) rand.nextInt(borneSupOcean - (borneInfOcean) + 1) + borneInfOcean;
int z = (int) rand.nextInt(borneSupEpaisseur - (borneInfEpaisseur) + 1) + borneInfEpaisseur;
MovableState mstArtefactCylindre;
EntityMouvementSequenceurInit msiArtefactCyclindre;
mstArtefactCylindre = new MovableState(new Point3D(x,y,z), Point3D.ZERO, Point3D.ZERO, Point3D.ZERO, Point3D.ZERO, Point3D.ZERO);
msiArtefactCyclindre= new EntityMouvementSequenceurInit("MSI", mstArtefactCylindre, 0, 0,0,0, positionsCles);
scenariFeatures.getArtefacts().put(new EntityArtefactFeatures("CubN 1",5,1,3.0,4), new EntityArtefactInit("CubN "+i,msiArtefactCyclindre,Color.BLACK));
}
//Création de l'ocean
positionsCles = new HashMap<String, Point3D>();
MovableState mstOcean = new MovableState(Point3D.ZERO, Point3D.ZERO, Point3D.ZERO, Point3D.ZERO, Point3D.ZERO, Point3D.ZERO);
EntityMouvementSequenceurInit msiOcean = new EntityMouvementSequenceurInit("MSIOCEAN", mstOcean, 0, 0,0,0, positionsCles);
scenariFeatures.getOcean().put(new EntityOceanFeature("O1"), new EntityOceanInit("Atlantique", msiOcean));
LogicalDateTime start = new LogicalDateTime("05/12/2017 06:00");
LogicalDateTime end = start.add(LogicalDuration.ofMinutes(2));
AnalyseSousMarineScenario bms = new AnalyseSousMarineScenario(new ScenarioId("S1"), scenariFeatures, start, end);
return bms;
}
}
|
package com.movietoy.api.controller.movieInfo;
import com.movietoy.api.dto.Message;
import com.movietoy.api.dto.StatusEnum;
import com.movietoy.api.dto.movieInfo.MovieInfoResponseDto;
import com.movietoy.api.service.movieInfo.MovieInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RequiredArgsConstructor
@RestController
public class MovieInfoController {
private final MovieInfoService movieInfoService;
@GetMapping("/movie/{movieCd}")
public ResponseEntity<Message> MovieInfo(@PathVariable(value="movieCd") String movieCd) throws Exception {
//영화 상세 정보
MovieInfoResponseDto movieInfo = movieInfoService.MovieInfo(movieCd);
Message message = new Message();
message.setStatus(StatusEnum.OK);
message.setMessage("성공");
message.setData(movieInfo);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Content-Type","application/json");
return new ResponseEntity<>(message, httpHeaders, HttpStatus.OK);
}
}
|
package com.shubh.javaworld;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
class EntryComparator implements Comparator<Map.Entry<Integer, Integer>> {
public int compare(Entry<Integer, Integer> e1, Entry<Integer, Integer> e2) {
return e1.getValue() - e2.getValue();
}
}
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Integer, Integer> myMap = new HashMap<>();
myMap.put(1, 100);
myMap.put(2, 10);
myMap.put(3, 50);
myMap.put(4, 5);
List<Map.Entry<Integer, Integer>> mapList = new LinkedList<>(myMap.entrySet());
Collections.sort(mapList,
(Comparator<Entry<Integer, Integer>>) (a, b) -> (a.getValue().compareTo(b.getValue())));
for (Entry<Integer, Integer> entry : mapList) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
myMap.put(7, 15);
System.out.println(myMap);
List<Entry<Integer, Integer>> myList2 = new LinkedList<Entry<Integer, Integer>>(myMap.entrySet());
Collections.sort(myList2, new EntryComparator());
for (Entry<Integer, Integer> entry : myList2) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
List<String> myList = new ArrayList<String>();
Set<List<String>> mySet = new HashSet<>();
myList.add("A");
myList.add("A");
myList.add("A");
mySet.add(new ArrayList<>(myList));
myList = new ArrayList<String>();
myList.add("A");
myList.add("B");
mySet.add(new ArrayList<>(myList));
myList = new ArrayList<String>();
myList.add("B");
myList.add("A");
mySet.add(new ArrayList<>(myList));
}
}
|
package com.scipianus.finder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.gson.Gson;
import com.scipianus.finder.model.Directory;
import com.scipianus.finder.model.FileSystem;
import com.scipianus.finder.recyclerview.DirectoryAdapter;
import com.scipianus.finder.utils.NetworkUtils;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
public static final String[] inputFiles = {"input1.json", "input2.json", "input3.json"};
private ProgressBar mProgressBar;
private TextView mErrorMessage;
private LinearLayout mResultsView;
private RecyclerView mLeftView;
private RecyclerView mRightView;
private DirectoryAdapter mLeftAdapter;
private DirectoryAdapter mRightAdapter;
private DevAcademyAsyncTask mDevAcademyAsyncTask;
private FileSystem mRoot;
private Directory mCurrentDirectory;
private Gson mGson;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar = findViewById(R.id.loading_bar);
mErrorMessage = findViewById(R.id.error_message);
mResultsView = findViewById(R.id.results_view);
mLeftView = findViewById(R.id.left_recycler_view);
mRightView = findViewById(R.id.right_recycler_view);
mLeftAdapter = new DirectoryAdapter(new LeftClickListener());
mRightAdapter = new DirectoryAdapter(new RightClickListener());
mLeftView.setLayoutManager(new LinearLayoutManager(this));
mLeftView.setHasFixedSize(false);
mLeftView.setAdapter(mLeftAdapter);
mRightView.setLayoutManager(new LinearLayoutManager(this));
mRightView.setHasFixedSize(false);
mRightView.setAdapter(mRightAdapter);
mGson = new Gson();
loadData(inputFiles[0]);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.input_options, menu);
boolean shouldShowBackButton = (mCurrentDirectory != null);
MenuItem backButton = menu.findItem(R.id.back_button);
if (backButton != null) {
backButton.setVisible(shouldShowBackButton);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.back_button:
onBackPressed();
return true;
case R.id.inputOption1:
loadData(inputFiles[0]);
return true;
case R.id.inputOption2:
loadData(inputFiles[1]);
return true;
case R.id.inputOption3:
loadData(inputFiles[2]);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed() {
if (mCurrentDirectory.getParent() != null) {
if (mCurrentDirectory.getParent().getParent() == null) {
mLeftAdapter.setFileSystem(mRoot);
} else {
mLeftAdapter.setFileSystem(new FileSystem(mCurrentDirectory.getParent().getParent()));
}
mRightAdapter.setFileSystem(new FileSystem(mCurrentDirectory.getParent()));
mCurrentDirectory = mCurrentDirectory.getParent();
} else {
mLeftAdapter.setFileSystem(mRoot);
mRightAdapter.setFileSystem(null);
mCurrentDirectory = null;
}
invalidateOptionsMenu();
}
private void loadData(String inputFile) {
if (mDevAcademyAsyncTask != null) {
mDevAcademyAsyncTask.cancel(true);
}
mDevAcademyAsyncTask = new DevAcademyAsyncTask();
mDevAcademyAsyncTask.execute(inputFile);
}
private void bindData(FileSystem fileSystem) {
mRoot = fileSystem;
mLeftAdapter.setFileSystem(mRoot);
mRightAdapter.setFileSystem(null);
}
class DevAcademyAsyncTask extends AsyncTask<String, Void, FileSystem> {
@Override
protected void onPreExecute() {
mProgressBar.setVisibility(View.VISIBLE);
}
@Override
protected FileSystem doInBackground(String... strings) {
if (strings == null || strings.length == 0)
return null;
String inputFile = strings[0];
URL queryURL = NetworkUtils.buildUrl(inputFile);
String jsonResponse = null;
try {
jsonResponse = NetworkUtils.getResponseFromHttpUrl(queryURL);
FileSystem root = mGson.fromJson(jsonResponse, FileSystem.class);
root.assignParents();
return root;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(FileSystem fileSystem) {
mProgressBar.setVisibility(View.INVISIBLE);
if (fileSystem == null) {
mErrorMessage.setVisibility(View.VISIBLE);
mResultsView.setVisibility(View.INVISIBLE);
} else {
bindData(fileSystem);
mErrorMessage.setVisibility(View.INVISIBLE);
mResultsView.setVisibility(View.VISIBLE);
}
}
}
class LeftClickListener implements DirectoryAdapter.DirectoryClickListener {
@Override
public void onDirectoryClicked(Directory directory) {
mCurrentDirectory = directory;
mRightAdapter.setFileSystem(new FileSystem(directory));
invalidateOptionsMenu();
}
}
class RightClickListener implements DirectoryAdapter.DirectoryClickListener {
@Override
public void onDirectoryClicked(Directory directory) {
mCurrentDirectory = directory;
mLeftAdapter.setFileSystem(new FileSystem(directory.getParent()));
mRightAdapter.setFileSystem(new FileSystem(directory));
invalidateOptionsMenu();
}
}
}
|
package com.tt.option.z;
public interface b {
void checkSession(String paramString, a parama);
public static interface a {
void onSessionChecked(boolean param1Boolean, String param1String);
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\option\z\b.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package br.com.audiojus.service;
import java.util.List;
import org.springframework.stereotype.Service;
import br.com.audiojus.model.Assunto;
import br.com.audiojus.model.Sumula;
import br.com.audiojus.model.Tribunal;
public interface ManterSumulaService extends ManterCadastro<Sumula> {
public void salvar(Sumula sumula);
public List<Sumula> listar(Assunto assunto);
public List<Sumula> listar(Tribunal tribunal);
}
|
package util;
/**
* Class for math utility methods
*/
public final class Math {
private Math() {}
/**
* Calculate square root of a number (double)
* @param number The number
* @return Value as double
*/
public static double sqrt(double number) {
if (number < 0) return Double.NaN;
double epsilon = 1.0e-15; // relative error tolerance
double t = number; // estimate of the square root of c
// repeatedly apply Newton update step until desired precision is achieved
while (abs(t - number/t) > epsilon*t) {
t = (number/t + t) / 2.0;
}
return t;
}
/**
* Calculate absolute value of a number
* @param a The number
* @return Absolute value
*/
public static double abs(double a) {
return a >= 0 ? a : (-1)*a;
}
/**
* Calculate hypothenuse of a right-angled triangle
* @param a first cathetus
* @param b second cathetus
* @return Value as double
*/
public static double hypot(double a, double b) {
return sqrt( a*a + b*b);
}
}
|
package com.apprisingsoftware.xmasrogue.io;
import com.apprisingsoftware.xmasrogue.util.Coord;
import java.awt.Color;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public final class MessageScreen implements AsciiScreen {
private static final String moreMessage = "-- MORE --";
private static final Color[] moreMessageColors = {Color.BLACK, Color.WHITE};
protected final int width, numMessages;
private final LinkedList<Message> messages;
private final LinkedList<Boolean> areActive;
private final Color bgColor;
private boolean hasBeenModified = true;
private boolean showingMorePrompt = false;
public MessageScreen(int width, int numMessages, Color bgColor) {
this.width = width;
this.numMessages = numMessages;
this.messages = new LinkedList<>(Collections.nCopies(numMessages, null));
this.areActive = new LinkedList<>(Collections.nCopies(numMessages, false));
this.bgColor = bgColor;
}
public Message pushMessage(Message message) {
if (message.getText().length() > width - moreMessage.length()) throw new IllegalArgumentException("\"" + message.getText() + "\" is too long of a message");
hasBeenModified = true;
messages.addLast(message);
areActive.addLast(true);
if (messages.size() > numMessages) {
areActive.removeFirst();
return messages.removeFirst();
}
else return null;
}
public void dilapidateOldMessages() {
for (int i=0; i<areActive.size(); i++) {
if (areActive.get(i)) {
hasBeenModified = true;
}
areActive.set(i, false);
}
}
public void showMorePrompt() {
showingMorePrompt = true;
hasBeenModified = true;
}
public void hideMorePrompt() {
showingMorePrompt = false;
hasBeenModified = true;
}
public int getNumMessages() {
return numMessages;
}
@Override public AsciiTile getTile(int x, int y) {
if (showingMorePrompt && y == numMessages - 1 && width-1 - x >= 0 && width-1 - x < moreMessage.length()) {
return new AsciiTile(moreMessage.charAt(moreMessage.length()-1 - (width-1 - x)), moreMessageColors[0], moreMessageColors[1]);
}
Message message = messages.get(y);
boolean active = areActive.get(y);
if (message == null || x >= message.getText().length()) {
return new AsciiTile(' ', Color.BLACK, bgColor);
}
else {
return new AsciiTile(message.getText().charAt(x), active ? message.getActiveColor() : message.getInactiveColor(), bgColor);
}
}
@Override public boolean isTransparent(int x, int y) {
return !inBounds(x, y);
}
@Override public Collection<Coord> getUpdatedTiles() {
if (hasBeenModified) {
hasBeenModified = false;
return IntStream.range(0, width).boxed().flatMap(x -> IntStream.range(0, numMessages).<Coord>mapToObj(y -> new Coord(x, y))).collect(Collectors.toList());
}
else return Collections.emptyList();
}
@Override public int getWidth() {
return width;
}
@Override public int getHeight() {
return numMessages;
}
}
|
package com.lbf.utils;
public class DEMO {
public static void main(String[] args) {
System.out.println("first use git");
}
public void sayHello() {
System.out.println("aa");
}
}
|
package com.mx.profuturo.bolsa.model.service.areasinteres.dto;
import java.io.Serializable;
import java.util.List;
public class UpdateInterestAreaRequestBean implements Serializable {
private String descripcion;
private int idArea;
private String nombre;
private List<SubAreaInteresDTO> subareas;
public String getDescripcion() {
return descripcion;
}
public int getIdArea() {
return idArea;
}
public String getNombre() {
return nombre;
}
public List<SubAreaInteresDTO> getSubareas() {
return subareas;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public void setIdArea(int idArea) {
this.idArea = idArea;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public void setSubareas(List<SubAreaInteresDTO> subareas) {
this.subareas = subareas;
}
}
|
package game_strategy;
import eg.edu.alexu.csd.oop.game.World;
public interface State {
public void changeGameMode(World engine);
}
|
import Character.Fighting.Dwarf;
import Character.Fighting.Wizard;
import Character.NonFighting.Cleric;
import Healing.HealingTool;
import Map.Room;
import Treasure.Gem;
import Treasure.ITreasurable;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class RoomTest {
private Room room;
private Wizard enemyWizard;
private Dwarf enemyDwarf;
private Cleric enemyCleric;
private ITreasurable treasureHealth;
private ITreasurable treasureGem;
private Wizard partyWizard;
@Before
public void before(){
room = new Room("Loyal Lair");
enemyWizard = new Wizard("John", 2, 2);
treasureHealth = new HealingTool("Bread", 10, 1);
treasureGem = new Gem("Ruby", 10);
enemyDwarf = new Dwarf("Ron", 2, 2);
enemyCleric = new Cleric("Bobby", 2);
partyWizard = new Wizard("Austin", 10, 10);
}
@Test
public void room_has_name(){
assertEquals("Loyal Lair", room.getName());
}
@Test
public void enemies_starts_empty(){
assertEquals(0, room.getEnemies().size());
}
@Test
public void can_add_a_WIZARD(){
room.addEnemy(enemyWizard);
assertEquals(1, room.getEnemies().size());
}
@Test
public void can_add_a_dwarf(){
room.addEnemy(enemyDwarf);
assertEquals(1, room.getEnemies().size());
}
@Test
public void can_add_cleric_to_enemies(){
room.addEnemy(enemyCleric);
assertEquals(1, room.getEnemies().size());
}
@Test
public void can_remove_an_enemy(){
room.addEnemy(enemyWizard);
room.removeEnemy(enemyWizard);
assertEquals(0, room.getEnemies().size());
}
@Test
public void starts_with_no_treasure(){
assertEquals(0, room.getTreasures().size());
}
@Test
public void can_add_health_treasure(){
room.addTreasure(treasureHealth);
assertEquals(1, room.getTreasures().size());
assertEquals(true, room.getTreasures().contains(treasureHealth));
}
@Test
public void can_add_gem_treasure(){
room.addTreasure(treasureGem);
assertEquals(1, room.getTreasures().size());
assertEquals(true, room.getTreasures().contains(treasureGem));
}
@Test
public void can_remove_treasure(){
room.addTreasure(treasureGem);
room.addTreasure(treasureHealth);
room.removeTreasure(treasureGem);
assertEquals(1, room.getTreasures().size());
assertEquals(false, room.getTreasures().contains(treasureGem));
}
}
|
/*
* created 21-Feb-2006
*
* Copyright 2009, ByteRefinery
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* $Id: ColumnDependencyDialog.java 656 2007-08-31 00:11:31Z cse $
*/
package com.byterefinery.rmbench.dialogs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import com.byterefinery.rmbench.RMBenchPlugin;
import com.byterefinery.rmbench.model.schema.Column;
import com.byterefinery.rmbench.model.schema.ForeignKey;
import com.byterefinery.rmbench.model.schema.Index;
import com.byterefinery.rmbench.model.schema.UniqueConstraint;
import com.byterefinery.rmbench.util.ScriptWriter;
public class ColumnDependencyDialog extends AbstractDependencyDialog {
private Column column;
private Button deleteButton;
private Button removeFKButton;
private Button deleteConstraintButton;
private Button deleteIndexButton;
private Button removeColumnButton;
private boolean deleteFK;
private boolean deleteUnique;
private boolean deleteIndex;
private int primaryKeyIndex;
private List<ForeignKey> foreignKeysDeletable;
private List<ForeignKey> foreignKeysUnDeletable;
private List<Index> indexList;
public ColumnDependencyDialog(Shell parentShell, Column column) {
super(parentShell);
this.column = column;
deleteFK = true;
deleteUnique = true;
deleteIndex = true;
}
public ColumnDependencyDialog(Column column) {
this(RMBenchPlugin.getModelView().getViewSite().getShell(), column);
}
protected String getDetails() {
ScriptWriter writer = new ScriptWriter();
if (foreignKeysDeletable == null)
calculateDependencies();
//Action text
writer.println("Action: delete Column"); //$NON-NLS-1$
//implied actions:
writer.println("Implied Actions:"); //$NON-NLS-1$
ForeignKey fk;
writer.indent(1);
// print foreignkeys, which can only be removed (without deltion of column)
for (Iterator<ForeignKey> it = foreignKeysUnDeletable.iterator(); it.hasNext();) {
fk = it.next();
writer.print("remove foreignkey constraint from column "); //$NON-NLS-1$
writer.print(fk.getColumn(primaryKeyIndex).getName());
writer.print(" from table "); //$NON-NLS-1$
writer.println(fk.getColumn(primaryKeyIndex).getTable().getName());
}
// print deletable foreignkeys
for (Iterator<ForeignKey> it = foreignKeysDeletable.iterator(); it.hasNext();) {
fk = it.next();
if (deleteFK) {
writer.print("delete column "); //$NON-NLS-1$
}
else {
writer.print("remove foreignkey constraint from column "); //$NON-NLS-1$
}
writer.print(fk.getColumn(primaryKeyIndex).getName());
writer.print(" from table "); //$NON-NLS-1$
writer.println(fk.getColumn(primaryKeyIndex).getTable().getName());
}
for (Iterator<UniqueConstraint> it = column.getUniqueConstraints().iterator(); it.hasNext();) {
UniqueConstraint constraint = it.next();
if (deleteUnique) {
writer.print("delete constraint "); //$NON-NLS-1$
}
else {
writer.print("remove column from constraint "); //$NON-NLS-1$
}
writer.println(constraint.getName());
}
for (Iterator<Index> it = indexList.iterator(); it.hasNext();) {
Index index = it.next();
if (deleteIndex) {
writer.print("delete index "); //$NON-NLS-1$
}
else {
writer.print("remove column from index "); //$NON-NLS-1$
}
writer.println(index.getName());
}
return writer.getString();
}
public boolean calculateDependencies() {
foreignKeysDeletable = Collections.emptyList();
foreignKeysUnDeletable = Collections.emptyList();
indexList = Collections.emptyList();
if (((column.getTable().getPrimaryKey() == null) || (!column.getTable().getPrimaryKey()
.contains(column))|| (column.getTable().getReferences().size()==0))
&& (column.getUniqueConstraints().size() == 0)
&& (column.getTable().getIndexes().size()==0)) {
return false;
}
if (column.belongsToPrimaryKey()) {
primaryKeyIndex = column.getTable().getPrimaryKey().getIndex(column);
// need to create new array list for concurency reasons
foreignKeysDeletable = new ArrayList<ForeignKey>(column.getTable().getReferences().size());
foreignKeysUnDeletable = new ArrayList<ForeignKey>();
for (Iterator<ForeignKey> it = column.getTable().getReferences().iterator(); it.hasNext();) {
ForeignKey foreignKey = (ForeignKey) it.next();
Column fkColumn = foreignKey.getColumn(primaryKeyIndex);
if ( (fkColumn.getForeignKeys().size()==1) && (!fkColumn.belongsToPrimaryKey()))
foreignKeysDeletable.add(foreignKey);
else
foreignKeysUnDeletable.add(foreignKey);
}
}
List<Index> indexes = column.getTable().getIndexes();
for (Iterator<Index> it=indexes.iterator(); it.hasNext();) {
Index index = it.next();
if (index.contains(column)) {
if (indexList.isEmpty()) {
indexList = new ArrayList<Index>();
}
indexList.add(index);
}
}
return true;
}
protected void createOptionsArea(Composite dialogArea) {
if (column.belongsToPrimaryKey()) {
Group actionGroup = new Group(dialogArea, SWT.NONE);
actionGroup.setText(Messages.ColumnDependencyDialog_GroupName);
GridData gd = new GridData(SWT.FILL, SWT.TOP, true, false);
actionGroup.setLayoutData(gd);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
actionGroup.setLayout(layout);
deleteButton = new Button(actionGroup, SWT.RADIO);
deleteButton.setText(Messages.ColumnDependencyDialog_DeleteButton);
gd = new GridData();
gd.horizontalSpan = 2;
gd.verticalAlignment = SWT.TOP;
deleteButton.setLayoutData(gd);
deleteButton.setSelection(true);
deleteButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
deleteFK = true;
setDetailsText(getDetails());
}
});
removeFKButton = new Button(actionGroup, SWT.RADIO);
removeFKButton.setText(Messages.ColumnDependencyDialog_RemoveButton);
removeFKButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
deleteFK = false;
setDetailsText(getDetails());
}
});
}
if (column.getUniqueConstraints().size() > 0) {
Group actionGroup = new Group(dialogArea, SWT.NONE);
actionGroup.setText("Unique constraint handling");
GridData gd = new GridData(SWT.FILL, SWT.TOP, true, false);
actionGroup.setLayoutData(gd);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
actionGroup.setLayout(layout);
deleteConstraintButton = new Button(actionGroup, SWT.RADIO);
deleteConstraintButton.setText("delete constraints");
gd = new GridData();
gd.horizontalSpan = 2;
gd.verticalAlignment = SWT.TOP;
deleteConstraintButton.setLayoutData(gd);
deleteConstraintButton.setSelection(true);
deleteConstraintButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
deleteUnique = true;
setDetailsText(getDetails());
}
});
removeColumnButton = new Button(actionGroup, SWT.RADIO);
removeColumnButton.setText("remove column from constraints");
removeColumnButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
deleteUnique = false;
setDetailsText(getDetails());
}
});
}
if (column.getTable().getIndexes().size() > 0) {
Group actionGroup = new Group(dialogArea, SWT.NONE);
actionGroup.setText("Indices handling");
GridData gd = new GridData(SWT.FILL, SWT.TOP, true, false);
actionGroup.setLayoutData(gd);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
actionGroup.setLayout(layout);
deleteIndexButton = new Button(actionGroup, SWT.RADIO);
deleteIndexButton.setText("delete indices");
gd = new GridData();
gd.horizontalSpan = 2;
gd.verticalAlignment = SWT.TOP;
deleteIndexButton.setLayoutData(gd);
deleteIndexButton.setSelection(true);
deleteIndexButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
deleteIndex = true;
setDetailsText(getDetails());
}
});
removeColumnButton = new Button(actionGroup, SWT.RADIO);
removeColumnButton.setText("remove column from index");
removeColumnButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
deleteIndex = false;
setDetailsText(getDetails());
}
});
}
}
/**
*
* @return the foreignkeys which column may be deleted
*/
public List<ForeignKey> getDeletableForeignKeys() {
return foreignKeysDeletable;
}
/**
*
* @return the indexlist which contains the column, which will bedeleted
*/
public List<Index> getIndexList() {
return indexList;
}
/**
*
* @return the foreignkeys which columns must not be deleted, because there
* are used by other foreignkeys
*/
public List<ForeignKey> getUnDeletableForeignKeys() {
return foreignKeysUnDeletable;
}
public boolean getDeleteConstraints() {
return deleteUnique;
}
public boolean getDeleteIndices() {
return deleteIndex;
}
protected void okPressed() {
if (!deleteFK) {
foreignKeysUnDeletable.addAll(foreignKeysDeletable);
foreignKeysDeletable = Collections.emptyList();
}
super.okPressed();
}
}
|
package com.chuxin.family.app;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.support.v4.app.FragmentActivity;
import com.chuxin.androidpush.sdk.push.RKPush;
import com.chuxin.family.global.CxGlobalConst;
import com.chuxin.family.global.CxGlobalParams;
import com.chuxin.family.settings.CxLockScreen;
import com.chuxin.family.utils.CxLog;
import com.chuxin.family.utils.Push;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author shichao.wang
*
*/
public class CxRootActivity extends FragmentActivity {
protected ImageLoader imageLoader = ImageLoader.getInstance();
@Override
protected void onStop() {
CxLog.i("rkroot", ""+openedResource.size());
try {
openedResource.remove(this);
} catch (Exception e) {
e.printStackTrace();
}
if (openedResource.size() < 1) {
if (CxGlobalParams.getInstance().isAppStatus()) {
CxGlobalParams.getInstance().setAppStatus(false);
try {
((AudioManager)getSystemService(Context.AUDIO_SERVICE)).setMode(AudioManager.MODE_NORMAL);
} catch (Exception e) {
e.printStackTrace();
}
//开启push
RKPush.S_SEND_FLAG = true;
CxLog.i("rkroot", "app status foreground turn to background");
}else{
CxLog.i("rkroot", "app status is background");
}
}else{ //
CxLog.i("rkroot", "app status foreground, size is:"+openedResource.size());
}
super.onStop();
}
private static List<FragmentActivity> openedResource = new ArrayList<FragmentActivity>();
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onPause() {
super.onPause();
// 打开push
// Log.d("PUSH", "onPause() => enablePush");
Push.getInstance(this).setNotificationType(null);
}
@Override
protected void onStart() {
super.onResume();
//关闭push
// Log.d("PUSH", "onResume() => disenablePush");
Push.getInstance(this).setNotificationType("ignore");
if (!CxGlobalParams.getInstance().isAppNormal()) {
this.finish();
return;
}
CxLog.i("lock", "AppStatus:"+CxGlobalParams.getInstance().isAppStatus());
if (!CxGlobalParams.getInstance().isAppStatus()) {
//开启密码保护
SharedPreferences sp = getSharedPreferences(
CxGlobalConst.S_LOCKSCREEN_NAME, Context.MODE_PRIVATE);
CxLog.i("lock", "FIELD:"+sp.getString(CxGlobalConst.S_LOCKSCREEN_FIELD, null)
+",isExist:"+CxLockScreen.isExist
+",gpuImage:"+CxGlobalParams.getInstance().isCallGpuimage() );
if ((null != sp.getString(CxGlobalConst.S_LOCKSCREEN_FIELD, null)) && (!CxLockScreen.isExist) && (!CxGlobalParams.getInstance().isCallGpuimage())) {
Intent toLock = new Intent(CxRootActivity.this, CxLockScreen.class);
toLock.putExtra(CxGlobalConst.S_LOCKSCREEN_TYPE, 0); // password protect
startActivity(toLock);
}
CxGlobalParams.getInstance().setAppStatus(true);
CxLog.i("lock", "AppStatus turn to foreground");
RKPush.S_SEND_FLAG = false;
}
openedResource.add(this);
// super.onResume();
}
}
|
package com.Jnet.ChatApplication.Controller;
import com.Jnet.ChatApplication.Model.User;
import com.Jnet.ChatApplication.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
@Controller
@RequestMapping("/chat")
public class ChatApplicationController {
@Autowired
private UserRepository userRepository;
@RequestMapping(value = {"/", ""}, method = RequestMethod.GET)
public String chatPage(HttpServletRequest request, HttpServletResponse response){
return "ChatApplication/ChatPage";
}
@RequestMapping(value = "/set-user", method = RequestMethod.POST)
public RedirectView setUser(@RequestBody MultiValueMap<String, String> val, @RequestBody String strVal, HttpSession session,
HttpServletResponse response){
Map<String, String> values = val.toSingleValueMap();
if (areUserValues(values)){
User oldUser;
User receivedUser = parseUserFromMapValues(values);
if (null != (oldUser = userRepository.findBySessionId(session.getId()))) {
userRepository.setUsernameByID(receivedUser.getUsername(), oldUser.getID());
userRepository.setTextColorByID(receivedUser.getTextColor(), oldUser.getID());
userRepository.setSessionIdByID(session.getId(), oldUser.getID());
} else {
User user = new User();
user.setUsername(receivedUser.getUsername());
user.setTextColor(receivedUser.getTextColor());
user.setSessionId(session.getId());
userRepository.save(user);
}
response.addCookie(new Cookie("username", receivedUser.getUsername()));
response.addCookie(new Cookie("textColor", receivedUser.getTextColor()));
}
return new RedirectView("/chat");
}
private User parseUserFromMapValues(Map<String, String> values) {
assert areUserValues(values) : "Incorrect values";
User user = new User();
user.setUsername(values.get("username"));
user.setTextColor(values.get("textColor"));
return user;
}
private boolean areUserValues(Map<String, String> values){
boolean result = false;
if (null != values){
Set<String> keys = values.keySet();
if (hasAllUserFields(keys) && !isAnyValueEmpty(values.values())){
result = true;
}
}
return result;
}
private boolean isAnyValueEmpty(Collection<String> values) {
return values.contains("");
}
private boolean hasAllUserFields(Set<String> keys) {
return keys.contains("username") && keys.contains("textColor");
}
}
|
package com.csform.android.uiapptemplate;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.csform.android.uiapptemplate.adapter.MyStickyListHeadersAdapter;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.VisibleRegion;
/**
* A simple {@link Fragment} subclass. Use the
* {@link GoogleMapFragment#newInstance} factory method to create an instance of
* this fragment.
*/
public class GoogleMapFragment extends Fragment implements
OnCameraChangeListener, AdapterView.OnItemSelectedListener,
com.google.android.gms.maps.GoogleMap.OnMarkerClickListener,
OnMapLongClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
static UserSessionManager session;
String title;
String user;
String type_name;
String description;
String address;
String image0, image1, image2;
String dateoccured;
String id;
static public ArrayList<HashMap<String, String>> mylist;
Marker newMarker;
GoogleMap mMap;
static public double lat, lon, lat12, lon12;
static JSONArray jArray;
static String entityResponse;
VisibleRegion vr;
String markerString;
ProgressBar progressBarMapFragmentDetail;
String searchAddress = null;
String dateOccur;
Location location1 = null;
static public double left, right, top, bottom;
/**
* Use this factory method to create a new instance of this fragment using
* the provided parameters.
*
* @param //param1 Parameter 1.
* @param //param2 Parameter 2.
* @return A new instance of fragment GoogleMap.
*/
// TODO: Rename and change types and number of parameters
public GoogleMapFragment(String searchAddress) {
this.searchAddress = searchAddress;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
this.searchAddress = savedInstanceState.getString("searchAddress");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// return inflater.inflate(R.layout.google_map, container, false);
mylist = new ArrayList<HashMap<String, String>>();
if (savedInstanceState != null) {
searchAddress = savedInstanceState.getString("searchAddress");
Log.e("searchAddress", searchAddress);
}
View v = inflater.inflate(R.layout.map_fragment_detail, container,
false);
progressBarMapFragmentDetail = (ProgressBar) v
.findViewById(R.id.progressBarMapFragmentDetail);
LocationManager_check locationManagerCheck = new LocationManager_check(
getActivity());
mMap = ((SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.mapfragmentid)).getMap();
mMap.setInfoWindowAdapter(new InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public View getInfoContents(Marker arg0) {
// TODO Auto-generated method stub
LatLng l = arg0.getPosition();
Double lat12 = l.latitude;
Double lon12 = l.longitude;
newMarker = arg0;
if (lat12 == location1.getLatitude()
&& lon12 == location1.getLongitude()) {
Toast.makeText(getActivity(),
"This is your current location", Toast.LENGTH_LONG)
.show();
return null;
} else {
final View v = getLayoutInflater(null).inflate(
R.layout.windowlayout, null);
// Getting the position from the marker
LatLng latLng = arg0.getPosition();
DatabaseOperations dbo = new DatabaseOperations(
getActivity());
Cursor c = dbo.getInformationByLatLng(dbo, latLng.latitude,
latLng.longitude);
c.moveToFirst();
type_name = c.getString(c.getColumnIndex("type_name"));
description = c.getString(c.getColumnIndex("description"));
title = c.getString(c.getColumnIndex("title"));
address = c.getString(c.getColumnIndex("address"));
image0 = c.getString(c.getColumnIndex("image0"));
image1 = c.getString(c.getColumnIndex("image1"));
image2 = c.getString(c.getColumnIndex("image2"));
dateoccured = c.getString(c.getColumnIndex("date_occured"));
id = c.getString(c.getColumnIndex("id"));
user = c.getString(c.getColumnIndex("user_login"));
SimpleDateFormat fromUser = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat myFormat1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat myFormat2 = new SimpleDateFormat("h:mma");
try {
String reformattedStr1 = myFormat1.format(fromUser.parse(dateoccured));
String reformattedStr2 = myFormat2.format(fromUser.parse(dateoccured)).toLowerCase();
dateOccur=reformattedStr1+" at "+reformattedStr2;
TextView date = (TextView) v.findViewById(R.id.dateoccuredwindow);
date.setText(dateOccur);
} catch (ParseException e) {
e.printStackTrace();
}
ImageLoader imageLoader = new ImageLoader(getActivity());
ImageView image = (ImageView) v
.findViewById(R.id.imagewindow);
// Getting reference to the TextView to set latitude
TextView type = (TextView) v
.findViewById(R.id.crime_type_window);
// Getting reference to the TextView to set longitude
TextView desc = (TextView) v
.findViewById(R.id.descriptionwindow);
TextView address1 = (TextView) v
.findViewById(R.id.addresswindow);
// Getting reference to the TextView to set longitude
TextView date = (TextView) v
.findViewById(R.id.dateoccuredwindow);
// Setting the latitude
type.setText(title);
// Setting the longitude
desc.setText(description);
address1.setText(address);
c.close();
// Returning the view containing InfoWindow contents
return v;
}
}
});
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
// Add the bundle to the intent
Bundle b = new Bundle();
b.putDouble("lat", newMarker.getPosition().latitude);
b.putDouble("lng", newMarker.getPosition().longitude);
b.putString("title", title);
b.putString("description", description);
b.putString("user_login", user);
b.putString("image0", image0);
b.putString("image1", image1);
b.putString("image2", image2);
b.putString("type_name", type_name);
b.putString("identifier", id);
b.putString("address", address);
b.putString("date_occured", dateOccur);
Intent i = new Intent(getActivity(), ParticularInfoOnMap.class);
i.putExtras(b);
startActivity(i);
}
});
// india location
LatLng latlng = new LatLng(24.821387, 78.060060);
if (locationManagerCheck.isLocationServiceAvailable()) {
if (locationManagerCheck.getProviderType() == 1)
location1 = locationManagerCheck.locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
else if (locationManagerCheck.getProviderType() == 2)
location1 = locationManagerCheck.locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (searchAddress == null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
location1.getLatitude(), location1.getLongitude()), 15));
lat = location1.getAltitude();
lon = location1.getLongitude();
markerString = "your current location";
session = new UserSessionManager(getActivity());
session.setLastLocation(String.valueOf(lat),
String.valueOf(lon));
} else {
Geocoder coder = new Geocoder(getActivity());
try {
ArrayList<Address> adresses = (ArrayList<Address>) coder
.getFromLocationName(searchAddress, 1);
for (Address add : adresses) {
double longitude = add.getLongitude();
double latitude = add.getLatitude();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(latitude, longitude), 7));
markerString = "your location " + searchAddress;
}
} catch (IOException e) {
e.printStackTrace();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(24.821387, 78.060060), 5));
markerString = "cannot locate to address " + searchAddress;
}
}
} else {
locationManagerCheck.createLocationServiceError(getActivity());
}
progressBarMapFragmentDetail = (ProgressBar) v
.findViewById(R.id.progressBarMapFragmentDetail);
mMap.getUiSettings().setRotateGesturesEnabled(false);
mMap.getUiSettings().setMapToolbarEnabled(false);
mMap.setOnMarkerClickListener(new com.google.android.gms.maps.GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
// do nothing
return false;
}
});
// mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 4.5f));
mMap.setOnCameraChangeListener(this);
vr = mMap.getProjection().getVisibleRegion();
left = vr.latLngBounds.southwest.longitude;
top = vr.latLngBounds.northeast.latitude;
right = vr.latLngBounds.northeast.longitude;
bottom = vr.latLngBounds.southwest.latitude;
try {
lat = location1.getLatitude();
lon = location1.getLongitude();
session = new UserSessionManager(getActivity());
session.setLastLocation(String.valueOf(lat), String.valueOf(lon));
} catch (Exception ex) {
mMap.setMyLocationEnabled(true);
mMap.addMarker(new MarkerOptions().position(latlng).title(
"could not set to your current location "));
ex.printStackTrace();
Toast.makeText(getActivity(),
"problem occur while getting current location",
Toast.LENGTH_LONG).show();
}
latlng = new LatLng(lat, lon);
if (mMap == null) {
Toast.makeText(getActivity(), "something wrong with google map",
Toast.LENGTH_SHORT).show();
} else {
mMap.addMarker(new MarkerOptions().position(latlng).title(
markerString));
// mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 15));
}
// getCrime(bottom, top, left, right);return v;
String url = getResources().getString(R.string.URL_ShowItem);
String a = String.valueOf(bottom);
String b = String.valueOf(top);
String c = String.valueOf(left);
String d = String.valueOf(right);
GetCrime getCrime = new GetCrime();
if(getCrime.getStatus().equals(AsyncTask.Status.RUNNING))
{
getCrime.cancel(true);
}
String[] args = { url, a, b, c, d };
getCrime.execute(args);
return v;
}
/*
* private void getCrime(final double a, final double b, final double c,
* final double d) { // TODO Auto-generated method stub new AsyncTask<Void,
* Long, Boolean>() {
*
* Boolean status; String url;
*
* protected void onPreExecute() {
*
* url = getResources().getString(R.string.URL_ShowItem);
*
* progressBarMapFragmentDetail.setVisibility(View.VISIBLE); };
*
* protected void onPostExecute(Boolean result) {
*
* try {
*
* StickyListHeadersActivity a = new StickyListHeadersActivity( bottom, top,
* left, right); StickyListHeadersActivity.adapter.clear();
* StickyListHeadersActivity.adapter = new MyStickyListHeadersAdapter(
* getActivity(), mylist);
* StickyListHeadersActivity.adapter.notifyDataSetChanged(); a.init();
*
* } catch (Exception ex) {
*
* }
*
* progressBarMapFragmentDetail.setVisibility(View.INVISIBLE);
*
* try { DatabaseOperations dop = new DatabaseOperations( getActivity());
* for (int i = 0; i < mylist.size(); i++) { String id =
* mylist.get(i).get("id"); String identifier =
* mylist.get(i).get("identifier"); String title =
* mylist.get(i).get("title"); String description =
* mylist.get(i).get("description"); String type_name =
* mylist.get(i).get("type_name"); String address =
* mylist.get(i).get("address"); double lat =
* Double.parseDouble(mylist.get(i) .get("lat")); double lng =
* Double.parseDouble(mylist.get(i) .get("lng")); String image0 =
* mylist.get(i).get("image0"); String image1 = mylist.get(i).get("image1");
* String image2 = mylist.get(i).get("image2"); String user_login =
* mylist.get(i).get("user_login"); String date_occured =
* mylist.get(i).get("date_occured");
*
* LatLng latlng = new LatLng(Double.parseDouble(mylist .get(i).get("lat")),
* Double.parseDouble(mylist .get(i).get("lng")));
*
* mMap.addMarker(new MarkerOptions() .position(latlng)
* .title(mylist.get(i).get("title")) .snippet(
* mylist.get(i).get("description") + " " + mylist.get(i).get(
* "date_occured"))); // .setSnippet(CR.getString(3)
*
* try { dop.putInformation(dop, id, identifier, title, description,
* type_name, address, lat, lng, image0, image1, image2, user_login,
* date_occured); } catch (Exception ex) {
*
* } dop.close(); } } catch (Exception ex) {
*
* }
*
* };
*
* @Override protected Boolean doInBackground(Void... added_item) { // TODO
* Auto-generated method stub status = retrieveData(url, a, b, c, d); return
* status; }
*
* }.execute(null, null, null);
*
* }
*/
protected Boolean retrieveData(String url, double a, double b, double c,
double d) {
// TODO Auto-generated method stub
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ctx.init(null, new TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
String authType) {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
} }, null);
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
// TODO Auto-generated method stub
return true;
}
});
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
HttpEntity httpEntity = null;
// TODO Auto-generated method stub
try {
try {
mylist.clear();
} catch (Exception ex) {
}
final List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("a", String.valueOf(a)));
params.add(new BasicNameValuePair("b", String.valueOf(b)));
params.add(new BasicNameValuePair("c", String.valueOf(c)));
params.add(new BasicNameValuePair("d", String.valueOf(d)));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("entity response", entityResponse);
JSONArray jArray = new JSONArray(entityResponse);
if (jArray.length() < 1) {
return false;
} else {
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
map.put("id", e.getString("id"));
map.put("identifier", e.getString("identifier"));
map.put("title", e.getString("title"));
map.put("description", e.getString("description"));
map.put("type_name", e.getString("type_name"));
map.put("address", e.getString("address"));
map.put("lat", e.getString("lat"));
map.put("lng", e.getString("lng"));
map.put("image0", e.getString("image0"));
map.put("image1", e.getString("image1"));
map.put("image2", e.getString("image2"));
map.put("user_login", e.getString("user_login"));
map.put("date_occured", e.getString("date_occured"));
mylist.add(map);
}
return true;
}
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
@Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
vr = mMap.getProjection().getVisibleRegion();
left = vr.latLngBounds.southwest.longitude;
top = vr.latLngBounds.northeast.latitude;
right = vr.latLngBounds.northeast.longitude;
bottom = vr.latLngBounds.southwest.latitude;
Log.i("google zoooooom", String.valueOf(left));
Log.i("google zoooooom", String.valueOf(arg0.zoom));
try {
mylist.clear();
} catch (Exception ex) {
}
// getCrime(bottom, top, left, right);
String url = getResources().getString(R.string.URL_ShowItem);
String a = String.valueOf(bottom);
String b = String.valueOf(top);
String c = String.valueOf(left);
String d = String.valueOf(right);
String[] args = { url, a, b, c, d };
GetCrime getCrime = new GetCrime();
if(getCrime.getStatus().equals(AsyncTask.Status.RUNNING))
{
getCrime.cancel(true);
}
getCrime.execute(args);
}
@Override
public boolean onMarkerClick(Marker marker) {
return false;
}
public class LocationManager_check {
LocationManager locationManager;
Boolean locationServiceBoolean = false;
int providerType = 0;
AlertDialog alert;
public LocationManager_check(Context context) {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
boolean gpsIsEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean networkIsEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (networkIsEnabled == true && gpsIsEnabled == true) {
locationServiceBoolean = true;
providerType = 1;
} else if (networkIsEnabled != true && gpsIsEnabled == true) {
locationServiceBoolean = true;
providerType = 2;
} else if (networkIsEnabled == true && gpsIsEnabled != true) {
locationServiceBoolean = true;
providerType = 1;
}
}
public Boolean isLocationServiceAvailable() {
return locationServiceBoolean;
}
public int getProviderType() {
return providerType;
}
public void createLocationServiceError(final Activity activityObj) {
// show alert dialog if Internet is not connected
AlertDialog.Builder builder = new AlertDialog.Builder(activityObj);
builder.setMessage(
"You need to activate location service to use this feature. Please turn on network or GPS mode in location settings")
.setTitle("Turn On")
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
activityObj.startActivity(intent);
alert.dismiss();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
alert.dismiss();
}
});
alert = builder.create();
alert.show();
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
@Override
public void onMapLongClick(LatLng arg0) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "clicked", 0).show();
}
private class GetCrime extends AsyncTask<String, Void, Boolean> {
String url;
String a, b, c, d;
boolean status;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressBarMapFragmentDetail.setVisibility(View.VISIBLE);
super.onPreExecute();
}
protected Boolean doInBackground(String... args) {
this.url = args[0];
this.a = args[1];
this.b = args[2];
this.c = args[3];
this.d = args[4];
URL newurl = null;
status = retrieveData(url, Double.parseDouble(a),
Double.parseDouble(b), Double.parseDouble(c),
Double.parseDouble(d));
return status;
}
// @Override
protected void onPostExecute(Boolean result1) {
try {
StickyListHeadersActivity a = new StickyListHeadersActivity(
bottom, top, left, right);
StickyListHeadersActivity.adapter.clear();
StickyListHeadersActivity.adapter = new MyStickyListHeadersAdapter(
getActivity(), mylist);
StickyListHeadersActivity.adapter.notifyDataSetChanged();
a.init();
} catch (Exception ex) {
}
progressBarMapFragmentDetail.setVisibility(View.INVISIBLE);
try {
DatabaseOperations dop = new DatabaseOperations(getActivity());
for (int i = 0; i < mylist.size(); i++) {
String id = mylist.get(i).get("id");
String identifier = mylist.get(i).get("identifier");
String title = mylist.get(i).get("title");
String description = mylist.get(i).get("description");
String type_name = mylist.get(i).get("type_name");
String address = mylist.get(i).get("address");
double lat = Double.parseDouble(mylist.get(i).get("lat"));
double lng = Double.parseDouble(mylist.get(i).get("lng"));
String image0 = mylist.get(i).get("image0");
String image1 = mylist.get(i).get("image1");
String image2 = mylist.get(i).get("image2");
String user_login = mylist.get(i).get("user_login");
String date_occured = mylist.get(i).get("date_occured");
LatLng latlng = new LatLng(Double.parseDouble(mylist.get(i)
.get("lat")), Double.parseDouble(mylist.get(i).get(
"lng")));
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.crimehere);
mMap.addMarker(new MarkerOptions()
.position(latlng)
.title(mylist.get(i).get("title"))
.icon(icon)
.snippet(
mylist.get(i).get("description") + " "
+ mylist.get(i).get("date_occured")));
// .setSnippet(CR.getString(3)
try {
dop.putInformation(dop, id, identifier, title,
description, type_name, address, lat, lng,
image0, image1, image2, user_login,
date_occured);
} catch (Exception ex) {
}
dop.close();
}
} catch (Exception ex) {
}
}
}
}
|
import java.util.Random;
/**
* Generates clue by taking out vowels and re-space string
*/
public class Clue {
private static Random rnd = new Random();
public static String getClue(String s) {
String out = delVowels(s);
int spaces = countSpaces(out);
out = out.replace(" ",""); // clump them together
if (spaces>3) {spaces = 3;}
for (int i=0; i<spaces; i++) { // re-space
int pos = rnd.nextInt(out.length());
if (pos>=1 && out.charAt(pos-1)==' ') continue; // no two adjacent spaces
if (pos<out.length()-1 && out.charAt(pos+1)==' ') continue;
out = out.substring(0,pos) + " " + out.substring(pos, out.length());
}
return out;
}
private static String delVowels(String s) { // and dot
return s.toLowerCase().replaceAll("[aeiou.]", "").toUpperCase();
}
private static int countSpaces(String s) {
return s.length() - s.replace(" ", "").length();
}
}
|
package fixit.dataloaders.api;
import fixit.model.Category;
import java.util.List;
public interface ICategoryLoader
{
List<Category> getCategories(IConnectionProvider connectionProvider);
}
|
package com.example.notificationassignment;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button simpleNotifictonButton,buttonNotificationButton,imageNotificatonButton,drawTextNotificationButton,customNotificationButton;
private String CHANNEL_ID="personal notification";
private int NOTIFICATION_ID=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleNotifictonButton=findViewById(R.id.simple_notification_button);
buttonNotificationButton=findViewById(R.id.button_notification_button);
imageNotificatonButton=findViewById(R.id.image_notification_button);
drawTextNotificationButton=findViewById(R.id.draw_text_notification_button);
customNotificationButton=findViewById(R.id.custom_notification_button);
simpleNotifictonButton.setOnClickListener(this);
buttonNotificationButton.setOnClickListener(this);
imageNotificatonButton.setOnClickListener(this);
drawTextNotificationButton.setOnClickListener(this);
customNotificationButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
createNotificationChannel();
NotificationCompat.Builder builder=new NotificationCompat.Builder(this,CHANNEL_ID);
NotificationManagerCompat managerCompat=NotificationManagerCompat.from(this);
switch (v.getId()){
case R.id.simple_notification_button:
builder.setSmallIcon(R.drawable.ic_message_black_24dp);
builder.setContentTitle("Title");
builder.setContentText("this is personal notification");
builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
managerCompat.notify(NOTIFICATION_ID,builder.build());
break;
case R.id.button_notification_button:
builder.setSmallIcon(R.drawable.ic_message_black_24dp);
builder.setContentTitle("Title");
builder.setContentText("this is personal notification");
builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
Intent intent=new Intent(this,OpenActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
builder.addAction(R.drawable.ic_message_black_24dp,"open",pendingIntent);
managerCompat.notify(NOTIFICATION_ID,builder.build());
break;
case R.id.image_notification_button:
builder.setSmallIcon(R.drawable.ic_message_black_24dp);
builder.setContentTitle("Title");
builder.setContentText("this is personal notification");
builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.img_snow);
builder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bitmap).bigLargeIcon(bitmap));
managerCompat.notify(NOTIFICATION_ID,builder.build());
break;
case R.id.draw_text_notification_button:
Bitmap bitmap1=BitmapFactory.decodeResource(getResources(),R.drawable.img_snow);
builder.setSmallIcon(R.drawable.ic_message_black_24dp);
builder.setLargeIcon(bitmap1);
builder.setContentTitle("Title");
builder.setContentText("this is personal notification");
builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.notification)));
managerCompat.notify(NOTIFICATION_ID,builder.build());
break;
case R.id.custom_notification_button:
RemoteViews remoteViews=new RemoteViews(getPackageName(),R.layout.custom_notification);
builder.setSmallIcon(R.drawable.ic_message_black_24dp);
builder.setStyle(new NotificationCompat.DecoratedCustomViewStyle());
builder.setCustomContentView(remoteViews);
managerCompat.notify(NOTIFICATION_ID,builder.build());
}
}
private void createNotificationChannel(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
CharSequence name="personal channel";
int importance= NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel=new NotificationChannel(CHANNEL_ID,name,importance);
NotificationManager notificationManager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
|
package com.ibm.jikesbt;
/*
* Licensed Material - Property of IBM
* (C) Copyright IBM Corp. 1998, 2003
* All rights reserved
*/
import java.io.Serializable;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import com.ibm.jikesbt.BT_BytecodeException.BT_InstructionReferenceException;
/**
BT_InsVector is a variable size contiguous indexable array of {@link BT_Ins}s.
The size of the BT_InsVector is the number of BT_Inss it contains.
The capacity of the BT_InsVector is the number of BT_Inss it can hold.
<p> BT_Inss may be inserted at any position up to the size of the
BT_InsVector, increasing the size of the BT_InsVector. BT_Inss at any
position in the BT_InsVector may be removed, shrinking the size of
the BT_InsVector. BT_Inss at any position in the BT_InsVector may be replaced,
which does not affect the BT_InsVector size.
<p> The capacity of a BT_InsVector may be specified when the BT_InsVector is
created. If the capacity of the BT_InsVector is exceeded, the capacity
is increased, doubling by default.
<p> The following public members are in addition to the usual Vector methods:
<sl>
<li> {@link BT_InsVector#findBasicBlock}
<li> {@link BT_InsVector#findInstruction}
<li> {@link BT_InsVector#setAllByteIndexes}
</sl>
* @author IBM
**/
public final class BT_InsVector implements Cloneable, Serializable {
/**
* The number of elements or the size of the vector.
*/
protected int elementCount;
/**
* The elements of the vector.
*/
protected BT_Ins[] elementData;
/**
* The amount by which the capacity of the vector is increased.
*/
protected int capacityIncrement;
/**
* Initial empty value for elementData.
*/
private final static BT_Ins[] emptyData = new BT_Ins[0];
private static final int DEFAULT_SIZE = 0;
/**
* Constructs a new BT_InsVector using the default capacity.
*
*/
public BT_InsVector() {
this(DEFAULT_SIZE, 0);
}
/**
* Constructs a new BT_InsVector using the specified capacity.
*
*
* @param capacity the initial capacity of the new vector
*/
public BT_InsVector(int capacity) {
this(capacity, 0);
}
/**
* Constructs a new BT_InsVector using the specified capacity and
* capacity increment.
*
*
* @param capacity the initial capacity of the new BT_InsVector
* @param capacityIncrement the amount to increase the capacity
when this BT_InsVector is full
*/
public BT_InsVector(int capacity, int capacityIncrement) {
elementData = (capacity == 0) ? emptyData : new BT_Ins[capacity];
this.capacityIncrement = capacityIncrement;
}
/**
* Constructs an instruction vector with the specified number of instructions
* from the array instrs.
*/
public BT_InsVector(BT_Ins instrs[]) {
this.elementData = (BT_Ins[]) instrs.clone();
this.elementCount = instrs.length;
}
/**
* Adds the specified object at the end of this BT_InsVector.
*
*
* @param object the object to add to the BT_InsVector
*/
public void addElement(BT_Ins object) {
insertElementAt(object, elementCount);
}
/**
Adds the specified object at the end of this AccessorMethodVector,
unless the vector already contains it.
@return true if it was added.
**/
public boolean addUnique(BT_Ins object) {
if (contains(object)) {
return false;
}
addElement(object);
return true;
}
private int expandFor(int count) {
int newElementCount = elementCount + count;
if(newElementCount >= elementData.length) {
int newCapacity = elementCount;
int increment = capacityIncrement == 0 ? elementCount : capacityIncrement;
if(increment == 0) {
increment = 1;
}
do {
newCapacity += increment;
} while(newCapacity < newElementCount);
grow(newCapacity);
}
return newElementCount;
}
public void addAllUnique(BT_InsVector other) {
expandFor(other.elementCount);
for(int i=0; i<other.size(); i++) {
addUnique(other.elementAt(i));
}
}
public void addAllUnique(BT_Ins other[]) {
expandFor(other.length);
for(int i=0; i<other.length; i++) {
addUnique(other[i]);
}
}
public void addAll(BT_InsVector other) {
int newElementCount = expandFor(other.elementCount);
System.arraycopy(other.elementData, 0, elementData, elementCount, other.elementCount);
elementCount = newElementCount;
}
/**
* Answers the number of elements this BT_InsVector can hold without
* growing.
*
*
* @return the capacity of this BT_InsVector
*
* @see #ensureCapacity
* @see #size
*/
public int capacity() {
return elementData.length;
}
/**
* Answers a new BT_InsVector with the same elements, size, capacity
* and capacityIncrement as this BT_InsVector.
*
*
* @return a shallow copy of this BT_InsVector
*
* @see java.lang.Cloneable
*/
public Object clone() {
try {
BT_InsVector vector = (BT_InsVector) super.clone();
vector.elementData = (BT_Ins[]) elementData.clone();
return vector;
} catch (CloneNotSupportedException e) {
return null;
}
}
/**
* Searches this BT_InsVector for the specified object.
*
*
* @param object the object to look for in this BT_InsVector
* @return true if object is an element of this BT_InsVector, false otherwise
*
* @see #indexOf
* @see java.lang.Object#equals
*/
public boolean contains(BT_Ins object) {
return indexOf(object, 0) != -1;
}
/**
* Copies the elements of this BT_InsVector into the specified BT_Ins array.
*
*
* @param elements the BT_Ins array into which the elements
* of this BT_InsVector are copied
*
* @see #clone
*/
public void copyInto(BT_Ins[] elements) {
copyInto(elements, 0, 0, elementCount);
}
/**
* Copies the elements of this BT_InsVector into the specified BT_Ins array.
*
*
* @param elements the BT_Ins array into which the elements
* of this BT_InsVector are copied
*
* @see #clone
*/
public void copyInto(BT_Ins[] elements, int copyIndex, int index, int howMany) {
System.arraycopy(elementData, index, elements, copyIndex, howMany);
}
/**
* Answers the element at the specified location in this BT_InsVector.
*
*
* @param location the index of the element to return in this BT_InsVector
* @return the element at the specified location
*
* @exception ArrayIndexOutOfBoundsException when location < 0 || >= size()
*
* @see #size
*/
public BT_Ins elementAt(int location) {
return elementData[location];
}
/**
* Answers an Enumeration on the elements of this BT_InsVector. The
* results of the Enumeration may be affected if the contents
* of this BT_InsVector are modified.
*
*
* @return an Enumeration of the elements of this BT_InsVector
*
* @see #elementAt
* @see Enumeration
*/
public Enumeration elements() {
return new BT_ArrayEnumerator(elementData, elementCount);
}
/**
* Ensures that this BT_InsVector can hold the specified number of elements
* without growing.
*
*
* @param minimumCapacity the minimum number of elements that this
* vector will hold before growing
*
* @see #capacity
*/
public void ensureCapacity(int minimumCapacity) {
if (elementData.length < minimumCapacity)
grow(minimumCapacity);
}
/**
* Answers the first element in this BT_InsVector.
*
*
* @return the element at the first position
*
* @exception NoSuchElementException when this vector is empty
*
* @see #elementAt
* @see #lastElement
* @see #size
*/
public BT_Ins firstElement() {
if (elementCount == 0)
throw new NoSuchElementException();
return elementData[0];
}
private void grow(int newCapacity) {
BT_Ins newData[] = new BT_Ins[newCapacity];
System.arraycopy(elementData, 0, newData, 0, elementCount);
elementData = newData;
}
/**
* Searches in this BT_InsVector for the index of the specified object. The
* search for the object starts at the beginning and moves towards the
* end of this BT_InsVector.
*
*
* @param object the object to find in this BT_InsVector
* @return the index in this BT_InsVector of the specified element, -1 if the
* element isn't found
*
* @see #contains
* @see #lastIndexOf
*/
public int indexOf(BT_Ins object) {
return indexOf(object, 0);
}
/**
* Searches in this BT_InsVector for the index of the specified object. The
* search for the object starts at the specified location and moves
* towards the end of this BT_InsVector.
*
*
* @param object the object to find in this BT_InsVector
* @param location the index at which to start searching
* @return the index in this BT_InsVector of the specified element, -1 if the
* element isn't found
*
* @exception ArrayIndexOutOfBoundsException when location < 0
*
* @see #contains
* @see #lastIndexOf
*/
public int indexOf(BT_Ins object, int location) {
for (int i = location; i < elementCount; i++) {
if (elementData[i] == object)
return i;
}
return -1;
}
/**
* for performance, finds the indices of all listed instructions.
* @param ins1
* @return
*/
public int[] indexOf(BT_Ins instructions[], int location) {
int total = instructions.length;
int result[] = new int[total];
if(0 == total) {
return result;
}
Arrays.fill(result, -1);
int found = 0;
for (int i = location; i < elementCount; i++) {
BT_Ins element = elementData[i];
for(int k=0; k<total; k++) {
if(result[k] < 0) {
BT_Ins object = instructions[k];
if (element == object || (element != null && element.equals(object))) {
result[k] = i;
found++;
if(found == total) {
return result;
}
}
}
}
}
return result;
}
/**
* Inserts the specified object into this BT_InsVector at the specified
* location. This object is inserted before any previous element at
* the specified location. If the location is equal to the size of
* this BT_InsVector, the object is added at the end.
*
*
* @param object the object to insert in this BT_InsVector
* @param location the index at which to insert the element
*
* @exception ArrayIndexOutOfBoundsException when location < 0 || > size()
*
* @see #addElement
* @see #size
*/
public void insertElementAt(BT_Ins object, int location) {
int count;
if (location >= 0 && location <= elementCount) {
if (elementCount == elementData.length) {
int newCapacity =
(capacityIncrement == 0 ? elementCount : capacityIncrement)
+ elementCount;
if (newCapacity == 0) {
newCapacity = 1;
}
grow(newCapacity);
}
if ((count = elementCount - location) > 0) {
System.arraycopy(
elementData,
location,
elementData,
location + 1,
count);
}
elementData[location] = object;
elementCount++;
return;
}
throw new ArrayIndexOutOfBoundsException();
}
/**
* Answers if this BT_InsVector has no elements, a size of zero.
*
*
* @return true if this BT_InsVector has no elements, false otherwise
*
* @see #size
*/
public boolean isEmpty() {
return elementCount == 0;
}
/**
* Answers the last element in this BT_InsVector.
*
*
* @return the element at the last position
*
* @exception NoSuchElementException when this vector is empty
*
* @see #elementAt
* @see #firstElement
* @see #size
*/
public BT_Ins lastElement() {
try {
return elementData[elementCount - 1];
} catch (ArrayIndexOutOfBoundsException e) {
throw new NoSuchElementException();
}
}
/**
* Searches in this BT_InsVector for the index of the specified object. The
* search for the object starts at the end and moves towards the start
* of this BT_InsVector.
*
*
* @param object the object to find in this BT_InsVector
* @return the index in this BT_InsVector of the specified element, -1 if the
* element isn't found
*
* @see #contains
* @see #indexOf
*/
public int lastIndexOf(BT_Ins object) {
return lastIndexOf(object, elementCount - 1);
}
/**
* Searches in this BT_InsVector for the index of the specified object. The
* search for the object starts at the specified location and moves
* towards the start of this BT_InsVector.
*
*
* @param object the object to find in this BT_InsVector
* @param location the index at which to start searching
* @return the index in this BT_InsVector of the specified element, -1 if the
* element isn't found
*
* @exception ArrayIndexOutOfBoundsException when location >= size()
*
* @see #contains
* @see #indexOf
*/
public int lastIndexOf(BT_Ins object, int location) {
if (location < elementCount) {
for (int i = location; i >= 0; i--) {
if (elementData[i] == object)
return i;
}
return -1;
}
throw new ArrayIndexOutOfBoundsException();
}
/**
* Removes all elements from this BT_InsVector, leaving the size zero and
* the capacity unchanged.
*
*
* @see #isEmpty
* @see #size
*/
public void removeAllElements() {
for (int i = 0; i < elementCount; i++) {
elementData[i] = null;
}
elementCount = 0;
}
/**
* Removes the first occurrence, starting at the beginning and
* moving towards the end, of the specified object from this
* BT_InsVector.
*
*
* @param object the object to remove from this BT_InsVector
* @return true if the specified object was found, false otherwise
*
* @see #removeAllElements
* @see #removeElementAt
* @see #size
*/
public boolean removeElement(BT_Ins object) {
int index;
if ((index = indexOf(object, 0)) == -1)
return false;
removeElementAt(index);
return true;
}
/**
* Removes the element at the specified location from this BT_InsVector.
*
*
* @param location the index of the element to remove
*
* @exception ArrayIndexOutOfBoundsException when location < 0 || >= size()
*
* @see #removeElement
* @see #removeAllElements
* @see #size
*/
public void removeElementAt(int location) {
if (location < elementCount) {
int size;
elementCount--;
if ((size = elementCount - location) > 0) {
System.arraycopy(
elementData,
location + 1,
elementData,
location,
size);
}
elementData[elementCount] = null;
return;
}
throw new ArrayIndexOutOfBoundsException();
}
/**
* Replaces the element at the specified location in this BT_InsVector with
* the specified object.
*
*
* @param object the object to add to this BT_InsVector
* @param location the index at which to put the specified object
*
* @exception ArrayIndexOutOfBoundsException when location < 0 || >= size()
*
* @see #size
*/
public void setElementAt(BT_Ins object, int location) {
if (location < elementCount) {
elementData[location] = object;
return;
}
throw new ArrayIndexOutOfBoundsException();
}
/**
* Replaces the element at the specified location in this BT_InsVector with
* a clone of itself.
*
*
* @param location the index at which to clone the instruction
*
* @exception ArrayIndexOutOfBoundsException when location < 0 || >= size()
*
* @see #size
*/
public void cloneElementAt(int location) {
if (location < elementCount) {
elementData[location] = (BT_Ins) elementData[location].clone();
return;
}
throw new ArrayIndexOutOfBoundsException();
}
/**
* Sets the size of this BT_InsVector to the specified size. If there
* are more than length elements in this BT_InsVector, the elements
* at end are lost. If there are less than length elements in
* the BT_InsVector, the additional elements contain null.
*
*
* @param length the new size of this BT_InsVector
*
* @see #size
*/
public void setSize(int length) {
ensureCapacity(length);
if (elementCount > length) {
for (int i = length; i < elementCount; i++)
elementData[i] = null;
}
elementCount = length;
}
/**
* Answers the number of elements in this BT_InsVector.
*
*
* @return the number of elements in this BT_InsVector
*
* @see #elementCount
* @see #lastElement
*/
public int size() {
return elementCount;
}
/**
* Answers the string representation of this BT_InsVector.
*
*
* @return the string representation of this BT_InsVector
*
* @see #elements
*/
public String toString() {
if (elementCount == 0)
return "[]";
int length = elementCount - 1;
StringBuffer buffer = new StringBuffer();
buffer.append('[');
for (int i = 0; i < length; i++) {
buffer.append(elementData[i]);
buffer.append(',');
}
buffer.append(elementData[length]);
buffer.append(']');
return buffer.toString();
}
/**
* Sets the capacity of this BT_InsVector to be the same as the size.
*
*
* @see #capacity
* @see #ensureCapacity
* @see #size
*/
public void trimToSize() {
if (elementData.length != elementCount)
grow(elementCount);
}
public BT_Ins[] toArray() {
BT_Ins[] ins = new BT_Ins[this.size()];
for (int i = 0; i < this.size(); i++)
ins[i] = this.elementAt(i);
return ins;
}
// ---------- End of code common to all JikesBT Vectors ----------
/**
* returns whether the two vectors contain the same instructions, not necessarily in the same order
*/
public boolean hasSameInstructions(BT_InsVector other) {
int otherSize = other.size();
if(otherSize != size()) {
return false;
}
for(int i=0; i<otherSize; i++) {
BT_Ins otherIns = other.elementAt(i);
if(!contains(otherIns)) {
return false;
}
}
return true;
}
/**
* returns whether the two vectors contain the same instructions in the same order
*/
public boolean isSame(BT_InsVector other) {
int otherSize = other.size();
if(otherSize != size()) {
return false;
}
for(int i=0; i<otherSize; i++) {
BT_Ins otherIns = other.elementAt(i);
BT_Ins thisIns = elementAt(i);
boolean isSame = otherIns == null ? thisIns == null :
(otherIns == thisIns || otherIns.equals(thisIns));
if(!isSame) {
return false;
}
}
return true;
}
/**
Find the basic block marker with the specified byteIndex, and
create one if none already exists.
@param code the code containing the instruction
@param from the attribute making the reference (which may be the same as code)
@param the byte index into the bytecodes
@return The BT_BasicBlockMarkerIns found or created at the specified
byteIndex.
@exception BT_InstructionReferenceException If no such element can be created.
**/
public BT_BasicBlockMarkerIns findBasicBlock(BT_CodeAttribute code, BT_Attribute from, int bytecodeIndex)
throws BT_InstructionReferenceException {
try {
return findBasicBlock(bytecodeIndex);
} catch(IllegalArgumentException e) {
throw new BT_InstructionReferenceException(code, from, bytecodeIndex, e.getMessage());
}
}
public BT_BasicBlockMarkerIns findBasicBlock(BT_CodeAttribute code, BT_ExceptionTableEntry from,
int bytecodeIndex, boolean end)
throws BT_InstructionReferenceException {
try {
if(end) {
BT_Ins lastIns = lastElement();
if(bytecodeIndex == lastIns.byteIndex + lastIns.size()) {
if(lastIns.isBlockMarker()) {
return (BT_BasicBlockMarkerIns) lastIns;
}
//we are pointing to the end of the code array
BT_BasicBlockMarkerIns blockIns = BT_Ins.make();
blockIns.byteIndex = bytecodeIndex;
addElement(blockIns);
return blockIns;
}
}
return findBasicBlock(bytecodeIndex);
} catch(IllegalArgumentException e) {
throw new BT_InstructionReferenceException(code, from, bytecodeIndex, e.getMessage());
}
}
public BT_BasicBlockMarkerIns findBasicBlock(BT_CodeAttribute code, BT_Ins from, int bytecodeIndex)
throws BT_InstructionReferenceException {
try {
return findBasicBlock(bytecodeIndex);
} catch(IllegalArgumentException e) {
throw new BT_InstructionReferenceException(code, from, bytecodeIndex, e.getMessage());
}
}
private BT_BasicBlockMarkerIns findBasicBlock(int bytecodeIndex) {
return (BT_BasicBlockMarkerIns) findBlock(bytecodeIndex, true, false);
}
/**
* @param bytecodeIndex
* @param asBlockMarker whether to return a BT_BasicBlockMarkerIns instead of the matching instruction
* if the matching instruction is not a BT_BasicBlockMarkerIns
* @throws IllegalArgumentException if the bytecodeIndex is out of range
* @return the matching instruction, which will be a BT_BasicBlockMarkerIns if asBlockMarker is true
*/
private BT_Ins findBlock(int bytecodeIndex, boolean asBlockMarker, boolean notBlockMarker) throws IllegalArgumentException {
if (bytecodeIndex < 0) {
throw new IllegalArgumentException(Messages.getString("JikesBT.instruction_reference_out_of_range_3"));
}
/*
Experimentation has shown that typically the instruction index to be found is
57% the value of byte index.
Other things the experimentation showed:
in general, the average error in such a case is higher when underestimating
the correct instruction index, but in general this average is skewed by
a larger number of large errors when underestimating.
The total sum of the errors is about the same when missing above or below,
so 57% is the most efficient guess.
*/
/*
* We jump directly to the most likely location of the targeted instruction.
* If not a match, then we move upwards or downwards as required.
*/
int x = (int) (0.57 * (float) bytecodeIndex);
if(x > elementCount - 1) {
if(elementCount == 0) {
throw new IllegalArgumentException(Messages.getString("JikesBT.empty_vector_2"));
}
x = elementCount - 1;
}
int byteIndex = elementData[x].byteIndex; //both elementCount == 0 and index < 0 throws ArrayIndexOutOfBoundsException here
if(byteIndex == bytecodeIndex) {
return findBlock(x, bytecodeIndex, true, asBlockMarker, notBlockMarker);
} else if(byteIndex < bytecodeIndex) { /* must go upwards */
do {
++x;
if(x == elementCount) {
throw new IllegalArgumentException(Messages.getString("JikesBT.invalid_instruction_reference_4"));
}
byteIndex = elementData[x].byteIndex;
if (byteIndex == bytecodeIndex) {
return findBlock(x, bytecodeIndex, false, asBlockMarker, notBlockMarker);
}
} while(byteIndex < bytecodeIndex);
} else { /* must go downwards */
do {
--x;
if(x < 0) {
throw new IllegalArgumentException(Messages.getString("JikesBT.invalid_instruction_reference_4"));
}
byteIndex = elementData[x].byteIndex;
if (byteIndex == bytecodeIndex) {
return findBlock(x, bytecodeIndex, true, asBlockMarker, notBlockMarker);
}
} while(byteIndex > bytecodeIndex);
}
throw new IllegalArgumentException(Messages.getString("JikesBT.invalid_instruction_reference_4"));
}
private BT_Ins findBlock(
int instructionIndex,
int byteIndex,
boolean checkBelow,
boolean asBlockMarker,
boolean notBlockMarker) {
if(asBlockMarker) {
if(notBlockMarker) {
throw new IllegalArgumentException();//should never reach here
}
return markBlock(instructionIndex, byteIndex, checkBelow);
}
BT_Ins ins = elementData[instructionIndex];
if(notBlockMarker) {
while(ins.isBlockMarker()) {
++instructionIndex;
if(instructionIndex == elementCount) {
//this should never happen, the last instruction should not be a block marker
throw new IllegalArgumentException(Messages.getString("JikesBT.invalid_instruction_reference_4"));
}
ins = elementData[instructionIndex];
}
}
return ins;
}
private BT_BasicBlockMarkerIns markBlock(int instructionIndex, int byteIndex, boolean checkBelow) {
BT_BasicBlockMarkerIns result = markBlock(instructionIndex, checkBelow);
result.byteIndex = byteIndex;
return result;
}
/**
* places a block marker instruction at the specified instructionIndex corresponding
* to the specified blockIndex.
* @param checkBelow check if a block marker instruction exists one index
* less than instruction index. Such a block marker will suffice. This will
* prevent duplicates from being created. Set this parameter to false
* if you already know the instruction just before is not the required block marker.
*/
public BT_BasicBlockMarkerIns markBlock(int instructionIndex, boolean checkBelow) {
BT_Ins result1 = elementData[instructionIndex];
if(result1.isBlockMarker()) {
return (BT_BasicBlockMarkerIns) result1;
}
if(checkBelow && instructionIndex > 0) {
result1 = elementData[instructionIndex - 1];
if(result1.isBlockMarker()) {
return (BT_BasicBlockMarkerIns) result1;
}
}
BT_BasicBlockMarkerIns result = BT_Ins.make();
insertElementAt(result, instructionIndex);
return result;
}
/**
* Find the BT_Ins with the specified byteIndex.
*
* @return the BT_Ins found at the specified byteIndex.
* @see #findBasicBlock
* @exception BT_InstructionReferenceException if no such element exists.
*/
public BT_Ins findInstruction(BT_CodeAttribute code, BT_Attribute from, int bytecodeIndex) throws BT_InstructionReferenceException {
try {
return findBlock(bytecodeIndex, false, false);
} catch(IllegalArgumentException e) {
throw new BT_InstructionReferenceException(code, from, bytecodeIndex, e.getMessage());
}
}
public BT_Ins findNonBlockInstruction(BT_CodeAttribute code, BT_Attribute from, int bytecodeIndex) throws BT_InstructionReferenceException {
try {
return findBlock(bytecodeIndex, false, true);
} catch(IllegalArgumentException e) {
throw new BT_InstructionReferenceException(code, from, bytecodeIndex, e.getMessage());
}
}
/**
Reset the byteIndex for each instruction to its proper value.
**/
public int setAllByteIndexes() {
return setAllByteIndexes(false);
}
/**
Reset the byteIndex for each instruction to its maximum proper value.
**/
public int setAllByteIndexesMax() {
return setAllByteIndexes(true);
}
/**
Reset the byteIndex for each instruction to its proper value.
If max is true, then it assumes the instruction will take on its maximum size.
The ambiguity arises because there are a few instructions that very in size depending
upon the index of their references to the constant pool.
There are also some instructions that very in size depending upon the index of the local
variable that is utilized, however that should not produce ambiguity here because the code
attribute maintains a local vector so we are aware at all times of the index.
**/
public int setAllByteIndexes(boolean max) {
//we continue to recalculate the byte indices because the length of jump
//instructions is dependent upon the byte indices of their targets
//the recalculation continues until no more jump instructions are changed to/from
//wide instructions
int offset;
check:
do {
offset = 0;
for (int k = 0; k < size(); k++) {
BT_Ins instr = elementAt(k);
if(instr.byteIndex != offset) {
while(true) {
instr.setByteIndex(offset);
if(++k >= size()) {
continue check;
}
offset += max ? instr.maxSize() : instr.size();
instr = elementAt(k);
}
}
offset += max ? instr.maxSize() : instr.size();
}
break;
} while(true);
return offset;
}
public void initializeLabels() {
for (int n = 0, nLabels = 0; n < size(); n++) {
BT_Ins in1 = elementAt(n);
if(in1.isBlockMarker()) {
((BT_BasicBlockMarkerIns) in1).setLabel("label_" + (nLabels++));
}
}
}
}
|
package com.yinghai.a24divine_user.module.friend.list.mvp;
import com.example.fansonlib.base.BaseView;
import com.yinghai.a24divine_user.bean.FriendListBean;
import com.yinghai.a24divine_user.callback.IHandleCodeCallback;
/**
* @author Created by:fanson
* Created Time: 2017/11/27 14:44
* Describe:好友的契约类
*/
public interface ContractFriendList {
interface IView extends BaseView{
/**
* 获取好友列表成功
*/
void showGetFriendSuccess(FriendListBean.DataBean bean);
/**
* 获取好友列表失败
*/
void showGetFriendFailure(String errorMsg);
}
interface IPresenter{
/**
* 获取好友列表
*/
void getFriendList();
}
interface IModel{
/**
* 获取好友列表
*/
void onGetFriend(int page, IGetCallback callback);
interface IGetCallback extends IHandleCodeCallback{
/**
* 获取好友列表成功
*/
void onGetFriendSuccess(FriendListBean.DataBean bean);
/**
* 获取好友列表失败
*/
void onGetFriendFailure(String errorMsg);
}
}
}
|
package com.sy.service;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.naming.NamingException;
import org.apache.tomcat.dbcp.dbcp2.SQLExceptionList;
import com.lol.comm.DBConn;
import com.sy.dao.JGBoardDAO;
import com.sy.dto.JGBoardDTO;
import com.sy.dto.JGRepBoardDTO;
public class JGBoardService {
private static JGBoardService service = new JGBoardService();
public static JGBoardService getService() {
return service;
}
private JGBoardService() {}
public List<JGBoardDTO> list(int startRow, int endRow){
DBConn db = DBConn.getinstance();
Connection conn = null;
List<JGBoardDTO> list = null;
try {
conn = db.getConn();
conn.setAutoCommit(false);
JGBoardDAO dao = JGBoardDAO.getDAO();
list = dao.list(conn, startRow, endRow);
System.out.println("servicelist:" + list);
conn.commit();
}catch(NamingException|SQLException e) {
e.getStackTrace();
try { conn.rollback(); } catch(Exception e2) {}
}finally {
if(conn!=null) try {conn.close();} catch(SQLException e) {}
}
System.out.println(list+"4444444444444444");
return list;
}
public void insert(JGBoardDTO dto) {
DBConn db = DBConn.getinstance();
Connection conn = null;
try {
conn = db.getConn();
conn.setAutoCommit(false);
JGBoardDAO dao = JGBoardDAO.getDAO();
dao.insert(conn, dto);
conn.commit();
}catch(NamingException|SQLException e) {
e.getStackTrace();
try { conn.rollback(); } catch(SQLException e2) {}
}finally {
if( conn!=null ) try{ conn.close(); } catch(SQLException e) {}
}
}
public JGBoardDTO detail(int bno) {
DBConn db = DBConn.getinstance();
Connection conn = null;
JGBoardDTO dto = new JGBoardDTO();
try {
conn = db.getConn();
conn.setAutoCommit(false);
JGBoardDAO dao = JGBoardDAO.getDAO();
dto = dao.detail(conn, bno);
dao.upHit(conn, bno);
conn.commit();
}catch(NamingException|SQLException e) {
e.getStackTrace();
try { conn.rollback(); } catch(SQLException e2) {}
}finally {
if( conn!=null ) try{ conn.close(); } catch(SQLException e) {}
}
return dto;
}
//return 값 없어두댐
public JGBoardDTO update(JGBoardDTO dto, int bno) {
DBConn db = DBConn.getinstance();
Connection conn = null;
try {
conn = db.getConn();
conn.setAutoCommit(false);
JGBoardDAO dao = JGBoardDAO.getDAO();
dao.update(conn, bno, dto);
conn.commit();
}catch(NamingException|SQLException e) {
e.getStackTrace();
try { conn.rollback(); } catch(Exception e2) {}
}finally {
if( conn!=null ) try{ conn.close(); } catch(SQLException e) {}
}
return dto;
}
public void delete(int bno) {
DBConn db = DBConn.getinstance();
Connection conn = null;
try {
conn = db.getConn();
conn.setAutoCommit(false);
JGBoardDAO dao = JGBoardDAO.getDAO();
dao.delete(conn, bno);
conn.commit();
}catch(NamingException|SQLException e) {
e.getStackTrace();
try { conn.rollback(); } catch(Exception e2) {}
}finally {
if( conn!=null ) try{ conn.close(); } catch(SQLException e) {}
}
}
//댓글 추가
public void addRep(int bno, JGRepBoardDTO rdto) {
DBConn db = DBConn.getinstance();
Connection conn = null;
try {
conn = db.getConn();
conn.setAutoCommit(false);
JGBoardDAO dao = JGBoardDAO.getDAO();
dao.addRep(conn, bno, rdto);
conn.commit();
}catch(NamingException|SQLException e) {
e.getStackTrace();
try { conn.rollback(); } catch(Exception e2) {}
}finally {
if( conn!=null ) try{ conn.close(); } catch(SQLException e) {}
}
}
public List<JGRepBoardDTO> listReq(int bno) {
DBConn db = DBConn.getinstance();
Connection conn = null;
List<JGRepBoardDTO> list = new ArrayList<>();
try {
conn = db.getConn();
conn.setAutoCommit(false);
JGBoardDAO dao = JGBoardDAO.getDAO();
list = dao.ListRep(conn, bno);
conn.commit();
}catch(NamingException|SQLException e) {
System.out.println(e);
try {conn.rollback();} catch(Exception e2) {}
}finally {
if(conn!=null) try { conn.close(); } catch(SQLException e) {}
}
return list;
}
public int totalCount() {
DBConn db = DBConn.getinstance();
Connection conn = null;
int totalCount = 0;
try {
conn = db.getConn();
conn.setAutoCommit(false);
JGBoardDAO dao = JGBoardDAO.getDAO();
totalCount = dao.getTotalCount(conn);
conn.commit();
}catch(NamingException|SQLException e) {
System.out.println(e);
try {conn.rollback();} catch(Exception e2) {}
}finally {
if(conn!=null) try { conn.close(); } catch(SQLException e) {}
}
return totalCount;
}
}
|
package io.github.forezp.fastwebadmin.service;
import io.github.forezp.fastwebadmin.entity.SysUser;
import com.baomidou.mybatisplus.extension.service.IService;
import io.github.forezp.fastwebcommon.dto.PageResultsDTO;
/**
* <p>
* 用户 服务类
* </p>
*
* @author forezp
* @since 2021-09-01
*/
public interface SysUserService extends IService<SysUser> {
/**
* @param sysUser
* @return
*/
// Boolean addRecord(SysUser sysUser);
//
//
// Boolean updateRecord(SysUser sysUser);
//
// Boolean deleteRecord(SysUser sysUser);
//
// PageResultsDTO selectPage(int page, int pageSize, String userId, String mobile);
}
|
package com.dao.mainProxy.mapper;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.pojo.MainProxy;
public interface MainProxyMapper {
/**
* 注意要和Employeer.xml的方法名对应
*/
public MainProxy getMainProxyByID(int userId);
public List<MainProxy> getMainProxyLikeUsername(String username);
/**
* 注意要和Employeer.xml的方法名对应
*/
public int addMainProxy(MainProxy user);
/**
* 注意要和Employeer.xml的方法名对应
*/
public void deleteMainProxy(String user);
/**
* 注意要和Employeer.xml的方法名对应
*/
public int updateMainProxy(MainProxy user);
public int updateCardLTime(MainProxy user);
public int updateCardLCount(MainProxy count);
public int updateCardFCount(MainProxy count);
public List<MainProxy> getMainProxys(Map<String, Object> paramMap);
public int getMainProxysCount();
public int editPassword(MainProxy user);
}
|
package wx.realware.grp.pt.pb.TransactionManagement;
public interface IsmartServiceExecute {
void doExcute();
}
|
package class1.dwit.com.assignmentreminder.domain;
/**
* Created by User on 4/5/2017.
*/
public class Assignment {
String deadline;
String assignment_name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
String URL;
String batch;
int id;
String name;
public String getBatch() {
return batch;
}
public void setBatch(String batch) {
this.batch = batch;
}
public String getDeadline() {
return deadline;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setDeadline(String deadline) {
this.deadline = deadline;
}
public String getAssignment_name() {
return assignment_name;
}
public void setAssignment_name(String assignment_name) {
this.assignment_name = assignment_name;
}
public String getURL() {
return URL;
}
public void setURL(String URL) {
this.URL = URL;
}
}
|
package com.mx.profuturo.bolsa.service.common;
import com.mx.profuturo.bolsa.model.restclient.RequestBean;
import com.mx.profuturo.bolsa.model.service.sample.UserDataBean;
import com.mx.profuturo.bolsa.model.service.sample.UserInfoRequestBean;
import com.mx.profuturo.bolsa.model.service.sample.UserInfoResponseBean;
import com.mx.profuturo.bolsa.model.vo.common.UserInfoVO;
import com.mx.profuturo.bolsa.util.exception.custom.GenericStatusException;
/**
* Created by alejandro.hernandez on 10/05/2017.
*/
public abstract class UserDataServiceBase implements UserDataService {
@Override
public void getUser(Integer id, UserInfoVO userInfo) throws GenericStatusException {
UserInfoResponseBean userInfoResponse = getUserData(id);
if(!userInfoResponse.isSuccess()){
throw new GenericStatusException("404", "ID BUC NOT FOUND OR ERROR.");
}
this.buildBasicUserData(userInfo, userInfoResponse );
}
private void buildBasicUserData(UserInfoVO userInfo, UserInfoResponseBean userInfoResponse) {
UserDataBean userData = userInfoResponse.getData();
userInfo.setSecondLastName(userData.getApellidoMaterno());
userInfo.setFirstName(userData.getNombre());
userInfo.setLastName(userData.getApellidoPaterno());
}
private UserInfoResponseBean getUserData(Integer id) throws GenericStatusException {
UserInfoRequestBean userInfoRequestBean = new UserInfoRequestBean();
userInfoRequestBean.setIdClienteUnico(id);
RequestBean<UserInfoRequestBean> genericRequestBean = new RequestBean();
genericRequestBean.setPayload(userInfoRequestBean);
return callUserInfoService(genericRequestBean);
}
protected abstract UserInfoResponseBean callUserInfoService(RequestBean<UserInfoRequestBean> genericRequestBean) throws GenericStatusException;
}
|
package com.hesoyam.pharmacy.integration.user;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.hesoyam.pharmacy.user.dto.LoginDTO;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class LoginTests {
@Autowired
private MockMvc mockMvc;
@Test
void loginUnconfirmedAccountTest() throws Exception{
mockMvc.perform(post("/auth/login").contentType(MediaType.APPLICATION_JSON_VALUE).content(getUnconfirmedAccountLoginDataJSON())).andExpect(status().is(401));
}
private String getUnconfirmedAccountLoginDataJSON() throws JsonProcessingException {
LoginDTO loginDTO = new LoginDTO();
loginDTO.setEmail("hesoyampharmacy+leksa@gmail.com");
loginDTO.setPassword("00000000");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter ow = objectMapper.writer().withDefaultPrettyPrinter();
return ow.writeValueAsString(loginDTO);
}
}
|
package com.smxknife.flowable.springboot.ui.modeler;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author smxknife
* 2020/11/16
*/
@SpringBootApplication
public class ModelerBoot {
public static void main(String[] args) {
SpringApplication.run(ModelerBoot.class, args);
}
}
|
package by.bsu.lab9;
import by.bsu.lab9.util.Deleter;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class DeleterTest
{
String text = "bla bla bla\n" +
"bob ala bob\n" +
"biba boba vova";
Deleter del = new Deleter();
char symbol = 'b';
@Test
public void deleteSymbolTest() {
String expected = "la la la\n" +
"o ala o\n" +
"ia oa vova";
assertEquals(expected, del.deleteSymbol(text, symbol));
}
}
|
package net.trejj.talk.model;
public class CreditsModel {
private String id;
private String credits;
private String sku;
private String type;
private String title;
private String price;
private String price_usd;
private String desc;
public String getDesc() {
return desc;
}
public String getId() {
return id;
}
public String getCredits() {
return credits;
}
public String getSku() {
return sku;
}
public String getType() {
return type;
}
public String getTitle() {
return title;
}
public CreditsModel(String id, String credits, String sku, String type, String title, String price,
String price_usd, String desc) {
this.id = id;
this.credits = credits;
this.sku = sku;
this.type = type;
this.title = title;
this.price = price;
this.price_usd = price_usd;
this.desc = desc;
}
public String getPrice_usd() {
return price_usd;
}
public void setPrice_usd(String price_usd) {
this.price_usd = price_usd;
}
public String getPrice() {
return price;
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.bean.kea;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
/**
* MetadataDTO
*
* @author jllort
*/
public class MetadataDTO implements Serializable {
private static final long serialVersionUID = 2530668808598426112L;
private String fileName;
private String tempFileName;
private String mimeType = "";
private String title = "";
private String creator = "";
private String generator = "";
private String keyword = "";
private int pageCount;
private List<String> subjects;
private Date contentCreated = null;
private Date contentLastModified = null;
/**
* MetadataDTO
*/
public MetadataDTO() {
subjects = new ArrayList<String>();
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
if (creator != null) this.creator = creator;
}
public List<String> getSubjects() {
return subjects;
}
public List<Term> getSubjectsAsTerms() {
List<Term> terms = new ArrayList<Term>();
Iterator<String> iter = subjects.iterator();
while (iter.hasNext()) {
terms.add(new Term("",iter.next()));
}
return terms;
}
public void setSubjects(List<String> subjects) {
this.subjects = subjects;
}
public void addSubject(String subject) {
if (subject != null) subjects.add(subject);
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
if (fileName != null) this.fileName = fileName;
}
public String getTempFileName() {
return tempFileName;
}
public void setTempFileName(String tempFileName) {
if (tempFileName != null) this.tempFileName = tempFileName;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
if (mimeType != null) this.mimeType = mimeType;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
if (title != null) this.title = title;
}
public String getGenerator() {
return generator;
}
public void setGenerator(String generator) {
this.generator = generator;
}
public Date getContentCreated() {
if (contentCreated != null) {
return new Date(contentCreated.getTime());
} else {
return null;
}
}
public void setContentCreated(Date contentCreated) {
if (contentCreated != null) {
this.contentCreated = new Date(contentCreated.getTime());
} else {
this.contentCreated = null;
}
}
public Date getContentLastModified() {
if (contentLastModified != null) {
return new Date(contentLastModified.getTime());
} else {
return null;
}
}
public void setContentLastModified(Date contentLastModified) {
if (contentLastModified != null) {
this.contentLastModified = new Date(contentLastModified.getTime());
} else {
this.contentLastModified = null;
}
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MetadataDTO that = (MetadataDTO) o;
if (contentCreated != null ? !contentCreated.equals(that.contentCreated) : that.contentCreated != null)
return false;
if (contentLastModified != null ? !contentLastModified.equals(that.contentLastModified) : that.contentLastModified != null)
return false;
if (!creator.equals(that.creator)) return false;
if (!fileName.equals(that.fileName)) return false;
if (!mimeType.equals(that.mimeType)) return false;
if (!subjects.equals(that.subjects)) return false;
if (!tempFileName.equals(that.tempFileName)) return false;
if (!title.equals(that.title)) return false;
return true;
}
public int hashCode() {
int result;
result = fileName.hashCode();
result = 31 * result + tempFileName.hashCode();
result = 31 * result + mimeType.hashCode();
result = 31 * result + title.hashCode();
result = 31 * result + creator.hashCode();
result = 31 * result + (contentCreated != null ? contentCreated.hashCode() : 0);
result = 31 * result + (contentLastModified != null ? contentLastModified.hashCode() : 0);
return result;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("title=").append(title);
sb.append(", mimeType=").append(mimeType);
sb.append(", fileName=").append(fileName);
sb.append(", tempFileName=").append(tempFileName);
sb.append(", creator=").append(creator);
sb.append(", generator=").append(generator);
sb.append(", keyword=").append(keyword);
sb.append(", pageCount=").append(pageCount);
sb.append(", contentCreated=").append(contentCreated==null?null:contentCreated.getTime());
sb.append(", contentLastModified=").append(contentLastModified==null?null:contentLastModified.getTime());
sb.append(", subjects=").append(subjects);
sb.append("}");
return sb.toString();
}
}
|
package com.example.demo.service.impl;
import com.diboot.core.service.impl.BaseServiceImpl;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
/**
* 用户表相关Service实现
* @author Elvis
* @version 1.0.0
* @date 2019-11-30
* Copyright © Elvis.com
*/
@Service
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements UserService {
private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
}
|
package com.example.test.blooth;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import com.example.test.R;
import com.readyidu.eshw.api.bluetooth.ESHWBluetoothApi;
import com.readyidu.eshw.api.bluetooth.ESHWBluetoothListener;
import com.readyidu.eshw.util.Block;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
public class BongActivity extends Activity {
/**
* 手环
*/
private ESHWBluetoothApi bongBluetoothApi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bong);
bongBluetoothApi = new ESHWBluetoothApi();
ESHWBluetoothApi.startBluetooth(this, new Block() {
@Override
public void block(String... strings) {
bongBluetoothApi.bluetoothConnect( //bong3HR C9:D4:F2:04:6A:DC F0:5B:8D:C5:3B:2D bong2PH D6:5A:79:6B:88:C5
"bong2PH", "D6:5A:79:6B:88:C5",
"6e400001-b5a3-f393-e0a9-e50e24dcca1e",
"6e400003-b5a3-f393-e0a9-e50e24dcca1e",
"6e400002-b5a3-f393-e0a9-e50e24dcca1e", true, true);
bongBluetoothApi.setBluetoothListener(new ESHWBluetoothListener() {
@Override
public void bluetoothConnect() {
mUpdateBongStateHandler.removeCallbacks(mUpdateBongStateRunnable);
mUpdateBongStateHandler.post(mUpdateBongStateRunnable);
// BongHeartRate rate = new BongHeartRate();
// bongBluetoothApi.sendData(rate.getStartRateCommand());//测量心率
bongBluetoothApi.sendData(ay());//同步时间
}
@Override
public void bluetoothDisconnect() {
}
@Override
public void dataReceive(String s) {
// int rate = new BongHeartRate().getResult(s);
// Log.d("Heart Rate->", String.valueOf(rate));
Sport sport = getResult(s);
if (sport != null) {
Log.d("BongSport ->", sport.toString());
}
// bongBluetoothApi.sendData("end");
// mUpdateBongStateHandler.removeCallbacks(mUpdateBongStateRunnable);
// mUpdateBongStateHandler.post(mUpdateBongStateRunnable);
}
});
}
});
}
//TODO: 每隔一段时间上传BONG更新状态指令
private final long UPDATE_RATE = 1000l;
private Handler mUpdateBongStateHandler = new Handler();
private Runnable mUpdateBongStateRunnable = new Runnable() {
@Override
public void run() {
try {
BongHeartRate rate = new BongHeartRate();
//当处于测心律时,需要上传更新指令
// bongBluetoothApi.sendData(rate.getRateCommand());
//当处于测跑步时,需要上传更新指令
bongBluetoothApi.sendData(getSportCommand());
mUpdateBongStateHandler.postDelayed(mUpdateBongStateRunnable, UPDATE_RATE);
} catch (Exception e) {
e.printStackTrace();
}
}
};
public String ay() {
Calendar instance = Calendar.getInstance();
instance.setTime(new Date(System.currentTimeMillis()));
return "100000" + year(instance) + other(instance.get(Calendar.MONTH) + 1) +
other(instance.get(Calendar.DAY_OF_MONTH)) + other(instance.get(Calendar.HOUR_OF_DAY))
+ other(instance.get(Calendar.MINUTE)) + other(instance.get(Calendar.SECOND)) + "0800";
}
private String year(Calendar instance) {
String s = Integer.toHexString(instance.get(Calendar.YEAR));
if (!TextUtils.isEmpty(s)) {
if (s.length() < 4) {
return "0" + s;
} else {
return s;
}
}
return "0000";
}
private String other(int number) {
String s = Integer.toHexString(number);
if (!TextUtils.isEmpty(s)) {
if (s.length() < 2) {
return "0" + s;
} else {
return s;
}
}
return "00";
}
public String getSportCommand() {
return "2000000013"
+ getStrTimeForHex(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(1))
+ getStrTimeForHex(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(2));
}
public Sport getResult(String data) {
Log.i("guo", data);
String dataArray[] = data.split(" ");
if (dataArray.length == 16) {
try {
int year = Integer.parseInt(dataArray[3], 16) & 0xf0;
year |= (Integer.parseInt(dataArray[2], 16) & 0x03) << 4;
year += 2000;
int month = Integer.parseInt(dataArray[0], 16) >> 4;
int day = Integer.parseInt(dataArray[1], 16) >> 7;
day |= (Integer.parseInt(dataArray[0], 16) & 0x0f) << 1;
int hour = (Integer.parseInt(dataArray[1], 16) >> 2) & 0x1f;
int minute = (Integer.parseInt(dataArray[2], 16) & 0xf0) >> 4;
minute |= (Integer.parseInt(dataArray[1], 16) & 0x03) << 4;
int steps0, steps1;
steps0 = Integer.parseInt(dataArray[7], 16) & 0x7f;
steps0 |= (Integer.parseInt(dataArray[2], 16) << 4) & 0x80;
steps1 = Integer.parseInt(dataArray[11], 16) & 0x7f;
steps1 |= (Integer.parseInt(dataArray[2], 16) << 5) & 0x80;
Log.e("AAAAAAAA", year + " " + month + " " + day + " " + hour + " " + minute + " " + steps0 + " " + steps1);
Sport sport = new Sport();
sport.setEnergy(0);
sport.setStep(steps0);
sport.setDistance(0);
return sport;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public class Sport {
private int energy;
private int step;
private int distance;
public Sport() {
}
public Sport(int energy, int step, int distance) {
super();
this.energy = energy;
this.step = step;
this.distance = distance;
}
public int getEnergy() {
return energy;
}
public void setEnergy(int energy) {
this.energy = energy;
}
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
@Override
public String toString() {
return "Sport [energy=" + energy + ", step=" + step + ", distance="
+ distance + "]";
}
}
public String getStrTimeForHex(long time) {
TimeZone CHINA_TIMEZONE = TimeZone.getTimeZone("GMT+08:00");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
calendar.setTimeZone(CHINA_TIMEZONE);
int year = calendar.get(Calendar.YEAR) % 100;// 只取2位年份
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
return (year > 0xf ? "" : "0")
+ Integer.toHexString(year)
+ // 只取2位年份
(month > 0xf ? "" : "0") + Integer.toHexString(month)
+ (day > 0xf ? "" : "0") + Integer.toHexString(day)
+ (hour > 0xf ? "" : "0") + Integer.toHexString(hour)
+ (minute > 0xf ? "" : "0") + Integer.toHexString(minute);
}
}
|
package dev.schoenberg.kicker_stats.core.domain;
public class Admin extends Player {
public Admin(String name, String email, String hashedPassword) {
super(name, email, hashedPassword);
}
@Override
public boolean isAdmin() {
return true;
}
}
|
package com.tencent.mm.plugin.websearch;
class PluginWebSearch$a implements Runnable {
final /* synthetic */ PluginWebSearch pKx;
boolean pKy;
PluginWebSearch$a(PluginWebSearch pluginWebSearch, boolean z) {
this.pKx = pluginWebSearch;
this.pKy = z;
}
public final void run() {
PluginWebSearch.access$400(this.pKx, this.pKy);
}
}
|
package com.albabich.grad.web.menuitem;
import com.albabich.grad.model.MenuItem;
import com.albabich.grad.repository.MenuItemRepository;
import com.albabich.grad.to.MenuItemTo;
import com.albabich.grad.util.MenuItemUtil;
import com.albabich.grad.util.exception.NotFoundException;
import com.albabich.grad.web.AbstractControllerTest;
import com.albabich.grad.web.json.JsonUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import static com.albabich.grad.util.ValidationUtil.checkNotFoundWithId;
import static com.albabich.grad.web.menuitem.MenuItemTestData.*;
import static com.albabich.grad.web.restaurant.RestaurantTestData.REST1_ID;
import static com.albabich.grad.web.TestUtil.userHttpBasic;
import static com.albabich.grad.web.user.UserTestData.admin;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class AdminMenuItemControllerTest extends AbstractControllerTest {
private static final String REST_URL = AdminMenuItemController.REST_URL + '/';
@Autowired
MenuItemRepository menuItemRepository;
@Test
void get() throws Exception {
perform(MockMvcRequestBuilders.get(REST_URL + REST1_ID + "/menu-items/" + MENU_ITEM1_ID)
.with(userHttpBasic(admin)))
.andExpect(status().isOk())
.andDo(print())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(MENU_ITEM_MATCHER.contentJson(menuItem1));
}
@Test
void getNotFound() throws Exception {
perform(MockMvcRequestBuilders.get(REST_URL + REST1_ID + "/menu-items/" + NOT_FOUND)
.with(userHttpBasic(admin)))
.andExpect(status().isUnprocessableEntity());
}
@Test
void createWithLocation() throws Exception {
MenuItemTo newMenuItemTo = new MenuItemTo("idaho potatoes", 28000);
MenuItem newMenuItem = MenuItemUtil.createNewFromTo(newMenuItemTo);
ResultActions action = perform(MockMvcRequestBuilders.post(REST_URL + REST1_ID + "/menu-items/")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonUtil.writeValue(newMenuItemTo))
.with(userHttpBasic(admin)))
.andDo(print());
MenuItem created = MENU_ITEM_MATCHER.readFromJson(action);
int newId = created.id();
newMenuItem.setId(newId);
MENU_ITEM_MATCHER.assertMatch(created, newMenuItem);
MenuItem actualMenuItem = menuItemRepository.findById(newId).orElse(null);
MENU_ITEM_MATCHER.assertMatch(actualMenuItem, newMenuItem);
}
@Test
void update() throws Exception {
MenuItemTo updatedTo = new MenuItemTo(100007, "salad updated", 280);
perform(MockMvcRequestBuilders.put(REST_URL + REST1_ID + "/menu-items/" + MENU_ITEM1_ID)
.contentType(MediaType.APPLICATION_JSON)
.content(JsonUtil.writeValue(updatedTo))
.with(userHttpBasic(admin)))
.andExpect(status().isNoContent())
.andDo(print());
MenuItem actualMenuItem = menuItemRepository.findById(MENU_ITEM1_ID).orElse(null);
MENU_ITEM_MATCHER.assertMatch(actualMenuItem, MenuItemUtil.updateFromTo(new MenuItem(menuItem1), updatedTo));
}
@Test
void createInvalid() throws Exception {
MenuItemTo newMenuItemTo = new MenuItemTo("", 0);
perform(MockMvcRequestBuilders.post(REST_URL + REST1_ID + "/menu-items/")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonUtil.writeValue(newMenuItemTo))
.with(userHttpBasic(admin)))
.andDo(print())
.andExpect(status().isUnprocessableEntity());
}
@Test
void updateInvalid() throws Exception {
MenuItemTo updatedTo = new MenuItemTo(100007, "", 280);
perform(MockMvcRequestBuilders.put(REST_URL + REST1_ID + "/menu-items/" + MENU_ITEM1_ID)
.contentType(MediaType.APPLICATION_JSON)
.content(JsonUtil.writeValue(updatedTo))
.with(userHttpBasic(admin)))
.andDo(print())
.andExpect(status().isUnprocessableEntity());
}
@Test
@Transactional(propagation = Propagation.NEVER)
void createDuplicate() throws Exception {
MenuItemTo newMenuItemTo = new MenuItemTo("salad", 150);
perform(MockMvcRequestBuilders.post(REST_URL + REST1_ID + "/menu-items/")
.contentType(MediaType.APPLICATION_JSON)
.content(JsonUtil.writeValue(newMenuItemTo))
.with(userHttpBasic(admin)))
.andDo(print())
.andExpect(status().isConflict());
}
@Test
@Transactional(propagation = Propagation.NEVER)
void updateDuplicate() throws Exception {
MenuItemTo updatedTo = new MenuItemTo(100007, "lobio", 280);
perform(MockMvcRequestBuilders.put(REST_URL + REST1_ID + "/menu-items/" + MENU_ITEM1_ID)
.contentType(MediaType.APPLICATION_JSON)
.content(JsonUtil.writeValue(updatedTo))
.with(userHttpBasic(admin)))
.andDo(print())
.andExpect(status().isConflict());
}
@Test
void delete() throws Exception {
perform(MockMvcRequestBuilders.delete(REST_URL + REST1_ID + "/menu-items/" + MENU_ITEM1_ID)
.with(userHttpBasic(admin)))
.andExpect(status().isNoContent());
MenuItem deleted = menuItemRepository.findById(MENU_ITEM1_ID).orElse(null);
assertThrows(NotFoundException.class, () -> checkNotFoundWithId(deleted, MENU_ITEM1_ID));
}
@Test
void deleteNotFound() throws Exception {
perform(MockMvcRequestBuilders.delete(REST_URL + REST1_ID + "/menu-items/" + NOT_FOUND)
.with(userHttpBasic(admin)))
.andExpect(status().isUnprocessableEntity());
}
}
|
package haydende.mongodbdemo.service;
import haydende.mongodbdemo.domain.Teacher;
import haydende.mongodbdemo.repositories.TeacherRepository;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class TeacherServiceImpl implements TeacherService {
private final TeacherRepository teacherRepository;
public TeacherServiceImpl(TeacherRepository teacherRepository) {
this.teacherRepository = teacherRepository;
}
@Override
public Teacher findById(String id) {
Optional<Teacher> teacher = teacherRepository.findById(id);
if (teacher.isPresent()) {
return teacher.get();
}
throw new RuntimeException("No Teacher with ID of: " + id + " has been found!");
}
@Override
public Teacher findByLastName(String lastName) {
Optional<Teacher> teacher = teacherRepository.findByLastName(lastName);
if (teacher.isPresent()) {
return teacher.get();
}
throw new RuntimeException("No Teacher with a last name of: " + lastName + " has been found!");
}
@Override
public Teacher save(Teacher teacher) {
return teacherRepository.save(teacher);
}
@Override
public void delete(Teacher... teachers) {
for (Teacher t: teachers) {
teacherRepository.delete(t);
}
}
@Override
public void deleteById(String id) {
teacherRepository.deleteById(id);
}
@Override
public void deleteAll() {
teacherRepository.deleteAll();
}
@Override
public List<Teacher> findAll() {
return teacherRepository.findAll();
}
}
|
package com.thoughtworks.tw101.introductory_programming_exercises;
import java.util.*;
public class DiamondExercises {
public static void main(String[] args) {
drawAnIsoscelesTriangle(3);
drawADiamond(3);
drawADiamondWithYourName(3);
}
// Isosceles Triangle
// Given a number n, print a centered triangle. Example for n=3:
// *
// ***
// *****
private static void drawAnIsoscelesTriangle(int n) {
for (int i=0;i<n;i++){
String spaces = repeat(n-(i+1)," ");
String stars = repeat((2*i)+1, "*");
System.out.println(spaces + stars);
}
}
private static String repeat(int n, String character){
String returnItem = "";
for(int i=0;i<n;i++){
returnItem += character;
}
return returnItem;
}
// Diamond
// Given a number n, print a centered diamond. Example for n=3:
// *
// ***
// *****
// ***
// *
private static void drawADiamond(int n) {
for (int i=0;i<n;i++){
String spaces = repeat(n-(i+1)," ");
String stars = repeat((2*i)+1, "*");
System.out.println(spaces + stars);
}
for (int i =(n-2);i>=0;i--){
String spaces = repeat(n-(i+1)," ");
String stars = repeat((2*i)+1, "*");
System.out.println(spaces + stars);
}
}
// Diamond with Name
// Given a number n, print a centered diamond with your name in place of the middle line. Example for n=3:
//
// *
// ***
// Bill
// ***
// *
private static void drawADiamondWithYourName(int n) {
for (int i=0;i<n;i++){
String spaces = repeat(n-(i)," ");
String stars = repeat((2*i)+1, "*");
System.out.println(spaces + stars);
}
System.out.println("Lauren");
for (int i =(n-1);i>=0;i--){
String spaces = repeat(n-(i)," ");
String stars = repeat((2*i)+1, "*");
System.out.println(spaces + stars);
}
}
}
|
package com.guava;
import com.google.common.base.Strings;
/**
* guava demo
*/
public class StringDemo {
public static void main(String[] args) {
String demo1 = Strings.padStart("demo", 6, '1');
String demo2 = Strings.padEnd("demo", 5, '1');
String s = Strings.lenientFormat("%s12313%s", "start", "end");
System.out.println(demo1 + " " + demo2 + " " + s);
}
}
|
package com.bass.common.util;
import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class LoginIntercepter extends AbstractInterceptor {
/**
* 自定义登录拦截器
*/
private static final long serialVersionUID = 1L;
@Override
public String intercept(ActionInvocation intercept) throws Exception {
//System.out.println("拦截器执行");
ActionContext acCtx=intercept.getInvocationContext();
Map<String, Object> session=new HashMap<>();
session=acCtx.getSession();
//System.out.println(session.size());
if(session!=null&&session.size()>0){
intercept.invoke();
}
acCtx.put("tip", "没有登录权限");
return Action.LOGIN;
}
}
|
package info_2_ex_8;
public class JulianDate implements JulianDateInterface {
protected long days;
int gregDay;
int gregMonth;
int gregYear;
public JulianDate(int day, int month, int year) {
this.days=gregToJulian(day,month,year);
this.gregDay=day;
this.gregMonth=month;
this.gregYear=year;
}
public JulianDate(long julianDays) {
this.days=julianDays;
//from https://en.wikipedia.org/wiki/Julian_day
long f = days + 1401 + (((4 * days + 274277) / 146097) * 3) / 4 + (-38);
long h = 5 * (((4 * f + 3) % 1461) / 4) + 2;
gregDay = (int) (((h % 153)) / 5 + 1);
gregMonth = (int) (((h / 153 + 2) % 12) + 1);
gregYear = (int) (((4 * f + 3) / 1461) - 4716 + (12 + 2 - gregMonth) / 12);
}
private long gregToJulian (int day, int month, int year) {
long julianDate;
long a = ((14-month)/12);
long y = year+4800-a;
long m = month+12*a-3;
julianDate = day+(((153*m+2)/5))+365*y+(y/4)-(y/100)+(y/400)-32045;
return julianDate;
}
/* (non-Javadoc)
* @see JulianDateInterfaces#getDays()
*/
/* (non-Javadoc)
* @see JulianDateInterface#getDays()
*/
@Override
public long getDays() {
return this.days;
}
/* (non-Javadoc)
* @see JulianDateInterface#getGregDay()
*/
@Override
public int getGregDay() {
return this.gregDay;
}
/* (non-Javadoc)
* @see JulianDateInterface#getGregMonth()
*/
@Override
public int getGregMonth() {
return this.gregMonth;
}
/* (non-Javadoc)
* @see JulianDateInterface#getGregYear()
*/
@Override
public int getGregYear() {
return this.gregYear;
}
/* (non-Javadoc)
* @see JulianDateInterface#getGregYear()
*/
@Override
public String getGregDate() {
String fullDate = getGregDay() + "." + getGregMonth() + "." + getGregYear();
return fullDate;
}
public long daysSince(JulianDateInterface julianDate) {
return this.days-julianDate.getDays();
}
/* (non-Javadoc)
* @see JulianDateInterfaces#getWeekday()
*/
/* (non-Javadoc)
* @see JulianDateInterface#getWeekday()
*/
@Override
public String getWeekday() {
int weekday = (int)this.days%7;
switch(weekday) {
case 0: return "Monday";
case 1: return "Tuesday";
case 2: return "Wednesday";
case 3: return "Thursday";
case 4: return "Friday";
case 5: return "Saturday";
case 6: return "Sunday";
default: return "Error";
}
}
@Override
public String toString() {
return "jd_" + days;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (days ^ (days >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
JulianDate other = (JulianDate) obj;
if (days != other.days)
return false;
return true;
}
public static void main(String[] args) {
JulianDate date = new JulianDate(50);
System.out.println(date.getGregYear());
}
}
|
/*
PrescriptionFactory.java
Factory for the Prescription class
Author: Sonwabile Gxoyiya (219267189)
Date: 8 June 2021
*/
package za.ac.cput.Factory;
import za.ac.cput.Entity.Prescription;
import za.ac.cput.Util.CreateID;
public class PrescriptionFactory {
public static Prescription build(String prescriptionDate, String direction, int dosage, String reason){
String prescriptionID = CreateID.createUUID();
return new Prescription.Builder()
.setPrescriptionID(prescriptionID)
.setPrescriptionDate(prescriptionDate)
.setDirections(direction)
.setDosage(dosage)
.setReason(reason).build();
}
}
|
package com.rockooapps.carrentals;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AdminPass_Change extends AppCompatActivity {
EditText old, newpass, connew;
Button set;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_pass__change);
old = (EditText)findViewById(R.id.CurrentPass_Edittext);
newpass = (EditText)findViewById(R.id.NewPass_EditText);
connew = (EditText)findViewById(R.id.ConfirmPass_EditText);
set = (Button) findViewById(R.id.ChangeAdminPassButton);
//gets the keyvalue of password
final SharedPreferences sp = getSharedPreferences("LoginActivity", MODE_PRIVATE);
final String pas = sp.getString("Pass", "");
set.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Animation myAnim = AnimationUtils.loadAnimation(AdminPass_Change.this, R.anim.bounce);
set.startAnimation(myAnim);
BounceInterpolator interpolator = new BounceInterpolator(0.1, 40);
myAnim.setInterpolator(interpolator);
set.startAnimation(myAnim);
String nP= newpass.getText().toString();
String CnP= connew.getText().toString();
String Opa = old.getText().toString();
//checks if old password matches for change of new
//checks if new password is type correctly twice
if((Opa.equals(pas))&&(nP.equals(CnP))){
SharedPreferences.Editor SPEditor = sp.edit();
SPEditor.putString("Pass", CnP);
SPEditor.apply();
Toast.makeText(AdminPass_Change.this, "Password Changed", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(AdminPass_Change.this, "Wrong Password", Toast.LENGTH_SHORT).show();
}
}
});
}
}
|
package pl.finsys.valueInjectionExample;
/**
* Place description here.
*
* @author q1wk@nykredit.dk
*/
public class FileNameGenerator {
private String name;
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String generate() {
return String.format("name: %s, type: %s", name, type);
}
}
|
package com.londonappbrewery.magiceightball;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.Console;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
// Initializes ImageView and Button.
private ImageView ballDisplay;
private Button myButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating ImageView and Button.
ballDisplay = (ImageView)findViewById(R.id.image_eightball);
myButton = (Button)findViewById(R.id.askbutton);
//creates an array of images.
//Final, so that it cannot be changed.
final int[] ballArray = new int[]{R.drawable.ball1, R.drawable.ball2, R.drawable.ball3,
R.drawable.ball4, R.drawable.ball5};
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// creates an object for random number.
Random randomNumber = new Random();
//variable holds the random number object. Random numbers from 0-4.
int number = randomNumber.nextInt(5);
// Get images from the image array randomly and set that in the ImageView.
ballDisplay.setImageResource(ballArray[number]);
}// end of onClick
});// end of setOnClickListener.
}// end of onCreate.
}// end of MainActivity.
|
package com.sdk4.boot.domain;
import lombok.Data;
import org.hibernate.annotations.*;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
* 短信验证码
*
* @author sh
*/
@Data
@Entity(name = "BootSmsCode")
@Table(name = "bcom_sms_code")
public class SmsCode {
@Id
@GeneratedValue(generator = "idGenerator")
@GenericGenerator(name = "idGenerator", strategy = "uuid.hex", parameters = {
@org.hibernate.annotations.Parameter(name = "type", value = "string") })
private String id;
/**
* 验证码类型
*/
private String type;
/**
* 手机国际区号
*/
private String phoneArea;
/**
* 手机号码
*/
private String mobile;
/**
* 下发的验证码
*/
private String code;
/**
* 下发时间
*/
private Date createTime;
/**
* 使用时间
*/
private Date usedTime;
/**
* 短信渠道名称
*/
private String channelName;
/**
* 短信渠道返回的消息id
*/
private String msgId;
/**
* 状态
*/
private Integer status;
/**
* 状态说明
*/
private String statusDesc;
}
|
/**
* Copyright (c) 2004-2011 QOS.ch
* All rights reserved.
*
* 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 org.slf4j;
import java.io.Serializable;
import java.util.Iterator;
/**
* Markers are named objects used to enrich log statements. Conforming logging
* system implementations of SLF4J should determine how information conveyed by
* any markers are used, if at all. Many conforming logging systems ignore marker
* data entirely.
*
* <p>Markers can contain references to nested markers, which in turn may
* contain references of their own. Note that the fluent API (new in 2.0) allows adding
* multiple markers to a logging statement. It is often preferable to use
* multiple markers instead of nested markers.
* </p>
*
* @author Ceki Gülcü
*/
public interface Marker extends Serializable {
/**
* This constant represents any marker, including a null marker.
*/
public final String ANY_MARKER = "*";
/**
* This constant represents any non-null marker.
*/
public final String ANY_NON_NULL_MARKER = "+";
/**
* Get the name of this Marker.
*
* @return name of marker
*/
public String getName();
/**
* Add a reference to another Marker.
*
* <p>Note that the fluent API allows adding multiple markers to a logging statement.
* It is often preferable to use multiple markers instead of nested markers.
* </p>
*
* @param reference
* a reference to another marker
* @throws IllegalArgumentException
* if 'reference' is null
*/
public void add(Marker reference);
/**
* Remove a marker reference.
*
* @param reference
* the marker reference to remove
* @return true if reference could be found and removed, false otherwise.
*/
public boolean remove(Marker reference);
/**
* @deprecated Replaced by {@link #hasReferences()}.
*/
@Deprecated
public boolean hasChildren();
/**
* Does this marker have any references?
*
* @return true if this marker has one or more references, false otherwise.
*/
public boolean hasReferences();
/**
* Returns an Iterator which can be used to iterate over the references of this
* marker. An empty iterator is returned when this marker has no references.
*
* @return Iterator over the references of this marker
*/
public Iterator<Marker> iterator();
/**
* Does this marker contain a reference to the 'other' marker? Marker A is defined
* to contain marker B, if A == B or if B is referenced by A, or if B is referenced
* by any one of A's references (recursively).
*
* @param other
* The marker to test for inclusion.
* @throws IllegalArgumentException
* if 'other' is null
* @return Whether this marker contains the other marker.
*/
public boolean contains(Marker other);
/**
* Does this marker contain the marker named 'name'?
*
* If 'name' is null the returned value is always false.
*
* @param name The marker name to test for inclusion.
* @return Whether this marker contains the other marker.
*/
public boolean contains(String name);
/**
* Markers are considered equal if they have the same name.
*
* @param o
* @return true, if this.name equals o.name
*
* @since 1.5.1
*/
public boolean equals(Object o);
/**
* Compute the hash code based on the name of this marker.
* Note that markers are considered equal if they have the same name.
*
* @return the computed hashCode
* @since 1.5.1
*/
public int hashCode();
}
|
package other;
import java.util.ArrayList;
public class PascalTriangleRows {
public ArrayList<ArrayList<Integer>> generate(int a) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> zero = new ArrayList<Integer>();
zero.add(1);
ArrayList<Integer> one = new ArrayList<Integer>();
one.add(1);
one.add(1);
if(a <= 0) { return res; }
res.add(zero);
if(a == 1) { return res; }
res.add(one);
if(a == 2) { return res; }
for(int i = 2; i < a; i++) {
ArrayList<Integer> row = new ArrayList<Integer>();
row.add(1);
for(int j = 1; j < i; j++) {
ArrayList<Integer> prevRow = res.get(i - 1);
int toAdd = prevRow.get(j) + prevRow.get(j - 1);
// System.out.println(prevRow.get(j) + prevRow.get(j - 1));
row.add(toAdd);
}
row.add(1);
res.add(row);
}
return res;
}
public void print(ArrayList<ArrayList<Integer>> a) {
for(int i = 0; i < a.size(); i++) {
for(int j = 0; j < a.get(i).size(); j++) {
System.out.print(a.get(i).get(j) + " ");
}
System.out.println();
}
}
public static void main(String [] a) {
PascalTriangleRows pascal = new PascalTriangleRows();
ArrayList<ArrayList<Integer>> res = pascal.generate(6);
pascal.print(res);
}
}
|
package com.jim.multipos.ui.cash_management.view;
import com.jim.multipos.core.BaseView;
/**
* Created by Sirojiddin on 12.01.2018.
*/
public interface CashDetailsView extends BaseView {
void fillTillDetails(double totalStartingCash, double payOut, double payIn, double payToVendor, double incomeDebt, double bankDrop, double expectedCash, double tips, double cashTransactions);
void updateDetails();
}
|
package com.ua.serg.alex.buy.any.things.dao.daoImpl;
import com.ua.serg.alex.buy.any.things.dao.AdministratorDao;
import com.ua.serg.alex.buy.any.things.model.User;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Repository
public class AdministratorDaoImpl implements AdministratorDao {
@PersistenceContext
private EntityManager entityManager;
@Override
public void blockedUser(User user) {
}
}
|
package edu.iit.cs445.StateParking.UnitTest;
import static org.junit.Assert.*;
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.junit.Test;
import edu.iit.cs445.StateParking.Objects.*;
import edu.iit.cs445.StateParking.ObjectsEnum.State;
import edu.iit.cs445.StateParking.ObjectsEnum.VehicleType;
public class ListOfNoteAndOrderTest {
private ListOfNote Nlist = ListOfNote.getInstance();
private ListOfOrder Olist = ListOfOrder.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
@Test
public void test() throws ParseException {
Date date1= format.parse("19910909");
Date date2 = format.parse("19891226");
Date date3 = format.parse("20111212");
Date date4 = format.parse("20201001");
Nlist.createNote("a", "b");
Nlist.createNote("c", "d");
Vehicle Batcar = new Vehicle(State.NY, VehicleType.car, "BAT-I GOTHAM CITY");
CreditCard card = new CreditCard("373456789074007","Jane Smith","05/23","94102");
Olist.createOrder(Batcar, card);
assertTrue(Nlist.GetNoteWithin(date2, date1).isEmpty());
assertTrue(!Nlist.GetNoteWithin(date3, date4).isEmpty());
assertTrue(Olist.GetOrderWithin(date2, date1).isEmpty());
assertTrue(!Olist.GetOrderWithin(date3, date4).isEmpty());
}
}
|
package com.test.sqlsession;
import java.lang.reflect.Proxy;
/**
* @author wyj
* @date 2018/10/20
*/
public class SimpleSqlSession {
private Excutor excutor = new SimpleExecutor();
private SimpleConfiguration simpleConfiguration = new SimpleConfiguration();
public <T> T selectOne(String statement, Object parameter) {
return excutor.query(statement, parameter);
}
@SuppressWarnings("unchecked")
public <T> T getMapper(Class<T> clazz) {
return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new SimpleMapperProxy(this, simpleConfiguration));
}
}
|
package com.webcloud.model;
import java.io.Serializable;
/**
* 空气质量指数。
*
* @author bangyue
* @version [版本号, 2013-11-13]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class AqiModel implements Serializable {
@Override
public String toString() {
return "AqiModel [aqi=" + aqi + ", area=" + area + ", co=" + co + ", co_24h=" + co_24h + ", no2=" + no2
+ ", no2_24h=" + no2_24h + ", o3=" + o3 + ", o3_24h=" + o3_24h + ", o3_8h=" + o3_8h + ", o3_8h_24h="
+ o3_8h_24h + ", pm10=" + pm10 + ", pm10_24h=" + pm10_24h + ", pm2_5=" + pm2_5 + ", pm2_5_24h=" + pm2_5_24h
+ ", quality=" + quality + ", so2=" + so2 + ", so2_24h=" + so2_24h + ", time_point=" + time_point + "]";
}
public int getAqi() {
return aqi;
}
public void setAqi(int aqi) {
this.aqi = aqi;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public float getCo() {
return co;
}
public void setCo(float co) {
this.co = co;
}
public float getCo_24h() {
return co_24h;
}
public void setCo_24h(float co_24h) {
this.co_24h = co_24h;
}
public int getNo2() {
return no2;
}
public void setNo2(int no2) {
this.no2 = no2;
}
public int getNo2_24h() {
return no2_24h;
}
public void setNo2_24h(int no2_24h) {
this.no2_24h = no2_24h;
}
public int getO3() {
return o3;
}
public void setO3(int o3) {
this.o3 = o3;
}
public int getO3_24h() {
return o3_24h;
}
public void setO3_24h(int o3_24h) {
this.o3_24h = o3_24h;
}
public int getO3_8h() {
return o3_8h;
}
public void setO3_8h(int o3_8h) {
this.o3_8h = o3_8h;
}
public int getO3_8h_24h() {
return o3_8h_24h;
}
public void setO3_8h_24h(int o3_8h_24h) {
this.o3_8h_24h = o3_8h_24h;
}
public int getPm10() {
return pm10;
}
public void setPm10(int pm10) {
this.pm10 = pm10;
}
public int getPm10_24h() {
return pm10_24h;
}
public void setPm10_24h(int pm10_24h) {
this.pm10_24h = pm10_24h;
}
public int getPm2_5() {
return pm2_5;
}
public void setPm2_5(int pm2_5) {
this.pm2_5 = pm2_5;
}
public int getPm2_5_24h() {
return pm2_5_24h;
}
public void setPm2_5_24h(int pm2_5_24h) {
this.pm2_5_24h = pm2_5_24h;
}
public String getQuality() {
return quality;
}
public void setQuality(String quality) {
this.quality = quality;
}
public int getSo2() {
return so2;
}
public void setSo2(int so2) {
this.so2 = so2;
}
public int getSo2_24h() {
return so2_24h;
}
public void setSo2_24h(int so2_24h) {
this.so2_24h = so2_24h;
}
public String getTime_point() {
return time_point;
}
public void setTime_point(String time_point) {
this.time_point = time_point;
}
/***/
private static final long serialVersionUID = 4491896664430684702L;
int aqi;//: 95,
String area;//: "合肥",
float co;//: 0.871,
float co_24h;//: 0.872,
int no2;//: 44,
int no2_24h;//: 33,
int o3;//: 30,
int o3_24h;//: 43,
int o3_8h;//: 31,
int o3_8h_24h;//: 35,
int pm10;//: 96,
int pm10_24h;//: 94,
int pm2_5;//: 61,
int pm2_5_24h;//: 71,
String quality;//: "良",
int so2;//: 25,
int so2_24h;//: 22,
String time_point;//: "2013-11-13T17:00:00Z"
}
|
import java.util.Random;
public class VendingMachine {
private static double totalSales = 0;
private VendingItem[][][] grid = new VendingItem[6][3][5];
private int freeChance = 0;
private Random rand = new Random();
public VendingMachine() {
restock();
}
public VendingItem vend(String code) {
if (code.length() != 2) {
System.out.println("This code is not a valid code");
return null;
}
int rows = code.charAt(0) - 'A';
int col = code.charAt(1) - '1';
if ( rows < 0 || rows > 5 || col < 0 || col > 2) {
System.out.println("This code is not a valid code");
return null;
} else if (grid[rows][col][0] == null) {
System.out.println("This is empty one");
return null;
} else {
VendingItem out = grid[rows][col][0];
if (free()) {
System.out.println("Congrats, You got it for free !");
} else {
totalSales += out.getPrice();
}
for (int i = 0; i < 4; i++) {
grid[rows][col][i] = grid[rows][col][i+1];
}
grid[rows][col][4] = null;
return out;
}
}
private boolean free() {
if (rand.nextInt(2) + 1 <= freeChance) {
freeChance = 0;
return true;
} else {
freeChance ++;
return false;
}
}
public void restock() {
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 3; j++) {
for (int k = 0; k < 5; k++) {
int ranpick = new Random().nextInt(VendingItem.values().length);
if (grid[i][j][k] == null) {
grid[i][j][k] = VendingItem.values()[ranpick];
}
}
}
}
}
public static double getTotalSales() {
return totalSales;
}
public int getNumberOfItems() {
int count = 0;
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 3; j++) {
for (int k = 0; k < 5; k++) {
if (grid[i][j][k] != null) {
count++;
}
}
}
}
return count;
}
public double getTotalValue() {
double totalsum = 0;
for(int i = 0; i < 6; i++) {
for(int j = 0; j < 3; j++) {
for (int k = 0; k < 5; k++) {
if(grid[i][j][k] != null) {
totalsum += grid[i][j][k].getPrice();
}
}
}
}
return totalsum;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append("----------------------------------------------------------"
+ "------------\n");
s.append(" VendaTron 9000 "
+ " \n");
for (int i = 0; i < grid.length; i++) {
s.append("------------------------------------------------------"
+ "----------------\n");
for (int j = 0; j < grid[0].length; j++) {
VendingItem item = grid[i][j][0];
String str = String.format("| %-20s ",
(item == null ? "(empty)" : item.name()));
s.append(str);
}
s.append("|\n");
}
s.append("----------------------------------------------------------"
+ "------------\n");
s.append(String.format("There are %d items with a total "
+ "value of $%.2f.%n", getNumberOfItems(), getTotalValue()));
s.append(String.format("Total sales across vending machines "
+ "is now: $%.2f.%n", getTotalSales()));
return s.toString();
}
}
|
import java.util.Scanner;
public class NumbersInWords {
private String[] unidades;
private String[] dezena;
private String[] dezenas;
private String[] centenas;
public NumbersInWords() {
unidades = new String[] {"zero", "um", "dois", "trs", "quatro", "cinco", "seis", "sete", "oito", "nove"};
dezena = new String[] {"dez", "onze", "doze", "treze", "Quatorze", "quinze", "dezesseis", "dezessete", "dezoito", "dezenove"};
dezenas = new String[] {"vinte", "trinta", "quarenta", "cinquenta", "sessenta", "setenta", "oitenta", "noventa"};
centenas = new String[] {"cento", "duzentos", "trezentos", "quatrocentos", "quinhentos", "seiscentos", "setecentos", "oitocentos", "novecentos"};
}
/**
* Recebe um nmero e retorna sua escrita por extenso.
* @param int num
* @return String com a escreita do numero por extenso
*/
public String NumberToWords(int num) {
String numS = Integer.toString(num);
int numDigitos = numS.length();
if (numDigitos < 4) {
return centena (num);
}else if (numDigitos == 4) {
return milhar(num);
}else if (numDigitos == 5) {
return dezenaDeMilhar(num);
}else if (numDigitos == 6) {
return centenaDeMilhar(num);
}else if (numDigitos == 7) {
return milhoes(num);
}else if(numDigitos == 8) {
return dezenasDemilhoes(num);
}else if (numDigitos == 9) {
return centenasDemilhoes(num);
}else if(num == 1000000000){//1 bilhao
return "um bilho";
}
return "Numero invalido";
}
/**
* Recebe um nmero no intervalo(0-999) e retorna sua escrita por extenso.
* @param int num
* @return O num escrito por extenso
*/
private String centena (int num) {
if (num < 0) { // numeros menores que 0
return "Numero invalido";
}
if (num < 10) { // numeros entre 0 e 9
return unidades[num];
}else if (num < 20) { // numeros entre 10 e 19
return dezena[num - 10];
}else if (num < 100) { // numeros entre 20 e 99
if (num % 10 == 0) {
return dezenas[(num/10) - 2];
}
return dezenas[(num/10) - 2] + " e " + unidades[num % 10];
}else if (num < 1000) {// numeros entre 100 e 999
if (num == 100){
return "cem";
}else if (num % 100 == 0) { // numeros entre 101 e 109
return centenas[(num/100) - 1];
}else if (num % 100 < 10) { // numeros entre 101 e 109
return centenas[(num/100) - 1] + " e " + unidades[num % 100];
}else if (num % 100 < 20) { // numeros entre 110 e 119
return centenas[(num/100) - 1] + " e " + dezena[(num % 100) - 10];
}else if (num % 10 == 0) { // numeros entre 120 a 990 divisiveis por 10
return centenas[(num/100) - 1] + " e " + dezenas[((num % 100)/10) -2];
} // o restante dos numeros
}
return centenas[(num/100) - 1] + " e " + dezenas[((num % 100)/10) -2] + " e " + unidades[(num % 100) % 10];
}
/**
* Recebe um nmero de 4 digitos e retorna sua escrita por extenso.
* @param int num
* @return O num escrito por extenso
*/
private String milhar(int num) {
if (num == 1000) {//mil
return "mil";
}
int milhares = Integer.parseInt(Integer.toString(num).substring(0, 1));
int centenas = Integer.parseInt(Integer.toString(num).substring(1, 4));
if (milhares == 1) {
if (centenas <= 100) {
return "mil e " + NumberToWords(centenas);
}
return "mil " + NumberToWords(centenas);
}else {
if (centenas <= 100) {
return NumberToWords(milhares) + " mil e " + NumberToWords(centenas);
}
return NumberToWords(milhares) + " mil " + NumberToWords(centenas);
}
}
/**
* Recebe um nmero de 5 digitos e retorna sua escrita por extenso.
* @param int num
* @return O num escrito por extenso
*/
private String dezenaDeMilhar(int num) {
int milhares = Integer.parseInt(Integer.toString(num).substring(0, 2));
int centenas = Integer.parseInt(Integer.toString(num).substring(2, 5));
if (centenas == 0) {
return NumberToWords(milhares) + " mil";
}else if (centenas <= 100) {
return NumberToWords(milhares) + " mil e " + NumberToWords(centenas);
}
return NumberToWords(milhares) + " mil " + NumberToWords(centenas);
}
/**
* Recebe um nmero de 6 digitos e retorna sua escrita por extenso.
* @param int num
* @return O num escrito por extenso
*/
private String centenaDeMilhar(int num) {
int milhares = Integer.parseInt(Integer.toString(num).substring(0, 3));
int centenas = Integer.parseInt(Integer.toString(num).substring(3, 6));
if (centenas == 0) {
return NumberToWords(milhares) + " mil";
}else if (centenas <= 100) {
return NumberToWords(milhares) + " mil e " + NumberToWords(centenas);
}
return NumberToWords(milhares) + " mil " + NumberToWords(centenas);
}
/**
* Recebe um nmero de 7 digitos e retorna sua escrita por extenso.
* @param int num
* @return O num escrito por extenso
*/
private String milhoes(int num) {
if(num == 1000000){//1 milhao
return "um milho";
}
int milhoes = Integer.parseInt(Integer.toString(num).substring(0, 1));
int milhares = Integer.parseInt(Integer.toString(num).substring(1, 4));
int centenas = Integer.parseInt(Integer.toString(num).substring(4, 7));
return writeMilhoes(centenas, milhares, milhoes);
}
/**
* Recebe um nmero de 8 digitos e retorna sua escrita por extenso.
* @param int num
* @return O num escrito por extenso
*/
private String dezenasDemilhoes(int num) {
int milhoes = Integer.parseInt(Integer.toString(num).substring(0, 2));
int milhares = Integer.parseInt(Integer.toString(num).substring(2, 5));
int centenas = Integer.parseInt(Integer.toString(num).substring(5, 8));
return writeMilhoes(centenas, milhares, milhoes);
}
/**
* Recebe um nmero de 9 digitos e retorna sua escrita por extenso.
* @param int num
* @return O num escrito por extenso
*/
private String centenasDemilhoes(int num) {
int milhoes = Integer.parseInt(Integer.toString(num).substring(0, 3));
int milhares = Integer.parseInt(Integer.toString(num).substring(3, 6));
int centenas = Integer.parseInt(Integer.toString(num).substring(6, 9));
return writeMilhoes(centenas, milhares, milhoes);
}
/**
* Recebe as 3 unidades dos numeros de 7 a 9 digitos e aos retorna por extenso.
* @param int centenas
* @param int milhares
* @param int milhoes
* @return O num escrito por extenso
*/
private String writeMilhoes(int centenas, int milhares, int milhoes) {
String milhoess;
if (milhoes > 1) {
milhoess = " milhes ";
}else {
milhoess = " milho ";
}
if (centenas == 0 && milhares == 0) {
return NumberToWords(milhoes) + " milhes";
}else if (milhares == 0) {
if (centenas <= 100) {
return NumberToWords(milhoes) + milhoess + "e " + NumberToWords(centenas);
}
return NumberToWords(milhoes) + milhoess + NumberToWords(centenas);
}else if (centenas == 0) {
if (milhares < 100) {
return NumberToWords(milhoes) + milhoess + "e " + NumberToWords(milhares) + " mil";
}
return NumberToWords(milhoes) + milhoess + NumberToWords(milhares) + " mil";
}else {
if (centenas <= 100) {
return NumberToWords(milhoes) + milhoess + NumberToWords(milhares) + " mil e " + NumberToWords(centenas);
}
return NumberToWords(milhoes) + milhoess + NumberToWords(milhares) + " mil " + NumberToWords(centenas);
}
}
/**
* main
* Interface via linha de comando.
*
* @param args
*/
public static void main(String[] args) {
NumbersInWords numberToWords = new NumbersInWords();
String number = "";
System.out.println("Digite um nmero no intervalo de 0 a 1000000000!\n");
while(number.equals("")){
Scanner entrada = new Scanner(System.in);
number = entrada.nextLine();
try{
System.out.println("\n" + numberToWords.NumberToWords(Integer.parseInt(number)));
}catch(Exception e){
number = "";
System.out.println("\nVoc deve informar um nmero no intervalo de 0 a 1000000000!\n");
}
}
}
}
|
/**
* Write a description of class GumballMachine2 here.
*
* @author (your name)
* @version (a version number or a date)
*/
import java.util.Scanner;
public class GumballMachine2
{
//
GumballMachine gumballMachine = new GumballMachine(5);
int sum = 0;
/**
* Below function will perform loop for twice only
* If user fail to give money for second attemp then it will not process with GumBall Machine Two.
**/
public void GumballMachinetwo()
{
System.out.println("Now, We will perform Same method for GumBallMachine Two");
int money=accept_money();
if(money != 25)
{
System.out.println("Please Enter Quarter Only !!");
GumballMachinetwo();
}
else
{
sum = sum + money;
perform_operation(sum);
}
}
/**
* Below function will accept the value from user.
*/
static int accept_money(){
int money_inserted;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Money for GumBallMachine Second = ");
money_inserted=sc.nextInt();
return money_inserted;
}
public void perform_operation(int money){
if (money < 50)
{
System.out.println("You have enetered less Amount ! Please enter remaining Amount. You need to enter total of 50 Cents !!");
GumballMachinetwo();
}
else
{
gumballMachine.insertQuarter();
gumballMachine.turnCrank();
}
}
}
|
//package com.ybg.company.controller;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Controller;
//import org.springframework.ui.ModelMap;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.ResponseBody;
//import com.ybg.base.jdbc.BaseMap;
//import com.ybg.base.util.BaseControllor;
//import com.ybg.base.util.Json;
//import com.ybg.base.util.Page;
//import com.ybg.base.util.ServletUtil;
//import com.ybg.company.domain.Employee;
//import com.ybg.company.qvo.EmployeeQvo;
//import com.ybg.company.service.EmployeeService;
//import com.ybg.component.org.inter.Organization;
//import io.swagger.annotations.Api;
//@Api("员工管理")
//@Controller
//@RequestMapping("/org/employee_do/")
//public class EmployeeController extends BaseControllor {
//
// @Autowired
// EmployeeService employeeService;
//
// /** 新增初始化 **/
// @RequestMapping("toadd.do")
// // @SystemLog(module = "OaEmployee管理", methods = "创建初始化")
// public String toadd(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
// return "/xxpt/add";
// }
//
// /** 更新初始化 **/
// @RequestMapping("toupdate.do")
// // @SystemLog(module = "OaEmployee管理", methods = "更新初始化 ")
// public String toupdate(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
// String id = ServletUtil.getStringParamDefaultBlank(request, "id");
// Organization employee = employeeService.get(id);
// map.put("oaEmployee", employee);
// return "/xxpt/edit";
// }
//
// /** 新增 **/
// @ResponseBody
// @RequestMapping("create.do")
// // @SystemLog(module = "OaEmployee管理", methods = "创建")
// public Json add(HttpServletRequest request) throws Exception {
// Json j = new Json();
// try {
// Employee employee = getServletOaEmployee(request);
// employeeService.create(employee);
// j.setSuccess(true);
// j.setMsg("新增成功!");
// j.setObj(employee);
// } catch (Exception e) {
// e.printStackTrace();
// j.setMsg(e.getMessage());
// }
// return j;
// }
//
// // 获取信息
// private Employee getServletOaEmployee(HttpServletRequest request) {
// return (Employee) getCommandObject(request, Employee.class);
// }
//
// // 获取信息-查询
// private EmployeeQvo getServletOaEmployeeQvo(HttpServletRequest request) {
// return (EmployeeQvo) getCommandObject(request, EmployeeQvo.class);
// }
//
// /** 更新 **/
// @ResponseBody
// @RequestMapping("update.do")
// // @SystemLog(module = "OaEmployee管理", methods = "更新")
// public Json updateoaEmployee(HttpServletRequest request, HttpServletResponse response) throws Exception {
// Employee employee = getServletOaEmployee(request);
// Json j = new Json();
// j.setSuccess(true);
// try {
// BaseMap<String, Object> updatemap = new BaseMap<String, Object>();
// BaseMap<String, Object> wheremap = new BaseMap<String, Object>();
// employeeService.update(updatemap, wheremap);
// } catch (Exception e) {
// j.setMsg("操作失败!");
// j.setObj(employee);
// return j;
// }
// j.setMsg("操作成功!");
// return j;
// }
//
// /** 列表初始化 **/
// @RequestMapping("index.do")
// // @SystemLog(module = "OaEmployee管理", methods = "首页初始化")
// public String oaEmployeelistindex(HttpServletRequest request, HttpServletResponse response) throws Exception {
// return "/xxpt/index";
// }
//
// /** 获取列表 **/
// @ResponseBody
// @RequestMapping("list.do")
// // @SystemLog(module = "OaEmployee管理", methods = "分页列表")
// public Page getOaEmployee_List(HttpServletRequest request, HttpServletResponse response) throws Exception {
// EmployeeQvo qvo = getServletOaEmployeeQvo(request);
// Page page = new Page();
// page.setCurPage(getCurrentPage(request));
// page = employeeService.query(page, qvo);
// page.init();
// return page;
// }
//
// /** 删除 **/
// @ResponseBody
// @RequestMapping("remove.do")
// // @SystemLog(module = "OaEmployee管理", methods = "删除")
// public Json removeOaEmployee(HttpServletRequest request, HttpServletResponse response) throws Exception {
// Json j = new Json();
// j.setSuccess(true);
// String[] ids = ServletUtil.getStringParamDefaultBlank(request, "ids").trim().split(",");
// try {
// for (String id : ids) {
// BaseMap<String, Object> condition = new BaseMap<String, Object>();
// condition.put("id", id);
// employeeService.remove(condition);
// }
// } catch (Exception e) {
// e.printStackTrace();
// j.setMsg("操作失败");
// return j;
// }
// j.setMsg("操作成功");
// return j;
// }
//}
|
package com.ev.srv.demopai.model;
import lombok.Builder;
import lombok.Data;
import com.ev.srv.demopai.model.BaseModel;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* CardMovement
*/
@Data
@Builder
public class CardMovement extends BaseModel implements Serializable {
private static final long serialVersionUID = 1L;
@JsonProperty("sequential")
private Long sequential;
@JsonProperty("associatedAccountType")
private String associatedAccountType;
@JsonProperty("associatedAccountTypeDescription")
private String associatedAccountTypeDescription;
@JsonProperty("operationSign")
private Boolean operationSign;
@JsonProperty("loadedCurrencyId")
private String loadedCurrencyId;
@JsonProperty("loadedCurrencyIdDescription")
private String loadedCurrencyIdDescription;
@JsonProperty("loadedCurrencyIdSymbol")
private String loadedCurrencyIdSymbol;
@JsonProperty("movementTypeId")
private String movementTypeId;
@JsonProperty("movementTypeDescription")
private String movementTypeDescription;
@JsonProperty("inbox")
@ApiModelProperty(value = "Tag/s of the movement inserted by the client")
private List<String> inbox = null;
@JsonProperty("editedTimestamp")
private String editedTimestamp;
@JsonProperty("textNote")
private String textNote;
@JsonProperty("urlImage")
private String urlImage;
@JsonProperty("urlVideo")
private String urlVideo;
@JsonProperty("urlVoiceNote")
private String urlVoiceNote;
@JsonProperty("recordSource")
private String recordSource;
@JsonProperty("operationCardType")
private String operationCardType;
@JsonProperty("operationCardTypeDescription")
private String operationCardTypeDescription;
@JsonProperty("operationCardStatusId")
private String operationCardStatusId;
@JsonProperty("operationCardStatusIdDescription")
private String operationCardStatusIdDescription;
@JsonProperty("cardSequential")
private Long cardSequential;
@JsonProperty("statementMovementNumber")
private String statementMovementNumber;
@JsonProperty("statementNumber")
private String statementNumber;
@JsonProperty("operationCardSign")
private Boolean operationCardSign;
@JsonProperty("cardId")
private String cardId;
@JsonProperty("associatedCardId")
private String associatedCardId;
@JsonProperty("associatedCardType")
private String associatedCardType;
@JsonProperty("associatedCardTypeDescription")
private String associatedCardTypeDescription;
@JsonProperty("commerceId")
private String commerceId;
@JsonProperty("terminalCode")
private String terminalCode;
@JsonProperty("entityCode")
private String entityCode;
@JsonProperty("entityName")
private String entityName;
@JsonProperty("merchantCode")
private String merchantCode;
@JsonProperty("operationCardDate")
private String operationCardDate;
@JsonProperty("operationAmount")
private Double operationAmount;
@JsonProperty("operationCurrencyId")
private String operationCurrencyId;
@JsonProperty("operationCurrencyIdSymbol")
private String operationCurrencyIdSymbol;
@JsonProperty("operationCurrencyIdDescription")
private String operationCurrencyIdDescription;
@JsonProperty("operationLocation")
private String operationLocation;
@JsonProperty("operationCountry")
private String operationCountry;
@JsonProperty("operationCountrySymbol")
private String operationCountrySymbol;
@JsonProperty("operationCountryDescription")
private String operationCountryDescription;
@JsonProperty("cancelledOperation")
private Boolean cancelledOperation;
@JsonProperty("isCreditOperation")
private Boolean isCreditOperation;
@JsonProperty("isInternationalOperation")
private Boolean isInternationalOperation;
@JsonProperty("getisInstallmentPurchase")
private Boolean getisInstallmentPurchase;
@JsonProperty("accountCrossingIndex")
private Boolean accountCrossingIndex;
@JsonProperty("accountChargeIndex")
private Boolean accountChargeIndex;
@JsonProperty("operationFee")
private Double operationFee;
@JsonProperty("operationExchangeRate")
private Double operationExchangeRate;
@JsonProperty("operationCardDescription")
private String operationCardDescription;
@JsonProperty("categoryBusinessDescription")
private String categoryBusinessDescription;
@JsonProperty("billingCategoryId")
private String billingCategoryId;
@JsonProperty("billingCategoryDescription")
private String billingCategoryDescription;
@JsonProperty("fee")
private String fee;
@JsonProperty("friendFee")
private String friendFee;
@JsonProperty("paymentMethodId")
private String paymentMethodId;
@JsonProperty("contactlessType")
private String contactlessType;
@JsonProperty("date")
private String date;
@JsonProperty("bic")
private String bic;
}
|
package wrapper;
import beans.GuidelinesItems;
import java.util.List;
public class GuideLinesItemsOperate implements BasicOperate<GuidelinesItems> {
@Override
public GuidelinesItems getById(String x) {
return null;
}
@Override
public List<GuidelinesItems> getAll() {
return null;
}
@Override
public void insert(GuidelinesItems x) {
}
@Override
public void updateById(GuidelinesItems x) {
}
@Override
public void softDeleteById(String Id) {
}
@Override
public void forceDeleteById(String id) {
}
@Override
public void createTable() {
}
@Override
public void dropTable() {
}
}
|
package com.appsquadz.hostelutility;
class StudentApplicatoinsActivity {
}
|
package com.tencent.mm.modelvideo;
import com.tencent.mm.modelvideo.s$a.a;
import com.tencent.mm.sdk.e.k;
class s$1 extends k<s$a, a> {
final /* synthetic */ s enY;
s$1(s sVar) {
this.enY = sVar;
}
}
|
public class Test1 {
// crée une ligne de fruits à partir d'une chaîne de caractères
static Row stringToRow(String s) {
int[] fruits = new int[s.length()];
for (int i = 0; i < s.length(); i++)
fruits[i] = (s.charAt(i) == '0' ? 0 : 1);
return new Row(fruits);
}
// teste la méthode addFruit
// on suppose que si + "f" et so sont de même longueur
static void testAddFruit(String si, int f, String so) {
assert (stringToRow(si).addFruit(f).equals(stringToRow(so))) : "\nLa ligne\n" + si
+ "apres l'appel de addFruit(" + f + ") devrait être la ligne\n" + so + ".";
}
// teste la méthode allStableRows
static void testAllStableRows(int n, int r) {
int x = Row.allStableRows(n).size();
assert (x == r) : "\nIl y a " + r + " lignes stables de largeur " + n
+ " (votre méthode allStableRows en trouve " + x + ").";
}
// teste la méthode areStackable
static void testAreStackable(String s1, String s2, String s3, boolean e) {
assert (e == stringToRow(s1).areStackable(stringToRow(s2), stringToRow(s3))) : "\nLes lignes\n" + s1 + "\n" + s2
+ "\n" + s3 + "\n" + (e ? "devraient " : "ne devraient pas ") + "être empilables.";
}
public static void main(String[] args) {
// vérifie que les asserts sont activés
if (!Test1.class.desiredAssertionStatus()) {
System.err.println("Vous devez activer l'option -ea de la JVM");
System.err.println("(Run As -> Run configurations -> Arguments -> VM Arguments)");
System.exit(1);
}
// tests de la méthode addFruit
System.out.print("Test de la méthode addFruit ... ");
testAddFruit("", 0, "0");
testAddFruit("", 1, "1");
testAddFruit("011", 0, "0110");
testAddFruit("0100" + "1", 0, "010010");
testAddFruit("100110", 1, "1001101");
System.out.println("[OK]");
// tests de la méthode allStableRows
System.out.print("Test de la méthode allStableRows ... ");
int[] nums = new int[] { 1, 2, 4, 6, 10, 16, 26, 42, 68, 110, 178, 288, 466, 754, 1220, 1974, 3194, 5168, 8362,
13530 };
for (int n = 0; n < 20; n++)
testAllStableRows(n, nums[n]);
System.out.println("[OK]");
// tests de la méthode areStackable
System.out.print("Test de la méthode areStackable ... ");
// taille différente
testAreStackable("1010", "011", "100", false);
// test de la permière et dernière colonne (au cas ou une boucle for commence à
// 1 au lieu de 0)
testAreStackable("1", "1", "1", false);
testAreStackable("0", "0", "0", false);
// autres exemples
testAreStackable("1011", "0110", "1100", true);
testAreStackable("1011", "0110", "1101", true);
testAreStackable("0001", "0110", "1100", true);
testAreStackable("1101", "1110", "1100", false);
testAreStackable("101011", "011011", "110011", false);
testAreStackable("101", "011", "111", false);
System.out.println("[OK]");
}
}
|
package servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import databaseconnection.DBManager;
import registrazione.Dottore;
import registrazione.Paziente;
/**
* Servlet implementation class ServletLogin
*/
@WebServlet("/ServletLogin")
public class ServletLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
private Paziente p=null;
private Dottore d=null;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String user = request.getHeader("user");
String psw = request.getHeader("psw");
String tipo=request.getHeader("tipo");
HttpSession session = request.getSession();
if(tipo.equals("paziente")){
boolean valoreP=esistePaziente(user,psw);
if(valoreP){
p=riempiPaziente(user,psw);
}
if(valoreP==false || p==null){
response.setHeader("controllo", "no");
}
else{
session.setAttribute("paziente", p);
session.removeAttribute("dottore");
response.setHeader("controllo", "ok");
}
}
else if(tipo.equals("dottore")){
boolean valoreD= esisteDottore(user,psw);
if(valoreD){
d=riempiDottore(user,psw);
}
if(valoreD==false || d==null){
System.out.println("no ok");
response.setHeader("controllo", "no");
}
else{
session.setAttribute("dottore", d);
session.removeAttribute("paziente");
response.setHeader("controllo", "ok");
}
}
}
private Dottore riempiDottore(String user, String psw) {
Connection conn=null;
Statement s=null;
Dottore d=null;
try {
conn=DBManager.getInstance().getConnection();
String query="SELECT * FROM dottore WHERE dottore.email='"+user+"' AND dottore.password='"+psw+"'";
s=conn.createStatement();
ResultSet res=s.executeQuery(query);
while(res.next()) {
String a0=res.getString(1);
String a1=res.getString(2);
String a2=res.getString(3);
String a3=res.getString(4);
String a4=res.getString(5);
String a5=res.getString(6);
String a6=res.getString(7);
String a7=res.getString(8);
String a8=res.getString(9);
d=new Dottore(a0,a1,a2,a3,a4,a5,a6,a7,a8);
}
}
catch (SQLException e) {
e.printStackTrace();
return d;
} finally{
if(s!=null)
try {
s.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return d;
}
private boolean esisteDottore(String user, String psw) {
Connection conn=null;
Statement s=null;
try {
conn=DBManager.getInstance().getConnection();
String query="SELECT * FROM dottore WHERE dottore.email='"+user+"' AND dottore.password='"+psw+"'";
s=conn.createStatement();
s.executeQuery(query);
if(s.getResultSet() != null) //verifico che l'update abbia avuto effetto su una riga
return true;
else
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally{
if(s!=null)
try {
s.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private boolean esistePaziente(String user, String psw) {
Connection conn=null;
Statement s=null;
try {
conn=DBManager.getInstance().getConnection();
String query="SELECT * FROM paziente WHERE paziente.email='"+user+"' AND paziente.password='"+psw+"'";
s=conn.createStatement();
s.executeQuery(query);
if(s.getResultSet() != null) //verifico che l'update abbia avuto effetto su una riga
return true;
else
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally{
if(s!=null)
try {
s.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private Paziente riempiPaziente(String user, String psw) {
Connection conn=null;
Statement s=null;
Paziente p=null;
try {
conn=DBManager.getInstance().getConnection();
String query="SELECT * FROM paziente WHERE paziente.email='"+user+"' AND paziente.password='"+psw+"'";
s=conn.createStatement();
ResultSet res=s.executeQuery(query);
while(res.next()){
String a0=res.getString(1);
String a1=res.getString(2);
String a2=res.getString(3);
String a3=res.getString(4);
String a4=res.getString(5);
String a5=res.getString(6);
String a6=res.getString(7);
int a7=res.getInt(8);
Date a8=res.getDate(9);
p=new Paziente(a0,a1,a2,a3,a4,a5,a6,a7,a8);
}
}
catch (SQLException e) {
e.printStackTrace();
return p;
} finally{
if(s!=null)
try {
s.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return p;
}
}
|
/**
* Copyright 2013 Cloudera 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 org.kitesdk.tools;
import com.google.common.io.Closeables;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
/**
* <p>
* This class is an helper to copy the jars needed by the job in the Distributed cache.
* </p>
*
* <p>
* This tool helps to setup the job classpath at runtime. It allows library sharing between job. That result in faster
* jobs setup (since most of the time the libs are already uploaded in HDFS). Before submitting a job, you use this tool
* to provide the classes that you use in your job.
* </p>
*
* <p>
* The tool will find the jar(s), or will create the jars and upload them to a "library" path in HDFS, and it will
* create an md5 file along the uploaded jar.
* </p>
*
* <p>
* In order to find the jar or creating the job's Jar It use a modified version of org.apache.hadoop.util.JarFinder that
* is found in Hadoop 0.23
* </p>
*
* <p>
* If another job needs the same jar and provide the same "library" path it will discover it and use it, without having
* to lose the time that the upload of the jar would require.
* </p>
*
* <p>
* If the jar does not exist in the "library" path, it will upload it. However, if the jar is already in the "library"
* path, the tool will compute the md5 of the jar and compare with the one found in HDFS, and if there's a difference,
* the jar will be uploaded.
* </p>
*
* <p>
* If it creates a jar (from the classes of the job itself or from the classes in your workspace for example), it will
* upload the created jar to the "library" path and clean them after the JVM exits.
* </p>
*
* <p>
* Here's an example for a job class TestTool.class that requires HashFunction from Guava.
* </p>
*
* <pre>
* {@code
* new JobClasspathHelper().prepareClasspath(getConf(), new Path("/lib/path"), new Class[] { TestTool.class, HashFunction.class});
* }
* </pre>
*
* @author tbussier (tony.bussieres@ticksmith.com)
* @since 0.3.0
*
*
*/
public class JobClasspathHelper {
private static final Logger logger = LoggerFactory.getLogger(JobClasspathHelper.class);
/**
*
* @param conf
* Configuration object for the Job. Used to get the FileSystem associated with it.
* @param libDir
* Destination directory in the FileSystem (Usually HDFS) where to upload and look for the libs.
* @param classesToInclude
* Classes that are needed by the job. JarFinder will look for the jar containing these classes.
* @throws Exception
*/
public void prepareClasspath(final Configuration conf, final Path libDir, Class<?>... classesToInclude)
throws Exception {
FileSystem fs = null;
List<Class<?>> classList = new ArrayList<Class<?>>(Arrays.asList(classesToInclude));
fs = FileSystem.get(conf);
Map<String, String> jarMd5Map = new TreeMap<String, String>();
// for each classes we use JarFinder to locate the jar in the local classpath.
for (Class<?> clz : classList) {
if (clz != null) {
String localJarPath = JarFinder.getJar(clz);
// we don't want to upload the same jar twice
if (!jarMd5Map.containsKey(localJarPath)) {
// We should not push core Hadoop classes with this tool.
// Should it be the responsibility of the developer or we let
// this fence here?
if (!clz.getName().startsWith("org.apache.hadoop.")) {
// we compute the MD5 sum of the local jar
InputStream in = new FileInputStream(localJarPath);
boolean threw = true;
try {
String md5sum = DigestUtils.md5Hex(in);
jarMd5Map.put(localJarPath, md5sum);
threw = false;
} finally {
Closeables.close(in, threw);
}
} else {
logger.info("Ignoring {}, since it looks like it's from Hadoop's core libs", localJarPath);
}
}
}
}
for (Entry<String, String> entry : jarMd5Map.entrySet()) {
Path localJarPath = new Path(entry.getKey());
String jarFilename = localJarPath.getName();
String localMd5sum = entry.getValue();
logger.info("Jar {}. MD5 : [{}]", localJarPath, localMd5sum);
Path remoteJarPath = new Path(libDir, jarFilename);
Path remoteMd5Path = new Path(libDir, jarFilename + ".md5");
// If the jar file does not exist in HDFS or if the MD5 file does not exist in HDFS,
// we force the upload of the jar.
if (!fs.exists(remoteJarPath) || !fs.exists(remoteMd5Path)) {
copyJarToHDFS(fs, localJarPath, localMd5sum, remoteJarPath, remoteMd5Path);
} else {
// If the jar exist,we validate the MD5 file.
// If the MD5 sum is different, we upload the jar
FSDataInputStream md5FileStream = null;
String remoteMd5sum = "";
try {
md5FileStream = fs.open(remoteMd5Path);
byte[] md5bytes = new byte[32];
if (32 == md5FileStream.read(md5bytes)) {
remoteMd5sum = new String(md5bytes, Charsets.UTF_8);
}
} finally {
if (md5FileStream != null) {
md5FileStream.close();
}
}
if (localMd5sum.equals(remoteMd5sum)) {
logger.info("Jar {} already exists [{}] and md5sum are equals", jarFilename, remoteJarPath.toUri()
.toASCIIString());
} else {
logger.info("Jar {} already exists [{}] and md5sum are different!", jarFilename, remoteJarPath
.toUri().toASCIIString());
copyJarToHDFS(fs, localJarPath, localMd5sum, remoteJarPath, remoteMd5Path);
}
}
// In all case we want to add the jar to the DistributedCache's classpath
DistributedCache.addFileToClassPath(remoteJarPath, conf, fs);
}
// and we create the symlink (was necessary in earlier versions of Hadoop)
DistributedCache.createSymlink(conf);
}
/**
* @param fs
* File system where to upload the jar.
* @param localJarPath
* The local path where we find the jar.
* @param md5sum
* The MD5 sum of the local jar.
* @param remoteJarPath
* The remote path where to upload the jar.
* @param remoteMd5Path
* The remote path where to create the MD5 file.
*
* @throws IOException
*/
private void copyJarToHDFS(FileSystem fs, Path localJarPath, String md5sum, Path remoteJarPath, Path remoteMd5Path)
throws IOException {
logger.info("Copying {} to {}", localJarPath.toUri().toASCIIString(), remoteJarPath.toUri().toASCIIString());
fs.copyFromLocalFile(localJarPath, remoteJarPath);
// create the MD5 file for this jar.
createMd5SumFile(fs, md5sum, remoteMd5Path);
// we need to clean the tmp files that are are created by JarFinder after the JVM exits.
if (remoteJarPath.getName().startsWith(JarFinder.TMP_HADOOP)) {
fs.deleteOnExit(remoteJarPath);
}
// same for the MD5 file.
if (remoteMd5Path.getName().startsWith(JarFinder.TMP_HADOOP)) {
fs.deleteOnExit(remoteMd5Path);
}
}
/**
* This method creates an file that contains a line with a MD5 sum
*
* @param fs
* FileSystem where to create the file.
* @param md5sum
* The string containing the MD5 sum.
* @param remoteMd5Path
* The path where to save the file.
* @throws IOException
*/
private void createMd5SumFile(FileSystem fs, String md5sum, Path remoteMd5Path) throws IOException {
FSDataOutputStream os = null;
try {
os = fs.create(remoteMd5Path, true);
os.writeBytes(md5sum);
os.flush();
} catch (Exception e) {
logger.error("{}", e);
} finally {
if (os != null) {
os.close();
}
}
};
}
|
package com.dns.feedbox.service;
import com.dns.feedbox.entity.Feed;
import com.dns.feedbox.repo.FeedRepo;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by dinusha on 11/12/16.
*/
@Service
public class FeedService {
private FeedRepo feedRepo;
public FeedService(FeedRepo feedRepo) {
this.feedRepo = feedRepo;
}
public List<Feed> getAllFeeds() {
return feedRepo.findAll();
}
}
|
//FILE: Controller.Java
//PROG: Adam Barker
//PURP: Instantiates Cab objects and passes Cab objects into UI
package edu.trident.barker.cpt237;
import java.util.ArrayList;
import java.util.List;
public class Controller implements CabLoader {
private Cab2 cab;
private List<Cab2> cabs = new ArrayList<Cab2>();
public Controller() {
}
/**
* Constructs Cab Objects and puts them in an ArrayList. Instantiates
* MultiCabUI.java
*
* @author Adam Barker
*/
public void contsruct() {
cabs.add(new Cab2("Cab1", 25, 33));
cabs.add(new Cab2("Cab2", 21, 28));
cabs.add(new Cab2("Cab3", 23, 19));
cabs.add(new Cab2("Cab4", 16, 22));
cabs.add(new Cab2("Cab5", 18, 26));
@SuppressWarnings("unused")
MultiCabUI cabUi = new MultiCabUI(setCabNames(), this);
}
/**
* Loads Cab Objects into MultiCabUI.java
*
* @author Adam Barker
*/
@Override
public Cab2 loadCab(String name) {
for(Cab2 cabName : cabs){
if(cabName.getName() == name)
cab = cabName;
}
return cab;
}
/**
* Returns string values of Cab Objects ArrayList's names and populates them
* into an array
*
* @return
*/
public String[] setCabNames() {
String[] cabNames = new String[cabs.size()];
for (int i = 0; i < cabs.size(); i++) {
cabNames[i] = cabs.get(i).getName();
}
return cabNames;
}
}
|
package ch11;
public class Dog extends Pets{
void setName(String name){
this.name = name;
}
String getName(){
return this.name;
}
void setColor(String name){
this.name = color;
}
String getColor(){
return this.color;
}
public Dog(){
this.name = "Pesho";
this.color = "white";
}
public Dog(String name, String color){
this.name = name;
this.color = color;
}
private static void makeBau(){
System.out.println("Bauuuuuu");
}
}
|
package com.sanju.exceptionHandling;
public class ExcetionInFinallyBlockDemo1 {
/**
* NOTE:Output order will be different for every run
*/
public static void main(String[] args) {
int a[] = {1,2,3,4,5};
try {
System.out.println("Accessing sixth element" + a[5]);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} finally {
System.out.println("finally block start");
try {
double divide = a[3] / 0;
System.out.println("Divide result:" + divide);
} catch (ArithmeticException e2) {
e2.printStackTrace();
}
System.out.println("Finall block end");
}
System.out.println("rest of the code");
}
}
|
package com.accp.pub.pojo;
public class Organization {
private Integer organizationid;
private String organizationname;
private String bz1;
private String bz2;
private Integer pid;
public Integer getOrganizationid() {
return organizationid;
}
public void setOrganizationid(Integer organizationid) {
this.organizationid = organizationid;
}
public String getOrganizationname() {
return organizationname;
}
public void setOrganizationname(String organizationname) {
this.organizationname = organizationname == null ? null : organizationname.trim();
}
public String getBz1() {
return bz1;
}
public void setBz1(String bz1) {
this.bz1 = bz1 == null ? null : bz1.trim();
}
public String getBz2() {
return bz2;
}
public void setBz2(String bz2) {
this.bz2 = bz2 == null ? null : bz2.trim();
}
public Integer getPid() {
return pid;
}
public void setPid(Integer pid) {
this.pid = pid;
}
}
|
package com.tiger;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tiger.common.UserInfo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import java.io.IOException;
/**
* 指定当前生效的配置文件( active profile),如果是 appplication-dev.yml 则 dev
**/
@ActiveProfiles("dev")
@SpringBootTest(classes = AdminApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class BaseTest {
private ObjectMapper objectMapper = new ObjectMapper();
@Test
public void test() throws IOException {
String json = "{\"id_user\":123,\"mobile\":\"123456789\",\"username\":\"json在线解析\"}";
UserInfo userInfo = new ObjectMapper().readValue(json.getBytes(), UserInfo.class);
System.out.println(userInfo);
}
}
|
package com.lr.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TestPaper {
private static final long serialVersionUID = -3558785342343129L;
private Integer id;
private String testpaperId;
private Integer subjectType;
private Integer subjectNum;
private Integer state;
}
|
package com.hallauniv.dialog;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;
import com.hallauniv.halla.R;
public class AlertDialog extends Activity{
private ImageButton m_ok;
private ImageButton m_dismiss;
private TextView m_alert;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
/*getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
*/
setContentView(R.layout.dialog_alert);
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 0.9f;
getWindow().setAttributes(lp);
setContentView(R.layout.dialog_alert);
//배경투명처리
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
m_alert = (TextView)findViewById(R.id.txt_alert);
m_ok = (ImageButton)findViewById(R.id.itn_alert_ok);
m_dismiss = (ImageButton)findViewById(R.id.itn_alert_dismiss);
Intent getIntent=getIntent();
if(getIntent.getStringExtra("alert") != null)
m_alert.setText(getIntent.getStringExtra("alert"));
m_ok.setOnClickListener(new OnClickListener() {
public void onClick(View v){
finish(); // 액티비티 종료
}
});
m_dismiss.setOnClickListener(new OnClickListener() {
public void onClick(View v){
finish();
}
});
}
public void onDestroy() { // 앱이 소멸되면
super.onDestroy();
}
}
|
package com.dh.Services;
import com.dh.JavaBean.*;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface UserServices {
User userLogin(String username, String password);
List<Recruit> findMessage();
void saveremuse(remuse rr);
Recruit findRecruitByid(Integer rid);
User findUserbyid(Integer uid);
List<remuse> findRemusebuName(String username);
String selectDept(Integer deptid);
String selectposi(Integer pid);
int employeeclocking(Integer id);
List<Cadets> SelectCadets(Integer uid);
List<bonus> selectBonus(Integer uid);
List<EmployeePay> selectPay(Integer uid);
}
|
package com.fillikenesucn.petcare.adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.fillikenesucn.petcare.R;
import com.fillikenesucn.petcare.activities.PetListFragmentActivity;
import com.fillikenesucn.petcare.models.Pet;
import java.util.ArrayList;
import java.util.Random;
/**
* Esta clase define objetos adapters que seran utilizados para los recyclerview del llistado de las mascotas registradas
* Permitiendo gestionar un adapter para el controlar las funcionalidades del los items pertenecientes al listado
* @author: Marcelo Lazo Chavez
* @version: 28/03/2020
*/
public class PetListAdapter extends RecyclerView.Adapter<PetListAdapter.PetHolder>{
//VARIABLES
private Context mContext;
private ArrayList<Pet> mPetList = new ArrayList<>();
// LISTADO DE LAS IMAGENES ESTATICAS QUE SE DESPLEGARÁN EN EL LISTADO
private ArrayList<Integer> dogDrawList = new ArrayList<>();
private ArrayList<Integer> catDrawList = new ArrayList<>();
/**
* Constructor para el adaptador del listado de mascotas asociadas al recyclerview
* Además de inicializar las imagenes estaticas de perros y gatos que se desplagarán en el listado
* @param mContext contexto asociado a la vista que llama al constructor
* @param mPetList listado de mascotas (tipo objeto PET)
*/
public PetListAdapter(Context mContext, ArrayList<Pet> mPetList) {
this.mPetList = mPetList;
this.mContext = mContext;
InitDrawImages();
}
/**
* Método que se encarga de poblar el listado de imagenes asociadas a las mascotas
* asociando su identificador numerico registrado en la aplicación
*/
private void InitDrawImages(){
dogDrawList = DataHelper.GetDogsImages();
catDrawList = DataHelper.GetCatsImages();
}
/**
* Método que se ejecuta para crear los holders del adaptador
* Creará las instancias del layout asociadas a los items xml que tendra los componentes de las mascotas
* @param viewGroup Es el componente al cual se le asociara los items del adapter
* @param i Indice asociado a la posición de la mascota en el listado
* @return Retorna un objeto PetHolder que tiene asociado los ocmponentes del item de la lista de mascota
*/
@NonNull
@Override
public PetHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_petlistitem, viewGroup, false);
PetHolder petHolder = new PetHolder(view);
return petHolder;
}
/**
* Método que setea a un item del listado sus valores correspondientes/asociados a una mascota que se encuentra
* en el listado de mascotas
* Además de integrarla las funcionalidades onCLICK para su funcionamiento dentro de la aplicación
* @param petHolder Objeto que tiene asociado los componentes del item del listado del adapter
* @param i indice asociado a la mascota del listado de mascota
*/
@Override
public void onBindViewHolder(@NonNull final PetHolder petHolder, final int i) {
final Pet petItem = mPetList.get(i);
petHolder.petName.setText(petItem.getName());
// SETEA UNA IMAGEN AL ITEM DEL ADAPTER
petHolder.image.setImageResource(GetDrawableImagePet(petItem.getSpecies()));
// SE LE AÑADE LA FUNCIONALIDAD DE QUE CUANDO SE CLICKE EL ITEM, SE DIRIGA A LA VISTA PETINFO
petHolder.parentLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mContext instanceof PetListFragmentActivity){
((PetListFragmentActivity)mContext).OpenInfoPet(petItem.getEPC());
}else{
Toast.makeText(mContext, "Ha ocurrido un error con esta mascota!", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Método que se encarga de retornar un identificador numerico asociada a la imagen/drawable al tipo de especie
* a la cual esta asociada una mascota, escogiendo una de forma aletoria de un pool de imagenes para cada especie
* @param specie Valor string que tiene el nombre de la especie de la mascota (gato/perro)
* @return retorna el identificador de la imagen que se desea asociar
*/
private int GetDrawableImagePet(String specie){
Random random = new Random();
switch (specie.toUpperCase()){
case "PERRO":
return dogDrawList.get(random.nextInt(dogDrawList.size()));
case "GATO":
return catDrawList.get(random.nextInt(catDrawList.size()));
default:
return R.drawable.ic_launcher;
}
}
/**
* Método que retona el tamaño de mascotas asociadas al listado del adapter
* @return retorna la cantidad de mascotas
*/
@Override
public int getItemCount() {
return mPetList.size();
}
/**
* Clase que retornar un objeto que tendra asociado los elementos pertenecientes a los item del listado
* del layout al cual estará asociado el adapter del recyclerview
*/
public class PetHolder extends RecyclerView.ViewHolder{
// VARIABLES
ImageView image;
TextView petName;
RelativeLayout parentLayout;
/**
* Constructor para el holder del item del listado de mascotas del layout
* @param itemView Es el layout perteneciente al item del listado de mascotas, tendra los componentes que se
* desean asociar a la vista del listado de mascotas
*/
public PetHolder(@NonNull View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
petName = (TextView) itemView.findViewById(R.id.petname);
parentLayout = (RelativeLayout) itemView.findViewById(R.id.parent_layout);
}
}
}
|
package Grupo1;
import javax.swing.text.AbstractDocument;
import javax.swing.text.Element;
public class EstendeMesmaClasse1 extends AbstractDocument {
protected EstendeMesmaClasse1(Content data, AttributeContext context) {
super(data, context);
// TODO Auto-generated constructor stub
}
@Override
public Element getDefaultRootElement() {
// TODO Auto-generated method stub
return null;
}
@Override
public Element getParagraphElement(int pos) {
// TODO Auto-generated method stub
return null;
}
}
|
package com.zhouyi.business.core.model;
import java.io.Serializable;
import java.util.Date;
public class LedenCollectSgtzzc implements Serializable {
private String pkId;
private String ryjcxxcjbh;
private String sg;
private String tz;
private String zc;
private String deletag;
private String annex;
private String createUserId;
private Date createDatetime;
private String updateUserId;
private Date updateDatetime;
private static final long serialVersionUID = 1L;
public String getPkId() {
return pkId;
}
public void setPkId(String pkId) {
this.pkId = pkId;
}
public String getRyjcxxcjbh() {
return ryjcxxcjbh;
}
public void setRyjcxxcjbh(String ryjcxxcjbh) {
this.ryjcxxcjbh = ryjcxxcjbh;
}
public String getSg() {
return sg;
}
public void setSg(String sg) {
this.sg = sg;
}
public String getTz() {
return tz;
}
public void setTz(String tz) {
this.tz = tz;
}
public String getZc() {
return zc;
}
public void setZc(String zc) {
this.zc = zc;
}
public String getDeletag() {
return deletag;
}
public void setDeletag(String deletag) {
this.deletag = deletag;
}
public String getAnnex() {
return annex;
}
public void setAnnex(String annex) {
this.annex = annex;
}
public String getCreateUserId() {
return createUserId;
}
public void setCreateUserId(String createUserId) {
this.createUserId = createUserId;
}
public Date getCreateDatetime() {
return createDatetime;
}
public void setCreateDatetime(Date createDatetime) {
this.createDatetime = createDatetime;
}
public String getUpdateUserId() {
return updateUserId;
}
public void setUpdateUserId(String updateUserId) {
this.updateUserId = updateUserId;
}
public Date getUpdateDatetime() {
return updateDatetime;
}
public void setUpdateDatetime(Date updateDatetime) {
this.updateDatetime = updateDatetime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", pkId=").append(pkId);
sb.append(", ryjcxxcjbh=").append(ryjcxxcjbh);
sb.append(", sg=").append(sg);
sb.append(", tz=").append(tz);
sb.append(", zc=").append(zc);
sb.append(", deletag=").append(deletag);
sb.append(", annex=").append(annex);
sb.append(", createUserId=").append(createUserId);
sb.append(", createDatetime=").append(createDatetime);
sb.append(", updateUserId=").append(updateUserId);
sb.append(", updateDatetime=").append(updateDatetime);
sb.append("]");
return sb.toString();
}
}
|
package com.smxknife.netty.v5.demo13;
/**
* @author smxknife
* 2018-12-12
*/
public class NettyConstant {
public static final String LOCAL_IP = "127.0.0.1";
public static final int LOCAL_PORT = 8080;
public static final String REMOTE_IP = "127.0.0.1";
public static final int REMOTE_PORT = 9090;
}
|
package com.tencent.mm.g.a;
public final class tt$a {
public int result;
}
|
package com.rc.portal.service;
import java.sql.SQLException;
import java.util.List;
import com.rc.portal.vo.TGoodsBrokerage;
import com.rc.portal.vo.TGoodsBrokerageExample;
public interface TGoodsBrokerageManager {
int countByExample(TGoodsBrokerageExample example) throws SQLException;
int deleteByExample(TGoodsBrokerageExample example) throws SQLException;
int deleteByPrimaryKey(Long id) throws SQLException;
Long insert(TGoodsBrokerage record) throws SQLException;
Long insertSelective(TGoodsBrokerage record) throws SQLException;
List selectByExample(TGoodsBrokerageExample example) throws SQLException;
TGoodsBrokerage selectByPrimaryKey(Long id) throws SQLException;
int updateByExampleSelective(TGoodsBrokerage record, TGoodsBrokerageExample example) throws SQLException;
int updateByExample(TGoodsBrokerage record, TGoodsBrokerageExample example) throws SQLException;
int updateByPrimaryKeySelective(TGoodsBrokerage record) throws SQLException;
int updateByPrimaryKey(TGoodsBrokerage record) throws SQLException;
}
|
package com;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
public class DecompressCallbackDelegate implements MqttCallback {
private MqttCallback initialCallback;
static HashMap<Integer,String> cacheMap = new HashMap<>();
public DecompressCallbackDelegate(MqttCallback mqttCallback){
this.initialCallback = mqttCallback;
}
@Override
public void connectionLost(Throwable cause) {
initialCallback.connectionLost(cause);
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
if (topic=="System/manager") {
//logic for sending reset to caches
}
message.setPayload(CompressionTools.decompressData(message.getPayload()).getBytes());
System.out.println("Message: " + (message) + "\nTopic: " + topic);
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
initialCallback.deliveryComplete(token);
}
}
|
package communication.packets.request.admin;
import communication.enums.PacketType;
import communication.packets.AuthenticatedRequestPacket;
import communication.packets.response.FailureResponsePacket;
import communication.packets.response.ValidResponsePacket;
import communication.wrapper.Connection;
import main.Conference;
/**
* This packet can be used by an admin to remove an attendee which is not an admin from the conference.
*/
public class RemoveAttendeeRequestPacket extends AuthenticatedRequestPacket {
private int id;
/**
* @param id the id of the attendee to be removed
*/
public RemoveAttendeeRequestPacket(int id) {
super(PacketType.REMOVE_ATTENDEE_REQUEST);
this.id = id;
}
@Override
public void handle(Conference conference, Connection connection) {
if(isPermitted(conference, connection, true)) {
if(!conference.isAdmin(id)) {
conference.removeAttendee(id);
new ValidResponsePacket().send(connection);
} else {
new FailureResponsePacket("Admin accounts cant be removed").send(connection);
}
}
}
}
|
package com.commercetools.pspadapter.payone.notification.common;
import com.commercetools.pspadapter.payone.domain.payone.model.common.Notification;
import com.commercetools.pspadapter.payone.domain.payone.model.common.NotificationAction;
import com.commercetools.pspadapter.payone.domain.payone.model.common.TransactionStatus;
import io.sphere.sdk.commands.UpdateAction;
import io.sphere.sdk.orders.PaymentState;
import io.sphere.sdk.payments.Payment;
import io.sphere.sdk.payments.Transaction;
import io.sphere.sdk.payments.TransactionDraftBuilder;
import io.sphere.sdk.payments.TransactionState;
import io.sphere.sdk.payments.TransactionType;
import io.sphere.sdk.payments.commands.updateactions.AddInterfaceInteraction;
import io.sphere.sdk.payments.commands.updateactions.AddTransaction;
import io.sphere.sdk.payments.commands.updateactions.ChangeTransactionState;
import io.sphere.sdk.payments.commands.updateactions.SetStatusInterfaceCode;
import io.sphere.sdk.payments.commands.updateactions.SetStatusInterfaceText;
import io.sphere.sdk.utils.MoneyImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnitRunner;
import javax.money.MonetaryAmount;
import java.util.List;
import static io.sphere.sdk.payments.TransactionType.CHARGE;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
import static util.UpdatePaymentTestHelper.assertStandardUpdateActions;
import static util.UpdatePaymentTestHelper.getAddInterfaceInteraction;
import static util.UpdatePaymentTestHelper.getSetStatusInterfaceCode;
import static util.UpdatePaymentTestHelper.getSetStatusInterfaceText;
/**
* @author Jan Wolter
*/
@RunWith(MockitoJUnitRunner.class)
public class PaidNotificationProcessorTest extends BaseChargedNotificationProcessorTest {
@InjectMocks
private PaidNotificationProcessor testee;
// Payone "paid" is mapped to CTP "paid" state
private static final PaymentState ORDER_PAYMENT_STATE = PaymentState.PAID;
@Before
public void setUp() throws Exception {
super.setUp();
notification = new Notification();
notification.setPrice("20.00");
notification.setCurrency("EUR");
notification.setTxtime(millis.toString());
notification.setSequencenumber("23");
notification.setTxaction(NotificationAction.PAID);
notification.setTransactionStatus(TransactionStatus.COMPLETED);
when(paymentToOrderStateMapper.mapPaymentToOrderState(any(Payment.class)))
.thenReturn(ORDER_PAYMENT_STATE);
}
@Test
@SuppressWarnings("unchecked")
public void processingPendingNotificationAboutUnknownTransactionAddsChargeTransactionWithStatePending() throws Exception {
super.processingPendingNotificationAboutUnknownTransactionAddsChargeTransactionWithStatePending(testee, ORDER_PAYMENT_STATE);
}
@Test
@SuppressWarnings("unchecked")
public void processingCompletedNotificationAboutUnknownTransactionAddsChargeTransactionWithStateSuccess()
throws Exception {
// arrange
final Payment payment = testHelper.dummyPaymentOneAuthPending20EuroCC();
payment.getTransactions().clear();
notification.setReceivable("20.00");
notification.setBalance("0.00");
// act
testee.processTransactionStatusNotification(notification, payment);
// assert
final List<? extends UpdateAction<Payment>> updateActions = updatePaymentAndGetUpdateActions(payment);
final MonetaryAmount amount = MoneyImpl.of(notification.getPrice(), notification.getCurrency());
final AddTransaction transaction = AddTransaction.of(TransactionDraftBuilder
.of(TransactionType.CHARGE, amount, timestamp)
.state(TransactionState.SUCCESS)
.interactionId(notification.getSequencenumber())
.build());
final AddInterfaceInteraction interfaceInteraction = getAddInterfaceInteraction(notification, timestamp);
final SetStatusInterfaceCode statusInterfaceCode = getSetStatusInterfaceCode(notification);
final SetStatusInterfaceText statusInterfaceText = getSetStatusInterfaceText(notification);
assertThat(updateActions).as("added transactions")
.containsExactlyInAnyOrder(transaction, interfaceInteraction, statusInterfaceCode, statusInterfaceText);
verifyUpdateOrderActions(payment, ORDER_PAYMENT_STATE);
}
@Test
@SuppressWarnings("unchecked")
public void processingPendingNotificationForPendingChargeTransactionDoesNotChangeState() throws Exception {
super.processingPendingNotificationForPendingChargeTransactionDoesNotChangeState(testee, ORDER_PAYMENT_STATE);
}
@Test
@SuppressWarnings("unchecked")
public void processingCompletedNotificationForPendingChargeTransactionChangesStateToSuccess() throws Exception {
final Payment payment = processingCompletedNotificationForPendingChargeTransactionChangesStateToSuccessWireframe();
verifyUpdateOrderActions(payment, ORDER_PAYMENT_STATE);
}
@Test
public void orderServiceIsNotCalledWhenIsUpdateOrderPaymentStateFalse() throws Exception {
// this test is similar to #processingCompletedNotificationForPendingChargeTransactionChangesStateToSuccess(),
// but #isUpdateOrderPaymentState() is false, so update order actions should be skipped
when(tenantConfig.isUpdateOrderPaymentState()).thenReturn(false);
processingCompletedNotificationForPendingChargeTransactionChangesStateToSuccessWireframe();
verifyUpdateOrderActionsNotCalled();
}
@Test
public void whenChargeTransactionIsInitial_ChangeTransactionStateISAdded() throws Exception {
Payment paymentChargeInitial = testHelper.dummyPaymentOneChargeInitial20Euro();
Transaction firstTransaction = paymentChargeInitial.getTransactions().get(0);
notification.setSequencenumber(firstTransaction.getInteractionId());
List<UpdateAction<Payment>> authPendingUpdates = testee.createPaymentUpdates(paymentChargeInitial, notification);
assertThat(authPendingUpdates).containsOnlyOnce(ChangeTransactionState.of(
notification.getTransactionStatus().getCtTransactionState(), firstTransaction.getId()));
verify_isNotCompletedTransaction_called(TransactionState.INITIAL, CHARGE);
}
@Test
public void whenChargeTransactionIsPending_ChangeTransactionStateISAdded() throws Exception {
Payment paymentChargePending = testHelper.dummyPaymentOneChargePending20Euro();
Transaction firstTransaction = paymentChargePending.getTransactions().get(0);
notification.setSequencenumber(firstTransaction.getInteractionId());
List<UpdateAction<Payment>> authPendingUpdates = testee.createPaymentUpdates(paymentChargePending, notification);
assertThat(authPendingUpdates).containsOnlyOnce(ChangeTransactionState.of(
notification.getTransactionStatus().getCtTransactionState(), firstTransaction.getId()));
verify_isNotCompletedTransaction_called(TransactionState.PENDING, CHARGE);
}
@Test
public void whenChargeTransactionIsSuccess_ChangeTransactionStateNOTAdded() throws Exception {
Payment paymentAuthSuccess = testHelper.dummyPaymentOneChargeSuccess20Euro();
Transaction firstTransaction = paymentAuthSuccess.getTransactions().get(0);
notification.setSequencenumber(firstTransaction.getInteractionId());
List<UpdateAction<Payment>> authSuccessUpdates = testee.createPaymentUpdates(paymentAuthSuccess, notification);
assertTransactionOfTypeIsNotAdded(authSuccessUpdates, ChangeTransactionState.class);
verify_isNotCompletedTransaction_called(TransactionState.SUCCESS, CHARGE);
}
@Test
public void whenChargeTransactionIsFailure_ChangeTransactionStateNOTAdded() throws Exception {
Payment paymentChargeFailure = testHelper.dummyPaymentOneChargeFailure20Euro();
Transaction firstTransaction = paymentChargeFailure.getTransactions().get(0);
notification.setSequencenumber(firstTransaction.getInteractionId());
List<UpdateAction<Payment>> authFailureUpdates = testee.createPaymentUpdates(paymentChargeFailure, notification);
assertTransactionOfTypeIsNotAdded(authFailureUpdates, ChangeTransactionState.class);
verify_isNotCompletedTransaction_called(TransactionState.FAILURE, CHARGE);
}
@SuppressWarnings("unchecked")
private Payment processingCompletedNotificationForPendingChargeTransactionChangesStateToSuccessWireframe() throws Exception {
// arrange
final Payment payment = testHelper.dummyPaymentOneChargePending20Euro();
final Transaction chargeTransaction = payment.getTransactions().get(0);
notification.setSequencenumber(chargeTransaction.getInteractionId());
notification.setReceivable("20.00");
notification.setBalance("0.00");
// act
testee.processTransactionStatusNotification(notification, payment);
// assert
final List<? extends UpdateAction<Payment>> updateActions = updatePaymentAndGetUpdateActions(payment);
final AddInterfaceInteraction interfaceInteraction = getAddInterfaceInteraction(notification, timestamp);
final SetStatusInterfaceCode statusInterfaceCode = getSetStatusInterfaceCode(notification);
final SetStatusInterfaceText statusInterfaceText = getSetStatusInterfaceText(notification);
assertThat(updateActions).as("payment update actions list")
.containsExactlyInAnyOrder(
ChangeTransactionState.of(TransactionState.SUCCESS, chargeTransaction.getId()),
interfaceInteraction, statusInterfaceCode, statusInterfaceText);
return payment;
}
@Test
@SuppressWarnings("unchecked")
public void processingCompletedNotificationForSuccessfulChargeTransactionDoesNotChangeState() throws Exception {
// arrange
final Payment payment = testHelper.dummyPaymentTwoTransactionsSuccessPending();
notification.setSequencenumber(payment.getTransactions().get(0).getInteractionId());
notification.setPrice("200.00");
notification.setReceivable(notification.getPrice());
notification.setBalance("0.00");
// act
testee.processTransactionStatusNotification(notification, payment);
// assert
final List<? extends UpdateAction<Payment>> updateActions = updatePaymentAndGetUpdateActions(payment);
final AddInterfaceInteraction interfaceInteraction = getAddInterfaceInteraction(notification, timestamp);
final SetStatusInterfaceCode statusInterfaceCode = getSetStatusInterfaceCode(notification);
final SetStatusInterfaceText statusInterfaceText = getSetStatusInterfaceText(notification);
assertThat(updateActions).as("# of payment update actions").hasSize(3);
assertStandardUpdateActions(updateActions, interfaceInteraction, statusInterfaceCode, statusInterfaceText);
verifyUpdateOrderActions(payment, ORDER_PAYMENT_STATE);
}
@Test
@SuppressWarnings("unchecked")
public void processingCompletedNotificationForFailedChargeTransactionDoesNotChangeState() throws Exception {
// arrange
final Payment payment = testHelper.dummyPaymentOneChargeFailure20Euro();
notification.setSequencenumber(payment.getTransactions().get(0).getInteractionId());
notification.setTransactionStatus(TransactionStatus.PENDING);
notification.setReceivable("20.00");
notification.setBalance("0.00");
// act
testee.processTransactionStatusNotification(notification, payment);
// assert
final List<? extends UpdateAction<Payment>> updateActions = updatePaymentAndGetUpdateActions(payment);
final AddInterfaceInteraction interfaceInteraction = getAddInterfaceInteraction(notification, timestamp);
final SetStatusInterfaceCode statusInterfaceCode = getSetStatusInterfaceCode(notification);
final SetStatusInterfaceText statusInterfaceText = getSetStatusInterfaceText(notification);
assertThat(updateActions).as("# of payment update actions").hasSize(3);
assertStandardUpdateActions(updateActions, interfaceInteraction, statusInterfaceCode, statusInterfaceText);
verifyUpdateOrderActions(payment, ORDER_PAYMENT_STATE);
}
}
|
package ru.otus.l101.db;
/*
* Created by VSkurikhin at winter 2018.
*/
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.service.ServiceRegistry;
import ru.otus.l101.dao.*;
import ru.otus.l101.dataset.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public class DBServiceHibernateImpl implements DBService, TypeNames {
private Map<String, HibernateDAO> adapters;
private final SessionFactory sessionFactory;
private static Configuration defaultConfiguration() {
Configuration cfg = new Configuration();
cfg.addAnnotatedClass(UserDataSet.class);
cfg.addAnnotatedClass(AddressDataSet.class);
cfg.addAnnotatedClass(PhoneDataSet.class);
cfg.addAnnotatedClass(EmptyDataSet.class);
cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
cfg.setProperty("hibernate.connection.driver_class", "org.postgresql.Driver");
cfg.setProperty("hibernate.connection.url", "jdbc:postgresql://localhost:5432/db");
cfg.setProperty("hibernate.connection.username", "dbuser");
cfg.setProperty("hibernate.connection.password", "password");
cfg.setProperty("hibernate.show_sql", "true");
cfg.setProperty("hibernate.hbm2ddl.auto", "create");
cfg.setProperty("hibernate.enable_lazy_load_no_trans", "true");
return cfg;
}
public DBServiceHibernateImpl() {
this(defaultConfiguration());
}
public DBServiceHibernateImpl(Configuration configuration) {
sessionFactory = createSessionFactory(configuration);
}
public void setDefaultDAOFor(Session session) {
adapters = new HashMap<>();
addAdapter(new AddressDataSetHibernateDAO(session));
addAdapter(new PhoneDataSetHibernateDAO(session));
addAdapter(new UserDataSetHibernateDAO(session));
}
public void addAdapter(HibernateDAO adapter) {
if (! adapters.containsKey(adapter.getAdapteeOfType())) {
adapters.put(adapter.getAdapteeOfType(), adapter);
adapter.setAdapters(adapters);
}
}
private static SessionFactory createSessionFactory(Configuration configuration) {
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
builder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = builder.build();
return configuration.buildSessionFactory(serviceRegistry);
}
@Override
public String getLocalStatus() {
return runInSession(session -> {
return session.getTransaction().getStatus().name();
});
}
@Override
public Connection getConnection() {
try {
((SessionImplementor) sessionFactory)
.getJdbcConnectionAccess()
.obtainConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public <T extends DataSet> void createTables(Class<T> clazz) {
// TODO
}
@Override
public <T extends DataSet> void save(T dataSet) {
try (Session session = sessionFactory.openSession()) {
setDefaultDAOFor(session);
String key = dataSet.getClass().getName();
HibernateDAO dao = adapters.getOrDefault(
key, new EmptyDataSetHibernateDAO(session)
);
dao.save(dataSet);
//session.save(dataSet);
}
}
@Override
public <T extends DataSet> T load(long id, Class<T> clazz) {
return runInSession(session -> {
setDefaultDAOFor(session);
String key = clazz.getName();
HibernateDAO dao = adapters.getOrDefault(
key, new EmptyDataSetHibernateDAO(session)
);
//noinspection unchecked
return (T) dao.read(id);
});
}
@Override
public UserDataSet loadByName(String name) {
return runInSession(session -> {
UserDataSetHibernateDAO dao = new UserDataSetHibernateDAO(session);
return dao.readByName(name);
});
}
@Override
public List<UserDataSet> loadAll() {
return runInSession(session -> {
UserDataSetHibernateDAO dao = new UserDataSetHibernateDAO(session);
return dao.readAll();
});
}
public void shutdown() {
try {
this.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private <R> R runInSession(Function<Session, R> function) {
try (Session session = sessionFactory.openSession()) {
Transaction transaction = session.beginTransaction();
R result = function.apply(session);
transaction.commit();
return result;
}
}
@Override
public void close() throws Exception {
sessionFactory.close();
}
}
/* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et
*/
//EOF
|
/*
* IO.java
* This file was last modified at 2018.12.03 20:05 by Victor N. Skurikhin.
* $Id$
* This is free and unencumbered software released into the public domain.
* For more information, please refer to <http://unlicense.org>
*/
package ru.otus.server.utils;
import ru.otus.server.exceptions.ExceptionIO;
import ru.otus.server.exceptions.ExceptionURISyntax;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
public class IO
{
/**
* Read all text from a file.
* Memory utilization
* The method preserves line breaks, can temporarily require memory several
* times the size of the file, because for a short time the raw file contents
* (a byte array), and the decoded characters (each of which is 16 bits even
* if encoded as 8 bits in the file) reside in memory at once. It is safest
* to apply to files that you know to be small relative to the available
* memory.
*
* @param path a file path
* @param encoding Character encoding.
* @return string from the contents of a file
* @throws IOException
*/
public static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
public static String readInputStream(InputStream is, String encoding) throws IOException
{
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(new InputStreamReader(is, encoding));
String line = br.readLine();
while (line != null) {
sb.append(line).append(System.lineSeparator());
line = br.readLine();
}
return sb.toString();
}
catch (IOException e) {
throw e;
}
finally {
if (br != null) br.close();
}
}
private static FileChannel getFileChannel(File file) throws FileNotFoundException
{
return new FileOutputStream(file, true).getChannel();
}
public static void saveResultToTruncatedFile(String result, String path)
throws IOException, URISyntaxException
{
File file = null;
try {
file = Paths.get(new URI(path)).toFile();
}
catch (URISyntaxException e) {
throw new ExceptionURISyntax(e);
}
try (FileChannel fc = getFileChannel(file); PrintWriter pw = new PrintWriter(file)) {
fc.truncate(0);
pw.print(result);
}
catch (IOException e) {
throw new ExceptionIO(e);
}
}
public static String getAbsolutePath(String relativePath)
{
return (new File(relativePath)).getAbsolutePath();
}
public static String converURIToAbsolutePath(URI uri)
{
return Paths.get(uri).toFile().getAbsolutePath();
}
public static String converURIToAbsolutePath(String uri) throws URISyntaxException
{
return converURIToAbsolutePath(new URI(uri));
}
}
/* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et
*/
//EOF
|
package org.eclipse.emf.codegen.ecore.templates.model;
import java.util.*;
import org.eclipse.emf.ecore.*;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.codegen.ecore.genmodel.*;
import org.eclipse.emf.codegen.ecore.genmodel.impl.Literals;
import org.eclipse.emf.codegen.ecore.genmodel.util.GenModelUtil;
public class PackageClass
{
protected static String nl;
public static synchronized PackageClass create(String lineSeparator)
{
nl = lineSeparator;
PackageClass result = new PackageClass();
nl = null;
return result;
}
public final String NL = nl == null ? (System.getProperties().getProperty("line.separator")) : nl;
protected final String TEXT_1 = "";
protected final String TEXT_2 = "/**";
protected final String TEXT_3 = NL + " * ";
protected final String TEXT_4 = NL + " */";
protected final String TEXT_5 = NL + "package ";
protected final String TEXT_6 = ";";
protected final String TEXT_7 = NL;
protected final String TEXT_8 = NL + NL + "/**" + NL + " * <!-- begin-user-doc -->" + NL + " * The <b>Package</b> for the model." + NL + " * It contains accessors for the meta objects to represent" + NL + " * <ul>" + NL + " * <li>each class,</li>" + NL + " * <li>each feature of each class,</li>";
protected final String TEXT_9 = NL + " * <li>each operation of each class,</li>";
protected final String TEXT_10 = NL + " * <li>each enum,</li>" + NL + " * <li>and each data type</li>" + NL + " * </ul>" + NL + " * <!-- end-user-doc -->";
protected final String TEXT_11 = NL + " * <!-- begin-model-doc -->" + NL + " * ";
protected final String TEXT_12 = NL + " * <!-- end-model-doc -->";
protected final String TEXT_13 = NL + " * @see ";
protected final String TEXT_14 = NL + " * @model ";
protected final String TEXT_15 = NL + " * ";
protected final String TEXT_16 = NL + " * @model";
protected final String TEXT_17 = NL + " * @generated" + NL + " */";
protected final String TEXT_18 = NL + NL + "/**" + NL + " * <!-- begin-user-doc -->" + NL + " * An implementation of the model <b>Package</b>." + NL + " * <!-- end-user-doc -->";
protected final String TEXT_19 = NL + "@Deprecated";
protected final String TEXT_20 = NL + "@SuppressWarnings(\"deprecation\")";
protected final String TEXT_21 = NL + "public class ";
protected final String TEXT_22 = " extends ";
protected final String TEXT_23 = " implements ";
protected final String TEXT_24 = NL + "public interface ";
protected final String TEXT_25 = NL + "{";
protected final String TEXT_26 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\t";
protected final String TEXT_27 = " copyright = ";
protected final String TEXT_28 = NL + "\t/**" + NL + "\t * The package name." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\t";
protected final String TEXT_29 = " eNAME = \"";
protected final String TEXT_30 = "\";";
protected final String TEXT_31 = NL + NL + "\t/**" + NL + "\t * The package namespace URI." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\t";
protected final String TEXT_32 = " eNS_URI = \"";
protected final String TEXT_33 = NL + NL + "\t/**" + NL + "\t * The package namespace name." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\t";
protected final String TEXT_34 = " eNS_PREFIX = \"";
protected final String TEXT_35 = NL + NL + "\t/**" + NL + "\t * The package content type ID." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\t";
protected final String TEXT_36 = " eCONTENT_TYPE = \"";
protected final String TEXT_37 = NL + NL + "\t/**" + NL + "\t * The singleton instance of the package." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\t";
protected final String TEXT_38 = " eINSTANCE = ";
protected final String TEXT_39 = ".init();" + NL;
protected final String TEXT_40 = NL + "\t/**";
protected final String TEXT_41 = NL + "\t * The meta object id for the '{@link ";
protected final String TEXT_42 = " <em>";
protected final String TEXT_43 = "</em>}' class." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @see ";
protected final String TEXT_44 = "</em>}' enum." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @see ";
protected final String TEXT_45 = NL + "\t * The meta object id for the '<em>";
protected final String TEXT_46 = "</em>' data type." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->";
protected final String TEXT_47 = NL + "\t * @see ";
protected final String TEXT_48 = "#get";
protected final String TEXT_49 = "()";
protected final String TEXT_50 = NL + "\t * ";
protected final String TEXT_51 = NL + "\t * @generated" + NL + "\t */";
protected final String TEXT_52 = NL + "\t@Deprecated";
protected final String TEXT_53 = NL + "\t";
protected final String TEXT_54 = "int ";
protected final String TEXT_55 = " = ";
protected final String TEXT_56 = ";" + NL;
protected final String TEXT_57 = NL + "\t/**" + NL + "\t * The feature id for the '<em><b>";
protected final String TEXT_58 = "</b></em>' ";
protected final String TEXT_59 = "." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->";
protected final String TEXT_60 = NL + "\t * @generated" + NL + "\t * @ordered" + NL + "\t */";
protected final String TEXT_61 = NL + "\t/**" + NL + "\t * The number of structural features of the '<em>";
protected final String TEXT_62 = "</em>' class." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->";
protected final String TEXT_63 = NL + "\t/**" + NL + "\t * The operation id for the '<em>";
protected final String TEXT_64 = "</em>' operation." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->";
protected final String TEXT_65 = NL + "\t/**" + NL + "\t * The number of operations of the '<em>";
protected final String TEXT_66 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprotected String packageFilename = \"";
protected final String TEXT_67 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->";
protected final String TEXT_68 = NL + "\tprivate ";
protected final String TEXT_69 = " ";
protected final String TEXT_70 = " = null;" + NL;
protected final String TEXT_71 = NL + "\t/**" + NL + "\t * Creates an instance of the model <b>Package</b>, registered with" + NL + "\t * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package" + NL + "\t * package URI value." + NL + "\t * <p>Note: the correct way to create the package is via the static" + NL + "\t * factory method {@link #init init()}, which also performs" + NL + "\t * initialization of the package, or returns the registered package," + NL + "\t * if one already exists." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @see org.eclipse.emf.ecore.EPackage.Registry" + NL + "\t * @see ";
protected final String TEXT_72 = "#eNS_URI" + NL + "\t * @see #init()" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprivate ";
protected final String TEXT_73 = "()" + NL + "\t{" + NL + "\t\tsuper(eNS_URI, ";
protected final String TEXT_74 = ");" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprivate static boolean isInited = false;" + NL + "" + NL + "\t/**" + NL + "\t * Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends." + NL + "\t *" + NL + "\t * <p>This method is used to initialize {@link ";
protected final String TEXT_75 = "#eINSTANCE} when that field is accessed." + NL + "\t * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @see #eNS_URI";
protected final String TEXT_76 = NL + "\t * @see #createPackageContents()" + NL + "\t * @see #initializePackageContents()";
protected final String TEXT_77 = NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic static ";
protected final String TEXT_78 = " init()" + NL + "\t{" + NL + "\t\tif (isInited) return (";
protected final String TEXT_79 = ")";
protected final String TEXT_80 = ".Registry.INSTANCE.getEPackage(";
protected final String TEXT_81 = ".eNS_URI);" + NL;
protected final String TEXT_82 = NL + "\t\tinitializeRegistryHelpers();" + NL;
protected final String TEXT_83 = NL + "\t\t// Obtain or create and register package" + NL + "\t\tObject registered";
protected final String TEXT_84 = ".Registry.INSTANCE.get(eNS_URI);" + NL + "\t\t";
protected final String TEXT_85 = " the";
protected final String TEXT_86 = " = registered";
protected final String TEXT_87 = " instanceof ";
protected final String TEXT_88 = " ? (";
protected final String TEXT_89 = ")registered";
protected final String TEXT_90 = " : new ";
protected final String TEXT_91 = "();" + NL + "" + NL + "\t\tisInited = true;" + NL;
protected final String TEXT_92 = NL + "\t\t// Initialize simple dependencies";
protected final String TEXT_93 = NL + "\t\t";
protected final String TEXT_94 = ".eINSTANCE.eClass();";
protected final String TEXT_95 = NL + "\t\t// Obtain or create and register interdependencies";
protected final String TEXT_96 = "Object ";
protected final String TEXT_97 = "registeredPackage = ";
protected final String TEXT_98 = ".eNS_URI);" + NL + "\t\t";
protected final String TEXT_99 = " = (";
protected final String TEXT_100 = ")(registeredPackage instanceof ";
protected final String TEXT_101 = " ? registeredPackage : ";
protected final String TEXT_102 = ".eINSTANCE);";
protected final String TEXT_103 = NL + "\t\t// Load packages";
protected final String TEXT_104 = NL + "\t\tthe";
protected final String TEXT_105 = ".loadPackage();";
protected final String TEXT_106 = NL + "\t\t// Create package meta-data objects";
protected final String TEXT_107 = ".createPackageContents();";
protected final String TEXT_108 = NL + NL + "\t\t// Initialize created meta-data";
protected final String TEXT_109 = ".initializePackageContents();";
protected final String TEXT_110 = NL + "\t\t// Fix loaded packages";
protected final String TEXT_111 = ".fixPackageContents();";
protected final String TEXT_112 = NL + "\t\t// Register package validator" + NL + "\t\t";
protected final String TEXT_113 = ".Registry.INSTANCE.put" + NL + "\t\t\t(the";
protected final String TEXT_114 = "," + NL + "\t\t\t new ";
protected final String TEXT_115 = ".Descriptor()" + NL + "\t\t\t {";
protected final String TEXT_116 = NL + "\t\t\t\t @Override";
protected final String TEXT_117 = NL + "\t\t\t\t public ";
protected final String TEXT_118 = " getEValidator()" + NL + "\t\t\t\t {" + NL + "\t\t\t\t\t return ";
protected final String TEXT_119 = ".INSTANCE;" + NL + "\t\t\t\t }" + NL + "\t\t\t });" + NL;
protected final String TEXT_120 = NL + "\t\t// Mark meta-data to indicate it can't be changed" + NL + "\t\tthe";
protected final String TEXT_121 = ".freeze();" + NL;
protected final String TEXT_122 = NL + "\t\t// Update the registry and return the package" + NL + "\t\t";
protected final String TEXT_123 = ".Registry.INSTANCE.put(";
protected final String TEXT_124 = ".eNS_URI, the";
protected final String TEXT_125 = ");" + NL + "\t\treturn the";
protected final String TEXT_126 = ";" + NL + "\t}";
protected final String TEXT_127 = NL + NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic static void initializeRegistryHelpers()" + NL + "\t{";
protected final String TEXT_128 = ".register" + NL + "\t\t\t(";
protected final String TEXT_129 = ".class," + NL + "\t\t\t new ";
protected final String TEXT_130 = ".Helper()" + NL + "\t\t\t {" + NL + "\t\t\t\t public boolean isInstance(Object instance)" + NL + "\t\t\t\t {" + NL + "\t\t\t\t\t return instance instanceof ";
protected final String TEXT_131 = ";" + NL + "\t\t\t\t }" + NL + "" + NL + "\t\t\t\t public Object newArrayInstance(int size)" + NL + "\t\t\t\t {" + NL + "\t\t\t\t\t return new ";
protected final String TEXT_132 = "[size];" + NL + "\t\t\t\t }" + NL + "\t\t\t });";
protected final String TEXT_133 = ";" + NL + "\t\t\t\t }" + NL + "" + NL + "\t\t\t\t public Object newArrayInstance(int size)" + NL + "\t\t\t\t {";
protected final String TEXT_134 = NL + "\t\t\t\t\t return new ";
protected final String TEXT_135 = "[size]";
protected final String TEXT_136 = "[size];";
protected final String TEXT_137 = NL + "\t\t\t\t }" + NL + "\t\t});";
protected final String TEXT_138 = NL + "\t}" + NL + "" + NL + "" + NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic static class WhiteList implements ";
protected final String TEXT_139 = ", EBasicWhiteList" + NL + "\t{";
protected final String TEXT_140 = NL + "\t\t/**" + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @generated" + NL + "\t\t */" + NL + "\t\tprotected ";
protected final String TEXT_141 = NL + "\t}";
protected final String TEXT_142 = NL + "\t * Returns the meta object for class '{@link ";
protected final String TEXT_143 = "</em>}'." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @return the meta object for class '<em>";
protected final String TEXT_144 = "</em>'." + NL + "\t * @see ";
protected final String TEXT_145 = NL + "\t * @model ";
protected final String TEXT_146 = NL + "\t * ";
protected final String TEXT_147 = NL + "\t * @model";
protected final String TEXT_148 = NL + "\t * Returns the meta object for enum '{@link ";
protected final String TEXT_149 = "</em>}'." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @return the meta object for enum '<em>";
protected final String TEXT_150 = NL + "\t * Returns the meta object for data type '<em>";
protected final String TEXT_151 = "</em>'.";
protected final String TEXT_152 = NL + "\t * Returns the meta object for data type '{@link ";
protected final String TEXT_153 = "</em>}'.";
protected final String TEXT_154 = NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->";
protected final String TEXT_155 = NL + " * <!-- begin-model-doc -->" + NL + " * ";
protected final String TEXT_156 = NL + " * <!-- end-model-doc -->";
protected final String TEXT_157 = NL + "\t * @return the meta object for data type '<em>";
protected final String TEXT_158 = NL + "\t@Override";
protected final String TEXT_159 = NL + "\tpublic ";
protected final String TEXT_160 = " get";
protected final String TEXT_161 = "()" + NL + "\t{";
protected final String TEXT_162 = NL + "\t\tif (";
protected final String TEXT_163 = " == null)" + NL + "\t\t{" + NL + "\t\t\t";
protected final String TEXT_164 = ".eNS_URI).getEClassifiers().get(";
protected final String TEXT_165 = ");" + NL + "\t\t}";
protected final String TEXT_166 = NL + "\t\treturn ";
protected final String TEXT_167 = ";" + NL + "\t}" + NL;
protected final String TEXT_168 = "();" + NL;
protected final String TEXT_169 = NL + "\t/**" + NL + "\t * Returns the meta object for the ";
protected final String TEXT_170 = " '{@link ";
protected final String TEXT_171 = "#";
protected final String TEXT_172 = "</em>}'." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @return the meta object for the ";
protected final String TEXT_173 = " '<em>";
protected final String TEXT_174 = NL + "\t * @see #get";
protected final String TEXT_175 = NL + "\t\treturn (";
protected final String TEXT_176 = ".getEStructuralFeatures().get(";
protected final String TEXT_177 = ");";
protected final String TEXT_178 = NL + " return (";
protected final String TEXT_179 = ")get";
protected final String TEXT_180 = "().getEStructuralFeatures().get(";
protected final String TEXT_181 = "();";
protected final String TEXT_182 = NL + "\t/**" + NL + "\t * Returns the meta object for the '{@link ";
protected final String TEXT_183 = "(";
protected final String TEXT_184 = ") <em>";
protected final String TEXT_185 = "</em>}' operation." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @return the meta object for the '<em>";
protected final String TEXT_186 = "</em>' operation." + NL + "\t * @see ";
protected final String TEXT_187 = ".getEOperations().get(";
protected final String TEXT_188 = NL + " return get";
protected final String TEXT_189 = "().getEOperations().get(";
protected final String TEXT_190 = NL + "\t/**" + NL + "\t * Returns the factory that creates the instances of the model." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @return the factory that creates the instances of the model." + NL + "\t * @generated" + NL + "\t */";
protected final String TEXT_191 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */";
protected final String TEXT_192 = "()" + NL + "\t{" + NL + "\t\treturn (";
protected final String TEXT_193 = ")getEFactoryInstance();" + NL + "\t}";
protected final String TEXT_194 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprivate boolean isCreated = false;" + NL + "" + NL + "\t/**" + NL + "\t * Creates the meta-model objects for the package. This method is" + NL + "\t * guarded to have no affect on any invocation but its first." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */";
protected final String TEXT_195 = NL + "\t@SuppressWarnings(\"deprecation\")";
protected final String TEXT_196 = NL + "\tpublic void createPackageContents()" + NL + "\t{" + NL + "\t\tif (isCreated) return;" + NL + "\t\tisCreated = true;";
protected final String TEXT_197 = NL + NL + "\t\t// Create classes and their features";
protected final String TEXT_198 = " = create";
protected final String TEXT_199 = NL + "\t\tcreate";
protected final String TEXT_200 = ", ";
protected final String TEXT_201 = NL + "\t\tcreateEOperation(";
protected final String TEXT_202 = NL + NL + "\t\t// Create enums";
protected final String TEXT_203 = " = createEEnum(";
protected final String TEXT_204 = NL + NL + "\t\t// Create data types";
protected final String TEXT_205 = " = createEDataType(";
protected final String TEXT_206 = NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprivate boolean isInitialized = false;" + NL;
protected final String TEXT_207 = NL + "\t/**" + NL + "\t * Complete the initialization of the package and its meta-model. This" + NL + "\t * method is guarded to have no affect on any invocation but its first." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */";
protected final String TEXT_208 = NL + "\tpublic void initializePackageContents()" + NL + "\t{" + NL + "\t\tif (isInitialized) return;" + NL + "\t\tisInitialized = true;" + NL + "" + NL + "\t\t// Initialize package" + NL + "\t\tsetName(eNAME);" + NL + "\t\tsetNsPrefix(eNS_PREFIX);" + NL + "\t\tsetNsURI(eNS_URI);";
protected final String TEXT_209 = NL + NL + "\t\t// Obtain other dependent packages";
protected final String TEXT_210 = ".eNS_URI);";
protected final String TEXT_211 = NL + NL + "\t\t// Add subpackages";
protected final String TEXT_212 = NL + "\t\tgetESubpackages().add(";
protected final String TEXT_213 = NL + NL + "\t\t// Create type parameters";
protected final String TEXT_214 = "_";
protected final String TEXT_215 = " = addETypeParameter(";
protected final String TEXT_216 = ", \"";
protected final String TEXT_217 = "\");";
protected final String TEXT_218 = NL + "\t\taddETypeParameter(";
protected final String TEXT_219 = NL + NL + "\t\t// Set bounds for type parameters";
protected final String TEXT_220 = "g";
protected final String TEXT_221 = " = createEGenericType(";
protected final String TEXT_222 = NL + "\t\tg";
protected final String TEXT_223 = ".";
protected final String TEXT_224 = "(g";
protected final String TEXT_225 = ".getEBounds().add(g1);";
protected final String TEXT_226 = NL + NL + "\t\t// Add supertypes to classes";
protected final String TEXT_227 = ".getESuperTypes().add(";
protected final String TEXT_228 = ".get";
protected final String TEXT_229 = "());";
protected final String TEXT_230 = ".getEGenericSuperTypes().add(g1);";
protected final String TEXT_231 = NL + NL + "\t\t// Initialize classes";
protected final String TEXT_232 = ", features, and operations; add parameters";
protected final String TEXT_233 = " and features; add operations and parameters";
protected final String TEXT_234 = NL + "\t\tinitEClass(";
protected final String TEXT_235 = "null";
protected final String TEXT_236 = ".class";
protected final String TEXT_237 = "\", ";
protected final String TEXT_238 = "\"";
protected final String TEXT_239 = NL + "\t\tinitEReference(get";
protected final String TEXT_240 = "(), ";
protected final String TEXT_241 = "g1";
protected final String TEXT_242 = NL + "\t\tget";
protected final String TEXT_243 = "().getEKeys().add(";
protected final String TEXT_244 = NL + "\t\tinitEAttribute(get";
protected final String TEXT_245 = "initEOperation(get";
protected final String TEXT_246 = "addEOperation(";
protected final String TEXT_247 = "(), \"";
protected final String TEXT_248 = ", null, \"";
protected final String TEXT_249 = "addETypeParameter(op, \"";
protected final String TEXT_250 = NL + "\t\tt";
protected final String TEXT_251 = NL + "\t\taddEParameter(op, ";
protected final String TEXT_252 = NL + "\t\taddEException(op, g";
protected final String TEXT_253 = NL + "\t\taddEException(op, ";
protected final String TEXT_254 = NL + "\t\tinitEOperation(op, g1);";
protected final String TEXT_255 = NL + NL + "\t\t// Initialize enums and add enum literals";
protected final String TEXT_256 = NL + "\t\tinitEEnum(";
protected final String TEXT_257 = ".class, \"";
protected final String TEXT_258 = NL + "\t\taddEEnumLiteral(";
protected final String TEXT_259 = NL + NL + "\t\t// Initialize data types";
protected final String TEXT_260 = NL + "\t\tinitEDataType(";
protected final String TEXT_261 = NL + NL + "\t\t// Create resource" + NL + "\t\tcreateResource(";
protected final String TEXT_262 = NL + NL + "\t\t// Create annotations";
protected final String TEXT_263 = NL + "\t\t// ";
protected final String TEXT_264 = "Annotations();";
protected final String TEXT_265 = NL + "\t}" + NL;
protected final String TEXT_266 = NL + "\t/**" + NL + "\t * Initializes the annotations for <b>";
protected final String TEXT_267 = "</b>." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprotected void create";
protected final String TEXT_268 = "Annotations()" + NL + "\t{" + NL + "\t\tString source = ";
protected final String TEXT_269 = "null;";
protected final String TEXT_270 = NL + "\t\taddAnnotation" + NL + "\t\t (";
protected final String TEXT_271 = "," + NL + "\t\t source," + NL + "\t\t new String[]" + NL + "\t\t {";
protected final String TEXT_272 = NL + "\t\t\t ";
protected final String TEXT_273 = NL + "\t\t }";
protected final String TEXT_274 = ",";
protected final String TEXT_275 = NL + "\t\t new ";
protected final String TEXT_276 = "[]" + NL + "\t\t {";
protected final String TEXT_277 = NL + "\t\t\t ";
protected final String TEXT_278 = ".createURI(";
protected final String TEXT_279 = "eNS_URI).appendFragment(\"";
protected final String TEXT_280 = "\")";
protected final String TEXT_281 = NL + "\t\t });";
protected final String TEXT_282 = "," + NL + "\t\t ";
protected final String TEXT_283 = "new boolean[] { ";
protected final String TEXT_284 = " }";
protected final String TEXT_285 = "null,";
protected final String TEXT_286 = "\",";
protected final String TEXT_287 = NL + "\t\t new String[]" + NL + "\t\t {";
protected final String TEXT_288 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprivate boolean isLoaded = false;" + NL + "" + NL + "\t/**" + NL + "\t * Laods the package and any sub-packages from their serialized form." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic void loadPackage()" + NL + "\t{" + NL + "\t\tif (isLoaded) return;" + NL + "\t\tisLoaded = true;" + NL + "" + NL + "\t\t";
protected final String TEXT_289 = " url = getClass().getResource(packageFilename);" + NL + "\t\tif (url == null)" + NL + "\t\t{" + NL + "\t\t\tthrow new RuntimeException(\"Missing serialized package: \" + packageFilename);";
protected final String TEXT_290 = NL + "\t\t}" + NL + "\t\t";
protected final String TEXT_291 = " uri = ";
protected final String TEXT_292 = ".createURI(url.toString());" + NL + "\t\t";
protected final String TEXT_293 = " resource = new ";
protected final String TEXT_294 = "().createResource(uri);" + NL + "\t\ttry" + NL + "\t\t{" + NL + "\t\t\tresource.load(null);" + NL + "\t\t}" + NL + "\t\tcatch (";
protected final String TEXT_295 = " exception)" + NL + "\t\t{" + NL + "\t\t\tthrow new ";
protected final String TEXT_296 = "(exception);" + NL + "\t\t}" + NL + "\t\tinitializeFromLoadedEPackage(this, (";
protected final String TEXT_297 = ")resource.getContents().get(0));" + NL + "\t\tcreateResource(eNS_URI);" + NL + "\t}" + NL;
protected final String TEXT_298 = NL + NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprivate boolean isFixed = false;" + NL + "" + NL + "\t/**" + NL + "\t * Fixes up the loaded package, to make it appear as if it had been programmatically built." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tpublic void fixPackageContents()" + NL + "\t{" + NL + "\t\tif (isFixed) return;" + NL + "\t\tisFixed = true;" + NL + "\t\tfixEClassifiers();" + NL + "\t}" + NL + "" + NL + "\t/**" + NL + "\t * Sets the instance class on the given classifier." + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */";
protected final String TEXT_299 = NL + "\tprotected void fixInstanceClass(";
protected final String TEXT_300 = " eClassifier)" + NL + "\t{" + NL + "\t\tif (eClassifier.getInstanceClassName() == null)" + NL + "\t\t{";
protected final String TEXT_301 = NL + "\t\t\teClassifier.setInstanceClassName(\"";
protected final String TEXT_302 = ".\" + eClassifier.getName());";
protected final String TEXT_303 = NL + "\t\t\tsetGeneratedClassName(eClassifier);";
protected final String TEXT_304 = NL + "\t\t\tswitch (eClassifier.getClassifierID())" + NL + "\t\t\t{";
protected final String TEXT_305 = NL + "\t\t\t\tcase ";
protected final String TEXT_306 = ":";
protected final String TEXT_307 = NL + "\t\t\t\t{" + NL + "\t\t\t\t\tbreak;" + NL + "\t\t\t\t}" + NL + "\t\t\t\tdefault:" + NL + "\t\t\t\t{" + NL + "\t\t\t\t\teClassifier.setInstanceClassName(\"";
protected final String TEXT_308 = NL + "\t\t\t\t\tsetGeneratedClassName(eClassifier);" + NL + "\t\t\t\t\tbreak;" + NL + "\t\t\t\t}" + NL + "\t\t\t}";
protected final String TEXT_309 = NL + "\t\t}" + NL + "\t}" + NL;
protected final String TEXT_310 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\tprotected ";
protected final String TEXT_311 = " addEOperation(";
protected final String TEXT_312 = " owner, ";
protected final String TEXT_313 = " type, String name, int lowerBound, int upperBound, boolean isUnique, boolean isOrdered)" + NL + "\t{" + NL + "\t\t";
protected final String TEXT_314 = " o = addEOperation(owner, type, name, lowerBound, upperBound);" + NL + "\t\to.setUnique(isUnique);" + NL + "\t\to.setOrdered(isOrdered);" + NL + "\t\treturn o;" + NL + "\t}" + NL;
protected final String TEXT_315 = " addEParameter(";
protected final String TEXT_316 = " p = ecoreFactory.createEParameter();" + NL + "\t\tp.setEType(type);" + NL + "\t\tp.setName(name);" + NL + "\t\tp.setLowerBound(lowerBound);" + NL + "\t\tp.setUpperBound(upperBound);" + NL + "\t\tp.setUnique(isUnique);" + NL + "\t\tp.setOrdered(isOrdered);" + NL + "\t\towner.getEParameters().add(p);" + NL + "\t\treturn p;" + NL + "\t}" + NL;
protected final String TEXT_317 = NL + "\t/**" + NL + "\t * <!-- begin-user-doc -->" + NL + "\t * Defines literals for the meta objects that represent" + NL + "\t * <ul>" + NL + "\t * <li>each class,</li>" + NL + "\t * <li>each feature of each class,</li>";
protected final String TEXT_318 = NL + "\t * <li>each operation of each class,</li>";
protected final String TEXT_319 = NL + "\t * <li>each enum,</li>" + NL + "\t * <li>and each data type</li>" + NL + "\t * </ul>" + NL + "\t * <!-- end-user-doc -->" + NL + "\t * @generated" + NL + "\t */" + NL + "\t";
protected final String TEXT_320 = "public ";
protected final String TEXT_321 = "interface Literals" + NL + "\t{";
protected final String TEXT_322 = NL + "\t\t/**";
protected final String TEXT_323 = NL + "\t\t * The meta object literal for the '{@link ";
protected final String TEXT_324 = "</em>}' class." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @see ";
protected final String TEXT_325 = "</em>}' enum." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->" + NL + "\t\t * @see ";
protected final String TEXT_326 = NL + "\t\t * The meta object literal for the '<em>";
protected final String TEXT_327 = "</em>' data type." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->";
protected final String TEXT_328 = NL + "\t\t * @see ";
protected final String TEXT_329 = NL + "\t\t * ";
protected final String TEXT_330 = NL + "\t\t * @generated" + NL + "\t\t */";
protected final String TEXT_331 = NL + "\t\t@Deprecated";
protected final String TEXT_332 = " = eINSTANCE.get";
protected final String TEXT_333 = NL + "\t\t/**" + NL + "\t\t * The meta object literal for the '<em><b>";
protected final String TEXT_334 = " feature." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->";
protected final String TEXT_335 = "</b></em>' operation." + NL + "\t\t * <!-- begin-user-doc -->" + NL + "\t\t * <!-- end-user-doc -->";
protected final String TEXT_336 = NL + "} //";
public String generate(Object argument)
{
final StringBuffer stringBuffer = new StringBuffer();
/**
* Copyright (c) 2002-2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v20.html
*
* Contributors:
* IBM - Initial API and implementation
*/
final GenPackage genPackage = (GenPackage)((Object[])argument)[0]; final GenModel genModel=genPackage.getGenModel();
final boolean isJDK50 = genModel.getComplianceLevel().getValue() >= GenJDKLevel.JDK50;
boolean isInterface = Boolean.TRUE.equals(((Object[])argument)[1]); boolean isImplementation = Boolean.TRUE.equals(((Object[])argument)[2]); boolean useInterfaceOverrideAnnotation = genModel.useInterfaceOverrideAnnotation() && !(isInterface && isImplementation);
boolean packageNeedsSuppressDeprecation = isJDK50 && GenModelUtil.hasAPIDeprecatedTag(genPackage.getOrderedGenClassifiers()) && !genPackage.hasAPIDeprecatedTag();
String publicStaticFinalFlag = isImplementation ? "public static final " : "";
boolean needsAddEOperation = false;
boolean needsAddEParameter = false;
stringBuffer.append(TEXT_1);
stringBuffer.append(TEXT_2);
{GenBase copyrightHolder = argument instanceof GenBase ? (GenBase)argument : argument instanceof Object[] && ((Object[])argument)[0] instanceof GenBase ? (GenBase)((Object[])argument)[0] : null;
if (copyrightHolder != null && copyrightHolder.hasCopyright()) {
stringBuffer.append(TEXT_3);
stringBuffer.append(copyrightHolder.getCopyright(copyrightHolder.getGenModel().getIndentation(stringBuffer)));
}}
stringBuffer.append(TEXT_4);
if (isImplementation && !genModel.isSuppressInterfaces()) {
stringBuffer.append(TEXT_5);
stringBuffer.append(genPackage.getClassPackageName());
stringBuffer.append(TEXT_6);
} else {
stringBuffer.append(TEXT_5);
stringBuffer.append(genPackage.getReflectionPackageName());
stringBuffer.append(TEXT_6);
}
stringBuffer.append(TEXT_7);
genModel.markImportLocation(stringBuffer, genPackage);
if (isImplementation) {
genModel.addPseudoImport("org.eclipse.emf.ecore.EPackage.Registry");
genModel.addPseudoImport("org.eclipse.emf.ecore.EPackage.Descriptor");
genModel.addPseudoImport("org.eclipse.emf.ecore.impl.EPackageImpl.EBasicWhiteList");
genModel.addPseudoImport("org.eclipse.emf.ecore.impl.MinimalEObjectImpl.Container");
genModel.addPseudoImport("org.eclipse.emf.ecore.impl.MinimalEObjectImpl.Container.Dynamic");
if (genPackage.isLiteralsInterface()) {
genModel.addPseudoImport(genPackage.getQualifiedPackageInterfaceName() + ".Literals");
}
for (GenClassifier genClassifier : genPackage.getOrderedGenClassifiers()) genModel.addPseudoImport(genPackage.getQualifiedPackageInterfaceName() + "." + genPackage.getClassifierID(genClassifier));
}
if (isInterface) {
stringBuffer.append(TEXT_8);
if (genModel.isOperationReflection()) {
stringBuffer.append(TEXT_9);
}
stringBuffer.append(TEXT_10);
if (genPackage.hasDocumentation()) {
stringBuffer.append(TEXT_11);
stringBuffer.append(genPackage.getDocumentation(genModel.getIndentation(stringBuffer)));
stringBuffer.append(TEXT_12);
}
stringBuffer.append(TEXT_13);
stringBuffer.append(genPackage.getQualifiedFactoryInterfaceName());
if (!genModel.isSuppressEMFModelTags()) { boolean first = true; for (StringTokenizer stringTokenizer = new StringTokenizer(genPackage.getModelInfo(), "\n\r"); stringTokenizer.hasMoreTokens(); ) { String modelInfo = stringTokenizer.nextToken(); if (first) { first = false;
stringBuffer.append(TEXT_14);
stringBuffer.append(modelInfo);
} else {
stringBuffer.append(TEXT_15);
stringBuffer.append(modelInfo);
}} if (first) {
stringBuffer.append(TEXT_16);
}}
stringBuffer.append(TEXT_17);
} else {
stringBuffer.append(TEXT_18);
if (genPackage.hasAPITags()) {
stringBuffer.append(TEXT_3);
stringBuffer.append(genPackage.getAPITags(genModel.getIndentation(stringBuffer)));
}
stringBuffer.append(TEXT_17);
}
if (isJDK50 && genPackage.hasAPIDeprecatedTag()) {
stringBuffer.append(TEXT_19);
}
if (isImplementation) {
if (packageNeedsSuppressDeprecation) {
stringBuffer.append(TEXT_20);
}
stringBuffer.append(TEXT_21);
stringBuffer.append(genPackage.getPackageClassName());
stringBuffer.append(TEXT_22);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.impl.EPackageImpl"));
if (!isInterface){
stringBuffer.append(TEXT_23);
stringBuffer.append(genPackage.getImportedPackageInterfaceName());
}
} else {
stringBuffer.append(TEXT_24);
stringBuffer.append(genPackage.getPackageInterfaceName());
stringBuffer.append(TEXT_22);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage"));
}
stringBuffer.append(TEXT_25);
if (genModel.hasCopyrightField()) {
stringBuffer.append(TEXT_26);
stringBuffer.append(publicStaticFinalFlag);
stringBuffer.append(genModel.getImportedName("java.lang.String"));
stringBuffer.append(TEXT_27);
stringBuffer.append(genModel.getCopyrightFieldLiteral());
stringBuffer.append(TEXT_6);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_7);
}
if (isInterface) {
stringBuffer.append(TEXT_28);
stringBuffer.append(publicStaticFinalFlag);
stringBuffer.append(genModel.getImportedName("java.lang.String"));
stringBuffer.append(TEXT_29);
stringBuffer.append(genPackage.getPackageName());
stringBuffer.append(TEXT_30);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_31);
stringBuffer.append(publicStaticFinalFlag);
stringBuffer.append(genModel.getImportedName("java.lang.String"));
stringBuffer.append(TEXT_32);
stringBuffer.append(genPackage.getNSURI());
stringBuffer.append(TEXT_30);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_33);
stringBuffer.append(publicStaticFinalFlag);
stringBuffer.append(genModel.getImportedName("java.lang.String"));
stringBuffer.append(TEXT_34);
stringBuffer.append(genPackage.getNSName());
stringBuffer.append(TEXT_30);
stringBuffer.append(genModel.getNonNLS());
if (genPackage.isContentType()) {
stringBuffer.append(TEXT_35);
stringBuffer.append(publicStaticFinalFlag);
stringBuffer.append(genModel.getImportedName("java.lang.String"));
stringBuffer.append(TEXT_36);
stringBuffer.append(genPackage.getContentTypeIdentifier());
stringBuffer.append(TEXT_30);
stringBuffer.append(genModel.getNonNLS());
}
stringBuffer.append(TEXT_37);
stringBuffer.append(publicStaticFinalFlag);
stringBuffer.append(genPackage.getPackageInterfaceName());
stringBuffer.append(TEXT_38);
stringBuffer.append(genPackage.getQualifiedPackageClassName());
stringBuffer.append(TEXT_39);
for (GenClassifier genClassifier : genPackage.getOrderedGenClassifiers()) {
stringBuffer.append(TEXT_40);
if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier;
if (!genClass.isInterface()) {
stringBuffer.append(TEXT_41);
stringBuffer.append(genClass.getQualifiedClassName());
stringBuffer.append(TEXT_42);
stringBuffer.append(genClass.getFormattedName());
stringBuffer.append(TEXT_43);
stringBuffer.append(genClass.getQualifiedClassName());
} else {
stringBuffer.append(TEXT_41);
stringBuffer.append(genClass.getRawQualifiedInterfaceName());
stringBuffer.append(TEXT_42);
stringBuffer.append(genClass.getFormattedName());
stringBuffer.append(TEXT_43);
stringBuffer.append(genClass.getRawQualifiedInterfaceName());
}
} else if (genClassifier instanceof GenEnum) { GenEnum genEnum = (GenEnum)genClassifier;
stringBuffer.append(TEXT_41);
stringBuffer.append(genEnum.getQualifiedName());
stringBuffer.append(TEXT_42);
stringBuffer.append(genEnum.getFormattedName());
stringBuffer.append(TEXT_44);
stringBuffer.append(genEnum.getQualifiedName());
} else if (genClassifier instanceof GenDataType) { GenDataType genDataType = (GenDataType)genClassifier;
stringBuffer.append(TEXT_45);
stringBuffer.append(genDataType.getFormattedName());
stringBuffer.append(TEXT_46);
if (!genDataType.isPrimitiveType() && !genDataType.isArrayType()) {
stringBuffer.append(TEXT_47);
stringBuffer.append(genDataType.getRawInstanceClassName());
}
}
stringBuffer.append(TEXT_47);
stringBuffer.append(genPackage.getQualifiedPackageClassName());
stringBuffer.append(TEXT_48);
stringBuffer.append(genClassifier.getClassifierAccessorName());
stringBuffer.append(TEXT_49);
if (genClassifier.hasAPITags()) {
stringBuffer.append(TEXT_50);
stringBuffer.append(genClassifier.getAPITags(genModel.getIndentation(stringBuffer)));
}
stringBuffer.append(TEXT_51);
if (isJDK50 && genClassifier.hasAPIDeprecatedTag()) {
stringBuffer.append(TEXT_52);
}
stringBuffer.append(TEXT_53);
stringBuffer.append(publicStaticFinalFlag);
stringBuffer.append(TEXT_54);
stringBuffer.append(genPackage.getClassifierID(genClassifier));
stringBuffer.append(TEXT_55);
stringBuffer.append(genPackage.getClassifierValue(genClassifier));
stringBuffer.append(TEXT_56);
if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier;
for (GenFeature genFeature : genClass.getAllGenFeatures()) {
stringBuffer.append(TEXT_57);
stringBuffer.append(genFeature.getFormattedName());
stringBuffer.append(TEXT_58);
stringBuffer.append(genFeature.getFeatureKind());
stringBuffer.append(TEXT_59);
if (genFeature.hasImplicitAPITags()) {
stringBuffer.append(TEXT_50);
stringBuffer.append(genFeature.getImplicitAPITags(genModel.getIndentation(stringBuffer)));
}
stringBuffer.append(TEXT_60);
if (isJDK50 && genFeature.hasImplicitAPIDeprecatedTag()) {
stringBuffer.append(TEXT_52);
}
stringBuffer.append(TEXT_53);
stringBuffer.append(publicStaticFinalFlag);
stringBuffer.append(TEXT_54);
stringBuffer.append(genClass.getFeatureID(genFeature));
stringBuffer.append(TEXT_55);
stringBuffer.append(genClass.getFeatureValue(genFeature));
stringBuffer.append(TEXT_56);
}
stringBuffer.append(TEXT_61);
stringBuffer.append(genClass.getFormattedName());
stringBuffer.append(TEXT_62);
if (genClass.hasAPITags()) {
stringBuffer.append(TEXT_50);
stringBuffer.append(genClass.getAPITags(genModel.getIndentation(stringBuffer)));
}
stringBuffer.append(TEXT_60);
if (isJDK50 && genClass.hasAPIDeprecatedTag()) {
stringBuffer.append(TEXT_52);
}
stringBuffer.append(TEXT_53);
stringBuffer.append(publicStaticFinalFlag);
stringBuffer.append(TEXT_54);
stringBuffer.append(genClass.getFeatureCountID());
stringBuffer.append(TEXT_55);
stringBuffer.append(genClass.getFeatureCountValue());
stringBuffer.append(TEXT_56);
if (genModel.isOperationReflection()) {
for (GenOperation genOperation : genClass.getAllGenOperations(false)) {
if (genClass.getOverrideGenOperation(genOperation) == null) {
stringBuffer.append(TEXT_63);
stringBuffer.append(genOperation.getFormattedName());
stringBuffer.append(TEXT_64);
if (genOperation.hasImplicitAPITags()) {
stringBuffer.append(TEXT_50);
stringBuffer.append(genOperation.getImplicitAPITags(genModel.getIndentation(stringBuffer)));
}
stringBuffer.append(TEXT_60);
if (isJDK50 && genOperation.hasImplicitAPIDeprecatedTag()) {
stringBuffer.append(TEXT_52);
}
stringBuffer.append(TEXT_53);
stringBuffer.append(publicStaticFinalFlag);
stringBuffer.append(TEXT_54);
stringBuffer.append(genClass.getOperationID(genOperation, false));
stringBuffer.append(TEXT_55);
stringBuffer.append(genClass.getOperationValue(genOperation));
stringBuffer.append(TEXT_56);
}
}
stringBuffer.append(TEXT_65);
stringBuffer.append(genClass.getFormattedName());
stringBuffer.append(TEXT_62);
if (genClass.hasAPITags()) {
stringBuffer.append(TEXT_50);
stringBuffer.append(genClass.getAPITags(genModel.getIndentation(stringBuffer)));
}
stringBuffer.append(TEXT_60);
if (isJDK50 && genClass.hasAPIDeprecatedTag()) {
stringBuffer.append(TEXT_52);
}
stringBuffer.append(TEXT_53);
stringBuffer.append(publicStaticFinalFlag);
stringBuffer.append(TEXT_54);
stringBuffer.append(genClass.getOperationCountID());
stringBuffer.append(TEXT_55);
stringBuffer.append(genClass.getOperationCountValue());
stringBuffer.append(TEXT_56);
}
}
}
}
if (isImplementation) {
if (genPackage.isLoadingInitialization()) {
stringBuffer.append(TEXT_66);
stringBuffer.append(genPackage.getSerializedPackageFilename());
stringBuffer.append(TEXT_30);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_7);
}
for (GenClassifier genClassifier : genPackage.getGenClassifiers()) {
stringBuffer.append(TEXT_67);
if (genClassifier.hasAPITags()) {
stringBuffer.append(TEXT_50);
stringBuffer.append(genClassifier.getAPITags(genModel.getIndentation(stringBuffer)));
}
stringBuffer.append(TEXT_51);
if (isJDK50 && genClassifier.hasAPIDeprecatedTag()) {
stringBuffer.append(TEXT_52);
}
stringBuffer.append(TEXT_68);
stringBuffer.append(genClassifier.getImportedMetaType());
stringBuffer.append(TEXT_69);
stringBuffer.append(genClassifier.getClassifierInstanceName());
stringBuffer.append(TEXT_70);
}
stringBuffer.append(TEXT_71);
stringBuffer.append(genPackage.getQualifiedPackageInterfaceName());
stringBuffer.append(TEXT_72);
stringBuffer.append(genPackage.getPackageClassName());
stringBuffer.append(TEXT_73);
stringBuffer.append(genPackage.getQualifiedEFactoryInstanceAccessor());
stringBuffer.append(TEXT_74);
stringBuffer.append(genPackage.getImportedPackageInterfaceName());
stringBuffer.append(TEXT_75);
if (!genPackage.isLoadedInitialization()) {
stringBuffer.append(TEXT_76);
}
stringBuffer.append(TEXT_77);
stringBuffer.append(genPackage.getImportedPackageInterfaceName());
stringBuffer.append(TEXT_78);
stringBuffer.append(genPackage.getImportedPackageInterfaceName());
stringBuffer.append(TEXT_79);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage"));
stringBuffer.append(TEXT_80);
stringBuffer.append(genPackage.getImportedPackageInterfaceName());
stringBuffer.append(TEXT_81);
if (genModel.getRuntimePlatform() == GenRuntimePlatform.GWT) {
stringBuffer.append(TEXT_82);
}
stringBuffer.append(TEXT_83);
stringBuffer.append(genPackage.getBasicPackageName());
stringBuffer.append(TEXT_55);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage"));
stringBuffer.append(TEXT_84);
stringBuffer.append(genPackage.getPackageClassName());
stringBuffer.append(TEXT_85);
stringBuffer.append(genPackage.getBasicPackageName());
stringBuffer.append(TEXT_86);
stringBuffer.append(genPackage.getBasicPackageName());
stringBuffer.append(TEXT_87);
stringBuffer.append(genPackage.getPackageClassName());
stringBuffer.append(TEXT_88);
stringBuffer.append(genPackage.getPackageClassName());
stringBuffer.append(TEXT_89);
stringBuffer.append(genPackage.getBasicPackageName());
stringBuffer.append(TEXT_90);
stringBuffer.append(genPackage.getPackageClassName());
stringBuffer.append(TEXT_91);
if (!genPackage.getPackageSimpleDependencies().isEmpty()) {
stringBuffer.append(TEXT_92);
for (GenPackage dep : genPackage.getPackageSimpleDependencies()) {
stringBuffer.append(TEXT_93);
stringBuffer.append(dep.getImportedPackageInterfaceName());
stringBuffer.append(TEXT_94);
}
stringBuffer.append(TEXT_7);
}
if (!genPackage.getPackageInterDependencies().isEmpty()) {
stringBuffer.append(TEXT_95);
for (ListIterator<GenPackage> i = genPackage.getPackageInterDependencies().listIterator(); i.hasNext(); ) { GenPackage interdep = i.next();
stringBuffer.append(TEXT_93);
if (i.previousIndex() == 0) {
stringBuffer.append(TEXT_96);
}
stringBuffer.append(TEXT_97);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage"));
stringBuffer.append(TEXT_80);
stringBuffer.append(interdep.getImportedPackageInterfaceName());
stringBuffer.append(TEXT_98);
stringBuffer.append(interdep.getImportedPackageClassName());
stringBuffer.append(TEXT_69);
stringBuffer.append(genPackage.getPackageInstanceVariable(interdep));
stringBuffer.append(TEXT_99);
stringBuffer.append(interdep.getImportedPackageClassName());
stringBuffer.append(TEXT_100);
stringBuffer.append(interdep.getImportedPackageClassName());
stringBuffer.append(TEXT_101);
stringBuffer.append(interdep.getImportedPackageInterfaceName());
stringBuffer.append(TEXT_102);
}
stringBuffer.append(TEXT_7);
}
if (genPackage.isLoadedInitialization() || !genPackage.getPackageLoadInterDependencies().isEmpty()) {
stringBuffer.append(TEXT_103);
if (genPackage.isLoadingInitialization()) {
stringBuffer.append(TEXT_104);
stringBuffer.append(genPackage.getBasicPackageName());
stringBuffer.append(TEXT_105);
}
for (GenPackage interdep : genPackage.getPackageLoadInterDependencies()) {
if (interdep.isLoadingInitialization()) {
stringBuffer.append(TEXT_93);
stringBuffer.append(genPackage.getPackageInstanceVariable(interdep));
stringBuffer.append(TEXT_105);
}
}
stringBuffer.append(TEXT_7);
}
if (!genPackage.isLoadedInitialization() || !genPackage.getPackageBuildInterDependencies().isEmpty()) {
stringBuffer.append(TEXT_106);
if (!genPackage.isLoadedInitialization()) {
stringBuffer.append(TEXT_104);
stringBuffer.append(genPackage.getBasicPackageName());
stringBuffer.append(TEXT_107);
}
for (GenPackage interdep : genPackage.getPackageBuildInterDependencies()) {
stringBuffer.append(TEXT_93);
stringBuffer.append(genPackage.getPackageInstanceVariable(interdep));
stringBuffer.append(TEXT_107);
}
stringBuffer.append(TEXT_108);
if (!genPackage.isLoadedInitialization()) {
stringBuffer.append(TEXT_104);
stringBuffer.append(genPackage.getBasicPackageName());
stringBuffer.append(TEXT_109);
}
for (GenPackage interdep : genPackage.getPackageBuildInterDependencies()) {
stringBuffer.append(TEXT_93);
stringBuffer.append(genPackage.getPackageInstanceVariable(interdep));
stringBuffer.append(TEXT_109);
}
stringBuffer.append(TEXT_7);
}
if (genPackage.isLoadedInitialization() || !genPackage.getPackageLoadInterDependencies().isEmpty()) {
stringBuffer.append(TEXT_110);
if (genPackage.isLoadedInitialization()) {
stringBuffer.append(TEXT_104);
stringBuffer.append(genPackage.getBasicPackageName());
stringBuffer.append(TEXT_111);
}
for (GenPackage interdep : genPackage.getPackageLoadInterDependencies()) {
stringBuffer.append(TEXT_93);
stringBuffer.append(genPackage.getPackageInstanceVariable(interdep));
stringBuffer.append(TEXT_111);
}
stringBuffer.append(TEXT_7);
}
if (genPackage.hasConstraints()) {
stringBuffer.append(TEXT_112);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EValidator"));
stringBuffer.append(TEXT_113);
stringBuffer.append(genPackage.getBasicPackageName());
stringBuffer.append(TEXT_114);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EValidator"));
stringBuffer.append(TEXT_115);
if (genModel.useInterfaceOverrideAnnotation()) {
stringBuffer.append(TEXT_116);
}
stringBuffer.append(TEXT_117);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EValidator"));
stringBuffer.append(TEXT_118);
stringBuffer.append(genPackage.getImportedValidatorClassName());
stringBuffer.append(TEXT_119);
}
if (!genPackage.isEcorePackage()) {
stringBuffer.append(TEXT_120);
stringBuffer.append(genPackage.getBasicPackageName());
stringBuffer.append(TEXT_121);
}
stringBuffer.append(TEXT_122);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage"));
stringBuffer.append(TEXT_123);
stringBuffer.append(genPackage.getImportedPackageInterfaceName());
stringBuffer.append(TEXT_124);
stringBuffer.append(genPackage.getBasicPackageName());
stringBuffer.append(TEXT_125);
stringBuffer.append(genPackage.getBasicPackageName());
stringBuffer.append(TEXT_126);
if (genModel.getRuntimePlatform() == GenRuntimePlatform.GWT) {
stringBuffer.append(TEXT_127);
Set<String> helpers = new HashSet<String>(); for (GenClassifier genClassifier : genPackage.getGenClassifiers()) {
if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier;
if (!genClass.isDynamic()) { String theClass = genClass.isMapEntry() ? genClass.getImportedClassName() : genClass.getRawImportedInterfaceName(); if (helpers.add(theClass)) {
stringBuffer.append(TEXT_93);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.common.util.Reflect"));
stringBuffer.append(TEXT_128);
stringBuffer.append(theClass);
stringBuffer.append(TEXT_129);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.common.util.Reflect"));
stringBuffer.append(TEXT_130);
stringBuffer.append(genClass.isMapEntry() ? genClass.getImportedClassName() : genClass.getRawImportedInterfaceName() + genClass.getInterfaceWildTypeArguments());
stringBuffer.append(TEXT_131);
stringBuffer.append(theClass);
stringBuffer.append(TEXT_132);
}}
} else if (genClassifier instanceof GenDataType) { GenDataType genDataType = (GenDataType)genClassifier;
if (!genDataType.isPrimitiveType() && !genDataType.isObjectType()) { String theClass = genDataType.getRawImportedInstanceClassName(); if (helpers.add(theClass)) {
stringBuffer.append(TEXT_93);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.common.util.Reflect"));
stringBuffer.append(TEXT_128);
stringBuffer.append(theClass);
stringBuffer.append(TEXT_129);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.common.util.Reflect"));
stringBuffer.append(TEXT_130);
stringBuffer.append(theClass);
stringBuffer.append(TEXT_133);
if (genDataType.isArrayType()) { String componentType = theClass; String indices = ""; while(componentType.endsWith("[]")) { componentType = componentType.substring(0, componentType.length() - 2); indices += "[]";}
stringBuffer.append(TEXT_134);
stringBuffer.append(componentType);
stringBuffer.append(TEXT_135);
stringBuffer.append(indices);
stringBuffer.append(TEXT_6);
} else {
stringBuffer.append(TEXT_134);
stringBuffer.append(theClass);
stringBuffer.append(TEXT_136);
}
stringBuffer.append(TEXT_137);
}}
}
}
stringBuffer.append(TEXT_138);
stringBuffer.append(genModel.getImportedName("com.google.gwt.user.client.rpc.IsSerializable"));
stringBuffer.append(TEXT_139);
for (GenClassifier genClassifier : genPackage.getGenClassifiers()) {
if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier;
if (!genClass.isDynamic()) {
stringBuffer.append(TEXT_140);
stringBuffer.append(genClass.isMapEntry() ? genClass.getImportedClassName() : genClass.getImportedWildcardInstanceClassName());
stringBuffer.append(TEXT_69);
stringBuffer.append(genClass.getSafeUncapName());
stringBuffer.append(TEXT_56);
}
} else if (genClassifier instanceof GenDataType) { GenDataType genDataType = (GenDataType)genClassifier;
if (!genDataType.isObjectType() && genDataType.isSerializable()) {
stringBuffer.append(TEXT_140);
stringBuffer.append(genDataType.getImportedWildcardInstanceClassName());
stringBuffer.append(TEXT_69);
stringBuffer.append(genDataType.getSafeUncapName());
stringBuffer.append(TEXT_56);
}
}
}
stringBuffer.append(TEXT_141);
}
stringBuffer.append(TEXT_7);
}
if (isInterface) { // TODO REMOVE THIS BOGUS EMPTY LINE
stringBuffer.append(TEXT_7);
}
for (GenClassifier genClassifier : genPackage.getGenClassifiers()) {
if (isInterface) {
stringBuffer.append(TEXT_40);
if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier;
stringBuffer.append(TEXT_142);
stringBuffer.append(genClass.getRawQualifiedInterfaceName());
stringBuffer.append(TEXT_42);
stringBuffer.append(genClass.getFormattedName());
stringBuffer.append(TEXT_143);
stringBuffer.append(genClass.getFormattedName());
stringBuffer.append(TEXT_144);
stringBuffer.append(genClass.getRawQualifiedInterfaceName());
if (!genModel.isSuppressEMFModelTags() && (genClass.isExternalInterface() || genClass.isDynamic())) { boolean first = true; for (StringTokenizer stringTokenizer = new StringTokenizer(genClass.getModelInfo(), "\n\r"); stringTokenizer.hasMoreTokens(); ) { String modelInfo = stringTokenizer.nextToken(); if (first) { first = false;
stringBuffer.append(TEXT_145);
stringBuffer.append(modelInfo);
} else {
stringBuffer.append(TEXT_146);
stringBuffer.append(modelInfo);
}} if (first) {
stringBuffer.append(TEXT_147);
}}
} else if (genClassifier instanceof GenEnum) { GenEnum genEnum = (GenEnum)genClassifier;
stringBuffer.append(TEXT_148);
stringBuffer.append(genEnum.getQualifiedName());
stringBuffer.append(TEXT_42);
stringBuffer.append(genEnum.getFormattedName());
stringBuffer.append(TEXT_149);
stringBuffer.append(genEnum.getFormattedName());
stringBuffer.append(TEXT_144);
stringBuffer.append(genEnum.getQualifiedName());
} else if (genClassifier instanceof GenDataType) { GenDataType genDataType = (GenDataType)genClassifier;
if (genDataType.isPrimitiveType() || genDataType.isArrayType()) {
stringBuffer.append(TEXT_150);
stringBuffer.append(genDataType.getFormattedName());
stringBuffer.append(TEXT_151);
} else {
stringBuffer.append(TEXT_152);
stringBuffer.append(genDataType.getRawInstanceClassName());
stringBuffer.append(TEXT_42);
stringBuffer.append(genDataType.getFormattedName());
stringBuffer.append(TEXT_153);
}
stringBuffer.append(TEXT_154);
if (genDataType.hasDocumentation()) {
stringBuffer.append(TEXT_155);
stringBuffer.append(genDataType.getDocumentation(genModel.getIndentation(stringBuffer)));
stringBuffer.append(TEXT_156);
}
stringBuffer.append(TEXT_157);
stringBuffer.append(genDataType.getFormattedName());
stringBuffer.append(TEXT_151);
if (!genDataType.isPrimitiveType() && !genDataType.isArrayType()) {
stringBuffer.append(TEXT_47);
stringBuffer.append(genDataType.getRawInstanceClassName());
}
if (!genModel.isSuppressEMFModelTags()) {boolean first = true; for (StringTokenizer stringTokenizer = new StringTokenizer(genDataType.getModelInfo(), "\n\r"); stringTokenizer.hasMoreTokens(); ) { String modelInfo = stringTokenizer.nextToken(); if (first) { first = false;
stringBuffer.append(TEXT_145);
stringBuffer.append(modelInfo);
} else {
stringBuffer.append(TEXT_146);
stringBuffer.append(modelInfo);
}} if (first) {
stringBuffer.append(TEXT_147);
}}
}
if ((genClassifier instanceof GenClass || genClassifier instanceof GenEnum) && genClassifier.hasAPITags()) {
stringBuffer.append(TEXT_50);
stringBuffer.append(genClassifier.getAPITags(genModel.getIndentation(stringBuffer)));
}
stringBuffer.append(TEXT_51);
} else {
stringBuffer.append(TEXT_67);
if (genClassifier.hasAPITags()) {
stringBuffer.append(TEXT_50);
stringBuffer.append(genClassifier.getAPITags(genModel.getIndentation(stringBuffer)));
}
stringBuffer.append(TEXT_51);
}
if (isJDK50 && genClassifier.hasAPIDeprecatedTag()) {
stringBuffer.append(TEXT_52);
}
if (isImplementation) {
if (useInterfaceOverrideAnnotation) {
stringBuffer.append(TEXT_158);
}
stringBuffer.append(TEXT_159);
stringBuffer.append(genClassifier.getImportedMetaType());
stringBuffer.append(TEXT_160);
stringBuffer.append(genClassifier.getClassifierAccessorName());
stringBuffer.append(TEXT_161);
if (genPackage.isLoadedInitialization()) {
stringBuffer.append(TEXT_162);
stringBuffer.append(genClassifier.getClassifierInstanceName());
stringBuffer.append(TEXT_163);
stringBuffer.append(genClassifier.getClassifierInstanceName());
stringBuffer.append(TEXT_99);
stringBuffer.append(genClassifier.getImportedMetaType());
stringBuffer.append(TEXT_79);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage"));
stringBuffer.append(TEXT_80);
stringBuffer.append(genPackage.getImportedPackageInterfaceName());
stringBuffer.append(TEXT_164);
stringBuffer.append(genPackage.getLocalClassifierIndex(genClassifier));
stringBuffer.append(TEXT_165);
}
stringBuffer.append(TEXT_166);
stringBuffer.append(genClassifier.getClassifierInstanceName());
stringBuffer.append(TEXT_167);
} else {
stringBuffer.append(TEXT_53);
stringBuffer.append(genClassifier.getImportedMetaType());
stringBuffer.append(TEXT_160);
stringBuffer.append(genClassifier.getClassifierAccessorName());
stringBuffer.append(TEXT_168);
}
if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier;
for (GenFeature genFeature : genClass.getGenFeatures()) {
if (isInterface) {
stringBuffer.append(TEXT_169);
stringBuffer.append(genFeature.getFeatureKind());
stringBuffer.append(TEXT_170);
stringBuffer.append(genClass.getRawQualifiedInterfaceName());
if (!genClass.isMapEntry() && !genFeature.isSuppressedGetVisibility()) {
stringBuffer.append(TEXT_171);
stringBuffer.append(genFeature.getGetAccessor());
}
stringBuffer.append(TEXT_42);
stringBuffer.append(genFeature.getFormattedName());
stringBuffer.append(TEXT_172);
stringBuffer.append(genFeature.getFeatureKind());
stringBuffer.append(TEXT_173);
stringBuffer.append(genFeature.getFormattedName());
stringBuffer.append(TEXT_144);
stringBuffer.append(genClass.getRawQualifiedInterfaceName());
if (!genClass.isMapEntry() && !genFeature.isSuppressedGetVisibility()) {
stringBuffer.append(TEXT_171);
stringBuffer.append(genFeature.getGetAccessor());
stringBuffer.append(TEXT_49);
}
stringBuffer.append(TEXT_174);
stringBuffer.append(genClass.getClassifierAccessorName());
stringBuffer.append(TEXT_49);
if (genFeature.hasImplicitAPITags()) {
stringBuffer.append(TEXT_50);
stringBuffer.append(genFeature.getImplicitAPITags(genModel.getIndentation(stringBuffer)));
}
stringBuffer.append(TEXT_51);
} else {
stringBuffer.append(TEXT_67);
if (genFeature.hasImplicitAPITags()) {
stringBuffer.append(TEXT_50);
stringBuffer.append(genFeature.getImplicitAPITags(genModel.getIndentation(stringBuffer)));
}
stringBuffer.append(TEXT_51);
}
if (isJDK50 && genFeature.hasImplicitAPIDeprecatedTag()) {
stringBuffer.append(TEXT_52);
}
if (isImplementation) {
if (useInterfaceOverrideAnnotation) {
stringBuffer.append(TEXT_158);
}
stringBuffer.append(TEXT_159);
stringBuffer.append(genFeature.getImportedMetaType());
stringBuffer.append(TEXT_160);
stringBuffer.append(genFeature.getFeatureAccessorName());
stringBuffer.append(TEXT_161);
if (!genPackage.isLoadedInitialization()) {
stringBuffer.append(TEXT_175);
stringBuffer.append(genFeature.getImportedMetaType());
stringBuffer.append(TEXT_79);
stringBuffer.append(genClass.getClassifierInstanceName());
stringBuffer.append(TEXT_176);
stringBuffer.append(genClass.getLocalFeatureIndex(genFeature));
stringBuffer.append(TEXT_177);
} else {
stringBuffer.append(TEXT_178);
stringBuffer.append(genFeature.getImportedMetaType());
stringBuffer.append(TEXT_179);
stringBuffer.append(genClassifier.getClassifierAccessorName());
stringBuffer.append(TEXT_180);
stringBuffer.append(genClass.getLocalFeatureIndex(genFeature));
stringBuffer.append(TEXT_177);
}
stringBuffer.append(TEXT_141);
} else {
stringBuffer.append(TEXT_53);
stringBuffer.append(genFeature.getImportedMetaType());
stringBuffer.append(TEXT_160);
stringBuffer.append(genFeature.getFeatureAccessorName());
stringBuffer.append(TEXT_181);
}
stringBuffer.append(TEXT_7);
}
if (genModel.isOperationReflection()) {
for (GenOperation genOperation : genClass.getGenOperations()) {
if (isInterface) {
stringBuffer.append(TEXT_182);
stringBuffer.append(genClass.getRawQualifiedInterfaceName());
stringBuffer.append(TEXT_171);
stringBuffer.append(genOperation.getName());
stringBuffer.append(TEXT_183);
stringBuffer.append(genOperation.getParameterTypes(", "));
stringBuffer.append(TEXT_184);
stringBuffer.append(genOperation.getFormattedName());
stringBuffer.append(TEXT_185);
stringBuffer.append(genOperation.getFormattedName());
stringBuffer.append(TEXT_186);
stringBuffer.append(genClass.getRawQualifiedInterfaceName());
stringBuffer.append(TEXT_171);
stringBuffer.append(genOperation.getName());
stringBuffer.append(TEXT_183);
stringBuffer.append(genOperation.getParameterTypes(", "));
stringBuffer.append(TEXT_79);
if (genOperation.hasImplicitAPITags()) {
stringBuffer.append(TEXT_50);
stringBuffer.append(genOperation.getImplicitAPITags(genModel.getIndentation(stringBuffer)));
}
stringBuffer.append(TEXT_51);
} else {
stringBuffer.append(TEXT_67);
if (genOperation.hasImplicitAPITags()) {
stringBuffer.append(TEXT_50);
stringBuffer.append(genOperation.getImplicitAPITags(genModel.getIndentation(stringBuffer)));
}
stringBuffer.append(TEXT_51);
}
if (isJDK50 && genOperation.hasImplicitAPIDeprecatedTag()) {
stringBuffer.append(TEXT_52);
}
if (isImplementation) {
if (useInterfaceOverrideAnnotation) {
stringBuffer.append(TEXT_158);
}
stringBuffer.append(TEXT_159);
stringBuffer.append(genOperation.getImportedMetaType());
stringBuffer.append(TEXT_160);
stringBuffer.append(genOperation.getOperationAccessorName());
stringBuffer.append(TEXT_161);
if (!genPackage.isLoadedInitialization()) {
stringBuffer.append(TEXT_166);
stringBuffer.append(genClass.getClassifierInstanceName());
stringBuffer.append(TEXT_187);
stringBuffer.append(genClass.getLocalOperationIndex(genOperation));
stringBuffer.append(TEXT_177);
} else {
stringBuffer.append(TEXT_188);
stringBuffer.append(genClassifier.getClassifierAccessorName());
stringBuffer.append(TEXT_189);
stringBuffer.append(genClass.getLocalOperationIndex(genOperation));
stringBuffer.append(TEXT_177);
}
stringBuffer.append(TEXT_141);
} else {
stringBuffer.append(TEXT_53);
stringBuffer.append(genOperation.getImportedMetaType());
stringBuffer.append(TEXT_160);
stringBuffer.append(genOperation.getOperationAccessorName());
stringBuffer.append(TEXT_181);
}
stringBuffer.append(TEXT_7);
}
}
}
}
if (isInterface) {
stringBuffer.append(TEXT_190);
} else {
stringBuffer.append(TEXT_191);
}
if (isImplementation) {
if (useInterfaceOverrideAnnotation) {
stringBuffer.append(TEXT_158);
}
stringBuffer.append(TEXT_159);
stringBuffer.append(genPackage.getImportedFactoryInterfaceName());
stringBuffer.append(TEXT_160);
stringBuffer.append(genPackage.getFactoryName());
stringBuffer.append(TEXT_192);
stringBuffer.append(genPackage.getImportedFactoryInterfaceName());
stringBuffer.append(TEXT_193);
} else {
stringBuffer.append(TEXT_53);
stringBuffer.append(genPackage.getFactoryInterfaceName());
stringBuffer.append(TEXT_160);
stringBuffer.append(genPackage.getFactoryName());
stringBuffer.append(TEXT_181);
}
stringBuffer.append(TEXT_7);
if (isImplementation) {
if (!genPackage.isLoadedInitialization()) {
stringBuffer.append(TEXT_194);
{boolean needsSuppressDeprecation = false; if (!packageNeedsSuppressDeprecation && isJDK50) { LOOP: for (GenClass genClass : genPackage.getGenClasses()) { for (GenFeature genFeature : genClass.getGenFeatures()) { if (genFeature.hasAPIDeprecatedTag()) { needsSuppressDeprecation = true; break LOOP; }}
for (GenOperation genOperation : genClass.getGenOperations()) { if (genOperation.hasAPIDeprecatedTag()) { needsSuppressDeprecation = true; break LOOP; }}} if (needsSuppressDeprecation) {
stringBuffer.append(TEXT_195);
}}}
stringBuffer.append(TEXT_196);
if (!genPackage.getGenClasses().isEmpty()) {
stringBuffer.append(TEXT_197);
for (Iterator<GenClass> c=genPackage.getGenClasses().iterator(); c.hasNext();) { GenClass genClass = c.next();
stringBuffer.append(TEXT_93);
stringBuffer.append(genClass.getClassifierInstanceName());
stringBuffer.append(TEXT_198);
stringBuffer.append(genClass.getMetaType());
stringBuffer.append(TEXT_183);
stringBuffer.append(genClass.getClassifierID());
stringBuffer.append(TEXT_177);
for (GenFeature genFeature : genClass.getGenFeatures()) {
stringBuffer.append(TEXT_199);
stringBuffer.append(genFeature.getMetaType());
stringBuffer.append(TEXT_183);
stringBuffer.append(genClass.getClassifierInstanceName());
stringBuffer.append(TEXT_200);
stringBuffer.append(genClass.getFeatureID(genFeature));
stringBuffer.append(TEXT_177);
}
if (genModel.isOperationReflection()) {
for (GenOperation genOperation : genClass.getGenOperations()) {
stringBuffer.append(TEXT_201);
stringBuffer.append(genClass.getClassifierInstanceName());
stringBuffer.append(TEXT_200);
stringBuffer.append(genClass.getOperationID(genOperation, false));
stringBuffer.append(TEXT_177);
}
}
if (c.hasNext()) {
stringBuffer.append(TEXT_7);
}
}
}
if (!genPackage.getGenEnums().isEmpty()) {
stringBuffer.append(TEXT_202);
for (GenEnum genEnum : genPackage.getGenEnums()) {
stringBuffer.append(TEXT_93);
stringBuffer.append(genEnum.getClassifierInstanceName());
stringBuffer.append(TEXT_203);
stringBuffer.append(genEnum.getClassifierID());
stringBuffer.append(TEXT_177);
}
}
if (!genPackage.getGenDataTypes().isEmpty()) {
stringBuffer.append(TEXT_204);
for (GenDataType genDataType : genPackage.getGenDataTypes()) {
stringBuffer.append(TEXT_93);
stringBuffer.append(genDataType.getClassifierInstanceName());
stringBuffer.append(TEXT_205);
stringBuffer.append(genDataType.getClassifierID());
stringBuffer.append(TEXT_177);
}
}
stringBuffer.append(TEXT_206);
///////////////////////
class Information
{
@SuppressWarnings("unused")
EGenericType eGenericType;
int depth;
String type;
String accessor;
}
class InformationIterator
{
Iterator<Object> iterator;
InformationIterator(EGenericType eGenericType)
{
iterator = EcoreUtil.getAllContents(Collections.singleton(eGenericType));
}
boolean hasNext()
{
return iterator.hasNext();
}
Information next()
{
Information information = new Information();
EGenericType eGenericType = information.eGenericType = (EGenericType)iterator.next();
for (EObject container = eGenericType.eContainer(); container instanceof EGenericType; container = container.eContainer())
{
++information.depth;
}
if (eGenericType.getEClassifier() != null )
{
GenClassifier genClassifier = genModel.findGenClassifier(eGenericType.getEClassifier());
information.type = genPackage.getPackageInstanceVariable(genClassifier.getGenPackage()) + ".get" + genClassifier.getClassifierAccessorName() + "()";
}
else if (eGenericType.getETypeParameter() != null)
{
ETypeParameter eTypeParameter = eGenericType.getETypeParameter();
if (eTypeParameter.eContainer() instanceof EClass)
{
information.type = genModel.findGenClassifier((EClass)eTypeParameter.eContainer()).getClassifierInstanceName() + "_" + eGenericType.getETypeParameter().getName();
}
else
{
information.type = "t" + (((EOperation)eTypeParameter.eContainer()).getETypeParameters().indexOf(eTypeParameter) + 1);
}
}
else
{
information.type ="";
}
if (information.depth > 0)
{
if (eGenericType.eContainmentFeature().isMany())
{
information.accessor = "getE" + eGenericType.eContainmentFeature().getName().substring(1) + "().add";
}
else
{
information.accessor = "setE" + eGenericType.eContainmentFeature().getName().substring(1);
}
}
return information;
}
}
///////////////////////
int maxGenericTypeAssignment = 0;
stringBuffer.append(TEXT_207);
{boolean needsSuppressDeprecation = false; if (!packageNeedsSuppressDeprecation && isJDK50) { LOOP: for (GenEnum genEnum : genPackage.getGenEnums()) { for (GenEnumLiteral genEnumLiteral : genEnum.getGenEnumLiterals()) { if (genEnumLiteral.hasAPIDeprecatedTag()) { needsSuppressDeprecation = true; break LOOP; }}} if (needsSuppressDeprecation) {
stringBuffer.append(TEXT_195);
}}}
stringBuffer.append(TEXT_208);
if (!genPackage.getPackageInitializationDependencies().isEmpty()) {
stringBuffer.append(TEXT_209);
for (GenPackage dep : genPackage.getPackageInitializationDependencies()) {
stringBuffer.append(TEXT_93);
stringBuffer.append(dep.getImportedPackageInterfaceName());
stringBuffer.append(TEXT_69);
stringBuffer.append(genPackage.getPackageInstanceVariable(dep));
stringBuffer.append(TEXT_99);
stringBuffer.append(dep.getImportedPackageInterfaceName());
stringBuffer.append(TEXT_79);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage"));
stringBuffer.append(TEXT_80);
stringBuffer.append(dep.getImportedPackageInterfaceName());
stringBuffer.append(TEXT_210);
}
}
if (!genPackage.getSubGenPackages().isEmpty()) {
stringBuffer.append(TEXT_211);
for (GenPackage sub : genPackage.getSubGenPackages()) {
stringBuffer.append(TEXT_212);
stringBuffer.append(genPackage.getPackageInstanceVariable(sub));
stringBuffer.append(TEXT_177);
}
}
if (!genPackage.getGenClasses().isEmpty()) { boolean firstOperationAssignment = true; int maxTypeParameterAssignment = 0;
if (genModel.useGenerics()) {
stringBuffer.append(TEXT_213);
for (GenClassifier genClassifier : genPackage.getGenClassifiers()) {
for (GenTypeParameter genTypeParameter : genClassifier.getGenTypeParameters()) {
if (!genTypeParameter.getEcoreTypeParameter().getEBounds().isEmpty() || genTypeParameter.isUsed()) {
stringBuffer.append(TEXT_93);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.ETypeParameter"));
stringBuffer.append(TEXT_69);
stringBuffer.append(genClassifier.getClassifierInstanceName());
stringBuffer.append(TEXT_214);
stringBuffer.append(genTypeParameter.getName());
stringBuffer.append(TEXT_215);
stringBuffer.append(genClassifier.getClassifierInstanceName());
stringBuffer.append(TEXT_216);
stringBuffer.append(genTypeParameter.getName());
stringBuffer.append(TEXT_217);
stringBuffer.append(genModel.getNonNLS());
} else {
stringBuffer.append(TEXT_218);
stringBuffer.append(genClassifier.getClassifierInstanceName());
stringBuffer.append(TEXT_216);
stringBuffer.append(genTypeParameter.getName());
stringBuffer.append(TEXT_217);
stringBuffer.append(genModel.getNonNLS());
}
}
}
}
if (genModel.useGenerics()) {
stringBuffer.append(TEXT_219);
for (GenClassifier genClassifier : genPackage.getGenClassifiers()) {
for (GenTypeParameter genTypeParameter : genClassifier.getGenTypeParameters()) {
for (EGenericType bound : genTypeParameter.getEcoreTypeParameter().getEBounds()) {
for (InformationIterator i=new InformationIterator(bound); i.hasNext(); ) { Information info = i.next(); String prefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; prefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; }
stringBuffer.append(TEXT_93);
stringBuffer.append(prefix);
stringBuffer.append(TEXT_220);
stringBuffer.append(info.depth + 1);
stringBuffer.append(TEXT_221);
stringBuffer.append(info.type);
stringBuffer.append(TEXT_177);
if (info.depth > 0) {
stringBuffer.append(TEXT_222);
stringBuffer.append(info.depth);
stringBuffer.append(TEXT_223);
stringBuffer.append(info.accessor);
stringBuffer.append(TEXT_224);
stringBuffer.append(info.depth + 1);
stringBuffer.append(TEXT_177);
}
}
stringBuffer.append(TEXT_93);
stringBuffer.append(genClassifier.getClassifierInstanceName());
stringBuffer.append(TEXT_214);
stringBuffer.append(genTypeParameter.getName());
stringBuffer.append(TEXT_225);
}
}
}
}
stringBuffer.append(TEXT_226);
for (GenClass genClass : genPackage.getGenClasses()) {
if (!genClass.hasGenericSuperTypes()) {
for (GenClass baseGenClass : genClass.getBaseGenClasses()) {
stringBuffer.append(TEXT_93);
stringBuffer.append(genClass.getClassifierInstanceName());
stringBuffer.append(TEXT_227);
stringBuffer.append(genPackage.getPackageInstanceVariable(baseGenClass.getGenPackage()));
stringBuffer.append(TEXT_228);
stringBuffer.append(baseGenClass.getClassifierAccessorName());
stringBuffer.append(TEXT_229);
}
} else {
for (EGenericType superType : genClass.getEcoreClass().getEGenericSuperTypes()) {
for (InformationIterator i=new InformationIterator(superType); i.hasNext(); ) { Information info = i.next(); String prefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; prefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; }
stringBuffer.append(TEXT_93);
stringBuffer.append(prefix);
stringBuffer.append(TEXT_220);
stringBuffer.append(info.depth + 1);
stringBuffer.append(TEXT_221);
stringBuffer.append(info.type);
stringBuffer.append(TEXT_177);
if (info.depth > 0) {
stringBuffer.append(TEXT_222);
stringBuffer.append(info.depth);
stringBuffer.append(TEXT_223);
stringBuffer.append(info.accessor);
stringBuffer.append(TEXT_224);
stringBuffer.append(info.depth + 1);
stringBuffer.append(TEXT_177);
}
}
stringBuffer.append(TEXT_93);
stringBuffer.append(genClass.getClassifierInstanceName());
stringBuffer.append(TEXT_230);
}
}
}
stringBuffer.append(TEXT_231);
if (genModel.isOperationReflection()) {
stringBuffer.append(TEXT_232);
} else {
stringBuffer.append(TEXT_233);
}
for (Iterator<GenClass> c=genPackage.getGenClasses().iterator(); c.hasNext();) { GenClass genClass = c.next(); boolean hasInstanceTypeName = genModel.useGenerics() && genClass.getEcoreClass().getInstanceTypeName() != null && genClass.getEcoreClass().getInstanceTypeName().contains("<");
stringBuffer.append(TEXT_234);
stringBuffer.append(genClass.getClassifierInstanceName());
stringBuffer.append(TEXT_200);
if (genClass.isDynamic()) {
stringBuffer.append(TEXT_235);
} else {
stringBuffer.append(genClass.getRawImportedInterfaceName());
stringBuffer.append(TEXT_236);
}
stringBuffer.append(TEXT_216);
stringBuffer.append(genClass.getName());
stringBuffer.append(TEXT_237);
stringBuffer.append(genClass.getAbstractFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genClass.getInterfaceFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genClass.getGeneratedInstanceClassFlag());
if (hasInstanceTypeName) {
stringBuffer.append(TEXT_216);
stringBuffer.append(genClass.getEcoreClass().getInstanceTypeName());
stringBuffer.append(TEXT_238);
}
stringBuffer.append(TEXT_177);
stringBuffer.append(genModel.getNonNLS());
if (hasInstanceTypeName) {
stringBuffer.append(genModel.getNonNLS(2));
}
for (GenFeature genFeature : genClass.getGenFeatures()) {
if (genFeature.hasGenericType()) {
for (InformationIterator i=new InformationIterator(genFeature.getEcoreFeature().getEGenericType()); i.hasNext(); ) { Information info = i.next(); String prefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; prefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; }
stringBuffer.append(TEXT_93);
stringBuffer.append(prefix);
stringBuffer.append(TEXT_220);
stringBuffer.append(info.depth + 1);
stringBuffer.append(TEXT_221);
stringBuffer.append(info.type);
stringBuffer.append(TEXT_177);
if (info.depth > 0) {
stringBuffer.append(TEXT_222);
stringBuffer.append(info.depth);
stringBuffer.append(TEXT_223);
stringBuffer.append(info.accessor);
stringBuffer.append(TEXT_224);
stringBuffer.append(info.depth + 1);
stringBuffer.append(TEXT_177);
}
}
}
if (genFeature.isReferenceType()) { GenFeature reverseGenFeature = genFeature.getReverse();
String reverse = reverseGenFeature == null ? "null" : genPackage.getPackageInstanceVariable(reverseGenFeature.getGenPackage()) + ".get" + reverseGenFeature.getFeatureAccessorName() + "()";
stringBuffer.append(TEXT_239);
stringBuffer.append(genFeature.getFeatureAccessorName());
stringBuffer.append(TEXT_240);
if (genFeature.hasGenericType()) {
stringBuffer.append(TEXT_241);
} else {
stringBuffer.append(genPackage.getPackageInstanceVariable(genFeature.getTypeGenPackage()));
stringBuffer.append(TEXT_228);
stringBuffer.append(genFeature.getTypeClassifierAccessorName());
stringBuffer.append(TEXT_49);
}
stringBuffer.append(TEXT_200);
stringBuffer.append(reverse);
stringBuffer.append(TEXT_216);
stringBuffer.append(genFeature.getName());
stringBuffer.append(TEXT_237);
stringBuffer.append(genFeature.getDefaultValue());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getLowerBound());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getUpperBound());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getContainerClass());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getTransientFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getVolatileFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getChangeableFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getContainmentFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getResolveProxiesFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getUnsettableFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getUniqueFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getDerivedFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getOrderedFlag());
stringBuffer.append(TEXT_177);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(genModel.getNonNLS(genFeature.getDefaultValue(), 2));
for (GenFeature keyFeature : genFeature.getKeys()) {
stringBuffer.append(TEXT_242);
stringBuffer.append(genFeature.getFeatureAccessorName());
stringBuffer.append(TEXT_243);
stringBuffer.append(genPackage.getPackageInstanceVariable(keyFeature.getGenPackage()));
stringBuffer.append(TEXT_228);
stringBuffer.append(keyFeature.getFeatureAccessorName());
stringBuffer.append(TEXT_229);
}
} else {
stringBuffer.append(TEXT_244);
stringBuffer.append(genFeature.getFeatureAccessorName());
stringBuffer.append(TEXT_240);
if (genFeature.hasGenericType()) {
stringBuffer.append(TEXT_241);
} else {
stringBuffer.append(genPackage.getPackageInstanceVariable(genFeature.getTypeGenPackage()));
stringBuffer.append(TEXT_228);
stringBuffer.append(genFeature.getTypeClassifierAccessorName());
stringBuffer.append(TEXT_49);
}
stringBuffer.append(TEXT_216);
stringBuffer.append(genFeature.getName());
stringBuffer.append(TEXT_237);
stringBuffer.append(genFeature.getDefaultValue());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getLowerBound());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getUpperBound());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getContainerClass());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getTransientFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getVolatileFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getChangeableFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getUnsettableFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getIDFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getUniqueFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getDerivedFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genFeature.getOrderedFlag());
stringBuffer.append(TEXT_177);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(genModel.getNonNLS(genFeature.getDefaultValue(), 2));
}
}
for (GenOperation genOperation : genClass.getGenOperations()) {String prefix = ""; if (genOperation.hasGenericType() || !genOperation.getGenParameters().isEmpty() || !genOperation.getGenExceptions().isEmpty() || !genOperation.getGenTypeParameters().isEmpty()) { if (firstOperationAssignment) { firstOperationAssignment = false; prefix = genModel.getImportedName("org.eclipse.emf.ecore.EOperation") + " op = "; } else { prefix = "op = "; }}
stringBuffer.append(TEXT_7);
if (genModel.useGenerics()) {
stringBuffer.append(TEXT_93);
stringBuffer.append(prefix);
if (genModel.isOperationReflection()) {
stringBuffer.append(TEXT_245);
stringBuffer.append(genOperation.getOperationAccessorName());
stringBuffer.append(TEXT_49);
} else {
stringBuffer.append(TEXT_246);
stringBuffer.append(genClass.getClassifierInstanceName());
}
stringBuffer.append(TEXT_200);
if (genOperation.isVoid() || genOperation.hasGenericType()) {
stringBuffer.append(TEXT_235);
} else {
stringBuffer.append(genPackage.getPackageInstanceVariable(genOperation.getTypeGenPackage()));
stringBuffer.append(TEXT_228);
stringBuffer.append(genOperation.getTypeClassifierAccessorName());
stringBuffer.append(TEXT_49);
}
stringBuffer.append(TEXT_216);
stringBuffer.append(genOperation.getName());
stringBuffer.append(TEXT_237);
stringBuffer.append(genOperation.getLowerBound());
stringBuffer.append(TEXT_200);
stringBuffer.append(genOperation.getUpperBound());
stringBuffer.append(TEXT_200);
stringBuffer.append(genOperation.getUniqueFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genOperation.getOrderedFlag());
stringBuffer.append(TEXT_177);
stringBuffer.append(genModel.getNonNLS());
} else if (!genOperation.isVoid()) {
if (!genOperation.getEcoreOperation().isOrdered() || !genOperation.getEcoreOperation().isUnique()) { needsAddEOperation = true;
stringBuffer.append(TEXT_93);
stringBuffer.append(prefix);
if (genModel.isOperationReflection()) {
stringBuffer.append(TEXT_245);
stringBuffer.append(genOperation.getOperationAccessorName());
stringBuffer.append(TEXT_49);
} else {
stringBuffer.append(TEXT_246);
stringBuffer.append(genClass.getClassifierInstanceName());
}
stringBuffer.append(TEXT_200);
stringBuffer.append(genPackage.getPackageInstanceVariable(genOperation.getTypeGenPackage()));
stringBuffer.append(TEXT_228);
stringBuffer.append(genOperation.getTypeClassifierAccessorName());
stringBuffer.append(TEXT_247);
stringBuffer.append(genOperation.getName());
stringBuffer.append(TEXT_237);
stringBuffer.append(genOperation.getLowerBound());
stringBuffer.append(TEXT_200);
stringBuffer.append(genOperation.getUpperBound());
stringBuffer.append(TEXT_200);
stringBuffer.append(genOperation.getUniqueFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genOperation.getOrderedFlag());
stringBuffer.append(TEXT_177);
stringBuffer.append(genModel.getNonNLS());
} else {
stringBuffer.append(TEXT_93);
stringBuffer.append(prefix);
if (genModel.isOperationReflection()) {
stringBuffer.append(TEXT_245);
stringBuffer.append(genOperation.getOperationAccessorName());
stringBuffer.append(TEXT_49);
} else {
stringBuffer.append(TEXT_246);
stringBuffer.append(genClass.getClassifierInstanceName());
}
stringBuffer.append(TEXT_200);
stringBuffer.append(genPackage.getPackageInstanceVariable(genOperation.getTypeGenPackage()));
stringBuffer.append(TEXT_228);
stringBuffer.append(genOperation.getTypeClassifierAccessorName());
stringBuffer.append(TEXT_247);
stringBuffer.append(genOperation.getName());
stringBuffer.append(TEXT_237);
stringBuffer.append(genOperation.getLowerBound());
stringBuffer.append(TEXT_200);
stringBuffer.append(genOperation.getUpperBound());
stringBuffer.append(TEXT_177);
stringBuffer.append(genModel.getNonNLS());
}
} else {
stringBuffer.append(TEXT_93);
stringBuffer.append(prefix);
if (genModel.isOperationReflection()) {
stringBuffer.append(TEXT_245);
stringBuffer.append(genOperation.getOperationAccessorName());
stringBuffer.append(TEXT_49);
} else {
stringBuffer.append(TEXT_246);
stringBuffer.append(genClass.getClassifierInstanceName());
}
stringBuffer.append(TEXT_248);
stringBuffer.append(genOperation.getName());
stringBuffer.append(TEXT_217);
stringBuffer.append(genModel.getNonNLS());
}
if (genModel.useGenerics()) {
for (ListIterator<GenTypeParameter> t=genOperation.getGenTypeParameters().listIterator(); t.hasNext(); ) { GenTypeParameter genTypeParameter = t.next(); String typeParameterVariable = ""; if (!genTypeParameter.getEcoreTypeParameter().getEBounds().isEmpty() || genTypeParameter.isUsed()) { if (maxTypeParameterAssignment <= t.previousIndex()) { ++maxTypeParameterAssignment; typeParameterVariable = genModel.getImportedName("org.eclipse.emf.ecore.ETypeParameter") + " t" + t.nextIndex() + " = "; } else { typeParameterVariable = "t" + t.nextIndex() + " = "; }}
stringBuffer.append(TEXT_93);
stringBuffer.append(typeParameterVariable);
stringBuffer.append(TEXT_249);
stringBuffer.append(genTypeParameter.getName());
stringBuffer.append(TEXT_217);
stringBuffer.append(genModel.getNonNLS());
for (EGenericType typeParameter : genTypeParameter.getEcoreTypeParameter().getEBounds()) {
for (InformationIterator i=new InformationIterator(typeParameter); i.hasNext(); ) { Information info = i.next(); String typePrefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; typePrefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; }
stringBuffer.append(TEXT_93);
stringBuffer.append(typePrefix);
stringBuffer.append(TEXT_220);
stringBuffer.append(info.depth + 1);
stringBuffer.append(TEXT_221);
stringBuffer.append(info.type);
stringBuffer.append(TEXT_177);
if (info.depth > 0) {
stringBuffer.append(TEXT_222);
stringBuffer.append(info.depth);
stringBuffer.append(TEXT_223);
stringBuffer.append(info.accessor);
stringBuffer.append(TEXT_224);
stringBuffer.append(info.depth + 1);
stringBuffer.append(TEXT_177);
}
}
stringBuffer.append(TEXT_250);
stringBuffer.append(t.nextIndex());
stringBuffer.append(TEXT_225);
}
}
}
for (GenParameter genParameter : genOperation.getGenParameters()) {
if (genParameter.hasGenericType()) {
for (InformationIterator i=new InformationIterator(genParameter.getEcoreParameter().getEGenericType()); i.hasNext(); ) { Information info = i.next(); String typePrefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; typePrefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; }
stringBuffer.append(TEXT_93);
stringBuffer.append(typePrefix);
stringBuffer.append(TEXT_220);
stringBuffer.append(info.depth + 1);
stringBuffer.append(TEXT_221);
stringBuffer.append(info.type);
stringBuffer.append(TEXT_177);
if (info.depth > 0) {
stringBuffer.append(TEXT_222);
stringBuffer.append(info.depth);
stringBuffer.append(TEXT_223);
stringBuffer.append(info.accessor);
stringBuffer.append(TEXT_224);
stringBuffer.append(info.depth + 1);
stringBuffer.append(TEXT_177);
}
}
}
if (genModel.useGenerics()) {
stringBuffer.append(TEXT_251);
if (genParameter.hasGenericType()){
stringBuffer.append(TEXT_241);
} else {
stringBuffer.append(genPackage.getPackageInstanceVariable(genParameter.getTypeGenPackage()));
stringBuffer.append(TEXT_228);
stringBuffer.append(genParameter.getTypeClassifierAccessorName());
stringBuffer.append(TEXT_49);
}
stringBuffer.append(TEXT_216);
stringBuffer.append(genParameter.getName());
stringBuffer.append(TEXT_237);
stringBuffer.append(genParameter.getLowerBound());
stringBuffer.append(TEXT_200);
stringBuffer.append(genParameter.getUpperBound());
stringBuffer.append(TEXT_200);
stringBuffer.append(genParameter.getUniqueFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genParameter.getOrderedFlag());
stringBuffer.append(TEXT_177);
stringBuffer.append(genModel.getNonNLS());
} else if (!genParameter.getEcoreParameter().isOrdered() || !genParameter.getEcoreParameter().isUnique()) { needsAddEParameter = true;
stringBuffer.append(TEXT_251);
if (genParameter.hasGenericType()){
stringBuffer.append(TEXT_241);
} else {
stringBuffer.append(genPackage.getPackageInstanceVariable(genParameter.getTypeGenPackage()));
stringBuffer.append(TEXT_228);
stringBuffer.append(genParameter.getTypeClassifierAccessorName());
stringBuffer.append(TEXT_49);
}
stringBuffer.append(TEXT_216);
stringBuffer.append(genParameter.getName());
stringBuffer.append(TEXT_237);
stringBuffer.append(genParameter.getLowerBound());
stringBuffer.append(TEXT_200);
stringBuffer.append(genParameter.getUpperBound());
stringBuffer.append(TEXT_200);
stringBuffer.append(genParameter.getUniqueFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genParameter.getOrderedFlag());
stringBuffer.append(TEXT_177);
stringBuffer.append(genModel.getNonNLS());
} else {
stringBuffer.append(TEXT_251);
if (genParameter.hasGenericType()){
stringBuffer.append(TEXT_241);
} else {
stringBuffer.append(genPackage.getPackageInstanceVariable(genParameter.getTypeGenPackage()));
stringBuffer.append(TEXT_228);
stringBuffer.append(genParameter.getTypeClassifierAccessorName());
stringBuffer.append(TEXT_49);
}
stringBuffer.append(TEXT_216);
stringBuffer.append(genParameter.getName());
stringBuffer.append(TEXT_237);
stringBuffer.append(genParameter.getLowerBound());
stringBuffer.append(TEXT_200);
stringBuffer.append(genParameter.getUpperBound());
stringBuffer.append(TEXT_177);
stringBuffer.append(genModel.getNonNLS());
}
}
if (genOperation.hasGenericExceptions()) {
for (EGenericType genericExceptions : genOperation.getEcoreOperation().getEGenericExceptions()) {
for (InformationIterator i=new InformationIterator(genericExceptions); i.hasNext(); ) { Information info = i.next(); String typePrefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; typePrefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; }
stringBuffer.append(TEXT_93);
stringBuffer.append(typePrefix);
stringBuffer.append(TEXT_220);
stringBuffer.append(info.depth + 1);
stringBuffer.append(TEXT_221);
stringBuffer.append(info.type);
stringBuffer.append(TEXT_177);
if (info.depth > 0) {
stringBuffer.append(TEXT_222);
stringBuffer.append(info.depth);
stringBuffer.append(TEXT_223);
stringBuffer.append(info.accessor);
stringBuffer.append(TEXT_224);
stringBuffer.append(info.depth + 1);
stringBuffer.append(TEXT_177);
}
stringBuffer.append(TEXT_252);
stringBuffer.append(info.depth + 1);
stringBuffer.append(TEXT_177);
}
}
} else {
for (GenClassifier genException : genOperation.getGenExceptions()) {
stringBuffer.append(TEXT_253);
stringBuffer.append(genPackage.getPackageInstanceVariable(genException.getGenPackage()));
stringBuffer.append(TEXT_228);
stringBuffer.append(genException.getClassifierAccessorName());
stringBuffer.append(TEXT_229);
}
}
if (!genOperation.isVoid() && genOperation.hasGenericType()) {
for (InformationIterator i=new InformationIterator(genOperation.getEcoreOperation().getEGenericType()); i.hasNext(); ) { Information info = i.next(); String typePrefix = ""; if (maxGenericTypeAssignment <= info.depth) { ++maxGenericTypeAssignment; typePrefix = genModel.getImportedName("org.eclipse.emf.ecore.EGenericType") + " "; }
stringBuffer.append(TEXT_93);
stringBuffer.append(typePrefix);
stringBuffer.append(TEXT_220);
stringBuffer.append(info.depth + 1);
stringBuffer.append(TEXT_221);
stringBuffer.append(info.type);
stringBuffer.append(TEXT_177);
if (info.depth > 0) {
stringBuffer.append(TEXT_222);
stringBuffer.append(info.depth);
stringBuffer.append(TEXT_223);
stringBuffer.append(info.accessor);
stringBuffer.append(TEXT_224);
stringBuffer.append(info.depth + 1);
stringBuffer.append(TEXT_177);
}
}
stringBuffer.append(TEXT_254);
}
}
if (c.hasNext()) {
stringBuffer.append(TEXT_7);
}
}
}
if (!genPackage.getGenEnums().isEmpty()) {
stringBuffer.append(TEXT_255);
for (Iterator<GenEnum> e=genPackage.getGenEnums().iterator(); e.hasNext();) { GenEnum genEnum = e.next();
stringBuffer.append(TEXT_256);
stringBuffer.append(genEnum.getClassifierInstanceName());
stringBuffer.append(TEXT_200);
stringBuffer.append(genEnum.getImportedName());
stringBuffer.append(TEXT_257);
stringBuffer.append(genEnum.getName());
stringBuffer.append(TEXT_217);
stringBuffer.append(genModel.getNonNLS());
for (GenEnumLiteral genEnumLiteral : genEnum.getGenEnumLiterals()) {
stringBuffer.append(TEXT_258);
stringBuffer.append(genEnum.getClassifierInstanceName());
stringBuffer.append(TEXT_200);
stringBuffer.append(genEnum.getImportedName().equals(genEnum.getClassifierID()) ? genEnum.getQualifiedName() : genEnum.getImportedName());
stringBuffer.append(TEXT_223);
stringBuffer.append(genEnumLiteral.getEnumLiteralInstanceConstantName());
stringBuffer.append(TEXT_177);
}
if (e.hasNext()) {
stringBuffer.append(TEXT_7);
}
}
}
if (!genPackage.getGenDataTypes().isEmpty()) {
stringBuffer.append(TEXT_259);
for (GenDataType genDataType : genPackage.getGenDataTypes()) {boolean hasInstanceTypeName = genModel.useGenerics() && genDataType.getEcoreDataType().getInstanceTypeName() != null && genDataType.getEcoreDataType().getInstanceTypeName().contains("<");
stringBuffer.append(TEXT_260);
stringBuffer.append(genDataType.getClassifierInstanceName());
stringBuffer.append(TEXT_200);
stringBuffer.append(genDataType.getRawImportedInstanceClassName());
stringBuffer.append(TEXT_257);
stringBuffer.append(genDataType.getName());
stringBuffer.append(TEXT_237);
stringBuffer.append(genDataType.getSerializableFlag());
stringBuffer.append(TEXT_200);
stringBuffer.append(genDataType.getGeneratedInstanceClassFlag());
if (hasInstanceTypeName) {
stringBuffer.append(TEXT_216);
stringBuffer.append(genDataType.getEcoreDataType().getInstanceTypeName());
stringBuffer.append(TEXT_238);
}
stringBuffer.append(TEXT_177);
stringBuffer.append(genModel.getNonNLS());
if (hasInstanceTypeName) {
stringBuffer.append(genModel.getNonNLS(2));
}
}
}
if (genPackage.getSuperGenPackage() == null) {
stringBuffer.append(TEXT_261);
stringBuffer.append(genPackage.getSchemaLocation());
stringBuffer.append(TEXT_177);
}
if (!genPackage.isEcorePackage() && !genPackage.getAnnotationSources().isEmpty()) {
stringBuffer.append(TEXT_262);
for (String annotationSource : genPackage.getAnnotationSources()) {
stringBuffer.append(TEXT_263);
stringBuffer.append(annotationSource);
stringBuffer.append(TEXT_199);
stringBuffer.append(genPackage.getAnnotationSourceIdentifier(annotationSource));
stringBuffer.append(TEXT_264);
}
}
stringBuffer.append(TEXT_265);
for (String annotationSource : genPackage.getAnnotationSources()) {
stringBuffer.append(TEXT_266);
stringBuffer.append(annotationSource);
stringBuffer.append(TEXT_267);
stringBuffer.append(genPackage.getAnnotationSourceIdentifier(annotationSource));
stringBuffer.append(TEXT_268);
if (annotationSource == null) {
stringBuffer.append(TEXT_269);
} else {
stringBuffer.append(TEXT_238);
stringBuffer.append(annotationSource);
stringBuffer.append(TEXT_30);
stringBuffer.append(genModel.getNonNLS());
}
for (EAnnotation eAnnotation : genPackage.getAllAnnotations()) { List<GenPackage.AnnotationReferenceData> annotationReferenceDataList = genPackage.getReferenceData(eAnnotation);
if (annotationSource == null ? eAnnotation.getSource() == null : annotationSource.equals(eAnnotation.getSource())) {
stringBuffer.append(TEXT_270);
stringBuffer.append(genPackage.getAnnotatedModelElementAccessor(eAnnotation));
stringBuffer.append(TEXT_271);
for (Iterator<Map.Entry<String, String>> k = eAnnotation.getDetails().iterator(); k.hasNext();) { Map.Entry<String, String> detail = k.next(); String key = Literals.toStringLiteral(detail.getKey(), genModel); String value = Literals.toStringLiteral(detail.getValue(), genModel);
stringBuffer.append(TEXT_272);
stringBuffer.append(key);
stringBuffer.append(TEXT_200);
stringBuffer.append(value);
stringBuffer.append(k.hasNext() ? "," : "");
stringBuffer.append(genModel.getNonNLS(key + value));
}
stringBuffer.append(TEXT_273);
if (annotationReferenceDataList.isEmpty()) {
stringBuffer.append(TEXT_177);
} else {
stringBuffer.append(TEXT_274);
}
if (!annotationReferenceDataList.isEmpty()) {
stringBuffer.append(TEXT_275);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.common.util.URI"));
stringBuffer.append(TEXT_276);
for (Iterator<GenPackage.AnnotationReferenceData> k = annotationReferenceDataList.iterator(); k.hasNext();) { GenPackage.AnnotationReferenceData annotationReferenceData = k.next();
stringBuffer.append(TEXT_277);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.common.util.URI"));
stringBuffer.append(TEXT_278);
if (annotationReferenceData.containingGenPackage != genPackage) {
stringBuffer.append(annotationReferenceData.containingGenPackage.getImportedPackageInterfaceName());
stringBuffer.append(TEXT_223);
}
stringBuffer.append(TEXT_279);
stringBuffer.append(annotationReferenceData.uriFragment);
stringBuffer.append(TEXT_280);
if (k.hasNext()) {
stringBuffer.append(TEXT_274);
}
stringBuffer.append(genModel.getNonNLS());
}
stringBuffer.append(TEXT_281);
}
for (EAnnotation nestedEAnnotation : genPackage.getAllNestedAnnotations(eAnnotation)) {String nestedAnnotationSource = nestedEAnnotation.getSource(); int depth = 0; boolean nonContentAnnotation = false; StringBuilder path = new StringBuilder(); for (EObject eContainer = nestedEAnnotation.eContainer(), child = nestedEAnnotation; child != eAnnotation; child = eContainer, eContainer = eContainer.eContainer()) { boolean nonContentChild = child.eContainmentFeature() != EcorePackage.Literals.EANNOTATION__CONTENTS; if (path.length() != 0) { path.insert(0, ", "); } path.insert(0, nonContentChild); if (nonContentChild) { nonContentAnnotation = true; } ++depth; } List<GenPackage.AnnotationReferenceData> nestedAnnotationReferenceDataList = genPackage.getReferenceData(nestedEAnnotation);
stringBuffer.append(TEXT_270);
stringBuffer.append(genPackage.getAnnotatedModelElementAccessor(eAnnotation));
stringBuffer.append(TEXT_282);
if (nonContentAnnotation && genModel.getRuntimeVersion().getValue() >= GenRuntimeVersion.EMF210_VALUE) {
stringBuffer.append(TEXT_283);
stringBuffer.append(path.toString());
stringBuffer.append(TEXT_284);
} else {
stringBuffer.append(depth);
}
stringBuffer.append(TEXT_282);
if (nestedAnnotationSource == null) {
stringBuffer.append(TEXT_285);
} else {
stringBuffer.append(TEXT_238);
stringBuffer.append(nestedAnnotationSource);
stringBuffer.append(TEXT_286);
stringBuffer.append(genModel.getNonNLS());
}
stringBuffer.append(TEXT_287);
for (Iterator<Map.Entry<String, String>> l = nestedEAnnotation.getDetails().iterator(); l.hasNext();) { Map.Entry<String, String> detail = l.next(); String key = Literals.toStringLiteral(detail.getKey(), genModel); String value = Literals.toStringLiteral(detail.getValue(), genModel);
stringBuffer.append(TEXT_272);
stringBuffer.append(key);
stringBuffer.append(TEXT_200);
stringBuffer.append(value);
stringBuffer.append(l.hasNext() ? "," : "");
stringBuffer.append(genModel.getNonNLS(key + value));
}
stringBuffer.append(TEXT_273);
if (nestedAnnotationReferenceDataList.isEmpty()) {
stringBuffer.append(TEXT_177);
} else {
stringBuffer.append(TEXT_274);
}
if (!nestedAnnotationReferenceDataList.isEmpty()) {
stringBuffer.append(TEXT_275);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.common.util.URI"));
stringBuffer.append(TEXT_276);
for (Iterator<GenPackage.AnnotationReferenceData> l = nestedAnnotationReferenceDataList.iterator(); l.hasNext();) { GenPackage.AnnotationReferenceData annotationReferenceData = l.next();
stringBuffer.append(TEXT_277);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.common.util.URI"));
stringBuffer.append(TEXT_278);
if (annotationReferenceData.containingGenPackage != genPackage) {
stringBuffer.append(annotationReferenceData.containingGenPackage.getImportedPackageInterfaceName());
stringBuffer.append(TEXT_223);
}
stringBuffer.append(TEXT_279);
stringBuffer.append(annotationReferenceData.uriFragment);
stringBuffer.append(TEXT_280);
if (l.hasNext()) {
stringBuffer.append(TEXT_274);
}
stringBuffer.append(genModel.getNonNLS());
}
stringBuffer.append(TEXT_281);
}
}
}
}
stringBuffer.append(TEXT_265);
}
} else {
if (genPackage.isLoadingInitialization()) {
stringBuffer.append(TEXT_288);
stringBuffer.append(genModel.getImportedName("java.net.URL"));
stringBuffer.append(TEXT_289);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_290);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.common.util.URI"));
stringBuffer.append(TEXT_291);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.common.util.URI"));
stringBuffer.append(TEXT_292);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.resource.Resource"));
stringBuffer.append(TEXT_293);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl"));
stringBuffer.append(TEXT_294);
stringBuffer.append(genModel.getImportedName("java.io.IOException"));
stringBuffer.append(TEXT_295);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.common.util.WrappedException"));
stringBuffer.append(TEXT_296);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EPackage"));
stringBuffer.append(TEXT_297);
}
stringBuffer.append(TEXT_298);
if (genModel.useClassOverrideAnnotation()) {
stringBuffer.append(TEXT_158);
}
stringBuffer.append(TEXT_299);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EClassifier"));
stringBuffer.append(TEXT_300);
ArrayList<GenClass> dynamicGenClasses = new ArrayList<GenClass>(); for (GenClass genClass : genPackage.getGenClasses()) { if (genClass.isDynamic()) { dynamicGenClasses.add(genClass); } }
if (dynamicGenClasses.isEmpty()) {
stringBuffer.append(TEXT_301);
stringBuffer.append(genPackage.getInterfacePackageName());
stringBuffer.append(TEXT_302);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_303);
} else {
stringBuffer.append(TEXT_304);
for (GenClass genClass : dynamicGenClasses) {
if (genClass.isDynamic()) {
stringBuffer.append(TEXT_305);
stringBuffer.append(genPackage.getClassifierID(genClass));
stringBuffer.append(TEXT_306);
}
}
stringBuffer.append(TEXT_307);
stringBuffer.append(genPackage.getInterfacePackageName());
stringBuffer.append(TEXT_302);
stringBuffer.append(genModel.getNonNLS());
stringBuffer.append(TEXT_308);
}
stringBuffer.append(TEXT_309);
}
if (needsAddEOperation) {
stringBuffer.append(TEXT_310);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EOperation"));
stringBuffer.append(TEXT_311);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EClass"));
stringBuffer.append(TEXT_312);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EClassifier"));
stringBuffer.append(TEXT_313);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EOperation"));
stringBuffer.append(TEXT_314);
}
if (needsAddEParameter) {
stringBuffer.append(TEXT_310);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EParameter"));
stringBuffer.append(TEXT_315);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EOperation"));
stringBuffer.append(TEXT_312);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EClassifier"));
stringBuffer.append(TEXT_313);
stringBuffer.append(genModel.getImportedName("org.eclipse.emf.ecore.EParameter"));
stringBuffer.append(TEXT_316);
}
}
if (isInterface && genPackage.isLiteralsInterface()) {
stringBuffer.append(TEXT_317);
if (genModel.isOperationReflection()) {
stringBuffer.append(TEXT_318);
}
stringBuffer.append(TEXT_319);
if (isImplementation) {
stringBuffer.append(TEXT_320);
}
stringBuffer.append(TEXT_321);
for (GenClassifier genClassifier : genPackage.getGenClassifiers()) {
stringBuffer.append(TEXT_322);
if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier;
if (!genClass.isInterface()) {
stringBuffer.append(TEXT_323);
stringBuffer.append(genClass.getQualifiedClassName());
stringBuffer.append(TEXT_42);
stringBuffer.append(genClass.getFormattedName());
stringBuffer.append(TEXT_324);
stringBuffer.append(genClass.getQualifiedClassName());
} else {
stringBuffer.append(TEXT_323);
stringBuffer.append(genClass.getRawQualifiedInterfaceName());
stringBuffer.append(TEXT_42);
stringBuffer.append(genClass.getFormattedName());
stringBuffer.append(TEXT_324);
stringBuffer.append(genClass.getRawQualifiedInterfaceName());
}
} else if (genClassifier instanceof GenEnum) { GenEnum genEnum = (GenEnum)genClassifier;
stringBuffer.append(TEXT_323);
stringBuffer.append(genEnum.getQualifiedName());
stringBuffer.append(TEXT_42);
stringBuffer.append(genEnum.getFormattedName());
stringBuffer.append(TEXT_325);
stringBuffer.append(genEnum.getQualifiedName());
} else if (genClassifier instanceof GenDataType) { GenDataType genDataType = (GenDataType)genClassifier;
stringBuffer.append(TEXT_326);
stringBuffer.append(genDataType.getFormattedName());
stringBuffer.append(TEXT_327);
if (!genDataType.isPrimitiveType() && !genDataType.isArrayType()) {
stringBuffer.append(TEXT_328);
stringBuffer.append(genDataType.getRawInstanceClassName());
}
}
stringBuffer.append(TEXT_328);
stringBuffer.append(genPackage.getQualifiedPackageClassName());
stringBuffer.append(TEXT_48);
stringBuffer.append(genClassifier.getClassifierAccessorName());
stringBuffer.append(TEXT_49);
if (genClassifier.hasAPITags()) {
stringBuffer.append(TEXT_329);
stringBuffer.append(genClassifier.getAPITags(genModel.getIndentation(stringBuffer)));
}
stringBuffer.append(TEXT_330);
if (isJDK50 && genClassifier.hasAPIDeprecatedTag()) {
stringBuffer.append(TEXT_331);
}
stringBuffer.append(TEXT_93);
stringBuffer.append(publicStaticFinalFlag);
stringBuffer.append(genClassifier.getImportedMetaType());
stringBuffer.append(TEXT_69);
stringBuffer.append(genPackage.getClassifierID(genClassifier));
stringBuffer.append(TEXT_332);
stringBuffer.append(genClassifier.getClassifierAccessorName());
stringBuffer.append(TEXT_168);
if (genClassifier instanceof GenClass) { GenClass genClass = (GenClass)genClassifier;
for (GenFeature genFeature : genClass.getGenFeatures()) {
stringBuffer.append(TEXT_333);
stringBuffer.append(genFeature.getFormattedName());
stringBuffer.append(TEXT_58);
stringBuffer.append(genFeature.getFeatureKind());
stringBuffer.append(TEXT_334);
if (genFeature.hasImplicitAPITags()) {
stringBuffer.append(TEXT_329);
stringBuffer.append(genFeature.getImplicitAPITags(genModel.getIndentation(stringBuffer)));
}
stringBuffer.append(TEXT_330);
if (isJDK50 && genFeature.hasImplicitAPIDeprecatedTag()) {
stringBuffer.append(TEXT_331);
}
stringBuffer.append(TEXT_93);
stringBuffer.append(publicStaticFinalFlag);
stringBuffer.append(genFeature.getImportedMetaType());
stringBuffer.append(TEXT_69);
stringBuffer.append(genClass.getFeatureID(genFeature));
stringBuffer.append(TEXT_332);
stringBuffer.append(genFeature.getFeatureAccessorName());
stringBuffer.append(TEXT_168);
}
if (genModel.isOperationReflection()) {
for (GenOperation genOperation : genClass.getGenOperations()) {
stringBuffer.append(TEXT_333);
stringBuffer.append(genOperation.getFormattedName());
stringBuffer.append(TEXT_335);
if (genOperation.hasImplicitAPITags()) {
stringBuffer.append(TEXT_329);
stringBuffer.append(genOperation.getImplicitAPITags(genModel.getIndentation(stringBuffer)));
}
stringBuffer.append(TEXT_330);
if (isJDK50 && genOperation.hasImplicitAPIDeprecatedTag()) {
stringBuffer.append(TEXT_331);
}
stringBuffer.append(TEXT_93);
stringBuffer.append(publicStaticFinalFlag);
stringBuffer.append(genOperation.getImportedMetaType());
stringBuffer.append(TEXT_69);
stringBuffer.append(genClass.getOperationID(genOperation, false));
stringBuffer.append(TEXT_332);
stringBuffer.append(genOperation.getOperationAccessorName());
stringBuffer.append(TEXT_168);
}
}
}
}
stringBuffer.append(TEXT_265);
}
stringBuffer.append(TEXT_336);
stringBuffer.append(isInterface ? genPackage.getPackageInterfaceName() : genPackage.getPackageClassName());
genModel.emitSortedImports();
stringBuffer.append(TEXT_7);
return stringBuffer.toString();
}
}
|
package com.freejavaman;
import java.io.OutputStream;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
public class ImgInsert extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//取得檔案來源
Bitmap sourceImg = null;
try {
sourceImg = BitmapFactory.decodeFile("/sdcard/tmp/trip.jpg");
Log.v("content", "read img done");
}catch (Exception e) {
Log.e("content", "read img err:" + e);
}
//取得ContentResolver工具物件實體
ContentResolver cResolver = this.getContentResolver();
//設定圖檔的基本資料
ContentValues values = new ContentValues(3);
values.put(Media.DISPLAY_NAME, "view");
values.put(Media.DESCRIPTION, "my trip");
values.put(Media.MIME_TYPE, "image/jpeg");
//新增圖檔的基本資料
Uri uri = cResolver.insert(Media.EXTERNAL_CONTENT_URI, values);
//進行圖檔的更新
try {
if (sourceImg != null) {
OutputStream out = cResolver.openOutputStream(uri);
sourceImg.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.close();
out = null;
Log.v("content", "insert image done");
}
} catch (Exception e) {
Log.e("content", "err:" + e);
}
}
}
|
package cn.chinaunicom.monitor;
import android.app.Application;
import android.util.DisplayMetrics;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.chinaunicom.monitor.adapters.AlarmCategoryAdapter;
import cn.chinaunicom.monitor.beans.AlarmCategoryEntity;
import cn.chinaunicom.monitor.beans.CellEntity;
import cn.chinaunicom.monitor.beans.CenterEntity;
import cn.chinaunicom.monitor.beans.GridInCenter;
import cn.chinaunicom.monitor.beans.GridItem;
import cn.chinaunicom.monitor.beans.HostIp;
import cn.chinaunicom.monitor.utils.Config;
/**
* Created by yfyang on 2017/8/1.
*/
public class ChinaUnicomApplication extends Application {
public static Application getApplication() {
return mApplication;
}
private static Application mApplication; //应用实例
public static String token; //用户token
public static String userName; //当前登录用户的用户名
public static List<AlarmCategoryEntity> unCheckAlarmCategories = new ArrayList<>(); //未查看告警类别列表
public static List<AlarmCategoryEntity> alarmCategoryEntities = new ArrayList<>(); //告警类别列表
public static Map<String, Integer> badgeMap = new HashMap<>(); //控制告警红点逻辑
public static AlarmCategoryAdapter alarmCategoryAdapter; //告警类别列表的adapter
public static List<CenterEntity> alarmCenterList = new ArrayList<>(); //有告警的中心
public static CenterEntity alarmCurCenter; //告警当前显示的中心
public static CenterEntity mainframeCurCenter; //监控界面当前选择的中心
public static List<GridInCenter> gridInCenterList= new ArrayList<>();
public static List<CenterEntity> mainframeCenterList = new ArrayList<>();
public static List<GridItem> mainframeCurGrid = new ArrayList<>();
public static List<CellEntity> curChartCells = new ArrayList<>();
public static List<Long> reportsIds = new ArrayList<>(); //晨检报告的id
public static List<HostIp> consoleHostIps = new ArrayList<>(); //控制台server的ip
@Override
public void onCreate() {
super.onCreate();
mApplication = this;
DisplayMetrics dm =getResources().getDisplayMetrics();
int w_screen = dm.widthPixels;
int h_screen = dm.heightPixels;
Config.LOAD_TOAST_POS = h_screen/2;
Config.POP_UP_DIALOG_HEIGHT = h_screen;
Config.POP_UP_DIALOG_WIDTH = (h_screen/3);
alarmCategoryAdapter = new AlarmCategoryAdapter(getApplication());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.