repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Adapter/RecyclerViewTimeCardAdapter.java | app/src/main/java/zql/app_jinnang/Adapter/RecyclerViewTimeCardAdapter.java | package zql.app_jinnang.Adapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearSmoothScroller;
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.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import zql.app_jinnang.Bean.Means;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.R;
import zql.app_jinnang.UserSeting;
import zql.app_jinnang.View.CalendarActivityImp;
import zql.app_jinnang.View.ListActivityImp;
import zql.app_jinnang.View.NoteinfoActivity;
/**
* Created by 尽途 on 2018/5/11.
*/
public class RecyclerViewTimeCardAdapter extends RecyclerView.Adapter<RecyclerViewCardAdapter.Viewholder>{
private ArrayList<NoteBean> notelist;
private Context context;
private UserSeting userSeting;
private CalendarActivityImp calendarActivityImp;
public RecyclerViewTimeCardAdapter(ArrayList<NoteBean>mnotelist,Context mcontext,CalendarActivityImp mcalendarActivityImp){
Collections.reverse(mnotelist);//倒序
this.notelist=mnotelist;
this.context=mcontext;
this.calendarActivityImp=mcalendarActivityImp;
userSeting=(UserSeting)mcalendarActivityImp.getCalendarApplication();
}
@Override
public RecyclerViewCardAdapter.Viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View iten_recycler= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recyclercard,parent,false);
RecyclerViewCardAdapter.Viewholder viewholder=new RecyclerViewCardAdapter.Viewholder(iten_recycler);
return viewholder;
}
@Override
public void onBindViewHolder(RecyclerViewCardAdapter.Viewholder holder, int position) {
switch (notelist.get(position).getNotetype().toString()){
case "旅行":
holder.recycler_image_notetype.setImageResource(R.drawable.icon_travel);
holder.recycler_text_note.setText(R.string.note_travel);
break;
case "学习":
holder.recycler_image_notetype.setImageResource(R.drawable.icon_study);
holder.recycler_text_note.setText(R.string.note_study);
break;
case "工作":
holder.recycler_image_notetype.setImageResource(R.drawable.icon_work);
holder.recycler_text_note.setText(R.string.note_work);
break;
case "日记":
holder.recycler_image_notetype.setImageResource(R.drawable.icon_diary);
holder.recycler_text_note.setText(R.string.note_diary);
break;
case "生活":
holder.recycler_image_notetype.setImageResource(R.drawable.icon_live);
holder.recycler_text_note.setText(R.string.note_live);
break;
default:
break;
}
holder.recycler_text_note.setText(Means.getNotetextOnRecyclerCard(notelist.get(position).getNoteinfo()));
holder.recycler_text_time.setText(notelist.get(position).getCreatetime());
startNoteinfoActivity(holder.linearLayout,notelist.get(position));
}
@Override
public int getItemCount() {
return notelist==null ? 0 : notelist.size();
}
public class Viewholder extends RecyclerView.ViewHolder{
ImageView recycler_image_notetype,recycler_image_menu;
TextView recycler_text_note,recycler_text_time;
LinearLayout linearLayout;
public Viewholder(View itemView){
super(itemView);
recycler_image_notetype=(ImageView)itemView.findViewById(R.id.recycler_image_notetype);
recycler_image_menu=(ImageView)itemView.findViewById(R.id.recycler_image_menu);
recycler_text_note=(TextView)itemView.findViewById(R.id.recycler_text_note);
recycler_text_time=(TextView)itemView.findViewById(R.id.recycler_text_time);
linearLayout=(LinearLayout)itemView.findViewById(R.id.recycler_item);
}
}
private void startNoteinfoActivity(View view,final NoteBean noteBean){
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent mintent=new Intent(context,NoteinfoActivity.class);
Bundle bundle=new Bundle();
bundle.putSerializable("noteinfo", Means.changefromNotebean(noteBean));
mintent.putExtras(bundle);
context.startActivity(mintent);
}
});
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/greendao/db/NoteBeanDao.java | app/src/main/java/zql/app_jinnang/greendao/db/NoteBeanDao.java | package zql.app_jinnang.greendao.db;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.internal.DaoConfig;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;
import zql.app_jinnang.Bean.NoteBean;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "NOTE_BEAN".
*/
public class NoteBeanDao extends AbstractDao<NoteBean, Long> {
public static final String TABLENAME = "NOTE_BEAN";
/**
* Properties of entity NoteBean.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Noteinfo = new Property(1, String.class, "noteinfo", false, "NOTEINFO");
public final static Property Notetype = new Property(2, String.class, "notetype", false, "NOTETYPE");
public final static Property People = new Property(3, String.class, "people", false, "PEOPLE");
public final static Property Date = new Property(4, String.class, "date", false, "DATE");
public final static Property Time = new Property(5, String.class, "time", false, "TIME");
public final static Property Location = new Property(6, String.class, "location", false, "LOCATION");
public final static Property Photopath = new Property(7, String.class, "photopath", false, "PHOTOPATH");
public final static Property Isshow = new Property(8, Boolean.class, "isshow", false, "ISSHOW");
public final static Property Createtime = new Property(9, String.class, "createtime", false, "CREATETIME");
}
public NoteBeanDao(DaoConfig config) {
super(config);
}
public NoteBeanDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(Database db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"NOTE_BEAN\" (" + //
"\"_id\" INTEGER PRIMARY KEY ," + // 0: id
"\"NOTEINFO\" TEXT," + // 1: noteinfo
"\"NOTETYPE\" TEXT," + // 2: notetype
"\"PEOPLE\" TEXT," + // 3: people
"\"DATE\" TEXT," + // 4: date
"\"TIME\" TEXT," + // 5: time
"\"LOCATION\" TEXT," + // 6: location
"\"PHOTOPATH\" TEXT," + // 7: photopath
"\"ISSHOW\" INTEGER," + // 8: isshow
"\"CREATETIME\" TEXT);"); // 9: createtime
}
/** Drops the underlying database table. */
public static void dropTable(Database db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"NOTE_BEAN\"";
db.execSQL(sql);
}
@Override
protected final void bindValues(DatabaseStatement stmt, NoteBean entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String noteinfo = entity.getNoteinfo();
if (noteinfo != null) {
stmt.bindString(2, noteinfo);
}
String notetype = entity.getNotetype();
if (notetype != null) {
stmt.bindString(3, notetype);
}
String people = entity.getPeople();
if (people != null) {
stmt.bindString(4, people);
}
String date = entity.getDate();
if (date != null) {
stmt.bindString(5, date);
}
String time = entity.getTime();
if (time != null) {
stmt.bindString(6, time);
}
String location = entity.getLocation();
if (location != null) {
stmt.bindString(7, location);
}
String photopath = entity.getPhotopath();
if (photopath != null) {
stmt.bindString(8, photopath);
}
Boolean isshow = entity.getIsshow();
if (isshow != null) {
stmt.bindLong(9, isshow ? 1L: 0L);
}
String createtime = entity.getCreatetime();
if (createtime != null) {
stmt.bindString(10, createtime);
}
}
@Override
protected final void bindValues(SQLiteStatement stmt, NoteBean entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String noteinfo = entity.getNoteinfo();
if (noteinfo != null) {
stmt.bindString(2, noteinfo);
}
String notetype = entity.getNotetype();
if (notetype != null) {
stmt.bindString(3, notetype);
}
String people = entity.getPeople();
if (people != null) {
stmt.bindString(4, people);
}
String date = entity.getDate();
if (date != null) {
stmt.bindString(5, date);
}
String time = entity.getTime();
if (time != null) {
stmt.bindString(6, time);
}
String location = entity.getLocation();
if (location != null) {
stmt.bindString(7, location);
}
String photopath = entity.getPhotopath();
if (photopath != null) {
stmt.bindString(8, photopath);
}
Boolean isshow = entity.getIsshow();
if (isshow != null) {
stmt.bindLong(9, isshow ? 1L: 0L);
}
String createtime = entity.getCreatetime();
if (createtime != null) {
stmt.bindString(10, createtime);
}
}
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
@Override
public NoteBean readEntity(Cursor cursor, int offset) {
NoteBean entity = new NoteBean( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // noteinfo
cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // notetype
cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // people
cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // date
cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5), // time
cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6), // location
cursor.isNull(offset + 7) ? null : cursor.getString(offset + 7), // photopath
cursor.isNull(offset + 8) ? null : cursor.getShort(offset + 8) != 0, // isshow
cursor.isNull(offset + 9) ? null : cursor.getString(offset + 9) // createtime
);
return entity;
}
@Override
public void readEntity(Cursor cursor, NoteBean entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setNoteinfo(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
entity.setNotetype(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
entity.setPeople(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
entity.setDate(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4));
entity.setTime(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5));
entity.setLocation(cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6));
entity.setPhotopath(cursor.isNull(offset + 7) ? null : cursor.getString(offset + 7));
entity.setIsshow(cursor.isNull(offset + 8) ? null : cursor.getShort(offset + 8) != 0);
entity.setCreatetime(cursor.isNull(offset + 9) ? null : cursor.getString(offset + 9));
}
@Override
protected final Long updateKeyAfterInsert(NoteBean entity, long rowId) {
entity.setId(rowId);
return rowId;
}
@Override
public Long getKey(NoteBean entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
@Override
public boolean hasKey(NoteBean entity) {
return entity.getId() != null;
}
@Override
protected final boolean isEntityUpdateable() {
return true;
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/greendao/db/DaoMaster.java | app/src/main/java/zql/app_jinnang/greendao/db/DaoMaster.java | package zql.app_jinnang.greendao.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;
import org.greenrobot.greendao.AbstractDaoMaster;
import org.greenrobot.greendao.database.StandardDatabase;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseOpenHelper;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* Master of DAO (schema version 1): knows all DAOs.
*/
public class DaoMaster extends AbstractDaoMaster {
public static final int SCHEMA_VERSION = 1;
/** Creates underlying database table using DAOs. */
public static void createAllTables(Database db, boolean ifNotExists) {
NoteBeanDao.createTable(db, ifNotExists);
}
/** Drops underlying database table using DAOs. */
public static void dropAllTables(Database db, boolean ifExists) {
NoteBeanDao.dropTable(db, ifExists);
}
/**
* WARNING: Drops all table on Upgrade! Use only during development.
* Convenience method using a {@link DevOpenHelper}.
*/
public static DaoSession newDevSession(Context context, String name) {
Database db = new DevOpenHelper(context, name).getWritableDb();
DaoMaster daoMaster = new DaoMaster(db);
return daoMaster.newSession();
}
public DaoMaster(SQLiteDatabase db) {
this(new StandardDatabase(db));
}
public DaoMaster(Database db) {
super(db, SCHEMA_VERSION);
registerDaoClass(NoteBeanDao.class);
}
public DaoSession newSession() {
return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
}
public DaoSession newSession(IdentityScopeType type) {
return new DaoSession(db, type, daoConfigMap);
}
/**
* Calls {@link #createAllTables(Database, boolean)} in {@link #onCreate(Database)} -
*/
public static abstract class OpenHelper extends DatabaseOpenHelper {
public OpenHelper(Context context, String name) {
super(context, name, SCHEMA_VERSION);
}
public OpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory, SCHEMA_VERSION);
}
@Override
public void onCreate(Database db) {
Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);
createAllTables(db, false);
}
}
/** WARNING: Drops all table on Upgrade! Use only during development. */
public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name) {
super(context, name);
}
public DevOpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
dropAllTables(db, true);
onCreate(db);
}
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/greendao/db/DaoSession.java | app/src/main/java/zql/app_jinnang/greendao/db/DaoSession.java | package zql.app_jinnang.greendao.db;
import java.util.Map;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.AbstractDaoSession;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.greenrobot.greendao.internal.DaoConfig;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.greendao.db.NoteBeanDao;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* {@inheritDoc}
*
* @see org.greenrobot.greendao.AbstractDaoSession
*/
public class DaoSession extends AbstractDaoSession {
private final DaoConfig noteBeanDaoConfig;
private final NoteBeanDao noteBeanDao;
public DaoSession(Database db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
daoConfigMap) {
super(db);
noteBeanDaoConfig = daoConfigMap.get(NoteBeanDao.class).clone();
noteBeanDaoConfig.initIdentityScope(type);
noteBeanDao = new NoteBeanDao(noteBeanDaoConfig, this);
registerDao(NoteBean.class, noteBeanDao);
}
public void clear() {
noteBeanDaoConfig.clearIdentityScope();
}
public NoteBeanDao getNoteBeanDao() {
return noteBeanDao;
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/Prestener_about.java | app/src/main/java/zql/app_jinnang/Prestener/Prestener_about.java | package zql.app_jinnang.Prestener;
import java.util.List;
import zql.app_jinnang.UserSeting;
import zql.app_jinnang.UserSetingImp;
import zql.app_jinnang.View.AboutActivityImp;
/**
* Created by 尽途 on 2018/5/12.
*/
public class Prestener_about implements PrestenerImp_about {
private AboutActivityImp aboutActivityImp;
private UserSeting userSeting;
public Prestener_about(AboutActivityImp aboutActivityImp){
this.aboutActivityImp=aboutActivityImp;
userSeting=(UserSeting)aboutActivityImp.getAboutApplication();
}
@Override
public boolean isnullthepasswordfromSeting() {
return userSeting.isnullthepassword();
}
@Override
public boolean isnullthequestionfromSeting() {
return userSeting.isnullthequestion();
}
@Override
public boolean iscurrentthepasswordfromSeting(String password) {
return userSeting.iscurrentthePassword(password);
}
@Override
public boolean iscurrentthequestionfromSeting(String question) {
return userSeting.iscurrentthQuestion(question);
}
@Override
public void putpasswordandquestionOnSeting(String password, String question) {
userSeting.putpasswordonSeting(password);
userSeting.putquestiononSeting(question);
}
@Override
public void putpasswordOnSeting(String password) {
userSeting.putpasswordonSeting(password);
}
@Override
public void putquestionOnSeting(String question) {
userSeting.putquestiononSeting(question);
}
@Override
public void showthecurrentpasswordOnAboutactivity() {
aboutActivityImp.showthecurrentPassword(userSeting.getpassswordfromSeting().toString());
}
@Override
public void putcurrentcolorOnSeting(int color) {
userSeting.putcurrentColor(color);
}
@Override
public int getcurrentcolorNumfromSeting() {
return userSeting.getcurrentColorNum();
}
@Override
public void setBackgroundcolorfromSeting() {
aboutActivityImp.setBackgroundcolorfromSeting(userSeting.getcurrentColor());
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/PrestenerImp_datachart.java | app/src/main/java/zql/app_jinnang/Prestener/PrestenerImp_datachart.java | package zql.app_jinnang.Prestener;
import java.util.List;
import lecho.lib.hellocharts.model.SliceValue;
public interface PrestenerImp_datachart {
public void setBackgroundcolorfromSeting();//设置主题色
public List<SliceValue> getPieChartNumberfromDatatoActivity();//获取数据到界面
public int getPieChartSumfromDatatoActivity();//获取总数
public List<Integer> getPieChartListfromData();//获取列表
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/Prestener_listserect.java | app/src/main/java/zql/app_jinnang/Prestener/Prestener_listserect.java | package zql.app_jinnang.Prestener;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Model.NoteInfoModel;
import zql.app_jinnang.Model.NoteInfoModelImp;
import zql.app_jinnang.UserSeting;
import zql.app_jinnang.View.ListSecretActivityImp;
public class Prestener_listserect implements PrestenerImp_listserect {
private ListSecretActivityImp listSecretActivityImp;
private NoteInfoModelImp noteInfoModelImp;
private UserSeting userSeting;
public Prestener_listserect(ListSecretActivityImp mlistSecretActivityImp){
this.listSecretActivityImp=mlistSecretActivityImp;
noteInfoModelImp=new NoteInfoModel(listSecretActivityImp.getListSerectActivityContext());
userSeting=(UserSeting)listSecretActivityImp.getListSerectApplication();
}
@Override
public void readNoteserectfromDatatoList() {
listSecretActivityImp.readAllNoteSerectfromData(noteInfoModelImp.QueryAllNotefromData_secret());
}
@Override
public void deleteNotebeanserect(NoteBean noteBean) {
noteInfoModelImp.DeleteNotefromData_secret(noteBean);
}
@Override
public void setBackgroundcolorfromSeting() {
listSecretActivityImp.setBackgroundcolorfromSeting(userSeting.getcurrentColor());
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/Prestener_list.java | app/src/main/java/zql/app_jinnang/Prestener/Prestener_list.java | package zql.app_jinnang.Prestener;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Model.NoteInfoModel;
import zql.app_jinnang.Model.NoteInfoModelImp;
import zql.app_jinnang.UserSeting;
import zql.app_jinnang.View.ListActivityImp;
/**
* Created by 尽途 on 2018/4/12.
*/
public class Prestener_list implements PrestenerImp_list {
private ListActivityImp listActivityImp;
private NoteInfoModelImp noteInfoModelImp;
private UserSeting userSeting;
public Prestener_list(ListActivityImp mlistActivityImp){
this.listActivityImp=mlistActivityImp;
noteInfoModelImp=new NoteInfoModel(listActivityImp.getListActivityConent());
userSeting=(UserSeting)listActivityImp.getListApplication();
}
@Override
public void setBackgroundcolorfromSeting() {
listActivityImp.setBackgroundcolorfromSeting(userSeting.getcurrentColor());
}
@Override
public void changeNotetoPasswordFile(NoteBean noteBean) {
if (noteBean.getId()!=null){
noteInfoModelImp.DeleteNotefromData(noteBean);
noteBean.setId(null);
}
noteInfoModelImp.InsertNotetoData_secret(noteBean);
}
@Override
public void readNotefromDatatoList(int READ_TYPE) {
switch (READ_TYPE){
case 0:
listActivityImp.readAllNotefromData(noteInfoModelImp.QueryAllNotefromData());
break;
case 1:
listActivityImp.readAllNotefromData(noteInfoModelImp.QueryNoyefromDataByType("工作"));
break;
case 2:
listActivityImp.readAllNotefromData(noteInfoModelImp.QueryNoyefromDataByType("学习"));
break;
case 3:
listActivityImp.readAllNotefromData(noteInfoModelImp.QueryNoyefromDataByType("生活"));
break;
case 4:
listActivityImp.readAllNotefromData(noteInfoModelImp.QueryNoyefromDataByType("日记"));
break;
case 5:
listActivityImp.readAllNotefromData(noteInfoModelImp.QueryNoyefromDataByType("旅行"));
break;
case 6:
break;
default:
break;
}
}
@Override
public void deleteNotebean(NoteBean noteBean) {
noteInfoModelImp.DeleteNotefromData(noteBean);
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/PrestenerImp_about.java | app/src/main/java/zql/app_jinnang/Prestener/PrestenerImp_about.java | package zql.app_jinnang.Prestener;
import java.util.List;
/**
* Created by 尽途 on 2018/5/12.
*/
public interface PrestenerImp_about {
public void showthecurrentpasswordOnAboutactivity();
public boolean isnullthepasswordfromSeting();//判断密码是不是初始化“null”
public boolean isnullthequestionfromSeting();//判断密保问题是不是初始化“null”
public void putpasswordandquestionOnSeting(String password,String question);//写入密码和密保到设置文件中
public boolean iscurrentthepasswordfromSeting(String password);//判断是否为当前密码
public boolean iscurrentthequestionfromSeting(String question);//判断是否为当前密保
public void putpasswordOnSeting(String password);//单独修改当前密码
public void putquestionOnSeting(String question);//单独修改当前密保
public void putcurrentcolorOnSeting(int color);//改变主题色
public int getcurrentcolorNumfromSeting();//获取最新的颜色代码
public void setBackgroundcolorfromSeting();//设置主题色
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/Prestener_noteinfo.java | app/src/main/java/zql/app_jinnang/Prestener/Prestener_noteinfo.java | package zql.app_jinnang.Prestener;
import java.util.ArrayList;
import java.util.List;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Bean.Noteinfo;
import zql.app_jinnang.UserSeting;
import zql.app_jinnang.View.NoteinfoActivityImp;
/**
* Created by 尽途 on 2018/4/26.
*/
public class Prestener_noteinfo implements PrestenerImp_noteinfo{
private NoteinfoActivityImp noteinfoActivityImp;
private UserSeting userSeting;
public Prestener_noteinfo(NoteinfoActivityImp noteinfoActivityImp){
this.noteinfoActivityImp=noteinfoActivityImp;
userSeting=(UserSeting)noteinfoActivityImp.getNoteinfoApplication();
}
@Override
public void readDatatoNoteinfo(Noteinfo noteinfo) {
noteinfoActivityImp.readNoteinfotoNotetext(noteinfo.getNoteinfo());
noteinfoActivityImp.readPhotopathtoNoteImageview(noteinfo.getPhotopath(),noteinfo.getNotetype());
List<String>tags=new ArrayList<String>();
if (noteinfo.getNotetype().equals("null")){
tags.add("创建类型:无类型");
}else {
tags.add("创建类型:"+noteinfo.getNotetype());
}
if (noteinfo.getPeople().equals("null")){
}else {
tags.add("相关的人:"+noteinfo.getPeople());
}
if (noteinfo.getDate().equals("null")){
}else {
tags.add("指定日期:"+noteinfo.getDate());
}
if (noteinfo.getTime().equals("null")){
}else {
tags.add("指定时间:"+noteinfo.getTime());
}
if (noteinfo.getLocation().equals("null")){
}else {
tags.add("指定地点:"+noteinfo.getLocation());
}
if (noteinfo.getCreatetime().equals("null")){
}else {
tags.add("创建于:"+noteinfo.getCreatetime());
}
noteinfoActivityImp.readLabelinfotoNoteTagrroup(tags);
}
@Override
public void setBackgroundcolorfromSeting() {
noteinfoActivityImp.setBackgroundcolorfromSeting(userSeting.getcurrentColor());
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/Prestener_calendar.java | app/src/main/java/zql/app_jinnang/Prestener/Prestener_calendar.java | package zql.app_jinnang.Prestener;
import zql.app_jinnang.Model.NoteInfoModel;
import zql.app_jinnang.Model.NoteInfoModelImp;
import zql.app_jinnang.UserSeting;
import zql.app_jinnang.View.CalendarActivityImp;
/**
* Created by 尽途 on 2018/5/10.
*/
public class Prestener_calendar implements PrestenerImp_calendar {
private NoteInfoModelImp noteInfoModelImp;
private CalendarActivityImp calendarActivityImp;
private UserSeting userSeting;
public Prestener_calendar(CalendarActivityImp calendarActivityImp){
this.calendarActivityImp=calendarActivityImp;
noteInfoModelImp=new NoteInfoModel(calendarActivityImp.getCalendarActivity());
userSeting=(UserSeting)calendarActivityImp.getCalendarApplication();
}
@Override
public void readNotecreatimeOnCalendar() {
calendarActivityImp.initCalendarViewandgetCreattime(noteInfoModelImp.QueryNotecreatetime());
}
@Override
public void readNotebeanOnRecycler(String createtime) {
calendarActivityImp.readNotebeansfromDatabycreatetime(noteInfoModelImp.QueryNotebeanBycreatetime(createtime));
}
@Override
public void setBackgroundcolorfromSeting() {
calendarActivityImp.setBackgroundcolorfromSeting(userSeting.getcurrentColor());
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/PrestenerImp_main.java | app/src/main/java/zql/app_jinnang/Prestener/PrestenerImp_main.java | package zql.app_jinnang.Prestener;
import java.util.List;
import zql.app_jinnang.Bean.NoteBean;
/**
* Created by 尽途 on 2018/4/4.
*/
public interface PrestenerImp_main {
public void openCalendarActivity();//打开日历界面
public void openSearchActivity();//打开新的搜索界面
public void openListActivity();//打开事件列表的界面
public void openSetiongActivity();//打开用户设置界面
public void openListSecretActivity();//打开秘密界面
public void readNotefromDatatoMain();//获取信息从数据库并展现在MainActivity上
public void deleteNoteBean(NoteBean noteBean);//删除一个Notebean
public void setBackgroundcolorfromSeting();//改变主题
public int getBackgroundcolorNumfromSering();//获取
public boolean iscurrentthepasswordfromSeting(String password);//判断密码是否正确
public void changeNotetoPasswordFile(NoteBean noteBean);//将文件转入秘密文件夹
public void readNotefromDtabyType(int TYPE);//通过标签类型展示数据
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/Prestener_main.java | app/src/main/java/zql/app_jinnang/Prestener/Prestener_main.java | package zql.app_jinnang.Prestener;
import java.util.List;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Model.NoteInfoModel;
import zql.app_jinnang.Model.NoteInfoModelImp;
import zql.app_jinnang.UserSeting;
import zql.app_jinnang.View.MainActivityImp;
/**
* Created by 尽途 on 2018/4/4.
*/
public class Prestener_main implements PrestenerImp_main {
private NoteInfoModelImp noteInfoModelImp;
private MainActivityImp mainActivityImp;
private UserSeting userSeting;
public Prestener_main(MainActivityImp mmainActivityImp){
this.mainActivityImp=mmainActivityImp;
noteInfoModelImp=new NoteInfoModel(mmainActivityImp.getActivity_this());
userSeting=(UserSeting)mainActivityImp.getMainApplication();
}
@Override
public boolean iscurrentthepasswordfromSeting(String password) {
return userSeting.iscurrentthePassword(password);
}
@Override
public void openCalendarActivity() {
mainActivityImp.startCalendarActivity();
}
@Override
public void openSearchActivity() {
mainActivityImp.startSearchActivity();
}
@Override
public void openListActivity() {
mainActivityImp.startListActivity();
}
@Override
public void openListSecretActivity() {
mainActivityImp.startListSecretActivity();
}
@Override
public void openSetiongActivity() {
mainActivityImp.startSetingActivity();
}
@Override
public void readNotefromDatatoMain() {
mainActivityImp.readNotefromData(noteInfoModelImp.QueryAllNotefromData());
}
@Override
public void readNotefromDtabyType(int READ_TYPE) {
switch (READ_TYPE){
case 0:
mainActivityImp.readNotefromData(noteInfoModelImp.QueryAllNotefromData());
break;
case 1:
mainActivityImp.readNotefromData(noteInfoModelImp.QueryNoyefromDataByType("工作"));
break;
case 2:
mainActivityImp.readNotefromData(noteInfoModelImp.QueryNoyefromDataByType("学习"));
break;
case 3:
mainActivityImp.readNotefromData(noteInfoModelImp.QueryNoyefromDataByType("生活"));
break;
case 4:
mainActivityImp.readNotefromData(noteInfoModelImp.QueryNoyefromDataByType("日记"));
break;
case 5:
mainActivityImp.readNotefromData(noteInfoModelImp.QueryNoyefromDataByType("旅行"));
break;
case 6:
break;
default:
break;
}
}
@Override
public void deleteNoteBean(NoteBean noteBean) {
noteInfoModelImp.DeleteNotefromData(noteBean);
}
@Override
public void changeNotetoPasswordFile(NoteBean noteBean) {
if (noteBean.getId()!=null){
noteInfoModelImp.DeleteNotefromData(noteBean);
noteBean.setId(null);
}
noteInfoModelImp.InsertNotetoData_secret(noteBean);
}
@Override
public void setBackgroundcolorfromSeting() {
mainActivityImp.setBackgroundcolorfromSeting(userSeting.getcurrentColor());
}
@Override
public int getBackgroundcolorNumfromSering() {
return userSeting.getcurrentColorNum();
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/PrestenerImp_listserect.java | app/src/main/java/zql/app_jinnang/Prestener/PrestenerImp_listserect.java | package zql.app_jinnang.Prestener;
import zql.app_jinnang.Bean.NoteBean;
public interface PrestenerImp_listserect {
public void readNoteserectfromDatatoList();
public void deleteNotebeanserect(NoteBean noteBean);
public void setBackgroundcolorfromSeting();//设置主题色
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/PrestenerImp_seacher.java | app/src/main/java/zql/app_jinnang/Prestener/PrestenerImp_seacher.java | package zql.app_jinnang.Prestener;
import android.database.Cursor;
import java.util.List;
import zql.app_jinnang.Bean.NoteBean;
/**
* Created by 尽途 on 2018/5/1.
*/
public interface PrestenerImp_seacher {
public Cursor getCursorfromtoSearch(String search);
public List<NoteBean> getNotebeanfromDatatoSearch(String search);
public void setBackgroundcolorfromSeting();//设置主题色
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/PresterImp_edit.java | app/src/main/java/zql/app_jinnang/Prestener/PresterImp_edit.java | package zql.app_jinnang.Prestener;
import zql.app_jinnang.Bean.NoteBean;
public interface PresterImp_edit {
public void saveNoteinfotoDatabase(NoteBean noteBean);
public void saveNoteinfotoSecrectDatabase(NoteBean noteBean);
public void setBackgroundColorfromUserseting();
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/Prestener_datachart.java | app/src/main/java/zql/app_jinnang/Prestener/Prestener_datachart.java | package zql.app_jinnang.Prestener;
import java.util.List;
import lecho.lib.hellocharts.model.SliceValue;
import zql.app_jinnang.Model.NoteInfoModel;
import zql.app_jinnang.Model.NoteInfoModelImp;
import zql.app_jinnang.UserSeting;
import zql.app_jinnang.View.DataChartActivityImp;
public class Prestener_datachart implements PrestenerImp_datachart {
private DataChartActivityImp dataChartActivityImp;
private UserSeting userSeting;
private NoteInfoModelImp noteInfoModelImp;
public Prestener_datachart(DataChartActivityImp mdataChartActivityImp){
this.dataChartActivityImp=mdataChartActivityImp;
userSeting=(UserSeting)dataChartActivityImp.getAddApplication();
noteInfoModelImp=new NoteInfoModel(dataChartActivityImp.getAddActivityContext());
}
@Override
public void setBackgroundcolorfromSeting() {
dataChartActivityImp.setBackgroundcolorfromSeting(userSeting.getcurrentColor());
}
@Override
public List<SliceValue> getPieChartNumberfromDatatoActivity() {
return noteInfoModelImp.getPieChartNumberfromData();
}
@Override
public List<Integer> getPieChartListfromData() {
return noteInfoModelImp.getPieChartTypeListfromData();
}
@Override
public int getPieChartSumfromDatatoActivity() {
return noteInfoModelImp.QueryAllNoteSumfromfromData();
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/PrestenerImp_list.java | app/src/main/java/zql/app_jinnang/Prestener/PrestenerImp_list.java | package zql.app_jinnang.Prestener;
import zql.app_jinnang.Bean.NoteBean;
/**
* Created by 尽途 on 2018/4/12.
*/
public interface PrestenerImp_list {
public void readNotefromDatatoList(int READ_TYPE);
public void deleteNotebean(NoteBean noteBean);
public void setBackgroundcolorfromSeting();//设置主题色
public void changeNotetoPasswordFile(NoteBean noteBean);//转入秘密文件夹
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/Prestener_edit.java | app/src/main/java/zql/app_jinnang/Prestener/Prestener_edit.java | package zql.app_jinnang.Prestener;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Model.NoteInfoModel;
import zql.app_jinnang.Model.NoteInfoModelImp;
import zql.app_jinnang.UserSeting;
import zql.app_jinnang.View.EditActivityImp;
public class Prestener_edit implements PresterImp_edit {
private EditActivityImp editActivityImp;
private NoteInfoModelImp noteInfoModelImp;
private UserSeting userSeting;
public Prestener_edit(EditActivityImp editActivityImp){
this.editActivityImp=editActivityImp;
this.noteInfoModelImp=new NoteInfoModel(editActivityImp.getbasecontext());
this.userSeting=(UserSeting)editActivityImp.getapplication();
}
/**
* 添加到普通的数据库
* @param noteBean
*/
@Override
public void saveNoteinfotoDatabase(NoteBean noteBean) {
if (noteBean.getId()!=null){
noteInfoModelImp.ChangeNotetoData(noteBean);
}else {
noteInfoModelImp.InsertNotetoData(noteBean);
}
}
/**
*添加到秘密数据库
* @param noteBean
*/
@Override
public void saveNoteinfotoSecrectDatabase(NoteBean noteBean) {
if (noteBean.getId()!=null){
noteInfoModelImp.DeleteNotefromDataByid(noteBean.getId());
}
noteInfoModelImp.InsertNotetoData_secret(noteBean);
}
@Override
public void setBackgroundColorfromUserseting() {
editActivityImp.setbackgroundcolor(userSeting.getcurrentColor());
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/PrestenerImp_calendar.java | app/src/main/java/zql/app_jinnang/Prestener/PrestenerImp_calendar.java | package zql.app_jinnang.Prestener;
/**
* Created by 尽途 on 2018/5/10.
*/
public interface PrestenerImp_calendar {
public void readNotecreatimeOnCalendar();
public void readNotebeanOnRecycler(String createtime);
public void setBackgroundcolorfromSeting();//设置主题色
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/Prestener_seacher.java | app/src/main/java/zql/app_jinnang/Prestener/Prestener_seacher.java | package zql.app_jinnang.Prestener;
import android.app.Application;
import android.database.Cursor;
import java.util.List;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Model.NoteInfoModel;
import zql.app_jinnang.Model.NoteInfoModelImp;
import zql.app_jinnang.UserSeting;
import zql.app_jinnang.View.SearchActivityImp;
/**
* Created by 尽途 on 2018/5/1.
*/
public class Prestener_seacher implements PrestenerImp_seacher{
private SearchActivityImp searchActivityImp;
private NoteInfoModelImp noteInfoModelImp;
private UserSeting userSeting;
public Prestener_seacher(SearchActivityImp msearchActivityImp){
this.searchActivityImp=msearchActivityImp;
this.noteInfoModelImp=new NoteInfoModel(searchActivityImp.getSearchActivityContext());
userSeting=(UserSeting)searchActivityImp.getSearchApplication();
}
@Override
public Cursor getCursorfromtoSearch(String search) {
return null;
}
@Override
public List<NoteBean> getNotebeanfromDatatoSearch(String search) {
return noteInfoModelImp.getSearchfromData(search);
}
@Override
public void setBackgroundcolorfromSeting() {
searchActivityImp.setBackgroundcolorfromSeting(userSeting.getcurrentColor());
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Prestener/PrestenerImp_noteinfo.java | app/src/main/java/zql/app_jinnang/Prestener/PrestenerImp_noteinfo.java | package zql.app_jinnang.Prestener;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Bean.Noteinfo;
/**
* Created by 尽途 on 2018/4/26.
*/
public interface PrestenerImp_noteinfo {
public void readDatatoNoteinfo(Noteinfo noteinfo);
public void setBackgroundcolorfromSeting();//设置主题色
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Bean/Noteinfo.java | app/src/main/java/zql/app_jinnang/Bean/Noteinfo.java | package zql.app_jinnang.Bean;
import java.io.Serializable;
/**
* Created by 尽途 on 2018/4/30.
*/
public class Noteinfo implements Serializable {
private Long id;
private String noteinfo;
private String notetype;
private String people;
private String date;
private String time;
private String location;
private String photopath;
private Boolean isshow;
private String createtime;
public Noteinfo(Long id, String noteinfo, String notetype, String people,
String date, String time, String location, String photopath,
Boolean isshow, String createtime) {
this.id = id;
this.noteinfo = noteinfo;
this.notetype = notetype;
this.people = people;
this.date = date;
this.time = time;
this.location = location;
this.photopath = photopath;
this.isshow = isshow;
this.createtime = createtime;
}
public Noteinfo() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getNoteinfo() {
return this.noteinfo;
}
public void setNoteinfo(String noteinfo) {
this.noteinfo = noteinfo;
}
public String getNotetype() {
return this.notetype;
}
public void setNotetype(String notetype) {
this.notetype = notetype;
}
public String getPeople() {
return this.people;
}
public void setPeople(String people) {
this.people = people;
}
public String getDate() {
return this.date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return this.time;
}
public void setTime(String time) {
this.time = time;
}
public String getLocation() {
return this.location;
}
public void setLocation(String location) {
this.location = location;
}
public String getPhotopath() {
return this.photopath;
}
public void setPhotopath(String photopath) {
this.photopath = photopath;
}
public Boolean getIsshow() {
return this.isshow;
}
public void setIsshow(Boolean isshow) {
this.isshow = isshow;
}
public String getCreatetime() {
return this.createtime;
}
public void setCreatetime(String createtime) {
this.createtime = createtime;
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Bean/Means.java | app/src/main/java/zql/app_jinnang/Bean/Means.java | package zql.app_jinnang.Bean;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;
import com.rengwuxian.materialedittext.MaterialEditText;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import zql.app_jinnang.R;
/**
* Created by 尽途 on 2018/4/26.
*/
public abstract class Means {
public static String NOSTRING="null";
public static int EDIT=0;
public static int CHANGE=1;
public static int WORK=0;
public static int STUDY=1;
public static int LIVE=2;
public static int DIARY=3;
public static int TRAYEL=4;
public static String getNoteStringfromNoteInt(int type){//获取note类型
switch (type){
case 0:
return "工作";
case 1:
return "学习";
case 2:
return "生活";
case 3:
return "日记";
case 4:
return "旅行";
default:
return null;
}
}
public static String buildTransaction(final String type) {//微信分享使用到的功能
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
public static void setViewonlick(View view,float X,float Y){
long dowmTime= SystemClock.uptimeMillis();
MotionEvent dowmEvent=MotionEvent.obtain(dowmTime,dowmTime,MotionEvent.ACTION_DOWN,X,Y,0);
dowmTime+=1000;
MotionEvent upEvent=MotionEvent.obtain(dowmTime,dowmTime,MotionEvent.ACTION_UP,X,Y,0);
view.onTouchEvent(dowmEvent);
view.onTouchEvent(upEvent);
dowmEvent.recycle();
upEvent.recycle();
}
public static String getNotetextOnSearchCard(String note){
int length=note.length();
if (length>=20){
return note.substring(0,20)+"...";
}else {
return note+"...";
}
}
public static String getNoteTitleOnNoteinfoActivity(String note){
int length=note.length();
if (length<=5){
return note;
}else {
return note.substring(0,5)+"...";
}
}
public static String getNotetextOnRecyclerCard(String note){
int length=note.length();
if (length<=20){
return note;
}else if (length<=40){
return note+"\n";
}else {
return note.substring(0,40)+"...";
}
}
public static String getNotetextOnViewPagerCard(String note){
int length=note.length();
if (length<=20){
return note+"\n"+"\n"+"\n";
}else if (length<=50){
return note+"\n"+"\n";
}else {
return note.substring(0,50)+"..."+"\n";
}
}
public static boolean isphotouri(String path){//判定是不是图片地址
if (path.length()>=10){
String str1=".jpg";
String str2=path.substring(path.length()-4,path.length());
if (str1.equals(str2)){
return true;
}else {
return false;
}
}else {
return false;
}
}
public static boolean isedittext_empty(String string){//判断是否为空
if (string.isEmpty()){
return true;
}else {
return false;
}
}
public static boolean isedittext_empty(MaterialEditText editText){//判断editext是否为空
if (editText.getText().toString().isEmpty()){
return true;
}else {
return false;
}
}
public static String getCreatetime(){//获取创建时间
Calendar calendar=Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
String year=String.valueOf(calendar.get(Calendar.YEAR));
String mounth=String.valueOf(calendar.get(Calendar.MONTH)+1);
String day=String.valueOf(calendar.get(Calendar.DATE));
String hour=String.valueOf(calendar.get(Calendar.HOUR_OF_DAY));
String minute=String.valueOf(calendar.get(Calendar.MINUTE));
return year+"-"+mounth+"-"+day;
}
public static int getTheYearoncalendar(){
Calendar calendar=Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
return calendar.get(Calendar.YEAR);
}
public static int getTheMonthoncalendar(){
Calendar calendar=Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
return calendar.get(Calendar.MONTH)+1;
}
public static List<String> removeDuplicate(List<String> list){//去除lis中的重复元素
List list1Temp=new ArrayList();
for (int i=0;i<list.size();i++){
if (!list1Temp.contains(list.get(i))){
list1Temp.add(list.get(i));
}
}
return list1Temp;
}
public static Noteinfo changefromNotebean(final NoteBean noteBean){
Noteinfo noteinfo=new Noteinfo();
String info,type,people,date,time,location,photo,createtime;
boolean isshow;
Long id;
id=noteBean.getId();
info=noteBean.getNoteinfo();
type=noteBean.getNotetype();
people=noteBean.getPeople();
date=noteBean.getDate();
time=noteBean.getTime();
location=noteBean.getLocation();
photo=noteBean.getPhotopath();
createtime=noteBean.getCreatetime();
isshow=noteBean.getIsshow();
noteinfo.setId(id);
noteinfo.setNoteinfo(info);
noteinfo.setNotetype(type);
noteinfo.setPeople(people);
noteinfo.setDate(date);
noteinfo.setTime(time);
noteinfo.setLocation(location);
noteinfo.setPhotopath(photo);
noteinfo.setCreatetime(createtime);
noteinfo.setIsshow(isshow);
return noteinfo;
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Bean/MessageEvent.java | app/src/main/java/zql/app_jinnang/Bean/MessageEvent.java | package zql.app_jinnang.Bean;
public class MessageEvent {
public final static int UPDATE_DATA=0;
public final static int UPDATA_COLOR=1;
private int messageevent;
public MessageEvent(int event){
this.messageevent=event;
}
public void setMessageevent(int messageevent) {
this.messageevent = messageevent;
}
public int getMessageevent() {
return messageevent;
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Bean/NoteBean.java | app/src/main/java/zql/app_jinnang/Bean/NoteBean.java | package zql.app_jinnang.Bean;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;
/**
* Created by 尽途 on 2018/4/27.
*/
@Entity
public class NoteBean{
@Id
private Long id;
private String noteinfo;
private String notetype;
private String people;
private String date;
private String time;
private String location;
private String photopath;
private Boolean isshow;
private String createtime;
@Generated(hash = 930099796)
public NoteBean(Long id, String noteinfo, String notetype, String people,
String date, String time, String location, String photopath,
Boolean isshow, String createtime) {
this.id = id;
this.noteinfo = noteinfo;
this.notetype = notetype;
this.people = people;
this.date = date;
this.time = time;
this.location = location;
this.photopath = photopath;
this.isshow = isshow;
this.createtime = createtime;
}
@Generated(hash = 451626881)
public NoteBean() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getNoteinfo() {
return this.noteinfo;
}
public void setNoteinfo(String noteinfo) {
this.noteinfo = noteinfo;
}
public String getNotetype() {
return this.notetype;
}
public void setNotetype(String notetype) {
this.notetype = notetype;
}
public String getPeople() {
return this.people;
}
public void setPeople(String people) {
this.people = people;
}
public String getDate() {
return this.date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return this.time;
}
public void setTime(String time) {
this.time = time;
}
public String getLocation() {
return this.location;
}
public void setLocation(String location) {
this.location = location;
}
public String getPhotopath() {
return this.photopath;
}
public void setPhotopath(String photopath) {
this.photopath = photopath;
}
public Boolean getIsshow() {
return this.isshow;
}
public void setIsshow(Boolean isshow) {
this.isshow = isshow;
}
public String getCreatetime() {
return this.createtime;
}
public void setCreatetime(String createtime) {
this.createtime = createtime;
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Service/DPCManager.java | app/src/main/java/zql/app_jinnang/Service/DPCManager.java | package zql.app_jinnang.Service;
import android.text.TextUtils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import cn.aigestudio.datepicker.bizs.calendars.DPCNCalendar;
import cn.aigestudio.datepicker.bizs.calendars.DPCalendar;
import cn.aigestudio.datepicker.bizs.calendars.DPUSCalendar;
import cn.aigestudio.datepicker.entities.DPInfo;
/**
* 日期管理器
* The manager of date picker.
*
* @author AigeStudio 2015-06-12
*/
public final class DPCManager {
private static final HashMap<Integer, HashMap<Integer, DPInfo[][]>> DATE_CACHE = new HashMap<>();
private static final HashMap<String, Set<String>> DECOR_CACHE_BG = new HashMap<>();
private static final HashMap<String, Set<String>> DECOR_CACHE_TL = new HashMap<>();
private static final HashMap<String, Set<String>> DECOR_CACHE_T = new HashMap<>();
private static final HashMap<String, Set<String>> DECOR_CACHE_TR = new HashMap<>();
private static final HashMap<String, Set<String>> DECOR_CACHE_L = new HashMap<>();
private static final HashMap<String, Set<String>> DECOR_CACHE_R = new HashMap<>();
private static DPCManager sManager;
private DPCalendar c;
private DPCManager() {
// 默认显示为中文日历
String locale = Locale.getDefault().getCountry().toLowerCase();
if (locale.equals("cn")) {
initCalendar(new DPCNCalendar());
} else {
initCalendar(new DPUSCalendar());
}
}
/**
* 获取月历管理器
* Get calendar manager
*
* @return 月历管理器
*/
public static DPCManager getInstance() {
if (null == sManager) {
sManager = new DPCManager();
}
return sManager;
}
/**
* 初始化日历对象
* <p/>
* Initialization Calendar
*
* @param c ...
*/
public void initCalendar(DPCalendar c) {
this.c = c;
}
/**
* 设置有背景标识物的日期
* <p/>
* Set date which has decor of background
*
* @param date 日期列表 List of date
*/
public void setDecorBG(List<String> date) {
setDecor(date, DECOR_CACHE_BG);
}
/**
* 设置左上角有标识物的日期
* <p/>
* Set date which has decor on Top left
*
* @param date 日期列表 List of date
*/
public void setDecorTL(List<String> date) {
setDecor(date, DECOR_CACHE_TL);
}
/**
* 设置顶部有标识物的日期
* <p/>
* Set date which has decor on Top
*
* @param date 日期列表 List of date
*/
public void setDecorT(List<String> date) {
setDecor(date, DECOR_CACHE_T);
}
/**
* 设置右上角有标识物的日期
* <p/>
* Set date which has decor on Top right
*
* @param date 日期列表 List of date
*/
public void setDecorTR(List<String> date) {
setDecor(date, DECOR_CACHE_TR);
}
/**
* 设置左边有标识物的日期
* <p/>
* Set date which has decor on left
*
* @param date 日期列表 List of date
*/
public void setDecorL(List<String> date) {
setDecor(date, DECOR_CACHE_L);
}
/**
* 设置右上角有标识物的日期
* <p/>
* Set date which has decor on right
*
* @param date 日期列表 List of date
*/
public void setDecorR(List<String> date) {
setDecor(date, DECOR_CACHE_R);
}
/**
* 获取指定年月的日历对象数组
*
* @param year 公历年
* @param month 公历月
* @return 日历对象数组 该数组长度恒为6x7 如果某个下标对应无数据则填充为null
*/
public DPInfo[][] obtainDPInfo(int year, int month) {
HashMap<Integer, DPInfo[][]> dataOfYear = DATE_CACHE.get(year);
if (null != dataOfYear && dataOfYear.size() != 0) {
DPInfo[][] dataOfMonth = dataOfYear.get(month);
if (dataOfMonth != null) {
return dataOfMonth;
}
dataOfMonth = buildDPInfo(year, month);
dataOfYear.put(month, dataOfMonth);
return dataOfMonth;
}
if (null == dataOfYear) dataOfYear = new HashMap<>();
DPInfo[][] dataOfMonth = buildDPInfo(year, month);
dataOfYear.put((month), dataOfMonth);
DATE_CACHE.put(year, dataOfYear);
return dataOfMonth;
}
private void setDecor(List<String> date, HashMap<String, Set<String>> cache) {
DATE_CACHE.clear();
DECOR_CACHE_BG.clear();
DECOR_CACHE_TL.clear();
DECOR_CACHE_T.clear();
DECOR_CACHE_TR.clear();
DECOR_CACHE_L.clear();
DECOR_CACHE_R.clear();
for (String str : date) {
int index = str.lastIndexOf("-");
String key = str.substring(0, index).replace("-", ":");
Set<String> days = cache.get(key);
if (null == days) {
days = new HashSet<>();
}
days.add(str.substring(index + 1, str.length()));
cache.put(key, days);
}
}
private DPInfo[][] buildDPInfo(int year, int month) {
DPInfo[][] info = new DPInfo[6][7];
String[][] strG = c.buildMonthG(year, month);
String[][] strF = c.buildMonthFestival(year, month);
Set<String> strHoliday = c.buildMonthHoliday(year, month);
Set<String> strWeekend = c.buildMonthWeekend(year, month);
Set<String> decorBG = DECOR_CACHE_BG.get(year + ":" + month);
Set<String> decorTL = DECOR_CACHE_TL.get(year + ":" + month);
Set<String> decorT = DECOR_CACHE_T.get(year + ":" + month);
Set<String> decorTR = DECOR_CACHE_TR.get(year + ":" + month);
Set<String> decorL = DECOR_CACHE_L.get(year + ":" + month);
Set<String> decorR = DECOR_CACHE_R.get(year + ":" + month);
for (int i = 0; i < info.length; i++) {
for (int j = 0; j < info[i].length; j++) {
DPInfo tmp = new DPInfo();
tmp.strG = strG[i][j];
if (c instanceof DPCNCalendar) {
tmp.strF = strF[i][j].replace("F", "");
} else {
tmp.strF = strF[i][j];
}
if (!TextUtils.isEmpty(tmp.strG) && strHoliday.contains(tmp.strG))
tmp.isHoliday = true;
if (!TextUtils.isEmpty(tmp.strG)) tmp.isToday =
c.isToday(year, month, Integer.valueOf(tmp.strG));
if (strWeekend.contains(tmp.strG)) tmp.isWeekend = true;
if (c instanceof DPCNCalendar) {
if (!TextUtils.isEmpty(tmp.strG)) tmp.isSolarTerms =
((DPCNCalendar) c).isSolarTerm(year, month, Integer.valueOf(tmp.strG));
if (!TextUtils.isEmpty(strF[i][j]) && strF[i][j].endsWith("F"))
tmp.isFestival = true;
if (!TextUtils.isEmpty(tmp.strG))
tmp.isDeferred = ((DPCNCalendar) c)
.isDeferred(year, month, Integer.valueOf(tmp.strG));
} else {
tmp.isFestival = !TextUtils.isEmpty(strF[i][j]);
}
if (null != decorBG && decorBG.contains(tmp.strG)) tmp.isDecorBG = true;
if (null != decorTL && decorTL.contains(tmp.strG)) tmp.isDecorTL = true;
if (null != decorT && decorT.contains(tmp.strG)) tmp.isDecorT = true;
if (null != decorTR && decorTR.contains(tmp.strG)) tmp.isDecorTR = true;
if (null != decorL && decorL.contains(tmp.strG)) tmp.isDecorL = true;
if (null != decorR && decorR.contains(tmp.strG)) tmp.isDecorR = true;
info[i][j] = tmp;
}
}
return info;
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Service/DatePicker.java | app/src/main/java/zql/app_jinnang/Service/DatePicker.java | package zql.app_jinnang.Service;
import android.content.Context;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.List;
import cn.aigestudio.datepicker.bizs.decors.DPDecor;
import cn.aigestudio.datepicker.bizs.languages.DPLManager;
import cn.aigestudio.datepicker.bizs.themes.DPTManager;
import cn.aigestudio.datepicker.cons.DPMode;
import cn.aigestudio.datepicker.utils.MeasureUtil;
import zql.app_jinnang.Service.MonthView;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
/**
* DatePicker///修改的源代码,解决的日历无法动态更新的问题
*
* @author AigeStudio 2015-06-29
*/
public class DatePicker extends LinearLayout {
private DPTManager mTManager;// 主题管理器
private DPLManager mLManager;// 语言管理器
private MonthView monthView;// 月视图
private TextView tvYear, tvMonth;// 年份 月份显示
private TextView tvEnsure;// 确定按钮显示
private OnDateSelectedListener onDateSelectedListener;// 日期多选后监听
/**
* 日期单选监听器
*/
public interface OnDatePickedListener {
void onDatePicked(String date);
}
/**
* 日期多选监听器
*/
public interface OnDateSelectedListener {
void onDateSelected(List<String> date);
}
public DatePicker(Context context) {
this(context, null);
}
public DatePicker(Context context, AttributeSet attrs) {
super(context, attrs);
mTManager = DPTManager.getInstance();
mLManager = DPLManager.getInstance();
// 设置排列方向为竖向
setOrientation(VERTICAL);
LayoutParams llParams =
new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
// 标题栏根布局
RelativeLayout rlTitle = new RelativeLayout(context);
rlTitle.setBackgroundColor(mTManager.colorTitleBG());
int rlTitlePadding = MeasureUtil.dp2px(context, 10);
rlTitle.setPadding(rlTitlePadding, rlTitlePadding, rlTitlePadding, rlTitlePadding);
// 周视图根布局
LinearLayout llWeek = new LinearLayout(context);
llWeek.setBackgroundColor(mTManager.colorTitleBG());
llWeek.setOrientation(HORIZONTAL);
int llWeekPadding = MeasureUtil.dp2px(context, 5);
llWeek.setPadding(0, llWeekPadding, 0, llWeekPadding);
LayoutParams lpWeek = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
lpWeek.weight = 1;
// 标题栏子元素布局参数
RelativeLayout.LayoutParams lpYear =
new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
lpYear.addRule(RelativeLayout.CENTER_VERTICAL);
RelativeLayout.LayoutParams lpMonth =
new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
lpMonth.addRule(RelativeLayout.CENTER_IN_PARENT);
RelativeLayout.LayoutParams lpEnsure =
new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
lpEnsure.addRule(RelativeLayout.CENTER_VERTICAL);
lpEnsure.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
// --------------------------------------------------------------------------------标题栏
// 年份显示
tvYear = new TextView(context);
tvYear.setText("2015");
tvYear.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
tvYear.setTextColor(mTManager.colorTitle());
// 月份显示
tvMonth = new TextView(context);
tvMonth.setText("六月");
tvMonth.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
tvMonth.setTextColor(mTManager.colorTitle());
// 确定显示
tvEnsure = new TextView(context);
tvEnsure.setText(mLManager.titleEnsure());
tvEnsure.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
tvEnsure.setTextColor(mTManager.colorTitle());
tvEnsure.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (null != onDateSelectedListener) {
onDateSelectedListener.onDateSelected(monthView.getDateSelected());
}
}
});
rlTitle.addView(tvYear, lpYear);
rlTitle.addView(tvMonth, lpMonth);
rlTitle.addView(tvEnsure, lpEnsure);
addView(rlTitle, llParams);
// --------------------------------------------------------------------------------周视图
for (int i = 0; i < mLManager.titleWeek().length; i++) {
TextView tvWeek = new TextView(context);
tvWeek.setText(mLManager.titleWeek()[i]);
tvWeek.setGravity(Gravity.CENTER);
tvWeek.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
tvWeek.setTextColor(mTManager.colorTitle());
llWeek.addView(tvWeek, lpWeek);
}
addView(llWeek, llParams);
// ------------------------------------------------------------------------------------月视图
monthView = new MonthView(context);
monthView.setOnDateChangeListener(new MonthView.OnDateChangeListener() {
@Override
public void onMonthChange(int month) {
tvMonth.setText(mLManager.titleMonth()[month - 1]);
}
@Override
public void onYearChange(int year) {
String tmp = String.valueOf(year);
if (tmp.startsWith("-")) {
tmp = tmp.replace("-", mLManager.titleBC());
}
tvYear.setText(tmp);
}
});
addView(monthView, llParams);
}
/**
* 设置初始化年月日期
*
* @param year ...
* @param month ...
*/
public void setDate(int year, int month) {
if (month < 1) {
month = 1;
}
if (month > 12) {
month = 12;
}
monthView.setDate(year, month);
}
public void setDPDecor(DPDecor decor) {
monthView.setDPDecor(decor);
}
/**
* 设置日期选择模式
*
* @param mode ...
*/
public void setMode(DPMode mode) {
if (mode != DPMode.MULTIPLE) {
tvEnsure.setVisibility(GONE);
}
monthView.setDPMode(mode);
}
public void setFestivalDisplay(boolean isFestivalDisplay) {
monthView.setFestivalDisplay(isFestivalDisplay);
}
public void setTodayDisplay(boolean isTodayDisplay) {
monthView.setTodayDisplay(isTodayDisplay);
}
public void setHolidayDisplay(boolean isHolidayDisplay) {
monthView.setHolidayDisplay(isHolidayDisplay);
}
public void setDeferredDisplay(boolean isDeferredDisplay) {
monthView.setDeferredDisplay(isDeferredDisplay);
}
/**
* 设置单选监听器
*
* @param onDatePickedListener ...
*/
public void setOnDatePickedListener(OnDatePickedListener onDatePickedListener) {
if (monthView.getDPMode() != DPMode.SINGLE) {
throw new RuntimeException(
"Current DPMode does not SINGLE! Please call setMode set DPMode to SINGLE!");
}
monthView.setOnDatePickedListener((OnDatePickedListener) onDatePickedListener);
}
/**
* 设置多选监听器
*
* @param onDateSelectedListener ...
*/
public void setOnDateSelectedListener(OnDateSelectedListener onDateSelectedListener) {
if (monthView.getDPMode() != DPMode.MULTIPLE) {
throw new RuntimeException(
"Current DPMode does not MULTIPLE! Please call setMode set DPMode to MULTIPLE!");
}
this.onDateSelectedListener = onDateSelectedListener;
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Service/MonthView.java | app/src/main/java/zql/app_jinnang/Service/MonthView.java | package zql.app_jinnang.Service;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.os.Build;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import zql.app_jinnang.Service.DPCManager;
import cn.aigestudio.datepicker.bizs.decors.DPDecor;
import cn.aigestudio.datepicker.bizs.themes.DPTManager;
import cn.aigestudio.datepicker.cons.DPMode;
import cn.aigestudio.datepicker.entities.DPInfo;
import zql.app_jinnang.Service.DatePicker;
/**
* MonthView
*
* @author AigeStudio 2015-06-29
*/
public class MonthView extends View {
private final Region[][] MONTH_REGIONS_4 = new Region[4][7];
private final Region[][] MONTH_REGIONS_5 = new Region[5][7];
private final Region[][] MONTH_REGIONS_6 = new Region[6][7];
private final DPInfo[][] INFO_4 = new DPInfo[4][7];
private final DPInfo[][] INFO_5 = new DPInfo[5][7];
private final DPInfo[][] INFO_6 = new DPInfo[6][7];
private final Map<String, List<Region>> REGION_SELECTED = new HashMap<>();
private DPCManager mCManager = DPCManager.getInstance();
private DPTManager mTManager = DPTManager.getInstance();
protected Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG |
Paint.LINEAR_TEXT_FLAG);
private Scroller mScroller;
private DecelerateInterpolator decelerateInterpolator = new DecelerateInterpolator();
private AccelerateInterpolator accelerateInterpolator = new AccelerateInterpolator();
private OnDateChangeListener onDateChangeListener;
private DatePicker.OnDatePickedListener onDatePickedListener;
private ScaleAnimationListener scaleAnimationListener;
private DPMode mDPMode = DPMode.MULTIPLE;
private SlideMode mSlideMode;
private DPDecor mDPDecor;
private int circleRadius;
private int indexYear, indexMonth;
private int centerYear, centerMonth;
private int leftYear, leftMonth;
private int rightYear, rightMonth;
private int topYear, topMonth;
private int bottomYear, bottomMonth;
private int width, height;
private int sizeDecor, sizeDecor2x, sizeDecor3x;
private int lastPointX, lastPointY;
private int lastMoveX, lastMoveY;
private int criticalWidth, criticalHeight;
private int animZoomOut1, animZoomIn1, animZoomOut2;
private float sizeTextGregorian, sizeTextFestival;
private float offsetYFestival1, offsetYFestival2;
private boolean isNewEvent,
isFestivalDisplay = true,
isHolidayDisplay = true,
isTodayDisplay = true,
isDeferredDisplay = true;
private Map<String, BGCircle> cirApr = new HashMap<>();
private Map<String, BGCircle> cirDpr = new HashMap<>();
private List<String> dateSelected = new ArrayList<>();
public MonthView(Context context) {
super(context);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
scaleAnimationListener = new ScaleAnimationListener();
}
mScroller = new Scroller(context);
mPaint.setTextAlign(Paint.Align.CENTER);
}
@Override
protected Parcelable onSaveInstanceState() {
return super.onSaveInstanceState();
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
super.onRestoreInstanceState(state);
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
invalidate();
} else {
requestLayout();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mScroller.forceFinished(true);
mSlideMode = null;
isNewEvent = true;
lastPointX = (int) event.getX();
lastPointY = (int) event.getY();
break;
case MotionEvent.ACTION_MOVE:
if (isNewEvent) {
if (Math.abs(lastPointX - event.getX()) > 100) {
mSlideMode = SlideMode.HOR;
isNewEvent = false;
} else if (Math.abs(lastPointY - event.getY()) > 50) {
mSlideMode = SlideMode.VER;
isNewEvent = false;
}
}
if (mSlideMode == SlideMode.HOR) {
int totalMoveX = (int) (lastPointX - event.getX()) + lastMoveX;
smoothScrollTo(totalMoveX, indexYear * height);
} else if (mSlideMode == SlideMode.VER) {
int totalMoveY = (int) (lastPointY - event.getY()) + lastMoveY;
smoothScrollTo(width * indexMonth, totalMoveY);
}
break;
case MotionEvent.ACTION_UP:
if (mSlideMode == SlideMode.VER) {
if (Math.abs(lastPointY - event.getY()) > 25) {
if (lastPointY < event.getY()) {
if (Math.abs(lastPointY - event.getY()) >= criticalHeight) {
indexYear--;
centerYear = centerYear - 1;
}
} else if (lastPointY > event.getY()) {
if (Math.abs(lastPointY - event.getY()) >= criticalHeight) {
indexYear++;
centerYear = centerYear + 1;
}
}
buildRegion();
computeDate();
smoothScrollTo(width * indexMonth, height * indexYear);
lastMoveY = height * indexYear;
} else {
defineRegion((int) event.getX(), (int) event.getY());
}
} else if (mSlideMode == SlideMode.HOR) {
if (Math.abs(lastPointX - event.getX()) > 25) {
if (lastPointX > event.getX() &&
Math.abs(lastPointX - event.getX()) >= criticalWidth) {
indexMonth++;
centerMonth = (centerMonth + 1) % 13;
if (centerMonth == 0) {
centerMonth = 1;
centerYear++;
}
} else if (lastPointX < event.getX() &&
Math.abs(lastPointX - event.getX()) >= criticalWidth) {
indexMonth--;
centerMonth = (centerMonth - 1) % 12;
if (centerMonth == 0) {
centerMonth = 12;
centerYear--;
}
}
buildRegion();
computeDate();
smoothScrollTo(width * indexMonth, indexYear * height);
lastMoveX = width * indexMonth;
} else {
defineRegion((int) event.getX(), (int) event.getY());
}
} else {
defineRegion((int) event.getX(), (int) event.getY());
}
break;
}
return true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
setMeasuredDimension(measureWidth, (int) (measureWidth * 6F / 7F));
}
@Override
protected void onSizeChanged(int w, int h, int oldW, int oldH) {
width = w;
height = h;
criticalWidth = (int) (1F / 5F * width);
criticalHeight = (int) (1F / 5F * height);
int cellW = (int) (w / 7F);
int cellH4 = (int) (h / 4F);
int cellH5 = (int) (h / 5F);
int cellH6 = (int) (h / 6F);
circleRadius = cellW;
animZoomOut1 = (int) (cellW * 1.2F);
animZoomIn1 = (int) (cellW * 0.8F);
animZoomOut2 = (int) (cellW * 1.1F);
sizeDecor = (int) (cellW / 3F);
sizeDecor2x = sizeDecor * 2;
sizeDecor3x = sizeDecor * 3;
sizeTextGregorian = width / 20F;
mPaint.setTextSize(sizeTextGregorian);
float heightGregorian = mPaint.getFontMetrics().bottom - mPaint.getFontMetrics().top;
sizeTextFestival = width / 40F;
mPaint.setTextSize(sizeTextFestival);
float heightFestival = mPaint.getFontMetrics().bottom - mPaint.getFontMetrics().top;
offsetYFestival1 = (((Math.abs(mPaint.ascent() + mPaint.descent())) / 2F) +
heightFestival / 2F + heightGregorian / 2F) / 2F;
offsetYFestival2 = offsetYFestival1 * 2F;
for (int i = 0; i < MONTH_REGIONS_4.length; i++) {
for (int j = 0; j < MONTH_REGIONS_4[i].length; j++) {
Region region = new Region();
region.set((j * cellW), (i * cellH4), cellW + (j * cellW),
cellW + (i * cellH4));
MONTH_REGIONS_4[i][j] = region;
}
}
for (int i = 0; i < MONTH_REGIONS_5.length; i++) {
for (int j = 0; j < MONTH_REGIONS_5[i].length; j++) {
Region region = new Region();
region.set((j * cellW), (i * cellH5), cellW + (j * cellW),
cellW + (i * cellH5));
MONTH_REGIONS_5[i][j] = region;
}
}
for (int i = 0; i < MONTH_REGIONS_6.length; i++) {
for (int j = 0; j < MONTH_REGIONS_6[i].length; j++) {
Region region = new Region();
region.set((j * cellW), (i * cellH6), cellW + (j * cellW),
cellW + (i * cellH6));
MONTH_REGIONS_6[i][j] = region;
}
}
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(mTManager.colorBG());
draw(canvas, width * indexMonth, (indexYear - 1) * height, topYear, topMonth);
draw(canvas, width * (indexMonth - 1), height * indexYear, leftYear, leftMonth);
draw(canvas, width * indexMonth, indexYear * height, centerYear, centerMonth);
draw(canvas, width * (indexMonth + 1), height * indexYear, rightYear, rightMonth);
draw(canvas, width * indexMonth, (indexYear + 1) * height, bottomYear, bottomMonth);
drawBGCircle(canvas);
}
private void drawBGCircle(Canvas canvas) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
for (String s : cirDpr.keySet()) {
BGCircle circle = cirDpr.get(s);
drawBGCircle(canvas, circle);
}
}
for (String s : cirApr.keySet()) {
BGCircle circle = cirApr.get(s);
drawBGCircle(canvas, circle);
}
}
private void drawBGCircle(Canvas canvas, BGCircle circle) {
canvas.save();
canvas.translate(circle.getX() - circle.getRadius() / 2,
circle.getY() - circle.getRadius() / 2);
circle.getShape().getShape().resize(circle.getRadius(), circle.getRadius());
circle.getShape().draw(canvas);
canvas.restore();
}
private void draw(Canvas canvas, int x, int y, int year, int month) {
canvas.save();
canvas.translate(x, y);
DPInfo[][] info = mCManager.obtainDPInfo(year, month);
DPInfo[][] result;
Region[][] tmp;
if (TextUtils.isEmpty(info[4][0].strG)) {
tmp = MONTH_REGIONS_4;
arrayClear(INFO_4);
result = arrayCopy(info, INFO_4);
} else if (TextUtils.isEmpty(info[5][0].strG)) {
tmp = MONTH_REGIONS_5;
arrayClear(INFO_5);
result = arrayCopy(info, INFO_5);
} else {
tmp = MONTH_REGIONS_6;
arrayClear(INFO_6);
result = arrayCopy(info, INFO_6);
}
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
draw(canvas, tmp[i][j].getBounds(), info[i][j]);
}
}
canvas.restore();
}
private void draw(Canvas canvas, Rect rect, DPInfo info) {
drawBG(canvas, rect, info);
drawGregorian(canvas, rect, info.strG, info.isWeekend);
if (isFestivalDisplay) drawFestival(canvas, rect, info.strF, info.isFestival);
drawDecor(canvas, rect, info);
}
private void drawBG(Canvas canvas, Rect rect, DPInfo info) {
if (null != mDPDecor && info.isDecorBG) {
mDPDecor.drawDecorBG(canvas, rect, mPaint,
centerYear + "-" + centerMonth + "-" + info.strG);
}
if (info.isToday && isTodayDisplay) {
drawBGToday(canvas, rect);
} else {
if (isHolidayDisplay) drawBGHoliday(canvas, rect, info.isHoliday);
if (isDeferredDisplay) drawBGDeferred(canvas, rect, info.isDeferred);
}
}
private void drawBGToday(Canvas canvas, Rect rect) {
mPaint.setColor(mTManager.colorToday());
canvas.drawCircle(rect.centerX(), rect.centerY(), circleRadius / 2F, mPaint);
}
private void drawBGHoliday(Canvas canvas, Rect rect, boolean isHoliday) {
mPaint.setColor(mTManager.colorHoliday());
if (isHoliday) canvas.drawCircle(rect.centerX(), rect.centerY(), circleRadius / 2F, mPaint);
}
private void drawBGDeferred(Canvas canvas, Rect rect, boolean isDeferred) {
mPaint.setColor(mTManager.colorDeferred());
if (isDeferred)
canvas.drawCircle(rect.centerX(), rect.centerY(), circleRadius / 2F, mPaint);
}
private void drawGregorian(Canvas canvas, Rect rect, String str, boolean isWeekend) {
mPaint.setTextSize(sizeTextGregorian);
if (isWeekend) {
mPaint.setColor(mTManager.colorWeekend());
} else {
mPaint.setColor(mTManager.colorG());
}
float y = rect.centerY();
if (!isFestivalDisplay)
y = rect.centerY() + Math.abs(mPaint.ascent()) - (mPaint.descent() - mPaint.ascent()) / 2F;
canvas.drawText(str, rect.centerX(), y, mPaint);
}
private void drawFestival(Canvas canvas, Rect rect, String str, boolean isFestival) {
mPaint.setTextSize(sizeTextFestival);
if (isFestival) {
mPaint.setColor(mTManager.colorF());
} else {
mPaint.setColor(mTManager.colorL());
}
if (str.contains("&")) {
String[] s = str.split("&");
String str1 = s[0];
if (mPaint.measureText(str1) > rect.width()) {
float ch = mPaint.measureText(str1, 0, 1);
int length = (int) (rect.width() / ch);
canvas.drawText(str1.substring(0, length), rect.centerX(),
rect.centerY() + offsetYFestival1, mPaint);
canvas.drawText(str1.substring(length), rect.centerX(),
rect.centerY() + offsetYFestival2, mPaint);
} else {
canvas.drawText(str1, rect.centerX(),
rect.centerY() + offsetYFestival1, mPaint);
String str2 = s[1];
if (mPaint.measureText(str2) < rect.width()) {
canvas.drawText(str2, rect.centerX(),
rect.centerY() + offsetYFestival2, mPaint);
}
}
} else {
if (mPaint.measureText(str) > rect.width()) {
float ch = 0.0F;
for (char c : str.toCharArray()) {
float tmp = mPaint.measureText(String.valueOf(c));
if (tmp > ch) {
ch = tmp;
}
}
int length = (int) (rect.width() / ch);
canvas.drawText(str.substring(0, length), rect.centerX(),
rect.centerY() + offsetYFestival1, mPaint);
canvas.drawText(str.substring(length), rect.centerX(),
rect.centerY() + offsetYFestival2, mPaint);
} else {
canvas.drawText(str, rect.centerX(),
rect.centerY() + offsetYFestival1, mPaint);
}
}
}
private void drawDecor(Canvas canvas, Rect rect, DPInfo info) {
if (!TextUtils.isEmpty(info.strG)) {
String data = centerYear + "-" + centerMonth + "-" + info.strG;
if (null != mDPDecor && info.isDecorTL) {
canvas.save();
canvas.clipRect(rect.left, rect.top, rect.left + sizeDecor, rect.top + sizeDecor);
mDPDecor.drawDecorTL(canvas, canvas.getClipBounds(), mPaint, data);
canvas.restore();
}
if (null != mDPDecor && info.isDecorT) {
canvas.save();
canvas.clipRect(rect.left + sizeDecor, rect.top, rect.left + sizeDecor2x,
rect.top + sizeDecor);
mDPDecor.drawDecorT(canvas, canvas.getClipBounds(), mPaint, data);
canvas.restore();
}
if (null != mDPDecor && info.isDecorTR) {
canvas.save();
canvas.clipRect(rect.left + sizeDecor2x, rect.top, rect.left + sizeDecor3x,
rect.top + sizeDecor);
mDPDecor.drawDecorTR(canvas, canvas.getClipBounds(), mPaint, data);
canvas.restore();
}
if (null != mDPDecor && info.isDecorL) {
canvas.save();
canvas.clipRect(rect.left, rect.top + sizeDecor, rect.left + sizeDecor,
rect.top + sizeDecor2x);
mDPDecor.drawDecorL(canvas, canvas.getClipBounds(), mPaint, data);
canvas.restore();
}
if (null != mDPDecor && info.isDecorR) {
canvas.save();
canvas.clipRect(rect.left + sizeDecor2x, rect.top + sizeDecor,
rect.left + sizeDecor3x, rect.top + sizeDecor2x);
mDPDecor.drawDecorR(canvas, canvas.getClipBounds(), mPaint, data);
canvas.restore();
}
}
}
List<String> getDateSelected() {
return dateSelected;
}
void setOnDateChangeListener(OnDateChangeListener onDateChangeListener) {
this.onDateChangeListener = onDateChangeListener;
}
public void setOnDatePickedListener(DatePicker.OnDatePickedListener onDatePickedListener) {
this.onDatePickedListener = onDatePickedListener;
}
void setDPMode(DPMode mode) {
this.mDPMode = mode;
}
void setDPDecor(DPDecor decor) {
this.mDPDecor = decor;
}
DPMode getDPMode() {
return mDPMode;
}
void setDate(int year, int month) {
centerYear = year;
centerMonth = month;
indexYear = 0;
indexMonth = 0;
buildRegion();
computeDate();
requestLayout();
invalidate();
}
void setFestivalDisplay(boolean isFestivalDisplay) {
this.isFestivalDisplay = isFestivalDisplay;
}
void setTodayDisplay(boolean isTodayDisplay) {
this.isTodayDisplay = isTodayDisplay;
}
void setHolidayDisplay(boolean isHolidayDisplay) {
this.isHolidayDisplay = isHolidayDisplay;
}
void setDeferredDisplay(boolean isDeferredDisplay) {
this.isDeferredDisplay = isDeferredDisplay;
}
private void smoothScrollTo(int fx, int fy) {
int dx = fx - mScroller.getFinalX();
int dy = fy - mScroller.getFinalY();
smoothScrollBy(dx, dy);
}
private void smoothScrollBy(int dx, int dy) {
mScroller.startScroll(mScroller.getFinalX(), mScroller.getFinalY(), dx, dy, 500);
invalidate();
}
private BGCircle createCircle(float x, float y) {
OvalShape circle = new OvalShape();
circle.resize(0, 0);
ShapeDrawable drawable = new ShapeDrawable(circle);
BGCircle circle1 = new BGCircle(drawable);
circle1.setX(x);
circle1.setY(y);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
circle1.setRadius(circleRadius);
}
drawable.getPaint().setColor(mTManager.colorBGCircle());
return circle1;
}
private void buildRegion() {
String key = indexYear + ":" + indexMonth;
if (!REGION_SELECTED.containsKey(key)) {
REGION_SELECTED.put(key, new ArrayList<Region>());
}
}
private void arrayClear(DPInfo[][] info) {
for (DPInfo[] anInfo : info) {
Arrays.fill(anInfo, null);
}
}
private DPInfo[][] arrayCopy(DPInfo[][] src, DPInfo[][] dst) {
for (int i = 0; i < dst.length; i++) {
System.arraycopy(src[i], 0, dst[i], 0, dst[i].length);
}
return dst;
}
private void defineRegion(int x, int y) {
DPInfo[][] info = mCManager.obtainDPInfo(centerYear, centerMonth);
Region[][] tmp;
if (TextUtils.isEmpty(info[4][0].strG)) {
tmp = MONTH_REGIONS_4;
} else if (TextUtils.isEmpty(info[5][0].strG)) {
tmp = MONTH_REGIONS_5;
} else {
tmp = MONTH_REGIONS_6;
}
for (int i = 0; i < tmp.length; i++) {
for (int j = 0; j < tmp[i].length; j++) {
Region region = tmp[i][j];
if (TextUtils.isEmpty(mCManager.obtainDPInfo(centerYear, centerMonth)[i][j].strG)) {
continue;
}
if (region.contains(x, y)) {
List<Region> regions = REGION_SELECTED.get(indexYear + ":" + indexMonth);
if (mDPMode == DPMode.SINGLE) {
cirApr.clear();
regions.add(region);
final String date = centerYear + "-" + centerMonth + "-" +
mCManager.obtainDPInfo(centerYear, centerMonth)[i][j].strG;
BGCircle circle = createCircle(
region.getBounds().centerX() + indexMonth * width,
region.getBounds().centerY() + indexYear * height);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ValueAnimator animScale1 =
ObjectAnimator.ofInt(circle, "radius", 0, animZoomOut1);
animScale1.setDuration(250);
animScale1.setInterpolator(decelerateInterpolator);
animScale1.addUpdateListener(scaleAnimationListener);
ValueAnimator animScale2 =
ObjectAnimator.ofInt(circle, "radius", animZoomOut1, animZoomIn1);
animScale2.setDuration(100);
animScale2.setInterpolator(accelerateInterpolator);
animScale2.addUpdateListener(scaleAnimationListener);
ValueAnimator animScale3 =
ObjectAnimator.ofInt(circle, "radius", animZoomIn1, animZoomOut2);
animScale3.setDuration(150);
animScale3.setInterpolator(decelerateInterpolator);
animScale3.addUpdateListener(scaleAnimationListener);
ValueAnimator animScale4 =
ObjectAnimator.ofInt(circle, "radius", animZoomOut2, circleRadius);
animScale4.setDuration(50);
animScale4.setInterpolator(accelerateInterpolator);
animScale4.addUpdateListener(scaleAnimationListener);
AnimatorSet animSet = new AnimatorSet();
animSet.playSequentially(animScale1, animScale2, animScale3, animScale4);
animSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (null != onDatePickedListener) {
onDatePickedListener.onDatePicked(date);
}
}
});
animSet.start();
}
cirApr.put(date, circle);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
invalidate();
if (null != onDatePickedListener) {
onDatePickedListener.onDatePicked(date);
}
}
} else if (mDPMode == DPMode.MULTIPLE) {
if (regions.contains(region)) {
regions.remove(region);
} else {
regions.add(region);
}
final String date = centerYear + "-" + centerMonth + "-" +
mCManager.obtainDPInfo(centerYear, centerMonth)[i][j].strG;
if (dateSelected.contains(date)) {
dateSelected.remove(date);
BGCircle circle = cirApr.get(date);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ValueAnimator animScale = ObjectAnimator.ofInt(circle, "radius", circleRadius, 0);
animScale.setDuration(250);
animScale.setInterpolator(accelerateInterpolator);
animScale.addUpdateListener(scaleAnimationListener);
animScale.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
cirDpr.remove(date);
}
});
animScale.start();
cirDpr.put(date, circle);
}
cirApr.remove(date);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
invalidate();
}
} else {
dateSelected.add(date);
BGCircle circle = createCircle(
region.getBounds().centerX() + indexMonth * width,
region.getBounds().centerY() + indexYear * height);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ValueAnimator animScale1 =
ObjectAnimator.ofInt(circle, "radius", 0, animZoomOut1);
animScale1.setDuration(250);
animScale1.setInterpolator(decelerateInterpolator);
animScale1.addUpdateListener(scaleAnimationListener);
ValueAnimator animScale2 =
ObjectAnimator.ofInt(circle, "radius", animZoomOut1, animZoomIn1);
animScale2.setDuration(100);
animScale2.setInterpolator(accelerateInterpolator);
animScale2.addUpdateListener(scaleAnimationListener);
ValueAnimator animScale3 =
ObjectAnimator.ofInt(circle, "radius", animZoomIn1, animZoomOut2);
animScale3.setDuration(150);
animScale3.setInterpolator(decelerateInterpolator);
animScale3.addUpdateListener(scaleAnimationListener);
ValueAnimator animScale4 =
ObjectAnimator.ofInt(circle, "radius", animZoomOut2, circleRadius);
animScale4.setDuration(50);
animScale4.setInterpolator(accelerateInterpolator);
animScale4.addUpdateListener(scaleAnimationListener);
AnimatorSet animSet = new AnimatorSet();
animSet.playSequentially(animScale1, animScale2, animScale3, animScale4);
animSet.start();
}
cirApr.put(date, circle);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
invalidate();
}
}
} else if (mDPMode == DPMode.NONE) {
if (regions.contains(region)) {
regions.remove(region);
} else {
regions.add(region);
}
final String date = centerYear + "-" + centerMonth + "-" +
mCManager.obtainDPInfo(centerYear, centerMonth)[i][j].strG;
if (dateSelected.contains(date)) {
dateSelected.remove(date);
} else {
dateSelected.add(date);
}
}
}
}
}
}
private void computeDate() {
rightYear = leftYear = centerYear;
topYear = centerYear - 1;
bottomYear = centerYear + 1;
topMonth = centerMonth;
bottomMonth = centerMonth;
rightMonth = centerMonth + 1;
leftMonth = centerMonth - 1;
if (centerMonth == 12) {
rightYear++;
rightMonth = 1;
}
if (centerMonth == 1) {
leftYear--;
leftMonth = 12;
}
if (null != onDateChangeListener) {
onDateChangeListener.onYearChange(centerYear);
onDateChangeListener.onMonthChange(centerMonth);
}
}
interface OnDateChangeListener {
void onMonthChange(int month);
void onYearChange(int year);
}
private enum SlideMode {
VER,
HOR
}
private class BGCircle {
private float x, y;
private int radius;
private ShapeDrawable shape;
public BGCircle(ShapeDrawable shape) {
this.shape = shape;
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public ShapeDrawable getShape() {
return shape;
}
public void setShape(ShapeDrawable shape) {
this.shape = shape;
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private class ScaleAnimationListener implements ValueAnimator.AnimatorUpdateListener {
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | true |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Service/PasswordView/KeynumberDialog.java | app/src/main/java/zql/app_jinnang/Service/PasswordView/KeynumberDialog.java | package zql.app_jinnang.Service.PasswordView;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class KeynumberDialog extends View{
private Context mcontext;
private Paint paint;
private float mWidth,mHeight;
private float mRectWidth,mRectHeigt;
private OnNumberClickListener onNumberClickListener;
private float x1,y1,x2,y2;
private float[] xs=new float[3];
private float[] ys=new float[4];
private float cx,cy;
private String showNumber;
private String[] password=new String[6];
private int type=1;
private int sum=0;
public KeynumberDialog(Context context){
super(context);
}
public KeynumberDialog(Context context, AttributeSet att){
super(context,att);
}
public KeynumberDialog(Context context,AttributeSet att,int defStyleAttr){
super(context,att,defStyleAttr);
}
public OnNumberClickListener getOnNumberClickListener() {
return onNumberClickListener;
}
public void setOnNumberClickListener(OnNumberClickListener onNumberClickListener) {
this.onNumberClickListener = onNumberClickListener;
}
@Override
protected void onDraw(Canvas canvas) {
initData();
drawKeyboard(canvas);
if (type==0){
paint.setColor(Color.GRAY);
canvas.drawRoundRect(new RectF(x1,y1,x2,y2),10,10,paint);
paint.setColor(Color.BLACK);
canvas.drawText(showNumber,cx,cy,paint);
}
if (type==1){
paint.setColor(Color.WHITE);
canvas.drawRoundRect(new RectF(x1,y1,x2,y2),0,0,paint);
}
super.onDraw(canvas);
}
private void initData(){
paint=new Paint(Paint.ANTI_ALIAS_FLAG);
mWidth=getWidth();
mHeight=getHeight();
mRectWidth=(mWidth-60)/3;
mRectHeigt=(mHeight-80)/4;
xs[0]=mRectWidth/2+3;
xs[1]=mRectWidth+23+mRectWidth/2;
xs[2]=mRectWidth*2+43+mRectWidth/2;
ys[0]=mRectHeigt/2+15;
ys[1]=mRectHeigt+35+mRectHeigt/2;
ys[2]=mRectHeigt*2+55+mRectHeigt/2;
ys[3]=mRectHeigt*3+75+mRectHeigt/2;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x=event.getX();
float y=event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
handleDown(x,y);
return true;
case MotionEvent.ACTION_UP:
handleup();
if (showNumber.equals("<")){
onNumberClickListener.onNumberDelete();
}else {
onNumberClickListener.onNumberReturn(showNumber);
}
return true;
case MotionEvent.ACTION_CANCEL:
return true;
default:
break;
}
return super.onTouchEvent(event);
}
private void drawKeyboard(Canvas canvas){
paint.setColor(Color.WHITE);
//第一列
canvas.drawRoundRect(new RectF(10,10,mRectWidth+10,mRectHeigt+10),10,10,paint);
canvas.drawRoundRect(new RectF(30+mRectWidth,10,mRectWidth*2+30,mRectHeigt+10),10,10,paint);
canvas.drawRoundRect(new RectF(50+2*mRectWidth,10,mRectWidth*3+50,mRectHeigt+10),10,10,paint);
//第2列
canvas.drawRoundRect(new RectF(10,30+mRectHeigt,mRectWidth+10,mRectHeigt*2+30),10,10,paint);
canvas.drawRoundRect(new RectF(30+mRectWidth,30+mRectHeigt,mRectWidth*2+30,mRectHeigt*2+30),10,10,paint);
canvas.drawRoundRect(new RectF(50+2*mRectWidth,30+mRectHeigt,mRectWidth*3+50,mRectHeigt*2+30),10,10,paint);
//第3列
canvas.drawRoundRect(new RectF(10,50+mRectHeigt*2,mRectWidth+10,mRectHeigt*3+50),10,10,paint);
canvas.drawRoundRect(new RectF(30+mRectWidth,50+mRectHeigt*2,mRectWidth*2+30,mRectHeigt*3+50),10,10,paint);
canvas.drawRoundRect(new RectF(50+2*mRectWidth,50+mRectHeigt*2,mRectWidth*3+50,mRectHeigt*3+50),10,10,paint);
//第4列
canvas.drawRoundRect(new RectF(10,70+mRectHeigt*3,mRectWidth+10,mRectHeigt*4+70),10,10,paint);
canvas.drawRoundRect(new RectF(30+mRectWidth,70+mRectHeigt*3,mRectWidth*2+30,mRectHeigt*4+70),10,10,paint);
canvas.drawRoundRect(new RectF(50+2*mRectWidth,70+mRectHeigt*3,mRectWidth*3+50,mRectHeigt*4+70),10,10,paint);
paint.setColor(Color.BLACK);
paint.setTextSize(60);
paint.setStrokeWidth(2);
//第一排
canvas.drawText("1",xs[0],ys[0],paint);
canvas.drawText("2",xs[1],ys[0],paint);
canvas.drawText("3",xs[2],ys[0],paint);
//第2排
canvas.drawText("4",xs[0],ys[1],paint);
canvas.drawText("5",xs[1],ys[1],paint);
canvas.drawText("6",xs[2],ys[1],paint);
//第一排
canvas.drawText("7",xs[0],ys[2],paint);
canvas.drawText("8",xs[1],ys[2],paint);
canvas.drawText("9",xs[2],ys[2],paint);
//第一排
canvas.drawText("/",xs[0],ys[3],paint);
canvas.drawText("0",xs[1],ys[3],paint);
canvas.drawText("<",xs[2],ys[3],paint);
}
private void handleDown(float x,float y){
if (x>=10&&x<=mRectHeigt+20){
if (y>10&&y<mRectHeigt+20){//选中1
x1=10;
y1=10;
x2=mRectWidth+10;
y2=mRectHeigt+10;
cx=xs[0];
cy=ys[0];
showNumber="1";
}else if (y>20+mRectHeigt&&y<mRectHeigt*2+40){//选中4
x1=10;
y1=30+mRectHeigt;
x2=mRectWidth+10;
y2=mRectHeigt*2+30;
cx=xs[0];
cy=ys[1];
showNumber="4";
}else if (y>mRectHeigt*2+40&&y<mRectHeigt*3+60){//选中7
x1=10;
y1=50+mRectHeigt*2;
x2=mRectWidth+10;
y2=mRectHeigt*3+50;
cx=xs[0];
cy=ys[2];
showNumber="7";
}else if (y>mRectHeigt*3+60&&y<mRectHeigt*4+80){//选中/
x1=10;
y1=70+mRectHeigt*3;
x2=mRectWidth+10;
y2=mRectHeigt*4+70;
cx=xs[0];
cy=ys[3];
showNumber="/";
}
}else if (x>mRectWidth+20&&x<mRectWidth*2+40){
if (y>10&&y<mRectHeigt+20){//选中2
x1=30+mRectWidth;
y1=10;
x2=mRectWidth*2+30;
y2=mRectHeigt+10;
cx=xs[1];
cy=ys[0];
showNumber="2";
}else if (y>20+mRectHeigt&&y<mRectHeigt*2+40){//选中5
x1=30+mRectWidth;
y1=30+mRectHeigt;
x2=mRectWidth*2+30;
y2=mRectHeigt*2+30;
cx=xs[1];
cy=ys[1];
showNumber="5";
}else if (y>mRectHeigt*2+40&&y<mRectHeigt*3+60){//选中8
x1=30+mRectWidth;
y1=50+mRectHeigt*2;
x2=mRectWidth*2+30;
y2=mRectHeigt*3+50;
cx=xs[1];
cy=ys[2];
showNumber="8";
}else if (y>mRectHeigt*3+60&&y<mRectHeigt*4+80){//选中0
x1=30+mRectWidth;
y1=70+mRectHeigt*3;
x2=mRectWidth*2+30;
y2=mRectHeigt*4+70;
cx=xs[1];
cy=ys[3];
showNumber="0";
}
}else if (x>mRectWidth*2+40&&x<mRectWidth*3+60){
if (y>10&&y<mRectHeigt+20){//选中3
x1=50+2*mRectWidth;
y1=10;
x2=mRectWidth*3+50;
y2=mRectHeigt+10;
cx=xs[2];
cy=ys[0];
showNumber="3";
}else if (y>20+mRectHeigt&&y<mRectHeigt*2+40){//选中6
x1=50+2*mRectWidth;
y1=30+mRectHeigt;
x2=mRectWidth*3+50;
y2=mRectHeigt*2+30;
cx=xs[2];
cy=ys[1];
showNumber="6";
}else if (y>mRectHeigt*2+40&&y<mRectHeigt*3+60){//选中9
x1=50+2*mRectWidth;
y1=50+mRectHeigt*2;
x2=mRectWidth*3+50;
y2=mRectHeigt*3+50;
cx=xs[2];
cy=ys[2];
showNumber="9";
}else if (y>mRectHeigt*3+60&&y<mRectHeigt*4+80){//选中<
x1=50+2*mRectWidth;
y1=70+mRectHeigt*3;
x2=mRectWidth*3+50;
y2=mRectHeigt*4+70;
cx=xs[2];
cy=ys[3];
showNumber="<";
}
}
type=0;//draw渲染的判断依据
invalidate();//渲染更新
}
private void handleup(){
type=1;
x1=0;
x2=0;
y1=0;
y2=0;
invalidate();
}
public interface OnNumberClickListener{
public void onNumberReturn(String number);
public void onNumberDelete();
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/Service/PasswordView/KeyPasswordView.java | app/src/main/java/zql/app_jinnang/Service/PasswordView/KeyPasswordView.java | package zql.app_jinnang.Service.PasswordView;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
public class KeyPasswordView extends View{
private int count=0;
private float mWidth,mHeight;
private float radius;
private float[] cx=new float[6];
private float cy;
private Paint paint;
private Integer rouldrect_integer;
public KeyPasswordView(Context context){
super(context);
}
public KeyPasswordView(Context context, AttributeSet att){
super(context,att);
}
public KeyPasswordView(Context context,AttributeSet att,int defStyleAttr){
super(context,att,defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
initData();
drawRouldRect(canvas);
drawCircle(canvas);
super.onDraw(canvas);
}
private void initData(){
paint=new Paint(Paint.ANTI_ALIAS_FLAG);
radius=15;
mWidth=getWidth();
mHeight=getHeight();
float spaceing=(mWidth-radius*2*6)/7;
cx[0]=spaceing+radius;
cx[1]=spaceing*2+radius*2+radius;
cx[2]=spaceing*3+radius*4+radius;
cx[3]=spaceing*4+radius*6+radius;
cx[4]=spaceing*5+radius*8+radius;
cx[5]=spaceing*6+radius*10+radius;
cy=mHeight/2;
}
private void drawCircle(Canvas canvas){
paint.setColor(Color.GRAY);
paint.setAntiAlias(true);
for (int j=0;j<count;j++){
canvas.drawCircle(cx[j],cy,radius,paint);
}
}
private void drawRouldRect(Canvas canvas){
paint.setColor(rouldrect_integer);
paint.setAntiAlias(true);
canvas.drawRoundRect(new RectF(10,10,mWidth-10,mHeight-10),mHeight/2,mHeight/2,paint);
}
public void changeTheNum(int mnum){
if (mnum>6){
mnum=0;
}
this.count=mnum;
invalidate();
}
public void setRouldRectcolor(Integer integer){
this.rouldrect_integer=integer;
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/CalendarActivity.java | app/src/main/java/zql/app_jinnang/View/CalendarActivity.java | package zql.app_jinnang.View;
import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;
import com.jaeger.library.StatusBarUtil;
import java.util.ArrayList;
import java.util.List;
import zql.app_jinnang.Adapter.RecyclerViewTimeCardAdapter;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Service.DPCManager;
import cn.aigestudio.datepicker.bizs.decors.DPDecor;
import cn.aigestudio.datepicker.cons.DPMode;
import zql.app_jinnang.Service.DatePicker;
import zql.app_jinnang.Bean.Means;
import zql.app_jinnang.Prestener.PrestenerImp_calendar;
import zql.app_jinnang.Prestener.Prestener_calendar;
import zql.app_jinnang.R;
import static zql.app_jinnang.R.color.colorFloatingButton;
public class CalendarActivity extends SwipeActivity implements CalendarActivityImp{
private PrestenerImp_calendar prestenerImp_calendar;
private Integer integer0,integer1;
private DatePicker datePicker;
private RecyclerView recyclerView;
@TargetApi(Build.VERSION_CODES.M)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setSwipeAnyWhere(false);
setContentView(R.layout.activity_calendar);
prestenerImp_calendar=new Prestener_calendar(this);
prestenerImp_calendar.setBackgroundcolorfromSeting();
prestenerImp_calendar.readNotecreatimeOnCalendar();
StatusBarUtil.setColor(this,integer0);
initview();
}
private void initview(){
initrecyclerview();
}
private void initrecyclerview(){
recyclerView=(RecyclerView)this.findViewById(R.id.calendar_recycler);
prestenerImp_calendar.readNotebeanOnRecycler(Means.getCreatetime());
}
private void getIntentExtra(){
}
@Override
public void setBackgroundcolorfromSeting(List<Integer> colorlist) {
integer0=colorlist.get(0);
integer1=colorlist.get(1);
}
@Override
public void readNotebeansfromDatabycreatetime(List<NoteBean> noteBeanList) {
setMainBackgroundIcon(noteBeanList.size());
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL,false);
RecyclerViewTimeCardAdapter recyclerViewTimeCardAdapter=new RecyclerViewTimeCardAdapter((ArrayList<NoteBean>) noteBeanList,this,this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerViewTimeCardAdapter);
}
@Override
public void initCalendarViewandgetCreattime(List<String> mlist) {
DPCManager.getInstance().setDecorTR(mlist);
datePicker=(DatePicker)this.findViewById(R.id.calendar_datapicker);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
datePicker.getChildAt(0).setBackgroundColor(integer0);
datePicker.getChildAt(1).setBackgroundColor(integer0);
}
datePicker.setDate(Means.getTheYearoncalendar(),Means.getTheMonthoncalendar());
datePicker.setMode(DPMode.SINGLE);
datePicker.setDPDecor(new DPDecor(){
@Override
public void drawDecorTR(Canvas canvas, Rect rect, Paint paint) {
paint.setColor(integer0);
canvas.drawCircle(rect.centerX(), rect.centerY(), rect.width() / 2, paint);
}
});
datePicker.setOnDatePickedListener(new DatePicker.OnDatePickedListener() {
@Override
public void onDatePicked(String date) {
prestenerImp_calendar.readNotebeanOnRecycler(date);
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode==KeyEvent.KEYCODE_BACK){
finish();
}
return false;
}
@Override
public void finish() {
super.finish();
}
@Override
public Context getCalendarActivity() {
return this;
}
@Override
public Application getCalendarApplication() {
return getApplication();
}
public void setMainBackgroundIcon(int size) {
RelativeLayout relativeLayout=(RelativeLayout)findViewById(R.id.calendar_empty);
if (size==0){
relativeLayout.setVisibility(View.VISIBLE);
}else {
relativeLayout.setVisibility(View.GONE);
}
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/ListSecretActivity.java | app/src/main/java/zql/app_jinnang/View/ListSecretActivity.java | package zql.app_jinnang.View;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.jaeger.library.StatusBarUtil;
import java.util.ArrayList;
import java.util.List;
import zql.app_jinnang.Adapter.RecyclerViewCardAdapter;
import zql.app_jinnang.Adapter.RecyclerViewSecretCardAdapter;
import zql.app_jinnang.Bean.Means;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Prestener.PrestenerImp_listserect;
import zql.app_jinnang.Prestener.Prestener_listserect;
import zql.app_jinnang.R;
public class ListSecretActivity extends SwipeActivity implements ListSecretActivityImp{
private Toolbar toolbar_listsecret;
private PrestenerImp_listserect prestenerImp_listserect;
private RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_secret);
prestenerImp_listserect=new Prestener_listserect(this);
initview();
prestenerImp_listserect.readNoteserectfromDatatoList();
prestenerImp_listserect.setBackgroundcolorfromSeting();
}
private void initview(){//具体view的实现
inittoolbarSeting();
initRecyclerView();
}
private void inittoolbarSeting(){//对toolbar的实例化
toolbar_listsecret=(Toolbar) this.findViewById(R.id.toolbar_list_secret);
setSupportActionBar(toolbar_listsecret);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
toolbar_listsecret.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
private void initBottomMenu(final NoteBean noteBean){//Bottomsheetdialog进行实例化
final BottomSheetDialog bottomSheetDialog=new BottomSheetDialog(this);
final View dialogview= LayoutInflater.from(this)
.inflate(R.layout.activity_secret_dialog,null);
LinearLayout list_dialog_linear_about,list_dialog_linear_hide,list_dialog_linear_delete,list_dialog_linear_change;
list_dialog_linear_about=(LinearLayout)dialogview.findViewById(R.id.secret_dialog_linear_about);
list_dialog_linear_delete=(LinearLayout)dialogview.findViewById(R.id.secret_dialog_linear_delete);
list_dialog_linear_about.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent mintent=new Intent(ListSecretActivity.this,NoteinfoActivity.class);
Bundle bundle=new Bundle();
bundle.putSerializable("noteinfo", Means.changefromNotebean(noteBean));
mintent.putExtras(bundle);
startActivity(mintent);
bottomSheetDialog.dismiss();
}
});
list_dialog_linear_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
initDeleteDialog(noteBean);
bottomSheetDialog.dismiss();
}
});
bottomSheetDialog.setContentView(dialogview);
bottomSheetDialog.show();
}
private void initDeleteDialog(final NoteBean noteBean){//加入一个dialog,来询问是否要删除。
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("删除");
builder.setMessage("确定删除");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
prestenerImp_listserect.deleteNotebeanserect(noteBean);
prestenerImp_listserect.readNoteserectfromDatatoList();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.create().show();
}
@Override
public void opensheetdialog(NoteBean noteBean) {
initBottomMenu(noteBean);
}
private void initRecyclerView(){//对recycerView实例化
recyclerView=(RecyclerView)this.findViewById(R.id.recycler_list_secret);
}
@Override
public void readAllNoteSerectfromData(List<NoteBean> noteBeanList) {
setMainBackgroundIcon(noteBeanList.size());
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL,false);
RecyclerViewSecretCardAdapter recyclerViewSecretCardAdapter=new RecyclerViewSecretCardAdapter((ArrayList<NoteBean>) noteBeanList,this,this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerViewSecretCardAdapter);
}
@Override
public void setBackgroundcolorfromSeting(List<Integer> colorlist) {
StatusBarUtil.setColor(this, colorlist.get(0));
toolbar_listsecret.setBackgroundColor(colorlist.get(0));
}
@Override
public Application getListSerectApplication() {
return getApplication();
}
@Override
public Context getListSerectActivityContext() {
return this;
}
public void setMainBackgroundIcon(int size) {
RelativeLayout relativeLayout=(RelativeLayout)findViewById(R.id.listserect_empty);
if (size==0){
relativeLayout.setVisibility(View.VISIBLE);
}else {
relativeLayout.setVisibility(View.GONE);
}
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/DataChartActivityImp.java | app/src/main/java/zql/app_jinnang/View/DataChartActivityImp.java | package zql.app_jinnang.View;
import android.app.Application;
import android.content.Context;
import java.util.List;
public interface DataChartActivityImp {
public Context getAddActivityContext();
public Application getAddApplication();
public void setBackgroundcolorfromSeting(List<Integer> colorlist);
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/DataChartActivity.java | app/src/main/java/zql/app_jinnang/View/DataChartActivity.java | package zql.app_jinnang.View;
import android.app.Application;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import com.jaeger.library.StatusBarUtil;
import org.angmarch.views.NiceSpinner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.listener.PieChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.LineChartView;
import lecho.lib.hellocharts.view.PieChartView;
import zql.app_jinnang.Prestener.PrestenerImp_datachart;
import zql.app_jinnang.Prestener.Prestener_datachart;
import zql.app_jinnang.R;
public class DataChartActivity extends SwipeActivity implements DataChartActivityImp {
private PrestenerImp_datachart prestenerImp_datachart;
private RelativeLayout relativeLayout;
private PieChartView pieChartView;//饼状图
private ColumnChartView columnChartView;//柱状图
private Integer integer0,integer1;
private NiceSpinner niceSpinner;
private List<Integer>typesNum=new ArrayList<>();
private int notesum;
private int[] colorData = {Color.parseColor("#f4ea2a"),
Color.parseColor("#d81e06"),
Color.parseColor("#1afa29"),
Color.parseColor("#1296ab"),
Color.parseColor("#d4237a")};
private String[] stateChar = {"工作", "学习", "生活", "日记", "旅行"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_chart);
prestenerImp_datachart=new Prestener_datachart(this);
prestenerImp_datachart.setBackgroundcolorfromSeting();
StatusBarUtil.setColor(this,integer0);
typesNum=prestenerImp_datachart.getPieChartListfromData();
notesum=prestenerImp_datachart.getPieChartSumfromDatatoActivity();
initView();
initPieChart();
}
private void initView(){
relativeLayout=(RelativeLayout)this.findViewById(R.id.chart_relativelayout);
initToolbar();
initNicespinner();
}
private void initNicespinner(){//创建一个筛选器
niceSpinner=(NiceSpinner)findViewById(R.id.chart_spinner);
List<String> data=new LinkedList<>(Arrays.asList("饼状图","柱状图"));
niceSpinner.attachDataSource(data);
niceSpinner.addOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
switch (i){
case 0:
relativeLayout.removeAllViews();
initPieChart();
break;
case 1:
relativeLayout.removeAllViews();
initColumnChart();
break;
default:
break;
}
}
});
}
private void initToolbar(){
Toolbar toolbar_chart=(Toolbar) this.findViewById(R.id.toolbar_chart);
toolbar_chart.setBackgroundColor(integer0);
setSupportActionBar(toolbar_chart);
getSupportActionBar().setHomeButtonEnabled(true);//设置返回键可用
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("数据分析");
toolbar_chart.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
private void initPieChart(){//设置饼状图
pieChartView=new PieChartView(this);
List<SliceValue> values = new ArrayList<SliceValue>();
int pieWidth=(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,400, getResources().getDisplayMetrics());
int pieHeigth=(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,400, getResources().getDisplayMetrics());
RelativeLayout.LayoutParams pieChartParams=new RelativeLayout.LayoutParams(pieWidth,pieHeigth);
pieChartParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
pieChartParams.addRule(RelativeLayout.CENTER_VERTICAL);
for (int i = 0; i < 5; ++i) {
SliceValue sliceValue = new SliceValue((float) typesNum.get(i), colorData[i]);
values.add(sliceValue);
}
pieChartView.setViewportCalculationEnabled(true);
pieChartView.setChartRotationEnabled(false);
pieChartView.setAlpha(0.9f);
pieChartView.setCircleFillRatio(1f);
pieChartView.setValueSelectionEnabled(true);
final PieChartData pieChartData=new PieChartData();
pieChartData.setHasLabels(true);
pieChartData.setHasLabelsOnlyForSelected(false);
pieChartData.setHasLabelsOutside(false);
pieChartData.setHasCenterCircle(true);
pieChartData.setCenterCircleColor(Color.WHITE);
pieChartData.setCenterCircleScale(0.5f);
pieChartData.setCenterText1Color(integer0);
pieChartData.setCenterText2Color(Color.BLUE);
pieChartData.setValues(values);
pieChartView.setPieChartData(pieChartData);
pieChartView.setOnValueTouchListener(new PieChartOnValueSelectListener() {
@Override
public void onValueSelected(int arcIndex, SliceValue value) {
pieChartData.setCenterText1Color(integer0);
pieChartData.setCenterText1FontSize(12);
pieChartData.setCenterText1(stateChar[arcIndex]);
pieChartData.setCenterText2Color(integer0);
pieChartData.setCenterText2FontSize(16);
pieChartData.setCenterText2(value.getValue()+"("+getCenterStringfromData(arcIndex)+")");
}
@Override
public void onValueDeselected() {
}
});
relativeLayout.addView(pieChartView,pieChartParams);
}
private void initColumnChart(){//创建柱状图
columnChartView=new ColumnChartView(this);
int columnWidth=(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,400, getResources().getDisplayMetrics());
int columnHeigth=(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,400, getResources().getDisplayMetrics());
RelativeLayout.LayoutParams columnChartParams=new RelativeLayout.LayoutParams(columnWidth,columnHeigth);
columnChartParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
columnChartParams.addRule(RelativeLayout.CENTER_VERTICAL);
List<Column>columnList=new ArrayList<>();
List<SubcolumnValue> values;
for (int i=0;i<5;++i){
values=new ArrayList<SubcolumnValue>();
values.add(new SubcolumnValue((float)typesNum.get(i),colorData[i]));
Column column=new Column(values);
column.setHasLabels(false);
column.setHasLabelsOnlyForSelected(true);
columnList.add(column);
}
ColumnChartData columnChartData=new ColumnChartData(columnList);
Axis axis=new Axis();
Axis axiy=new Axis().setHasLines(true);
List<AxisValue>axisValues=new ArrayList<>();
for (int j=0;j<5;++j){
axisValues.add(new AxisValue(j).setLabel(stateChar[j]));
}
axis.setValues(axisValues);
axis.setName("类别");
axiy.setName("数量");
columnChartData.setAxisXBottom(axis);
columnChartData.setAxisYLeft(axiy);
columnChartView.setColumnChartData(columnChartData);
relativeLayout.addView(columnChartView,columnChartParams);
}
private String getCenterStringfromData(int i){
String result="";
int sum=prestenerImp_datachart.getPieChartSumfromDatatoActivity();
result=String.format("%.2f",(float)typesNum.get(i)*100/sum)+"%";
return result;
}
@Override
public Application getAddApplication() {
return this.getApplication();
}
@Override
public Context getAddActivityContext() {
return this;
}
@Override
public void setBackgroundcolorfromSeting(List<Integer> colorlist) {
integer0=colorlist.get(0);
integer1=colorlist.get(1);
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/ListActivity.java | app/src/main/java/zql/app_jinnang/View/ListActivity.java | package zql.app_jinnang.View;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.jaeger.library.StatusBarUtil;
import org.angmarch.views.NiceSpinner;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import zql.app_jinnang.Adapter.RecyclerViewCardAdapter;
import zql.app_jinnang.Bean.Means;
import zql.app_jinnang.Bean.MessageEvent;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Prestener.PrestenerImp_list;
import zql.app_jinnang.Prestener.Prestener_list;
import zql.app_jinnang.R;
public class ListActivity extends SwipeActivity implements ListActivityImp {
private Toolbar toolbar_list;
private PrestenerImp_list prestenerImp_list;
private RecyclerView recyclerView;
private RelativeLayout relativeLayout_list;
private NiceSpinner niceSpinner;
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
EventBus.getDefault().register(this);
prestenerImp_list=new Prestener_list(this);
initView();
prestenerImp_list.readNotefromDatatoList(0);
prestenerImp_list.setBackgroundcolorfromSeting();
}
private void initView(){//具体view实现函数
initToolBarSeting();
initRecyclerView();
initdropView();
}
private void initToolBarSeting(){//对ToolBar的具体实现
toolbar_list=(Toolbar)this.findViewById(R.id.toolbar_list);
relativeLayout_list=(RelativeLayout)this.findViewById(R.id.relativeLayout_list);
setSupportActionBar(toolbar_list);
getSupportActionBar().setHomeButtonEnabled(true);//设置返回键可用
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
toolbar_list.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
private void initRecyclerView(){//对recyclerview进行实例化
recyclerView=(RecyclerView)this.findViewById(R.id.recycler_list);
}
private void initDeleteDilog(final NoteBean noteBean){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("删除");
builder.setMessage("确定删除?");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
prestenerImp_list.deleteNotebean(noteBean);
prestenerImp_list.readNotefromDatatoList(0);
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.create().show();
}
private void initdropView(){
niceSpinner=(NiceSpinner)findViewById(R.id.list_spinner);
List<String> data=new LinkedList<>(Arrays.asList("全部","工作","学习","生活","日记","旅行"));
niceSpinner.attachDataSource(data);
niceSpinner.addOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
switch (i){
case 0:
prestenerImp_list.readNotefromDatatoList(0);
break;
case 1:
prestenerImp_list.readNotefromDatatoList(1);
break;
case 2:
prestenerImp_list.readNotefromDatatoList(2);
break;
case 3:
prestenerImp_list.readNotefromDatatoList(3);
break;
case 4:
prestenerImp_list.readNotefromDatatoList(4);
break;
case 5:
prestenerImp_list.readNotefromDatatoList(5);
break;
case 6:
prestenerImp_list.readNotefromDatatoList(6);
break;
default:
break;
}
}
});
}
@Override
public void readAllNotefromData(List<NoteBean> noteBeanList) {//读取数据库内的文件
setMainBackgroundIcon(noteBeanList.size());
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL,false);
RecyclerViewCardAdapter recyclerViewCardAdapter=new RecyclerViewCardAdapter((ArrayList<NoteBean>) noteBeanList,this,this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerViewCardAdapter);
}
@Override
public void setBackgroundcolorfromSeting(List<Integer> colorlist) {
StatusBarUtil.setColor(this, colorlist.get(0));
toolbar_list.setBackgroundColor(colorlist.get(0));
niceSpinner.setBackgroundColor(colorlist.get(0));
}
@Override
public Context getListActivityConent() {
return this;
}
@Override
public void opensheeetdialog(NoteBean noteBean) {
initBottomMenu(noteBean);
}
private void initBottomMenu(final NoteBean noteBean){//Bottomsheetdialog进行实例化
final BottomSheetDialog bottomSheetDialog=new BottomSheetDialog(ListActivity.this);
final View dialogview= LayoutInflater.from(ListActivity.this)
.inflate(R.layout.activity_main_dialog,null);
LinearLayout list_dialog_linear_about,list_dialog_linear_hide,list_dialog_linear_delete,list_dialog_linear_change,list_dialog_linear_share;
list_dialog_linear_about=(LinearLayout)dialogview.findViewById(R.id.main_dialog_linear_about);
list_dialog_linear_hide=(LinearLayout)dialogview.findViewById(R.id.main_dialog_linear_hide);
list_dialog_linear_delete=(LinearLayout)dialogview.findViewById(R.id.main_dialog_linear_delete);
list_dialog_linear_change=(LinearLayout)dialogview.findViewById(R.id.main_dialog_linear_change);
list_dialog_linear_share=(LinearLayout)dialogview.findViewById(R.id.main_dialog_linear_friendspace);
list_dialog_linear_about.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent mintent=new Intent(ListActivity.this,NoteinfoActivity.class);
Bundle bundle=new Bundle();
bundle.putSerializable("noteinfo", Means.changefromNotebean(noteBean));
mintent.putExtras(bundle);
startActivity(mintent);
bottomSheetDialog.dismiss();
}
});
list_dialog_linear_hide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
initPasswordFileDialog(noteBean);
bottomSheetDialog.dismiss();
}
});
list_dialog_linear_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
initDeleteDilog(noteBean);
bottomSheetDialog.dismiss();
}
});
list_dialog_linear_change.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent addintent=new Intent(ListActivity.this,EditActivity.class);
Bundle bundle=new Bundle();
bundle.putInt("type",10);
bundle.putSerializable("noteinfo",Means.changefromNotebean(noteBean));
addintent.putExtra("data",bundle);
startActivity(addintent);
bottomSheetDialog.dismiss();
}
});
list_dialog_linear_share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sharedNotetexttoWeChart(noteBean.getNoteinfo());
bottomSheetDialog.dismiss();
}
});
bottomSheetDialog.setContentView(dialogview);
bottomSheetDialog.show();
}
private void sharedNotetexttoWeChart(String text){//将便签文字分享到微信或者QQ等,主要调用系统分享控件
Intent intent=new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,text);
startActivity(Intent.createChooser(intent,"share"));
}
private void initPasswordFileDialog(final NoteBean noteBean){//将备忘录加入到私密文件夹中。
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("隐藏");
builder.setMessage("确认隐藏?");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
prestenerImp_list.changeNotetoPasswordFile(noteBean);
prestenerImp_list.readNotefromDatatoList(0);
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.create().show();
}
@Override
public Application getListApplication() {
return getApplication();
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void handEvent(MessageEvent messageEvent){
switch (messageEvent.getMessageevent()){
case MessageEvent.UPDATE_DATA:
prestenerImp_list.readNotefromDatatoList(0);
break;
case MessageEvent.UPDATA_COLOR:
//prestenerImpMain.setBackgroundcolorfromSeting();
break;
default:
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
public void setMainBackgroundIcon(int size) {
RelativeLayout relativeLayout=(RelativeLayout)findViewById(R.id.list_empty);
if (size==0){
relativeLayout.setVisibility(View.VISIBLE);
}else {
relativeLayout.setVisibility(View.GONE);
}
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/MainActivity.java | app/src/main/java/zql/app_jinnang/View/MainActivity.java | package zql.app_jinnang.View;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.getbase.floatingactionbutton.AddFloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.jaeger.library.StatusBarUtil;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import zql.app_jinnang.Adapter.ViewPagerCardAdapter;
import zql.app_jinnang.Bean.Means;
import zql.app_jinnang.Bean.MessageEvent;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Prestener.Prestener_main;
import zql.app_jinnang.Prestener.PrestenerImp_main;
import zql.app_jinnang.R;
import zql.app_jinnang.Service.PasswordView.KeyPasswordView;
import zql.app_jinnang.Service.PasswordView.KeynumberDialog;
public class MainActivity extends AppCompatActivity implements MainActivityImp{
private PrestenerImp_main prestenerImpMain;
private FloatingActionsMenu floatingActionsmenu_add;
private FloatingActionButton floatingActionButton_work,floatingActionButton_study,floatingActionButton_live,floatingActionButton_diarly,floatingActionButton_travel,floatingActionButton_calendar;
private AddFloatingActionButton addFloatingActionButton;
private LinearLayout mainbottomlinearlayout,voicebuttonlayout;
private ViewPager viewPagercard;
private ViewPagerCardAdapter adapter;
private Toolbar toolbar_main;
private TextView title_toolbar_main,text_refresh;
private RelativeLayout relativeLayout;
private Integer maincolor;
private String password="";
private int count_delete;
private static final int REQUEST_UPDATE=2;
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StatusBarUtil.setColor(this, getColor(R.color.colorFloatingButton));
prestenerImpMain =new Prestener_main(this);
initview();
prestenerImpMain.readNotefromDatatoMain();
prestenerImpMain.setBackgroundcolorfromSeting();
EventBus.getDefault().register(this);
}
private void initview(){//具体的View实现生成的函数
initToolBarSeting();
initFloatingActionButton();
initViewPagercard();
initrefresh();
}
private void initToolBarSeting(){//实现ToolBar的生成
relativeLayout=(RelativeLayout)this.findViewById(R.id.relativeLayout_main);
toolbar_main=(Toolbar)this.findViewById(R.id.toolbar_main);
title_toolbar_main=(TextView)findViewById(R.id.title_toolbar_main);
YoYo.with(Techniques.DropOut)
.duration(700)
.playOn(findViewById(R.id.title_toolbar_main));
setSupportActionBar(toolbar_main);
}
private void initrefresh(){//实现刷新
text_refresh=(TextView)this.findViewById(R.id.main_refresh);
text_refresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
prestenerImpMain.readNotefromDatatoMain();
}
});
}
private void initFloatingActionButton(){//实现FloatingActionButton的生成
floatingActionButton_calendar=(FloatingActionButton)this.findViewById(R.id.floatingbutton_calendar);
floatingActionsmenu_add=(FloatingActionsMenu)this.findViewById(R.id.floatinbuttonmenu_add);
floatingActionButton_work=(FloatingActionButton)this.findViewById(R.id.floatingbutton_work);
floatingActionButton_study=(FloatingActionButton)this.findViewById(R.id.floatingbutton_study);
floatingActionButton_live=(FloatingActionButton)this.findViewById(R.id.floatingbutton_live);
floatingActionButton_diarly=(FloatingActionButton)this.findViewById(R.id.floatingbutton_diary);
floatingActionButton_travel=(FloatingActionButton)this.findViewById(R.id.floatingbutton_travel);
floatingActionButton_calendar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
prestenerImpMain.openCalendarActivity();
}
});
floatingActionButton_work.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startEditActivity(0,null);
floatingActionsmenu_add.collapse();
}
});
floatingActionButton_study.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startEditActivity(1,null);
floatingActionsmenu_add.collapse();
}
});
floatingActionButton_live.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startEditActivity(2,null);
floatingActionsmenu_add.collapse();
}
});
floatingActionButton_diarly.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startEditActivity(3,null);
floatingActionsmenu_add.collapse();
}
});
floatingActionButton_travel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startEditActivity(4,null);
floatingActionsmenu_add.collapse();
}
});
}
private void startEditActivity(int type,NoteBean noteBean){
Intent addintent=new Intent(MainActivity.this,EditActivity.class);
Bundle bundle=new Bundle();
bundle.putInt("type",type);
if (noteBean!=null){
bundle.putSerializable("noteinfo",Means.changefromNotebean(noteBean));
}
addintent.putExtra("data",bundle);
startActivity(addintent);
}
private void initEditpassworddialog(){//实例化一个重新编辑密码的dialog
if (!password.isEmpty()){
password="";
}
final BottomSheetDialog passwordbottomsheetdialog=new BottomSheetDialog(MainActivity.this);
View dialogview=LayoutInflater.from(MainActivity.this)
.inflate(R.layout.sheetdialog_password,null);
final KeynumberDialog keynumberDialog=(KeynumberDialog)dialogview.findViewById(R.id.main_sheetdialog_keynumber);
final KeyPasswordView keyPasswordView=(KeyPasswordView)dialogview.findViewById(R.id.main_sheetdialog_passwordview);
keyPasswordView.setRouldRectcolor(maincolor);
keynumberDialog.setOnNumberClickListener(new KeynumberDialog.OnNumberClickListener() {
@Override
public void onNumberReturn(String number) {
password+=number;
if (password.length()==6){
if (prestenerImpMain.iscurrentthepasswordfromSeting(password)){
startListSecretActivity();
password="";
passwordbottomsheetdialog.dismiss();
}else {
Toast.makeText(MainActivity.this, "输入密码有误", Toast.LENGTH_SHORT).show();
password="";
}
}
keyPasswordView.changeTheNum(password.length());
}
@Override
public void onNumberDelete() {
if (password.length()<=1){
password="";
}else {
password=password.substring(0,password.length()-1);
}
keyPasswordView.changeTheNum(password.length());
}
});
passwordbottomsheetdialog.setContentView(dialogview);
passwordbottomsheetdialog.show();
}
private void initViewPagercard(){//实现ViewPagerCard的生成
viewPagercard=(ViewPager)this.findViewById(R.id.viewpager_main);
viewPagercard.setPageMargin((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,24,getResources().getDisplayMetrics()));
viewPagercard.setPageTransformer(false,new ScaleTransformer0(this));
}
private void initBottomDialog(final NoteBean noteBean){//创建底部弹出的窗口
final BottomSheetDialog bottomSheetDialog=new BottomSheetDialog(MainActivity.this);
View dialogview= LayoutInflater.from(MainActivity.this)
.inflate(R.layout.activity_main_dialog,null);
LinearLayout main_dialog_linear_about,main_dialog_linear_hide,main_dialog_linear_delete,main_dialog_linear_change,main_dialog_friendspace,main_dialog;
main_dialog=(LinearLayout)dialogview.findViewById(R.id.main_dialog);
main_dialog_linear_about=(LinearLayout)dialogview.findViewById(R.id.main_dialog_linear_about);
main_dialog_friendspace=(LinearLayout)dialogview.findViewById(R.id.main_dialog_linear_friendspace);
main_dialog_linear_hide=(LinearLayout)dialogview.findViewById(R.id.main_dialog_linear_hide);
main_dialog_linear_delete=(LinearLayout)dialogview.findViewById(R.id.main_dialog_linear_delete);
main_dialog_linear_change=(LinearLayout)dialogview.findViewById(R.id.main_dialog_linear_change);
main_dialog_linear_about.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent mintent=new Intent(MainActivity.this,NoteinfoActivity.class);
Bundle bundle=new Bundle();
bundle.putSerializable("noteinfo", Means.changefromNotebean(noteBean));
mintent.putExtras(bundle);
startActivity(mintent);
bottomSheetDialog.dismiss();
}
});
main_dialog_friendspace.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sharedNotetexttoWeChart(noteBean.getNoteinfo());
bottomSheetDialog.dismiss();
}
});
main_dialog_linear_hide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
initPasswordFileDialog(noteBean);
bottomSheetDialog.dismiss();
}
});
main_dialog_linear_delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
initDeleteDialog(noteBean);
bottomSheetDialog.dismiss();
}
});
main_dialog_linear_change.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startEditActivity(10,noteBean);
bottomSheetDialog.dismiss();
}
});
main_dialog.setBackgroundColor(maincolor);
bottomSheetDialog.setContentView(dialogview);
bottomSheetDialog.show();
}
private void sharedNotetexttoWeChart(String text){//将便签文字分享到微信朋友圈
Intent intent=new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,text);
startActivity(Intent.createChooser(intent,"share"));
}
private void initPasswordFileDialog(final NoteBean noteBean){//将便签加入到私密文件夹中
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("隐藏");
builder.setMessage("确认隐藏?");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
count_delete=viewPagercard.getCurrentItem();//做一个跳转优化
prestenerImpMain.changeNotetoPasswordFile(noteBean);
prestenerImpMain.readNotefromDatatoMain();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.create().show();
}
private void initDeleteDialog(final NoteBean noteBean){//删除选定的便签
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("删除");
builder.setMessage("确定删除?");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
count_delete=viewPagercard.getCurrentItem();//做一个跳转优化
prestenerImpMain.deleteNoteBean(noteBean);
prestenerImpMain.readNotefromDatatoMain();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.create().show();
}
@Override//创建菜单目录
public boolean onCreatePanelMenu(int featureId, Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return super.onCreatePanelMenu(featureId, menu);
}
@SuppressLint("RestrictedApi")
@Override
protected boolean onPrepareOptionsPanel(View view, Menu menu) {
if (menu.getClass() == MenuBuilder.class) {
try {
Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
method.setAccessible(true);
method.invoke(menu, true);
} catch (Exception e) {
e.printStackTrace();
}
}
return super.onPrepareOptionsPanel(view, menu);
}
@Override//设置监听菜单
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_list:
prestenerImpMain.openListActivity();
return true;
case R.id.action_seting:
prestenerImpMain.openSetiongActivity();
return true;
case R.id.action_search:
prestenerImpMain.openSearchActivity();
return true;
case R.id.action_serect:
initEditpassworddialog();
return true;
case R.id.action_chart:
initChartActiviy();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override//打开新的搜索界面
public void startSearchActivity() {
Intent mintent=new Intent(this,SearchActivity.class);
startActivity(mintent);
}
//打开数据图表分析界面
private void initChartActiviy(){
Intent mintent=new Intent(MainActivity.this,DataChartActivity.class);
this.startActivity(mintent);
}
@Override
public Context getActivity_this() {
return this;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
/**
* EventBus接受事件
*/
@Subscribe(threadMode = ThreadMode.MAIN)
public void handEvent(MessageEvent messageEvent){
switch (messageEvent.getMessageevent()){
case MessageEvent.UPDATE_DATA:
prestenerImpMain.readNotefromDatatoMain();
break;
case MessageEvent.UPDATA_COLOR:
prestenerImpMain.setBackgroundcolorfromSeting();
break;
default:
break;
}
}
@Override
public void startSetingActivity() {
Intent mintet=new Intent(MainActivity.this,AboutActivity.class);
this.startActivity(mintet);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override//设置背景的颜色
public void setMainBackground(Integer integer) {
relativeLayout.setBackground(getDrawable(integer));
}
@Override//打开新的ListActivity
public void startListActivity() {
Intent mintent=new Intent(MainActivity.this,ListActivity.class);
this.startActivityForResult(mintent,REQUEST_UPDATE);
}
@Override//打开秘密ListActivity
public void startListSecretActivity() {
Intent mintent=new Intent(MainActivity.this,ListSecretActivity.class);
this.startActivity(mintent);
}
@Override//打开日历CalendarActivity
public void startCalendarActivity() {
Intent mintent=new Intent(MainActivity.this,CalendarActivity.class);
mintent.putExtra("UPDATE",0);
this.startActivity(mintent);
}
public class ScaleTransformer0 implements ViewPager.PageTransformer {//改变形状的透明度
private Context context;
private float elevation;
public ScaleTransformer0(Context context) {
this.context = context;
elevation = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
20, context.getResources().getDisplayMetrics());
}
@Override
public void transformPage(View page, float position) {
if (position < -1 || position > 1) {
} else {
if (position < 0) {
((CardView) page).setCardElevation((1 + position) * elevation);
} else {
((CardView) page).setCardElevation((1 - position) * elevation);
}
}
}
}
@Override
public void openSheetDialog(NoteBean noteBean) {
initBottomDialog(noteBean);
}
@Override
public void readNotefromData(List<NoteBean> noteBeanList) {
setMainBackgroundIcon(noteBeanList.size());
adapter=new ViewPagerCardAdapter(this,noteBeanList,this,prestenerImpMain);
viewPagercard.setAdapter(adapter);
/**
* 当为删除事件时,count_delete为大于1,否则为0,在进入界面初始化的时候,我们会把count_delete设置为0
* */
if (count_delete>=1){//优化删除(删除完成后跳转到上一个事件界面)
viewPagercard.setCurrentItem(count_delete-1);
}else {
viewPagercard.setCurrentItem(0);
}
}
@Override
public Application getMainApplication() {
return getApplication();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void setBackgroundcolorfromSeting(List<Integer>mlist) {
maincolor=mlist.get(0);//设置主体颜色
StatusBarUtil.setColor(this, mlist.get(0));
toolbar_main.setBackgroundColor(mlist.get(0));
relativeLayout.setBackgroundColor(mlist.get(1));
floatingActionButton_diarly.setColorNormal(mlist.get(0));
floatingActionButton_live.setColorNormal(mlist.get(0));
floatingActionButton_study.setColorNormal(mlist.get(0));
floatingActionButton_travel.setColorNormal(mlist.get(0));
floatingActionButton_work.setColorNormal(mlist.get(0));
}
@Override
public void setMainBackgroundIcon(int size) {
LinearLayout linearlayout_listempty=(LinearLayout)findViewById(R.id.linearlayout_listEmpty);
if (size==0){
linearlayout_listempty.setVisibility(View.VISIBLE);
}else {
linearlayout_listempty.setVisibility(View.GONE);
}
}
@Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/NoteinfoActivityImp.java | app/src/main/java/zql/app_jinnang/View/NoteinfoActivityImp.java | package zql.app_jinnang.View;
import android.app.Application;
import android.graphics.Color;
import java.util.List;
/**
* Created by 尽途 on 2018/4/26.
*/
public interface NoteinfoActivityImp {
public void readNoteinfotoNotetext(String noteinfo);
public void readLabelinfotoNoteTagrroup(List<String> tags);
public void readPhotopathtoNoteImageview(String photopath,String type);
public Application getNoteinfoApplication();
public void setBackgroundcolorfromSeting(List<Integer>colorlist);
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/EditActivityImp.java | app/src/main/java/zql/app_jinnang/View/EditActivityImp.java | package zql.app_jinnang.View;
import android.app.Application;
import android.content.Context;
import java.util.List;
public interface EditActivityImp {
public Context getbasecontext();//获取
public Application getapplication();
public void setbackgroundcolor(List<Integer>list);//修改背景色
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/SearchActivity.java | app/src/main/java/zql/app_jinnang/View/SearchActivity.java | package zql.app_jinnang.View;
import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.jaeger.library.StatusBarUtil;
import com.rengwuxian.materialedittext.MaterialEditText;
import java.util.ArrayList;
import java.util.List;
import zql.app_jinnang.Adapter.RecyclerViewSearchAdapter;
import zql.app_jinnang.Bean.Means;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Prestener.PrestenerImp_seacher;
import zql.app_jinnang.Prestener.Prestener_seacher;
import zql.app_jinnang.R;
public class SearchActivity extends SwipeActivity implements SearchActivityImp {
private SearchView searchView;
private Toolbar toolbar_search;
private RecyclerView searchrecyclerView;
private PrestenerImp_seacher prestenerImpSeacher;
private RecyclerViewSearchAdapter recyclerViewSearchAdapter;
@TargetApi(Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
StatusBarUtil.setColor(this, getColor(R.color.colorFloatingButton));
prestenerImpSeacher=new Prestener_seacher(this);
initview();
prestenerImpSeacher.setBackgroundcolorfromSeting();
}
private void initview(){
initsearchview();
inittoolbarset();
initrecyclerview();
}
private void inittoolbarset(){
toolbar_search=(Toolbar)this.findViewById(R.id.toolbar_search);
setSupportActionBar(toolbar_search);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
toolbar_search.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
private void initrecyclerview(){
searchrecyclerView=(RecyclerView)this.findViewById(R.id.recycler_search);
}
private void initAdapter(String searth){
List<NoteBean>list=prestenerImpSeacher.getNotebeanfromDatatoSearch(searth);
if (list.size()>0){
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL,false);
RecyclerViewSearchAdapter recyclerViewSearchAdapter=new RecyclerViewSearchAdapter(list,this);
searchrecyclerView.setLayoutManager(layoutManager);
searchrecyclerView.setAdapter(recyclerViewSearchAdapter);
}else {
searchrecyclerView.removeAllViews();
Toast.makeText(this, "无搜索结果", Toast.LENGTH_SHORT).show();
}
}
private void initsearchview(){
searchView=(SearchView)this.findViewById(R.id.searchview_search);
searchView.setIconifiedByDefault(false);
searchView.setIconified(false);
searchView.onActionViewExpanded();
searchView.clearFocus();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
initAdapter(s);
return false;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
});
}
@Override
public Context getSearchActivityContext() {
return this;
}
@Override
public Application getSearchApplication() {
return getApplication();
}
@Override
public void setBackgroundcolorfromSeting(List<Integer> colorlist) {
StatusBarUtil.setColor(this, colorlist.get(0));
toolbar_search.setBackgroundColor(colorlist.get(0));
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/ListSecretActivityImp.java | app/src/main/java/zql/app_jinnang/View/ListSecretActivityImp.java | package zql.app_jinnang.View;
import android.app.Application;
import android.content.Context;
import java.util.List;
import zql.app_jinnang.Bean.NoteBean;
public interface ListSecretActivityImp {
public void opensheetdialog(NoteBean noteBean);
public Context getListSerectActivityContext();
public Application getListSerectApplication();
public void readAllNoteSerectfromData(List<NoteBean>noteBeanList);
public void setBackgroundcolorfromSeting(List<Integer>colorlist);
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/AboutActivityImp.java | app/src/main/java/zql/app_jinnang/View/AboutActivityImp.java | package zql.app_jinnang.View;
import android.app.Application;
import android.content.Context;
import java.util.List;
/**
* Created by 尽途 on 2018/5/12.
*/
public interface AboutActivityImp {
public void showthecurrentPassword(String string);
public Context getAboutActivityContext();
public Application getAboutApplication();
public void setBackgroundcolorfromSeting(List<Integer>colorlist);
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/AboutActivity.java | app/src/main/java/zql/app_jinnang/View/AboutActivity.java | package zql.app_jinnang.View;
import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.jaeger.library.StatusBarUtil;
import com.rengwuxian.materialedittext.MaterialEditText;
import org.angmarch.views.NiceSpinner;
import org.greenrobot.eventbus.EventBus;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import zql.app_jinnang.Bean.Means;
import zql.app_jinnang.Bean.MessageEvent;
import zql.app_jinnang.Prestener.PrestenerImp_about;
import zql.app_jinnang.Prestener.Prestener_about;
import zql.app_jinnang.R;
import zql.app_jinnang.UserSeting;
import static zql.app_jinnang.R.color.colorFloatingButton;
public class AboutActivity extends SwipeActivity implements AboutActivityImp,View.OnClickListener{
private PrestenerImp_about prestenerImp_about;
private AlertDialog alertDialog_creatpassword;
private NiceSpinner niceSpinner;
private Toolbar toolbar_about;
private UserSeting userSeting;
@TargetApi(Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
prestenerImp_about=new Prestener_about(this);
StatusBarUtil.setColor(this,getColor(colorFloatingButton));
userSeting=(UserSeting)getApplication();
initview();
prestenerImp_about.setBackgroundcolorfromSeting();
}
private void initview(){
inittoolbarseting();
initAboutcode();
initBackgroundcolorview();
initSerectandQuestionview();
}
private void inittoolbarseting(){
toolbar_about=(Toolbar)this.findViewById(R.id.toolbar_about);
setSupportActionBar(toolbar_about);
getSupportActionBar().setHomeButtonEnabled(true);//设置返回键可用
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
toolbar_about.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
private void initSerectandQuestionview(){
TextView text_password=(TextView)this.findViewById(R.id.text_creatpasswordandquestion);
TextView text_password_edit=(TextView)this.findViewById(R.id.text_editpassword);
TextView text_question_edit=(TextView)this.findViewById(R.id.text_editquestion);
TextView text_forgetpaswword=(TextView)this.findViewById(R.id.text_forgetpassword);
text_password.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (prestenerImp_about.isnullthepasswordfromSeting()){
initpassworddialog();
}else {
Toast.makeText(AboutActivity.this, "密码已经存在,如修改请点击修改密码", Toast.LENGTH_SHORT).show();
}
}
});
text_password_edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (prestenerImp_about.isnullthepasswordfromSeting()){
Toast.makeText(AboutActivity.this, "密码尚未创建,请先创建密码", Toast.LENGTH_SHORT).show();
}else {
initEditpassworddialog();
}
}
});
text_question_edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (prestenerImp_about.isnullthequestionfromSeting()){
Toast.makeText(AboutActivity.this, "密保尚未创建,请先创建密保", Toast.LENGTH_SHORT).show();
}else {
initQuestionddialog();
}
}
});
text_forgetpaswword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (prestenerImp_about.isnullthequestionfromSeting()){
Toast.makeText(AboutActivity.this, "密保尚未创建,请先创建密保", Toast.LENGTH_SHORT).show();
}else {
initiscurrentQuestiondialog();
}
}
});
}
private void initEditnewpasssworddialog(){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
LayoutInflater layoutInflater=LayoutInflater.from(this);
View centerview=layoutInflater.inflate(R.layout.activity_set_editpassworddialog,null);
final MaterialEditText materialEditText_password=(MaterialEditText)centerview.findViewById(R.id.set_dialog_password_edit_password);
final TextView texttitle=(TextView)centerview.findViewById(R.id.title_text_password);
Button button_ok=(Button)centerview.findViewById(R.id.set_dialog_password_ok_password);
final AlertDialog alertDialog_editpassword=builder.setView(centerview).create();
texttitle.setText("创建新的密码");
button_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Means.isedittext_empty(materialEditText_password)){
Toast.makeText(AboutActivity.this, "请输入新密码", Toast.LENGTH_SHORT).show();
}else {
if (materialEditText_password.getText().toString().length()!=6){
Toast.makeText(AboutActivity.this, "请输入六位密码", Toast.LENGTH_SHORT).show();
}else {
prestenerImp_about.putpasswordOnSeting(materialEditText_password.getText().toString());
alertDialog_editpassword.dismiss();
}
}
}
});
alertDialog_editpassword.show();
}
private void initEditpassworddialog(){//实例化一个重新编辑密码的dialog
AlertDialog.Builder builder=new AlertDialog.Builder(this);
LayoutInflater layoutInflater=LayoutInflater.from(this);
View centerview=layoutInflater.inflate(R.layout.activity_set_editpassworddialog,null);
final MaterialEditText materialEditText_password=(MaterialEditText)centerview.findViewById(R.id.set_dialog_password_edit_password);
final TextView texttitle=(TextView)centerview.findViewById(R.id.title_text_password);
Button button_ok=(Button)centerview.findViewById(R.id.set_dialog_password_ok_password);
final AlertDialog alertDialog_editpassword=builder.setView(centerview).create();
texttitle.setText("请输入旧密码");
button_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (prestenerImp_about.iscurrentthepasswordfromSeting(materialEditText_password.getText().toString())){
initEditnewpasssworddialog();
alertDialog_editpassword.dismiss();
}else {
Toast.makeText(AboutActivity.this, "输入密码有误", Toast.LENGTH_SHORT).show();
}
}
});
alertDialog_editpassword.show();
}
private void initQuestionddialog(){//实例化一个重新编辑密保的dialog
AlertDialog.Builder builder=new AlertDialog.Builder(this);
LayoutInflater layoutInflater=LayoutInflater.from(this);
View centerview=layoutInflater.inflate(R.layout.activity_set_editquestiondialog,null);
final MaterialEditText materialEditText_password=(MaterialEditText)centerview.findViewById(R.id.set_dialog_question_edit_question);
final TextView texttitle=(TextView)centerview.findViewById(R.id.title_text_question);
Button button_ok=(Button)centerview.findViewById(R.id.set_dialog_password_ok_question);
final AlertDialog alertDialog_editpassword=builder.setView(centerview).create();
texttitle.setText("请输入旧密保");
button_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (prestenerImp_about.iscurrentthequestionfromSeting(materialEditText_password.getText().toString())){
alertDialog_editpassword.dismiss();
initeditnewQuestiondialog();
}else {
Toast.makeText(AboutActivity.this, "输入旧的密保有误", Toast.LENGTH_SHORT).show();
}
}
});
alertDialog_editpassword.show();
}
private void initeditnewQuestiondialog(){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
LayoutInflater layoutInflater=LayoutInflater.from(this);
View centerview=layoutInflater.inflate(R.layout.activity_set_editquestiondialog,null);
final MaterialEditText materialEditText_password=(MaterialEditText)centerview.findViewById(R.id.set_dialog_question_edit_question);
final TextView texttitle=(TextView)centerview.findViewById(R.id.title_text_question);
Button button_ok=(Button)centerview.findViewById(R.id.set_dialog_password_ok_question);
final AlertDialog alertDialog_editpassword=builder.setView(centerview).create();
texttitle.setText("请输入新密保");
button_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Means.isedittext_empty(materialEditText_password)){
Toast.makeText(AboutActivity.this, "请输入密保", Toast.LENGTH_SHORT).show();
}else {
prestenerImp_about.putquestionOnSeting(materialEditText_password.getText().toString());
alertDialog_editpassword.dismiss();
}
}
});
alertDialog_editpassword.show();
}
private void initiscurrentQuestiondialog(){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
LayoutInflater layoutInflater=LayoutInflater.from(this);
View centerview=layoutInflater.inflate(R.layout.activity_set_editquestiondialog,null);
final MaterialEditText materialEditText_password=(MaterialEditText)centerview.findViewById(R.id.set_dialog_question_edit_question);
final TextView texttitle=(TextView)centerview.findViewById(R.id.title_text_question);
Button button_ok=(Button)centerview.findViewById(R.id.set_dialog_password_ok_question);
final AlertDialog alertDialog_editpassword=builder.setView(centerview).create();
texttitle.setText("请输入密保");
button_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Means.isedittext_empty(materialEditText_password)){
Toast.makeText(AboutActivity.this, "请输入密保", Toast.LENGTH_SHORT).show();
}else {
if (prestenerImp_about.iscurrentthequestionfromSeting(materialEditText_password.getText().toString())){
alertDialog_editpassword.dismiss();
prestenerImp_about.showthecurrentpasswordOnAboutactivity();
}else {
Toast.makeText(AboutActivity.this, "密保错误请重新输入", Toast.LENGTH_SHORT).show();
}
}
}
});
alertDialog_editpassword.show();
}
private void initBackgroundcolorview(){//颜色选择
niceSpinner=(NiceSpinner)this.findViewById(R.id.spiner_color_set);
List<String>data=new LinkedList<>(Arrays.asList("默认","珊瑚朱","樱草紫","霓虹绿","绅士黑"));
niceSpinner.attachDataSource(data);
niceSpinner.addOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
switch (i){
case 0:
prestenerImp_about.putcurrentcolorOnSeting(0);
prestenerImp_about.setBackgroundcolorfromSeting();
break;
case 1:
prestenerImp_about.putcurrentcolorOnSeting(1);
prestenerImp_about.setBackgroundcolorfromSeting();
break;
case 2:
prestenerImp_about.putcurrentcolorOnSeting(2);
prestenerImp_about.setBackgroundcolorfromSeting();
break;
case 3:
prestenerImp_about.putcurrentcolorOnSeting(3);
prestenerImp_about.setBackgroundcolorfromSeting();
break;
case 4:
prestenerImp_about.putcurrentcolorOnSeting(4);
prestenerImp_about.setBackgroundcolorfromSeting();
break;
default:
break;
}
EventBus.getDefault().post(new MessageEvent(MessageEvent.UPDATA_COLOR));
}
});
}
private void initAboutcode(){
}
private void initpassworddialog(){//实例化一个创建密码和密保问题的Dialog
AlertDialog.Builder builder=new AlertDialog.Builder(this);
LayoutInflater layoutInflater=LayoutInflater.from(this);
View centerview=layoutInflater.inflate(R.layout.activity_set_passworddialog,null);
final MaterialEditText materialEditText_password=(MaterialEditText)centerview.findViewById(R.id.set_dialog_password_edit);
final MaterialEditText materialEditText_question=(MaterialEditText)centerview.findViewById(R.id.set_dialog_question_edit);
Button button_ok=(Button)centerview.findViewById(R.id.set_dialog_password_ok);
alertDialog_creatpassword=builder.setView(centerview).create();
button_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Means.isedittext_empty(materialEditText_password)&Means.isedittext_empty(materialEditText_question)){
Toast.makeText(AboutActivity.this, "请输入密码和密保", Toast.LENGTH_SHORT).show();
}else if (Means.isedittext_empty(materialEditText_password)|Means.isedittext_empty(materialEditText_question)){
Toast.makeText(AboutActivity.this, "请输入密码或密保", Toast.LENGTH_SHORT).show();
}else {
if (materialEditText_password.getText().toString().length()!=6){
Toast.makeText(AboutActivity.this, "密码为6位数字", Toast.LENGTH_SHORT).show();
}else {
prestenerImp_about.putpasswordandquestionOnSeting(materialEditText_password.getText().toString(),
materialEditText_question.getText().toString());
alertDialog_creatpassword.dismiss();
}
}
}
});
alertDialog_creatpassword.show();
}
@Override
public void showthecurrentPassword(String password) {
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("密码");
builder.setMessage(password);
builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.create().show();
}
@Override
public Context getAboutActivityContext() {
return this;
}
@Override
public Application getAboutApplication() {
return this.getApplication();
}
@Override
public void onClick(View view) {
}
@Override
public void setBackgroundcolorfromSeting(List<Integer>colorlist) {
niceSpinner.setSelectedIndex(prestenerImp_about.getcurrentcolorNumfromSeting());
StatusBarUtil.setColor(this,colorlist.get(0));
toolbar_about.setBackgroundColor(colorlist.get(0));
}
@Override
public void finish() {
super.finish();
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/MainActivityImp.java | app/src/main/java/zql/app_jinnang/View/MainActivityImp.java | package zql.app_jinnang.View;
import android.app.Application;
import android.content.Context;
import android.graphics.Color;
import java.util.List;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Bean.Noteinfo;
/**
* Created by 尽途 on 2018/4/4.
*/
public interface MainActivityImp {
public Context getActivity_this();//获取此Activity的this
public void startListActivity();
public void startListSecretActivity();
public void startCalendarActivity();
public void startSetingActivity();
public void startSearchActivity();
public void setMainBackground(Integer integer);
public void setMainBackgroundIcon(int size);//如果数据库为空,界面加载一个图片显示。
public void openSheetDialog(NoteBean noteBean);
public void readNotefromData(List<NoteBean>noteBeanList);
public Application getMainApplication();
public void setBackgroundcolorfromSeting(List<Integer>mlist);
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/SearchActivityImp.java | app/src/main/java/zql/app_jinnang/View/SearchActivityImp.java | package zql.app_jinnang.View;
import android.app.Application;
import android.content.Context;
import android.graphics.Color;
import java.util.List;
import zql.app_jinnang.Bean.NoteBean;
/**
* Created by 尽途 on 2018/5/1.
*/
public interface SearchActivityImp {
public Context getSearchActivityContext();
public Application getSearchApplication();
public void setBackgroundcolorfromSeting(List<Integer>colorlist);
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/EditActivity.java | app/src/main/java/zql/app_jinnang/View/EditActivity.java | package zql.app_jinnang.View;
import android.annotation.TargetApi;
import android.app.Application;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.jaeger.library.StatusBarUtil;
import com.joaquimley.faboptions.FabOptions;
import com.kyleduo.switchbutton.SwitchButton;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.ImageLoader;
import com.yuyh.library.imgsel.config.ISListConfig;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import me.gujun.android.taggroup.TagGroup;
import zql.app_jinnang.Bean.Means;
import zql.app_jinnang.Bean.MessageEvent;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Bean.Noteinfo;
import zql.app_jinnang.Prestener.Prestener_edit;
import zql.app_jinnang.Prestener.PresterImp_edit;
import zql.app_jinnang.R;
import static zql.app_jinnang.Bean.Means.isphotouri;
public class EditActivity extends AppCompatActivity implements EditActivityImp,View.OnClickListener {
private PresterImp_edit presterImp_edit;//代理接口
private FabOptions fabOptions;
private SwitchButton switchButton_secret;
private Toolbar toolbar_add;
private TagGroup tagGroup;
private List<String> tags;
private MaterialEditText materialEditText;
private NoteBean noteBean;//最后加入数据库的数据类
private static final int REQUEST_CAMERA_CODE = 1;
@TargetApi(Build.VERSION_CODES.M)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
initprestener();
initviewanddata();
presterImp_edit.setBackgroundColorfromUserseting();
initIntentExtra();
}
/**
* 实现界面实例化
*/
private void initviewanddata(){
this.tags=new ArrayList<>();
this.noteBean=new NoteBean();
tags.add("<类型>");
tags.add("<人物>");
tags.add("<日期>");
tags.add("<时间>");
tags.add("<地点>");
tags.add("<图片>");
noteBean.setNotetype("null");//默认为null
noteBean.setPeople("null");
noteBean.setDate("null");
noteBean.setTime("null");
noteBean.setLocation("null");
noteBean.setPhotopath("null");
noteBean.setIsshow(true);
inittoolbarseting();
initfloationgButton();
inittagegroup();
initEdittextView();
initsaveview();
initSwitchbutton();
ISNav.getInstance().init(new ImageLoader() {
@Override
public void displayImage(Context context, String path, ImageView imageView) {
Glide.with(context).load(path).into(imageView);
}
});
}
/**
* 实现代理接口
*/
private void initprestener(){
presterImp_edit=new Prestener_edit(this);
}
/**
* 监听传入值
*/
private void initIntentExtra(){
Intent mintent=getIntent();
Bundle bundle=mintent.getBundleExtra("data");
int type=bundle.getInt("type");
switch (type){
case 0:
updateTagsGroup(0,"工作");
break;
case 1:
updateTagsGroup(0,"学习");
break;
case 2:
updateTagsGroup(0,"生活");
break;
case 3:
updateTagsGroup(0,"日记");
break;
case 4:
updateTagsGroup(0,"旅行");
break;
case 10:
Noteinfo noteinfo=(Noteinfo) bundle.getSerializable("noteinfo");
loadNoteinfotoEdit(noteinfo);
break;
default:
break;
}
}
/**
* 修改背景色
*/
@Override
public void setbackgroundcolor(List<Integer>list) {
StatusBarUtil.setColor(this,list.get(0));
toolbar_add.setBackgroundColor(list.get(1));
}
/**
* //实例化一个edittext
*/
private void initEdittextView(){
materialEditText=(MaterialEditText)this.findViewById(R.id.add_noteinfoedittext);
}
private void initSwitchbutton(){
switchButton_secret=(SwitchButton)this.findViewById(R.id.add_switchbutton_secret);
}
/**
* //实例化保存按钮
*/
private void initsaveview(){
TextView saveview=this.findViewById(R.id.add_savefile);
saveview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
savedNoteinfotoDatabase();
}
});
}
/**
* 添加到数据库
*/
private void savedNoteinfotoDatabase(){
if (materialEditText.getText().toString().isEmpty()){
Toast.makeText(EditActivity.this, "输入框为空,请重新输入", Toast.LENGTH_SHORT).show();
}else {
noteBean.setNoteinfo(materialEditText.getText().toString());
noteBean.setCreatetime(Means.getCreatetime());
if (switchButton_secret.isChecked()){
presterImp_edit.saveNoteinfotoSecrectDatabase(noteBean);
}else {
presterImp_edit.saveNoteinfotoDatabase(noteBean);
}
//EventBus.getDefault().post(new MessageEvent(MessageEvent.UPDATE_DATA));
finish();
}
}
/**
* //实例化标签框
*/
private void inittagegroup(){
tagGroup=(TagGroup)this.findViewById(R.id.add_tag_group);
tagGroup.setTags(tags);
tagGroup.setOnTagClickListener(new TagGroup.OnTagClickListener() {
@Override
public void onTagClick(String tag) {
if (isphotouri(tag)){
initphotoshowdialog(tag);
}else {
Toast.makeText(EditActivity.this,tag, Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* //实例化floatingbuttond对象
*/
private void initfloationgButton(){
fabOptions=(FabOptions)this.findViewById(R.id.add_floatingbutton);
fabOptions.setButtonsMenu(R.menu.menu_item_add_floatingbutton);
fabOptions.setOnClickListener(this);
}
/**
* //实例化toolbar对象,设置返回按钮,监听返回按钮状态
*/
private void inittoolbarseting(){
toolbar_add=(Toolbar)this.findViewById(R.id.toolbar_add);
setSupportActionBar(toolbar_add);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
toolbar_add.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (materialEditText.getText().toString().isEmpty()){
finish();
}else {
initsavenotedialog();
}
}
});
}
/**
* //实例化一个中心dialog输入人物
*/
private void initcenterpeopledialog(){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
LayoutInflater layoutInflater=LayoutInflater.from(this);
View centerview=layoutInflater.inflate(R.layout.activity_add_peopledialog,null);
final TextView add_dialog_ok,add_dialog_cancel;
final MaterialEditText add_dialog_peole_edit;
final AlertDialog alertDialog=builder.setView(centerview).create();
add_dialog_ok=(TextView) centerview.findViewById(R.id.add_dialog_people_ok);
add_dialog_cancel=(TextView) centerview.findViewById(R.id.add_dialog_people_cancel);
add_dialog_peole_edit=(MaterialEditText)centerview.findViewById(R.id.add_dialog_edit_people);
add_dialog_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
updateTagsGroup(1,add_dialog_peole_edit.getText().toString());
alertDialog.dismiss();
}
});
add_dialog_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
/**
* //实例化地址输入dialog
*/
private void initcenterlocationdialog(){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
LayoutInflater layoutInflater=LayoutInflater.from(this);
View centerview=layoutInflater.inflate(R.layout.activity_add_locationdialog,null);
final TextView add_location_ok,add_location_cancel;
final MaterialEditText add_dialog_location_edit;
final AlertDialog alertDialog=builder.setView(centerview).create();
add_location_ok=(TextView)centerview.findViewById(R.id.add_dialog_location_ok);
add_location_cancel=(TextView)centerview.findViewById(R.id.add_dialog_location_cancel);
add_dialog_location_edit=(MaterialEditText)centerview.findViewById(R.id.add_dialog_edit_location);
add_location_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
updateTagsGroup(4,add_dialog_location_edit.getText().toString());
alertDialog.dismiss();
}
});
add_location_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
/**
* //实例化一个类型重新选择菜单
*/
private void initnoteTypeDialog(){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
LayoutInflater layoutInflater=LayoutInflater.from(this);
View centerview=layoutInflater.inflate(R.layout.activity_add_notetypedialog,null);
LinearLayout add_dialog_type_work,add_dialog_type_study,add_dialog_type_live,add_dialog_type_diary,add_dialog_type_travel;
add_dialog_type_work=(LinearLayout)centerview.findViewById(R.id.add_dialog_typenote_work);
add_dialog_type_diary=(LinearLayout)centerview.findViewById(R.id.add_dialog_typenote_diary);
add_dialog_type_live=(LinearLayout)centerview.findViewById(R.id.add_dialog_typenote_live);
add_dialog_type_study=(LinearLayout)centerview.findViewById(R.id.add_dialog_typenote_study);
add_dialog_type_travel=(LinearLayout)centerview.findViewById(R.id.add_dialog_typenote_travel);
final AlertDialog alertDialog=builder.setView(centerview).create();
add_dialog_type_work.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
updateTagsGroup(0,getString(R.string.note_work));
alertDialog.dismiss();
}
});
add_dialog_type_diary.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
updateTagsGroup(0,getString(R.string.note_diary));
alertDialog.dismiss();
}
});
add_dialog_type_live.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
updateTagsGroup(0,getString(R.string.note_live));
alertDialog.dismiss();
}
});
add_dialog_type_study.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
updateTagsGroup(0,getString(R.string.note_study));
alertDialog.dismiss();
}
});
add_dialog_type_travel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
updateTagsGroup(0,getString(R.string.note_travel));
alertDialog.dismiss();
}
});
alertDialog.show();
}
/**
* //实例化图片拍摄选取对象
*/
@TargetApi(Build.VERSION_CODES.M)
private void initphotoseleteActivity(){
ISListConfig config=new ISListConfig.Builder()
.multiSelect(false)
.rememberSelected(false)
.btnBgColor(Color.WHITE)
.btnTextColor(Color.BLACK)
.statusBarColor(getColor(R.color.colorFloatingButton))
.backResId(R.drawable.icon_back)
.title("选取图片")
.titleColor(Color.BLACK)
.titleBgColor(getColor(R.color.colorFloatingButton))
.needCamera(true)
.needCrop(false)
.cropSize(0,0,400,200)
.maxNum(9)
.build();
ISNav.getInstance().toListActivity(this,config,REQUEST_CAMERA_CODE);
}
/**
* //实例化一个日期选择dialog
*/
private void initdatecenterdialog(){
final Calendar calendar=Calendar.getInstance();
new DatePickerDialog(this,0, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
int year=i1+1;
updateTagsGroup(2,i+"年"+year+"月"+i2+"日");
}
},calendar.get(Calendar.YEAR)
,calendar.get(Calendar.MONTH)
,calendar.get(Calendar.DAY_OF_MONTH)).show();
}
/**
//实例化一个时间选择dialog
*/
private void inittimecenterdialog(){
Calendar calendar=Calendar.getInstance();
new TimePickerDialog(this,3, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int i, int i1) {
updateTagsGroup(3,i+"时"+i1+"分");
}
}
,calendar.get(Calendar.HOUR_OF_DAY)
,calendar.get(Calendar.MINUTE)
,true).show();
}
/**
//实例化一个显示图片的dialog
*/
private void initphotoshowdialog(String imagpath){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
LayoutInflater layoutInflater=LayoutInflater.from(this);
View centerview=layoutInflater.inflate(R.layout.activity_add_photodiaolg,null);
final ImageView photoimageview;
final AlertDialog alertDialog=builder.setView(centerview).create();
photoimageview=(ImageView)centerview.findViewById(R.id.add_dialog_imageview);
Glide.with(centerview.getContext()).load(imagpath).into(photoimageview);
photoimageview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
/**
实例化一个保存界面弹出的dialog
*/
private void initsavenotedialog(){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setMessage(R.string.add_dialog_savenote_message);
builder.setCancelable(true);
builder.setPositiveButton(R.string.add_dialog_savenote_save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
savedNoteinfotoDatabase();
dialogInterface.dismiss();
finish();
}
});
builder.setNegativeButton(R.string.add_dialog_savenote_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
finish();
}
});
AlertDialog dialog=builder.create();
dialog.show();
}
/**
* 函数重写区
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_CAMERA_CODE&&resultCode==RESULT_OK&&data!=null){
List<String>pathlist=data.getStringArrayListExtra("result");
updateTagsGroup(5,pathlist.get(0).toString());
}
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.add_floatingbutton_people:
initcenterpeopledialog();
if (fabOptions.isOpen()){
fabOptions.close(null);
}
break;
case R.id.add_floatingbutton_clock:
inittimecenterdialog();
if (fabOptions.isOpen()){
fabOptions.close(null);
}
break;
case R.id.add_floatingbutton_location:
initcenterlocationdialog();
if (fabOptions.isOpen()){
fabOptions.close(null);
}
break;
case R.id.add_floatingbutton_photo:
initphotoseleteActivity();
if (fabOptions.isOpen()){
fabOptions.close(null);
}
break;
case R.id.add_floatingbutton_type:
initnoteTypeDialog();
if (fabOptions.isOpen()){
fabOptions.close(null);
}
break;
case R.id.add_floatingbutton_time:
initdatecenterdialog();
if (fabOptions.isOpen()){
fabOptions.close(null);
}
break;
default:
break;
}
}
/**
* 修改模式下,加载已经有的记录
* @return
*/
private void loadNoteinfotoEdit(Noteinfo noteinfo){
if (noteinfo.getId()!=null){
noteBean.setId(noteinfo.getId());
}
if (!noteinfo.getNoteinfo().isEmpty()){
materialEditText.setText(noteinfo.getNoteinfo());
}
if (!noteinfo.getNotetype().isEmpty()){
updateTagsGroup(0,noteinfo.getNotetype());
}
if (!noteinfo.getPeople().equals("null")){
updateTagsGroup(1,noteinfo.getPeople());
}
if (!noteinfo.getDate().equals("null")){
updateTagsGroup(2,noteinfo.getDate());
}
if (!noteinfo.getTime().equals("null")){
updateTagsGroup(3,noteinfo.getTime());
}
if (!noteinfo.getLocation().equals("null")){
updateTagsGroup(4,noteinfo.getLocation());
}
if (!noteinfo.getPhotopath().equals("图片")||!noteinfo.getPhotopath().equals("null")){
updateTagsGroup(5,noteinfo.getPhotopath());
}
}
/**
* 更新视图
* @param i
* @param str
*/
private void updateTagsGroup(int i,String str){
if (tags!=null){
tags.remove(i);
tags.add(i,str);
}
switch (i){
case 0:
noteBean.setNotetype(str);
break;
case 1:
noteBean.setPeople(str);
break;
case 2:
noteBean.setDate(str);
break;
case 3:
noteBean.setTime(str);
break;
case 4:
noteBean.setLocation(str);
break;
case 5:
noteBean.setPhotopath(str);
break;
default:
break;
}
tagGroup.setTags(tags);
}
/**
获取context
*/
@Override
public Context getbasecontext() {
return this;
}
/**
* 获取application
*/
@Override
public Application getapplication() {
return this.getApplication();
}
/**
* 返回按键事件
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode==KeyEvent.KEYCODE_BACK){
if (materialEditText.getText().toString().isEmpty()){
finish();
}else {
initsavenotedialog();
}
}
return false;
}
@Override
public void finish() {
super.finish();
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/SwipeActivity.java | app/src/main/java/zql/app_jinnang/View/SwipeActivity.java | package zql.app_jinnang.View;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import zql.app_jinnang.R;
public class SwipeActivity extends AppCompatActivity {
private SwipeLayout swipeLayout;
/**
* 是否可以滑动关闭页面
*/
protected boolean swipeEnabled = true;
/**
* 是否可以在页面任意位置右滑关闭页面,如果是false则从左边滑才可以关闭。
*/
protected boolean swipeAnyWhere = true;
public SwipeActivity() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
swipeLayout = new SwipeLayout(this);
}
public void setSwipeAnyWhere(boolean swipeAnyWhere) {
this.swipeAnyWhere = swipeAnyWhere;
}
public boolean isSwipeAnyWhere() {
return swipeAnyWhere;
}
public void setSwipeEnabled(boolean swipeEnabled) {
this.swipeEnabled = swipeEnabled;
}
public boolean isSwipeEnabled() {
return swipeEnabled;
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
swipeLayout.replaceLayer(this);
}
public static int getScreenWidth(Context context) {
DisplayMetrics metrics = new DisplayMetrics();
WindowManager manager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
manager.getDefaultDisplay().getMetrics(metrics);
return metrics.widthPixels;
}
private boolean swipeFinished = false;
@Override
public void finish() {
if (swipeFinished) {
super.finish();
overridePendingTransition(0, 0);
} else {
swipeLayout.cancelPotentialAnimation();
super.finish();
overridePendingTransition(0, R.anim.slide_out_right);
}
}
class SwipeLayout extends FrameLayout {
//private View backgroundLayer;用来设置滑动时的背景色
private Drawable leftShadow;
public SwipeLayout(Context context) {
super(context);
}
public SwipeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SwipeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void replaceLayer(Activity activity) {
leftShadow = activity.getResources().getDrawable(R.drawable.left_shadow);
touchSlop = (int) (touchSlopDP * activity.getResources().getDisplayMetrics().density);
sideWidth = (int) (sideWidthInDP * activity.getResources().getDisplayMetrics().density);
mActivity = activity;
screenWidth = getScreenWidth(activity);
setClickable(true);
final ViewGroup root = (ViewGroup) activity.getWindow().getDecorView();
content = root.getChildAt(0);
ViewGroup.LayoutParams params = content.getLayoutParams();
ViewGroup.LayoutParams params2 = new ViewGroup.LayoutParams(-1, -1);
root.removeView(content);
this.addView(content, params2);
root.addView(this, params);
}
@Override
protected boolean drawChild(@NonNull Canvas canvas, @NonNull View child, long drawingTime) {
boolean result = super.drawChild(canvas, child, drawingTime);
final int shadowWidth = leftShadow.getIntrinsicWidth();
int left = (int) (getContentX()) - shadowWidth;
leftShadow.setBounds(left, child.getTop(), left + shadowWidth, child.getBottom());
leftShadow.draw(canvas);
return result;
}
boolean canSwipe = false;
/**
* 超过了touchslop仍然没有达到没有条件,则忽略以后的动作
*/
boolean ignoreSwipe = false;
View content;
Activity mActivity;
int sideWidthInDP = 16;
int sideWidth = 72;
int screenWidth = 1080;
VelocityTracker tracker;
float downX;
float downY;
float lastX;
float currentX;
float currentY;
int touchSlopDP = 20;
int touchSlop = 60;
@Override
public boolean dispatchTouchEvent(@NonNull MotionEvent ev) {
if (swipeEnabled && !canSwipe && !ignoreSwipe) {
if (swipeAnyWhere) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = ev.getX();
downY = ev.getY();
currentX = downX;
currentY = downY;
lastX = downX;
break;
case MotionEvent.ACTION_MOVE:
float dx = ev.getX() - downX;
float dy = ev.getY() - downY;
if (dx * dx + dy * dy > touchSlop * touchSlop) {
if (dy == 0f || Math.abs(dx / dy) > 1) {
downX = ev.getX();
downY = ev.getY();
currentX = downX;
currentY = downY;
lastX = downX;
canSwipe = true;
tracker = VelocityTracker.obtain();
return true;
} else {
ignoreSwipe = true;
}
}
break;
}
} else if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getX() < sideWidth) {
canSwipe = true;
tracker = VelocityTracker.obtain();
return true;
}
}
if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) {
ignoreSwipe = false;
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return canSwipe || super.onInterceptTouchEvent(ev);
}
boolean hasIgnoreFirstMove;
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
if (canSwipe) {
tracker.addMovement(event);
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downX = event.getX();
downY = event.getY();
currentX = downX;
currentY = downY;
lastX = downX;
break;
case MotionEvent.ACTION_MOVE:
currentX = event.getX();
currentY = event.getY();
float dx = currentX - lastX;
if (dx != 0f && !hasIgnoreFirstMove) {
hasIgnoreFirstMove = true;
dx = dx / dx;
}
if (getContentX() + dx < 0) {
setContentX(0);
} else {
setContentX(getContentX() + dx);
}
lastX = currentX;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
tracker.computeCurrentVelocity(10000);
tracker.computeCurrentVelocity(1000, 20000);
canSwipe = false;
hasIgnoreFirstMove = false;
int mv = screenWidth * 3;
if (Math.abs(tracker.getXVelocity()) > mv) {
animateFromVelocity(tracker.getXVelocity());
} else {
if (getContentX() > screenWidth / 3) {
animateFinish(false);
} else {
animateBack(false);
}
}
tracker.recycle();
break;
default:
break;
}
}
return super.onTouchEvent(event);
}
ObjectAnimator animator;
public void cancelPotentialAnimation() {
if (animator != null) {
animator.removeAllListeners();
animator.cancel();
}
}
public void setContentX(float x) {
int ix = (int) x;
content.setX(ix);
invalidate();
}
public float getContentX() {
return content.getX();
}
/**
* 弹回,不关闭,因为left是0,所以setX和setTranslationX效果是一样的
*
* @param withVel 使用计算出来的时间
*/
private void animateBack(boolean withVel) {
cancelPotentialAnimation();
animator = ObjectAnimator.ofFloat(this, "contentX", getContentX(), 0);
int tmpDuration = withVel ? ((int) (duration * getContentX() / screenWidth)) : duration;
if (tmpDuration < 100) {
tmpDuration = 100;
}
animator.setDuration(tmpDuration);
animator.setInterpolator(new DecelerateInterpolator());
animator.start();
}
private void animateFinish(boolean withVel) {
cancelPotentialAnimation();
animator = ObjectAnimator.ofFloat(this, "contentX", getContentX(), screenWidth);
int tmpDuration = withVel ? ((int) (duration * (screenWidth - getContentX()) / screenWidth)) : duration;
if (tmpDuration < 100) {
tmpDuration = 100;
}
animator.setDuration(tmpDuration);
animator.setInterpolator(new DecelerateInterpolator());
animator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
if (!mActivity.isFinishing()) {
swipeFinished = true;
mActivity.finish();
}
}
@Override
public void onAnimationCancel(Animator animation) {
}
});
animator.start();
}
private final int duration = 200;
private void animateFromVelocity(float v) {
if (v > 0) {
if (getContentX() < screenWidth / 3 && v * duration / 1000 + getContentX() < screenWidth / 3) {
animateBack(false);
} else {
animateFinish(true);
}
} else {
if (getContentX() > screenWidth / 3 && v * duration / 1000 + getContentX() > screenWidth / 3) {
animateFinish(false);
} else {
animateBack(true);
}
}
}
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/CalendarActivityImp.java | app/src/main/java/zql/app_jinnang/View/CalendarActivityImp.java | package zql.app_jinnang.View;
import android.app.Application;
import android.content.Context;
import java.util.List;
import zql.app_jinnang.Bean.NoteBean;
/**
* Created by 尽途 on 2018/5/10.
*/
public interface CalendarActivityImp {
public Context getCalendarActivity();
public void initCalendarViewandgetCreattime(List<String> mlist);
public void readNotebeansfromDatabycreatetime(List<NoteBean>noteBeanList);
public Application getCalendarApplication();
public void setBackgroundcolorfromSeting(List<Integer>colorlist);
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/ListActivityImp.java | app/src/main/java/zql/app_jinnang/View/ListActivityImp.java | package zql.app_jinnang.View;
import android.app.Application;
import android.content.Context;
import android.graphics.Color;
import java.util.List;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Bean.Noteinfo;
/**
* Created by 尽途 on 2018/4/4.
*/
public interface ListActivityImp {
public void opensheeetdialog(NoteBean noteBean);
public Context getListActivityConent();
public void readAllNotefromData(List<NoteBean>noteBeanList);
public Application getListApplication();
public void setBackgroundcolorfromSeting(List<Integer>colorlist);
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/main/java/zql/app_jinnang/View/NoteinfoActivity.java | app/src/main/java/zql/app_jinnang/View/NoteinfoActivity.java | package zql.app_jinnang.View;
import android.annotation.TargetApi;
import android.app.Application;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.transition.Explode;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.jaeger.library.StatusBarUtil;
import java.util.List;
import me.gujun.android.taggroup.TagGroup;
import zql.app_jinnang.Bean.Means;
import zql.app_jinnang.Bean.NoteBean;
import zql.app_jinnang.Bean.Noteinfo;
import zql.app_jinnang.Prestener.PrestenerImp_noteinfo;
import zql.app_jinnang.Prestener.Prestener_noteinfo;
import zql.app_jinnang.R;
public class NoteinfoActivity extends SwipeActivity implements NoteinfoActivityImp{
PrestenerImp_noteinfo prestenerImpNoteinfo;
private TagGroup tagGroup_noteinfo;
private TextView textView_noteinfo;
private ImageView imageview_noteinfo;
private CoordinatorLayout coordinatorLayout_noteinfo;
private Integer maincolor;
private Toolbar toolbar;
@TargetApi(Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_noteinfo);
prestenerImpNoteinfo=new Prestener_noteinfo(this);
initView();
getintentExtra();
prestenerImpNoteinfo.setBackgroundcolorfromSeting();
}
private void initView(){
initToolbarSeting();
initTaggroupView();
initTextview();
initImageview();
}
private void getintentExtra(){//获取传递过来的信息,并通过PrestenerImpNoteInfo读取显示在NoteinfoActivity上
Intent mintent=getIntent();
Bundle bundle=mintent.getExtras();
Noteinfo noteinfo= (Noteinfo) bundle.getSerializable("noteinfo");
prestenerImpNoteinfo.readDatatoNoteinfo(noteinfo);
}
private void initToolbarSeting(){//toolbard的设置
toolbar=(Toolbar)this.findViewById(R.id.toolbar_noteinfo);
coordinatorLayout_noteinfo=(CoordinatorLayout)this.findViewById(R.id.coordinator_noteinfo);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
CollapsingToolbarLayout collapsingToolbarLayout=(CollapsingToolbarLayout)findViewById(R.id.cool_noteinfo);
collapsingToolbarLayout.setExpandedTitleColor(Color.WHITE);
collapsingToolbarLayout.setCollapsedTitleTextColor(Color.WHITE);
}
private void initTaggroupView(){//实例化TagGroup
tagGroup_noteinfo=(TagGroup)this.findViewById(R.id.taggroup_noteinfo_item);
}
private void initTextview(){//实例化TextView
textView_noteinfo=(TextView)this.findViewById(R.id.text_noteinfo_item);
}
private void initImageview(){//实例化ImagView
imageview_noteinfo=(ImageView)this.findViewById(R.id.noteinfo_imageview);
}
@Override
public void readNoteinfotoNotetext(String noteinfo) {
if (noteinfo.isEmpty()){
textView_noteinfo.setText("无内容");
}else {
textView_noteinfo.setText(noteinfo);
toolbar.setTitle(Means.getNoteTitleOnNoteinfoActivity(noteinfo));
}
}
@Override
public void readLabelinfotoNoteTagrroup(List<String> tags) {
if (tags.isEmpty()){
tagGroup_noteinfo.setTags("无标签");
}else {
tagGroup_noteinfo.setTags(tags);
}
}
@Override
public void readPhotopathtoNoteImageview(String photopath,String type) {
if (photopath.equals("<图片>")||photopath.equals("null")){
switch (type){
case "旅行":
imageview_noteinfo.setImageResource(R.drawable.photo_travel);
break;
case "学习":
imageview_noteinfo.setImageResource(R.drawable.photo_study);
break;
case "工作":
imageview_noteinfo.setImageResource(R.drawable.photo_work);
break;
case "日记":
imageview_noteinfo.setImageResource(R.drawable.photo_dilary);
break;
case "生活":
imageview_noteinfo.setImageResource(R.drawable.photo_live);
break;
default:
imageview_noteinfo.setImageResource(R.drawable.photo_live);
break;
}
}else {
Glide.with(this).load(photopath).into(imageview_noteinfo);
}
}
@Override
public Application getNoteinfoApplication() {
return getApplication();
}
@Override
public void setBackgroundcolorfromSeting(List<Integer> colorlist) {
StatusBarUtil.setColor(this, colorlist.get(0));
maincolor=colorlist.get(0);
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
zqljintu/Memory-capsule | https://github.com/zqljintu/Memory-capsule/blob/b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7/app/src/androidTest/java/zql/app_jinnang/ExampleInstrumentedTest.java | app/src/androidTest/java/zql/app_jinnang/ExampleInstrumentedTest.java | package zql.app_jinnang;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("zql.app_jinnang", appContext.getPackageName());
}
}
| java | Apache-2.0 | b06bfb26e86385f5966bb1f35f03b5cc3c4a80a7 | 2026-01-05T02:40:11.771084Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/test/java/com/deepl/api/GlossaryCleanupUtility.java | deepl-java/src/test/java/com/deepl/api/GlossaryCleanupUtility.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import java.util.*;
public class GlossaryCleanupUtility implements AutoCloseable {
private final String glossaryName;
private final Translator translator;
public GlossaryCleanupUtility(Translator translator) {
this(translator, "");
}
public GlossaryCleanupUtility(Translator translator, String testNameSuffix) {
String callingFunc = getCallerFunction();
String uuid = UUID.randomUUID().toString();
this.glossaryName =
String.format("deepl-java-test-glossary: %s%s %s", callingFunc, testNameSuffix, uuid);
this.translator = translator;
}
public String getGlossaryName() {
return glossaryName;
}
@Override
public void close() throws Exception {
List<GlossaryInfo> glossaries = translator.listGlossaries();
for (GlossaryInfo glossary : glossaries) {
if (Objects.equals(glossary.getName(), glossaryName)) {
try {
translator.deleteGlossary(glossary);
} catch (Exception exception) {
// Ignore
}
}
}
}
private static String getCallerFunction() {
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
// Find the first function outside this class following functions in this class
for (int i = 1; i < stacktrace.length; i++) {
if (!stacktrace[i].getClassName().equals(GlossaryCleanupUtility.class.getName())
&& stacktrace[i - 1].getClassName().equals(GlossaryCleanupUtility.class.getName())) {
return stacktrace[i].getMethodName();
}
}
return "unknown";
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/test/java/com/deepl/api/GeneralTest.java | deepl-java/src/test/java/com/deepl/api/GeneralTest.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import java.io.*;
import java.net.*;
import java.time.*;
import java.util.*;
import java.util.stream.Stream;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.condition.EnabledIf;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;
class GeneralTest extends TestBase {
@Test
void testEmptyAuthKey() {
IllegalArgumentException thrown =
Assertions.assertThrows(
IllegalArgumentException.class,
() -> {
Translator translator = new Translator("");
});
}
@Test
void testNullAuthKey() {
IllegalArgumentException thrown =
Assertions.assertThrows(
IllegalArgumentException.class,
() -> {
Translator translator = new Translator(null);
});
}
@Test
void testInvalidAuthKey() {
String authKey = "invalid";
Translator translator = new Translator(authKey);
Assertions.assertThrows(AuthorizationException.class, translator::getUsage);
}
@Test
void testExampleTranslation() throws DeepLException, InterruptedException {
Translator translator = createTranslator();
for (Map.Entry<String, String> entry : exampleText.entrySet()) {
String inputText = entry.getValue();
String sourceLang = LanguageCode.removeRegionalVariant(entry.getKey());
TextResult result = translator.translateText(inputText, sourceLang, "en-US");
Assertions.assertTrue(result.getText().toLowerCase(Locale.ENGLISH).contains("proton"));
Assertions.assertEquals(inputText.length(), result.getBilledCharacters());
}
}
@ParameterizedTest
@CsvSource({
"quality_optimized,quality_optimized",
"prefer_quality_optimized,quality_optimized",
"latency_optimized,latency_optimized"
})
void testModelType(String modelTypeArg, String expectedModelType)
throws DeepLException, InterruptedException {
Translator translator = createTranslator();
String sourceLang = "de";
TextResult result =
translator.translateText(
exampleText.get(sourceLang),
sourceLang,
"en-US",
new TextTranslationOptions().setModelType(modelTypeArg));
Assertions.assertEquals(expectedModelType, result.getModelTypeUsed());
}
@Test
void testInvalidServerUrl() {
Assertions.assertThrows(
DeepLException.class,
() -> {
Translator translator =
new Translator(authKey, new TranslatorOptions().setServerUrl("http:/api.deepl.com"));
translator.getUsage();
});
}
@Test
void testMixedDirectionText() throws DeepLException, InterruptedException {
Assumptions.assumeFalse(isMockServer);
Translator translator = createTranslator();
TextTranslationOptions options =
new TextTranslationOptions().setTagHandling("xml").setIgnoreTags(Arrays.asList("xml"));
String arIgnorePart = "<ignore>يجب تجاهل هذا الجزء.</ignore>";
String enSentenceWithArIgnorePart =
"<p>This is a <b>short</b> <i>sentence</i>. " + arIgnorePart + " This is another sentence.";
String enIgnorePart = "<ignore>This part should be ignored.</ignore>";
String arSentenceWithEnIgnorePart =
"<p>هذه <i>جملة</i> <b>قصيرة</b>. " + enIgnorePart + "هذه جملة أخرى.</p>";
TextResult enResult =
translator.translateText(enSentenceWithArIgnorePart, null, "en-US", options);
Assertions.assertTrue(enResult.getText().contains(arIgnorePart));
TextResult arResult = translator.translateText(arSentenceWithEnIgnorePart, null, "ar", options);
Assertions.assertTrue(arResult.getText().contains(enIgnorePart));
}
@Test
void testUsage() throws DeepLException, InterruptedException {
Translator translator = createTranslator();
Usage usage = translator.getUsage();
Assertions.assertTrue(usage.toString().contains("Usage this billing period"));
}
@Test
void testUsageLarge() throws DeepLException, InterruptedException {
Assumptions.assumeTrue(isMockServer);
SessionOptions sessionOptions = new SessionOptions();
sessionOptions.initCharacterLimit = 1000000000000L;
Map<String, String> headers = sessionOptions.createSessionHeaders();
TranslatorOptions options = new TranslatorOptions().setHeaders(headers).setServerUrl(serverUrl);
String authKeyWithUuid = authKey + "/" + UUID.randomUUID().toString();
Translator translator = new Translator(authKeyWithUuid, options);
Usage usage = translator.getUsage();
Assertions.assertNotNull(usage.getCharacter());
Assertions.assertEquals(sessionOptions.initCharacterLimit, usage.getCharacter().getLimit());
}
@Test
void testGetSourceAndTargetLanguages() throws DeepLException, InterruptedException {
Translator translator = createTranslator();
List<Language> sourceLanguages = translator.getSourceLanguages();
List<Language> targetLanguages = translator.getTargetLanguages();
for (Language language : sourceLanguages) {
if (Objects.equals(language.getCode(), "en")) {
Assertions.assertEquals("English", language.getName());
}
Assertions.assertNull(language.getSupportsFormality());
}
Assertions.assertTrue(sourceLanguages.size() >= 29);
for (Language language : targetLanguages) {
Assertions.assertNotNull(language.getSupportsFormality());
if (Objects.equals(language.getCode(), "de")) {
Assertions.assertTrue(language.getSupportsFormality());
Assertions.assertEquals("German", language.getName());
}
}
Assertions.assertTrue(targetLanguages.size() >= 31);
}
@Test
void testGetGlossaryLanguages() throws DeepLException, InterruptedException {
Translator translator = createTranslator();
List<GlossaryLanguagePair> glossaryLanguagePairs = translator.getGlossaryLanguages();
Assertions.assertTrue(glossaryLanguagePairs.size() > 0);
for (GlossaryLanguagePair glossaryLanguagePair : glossaryLanguagePairs) {
Assertions.assertTrue(glossaryLanguagePair.getSourceLanguage().length() > 0);
Assertions.assertTrue(glossaryLanguagePair.getTargetLanguage().length() > 0);
}
}
@Test
void testAuthKeyIsFreeAccount() {
Assertions.assertTrue(
Translator.isFreeAccountAuthKey("b493b8ef-0176-215d-82fe-e28f182c9544:fx"));
Assertions.assertFalse(Translator.isFreeAccountAuthKey("b493b8ef-0176-215d-82fe-e28f182c9544"));
}
@Test
void testProxyUsage() throws DeepLException, InterruptedException, MalformedURLException {
Assumptions.assumeTrue(isMockProxyServer);
SessionOptions sessionOptions = new SessionOptions();
sessionOptions.expectProxy = true;
Map<String, String> headers = sessionOptions.createSessionHeaders();
URL proxyUrl = new URL(TestBase.proxyUrl);
TranslatorOptions options =
new TranslatorOptions()
.setProxy(
new Proxy(
Proxy.Type.HTTP, new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())))
.setHeaders(headers)
.setServerUrl(serverUrl);
Translator translator = new Translator(authKey, options);
translator.getUsage();
}
@Test
void testUsageNoResponse() {
Assumptions.assumeTrue(isMockServer);
// Lower the retry count and timeout for this test
Translator translator =
createTranslator(
new SessionOptions().setNoResponse(2),
new TranslatorOptions().setMaxRetries(0).setTimeout(Duration.ofMillis(1)));
Assertions.assertThrows(ConnectionException.class, translator::getUsage);
}
@Test
void testTranslateTooManyRequests() {
Assumptions.assumeTrue(isMockServer);
// Lower the retry count and timeout for this test
Translator translator =
createTranslator(
new SessionOptions().setRespondWith429(2), new TranslatorOptions().setMaxRetries(0));
Assertions.assertThrows(
TooManyRequestsException.class,
() -> translator.translateText(exampleText.get("en"), null, "DE"));
}
@Test
void testUsageOverrun() throws DeepLException, InterruptedException, IOException {
Assumptions.assumeTrue(isMockServer);
int characterLimit = 20;
int documentLimit = 1;
// Lower the retry count and timeout for this test
Translator translator =
createTranslator(
new SessionOptions()
.setInitCharacterLimit(characterLimit)
.setInitDocumentLimit(documentLimit)
.withRandomAuthKey(),
new TranslatorOptions().setMaxRetries(0).setTimeout(Duration.ofMillis(1)));
Usage usage = translator.getUsage();
Assertions.assertNotNull(usage.getCharacter());
Assertions.assertNotNull(usage.getDocument());
Assertions.assertNull(usage.getTeamDocument());
Assertions.assertEquals(0, usage.getCharacter().getCount());
Assertions.assertEquals(0, usage.getDocument().getCount());
Assertions.assertEquals(characterLimit, usage.getCharacter().getLimit());
Assertions.assertEquals(documentLimit, usage.getDocument().getLimit());
Assertions.assertTrue(usage.toString().contains("Characters: 0 of 20"));
Assertions.assertTrue(usage.toString().contains("Documents: 0 of 1"));
File inputFile = createInputFile();
writeToFile(inputFile, repeatString("a", characterLimit));
File outputFile = createOutputFile();
translator.translateDocument(inputFile, outputFile, null, "de");
usage = translator.getUsage();
Assertions.assertTrue(usage.anyLimitReached());
Assertions.assertNotNull(usage.getCharacter());
Assertions.assertNotNull(usage.getDocument());
Assertions.assertTrue(usage.getDocument().limitReached());
Assertions.assertTrue(usage.getCharacter().limitReached());
Assertions.assertThrows(
IOException.class,
() -> {
translator.translateDocument(inputFile, outputFile, null, "de");
});
outputFile.delete();
DocumentTranslationException thrownDeepLException =
Assertions.assertThrows(
DocumentTranslationException.class,
() -> {
translator.translateDocument(inputFile, outputFile, null, "de");
});
Assertions.assertNull(thrownDeepLException.getHandle());
Assertions.assertEquals(
QuotaExceededException.class, thrownDeepLException.getCause().getClass());
Assertions.assertThrows(
QuotaExceededException.class,
() -> {
translator.translateText(exampleText.get("en"), null, "de");
});
}
@Test
void testUsageTeamDocumentLimit() throws Exception {
Assumptions.assumeTrue(isMockServer);
int teamDocumentLimit = 1;
Translator translator =
createTranslator(
new SessionOptions()
.setInitCharacterLimit(0)
.setInitDocumentLimit(0)
.setInitTeamDocumentLimit(teamDocumentLimit)
.withRandomAuthKey());
Usage usage = translator.getUsage();
Assertions.assertNull(usage.getCharacter());
Assertions.assertNull(usage.getDocument());
Assertions.assertNotNull(usage.getTeamDocument());
Assertions.assertEquals(0, usage.getTeamDocument().getCount());
Assertions.assertEquals(teamDocumentLimit, usage.getTeamDocument().getLimit());
Assertions.assertTrue(usage.toString().contains("Team documents: 0 of 1"));
File inputFile = createInputFile();
writeToFile(inputFile, "a");
File outputFile = createOutputFile();
translator.translateDocument(inputFile, outputFile, null, "de");
usage = translator.getUsage();
Assertions.assertTrue(usage.anyLimitReached());
Assertions.assertNotNull(usage.getTeamDocument());
Assertions.assertTrue(usage.getTeamDocument().limitReached());
}
@ParameterizedTest
@MethodSource("provideUserAgentTestData")
void testUserAgent(
SessionOptions sessionOptions,
TranslatorOptions translatorOptions,
Iterable<String> requiredStrings,
Iterable<String> blocklistedStrings)
throws Exception {
Map<String, String> headers = new HashMap<>();
HttpURLConnection con = Mockito.mock(HttpURLConnection.class);
Mockito.doAnswer(
invocation -> {
String key = (String) invocation.getArgument(0);
String value = (String) invocation.getArgument(1);
headers.put(key, value);
return null;
})
.when(con)
.setRequestProperty(Mockito.any(String.class), Mockito.any(String.class));
Mockito.when(con.getResponseCode()).thenReturn(200);
try (MockedConstruction<URL> mockUrl =
Mockito.mockConstruction(
URL.class,
(mock, context) -> {
Mockito.when(mock.openConnection()).thenReturn(con);
})) {
Translator translator = createTranslator(sessionOptions, translatorOptions);
Usage usage = translator.getUsage();
String userAgentHeader = headers.get("User-Agent");
for (String s : requiredStrings) {
Assertions.assertTrue(
userAgentHeader.contains(s),
String.format(
"Expected User-Agent header to contain %s\nActual:\n%s", s, userAgentHeader));
}
for (String n : blocklistedStrings) {
Assertions.assertFalse(
userAgentHeader.contains(n),
String.format(
"Expected User-Agent header not to contain %s\nActual:\n%s", n, userAgentHeader));
}
}
}
@Test
@EnabledIf("runV1ApiTests")
void testV1Api() throws DeepLException, InterruptedException {
SessionOptions sessionOptions = new SessionOptions();
DeepLClientOptions clientOptions =
(new DeepLClientOptions()).setApiVersion(DeepLApiVersion.VERSION_1);
DeepLClient client = createDeepLClient(sessionOptions, clientOptions);
for (Map.Entry<String, String> entry : exampleText.entrySet()) {
String inputText = entry.getValue();
String sourceLang = LanguageCode.removeRegionalVariant(entry.getKey());
TextResult result = client.translateText(inputText, sourceLang, "en-US");
Assertions.assertTrue(result.getText().toLowerCase(Locale.ENGLISH).contains("proton"));
Assertions.assertEquals(inputText.length(), result.getBilledCharacters());
}
Usage usage = client.getUsage();
Assertions.assertTrue(usage.toString().contains("Usage this billing period"));
List<Language> sourceLanguages = client.getSourceLanguages();
List<Language> targetLanguages = client.getTargetLanguages();
Assertions.assertTrue(sourceLanguages.size() > 20);
Assertions.assertTrue(targetLanguages.size() > 20);
Assertions.assertTrue(targetLanguages.size() >= sourceLanguages.size());
}
// Session options & Translator options: Used to construct the `Translator`
// Next arg: List of Strings that must be contained in the user agent header
// Last arg: List of Strings that must not be contained in the user agent header
private static Stream<? extends Arguments> provideUserAgentTestData() {
Map<String, String> testHeaders = new HashMap<>();
testHeaders.put("User-Agent", "my custom user agent");
Iterable<String> lightPlatformInfo = Arrays.asList("deepl-java/");
Iterable<String> lightPlatformInfoWithAppInfo =
Arrays.asList("deepl", "my-java-translation-plugin/1.2.3");
Iterable<String> detailedPlatformInfo = Arrays.asList(" java/", "(");
Iterable<String> detailedPlatformInfoWithAppInfo =
Arrays.asList(" java/", "(", "my-java-translation-plugin/1.2.3");
Iterable<String> customUserAgent = Arrays.asList("my custom user agent");
Iterable<String> noStrings = new ArrayList<String>();
return Stream.of(
Arguments.of(
new SessionOptions(), new TranslatorOptions(), detailedPlatformInfo, noStrings),
Arguments.of(
new SessionOptions(),
new TranslatorOptions().setSendPlatformInfo(false),
lightPlatformInfo,
detailedPlatformInfo),
Arguments.of(
new SessionOptions(),
new TranslatorOptions().setHeaders(testHeaders),
customUserAgent,
detailedPlatformInfo),
Arguments.of(
new SessionOptions(),
new TranslatorOptions().setAppInfo("my-java-translation-plugin", "1.2.3"),
detailedPlatformInfoWithAppInfo,
noStrings),
Arguments.of(
new SessionOptions(),
new TranslatorOptions()
.setSendPlatformInfo(false)
.setAppInfo("my-java-translation-plugin", "1.2.3"),
lightPlatformInfoWithAppInfo,
detailedPlatformInfo),
Arguments.of(
new SessionOptions(),
new TranslatorOptions()
.setHeaders(testHeaders)
.setAppInfo("my-java-translation-plugin", "1.2.3"),
customUserAgent,
detailedPlatformInfoWithAppInfo));
}
boolean runV1ApiTests() {
return Boolean.getBoolean("runV1ApiTests");
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/test/java/com/deepl/api/MultilingualGlossaryCleanupUtility.java | deepl-java/src/test/java/com/deepl/api/MultilingualGlossaryCleanupUtility.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
public class MultilingualGlossaryCleanupUtility implements AutoCloseable {
private final String glossaryName;
private final DeepLClient deepLClient;
public MultilingualGlossaryCleanupUtility(DeepLClient deepLClient) {
this(deepLClient, "");
}
public MultilingualGlossaryCleanupUtility(DeepLClient deepLClient, String testNameSuffix) {
String callingFunc = getCallerFunction();
String uuid = UUID.randomUUID().toString();
this.glossaryName =
String.format("deepl-java-test-glossary: %s%s %s", callingFunc, testNameSuffix, uuid);
this.deepLClient = deepLClient;
}
public String getGlossaryName() {
return glossaryName;
}
@Override
public void close() throws Exception {
List<MultilingualGlossaryInfo> glossaries = deepLClient.listMultilingualGlossaries();
for (MultilingualGlossaryInfo glossary : glossaries) {
if (Objects.equals(glossary.getName(), glossaryName)) {
try {
deepLClient.deleteMultilingualGlossary(glossary.getGlossaryId());
} catch (Exception exception) {
// Ignore
System.out.println(
"Failed to delete glossary: "
+ glossaryName
+ "\nException: "
+ exception.getMessage());
}
}
}
}
private static String getCallerFunction() {
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
// Find the first function outside this class following functions in this class
for (int i = 1; i < stacktrace.length; i++) {
if (!stacktrace[i].getClassName().equals(MultilingualGlossaryCleanupUtility.class.getName())
&& stacktrace[i - 1]
.getClassName()
.equals(MultilingualGlossaryCleanupUtility.class.getName())) {
return stacktrace[i].getMethodName();
}
}
return "unknown";
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/test/java/com/deepl/api/StyleRuleTest.java | deepl-java/src/test/java/com/deepl/api/StyleRuleTest.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import java.util.List;
import org.junit.jupiter.api.*;
public class StyleRuleTest extends TestBase {
private static final String DEFAULT_STYLE_ID = "dca2e053-8ae5-45e6-a0d2-881156e7f4e4";
@Test
void testGetAllStyleRules() throws Exception {
Assumptions.assumeTrue(isMockServer);
DeepLClient client = createDeepLClient();
List<StyleRuleInfo> styleRules = client.getAllStyleRules(0, 10, true);
Assertions.assertNotNull(styleRules);
Assertions.assertFalse(styleRules.isEmpty());
Assertions.assertEquals(DEFAULT_STYLE_ID, styleRules.get(0).getStyleId());
Assertions.assertEquals("Default Style Rule", styleRules.get(0).getName());
Assertions.assertNotNull(styleRules.get(0).getCreationTime());
Assertions.assertNotNull(styleRules.get(0).getUpdatedTime());
Assertions.assertEquals("en", styleRules.get(0).getLanguage());
Assertions.assertEquals(1, styleRules.get(0).getVersion());
Assertions.assertNotNull(styleRules.get(0).getConfiguredRules());
Assertions.assertNotNull(styleRules.get(0).getCustomInstructions());
}
@Test
void testGetAllStyleRulesWithoutDetailed() throws Exception {
Assumptions.assumeTrue(isMockServer);
DeepLClient client = createDeepLClient();
List<StyleRuleInfo> styleRules = client.getAllStyleRules();
Assertions.assertNotNull(styleRules);
Assertions.assertFalse(styleRules.isEmpty());
Assertions.assertEquals(DEFAULT_STYLE_ID, styleRules.get(0).getStyleId());
Assertions.assertNull(styleRules.get(0).getConfiguredRules());
Assertions.assertNull(styleRules.get(0).getCustomInstructions());
}
@Test
void testTranslateTextWithStyleId() throws Exception {
// Note: this test may use the mock server that will not translate the text
// with a style rule, therefore we do not check the translated result.
Assumptions.assumeTrue(isMockServer);
DeepLClient client = createDeepLClient();
String text = "Hallo, Welt!";
TextResult result =
client.translateText(
text, "de", "en-US", new TextTranslationOptions().setStyleId(DEFAULT_STYLE_ID));
Assertions.assertNotNull(result);
}
@Test
void testTranslateTextWithStyleRuleInfo() throws Exception {
Assumptions.assumeTrue(isMockServer);
DeepLClient client = createDeepLClient();
List<StyleRuleInfo> styleRules = client.getAllStyleRules();
StyleRuleInfo rule = styleRules.get(0);
String text = "Hallo, Welt!";
TextResult result =
client.translateText(text, "de", "en-US", new TextTranslationOptions().setStyleRule(rule));
Assertions.assertNotNull(result);
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/test/java/com/deepl/api/TranslateDocumentTest.java | deepl-java/src/test/java/com/deepl/api/TranslateDocumentTest.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.Date;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
public class TranslateDocumentTest extends TestBase {
@Test
void testTranslateDocument() throws Exception {
Translator translator = createTranslator();
File inputFile = createInputFile();
File outputFile = createOutputFile();
translator.translateDocument(inputFile, outputFile, "en", "de");
Assertions.assertEquals(exampleOutput, readFromFile(outputFile));
// Test with output path occupied
Assertions.assertThrows(
IOException.class,
() -> {
translator.translateDocument(inputFile, outputFile, "en", "de");
});
}
@Test
void testTranslateDocumentFailsWithOutputOccupied() throws Exception {
Translator translator = createTranslator();
File inputFile = createInputFile();
File outputFile = createOutputFile();
outputFile.createNewFile();
// Test with output path occupied
Assertions.assertThrows(
IOException.class,
() -> {
translator.translateDocument(inputFile, outputFile, "en", "de");
});
}
@Test
void testTranslateDocumentWithRetry() throws Exception {
Assumptions.assumeTrue(isMockServer);
Translator translator =
createTranslator(
new SessionOptions().setNoResponse(1),
new TranslatorOptions().setTimeout(Duration.ofSeconds(1)));
File outputFile = createOutputFile();
translator.translateDocument(createInputFile(), outputFile, "en", "de");
Assertions.assertEquals(exampleOutput, readFromFile(outputFile));
}
@Test
void testTranslateDocumentWithWaiting() throws Exception {
Assumptions.assumeTrue(isMockServer);
Translator translator =
createTranslator(
new SessionOptions()
.setDocumentTranslateTime(Duration.ofSeconds(2))
.setDocumentQueueTime(Duration.ofSeconds(2)));
File outputFile = createOutputFile();
translator.translateDocument(createInputFile(), outputFile, "en", "de");
Assertions.assertEquals(exampleOutput, readFromFile(outputFile));
}
@Test
void testTranslateLargeDocument() throws Exception {
Assumptions.assumeTrue(isMockServer);
Translator translator = createTranslator();
File inputFile = createInputFile(exampleLargeInput);
File outputFile = createOutputFile();
translator.translateDocument(inputFile, outputFile, "en", "de");
Assertions.assertEquals(exampleLargeOutput, readFromFile(outputFile));
}
@Test
void testTranslateDocumentFormality() throws Exception {
Translator translator = createTranslator();
File inputFile = createInputFile("How are you?");
File outputFile = createOutputFile();
translator.translateDocument(
inputFile,
outputFile,
"en",
"de",
new DocumentTranslationOptions().setFormality(Formality.More));
if (!isMockServer) {
Assertions.assertTrue(readFromFile(outputFile).contains("Ihnen"));
}
outputFile.delete();
translator.translateDocument(
inputFile,
outputFile,
"en",
"de",
new DocumentTranslationOptions().setFormality(Formality.Less));
if (!isMockServer) {
Assertions.assertTrue(readFromFile(outputFile).contains("dir"));
}
}
@Test
void testTranslateDocumentFailureDuringTranslation() throws Exception {
Translator translator = createTranslator();
// Translating text from DE to DE will trigger error
File inputFile = createInputFile(exampleText.get("de"));
File outputFile = createOutputFile();
DocumentTranslationException exception =
Assertions.assertThrows(
DocumentTranslationException.class,
() -> {
translator.translateDocument(inputFile, outputFile, null, "de");
});
Assertions.assertTrue(exception.getMessage().contains("Source and target language"));
}
@Test
void testInvalidDocument() throws Exception {
Translator translator = createTranslator();
File inputFile = new File(tempDir + "/document.xyz");
writeToFile(inputFile, exampleText.get("en"));
File outputFile = new File(tempDir + "/output_document.xyz");
outputFile.delete();
DocumentTranslationException exception =
Assertions.assertThrows(
DocumentTranslationException.class,
() -> {
translator.translateDocument(inputFile, outputFile, "en", "de");
});
Assertions.assertNull(exception.getHandle());
}
@Test
void testTranslateDocumentLowLevel() throws Exception {
Assumptions.assumeTrue(isMockServer);
// Set a small document queue time to attempt downloading a queued document
Translator translator =
createTranslator(new SessionOptions().setDocumentQueueTime(Duration.ofMillis(100)));
File inputFile = createInputFile();
File outputFile = createOutputFile();
final DocumentHandle handle = translator.translateDocumentUpload(inputFile, "en", "de");
DocumentStatus status = translator.translateDocumentStatus(handle);
Assertions.assertEquals(handle.getDocumentId(), status.getDocumentId());
Assertions.assertTrue(status.ok());
Assertions.assertFalse(status.done());
// Test recreating a document handle from id & key
String documentId = handle.getDocumentId();
String documentKey = handle.getDocumentKey();
DocumentHandle recreatedHandle = new DocumentHandle(documentId, documentKey);
status = translator.translateDocumentStatus(recreatedHandle);
Assertions.assertTrue(status.ok());
while (status.ok() && !status.done()) {
Thread.sleep(200);
status = translator.translateDocumentStatus(recreatedHandle);
}
Assertions.assertTrue(status.ok() && status.done());
translator.translateDocumentDownload(recreatedHandle, outputFile);
Assertions.assertEquals(exampleOutput, readFromFile(outputFile));
}
@Test
void testTranslateDocumentRequestFields() throws Exception {
Assumptions.assumeTrue(isMockServer);
Translator translator =
createTranslator(
new SessionOptions()
.setDocumentTranslateTime(Duration.ofSeconds(2))
.setDocumentQueueTime(Duration.ofSeconds(2)));
File inputFile = createInputFile();
File outputFile = createOutputFile();
long timeBefore = new Date().getTime();
DocumentHandle handle = translator.translateDocumentUpload(inputFile, "en", "de");
DocumentStatus status = translator.translateDocumentStatus(handle);
Assertions.assertTrue(status.ok());
Assertions.assertTrue(
status.getSecondsRemaining() == null || status.getSecondsRemaining() >= 0);
status = translator.translateDocumentWaitUntilDone(handle);
translator.translateDocumentDownload(handle, outputFile);
long timeAfter = new Date().getTime();
Assertions.assertEquals(exampleInput.length(), status.getBilledCharacters());
Assertions.assertTrue(timeAfter - timeBefore > 4000);
Assertions.assertEquals(exampleOutput, readFromFile(outputFile));
}
@Test
void testRecreateDocumentHandleInvalid() {
Translator translator = createTranslator();
String documentId = repeatString("12AB", 8);
String documentKey = repeatString("CD34", 16);
DocumentHandle handle = new DocumentHandle(documentId, documentKey);
Assertions.assertThrows(
NotFoundException.class,
() -> {
translator.translateDocumentStatus(handle);
});
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/test/java/com/deepl/api/SessionOptions.java | deepl-java/src/test/java/com/deepl/api/SessionOptions.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class SessionOptions {
// Mock server session options
public Integer noResponse;
public Integer respondWith429;
public Long initCharacterLimit;
public Long initDocumentLimit;
public Long initTeamDocumentLimit;
public Integer documentFailure;
public Duration documentQueueTime;
public Duration documentTranslateTime;
public Boolean expectProxy;
public boolean randomAuthKey;
SessionOptions() {
randomAuthKey = false;
}
public Map<String, String> createSessionHeaders() {
Map<String, String> headers = new HashMap<>();
String uuid = UUID.randomUUID().toString();
headers.put("mock-server-session", "deepl-java-test/" + uuid);
if (noResponse != null) {
headers.put("mock-server-session-no-response-count", noResponse.toString());
}
if (respondWith429 != null) {
headers.put("mock-server-session-429-count", respondWith429.toString());
}
if (initCharacterLimit != null) {
headers.put("mock-server-session-init-character-limit", initCharacterLimit.toString());
}
if (initDocumentLimit != null) {
headers.put("mock-server-session-init-document-limit", initDocumentLimit.toString());
}
if (initTeamDocumentLimit != null) {
headers.put("mock-server-session-init-team-document-limit", initTeamDocumentLimit.toString());
}
if (documentFailure != null) {
headers.put("mock-server-session-doc-failure", documentFailure.toString());
}
if (documentQueueTime != null) {
headers.put(
"mock-server-session-doc-queue-time", Long.toString(documentQueueTime.toMillis()));
}
if (documentTranslateTime != null) {
headers.put(
"mock-server-session-doc-translate-time",
Long.toString(documentTranslateTime.toMillis()));
}
if (expectProxy != null) {
headers.put("mock-server-session-expect-proxy", expectProxy ? "1" : "0");
}
return headers;
}
public SessionOptions setNoResponse(int noResponse) {
this.noResponse = noResponse;
return this;
}
public SessionOptions setRespondWith429(int respondWith429) {
this.respondWith429 = respondWith429;
return this;
}
public SessionOptions setInitCharacterLimit(long initCharacterLimit) {
this.initCharacterLimit = initCharacterLimit;
return this;
}
public SessionOptions setInitDocumentLimit(long initDocumentLimit) {
this.initDocumentLimit = initDocumentLimit;
return this;
}
public SessionOptions setInitTeamDocumentLimit(long initTeamDocumentLimit) {
this.initTeamDocumentLimit = initTeamDocumentLimit;
return this;
}
public SessionOptions setDocumentFailure(int documentFailure) {
this.documentFailure = documentFailure;
return this;
}
public SessionOptions setDocumentQueueTime(Duration documentQueueTime) {
this.documentQueueTime = documentQueueTime;
return this;
}
public SessionOptions setDocumentTranslateTime(Duration documentTranslateTime) {
this.documentTranslateTime = documentTranslateTime;
return this;
}
public SessionOptions setExpectProxy(boolean expectProxy) {
this.expectProxy = expectProxy;
return this;
}
public SessionOptions withRandomAuthKey() {
this.randomAuthKey = true;
return this;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/test/java/com/deepl/api/RephraseTextTest.java | deepl-java/src/test/java/com/deepl/api/RephraseTextTest.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import java.util.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class RephraseTextTest extends TestBase {
@Test
void testSingleText() throws DeepLException, InterruptedException {
String inputText = exampleText.get("en");
DeepLClient client = createDeepLClient();
WriteResult result = client.rephraseText(inputText, "EN-GB", null);
this.checkSanityOfImprovements(inputText, result, "EN", "EN-GB", 0.2f);
}
@Test
void testTextArray() throws DeepLException, InterruptedException {
DeepLClient client = createDeepLClient();
List<String> texts = new ArrayList<>();
texts.add(exampleText.get("en"));
texts.add(exampleText.get("en"));
List<WriteResult> results = client.rephraseText(texts, "EN-GB", null);
for (int i = 0; i < texts.size(); i++) {
this.checkSanityOfImprovements(texts.get(i), results.get(i), "EN", "EN-GB", 0.2f);
}
}
@Test
void testBusinessStyle() throws DeepLException, InterruptedException {
String inputText =
"As Gregor Samsa awoke one morning from uneasy dreams he found himself transformed in his bed into a gigantic insect.";
DeepLClient client = createDeepLClient();
TextRephraseOptions options =
(new TextRephraseOptions()).setWritingStyle(WritingStyle.Business.getValue());
WriteResult result = client.rephraseText(inputText, "EN-GB", options);
if (!isMockServer) {
this.checkSanityOfImprovements(inputText, result, "EN", "EN-GB", 0.2f);
}
}
protected void checkSanityOfImprovements(
String inputText,
WriteResult result,
String expectedSourceLanguageUppercase,
String expectedTargetLanguageUppercase,
float epsilon) {
Assertions.assertEquals(
expectedSourceLanguageUppercase, result.getDetectedSourceLanguage().toUpperCase());
Assertions.assertEquals(
expectedTargetLanguageUppercase, result.getTargetLanguage().toUpperCase());
int nImproved = result.getText().length();
int nOriginal = inputText.length();
Assertions.assertTrue(
1 / (1 + epsilon) <= ((float) nImproved) / nOriginal,
"Improved text is too short compared to original, improved:\n"
+ result.getText()
+ "\n, original:\n"
+ inputText);
Assertions.assertTrue(
nImproved / nOriginal <= (1 + epsilon), "Improved text is too long compared to original");
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/test/java/com/deepl/api/TranslateTextTest.java | deepl-java/src/test/java/com/deepl/api/TranslateTextTest.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import java.util.*;
import java.util.function.Consumer;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
public class TranslateTextTest extends TestBase {
@Test
void testSingleText() throws DeepLException, InterruptedException {
Translator translator = createTranslator();
TextResult result = translator.translateText(exampleText.get("en"), null, LanguageCode.German);
Assertions.assertEquals(exampleText.get("de"), result.getText());
Assertions.assertEquals("en", result.getDetectedSourceLanguage());
Assertions.assertEquals(exampleText.get("en").length(), result.getBilledCharacters());
}
@Test
void testTextArray() throws DeepLException, InterruptedException {
Translator translator = createTranslator();
List<String> texts = new ArrayList<>();
texts.add(exampleText.get("fr"));
texts.add(exampleText.get("en"));
List<TextResult> result = translator.translateText(texts, null, LanguageCode.German);
Assertions.assertEquals(exampleText.get("de"), result.get(0).getText());
Assertions.assertEquals(exampleText.get("de"), result.get(1).getText());
}
@Test
void testSourceLang() throws DeepLException, InterruptedException {
Consumer<TextResult> checkResult =
(result) -> {
Assertions.assertEquals(exampleText.get("de"), result.getText());
Assertions.assertEquals("en", result.getDetectedSourceLanguage());
};
Translator translator = createTranslator();
checkResult.accept(translator.translateText(exampleText.get("en"), null, "DE"));
checkResult.accept(translator.translateText(exampleText.get("en"), "En", "DE"));
checkResult.accept(translator.translateText(exampleText.get("en"), "en", "DE"));
List<Language> sourceLanguages = translator.getSourceLanguages();
Language sourceLanguageEn =
sourceLanguages.stream()
.filter((language -> Objects.equals(language.getCode(), "en")))
.findFirst()
.orElse(null);
Language sourceLanguageDe =
sourceLanguages.stream()
.filter((language -> Objects.equals(language.getCode(), "de")))
.findFirst()
.orElse(null);
Assertions.assertNotNull(sourceLanguageEn);
Assertions.assertNotNull(sourceLanguageDe);
checkResult.accept(
translator.translateText(exampleText.get("en"), sourceLanguageEn, sourceLanguageDe));
}
@Test
void testTargetLang() throws DeepLException, InterruptedException {
Consumer<TextResult> checkResult =
(result) -> {
Assertions.assertEquals(exampleText.get("de"), result.getText());
Assertions.assertEquals("en", result.getDetectedSourceLanguage());
};
Translator translator = createTranslator();
checkResult.accept(translator.translateText(exampleText.get("en"), null, "De"));
checkResult.accept(translator.translateText(exampleText.get("en"), null, "de"));
checkResult.accept(translator.translateText(exampleText.get("en"), null, "DE"));
List<Language> targetLanguages = translator.getTargetLanguages();
Language targetLanguageDe =
targetLanguages.stream()
.filter((language -> Objects.equals(language.getCode(), "de")))
.findFirst()
.orElse(null);
Assertions.assertNotNull(targetLanguageDe);
checkResult.accept(translator.translateText(exampleText.get("en"), null, targetLanguageDe));
// Check that en and pt as target languages throw an exception
Assertions.assertThrows(
IllegalArgumentException.class,
() -> {
translator.translateText(exampleText.get("de"), null, "en");
});
Assertions.assertThrows(
IllegalArgumentException.class,
() -> {
translator.translateText(exampleText.get("de"), null, "pt");
});
}
@Test
void testInvalidLanguage() {
Translator translator = createTranslator();
DeepLException thrown;
thrown =
Assertions.assertThrows(
DeepLException.class,
() -> {
translator.translateText(exampleText.get("en"), null, "XX");
});
Assertions.assertTrue(thrown.getMessage().contains("target_lang"));
thrown =
Assertions.assertThrows(
DeepLException.class,
() -> {
translator.translateText(exampleText.get("en"), "XX", "de");
});
Assertions.assertTrue(thrown.getMessage().contains("source_lang"));
}
@Test
void testTranslateWithRetries() throws DeepLException, InterruptedException {
Assumptions.assumeTrue(isMockServer);
Translator translator = createTranslator(new SessionOptions().setRespondWith429(2));
long timeBefore = new Date().getTime();
List<String> texts = new ArrayList<>();
texts.add(exampleText.get("en"));
texts.add(exampleText.get("ja"));
List<TextResult> result = translator.translateText(texts, null, "de");
long timeAfter = new Date().getTime();
Assertions.assertEquals(2, result.size());
Assertions.assertEquals(exampleText.get("de"), result.get(0).getText());
Assertions.assertEquals("en", result.get(0).getDetectedSourceLanguage());
Assertions.assertEquals(exampleText.get("de"), result.get(1).getText());
Assertions.assertEquals("ja", result.get(1).getDetectedSourceLanguage());
Assertions.assertTrue(timeAfter - timeBefore > 1000);
}
@Test
void testFormality() throws DeepLException, InterruptedException {
Translator translator = createTranslator();
TextResult result;
result =
translator.translateText(
"How are you?", null, "de", new TextTranslationOptions().setFormality(Formality.Less));
if (!isMockServer) {
Assertions.assertTrue(result.getText().contains("dir"));
}
result =
translator.translateText(
"How are you?",
null,
"de",
new TextTranslationOptions().setFormality(Formality.Default));
if (!isMockServer) {
Assertions.assertTrue(result.getText().contains("Ihnen"));
}
result =
translator.translateText(
"How are you?", null, "de", new TextTranslationOptions().setFormality(Formality.More));
if (!isMockServer) {
Assertions.assertTrue(result.getText().contains("Ihnen"));
}
result =
translator.translateText(
"How are you?",
null,
"de",
new TextTranslationOptions().setFormality(Formality.PreferLess));
if (!isMockServer) {
Assertions.assertTrue(result.getText().contains("dir"));
}
result =
translator.translateText(
"How are you?",
null,
"de",
new TextTranslationOptions().setFormality(Formality.PreferMore));
if (!isMockServer) {
Assertions.assertTrue(result.getText().contains("Ihnen"));
}
}
@Test
void testContext() throws DeepLException, InterruptedException {
// In German, "scharf" can mean:
// - spicy/hot when referring to food, or
// - sharp when referring to other objects such as a knife (Messer).
Translator translator = createTranslator();
String text = "Das ist scharf!";
translator.translateText(text, null, "de");
// Result: "That is hot!"
translator.translateText(
text, null, "de", new TextTranslationOptions().setContext("Das ist ein Messer."));
// Result: "That is sharp!"
}
@Test
void testSplitSentences() throws DeepLException, InterruptedException {
Assumptions.assumeTrue(isMockServer);
Translator translator = createTranslator();
String text =
"If the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.";
translator.translateText(
text,
null,
"de",
new TextTranslationOptions().setSentenceSplittingMode(SentenceSplittingMode.Off));
translator.translateText(
text,
null,
"de",
new TextTranslationOptions().setSentenceSplittingMode(SentenceSplittingMode.All));
translator.translateText(
text,
null,
"de",
new TextTranslationOptions().setSentenceSplittingMode(SentenceSplittingMode.NoNewlines));
}
@Test
void testPreserveFormatting() throws DeepLException, InterruptedException {
Assumptions.assumeTrue(isMockServer);
Translator translator = createTranslator();
translator.translateText(
exampleText.get("en"),
null,
"de",
new TextTranslationOptions().setPreserveFormatting(true));
translator.translateText(
exampleText.get("en"),
null,
"de",
new TextTranslationOptions().setPreserveFormatting(false));
}
@Test
void testTagHandlingXML() throws DeepLException, InterruptedException {
Translator translator = createTranslator();
String text =
"<document><meta><title>A document's title</title></meta>"
+ "<content><par>"
+ "<span>This is a sentence split</span>"
+ "<span>across two <span> tags that should be treated as one."
+ "</span>"
+ "</par>"
+ "<par>Here is a sentence. Followed by a second one.</par>"
+ "<raw>This sentence will not be translated.</raw>"
+ "</content>"
+ "</document>";
TextResult result =
translator.translateText(
text,
null,
"de",
new TextTranslationOptions()
.setTagHandling("xml")
.setOutlineDetection(false)
.setNonSplittingTags(Arrays.asList("span"))
.setSplittingTags(Arrays.asList("title", "par"))
.setIgnoreTags(Arrays.asList("raw")));
if (!isMockServer) {
Assertions.assertTrue(
result.getText().contains("<raw>This sentence will not be translated.</raw>"));
Assertions.assertTrue(result.getText().matches(".*<title>.*Der Titel.*</title>.*"));
}
}
@Test
void testTagHandlingHTML() throws DeepLException, InterruptedException {
Translator translator = createTranslator();
String text =
"<!DOCTYPE html>"
+ "<html>"
+ "<body>"
+ "<h1>My First Heading</h1>"
+ "<p translate=\"no\">My first paragraph.</p>"
+ "</body>"
+ "</html>";
TextResult result =
translator.translateText(
text, null, "de", new TextTranslationOptions().setTagHandling("html"));
if (!isMockServer) {
Assertions.assertTrue(result.getText().contains("<h1>Meine erste Überschrift</h1>"));
Assertions.assertTrue(
result.getText().contains("<p translate=\"no\">My first paragraph.</p>"));
}
}
@Test
void testTagHandlingVersionV1() throws DeepLException, InterruptedException {
Translator translator = createTranslator();
String text = "<p>Hello world</p>";
TextResult result =
translator.translateText(
text,
null,
"de",
new TextTranslationOptions().setTagHandling("html").setTagHandlingVersion("v1"));
Assertions.assertNotNull(result);
Assertions.assertNotNull(result.getText());
Assertions.assertFalse(result.getText().isEmpty());
}
@Test
void testTagHandlingVersionV2() throws DeepLException, InterruptedException {
Translator translator = createTranslator();
String text = "<p>Hello world</p>";
TextResult result =
translator.translateText(
text,
null,
"de",
new TextTranslationOptions().setTagHandling("html").setTagHandlingVersion("v2"));
Assertions.assertNotNull(result);
Assertions.assertNotNull(result.getText());
Assertions.assertFalse(result.getText().isEmpty());
}
@Test
void testEmptyText() {
Translator translator = createTranslator();
Assertions.assertThrows(
IllegalArgumentException.class,
() -> {
translator.translateText("", null, "de");
});
}
@Test
void testMixedCaseLanguages() throws DeepLException, InterruptedException {
Translator translator = createTranslator();
TextResult result;
result = translator.translateText(exampleText.get("de"), null, "en-us");
Assertions.assertEquals(exampleText.get("en-US"), result.getText().toLowerCase(Locale.ENGLISH));
Assertions.assertEquals("de", result.getDetectedSourceLanguage());
result = translator.translateText(exampleText.get("de"), null, "EN-us");
Assertions.assertEquals(exampleText.get("en-US"), result.getText().toLowerCase(Locale.ENGLISH));
Assertions.assertEquals("de", result.getDetectedSourceLanguage());
result = translator.translateText(exampleText.get("de"), "de", "EN-US");
Assertions.assertEquals(exampleText.get("en-US"), result.getText().toLowerCase(Locale.ENGLISH));
Assertions.assertEquals("de", result.getDetectedSourceLanguage());
result = translator.translateText(exampleText.get("de"), "dE", "EN-US");
Assertions.assertEquals(exampleText.get("en-US"), result.getText().toLowerCase(Locale.ENGLISH));
Assertions.assertEquals("de", result.getDetectedSourceLanguage());
}
@Test
void testExtraBodyParams() throws DeepLException, InterruptedException {
Translator translator = createTranslator();
// Verifies that extra_body_parameters can override standard parameters like target_lang
Map<String, String> extraParams = new HashMap<>();
extraParams.put("target_lang", "FR");
extraParams.put("debug", "1");
TextTranslationOptions options = new TextTranslationOptions();
options.setExtraBodyParameters(extraParams);
TextResult result = translator.translateText(exampleText.get("en"), null, "DE", options);
Assertions.assertEquals(exampleText.get("fr"), result.getText());
Assertions.assertEquals("en", result.getDetectedSourceLanguage());
Assertions.assertEquals(exampleText.get("en").length(), result.getBilledCharacters());
}
@Test
void testCustomInstructions() throws DeepLException, InterruptedException {
Translator translator = createTranslator();
String text = "Hello world. I am testing if custom instructions are working correctly.";
TextResult resultWithCustomInstructions =
translator.translateText(
text,
null,
"de",
new TextTranslationOptions()
.setCustomInstructions(Arrays.asList("Use informal language", "Be concise")));
TextResult resultWithoutCustomInstructions = translator.translateText(text, null, "de");
Assertions.assertNotNull(resultWithCustomInstructions.getText());
Assertions.assertEquals("en", resultWithCustomInstructions.getDetectedSourceLanguage());
if (!isMockServer) {
Assertions.assertFalse(
resultWithCustomInstructions.getText().equals(resultWithoutCustomInstructions.getText()));
}
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/test/java/com/deepl/api/TestBase.java | deepl-java/src/test/java/com/deepl/api/TestBase.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import com.deepl.api.utils.*;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class TestBase {
protected static final boolean isMockServer;
protected static final boolean isMockProxyServer;
protected static final String authKey;
protected static final String serverUrl;
protected static final String proxyUrl;
protected static final Map<String, String> exampleText;
private static final String tempDirBase;
final String exampleInput = exampleText.get("en");
final String exampleLargeInput = repeatString(exampleText.get("en") + "\n", 1000);
final String exampleOutput = exampleText.get("de");
final String exampleLargeOutput = repeatString(exampleText.get("de") + "\n", 1000);
final String tempDir;
static {
isMockServer = System.getenv("DEEPL_MOCK_SERVER_PORT") != null;
serverUrl = System.getenv("DEEPL_SERVER_URL");
proxyUrl = System.getenv("DEEPL_PROXY_URL");
isMockProxyServer = proxyUrl != null;
if (isMockServer) {
authKey = "mock_server";
if (serverUrl == null) {
System.err.println(
"DEEPL_SERVER_URL environment variable must be set when using mock server.");
System.exit(1);
}
} else {
authKey = System.getenv("DEEPL_AUTH_KEY");
if (authKey == null) {
System.err.println(
"DEEPL_AUTH_KEY environment variable must be set unless using mock server.");
System.exit(1);
}
}
exampleText = new HashMap<>();
exampleText.put("ar", "شعاع البروتون");
exampleText.put("bg", "протонен лъч");
exampleText.put("cs", "protonový paprsek");
exampleText.put("da", "protonstråle");
exampleText.put("de", "Protonenstrahl");
exampleText.put("el", "δέσμη πρωτονίων");
exampleText.put("en", "proton beam");
exampleText.put("en-US", "proton beam");
exampleText.put("en-GB", "proton beam");
exampleText.put("es", "haz de protones");
exampleText.put("et", "prootonikiirgus");
exampleText.put("fi", "protonisäde");
exampleText.put("fr", "faisceau de protons");
exampleText.put("hu", "protonnyaláb");
exampleText.put("id", "berkas proton");
exampleText.put("it", "fascio di protoni");
exampleText.put("ja", "陽子ビーム");
exampleText.put("ko", "양성자 빔");
exampleText.put("lt", "protonų spindulys");
exampleText.put("lv", "protonu staru kūlis");
exampleText.put("nb", "protonstråle");
exampleText.put("nl", "protonenbundel");
exampleText.put("pl", "wiązka protonów");
exampleText.put("pt", "feixe de prótons");
exampleText.put("pt-BR", "feixe de prótons");
exampleText.put("pt-PT", "feixe de prótons");
exampleText.put("ro", "fascicul de protoni");
exampleText.put("ru", "протонный луч");
exampleText.put("sk", "protónový lúč");
exampleText.put("sl", "protonski žarek");
exampleText.put("sv", "protonstråle");
exampleText.put("tr", "proton ışını");
exampleText.put("uk", "Протонний промінь");
exampleText.put("zh", "质子束");
String tmpdir = System.getProperty("java.io.tmpdir");
tempDirBase = tmpdir.endsWith("/") ? tmpdir : tmpdir + "/";
}
protected TestBase() {
tempDir = createTempDir();
}
// TODO: Delete `createTranslator` methods, replace with `createDeepLClient`
protected Translator createTranslator() {
SessionOptions sessionOptions = new SessionOptions();
return createTranslator(sessionOptions);
}
protected Translator createTranslator(SessionOptions sessionOptions) {
TranslatorOptions translatorOptions = new TranslatorOptions();
return createTranslator(sessionOptions, translatorOptions);
}
protected Translator createTranslator(
SessionOptions sessionOptions, TranslatorOptions translatorOptions) {
Map<String, String> headers = sessionOptions.createSessionHeaders();
if (translatorOptions.getServerUrl() == null) {
translatorOptions.setServerUrl(serverUrl);
}
if (translatorOptions.getHeaders() != null) {
headers.putAll(translatorOptions.getHeaders());
}
translatorOptions.setHeaders(headers);
String authKey = sessionOptions.randomAuthKey ? UUID.randomUUID().toString() : TestBase.authKey;
try {
return new Translator(authKey, translatorOptions);
} catch (IllegalArgumentException e) {
e.printStackTrace();
System.exit(1);
return null;
}
}
protected DeepLClient createDeepLClient() {
SessionOptions sessionOptions = new SessionOptions();
return createDeepLClient(sessionOptions);
}
protected DeepLClient createDeepLClient(SessionOptions sessionOptions) {
TranslatorOptions translatorOptions = new TranslatorOptions();
return createDeepLClient(sessionOptions, translatorOptions);
}
protected DeepLClient createDeepLClient(
SessionOptions sessionOptions, TranslatorOptions translatorOptions) {
Map<String, String> headers = sessionOptions.createSessionHeaders();
if (translatorOptions.getServerUrl() == null) {
translatorOptions.setServerUrl(serverUrl);
}
if (translatorOptions.getHeaders() != null) {
headers.putAll(translatorOptions.getHeaders());
}
translatorOptions.setHeaders(headers);
String authKey = sessionOptions.randomAuthKey ? UUID.randomUUID().toString() : TestBase.authKey;
try {
return new DeepLClient(authKey, translatorOptions);
} catch (IllegalArgumentException e) {
e.printStackTrace();
System.exit(1);
return null;
}
}
protected String createTempDir() {
String newTempDir = tempDirBase + UUID.randomUUID();
boolean created = new File(newTempDir).mkdirs();
return newTempDir;
}
protected void writeToFile(File file, String content) throws IOException {
Boolean justCreated = file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(content);
writer.flush();
writer.close();
}
protected String readFromFile(File file) throws IOException {
if (!file.exists()) return "";
return StreamUtil.readStream(new FileInputStream(file));
}
/**
* Returns a string containing the input string repeated given number of times. Note:
* String.repeat() was added in Java 11.
*
* @param input Input string to be repeated.
* @param number Number of times to repeat string.
* @return Input string repeated given number of times.
*/
protected static String repeatString(String input, int number) {
StringBuilder sb = new StringBuilder(input.length() * number);
for (int i = 0; i < number; i++) {
sb.append(input);
}
return sb.toString();
}
protected File createInputFile() throws IOException {
return createInputFile(exampleInput);
}
protected File createInputFile(String content) throws IOException {
File inputFile = new File(tempDir + "/example_document.txt");
boolean ignored = inputFile.delete();
ignored = inputFile.createNewFile();
writeToFile(inputFile, content);
return inputFile;
}
protected File createOutputFile() {
File outputFile = new File(tempDir + "/output/example_document.txt");
boolean ignored = new File(outputFile.getParent()).mkdir();
ignored = outputFile.delete();
return outputFile;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/test/java/com/deepl/api/MultilingualGlossaryTest.java | deepl-java/src/test/java/com/deepl/api/MultilingualGlossaryTest.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import java.io.File;
import java.util.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class MultilingualGlossaryTest extends TestBase {
private final String invalidGlossaryId = "invalid_glossary_id";
private final String nonexistentGlossaryId = "96ab91fd-e715-41a1-adeb-5d701f84a483";
private final String sourceLang = "en";
private final String targetLang = "de";
private final GlossaryEntries testEntries = GlossaryEntries.fromTsv("Hello\tHallo");
private final MultilingualGlossaryDictionaryEntries testGlossaryDict =
new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, testEntries);
@Test
void testGlossaryCreate() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
GlossaryEntries entries = new GlossaryEntries(Collections.singletonMap("Hello", "Hallo"));
System.out.println(entries);
for (Map.Entry<String, String> entry : entries.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
String glossaryName = cleanup.getGlossaryName();
List<MultilingualGlossaryDictionaryEntries> glossaryDicts =
Arrays.asList(
testGlossaryDict,
new MultilingualGlossaryDictionaryEntries(targetLang, sourceLang, entries));
MultilingualGlossaryInfo glossary =
deepLClient.createMultilingualGlossary(glossaryName, glossaryDicts);
Assertions.assertEquals(glossaryName, glossary.getName());
AssertGlossaryDictionariesEquivalent(glossaryDicts, glossary.getDictionaries());
MultilingualGlossaryInfo getResult =
deepLClient.getMultilingualGlossary(glossary.getGlossaryId());
AssertGlossaryDictionariesEquivalent(glossaryDicts, getResult.getDictionaries());
}
}
@Test
void testGlossaryCreateLarge() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
Map<String, String> entryPairs = new HashMap<>();
for (int i = 0; i < 10000; i++) {
entryPairs.put(String.format("Source-%d", i), String.format("Target-%d", i));
}
GlossaryEntries entries = new GlossaryEntries(entryPairs);
Assertions.assertTrue(entries.toTsv().length() > 100000);
List<MultilingualGlossaryDictionaryEntries> glossaryDicts =
Arrays.asList(new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, entries));
MultilingualGlossaryInfo glossary =
deepLClient.createMultilingualGlossary(glossaryName, glossaryDicts);
Assertions.assertEquals(glossaryName, glossary.getName());
AssertGlossaryDictionariesEquivalent(glossaryDicts, glossary.getDictionaries());
}
}
@Test
void testGlossaryCreateCsv() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
Map<String, String> expectedEntries = new HashMap<>();
expectedEntries.put("sourceEntry1", "targetEntry1");
expectedEntries.put("source\"Entry", "target,Entry");
String csvContent =
"sourceEntry1,targetEntry1,en,de\n\"source\"\"Entry\",\"target,Entry\",en,de";
MultilingualGlossaryInfo glossary =
deepLClient.createMultilingualGlossaryFromCsv(
glossaryName, sourceLang, targetLang, csvContent);
MultilingualGlossaryDictionaryEntries createdGlossaryDict =
deepLClient.getMultilingualGlossaryDictionaryEntries(glossary, sourceLang, targetLang);
Assertions.assertEquals(expectedEntries, createdGlossaryDict.getEntries());
}
}
@Test
void testGlossaryCreateInvalid() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
Assertions.assertThrows(
IllegalArgumentException.class,
() -> deepLClient.createMultilingualGlossary("", Arrays.asList(testGlossaryDict)));
Assertions.assertThrows(
Exception.class,
() ->
deepLClient.createMultilingualGlossary(
glossaryName,
Arrays.asList(
new MultilingualGlossaryDictionaryEntries("en", "xx", testEntries))));
}
}
@Test
void testGlossaryGet() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
List<MultilingualGlossaryDictionaryEntries> glossaryDicts = Arrays.asList(testGlossaryDict);
MultilingualGlossaryInfo createdGlossary =
deepLClient.createMultilingualGlossary(glossaryName, glossaryDicts);
MultilingualGlossaryInfo glossary =
deepLClient.getMultilingualGlossary(createdGlossary.getGlossaryId());
Assertions.assertEquals(createdGlossary.getGlossaryId(), glossary.getGlossaryId());
Assertions.assertEquals(glossaryName, glossary.getName());
AssertGlossaryDictionariesEquivalent(glossaryDicts, glossary.getDictionaries());
}
Assertions.assertThrows(
DeepLException.class, () -> deepLClient.getMultilingualGlossary(invalidGlossaryId));
Assertions.assertThrows(
GlossaryNotFoundException.class,
() -> deepLClient.getMultilingualGlossary(nonexistentGlossaryId));
}
@Test
void testGlossaryGetEntries() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
GlossaryEntries entries = new GlossaryEntries();
entries.put("Apple", "Apfel");
entries.put("Banana", "Banane");
entries.put("A%=&", "B&=%");
entries.put("\u0394\u3041", "\u6DF1");
entries.put("\uD83E\uDEA8", "\uD83E\uDEB5");
MultilingualGlossaryDictionaryEntries glossaryDict =
new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, entries);
MultilingualGlossaryInfo createdGlossary =
deepLClient.createMultilingualGlossary(glossaryName, Arrays.asList(glossaryDict));
Assertions.assertEquals(1, createdGlossary.getDictionaries().size());
MultilingualGlossaryDictionaryInfo createdGlossaryDict =
createdGlossary.getDictionaries().get(0);
MultilingualGlossaryDictionaryEntries updatedGlossaryDict =
deepLClient.getMultilingualGlossaryDictionaryEntries(
createdGlossary, sourceLang, targetLang);
Assertions.assertEquals(entries, updatedGlossaryDict.getEntries());
updatedGlossaryDict =
deepLClient.getMultilingualGlossaryDictionaryEntries(
createdGlossary, sourceLang, targetLang);
Assertions.assertEquals(entries, updatedGlossaryDict.getEntries());
updatedGlossaryDict =
deepLClient.getMultilingualGlossaryDictionaryEntries(
createdGlossary, createdGlossaryDict);
Assertions.assertEquals(entries, updatedGlossaryDict.getEntries());
updatedGlossaryDict =
deepLClient.getMultilingualGlossaryDictionaryEntries(
createdGlossary.getGlossaryId(), createdGlossaryDict);
Assertions.assertEquals(entries, updatedGlossaryDict.getEntries());
Assertions.assertThrows(
DeepLException.class,
() ->
deepLClient.getMultilingualGlossaryDictionaryEntries(
invalidGlossaryId, sourceLang, targetLang));
Assertions.assertThrows(
GlossaryNotFoundException.class,
() ->
deepLClient.getMultilingualGlossaryDictionaryEntries(
nonexistentGlossaryId, sourceLang, targetLang));
Assertions.assertThrows(
Exception.class,
() -> deepLClient.getMultilingualGlossaryDictionaryEntries(createdGlossary, "en", "xx"));
Assertions.assertThrows(
IllegalArgumentException.class,
() ->
deepLClient.getMultilingualGlossaryDictionaryEntries(
createdGlossary, "", targetLang));
}
}
@Test
void testGlossaryList() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
deepLClient.createMultilingualGlossary(glossaryName, Arrays.asList(testGlossaryDict));
List<MultilingualGlossaryInfo> glossaries = deepLClient.listMultilingualGlossaries();
Assertions.assertTrue(
glossaries.stream()
.anyMatch((glossaryInfo -> Objects.equals(glossaryInfo.getName(), glossaryName))));
}
}
@Test
void testGlossaryDelete() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
MultilingualGlossaryInfo glossary =
deepLClient.createMultilingualGlossary(glossaryName, Arrays.asList(testGlossaryDict));
deepLClient.deleteMultilingualGlossary(glossary);
Assertions.assertThrows(
GlossaryNotFoundException.class, () -> deepLClient.deleteMultilingualGlossary(glossary));
Assertions.assertThrows(
DeepLException.class, () -> deepLClient.deleteMultilingualGlossary(invalidGlossaryId));
Assertions.assertThrows(
GlossaryNotFoundException.class,
() -> deepLClient.deleteMultilingualGlossary(nonexistentGlossaryId));
}
}
@Test
void testGlossaryDictionaryDelete() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
MultilingualGlossaryInfo glossary =
deepLClient.createMultilingualGlossary(glossaryName, Arrays.asList(testGlossaryDict));
deepLClient.deleteMultilingualGlossaryDictionary(glossary, sourceLang, targetLang);
Assertions.assertThrows(
GlossaryNotFoundException.class,
() -> deepLClient.deleteMultilingualGlossaryDictionary(glossary, sourceLang, targetLang));
Assertions.assertThrows(
DeepLException.class,
() ->
deepLClient.deleteMultilingualGlossaryDictionary(
invalidGlossaryId, sourceLang, targetLang));
Assertions.assertThrows(
GlossaryNotFoundException.class,
() ->
deepLClient.deleteMultilingualGlossaryDictionary(
nonexistentGlossaryId, sourceLang, targetLang));
}
}
@Test
void testGlossaryReplaceDictionary() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
List<MultilingualGlossaryDictionaryEntries> glossaryDicts = Arrays.asList(testGlossaryDict);
MultilingualGlossaryInfo glossary =
deepLClient.createMultilingualGlossary(glossaryName, glossaryDicts);
GlossaryEntries newEntries = new GlossaryEntries();
newEntries.put("key1", "value1");
MultilingualGlossaryDictionaryEntries newGlossaryDict =
new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, newEntries);
MultilingualGlossaryDictionaryInfo updatedGlossary =
deepLClient.replaceMultilingualGlossaryDictionary(glossary, newGlossaryDict);
AssertGlossaryDictionariesEquivalent(
Arrays.asList(newGlossaryDict), Arrays.asList(updatedGlossary));
newEntries.put("key2", "value2");
newGlossaryDict =
new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, newEntries);
updatedGlossary =
deepLClient.replaceMultilingualGlossaryDictionary(
glossary.getGlossaryId(), newGlossaryDict);
AssertGlossaryDictionariesEquivalent(
Arrays.asList(newGlossaryDict), Arrays.asList(updatedGlossary));
newEntries.put("key3", "value3");
newGlossaryDict =
new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, newEntries);
updatedGlossary =
deepLClient.replaceMultilingualGlossaryDictionary(
glossary.getGlossaryId(), sourceLang, targetLang, newEntries);
AssertGlossaryDictionariesEquivalent(
Arrays.asList(newGlossaryDict), Arrays.asList(updatedGlossary));
newEntries.put("key4", "value4");
newGlossaryDict =
new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, newEntries);
updatedGlossary =
deepLClient.replaceMultilingualGlossaryDictionary(
glossary, sourceLang, targetLang, newEntries);
AssertGlossaryDictionariesEquivalent(
Arrays.asList(newGlossaryDict), Arrays.asList(updatedGlossary));
}
}
@Test
void testGlossaryReplaceDictionaryReplacesExistingEntries() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
List<MultilingualGlossaryDictionaryEntries> glossaryDicts = Arrays.asList(testGlossaryDict);
MultilingualGlossaryInfo glossary =
deepLClient.createMultilingualGlossary(glossaryName, glossaryDicts);
GlossaryEntries newEntries = new GlossaryEntries();
newEntries.put("key1", "value1");
newEntries.put("key2", "value2");
MultilingualGlossaryDictionaryEntries newGlossaryDict =
new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, newEntries);
deepLClient.replaceMultilingualGlossaryDictionary(glossary, newGlossaryDict);
MultilingualGlossaryDictionaryEntries updatedGlossaryDict =
deepLClient.getMultilingualGlossaryDictionaryEntries(glossary, sourceLang, targetLang);
Assertions.assertEquals(newEntries, updatedGlossaryDict.getEntries());
}
}
@Test
void testGlossaryReplaceDictionaryFromCsvReplacesExistingEntries() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
List<MultilingualGlossaryDictionaryEntries> glossaryDicts = Arrays.asList(testGlossaryDict);
MultilingualGlossaryInfo glossary =
deepLClient.createMultilingualGlossary(glossaryName, glossaryDicts);
GlossaryEntries newEntries = new GlossaryEntries();
newEntries.put("key1", "value1");
newEntries.put("key2", "value2");
String csvContent = "key1,value1\nkey2,value2";
deepLClient.replaceMultilingualGlossaryDictionaryFromCsv(
glossary.getGlossaryId(), sourceLang, targetLang, csvContent);
MultilingualGlossaryDictionaryEntries updatedGlossaryDict =
deepLClient.getMultilingualGlossaryDictionaryEntries(glossary, sourceLang, targetLang);
Assertions.assertEquals(newEntries, updatedGlossaryDict.getEntries());
}
}
@Test
void testGlossaryUpdateDictionary() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
GlossaryEntries entries = new GlossaryEntries(Collections.singletonMap("key1", "value1"));
List<MultilingualGlossaryDictionaryEntries> glossaryDicts =
Arrays.asList(new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, entries));
MultilingualGlossaryInfo glossary =
deepLClient.createMultilingualGlossary(glossaryName, glossaryDicts);
entries = new GlossaryEntries(Collections.singletonMap("key1", "value2"));
MultilingualGlossaryDictionaryEntries newGlossaryDict =
new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, entries);
MultilingualGlossaryInfo updatedGlossary =
deepLClient.updateMultilingualGlossaryDictionary(glossary, newGlossaryDict);
AssertGlossaryDictionariesEquivalent(
Arrays.asList(newGlossaryDict), updatedGlossary.getDictionaries());
entries = new GlossaryEntries(Collections.singletonMap("key1", "value3"));
newGlossaryDict = new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, entries);
updatedGlossary =
deepLClient.updateMultilingualGlossaryDictionary(
glossary.getGlossaryId(), newGlossaryDict);
AssertGlossaryDictionariesEquivalent(
Arrays.asList(newGlossaryDict), updatedGlossary.getDictionaries());
entries = new GlossaryEntries(Collections.singletonMap("key1", "value4"));
newGlossaryDict = new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, entries);
updatedGlossary =
deepLClient.updateMultilingualGlossaryDictionary(
glossary.getGlossaryId(), sourceLang, targetLang, entries);
AssertGlossaryDictionariesEquivalent(
Arrays.asList(newGlossaryDict), updatedGlossary.getDictionaries());
entries.put("key1", "value5");
newGlossaryDict = new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, entries);
updatedGlossary =
deepLClient.updateMultilingualGlossaryDictionary(
glossary, sourceLang, targetLang, entries);
AssertGlossaryDictionariesEquivalent(
Arrays.asList(newGlossaryDict), updatedGlossary.getDictionaries());
}
}
@Test
void testGlossaryUpdateDictionaryUpdatesExistingEntries() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
GlossaryEntries entries = new GlossaryEntries();
entries.put("key1", "value1");
entries.put("key2", "value2");
List<MultilingualGlossaryDictionaryEntries> glossaryDicts =
Arrays.asList(new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, entries));
MultilingualGlossaryInfo glossary =
deepLClient.createMultilingualGlossary(glossaryName, glossaryDicts);
GlossaryEntries newEntries = new GlossaryEntries();
newEntries.put("key1", "updatedValue1");
newEntries.put("newKey", "newValue");
MultilingualGlossaryDictionaryEntries newGlossaryDict =
new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, newEntries);
deepLClient.updateMultilingualGlossaryDictionary(glossary, newGlossaryDict);
/* We expect the entries to be the newly updated entries plus the old key2/value2 entry that was unchanged */
GlossaryEntries expectedEntries = newEntries;
expectedEntries.put("key2", "value2");
MultilingualGlossaryDictionaryEntries updatedGlossaryDict =
deepLClient.getMultilingualGlossaryDictionaryEntries(glossary, sourceLang, targetLang);
Assertions.assertEquals(expectedEntries, updatedGlossaryDict.getEntries());
}
}
@Test
void testGlossaryUpdateDictionaryFromCsvUpdatesExistingEntries() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
GlossaryEntries entries = new GlossaryEntries();
entries.put("key1", "value1");
entries.put("key2", "value2");
List<MultilingualGlossaryDictionaryEntries> glossaryDicts =
Arrays.asList(new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, entries));
MultilingualGlossaryInfo glossary =
deepLClient.createMultilingualGlossary(glossaryName, glossaryDicts);
GlossaryEntries csvEntries = new GlossaryEntries();
csvEntries.put("key1", "updatedValue1");
csvEntries.put("newKey", "newValue");
String csvContent = "key1,updatedValue1\nnewKey,newValue";
deepLClient.updateMultilingualGlossaryDictionaryFromCsv(
glossary.getGlossaryId(), sourceLang, targetLang, csvContent);
/* We expect the entries to be the newly updated entries plus the old key2/value2 entry that was unchanged */
GlossaryEntries expectedEntries = csvEntries;
expectedEntries.put("key2", "value2");
MultilingualGlossaryDictionaryEntries updatedGlossaryDict =
deepLClient.getMultilingualGlossaryDictionaryEntries(glossary, sourceLang, targetLang);
Assertions.assertEquals(expectedEntries, updatedGlossaryDict.getEntries());
}
}
@Test
void testGlossaryUpdateName() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String originalGlossaryName = "original glossary name";
GlossaryEntries entries = new GlossaryEntries();
entries.put("key1", "value1");
List<MultilingualGlossaryDictionaryEntries> glossaryDicts =
Arrays.asList(new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, entries));
MultilingualGlossaryInfo glossary =
deepLClient.createMultilingualGlossary(originalGlossaryName, glossaryDicts);
String glossaryName = cleanup.getGlossaryName();
MultilingualGlossaryInfo updatedGlossary =
deepLClient.updateMultilingualGlossaryName(glossary.getGlossaryId(), glossaryName);
Assertions.assertEquals(glossaryName, updatedGlossary.getName());
}
}
@Test
void testGlossaryTranslateTextSentence() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
GlossaryEntries entries =
new GlossaryEntries() {
{
put("artist", "Maler");
put("prize", "Gewinn");
}
};
String inputText = "The artist was awarded a prize.";
MultilingualGlossaryDictionaryEntries glossaryDict =
new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, entries);
MultilingualGlossaryInfo glossary =
deepLClient.createMultilingualGlossary(glossaryName, Arrays.asList(glossaryDict));
TextResult result =
deepLClient.translateText(
inputText,
sourceLang,
targetLang,
new TextTranslationOptions().setGlossary(glossary.getGlossaryId()));
if (!isMockServer) {
Assertions.assertTrue(result.getText().contains("Maler"));
Assertions.assertTrue(result.getText().contains("Gewinn"));
}
// It is also possible to specify GlossaryInfo
result =
deepLClient.translateText(
inputText,
sourceLang,
targetLang,
new TextTranslationOptions().setGlossary(glossary));
if (!isMockServer) {
Assertions.assertTrue(result.getText().contains("Maler"));
Assertions.assertTrue(result.getText().contains("Gewinn"));
}
}
}
@Test
void testGlossaryTranslateTextBasic() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
List<String> textsEn =
new ArrayList<String>() {
{
add("Apple");
add("Banana");
}
};
List<String> textsDe =
new ArrayList<String>() {
{
add("Apfel");
add("Banane");
}
};
GlossaryEntries glossaryEntriesEnDe = new GlossaryEntries();
GlossaryEntries glossaryEntriesDeEn = new GlossaryEntries();
for (int i = 0; i < textsEn.size(); i++) {
glossaryEntriesEnDe.put(textsEn.get(i), textsDe.get(i));
glossaryEntriesDeEn.put(textsDe.get(i), textsEn.get(i));
}
MultilingualGlossaryDictionaryEntries glossaryDictEnDe =
new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, glossaryEntriesEnDe);
MultilingualGlossaryDictionaryEntries glossaryDictDeEn =
new MultilingualGlossaryDictionaryEntries(targetLang, sourceLang, glossaryEntriesDeEn);
MultilingualGlossaryInfo glossary =
deepLClient.createMultilingualGlossary(
glossaryName, Arrays.asList(glossaryDictEnDe, glossaryDictDeEn));
List<TextResult> result =
deepLClient.translateText(
textsEn, "en", "de", new TextTranslationOptions().setGlossary(glossary));
Assertions.assertArrayEquals(
textsDe.toArray(), result.stream().map(TextResult::getText).toArray());
result =
deepLClient.translateText(
textsDe,
"de",
"en-US",
new TextTranslationOptions().setGlossary(glossary.getGlossaryId()));
Assertions.assertArrayEquals(
textsEn.toArray(), result.stream().map(TextResult::getText).toArray());
}
}
@Test
void testGlossaryTranslateDocument() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
File inputFile = createInputFile("artist\nprize");
File outputFile = createOutputFile();
String expectedOutput = "Maler\nGewinn";
GlossaryEntries entries =
new GlossaryEntries() {
{
put("artist", "Maler");
put("prize", "Gewinn");
}
};
MultilingualGlossaryDictionaryEntries glossaryDict =
new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, entries);
MultilingualGlossaryInfo glossary =
deepLClient.createMultilingualGlossary(glossaryName, Arrays.asList(glossaryDict));
deepLClient.translateDocument(
inputFile,
outputFile,
sourceLang,
targetLang,
new DocumentTranslationOptions().setGlossary(glossary));
Assertions.assertEquals(expectedOutput, readFromFile(outputFile));
boolean ignored = outputFile.delete();
deepLClient.translateDocument(
inputFile,
outputFile,
sourceLang,
targetLang,
new DocumentTranslationOptions().setGlossary(glossary.getGlossaryId()));
Assertions.assertEquals(expectedOutput, readFromFile(outputFile));
}
}
@Test
void testGlossaryTranslateTextInvalid() throws Exception {
DeepLClient deepLClient = createDeepLClient();
try (MultilingualGlossaryCleanupUtility cleanup =
new MultilingualGlossaryCleanupUtility(deepLClient)) {
String glossaryName = cleanup.getGlossaryName();
MultilingualGlossaryDictionaryEntries glossaryDictEnDe =
new MultilingualGlossaryDictionaryEntries(sourceLang, targetLang, testEntries);
MultilingualGlossaryDictionaryEntries glossaryDictDeEn =
new MultilingualGlossaryDictionaryEntries(targetLang, sourceLang, testEntries);
MultilingualGlossaryInfo glossary =
deepLClient.createMultilingualGlossary(
glossaryName, Arrays.asList(glossaryDictEnDe, glossaryDictDeEn));
IllegalArgumentException exception =
Assertions.assertThrows(
IllegalArgumentException.class,
() ->
deepLClient.translateText(
"test", null, "de", new TextTranslationOptions().setGlossary(glossary)));
Assertions.assertTrue(exception.getMessage().contains("sourceLang is required"));
exception =
Assertions.assertThrows(
IllegalArgumentException.class,
() ->
deepLClient.translateText(
"test", "de", "en", new TextTranslationOptions().setGlossary(glossary)));
Assertions.assertTrue(exception.getMessage().contains("targetLang=\"en\" is not allowed"));
}
}
/**
* Utility function for determining if a list of MultilingualGlossaryDictionaryEntries objects
* (that have entries) matches a list of MultilingualGlossaryDictionaryInfo (that do not contain
* entries, but just a count of the number of entries for that glossary dictionary
*/
private void AssertGlossaryDictionariesEquivalent(
List<MultilingualGlossaryDictionaryEntries> expectedDicts,
List<MultilingualGlossaryDictionaryInfo> actualDicts) {
Assertions.assertEquals(expectedDicts.size(), actualDicts.size());
for (MultilingualGlossaryDictionaryEntries expectedDict : expectedDicts) {
MultilingualGlossaryDictionaryInfo actualDict =
findMatchingDictionary(
actualDicts,
expectedDict.getSourceLanguageCode(),
expectedDict.getTargetLanguageCode());
Assertions.assertEquals(
expectedDict.getSourceLanguageCode().toLowerCase(),
actualDict.getSourceLanguageCode().toLowerCase());
Assertions.assertEquals(
expectedDict.getTargetLanguageCode().toLowerCase(),
actualDict.getTargetLanguageCode().toLowerCase());
Assertions.assertEquals(
expectedDict.getEntries().entrySet().size(), actualDict.getEntryCount());
}
}
private MultilingualGlossaryDictionaryInfo findMatchingDictionary(
List<MultilingualGlossaryDictionaryInfo> glossaryDicts,
String sourceLang,
String targetLang) {
String lowerCaseSourceLang = sourceLang.toLowerCase();
String lowerCaseTargetLang = targetLang.toLowerCase();
for (MultilingualGlossaryDictionaryInfo glossaryDict : glossaryDicts) {
if (glossaryDict.getSourceLanguageCode().equals(lowerCaseSourceLang)
&& glossaryDict.getTargetLanguageCode().equals(lowerCaseTargetLang)) {
return glossaryDict;
}
}
Assertions.fail("glossary did not contain expected language pair $sourceLang->$targetLang");
return null;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/test/java/com/deepl/api/GlossaryTest.java | deepl-java/src/test/java/com/deepl/api/GlossaryTest.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import com.deepl.api.utils.*;
import java.io.*;
import java.util.*;
import org.junit.jupiter.api.*;
public class GlossaryTest extends TestBase {
private final String invalidGlossaryId = "invalid_glossary_id";
private final String nonexistentGlossaryId = "96ab91fd-e715-41a1-adeb-5d701f84a483";
private final String sourceLang = "en";
private final String targetLang = "de";
private final GlossaryEntries testEntries = GlossaryEntries.fromTsv("Hello\tHallo");
@Test
void TestGlossaryEntries() {
GlossaryEntries testEntries = new GlossaryEntries();
testEntries.put("apple", "Apfel");
testEntries.put("crab apple", "Holzapfel");
Assertions.assertEquals(
testEntries, GlossaryEntries.fromTsv("apple\tApfel\n crab apple \t Holzapfel "));
Assertions.assertThrows(Exception.class, () -> GlossaryEntries.fromTsv(""));
Assertions.assertThrows(
Exception.class, () -> GlossaryEntries.fromTsv("Küche\tKitchen\nKüche\tCuisine"));
Assertions.assertThrows(Exception.class, () -> GlossaryEntries.fromTsv("A\tB\tC"));
Assertions.assertThrows(Exception.class, () -> GlossaryEntries.fromTsv("A\t "));
Assertions.assertThrows(
Exception.class, () -> new GlossaryEntries(Collections.singletonMap("A", "B\tC")));
}
@Test
void testGlossaryCreate() throws Exception {
Translator translator = createTranslator();
try (GlossaryCleanupUtility cleanup = new GlossaryCleanupUtility(translator)) {
GlossaryEntries entries = new GlossaryEntries(Collections.singletonMap("Hello", "Hallo"));
System.out.println(entries);
for (Map.Entry<String, String> entry : entries.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
String glossaryName = cleanup.getGlossaryName();
GlossaryInfo glossary =
translator.createGlossary(glossaryName, sourceLang, targetLang, entries);
Assertions.assertEquals(glossaryName, glossary.getName());
Assertions.assertEquals(sourceLang, glossary.getSourceLang());
Assertions.assertEquals(targetLang, glossary.getTargetLang());
Assertions.assertEquals(1, glossary.getEntryCount());
GlossaryInfo getResult = translator.getGlossary(glossary.getGlossaryId());
Assertions.assertEquals(getResult.getName(), glossary.getName());
Assertions.assertEquals(getResult.getSourceLang(), glossary.getSourceLang());
Assertions.assertEquals(getResult.getTargetLang(), glossary.getTargetLang());
Assertions.assertEquals(getResult.getCreationTime(), glossary.getCreationTime());
Assertions.assertEquals(getResult.getEntryCount(), glossary.getEntryCount());
}
}
@Test
void testGlossaryCreateLarge() throws Exception {
Translator translator = createTranslator();
try (GlossaryCleanupUtility cleanup = new GlossaryCleanupUtility(translator)) {
String glossaryName = cleanup.getGlossaryName();
Map<String, String> entryPairs = new HashMap<>();
for (int i = 0; i < 10000; i++) {
entryPairs.put(String.format("Source-%d", i), String.format("Target-%d", i));
}
GlossaryEntries entries = new GlossaryEntries(entryPairs);
Assertions.assertTrue(entries.toTsv().length() > 100000);
GlossaryInfo glossary =
translator.createGlossary(glossaryName, sourceLang, targetLang, entries);
Assertions.assertEquals(glossaryName, glossary.getName());
Assertions.assertEquals(sourceLang, glossary.getSourceLang());
Assertions.assertEquals(targetLang, glossary.getTargetLang());
Assertions.assertEquals(entryPairs.size(), glossary.getEntryCount());
}
}
@Test
void testGlossaryCreateCsv() throws Exception {
Translator translator = createTranslator();
try (GlossaryCleanupUtility cleanup = new GlossaryCleanupUtility(translator)) {
String glossaryName = cleanup.getGlossaryName();
Map<String, String> expectedEntries = new HashMap<>();
expectedEntries.put("sourceEntry1", "targetEntry1");
expectedEntries.put("source\"Entry", "target,Entry");
String csvContent =
"sourceEntry1,targetEntry1,en,de\n\"source\"\"Entry\",\"target,Entry\",en,de";
GlossaryInfo glossary =
translator.createGlossaryFromCsv(glossaryName, sourceLang, targetLang, csvContent);
GlossaryEntries entries = translator.getGlossaryEntries(glossary);
Assertions.assertEquals(expectedEntries, entries);
}
}
@Test
void testGlossaryCreateInvalid() throws Exception {
Translator translator = createTranslator();
try (GlossaryCleanupUtility cleanup = new GlossaryCleanupUtility(translator)) {
String glossaryName = cleanup.getGlossaryName();
Assertions.assertThrows(
Exception.class,
() -> translator.createGlossary("", sourceLang, targetLang, testEntries));
Assertions.assertThrows(
Exception.class, () -> translator.createGlossary(glossaryName, "en", "xx", testEntries));
}
}
@Test
void testGlossaryGet() throws Exception {
Translator translator = createTranslator();
try (GlossaryCleanupUtility cleanup = new GlossaryCleanupUtility(translator)) {
String glossaryName = cleanup.getGlossaryName();
GlossaryInfo createdGlossary =
translator.createGlossary(glossaryName, sourceLang, targetLang, testEntries);
GlossaryInfo glossary = translator.getGlossary(createdGlossary.getGlossaryId());
Assertions.assertEquals(createdGlossary.getGlossaryId(), glossary.getGlossaryId());
Assertions.assertEquals(glossaryName, glossary.getName());
Assertions.assertEquals(sourceLang, glossary.getSourceLang());
Assertions.assertEquals(targetLang, glossary.getTargetLang());
Assertions.assertEquals(createdGlossary.getCreationTime(), glossary.getCreationTime());
Assertions.assertEquals(testEntries.size(), glossary.getEntryCount());
}
Assertions.assertThrows(DeepLException.class, () -> translator.getGlossary(invalidGlossaryId));
Assertions.assertThrows(
GlossaryNotFoundException.class, () -> translator.getGlossary(nonexistentGlossaryId));
}
@Test
void testGlossaryGetEntries() throws Exception {
Translator translator = createTranslator();
try (GlossaryCleanupUtility cleanup = new GlossaryCleanupUtility(translator)) {
String glossaryName = cleanup.getGlossaryName();
GlossaryEntries entries = new GlossaryEntries();
entries.put("Apple", "Apfel");
entries.put("Banana", "Banane");
entries.put("A%=&", "B&=%");
entries.put("\u0394\u3041", "\u6DF1");
entries.put("\uD83E\uDEA8", "\uD83E\uDEB5");
GlossaryInfo createdGlossary =
translator.createGlossary(glossaryName, sourceLang, targetLang, entries);
Assertions.assertEquals(entries, translator.getGlossaryEntries(createdGlossary));
Assertions.assertEquals(
entries, translator.getGlossaryEntries(createdGlossary.getGlossaryId()));
}
Assertions.assertThrows(
DeepLException.class, () -> translator.getGlossaryEntries(invalidGlossaryId));
Assertions.assertThrows(
GlossaryNotFoundException.class,
() -> translator.getGlossaryEntries(nonexistentGlossaryId));
}
@Test
void testGlossaryList() throws Exception {
Translator translator = createTranslator();
try (GlossaryCleanupUtility cleanup = new GlossaryCleanupUtility(translator)) {
String glossaryName = cleanup.getGlossaryName();
translator.createGlossary(glossaryName, sourceLang, targetLang, testEntries);
List<GlossaryInfo> glossaries = translator.listGlossaries();
Assertions.assertTrue(
glossaries.stream()
.anyMatch((glossaryInfo -> Objects.equals(glossaryInfo.getName(), glossaryName))));
}
}
@Test
void testGlossaryDelete() throws Exception {
Translator translator = createTranslator();
try (GlossaryCleanupUtility cleanup = new GlossaryCleanupUtility(translator)) {
String glossaryName = cleanup.getGlossaryName();
GlossaryInfo glossary =
translator.createGlossary(glossaryName, sourceLang, targetLang, testEntries);
translator.deleteGlossary(glossary);
Assertions.assertThrows(
GlossaryNotFoundException.class, () -> translator.deleteGlossary(glossary));
Assertions.assertThrows(
DeepLException.class, () -> translator.deleteGlossary(invalidGlossaryId));
Assertions.assertThrows(
GlossaryNotFoundException.class, () -> translator.deleteGlossary(nonexistentGlossaryId));
}
}
@Test
void testGlossaryTranslateTextSentence() throws Exception {
Translator translator = createTranslator();
try (GlossaryCleanupUtility cleanup = new GlossaryCleanupUtility(translator)) {
String glossaryName = cleanup.getGlossaryName();
GlossaryEntries entries =
new GlossaryEntries() {
{
put("artist", "Maler");
put("prize", "Gewinn");
}
};
String inputText = "The artist was awarded a prize.";
GlossaryInfo glossary =
translator.createGlossary(glossaryName, sourceLang, targetLang, entries);
TextResult result =
translator.translateText(
inputText,
sourceLang,
targetLang,
new TextTranslationOptions().setGlossary(glossary.getGlossaryId()));
if (!isMockServer) {
Assertions.assertTrue(result.getText().contains("Maler"));
Assertions.assertTrue(result.getText().contains("Gewinn"));
}
// It is also possible to specify GlossaryInfo
result =
translator.translateText(
inputText,
sourceLang,
targetLang,
new TextTranslationOptions().setGlossary(glossary));
if (!isMockServer) {
Assertions.assertTrue(result.getText().contains("Maler"));
Assertions.assertTrue(result.getText().contains("Gewinn"));
}
}
}
@Test
void testGlossaryTranslateTextBasic() throws Exception {
Translator translator = createTranslator();
try (GlossaryCleanupUtility cleanupEnDe = new GlossaryCleanupUtility(translator, "EnDe");
GlossaryCleanupUtility cleanupDeEn = new GlossaryCleanupUtility(translator, "DeEn")) {
String glossaryNameEnDe = cleanupEnDe.getGlossaryName();
String glossaryNameDeEn = cleanupDeEn.getGlossaryName();
List<String> textsEn =
new ArrayList<String>() {
{
add("Apple");
add("Banana");
}
};
List<String> textsDe =
new ArrayList<String>() {
{
add("Apfel");
add("Banane");
}
};
GlossaryEntries glossaryEntriesEnDe = new GlossaryEntries();
GlossaryEntries glossaryEntriesDeEn = new GlossaryEntries();
for (int i = 0; i < textsEn.size(); i++) {
glossaryEntriesEnDe.put(textsEn.get(i), textsDe.get(i));
glossaryEntriesDeEn.put(textsDe.get(i), textsEn.get(i));
}
GlossaryInfo glossaryEnDe =
translator.createGlossary(glossaryNameEnDe, "en", "de", glossaryEntriesEnDe);
GlossaryInfo glossaryDeEn =
translator.createGlossary(glossaryNameDeEn, "de", "en", glossaryEntriesDeEn);
List<TextResult> result =
translator.translateText(
textsEn, "en", "de", new TextTranslationOptions().setGlossary(glossaryEnDe));
Assertions.assertArrayEquals(
textsDe.toArray(), result.stream().map(TextResult::getText).toArray());
result =
translator.translateText(
textsDe,
"de",
"en-US",
new TextTranslationOptions().setGlossary(glossaryDeEn.getGlossaryId()));
Assertions.assertArrayEquals(
textsEn.toArray(), result.stream().map(TextResult::getText).toArray());
}
}
@Test
void testGlossaryTranslateDocument() throws Exception {
Translator translator = createTranslator();
try (GlossaryCleanupUtility cleanup = new GlossaryCleanupUtility(translator)) {
String glossaryName = cleanup.getGlossaryName();
File inputFile = createInputFile("artist\nprize");
File outputFile = createOutputFile();
String expectedOutput = "Maler\nGewinn";
GlossaryEntries entries =
new GlossaryEntries() {
{
put("artist", "Maler");
put("prize", "Gewinn");
}
};
GlossaryInfo glossary =
translator.createGlossary(glossaryName, sourceLang, targetLang, entries);
translator.translateDocument(
inputFile,
outputFile,
sourceLang,
targetLang,
new DocumentTranslationOptions().setGlossary(glossary));
Assertions.assertEquals(expectedOutput, readFromFile(outputFile));
boolean ignored = outputFile.delete();
translator.translateDocument(
inputFile,
outputFile,
sourceLang,
targetLang,
new DocumentTranslationOptions().setGlossary(glossary.getGlossaryId()));
Assertions.assertEquals(expectedOutput, readFromFile(outputFile));
}
}
@Test
void testGlossaryTranslateTextInvalid() throws Exception {
Translator translator = createTranslator();
try (GlossaryCleanupUtility cleanupEnDe = new GlossaryCleanupUtility(translator, "EnDe");
GlossaryCleanupUtility cleanupDeEn = new GlossaryCleanupUtility(translator, "DeEn")) {
String glossaryNameEnDe = cleanupEnDe.getGlossaryName();
String glossaryNameDeEn = cleanupDeEn.getGlossaryName();
GlossaryInfo glossaryEnDe =
translator.createGlossary(glossaryNameEnDe, "en", "de", testEntries);
GlossaryInfo glossaryDeEn =
translator.createGlossary(glossaryNameDeEn, "de", "en", testEntries);
IllegalArgumentException exception =
Assertions.assertThrows(
IllegalArgumentException.class,
() ->
translator.translateText(
"test", null, "de", new TextTranslationOptions().setGlossary(glossaryEnDe)));
Assertions.assertTrue(exception.getMessage().contains("sourceLang is required"));
exception =
Assertions.assertThrows(
IllegalArgumentException.class,
() ->
translator.translateText(
"test", "de", "en", new TextTranslationOptions().setGlossary(glossaryDeEn)));
Assertions.assertTrue(exception.getMessage().contains("targetLang=\"en\" is not allowed"));
}
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/DocumentStatus.java | deepl-java/src/main/java/com/deepl/api/DocumentStatus.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import com.google.gson.annotations.SerializedName;
import org.jetbrains.annotations.Nullable;
/** Status of an in-progress document translation. */
public class DocumentStatus {
@SerializedName(value = "document_id")
private final String documentId;
@SerializedName(value = "status")
private final StatusCode status;
@SerializedName(value = "billed_characters")
private final @Nullable Long billedCharacters;
@SerializedName(value = "seconds_remaining")
private final @Nullable Long secondsRemaining;
@SerializedName(value = "error_message")
private final @Nullable String errorMessage;
/** Status code indicating status of the document translation. */
public enum StatusCode {
/** Document translation has not yet started, but will begin soon. */
@SerializedName("queued")
Queued,
/** Document translation is in progress. */
@SerializedName("translating")
Translating,
/**
* Document translation completed successfully, and the translated document may be downloaded.
*/
@SerializedName("done")
Done,
/** An error occurred during document translation. */
@SerializedName("error")
Error,
}
public DocumentStatus(
String documentId,
StatusCode status,
@Nullable Long billedCharacters,
@Nullable Long secondsRemaining,
@Nullable String errorMessage) {
this.documentId = documentId;
this.status = status;
this.billedCharacters = billedCharacters;
this.secondsRemaining = secondsRemaining;
this.errorMessage = errorMessage;
}
/** @return Document ID of the associated document. */
public String getDocumentId() {
return documentId;
}
/** @return Status of the document translation. */
public StatusCode getStatus() {
return status;
}
/**
* @return <code>true</code> if no error has occurred during document translation, otherwise
* <code>false</code>.
*/
public boolean ok() {
return status != null && status != StatusCode.Error;
}
/**
* @return <code>true</code> if document translation has completed successfully, otherwise <code>
* false</code>.
*/
public boolean done() {
return status != null && status == StatusCode.Done;
}
/**
* @return Number of seconds remaining until translation is complete if available, otherwise
* <code>null</code>. Only available while document is in translating state.
*/
public @Nullable Long getSecondsRemaining() {
return secondsRemaining;
}
/**
* @return Number of characters billed for the translation of this document if available,
* otherwise <code>null</code>. Only available after document translation is finished and the
* status is {@link StatusCode#Done}, otherwise <code>null</code>.
*/
public @Nullable Long getBilledCharacters() {
return billedCharacters;
}
/** @return Short description of the error if available, otherwise <code>null</code>. */
public @Nullable String getErrorMessage() {
return errorMessage;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/ConnectionException.java | deepl-java/src/main/java/com/deepl/api/ConnectionException.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/** Exception thrown when a connection error occurs while accessing the DeepL API. */
public class ConnectionException extends DeepLException {
private final boolean shouldRetry;
public ConnectionException(String message, boolean shouldRetry, Throwable cause) {
super(message, cause);
this.shouldRetry = shouldRetry;
}
/**
* Returns <code>true</code> if this exception occurred due to transient condition and the request
* should be retried, otherwise <code>false</code>.
*/
public boolean getShouldRetry() {
return shouldRetry;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/SentenceSplittingMode.java | deepl-java/src/main/java/com/deepl/api/SentenceSplittingMode.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/** Enum controlling how input translation text should be split into sentences. */
public enum SentenceSplittingMode {
/**
* Input translation text will be split into sentences using both newlines and punctuation, this
* is the default behaviour.
*/
All,
/**
* Input text will not be split into sentences. This is advisable for applications where each
* input translation text is only one sentence.
*/
Off,
/**
* Input translation text will be split into sentences using only punctuation but not newlines.
*/
NoNewlines,
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/StyleRuleInfo.java | deepl-java/src/main/java/com/deepl/api/StyleRuleInfo.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import com.google.gson.annotations.*;
import java.util.*;
import org.jetbrains.annotations.*;
/** Information about a style rule list. */
public class StyleRuleInfo {
@SerializedName(value = "style_id")
private final String styleId;
@SerializedName(value = "name")
private final String name;
@SerializedName(value = "creation_time")
private final Date creationTime;
@SerializedName(value = "updated_time")
private final Date updatedTime;
@SerializedName(value = "language")
private final String language;
@SerializedName(value = "version")
private final int version;
@SerializedName(value = "configured_rules")
@Nullable
private final ConfiguredRules configuredRules;
@SerializedName(value = "custom_instructions")
@Nullable
private final List<CustomInstruction> customInstructions;
/**
* Initializes a new {@link StyleRuleInfo} containing information about a style rule list.
*
* @param styleId Unique ID assigned to the style rule list.
* @param name User-defined name assigned to the style rule list.
* @param creationTime Timestamp when the style rule list was created.
* @param updatedTime Timestamp when the style rule list was last updated.
* @param language Language code for the style rule list.
* @param version Version number of the style rule list.
* @param configuredRules The predefined rules that have been enabled.
* @param customInstructions Optional list of custom instructions.
*/
public StyleRuleInfo(
String styleId,
String name,
Date creationTime,
Date updatedTime,
String language,
int version,
@Nullable ConfiguredRules configuredRules,
@Nullable List<CustomInstruction> customInstructions) {
this.styleId = styleId;
this.name = name;
this.creationTime = creationTime;
this.updatedTime = updatedTime;
this.language = language;
this.version = version;
this.configuredRules = configuredRules;
this.customInstructions = customInstructions;
}
/** @return Unique ID assigned to the style rule list. */
public String getStyleId() {
return styleId;
}
/** @return User-defined name assigned to the style rule list. */
public String getName() {
return name;
}
/** @return Timestamp when the style rule list was created. */
public Date getCreationTime() {
return creationTime;
}
/** @return Timestamp when the style rule list was last updated. */
public Date getUpdatedTime() {
return updatedTime;
}
/** @return Language code for the style rule list. */
public String getLanguage() {
return language;
}
/** @return Version number of the style rule list. */
public int getVersion() {
return version;
}
/** @return The predefined rules that have been enabled. */
@Nullable
public ConfiguredRules getConfiguredRules() {
return configuredRules;
}
/** @return Optional list of custom instructions. */
@Nullable
public List<CustomInstruction> getCustomInstructions() {
return customInstructions;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/TextTranslationOptions.java | deepl-java/src/main/java/com/deepl/api/TextTranslationOptions.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/**
* Options to control text translation behaviour. These options may be provided to {@link
* Translator#translateText} overloads.
*
* <p>All properties have corresponding setters in fluent-style, so the following is possible:
* <code>
* TextTranslationOptions options = new TextTranslationOptions()
* .setFormality(Formality.Less).setGlossaryId("f63c02c5-f056-..");
* </code>
*/
public class TextTranslationOptions extends BaseRequestOptions {
private Formality formality;
private String glossaryId;
private String styleId;
private SentenceSplittingMode sentenceSplittingMode;
private boolean preserveFormatting = false;
private String context;
private String tagHandling;
private String tagHandlingVersion;
private String modelType;
private boolean outlineDetection = true;
private Iterable<String> ignoreTags;
private Iterable<String> nonSplittingTags;
private Iterable<String> splittingTags;
private Iterable<String> customInstructions;
/**
* Sets whether translations should lean toward formal or informal language. This option is only
* applicable for target languages that support the formality option. By default, this value is
* <code>null</code> and<code>null</code> translations use the default formality.
*
* @see Language#getSupportsFormality()
* @see Formality
*/
public TextTranslationOptions setFormality(Formality formality) {
this.formality = formality;
return this;
}
/**
* Sets the ID of a glossary to use with the translation. By default, this value is <code>
* null</code> and no glossary is used.
*/
public TextTranslationOptions setGlossaryId(String glossaryId) {
this.glossaryId = glossaryId;
return this;
}
/**
* Sets the glossary to use with the translation. By default, this value is <code>null</code> and
* no glossary is used.
*/
public TextTranslationOptions setGlossary(IGlossary glossary) {
return setGlossary(glossary.getGlossaryId());
}
/**
* Sets the glossary to use with the translation. By default, this value is <code>null</code> and
* no glossary is used.
*/
public TextTranslationOptions setGlossary(String glossaryId) {
this.glossaryId = glossaryId;
return this;
}
/**
* Sets the ID of a style rule to use with the translation. By default, this value is <code>
* null</code> and no style rule is used.
*/
public TextTranslationOptions setStyleId(String styleId) {
this.styleId = styleId;
return this;
}
/**
* Sets the style rule to use with the translation. By default, this value is <code>null</code>
* and no style rule is used.
*/
public TextTranslationOptions setStyleRule(StyleRuleInfo styleRule) {
return setStyleId(styleRule.getStyleId());
}
/**
* Specifies additional context to influence translations, that is not translated itself.
* Characters in the `context` parameter are not counted toward billing. See the API documentation
* for more information and example usage.
*/
public TextTranslationOptions setContext(String context) {
this.context = context;
return this;
}
/**
* Specifies how input translation text should be split into sentences. By default, this value is
* <code>null</code> and the default sentence splitting mode is used.
*
* @see SentenceSplittingMode
*/
public TextTranslationOptions setSentenceSplittingMode(
SentenceSplittingMode sentenceSplittingMode) {
this.sentenceSplittingMode = sentenceSplittingMode;
return this;
}
/**
* Sets whether formatting should be preserved in translations. Set to <code>true</code> to
* prevent the translation engine from correcting some formatting aspects, and instead leave the
* formatting unchanged, default is <code>false</code>.
*/
public TextTranslationOptions setPreserveFormatting(boolean preserveFormatting) {
this.preserveFormatting = preserveFormatting;
return this;
}
/**
* Set the type of tags to parse before translation, only <code>"xml"</code> and <code>"html"
* </code> are currently available. By default, this value is <code>null</code> and no
* tag-handling is used.
*/
public TextTranslationOptions setTagHandling(String tagHandling) {
this.tagHandling = tagHandling;
return this;
}
/**
* Sets the version of tag handling algorithm to use. By default, this value is <code>null</code>
* and the API default is used.
*/
public TextTranslationOptions setTagHandlingVersion(String tagHandlingVersion) {
this.tagHandlingVersion = tagHandlingVersion;
return this;
}
/**
* Set the type of model to use for a text translation. Currently supported values: <code>
* "quality_optimized"</code> use a translation model that maximizes translation quality, at the
* cost of response time. This option may be unavailable for some language pairs and the API would
* respond with an error in this case; <code>"prefer_quality_optimized"</code> use the
* highest-quality translation model for the given language pair; <code>"latency_optimized"
* </code> use a translation model that minimizes response time, at the cost of translation
* quality.
*/
public TextTranslationOptions setModelType(String modelType) {
this.modelType = modelType;
return this;
}
/**
* Sets whether outline detection is used; set to <code>false</code> to disable automatic tag
* detection, default is <code>true</code>.
*/
public TextTranslationOptions setOutlineDetection(boolean outlineDetection) {
this.outlineDetection = outlineDetection;
return this;
}
/**
* Sets the list of XML tags containing content that should not be translated. By default, this
* value is <code>null</code> and no tags are specified.
*/
public TextTranslationOptions setIgnoreTags(Iterable<String> ignoreTags) {
this.ignoreTags = ignoreTags;
return this;
}
/**
* Sets the list of XML tags that should not be used to split text into sentences. By default,
* this value is <code>null</code> and no tags are specified.
*/
public TextTranslationOptions setNonSplittingTags(Iterable<String> nonSplittingTags) {
this.nonSplittingTags = nonSplittingTags;
return this;
}
/**
* Set the list of XML tags that should be used to split text into sentences. By default, this
* value is <code>null</code> and no tags are specified.
*/
public TextTranslationOptions setSplittingTags(Iterable<String> splittingTags) {
this.splittingTags = splittingTags;
return this;
}
/**
* Sets custom instructions to influence translations. By default, this value is <code>null</code>
* and no custom instructions are used.
*/
public TextTranslationOptions setCustomInstructions(Iterable<String> customInstructions) {
this.customInstructions = customInstructions;
return this;
}
/** Gets the current formality setting. */
public Formality getFormality() {
return formality;
}
/** Gets the current glossary ID. */
public String getGlossaryId() {
return glossaryId;
}
/** Gets the current style rule ID. */
public String getStyleId() {
return styleId;
}
/** Gets the current sentence splitting mode. */
public SentenceSplittingMode getSentenceSplittingMode() {
return sentenceSplittingMode;
}
/** Gets the current preserve formatting setting. */
public boolean isPreserveFormatting() {
return preserveFormatting;
}
/** Gets the current context. */
public String getContext() {
return context;
}
/** Gets the current model type. */
public String getModelType() {
return modelType;
}
/** Gets the current tag handling setting. */
public String getTagHandling() {
return tagHandling;
}
/** Gets the current tag handling version. */
public String getTagHandlingVersion() {
return tagHandlingVersion;
}
/** Gets the current outline detection setting. */
public boolean isOutlineDetection() {
return outlineDetection;
}
/** Gets the current ignore tags list. */
public Iterable<String> getIgnoreTags() {
return ignoreTags;
}
/** Gets the current non-splitting tags list. */
public Iterable<String> getNonSplittingTags() {
return nonSplittingTags;
}
/** Gets the current splitting tags list. */
public Iterable<String> getSplittingTags() {
return splittingTags;
}
/** Gets the current custom instructions list. */
public Iterable<String> getCustomInstructions() {
return customInstructions;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/DocumentHandle.java | deepl-java/src/main/java/com/deepl/api/DocumentHandle.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import com.google.gson.annotations.SerializedName;
/**
* Handle to an in-progress document translation.
*
* @see Translator#translateDocumentStatus(DocumentHandle)
*/
public class DocumentHandle {
@SerializedName(value = "document_id")
private final String documentId;
@SerializedName(value = "document_key")
private final String documentKey;
public DocumentHandle(String documentId, String documentKey) {
this.documentId = documentId;
this.documentKey = documentKey;
}
/** Get the ID of associated document request. */
public String getDocumentId() {
return documentId;
}
/** Get the key of associated document request. */
public String getDocumentKey() {
return documentKey;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/TooManyRequestsException.java | deepl-java/src/main/java/com/deepl/api/TooManyRequestsException.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/** Exception thrown when too many requests are made to the DeepL API too quickly. */
public class TooManyRequestsException extends DeepLException {
public TooManyRequestsException(String message) {
super(message);
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/DeepLApiVersion.java | deepl-java/src/main/java/com/deepl/api/DeepLApiVersion.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
public enum DeepLApiVersion {
VERSION_1("v1"),
VERSION_2("v2");
/**
* How the version is represented in the URL string. Does not include any slashes (/). Example:
* "v2"
*/
private final String urlRepresentation;
private DeepLApiVersion(String urlRepresentation) {
this.urlRepresentation = urlRepresentation;
}
public String toString() {
return this.urlRepresentation;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/DocumentTranslationException.java | deepl-java/src/main/java/com/deepl/api/DocumentTranslationException.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import org.jetbrains.annotations.Nullable;
/**
* Exception thrown when an error occurs during {@link Translator#translateDocument}. If the error
* occurs after the document was successfully uploaded, the {@link DocumentHandle} for the
* associated document is included, to allow later retrieval of the document.
*/
public class DocumentTranslationException extends DeepLException {
private final @Nullable DocumentHandle handle;
public DocumentTranslationException(
String message, Throwable throwable, @Nullable DocumentHandle handle) {
super(message, throwable);
this.handle = handle;
}
/**
* Get the handle to the in-progress document translation, or <code>null</code> if an error
* occurred before uploading the document.
*/
public @Nullable DocumentHandle getHandle() {
return handle;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/DeepLClientOptions.java | deepl-java/src/main/java/com/deepl/api/DeepLClientOptions.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import org.jetbrains.annotations.Nullable;
/** {@inheritDoc} */
@SuppressWarnings("deprecation")
public class DeepLClientOptions extends TranslatorOptions {
/**
* Set the version of the DeepL API to use. By default, this value is <code>
* DeepLApiVersion.VERSION_2</code> and the most recent DeepL API version is used. Note that older
* API versions like <code>DeepLApiVersion.VERSION_1</code> might not support all features of the
* more modern API (eg. document translation is v2-only), and that not all API subscriptions have
* access to one or the other API version. If in doubt, always use the most recent API version you
* have access to.
*/
public DeepLClientOptions setApiVersion(DeepLApiVersion apiVersion) {
this.apiVersion = apiVersion;
return this;
}
/** Gets the current API version. */
public @Nullable DeepLApiVersion getApiVersion() {
return apiVersion;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/TextRephraseOptions.java | deepl-java/src/main/java/com/deepl/api/TextRephraseOptions.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/**
* Options to control text rephrasing behaviour. These options may be provided to {@link
* DeepLClient#rephraseText} overloads.
*
* <p>All properties have corresponding setters in fluent-style, so the following is possible:
* <code>
* TextRephraseOptions options = new TextRephraseOptions()
* .WritingStyle(WritingStyle.Business.getValue());
* </code>
*/
public class TextRephraseOptions {
private String writingStyle;
private String tone;
/**
* Sets a style the improved text should be in. Note that only style OR tone can be set.
*
* @see WritingStyle
*/
public TextRephraseOptions setWritingStyle(String style) {
this.writingStyle = style;
return this;
}
/**
* Sets a tone the improved text should be in. Note that only style OR tone can be set.
*
* @see WritingTone
*/
public TextRephraseOptions setTone(String tone) {
this.tone = tone;
return this;
}
/** Gets the current style setting. */
public String getWritingStyle() {
return writingStyle;
}
/** Gets the current tone setting. */
public String getTone() {
return tone;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/MultilingualGlossaryInfo.java | deepl-java/src/main/java/com/deepl/api/MultilingualGlossaryInfo.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import com.google.gson.annotations.*;
import java.util.*;
/** Information about a glossary, excluding the entry list. */
public class MultilingualGlossaryInfo implements IGlossary {
@SerializedName(value = "glossary_id")
private final String glossaryId;
@SerializedName(value = "name")
private final String name;
@SerializedName(value = "creation_time")
private final Date creationTime;
@SerializedName(value = "dictionaries")
private final List<MultilingualGlossaryDictionaryInfo> dictionaries;
/**
* Initializes a new {@link MultilingualGlossaryInfo} containing information about a glossary.
*
* @param glossaryId ID of the associated glossary.
* @param name Name of the glossary chosen during creation.
* @param creationTime Time when the glossary was created.
* @param dictionaries A list of dictionaries that are in this glossary
*/
public MultilingualGlossaryInfo(
String glossaryId,
String name,
Date creationTime,
List<MultilingualGlossaryDictionaryInfo> dictionaries) {
this.glossaryId = glossaryId;
this.name = name;
this.creationTime = creationTime;
this.dictionaries = dictionaries;
}
/** @return Unique ID assigned to the glossary. */
public String getGlossaryId() {
return glossaryId;
}
/** @return User-defined name assigned to the glossary. */
public String getName() {
return name;
}
/** @return Timestamp when the glossary was created. */
public Date getCreationTime() {
return creationTime;
}
/** @return the list of dictionaries in this glossary */
public List<MultilingualGlossaryDictionaryInfo> getDictionaries() {
return dictionaries;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/GlossaryNotFoundException.java | deepl-java/src/main/java/com/deepl/api/GlossaryNotFoundException.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/** Exception thrown when the specified glossary could not be found. */
public class GlossaryNotFoundException extends NotFoundException {
public GlossaryNotFoundException(String message) {
super(message);
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/TextResult.java | deepl-java/src/main/java/com/deepl/api/TextResult.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import org.jetbrains.annotations.Nullable;
/** The result of a text translation. */
public class TextResult {
private final String text;
private final String detectedSourceLanguage;
private final int billedCharacters;
private final @Nullable String modelTypeUsed;
/** Constructs a new instance. */
public TextResult(
String text,
String detectedSourceLanguage,
int billedCharacters,
@Nullable String modelTypeUsed) {
this.text = text;
this.detectedSourceLanguage = LanguageCode.standardize(detectedSourceLanguage);
this.billedCharacters = billedCharacters;
this.modelTypeUsed = modelTypeUsed;
}
/** The translated text. */
public String getText() {
return text;
}
/** The language code of the source text detected by DeepL. */
public String getDetectedSourceLanguage() {
return detectedSourceLanguage;
}
/** Number of characters billed for this text. */
public int getBilledCharacters() {
return billedCharacters;
}
/** Model type used for the translation of this text. */
public @Nullable String getModelTypeUsed() {
return modelTypeUsed;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/GlossaryEntries.java | deepl-java/src/main/java/com/deepl/api/GlossaryEntries.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import com.deepl.api.utils.*;
import java.util.*;
import org.jetbrains.annotations.*;
/** Stores the entries of a glossary. */
public class GlossaryEntries implements Map<String, String> {
private final Map<String, String> entries = new HashMap<>();
/** Construct an empty GlossaryEntries. */
public GlossaryEntries() {}
/** Initializes a new GlossaryEntries with the entry pairs in the given map. */
public GlossaryEntries(Map<String, String> entryPairs) {
this.putAll(entryPairs);
}
/**
* Converts the given tab-separated-value (TSV) string of glossary entries into a new
* GlossaryEntries object. Whitespace is trimmed from the start and end of each term.
*/
public static GlossaryEntries fromTsv(String tsv) {
GlossaryEntries result = new GlossaryEntries();
String[] lines = tsv.split("(\\r\\n|\\n|\\r)");
int lineNumber = 0;
for (String line : lines) {
++lineNumber;
String lineTrimmed = trimWhitespace(line);
if (lineTrimmed.isEmpty()) {
continue;
}
String[] splitLine = lineTrimmed.split("\\t");
if (splitLine.length < 2) {
throw new IllegalArgumentException(
String.format(
"Entry on line %d does not contain a term separator: %s", lineNumber, lineTrimmed));
} else if (splitLine.length > 2) {
throw new IllegalArgumentException(
String.format(
"Entry on line %d contains more than one term separator: %s", lineNumber, line));
} else {
String sourceTerm = trimWhitespace(splitLine[0]);
String targetTerm = trimWhitespace(splitLine[1]);
validateGlossaryTerm(sourceTerm);
validateGlossaryTerm(targetTerm);
if (result.containsKey(sourceTerm)) {
throw new IllegalArgumentException(
String.format(
"Entry on line %d duplicates source term '%s'", lineNumber, sourceTerm));
}
result.put(sourceTerm, targetTerm);
}
}
if (result.entries.isEmpty()) {
throw new IllegalArgumentException("TSV string contains no valid entries");
}
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (getClass() != o.getClass()) return false;
GlossaryEntries glossaryEntries = (GlossaryEntries) o;
return glossaryEntries.entries.equals(entries);
}
@Override
public int size() {
return entries.size();
}
@Override
public boolean isEmpty() {
return entries.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return entries.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return entries.containsValue(value);
}
@Override
public String get(Object key) {
return entries.get(key);
}
/**
* Adds the given source term and target term to the glossary entries.
*
* @param sourceTerm key with which the specified value is to be associated
* @param targetTerm value to be associated with the specified key
* @return The previous target term associated with this source term, or null if this source term
* was not present.
*/
public String put(String sourceTerm, String targetTerm) throws IllegalArgumentException {
validateGlossaryTerm(sourceTerm);
validateGlossaryTerm(targetTerm);
return entries.put(sourceTerm, targetTerm);
}
@Override
public String remove(Object key) {
return entries.remove(key);
}
@Override
public void putAll(@NotNull Map<? extends String, ? extends String> m) {
for (Map.Entry<? extends String, ? extends String> entryPair : m.entrySet()) {
put(entryPair.getKey(), entryPair.getValue());
}
}
@Override
public void clear() {
entries.clear();
}
@NotNull
@Override
public Set<String> keySet() {
return entries.keySet();
}
@NotNull
@Override
public Collection<String> values() {
return entries.values();
}
@NotNull
@Override
public Set<Entry<String, String>> entrySet() {
return entries.entrySet();
}
/**
* Checks the validity of the given glossary term, for example that it contains no invalid
* characters. Whitespace at the start and end of the term is ignored. Terms are considered valid
* if they comprise at least one non-whitespace character, and contain no invalid characters: C0
* and C1 control characters, and Unicode newlines.
*
* @param term String containing term to check.
*/
public static void validateGlossaryTerm(String term) throws IllegalArgumentException {
String termTrimmed = trimWhitespace(term);
if (termTrimmed.isEmpty()) {
throw new IllegalArgumentException(
String.format("Term '%s' contains no non-whitespace characters", term));
}
for (int i = 0; i < termTrimmed.length(); ++i) {
char ch = termTrimmed.charAt(i);
if ((ch <= 31) || (128 <= ch && ch <= 159) || ch == '\u2028' || ch == '\u2029') {
throw new IllegalArgumentException(
String.format(
"Term '%s' contains invalid character: '%c' (U+%04d)", term, ch, (int) ch));
}
}
}
/**
* Converts the glossary entries to a string containing the entries in tab-separated-value (TSV)
* format.
*
* @return String containing the entries in TSV format.
*/
public String toTsv() {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entryPair : entries.entrySet()) {
if (builder.length() > 0) {
builder.append("\n");
}
builder.append(entryPair.getKey()).append("\t").append(entryPair.getValue());
}
return builder.toString();
}
/**
* Strips whitespace characters from the beginning and end of the given string. Implemented here
* because String.strip() is not available in Java 8.
*
* @param input String to have whitespace trimmed.
* @return Input string with whitespace removed from ends.
*/
private static String trimWhitespace(String input) {
int left = 0;
for (; left < input.length(); left++) {
char ch = input.charAt(left);
if (ch != ' ' && ch != '\t') {
break;
}
}
if (left >= input.length()) {
return "";
}
int right = input.length() - 1;
for (; left < right; right--) {
char ch = input.charAt(right);
if (ch != ' ' && ch != '\t') {
break;
}
}
return input.substring(left, right + 1);
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/WritingTone.java | deepl-java/src/main/java/com/deepl/api/WritingTone.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/** Represents the tone the improved text should be in in a rephrase request. */
public enum WritingTone {
Confident("confident"),
Default("default"),
Diplomatic("diplomatic"),
Enthusiastic("enthusiastic"),
Friendly("friendly"),
PreferConfident("prefer_confident"),
PreferDiplomatic("prefer_diplomatic"),
PreferEnthusiastic("prefer_enthusiastic"),
PreferFriendly("prefer_friendly");
private final String value;
WritingTone(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/AppInfo.java | deepl-java/src/main/java/com/deepl/api/AppInfo.java | // Copyright 2023 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
public class AppInfo {
private String appName;
private String appVersion;
public AppInfo(String appName, String appVersion) {
this.appName = appName;
this.appVersion = appVersion;
}
public String getAppName() {
return appName;
}
public String getAppVersion() {
return appVersion;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/DocumentNotReadyException.java | deepl-java/src/main/java/com/deepl/api/DocumentNotReadyException.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/** Exception thrown when attempting to download a translated document before it is ready. */
public class DocumentNotReadyException extends DeepLException {
public DocumentNotReadyException(String message) {
super(message);
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/LanguageType.java | deepl-java/src/main/java/com/deepl/api/LanguageType.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/** Enum specifying a source or target language type. */
public enum LanguageType {
Source,
Target,
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/Usage.java | deepl-java/src/main/java/com/deepl/api/Usage.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import java.util.function.BiConsumer;
import org.jetbrains.annotations.Nullable;
/**
* Information about DeepL account usage for the current billing period, for example the number of
* characters translated.
*
* <p>Depending on the account type, some usage types will be omitted. See the <a
* href="https://www.deepl.com/docs-api/">API documentation</a> for more information.
*/
public class Usage {
private final @Nullable Detail character;
private final @Nullable Detail document;
private final @Nullable Detail teamDocument;
/** The character usage if included for the account type, or <code>null</code>. */
public @Nullable Detail getCharacter() {
return character;
}
/** The document usage if included for the account type, or <code>null</code>. */
public @Nullable Detail getDocument() {
return document;
}
/** The team document usage if included for the account type, or <code>null</code>. */
public @Nullable Detail getTeamDocument() {
return teamDocument;
}
/** Stores the amount used and maximum amount for one usage type. */
public static class Detail {
private final long count;
private final long limit;
public Detail(long count, long limit) {
this.count = count;
this.limit = limit;
}
/** @return The currently used number of items for this usage type. */
public long getCount() {
return count;
}
/** @return The maximum permitted number of items for this usage type. */
public long getLimit() {
return limit;
}
/**
* @return <code>true</code> if the amount used meets or exceeds the limit, otherwise <code>
* false</code>.
*/
public boolean limitReached() {
return getCount() >= getLimit();
}
@Override
public String toString() {
return getCount() + " of " + getLimit();
}
}
public Usage(
@Nullable Detail character, @Nullable Detail document, @Nullable Detail teamDocument) {
this.character = character;
this.document = document;
this.teamDocument = teamDocument;
}
/**
* @return <code>true</code> if any of the usage types included for the account type have been
* reached, otherwise <code>false</code>.
*/
public boolean anyLimitReached() {
return (getCharacter() != null && getCharacter().limitReached())
|| (getDocument() != null && getDocument().limitReached())
|| (getTeamDocument() != null && getTeamDocument().limitReached());
}
/**
* Returns a string representing the usage. This function is for diagnostic purposes only; the
* content of the returned string is exempt from backwards compatibility.
*
* @return A string containing the usage for this billing period.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Usage this billing period:");
BiConsumer<String, Detail> addLabelledDetail =
(label, detail) -> {
if (detail != null) {
sb.append("\n").append(label).append(": ").append(detail);
}
};
addLabelledDetail.accept("Characters", getCharacter());
addLabelledDetail.accept("Documents", getDocument());
addLabelledDetail.accept("Team documents", getTeamDocument());
return sb.toString();
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/ConfiguredRules.java | deepl-java/src/main/java/com/deepl/api/ConfiguredRules.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import com.google.gson.annotations.*;
import java.util.*;
import org.jetbrains.annotations.*;
/** Configuration rules for a style rule list. */
public class ConfiguredRules {
@SerializedName(value = "dates_and_times")
@Nullable
private final Map<String, String> datesAndTimes;
@SerializedName(value = "formatting")
@Nullable
private final Map<String, String> formatting;
@SerializedName(value = "numbers")
@Nullable
private final Map<String, String> numbers;
@SerializedName(value = "punctuation")
@Nullable
private final Map<String, String> punctuation;
@SerializedName(value = "spelling_and_grammar")
@Nullable
private final Map<String, String> spellingAndGrammar;
@SerializedName(value = "style_and_tone")
@Nullable
private final Map<String, String> styleAndTone;
@SerializedName(value = "vocabulary")
@Nullable
private final Map<String, String> vocabulary;
/**
* Initializes a new {@link ConfiguredRules} containing configuration rules for a style rule list.
*
* @param datesAndTimes Date and time formatting rules.
* @param formatting Text formatting rules.
* @param numbers Number formatting rules.
* @param punctuation Punctuation rules.
* @param spellingAndGrammar Spelling and grammar rules.
* @param styleAndTone Style and tone rules.
* @param vocabulary Vocabulary rules.
*/
public ConfiguredRules(
@Nullable Map<String, String> datesAndTimes,
@Nullable Map<String, String> formatting,
@Nullable Map<String, String> numbers,
@Nullable Map<String, String> punctuation,
@Nullable Map<String, String> spellingAndGrammar,
@Nullable Map<String, String> styleAndTone,
@Nullable Map<String, String> vocabulary) {
this.datesAndTimes = datesAndTimes;
this.formatting = formatting;
this.numbers = numbers;
this.punctuation = punctuation;
this.spellingAndGrammar = spellingAndGrammar;
this.styleAndTone = styleAndTone;
this.vocabulary = vocabulary;
}
/** @return Date and time formatting rules. */
@Nullable
public Map<String, String> getDatesAndTimes() {
return datesAndTimes;
}
/** @return Text formatting rules. */
@Nullable
public Map<String, String> getFormatting() {
return formatting;
}
/** @return Number formatting rules. */
@Nullable
public Map<String, String> getNumbers() {
return numbers;
}
/** @return Punctuation rules. */
@Nullable
public Map<String, String> getPunctuation() {
return punctuation;
}
/** @return Spelling and grammar rules. */
@Nullable
public Map<String, String> getSpellingAndGrammar() {
return spellingAndGrammar;
}
/** @return Style and tone rules. */
@Nullable
public Map<String, String> getStyleAndTone() {
return styleAndTone;
}
/** @return Vocabulary rules. */
@Nullable
public Map<String, String> getVocabulary() {
return vocabulary;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/WriteResult.java | deepl-java/src/main/java/com/deepl/api/WriteResult.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/** The result of a text translation. */
public class WriteResult {
private final String text;
private final String detectedSourceLanguage;
private final String targetLanguage;
/** Constructs a new instance. */
public WriteResult(String text, String detectedSourceLanguage, String targetLanguage) {
this.text = text;
this.detectedSourceLanguage = LanguageCode.standardize(detectedSourceLanguage);
this.targetLanguage = targetLanguage;
}
/** The translated text. */
public String getText() {
return text;
}
/** The language code of the source text detected by DeepL. */
public String getDetectedSourceLanguage() {
return detectedSourceLanguage;
}
/** The language code of the target language set by the request. */
public String getTargetLanguage() {
return targetLanguage;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/LanguageCode.java | deepl-java/src/main/java/com/deepl/api/LanguageCode.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import java.util.*;
/**
* Language codes for the languages currently supported by DeepL translation. New languages may be
* added in the future; to retrieve the currently supported languages use {@link
* Translator#getSourceLanguages()} and {@link Translator#getTargetLanguages()}.
*/
public class LanguageCode {
/** Arabic (MSA) language code, may be used as source or target language */
public static final String Arabic = "ar";
/** Bulgarian language code, may be used as source or target language. */
public static final String Bulgarian = "bg";
/** Czech language code, may be used as source or target language. */
public static final String Czech = "cs";
/** Danish language code, may be used as source or target language. */
public static final String Danish = "da";
/** German language code, may be used as source or target language. */
public static final String German = "de";
/** Greek language code, may be used as source or target language. */
public static final String Greek = "el";
/**
* English language code, may only be used as a source language. In input texts, this language
* code supports all English variants.
*/
public static final String English = "en";
/** British English language code, may only be used as a target language. */
public static final String EnglishBritish = "en-GB";
/** American English language code, may only be used as a target language. */
public static final String EnglishAmerican = "en-US";
/** Spanish language code, may be used as source or target language. */
public static final String Spanish = "es";
/** Estonian language code, may be used as source or target language. */
public static final String Estonian = "et";
/** Finnish language code, may be used as source or target language. */
public static final String Finnish = "fi";
/** French language code, may be used as source or target language. */
public static final String French = "fr";
/** Hungarian language code, may be used as source or target language. */
public static final String Hungarian = "hu";
/** Indonesian language code, may be used as source or target language. */
public static final String Indonesian = "id";
/** Italian language code, may be used as source or target language. */
public static final String Italian = "it";
/** Japanese language code, may be used as source or target language. */
public static final String Japanese = "ja";
/** Korean language code, may be used as source or target language. */
public static final String Korean = "ko";
/** Lithuanian language code, may be used as source or target language. */
public static final String Lithuanian = "lt";
/** Latvian language code, may be used as source or target language. */
public static final String Latvian = "lv";
/** Norwegian (bokmål) language code, may be used as source or target language. */
public static final String Norwegian = "nb";
/** Dutch language code, may be used as source or target language. */
public static final String Dutch = "nl";
/** Polish language code, may be used as source or target language. */
public static final String Polish = "pl";
/**
* Portuguese language code, may only be used as a source language. In input texts, this language
* code supports all Portuguese variants.
*/
public static final String Portuguese = "pt";
/** Brazilian Portuguese language code, may only be used as a target language. */
public static final String PortugueseBrazilian = "pt-BR";
/** European Portuguese language code, may only be used as a target language. */
public static final String PortugueseEuropean = "pt-PT";
/** Romanian language code, may be used as source or target language. */
public static final String Romanian = "ro";
/** Russian language code, may be used as source or target language. */
public static final String Russian = "ru";
/** Slovak language code, may be used as source or target language. */
public static final String Slovak = "sk";
/** Slovenian language code, may be used as source or target language. */
public static final String Slovenian = "sl";
/** Swedish language code, may be used as source or target language. */
public static final String Swedish = "sv";
/** Turkish language code, may be used as source or target language. */
public static final String Turkish = "tr";
/** Ukrainian language code, may be used as source or target language. */
public static final String Ukrainian = "uk";
/** Chinese language code, may be used as source or target language. */
public static final String Chinese = "zh";
/**
* Removes the regional variant (if any) from the given language code.
*
* @param langCode Language code possibly containing a regional variant.
* @return The language code without a regional variant.
*/
public static String removeRegionalVariant(String langCode) {
String[] parts = langCode.split("-", 2);
return parts[0].toLowerCase(Locale.ENGLISH);
}
/**
* Changes the upper- and lower-casing of the given language code to match ISO 639-1 with an
* optional regional code from ISO 3166-1.
*
* @param langCode String containing language code to standardize.
* @return String containing the standardized language code.
*/
public static String standardize(String langCode) {
String[] parts = langCode.split("-", 2);
if (parts.length == 1) {
return parts[0].toLowerCase(Locale.ENGLISH);
} else {
return parts[0].toLowerCase(Locale.ENGLISH) + "-" + parts[1].toUpperCase(Locale.ENGLISH);
}
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/BaseRequestOptions.java | deepl-java/src/main/java/com/deepl/api/BaseRequestOptions.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import java.util.Map;
/** Base class for request options providing common functionality for all endpoints. */
public abstract class BaseRequestOptions {
private Map<String, String> extraBodyParameters;
/**
* Sets additional parameters to pass in the body of the HTTP request. Can be used to access beta
* features, override built-in parameters, or for testing purposes. Keys in this map will be added
* to the request body and can override existing keys.
*
* @param extraBodyParameters Map of additional parameters to include in the request.
* @return This options object for method chaining.
*/
public BaseRequestOptions setExtraBodyParameters(Map<String, String> extraBodyParameters) {
this.extraBodyParameters = extraBodyParameters;
return this;
}
/** Gets the current extra body parameters. */
public Map<String, String> getExtraBodyParameters() {
return extraBodyParameters;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/GlossaryInfo.java | deepl-java/src/main/java/com/deepl/api/GlossaryInfo.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import com.google.gson.annotations.*;
import java.util.*;
import org.jetbrains.annotations.*;
/** Information about a glossary, excluding the entry list. */
public class GlossaryInfo implements IGlossary {
@SerializedName(value = "glossary_id")
private final String glossaryId;
@SerializedName(value = "name")
private final String name;
@SerializedName(value = "ready")
private final boolean ready;
@SerializedName(value = "source_lang")
private final String sourceLang;
@SerializedName(value = "target_lang")
private final String targetLang;
@SerializedName(value = "creation_time")
private final Date creationTime;
@SerializedName(value = "entry_count")
private final long entryCount;
/**
* Initializes a new {@link GlossaryInfo} containing information about a glossary.
*
* @param glossaryId ID of the associated glossary.
* @param name Name of the glossary chosen during creation.
* @param ready <c>true</c> if the glossary may be used for translations, otherwise <c>false</c>.
* @param sourceLang Language code of the source terms in the glossary.
* @param targetLang Language code of the target terms in the glossary.
* @param creationTime Time when the glossary was created.
* @param entryCount The number of source-target entry pairs in the glossary.
*/
public GlossaryInfo(
String glossaryId,
String name,
boolean ready,
String sourceLang,
String targetLang,
Date creationTime,
long entryCount) {
this.glossaryId = glossaryId;
this.name = name;
this.ready = ready;
this.sourceLang = sourceLang;
this.targetLang = targetLang;
this.creationTime = creationTime;
this.entryCount = entryCount;
}
/** @return Unique ID assigned to the glossary. */
public String getGlossaryId() {
return glossaryId;
}
/** @return User-defined name assigned to the glossary. */
public String getName() {
return name;
}
/** @return True if the glossary may be used for translations, otherwise false. */
public boolean isReady() {
return ready;
}
/** @return Source language code of the glossary. */
public String getSourceLang() {
return sourceLang;
}
/** @return Target language code of the glossary. */
public String getTargetLang() {
return targetLang;
}
/** @return Timestamp when the glossary was created. */
public Date getCreationTime() {
return creationTime;
}
/** @return The number of entries contained in the glossary. */
public long getEntryCount() {
return entryCount;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/MultilingualGlossaryDictionaryEntries.java | deepl-java/src/main/java/com/deepl/api/MultilingualGlossaryDictionaryEntries.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/** Stores the entries of a glossary. */
public class MultilingualGlossaryDictionaryEntries {
private final String sourceLanguageCode;
private final String targetLanguageCode;
private final GlossaryEntries entries;
/**
* Initializes a new {@link MultilingualGlossaryDictionaryInfo} containing information about a
* glossary dictionary.
*
* @param sourceLanguageCode the source language for this dictionary
* @param targetLanguageCode the target language for this dictionary
* @param entries the entries in this dictionary
*/
public MultilingualGlossaryDictionaryEntries(
String sourceLanguageCode, String targetLanguageCode, GlossaryEntries entries) {
this.sourceLanguageCode = sourceLanguageCode;
this.targetLanguageCode = targetLanguageCode;
this.entries = entries;
}
/** @return the source language code */
public String getSourceLanguageCode() {
return this.sourceLanguageCode;
}
/** @return the target language code */
public String getTargetLanguageCode() {
return this.targetLanguageCode;
}
/** @return the entry count */
public GlossaryEntries getEntries() {
return this.entries;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/NotFoundException.java | deepl-java/src/main/java/com/deepl/api/NotFoundException.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/** Exception thrown when the specified resource could not be found. */
public class NotFoundException extends DeepLException {
public NotFoundException(String message) {
super(message);
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/CustomInstruction.java | deepl-java/src/main/java/com/deepl/api/CustomInstruction.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import com.google.gson.annotations.*;
import org.jetbrains.annotations.*;
/** Custom instruction for a style rule. */
public class CustomInstruction {
@SerializedName(value = "label")
private final String label;
@SerializedName(value = "prompt")
private final String prompt;
@SerializedName(value = "source_language")
@Nullable
private final String sourceLanguage;
/**
* Initializes a new {@link CustomInstruction} containing a custom instruction for a style rule.
*
* @param label Label for the custom instruction.
* @param prompt Prompt text for the custom instruction.
* @param sourceLanguage Optional source language code for the custom instruction.
*/
public CustomInstruction(String label, String prompt, @Nullable String sourceLanguage) {
this.label = label;
this.prompt = prompt;
this.sourceLanguage = sourceLanguage;
}
/** @return Label for the custom instruction. */
public String getLabel() {
return label;
}
/** @return Prompt text for the custom instruction. */
public String getPrompt() {
return prompt;
}
/** @return Optional source language code for the custom instruction. */
@Nullable
public String getSourceLanguage() {
return sourceLanguage;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/Formality.java | deepl-java/src/main/java/com/deepl/api/Formality.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/** Desired level of formality for translation. */
public enum Formality {
/** Standard level of formality. */
Default,
/** Less formality, i.e. more informal. */
Less,
/** Increased formality. */
More,
/**
* Less formality, i.e. more informal, if available for the specified target language, otherwise
* default.
*/
PreferLess,
/** Increased formality, if available for the specified target language, otherwise default. */
PreferMore,
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/DocumentTranslationOptions.java | deepl-java/src/main/java/com/deepl/api/DocumentTranslationOptions.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/**
* Options to control document translation behaviour. These options may be provided to {@link
* Translator#translateDocument} overloads.
*
* <p>All properties have corresponding setters in fluent-style, so the following is possible:
* <code>
* DocumentTranslationOptions options = new DocumentTranslationOptions()
* .setFormality(Formality.Less).setGlossaryId("f63c02c5-f056-..");
* </code>
*/
public class DocumentTranslationOptions extends BaseRequestOptions {
private Formality formality;
private String glossaryId;
/**
* Sets whether translations should lean toward formal or informal language. This option is only
* applicable for target languages that support the formality option. By default, this value is
* <code>null</code> and translations use the default formality.
*
* @see Language#getSupportsFormality()
* @see Formality
*/
public DocumentTranslationOptions setFormality(Formality formality) {
this.formality = formality;
return this;
}
/**
* Sets the ID of a glossary to use with the translation. By default, this value is <code>
* null</code> and no glossary is used.
*/
public DocumentTranslationOptions setGlossaryId(String glossaryId) {
this.glossaryId = glossaryId;
return this;
}
/**
* Sets the glossary to use with the translation. By default, this value is <code>null</code> and
* no glossary is used.
*/
public DocumentTranslationOptions setGlossary(IGlossary glossary) {
return setGlossary(glossary.getGlossaryId());
}
/**
* Sets the glossary to use with the translation. By default, this value is <code>null</code> and
* no glossary is used.
*/
public DocumentTranslationOptions setGlossary(String glossaryId) {
this.glossaryId = glossaryId;
return this;
}
/** Gets the current formality setting. */
public Formality getFormality() {
return formality;
}
/** Gets the current glossary ID. */
public String getGlossaryId() {
return glossaryId;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/HttpClientWrapper.java | deepl-java/src/main/java/com/deepl/api/HttpClientWrapper.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import com.deepl.api.http.*;
import com.deepl.api.utils.*;
import java.io.*;
import java.net.*;
import java.time.*;
import java.util.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jetbrains.annotations.*;
/**
* Helper class providing functions to make HTTP requests and retry with exponential-backoff.
*
* <p>This class is internal; you should not use this class directly.
*/
class HttpClientWrapper {
private static final String CONTENT_TYPE = "Content-Type";
private static final String GET = "GET";
private static final String POST = "POST";
private static final String DELETE = "DELETE";
private static final String PUT = "PUT";
private final String serverUrl;
private final Map<String, String> headers;
private final Duration minTimeout;
private final @Nullable Proxy proxy;
private final int maxRetries;
public HttpClientWrapper(
String serverUrl,
Map<String, String> headers,
Duration minTimeout,
@Nullable Proxy proxy,
int maxRetries) {
this.serverUrl = serverUrl;
this.headers = headers;
this.minTimeout = minTimeout;
this.proxy = proxy;
this.maxRetries = maxRetries;
}
public HttpResponse sendGetRequestWithBackoff(String relativeUrl)
throws InterruptedException, DeepLException {
return sendRequestWithBackoff(GET, relativeUrl, null).toStringResponse();
}
public HttpResponse sendDeleteRequestWithBackoff(
String relativeUrl, @Nullable Iterable<KeyValuePair<String, String>> params)
throws InterruptedException, DeepLException {
HttpContent content = HttpContent.buildFormURLEncodedContent(params);
return sendRequestWithBackoff(DELETE, relativeUrl, content).toStringResponse();
}
public HttpResponse sendDeleteRequestWithBackoff(String relativeUrl)
throws InterruptedException, DeepLException {
return sendDeleteRequestWithBackoff(relativeUrl, null);
}
public HttpResponse sendRequestWithBackoff(String relativeUrl)
throws InterruptedException, DeepLException {
return sendRequestWithBackoff(POST, relativeUrl, null).toStringResponse();
}
public HttpResponse sendRequestWithBackoff(
String relativeUrl, @Nullable Iterable<KeyValuePair<String, String>> params)
throws InterruptedException, DeepLException {
HttpContent content = HttpContent.buildFormURLEncodedContent(params);
return sendRequestWithBackoff(POST, relativeUrl, content).toStringResponse();
}
public HttpResponse sendPutRequestWithBackoff(
String relativeUrl, @Nullable Iterable<KeyValuePair<String, String>> params)
throws InterruptedException, DeepLException {
HttpContent content = HttpContent.buildFormURLEncodedContent(params);
return sendRequestWithBackoff(PUT, relativeUrl, content).toStringResponse();
}
public HttpResponse sendPatchRequestWithBackoff(
String relativeUrl, @Nullable Iterable<KeyValuePair<String, String>> params)
throws DeepLException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpContent content = HttpContent.buildFormURLEncodedContent(params);
HttpPatch request = new HttpPatch(serverUrl + relativeUrl);
// Set timeouts
BackoffTimer backoffTimer = new BackoffTimer(this.minTimeout);
RequestConfig requestConfig =
RequestConfig.custom()
.setConnectTimeout((int) backoffTimer.getTimeoutMillis())
.setSocketTimeout((int) backoffTimer.getTimeoutMillis())
.build();
request.setConfig(requestConfig);
// Set headers
for (Map.Entry<String, String> entry : this.headers.entrySet()) {
request.setHeader(entry.getKey(), entry.getValue());
}
request.setHeader("Content-Type", content.getContentType());
request.setEntity(new ByteArrayEntity(content.getContent()));
// Execute the request
org.apache.http.HttpResponse response = httpClient.execute(request);
// Get the response stream
InputStream responseStream =
(response.getStatusLine().getStatusCode() >= 200
&& response.getStatusLine().getStatusCode() < 400)
? response.getEntity().getContent()
: new ByteArrayInputStream(EntityUtils.toByteArray(response.getEntity()));
return new HttpResponseStream(response.getStatusLine().getStatusCode(), responseStream)
.toStringResponse();
} catch (SocketTimeoutException e) {
throw new ConnectionException(e.getMessage(), true, e);
} catch (RuntimeException | IOException e) {
throw new ConnectionException(e.getMessage(), false, e);
}
}
public HttpResponseStream downloadWithBackoff(
String relativeUrl, @Nullable Iterable<KeyValuePair<String, String>> params)
throws InterruptedException, DeepLException {
HttpContent content = HttpContent.buildFormURLEncodedContent(params);
return sendRequestWithBackoff(POST, relativeUrl, content);
}
public HttpResponse uploadWithBackoff(
String relativeUrl,
@Nullable Iterable<KeyValuePair<String, String>> params,
String fileName,
InputStream inputStream)
throws InterruptedException, DeepLException {
ArrayList<KeyValuePair<String, Object>> fields = new ArrayList<>();
fields.add(new KeyValuePair<>("file", new NamedStream(fileName, inputStream)));
if (params != null) {
params.forEach(
(KeyValuePair<String, String> entry) -> {
fields.add(new KeyValuePair<>(entry.getKey(), entry.getValue()));
});
}
HttpContent content;
try {
content = HttpContent.buildMultipartFormDataContent(fields);
} catch (Exception e) {
throw new DeepLException("Failed building request", e);
}
return sendRequestWithBackoff(POST, relativeUrl, content).toStringResponse();
}
// Sends a request with exponential backoff
private HttpResponseStream sendRequestWithBackoff(
String method, String relativeUrl, HttpContent content)
throws InterruptedException, DeepLException {
BackoffTimer backoffTimer = new BackoffTimer(this.minTimeout);
while (true) {
try {
HttpResponseStream response =
sendRequest(method, serverUrl + relativeUrl, backoffTimer.getTimeoutMillis(), content);
if (backoffTimer.getNumRetries() >= this.maxRetries) {
return response;
} else if (response.getCode() != 429 && response.getCode() < 500) {
return response;
}
response.close();
} catch (ConnectionException exception) {
if (!exception.getShouldRetry() || backoffTimer.getNumRetries() >= this.maxRetries) {
throw exception;
}
}
backoffTimer.sleepUntilRetry();
}
}
private HttpResponseStream sendRequest(
String method, String urlString, long timeoutMs, HttpContent content)
throws ConnectionException {
try {
URL url = new URL(urlString);
HttpURLConnection connection =
(HttpURLConnection) (proxy != null ? url.openConnection(proxy) : url.openConnection());
connection.setRequestMethod(method);
connection.setConnectTimeout((int) timeoutMs);
connection.setReadTimeout((int) timeoutMs);
connection.setUseCaches(false);
for (Map.Entry<String, String> entry : this.headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
if (content != null) {
connection.setDoOutput(true);
connection.setRequestProperty(CONTENT_TYPE, content.getContentType());
try (OutputStream output = connection.getOutputStream()) {
output.write(content.getContent());
}
}
int responseCode = connection.getResponseCode();
InputStream responseStream =
(responseCode >= 200 && responseCode < 400)
? connection.getInputStream()
: connection.getErrorStream();
return new HttpResponseStream(responseCode, responseStream);
} catch (SocketTimeoutException e) {
throw new ConnectionException(e.getMessage(), true, e);
} catch (RuntimeException | IOException e) {
throw new ConnectionException(e.getMessage(), false, e);
}
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/Translator.java | deepl-java/src/main/java/com/deepl/api/Translator.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import com.deepl.api.http.HttpResponse;
import com.deepl.api.http.HttpResponseStream;
import com.deepl.api.parsing.Parser;
import com.deepl.api.utils.*;
import com.google.gson.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.util.*;
import org.jetbrains.annotations.Nullable;
/**
* Client for the DeepL API. To use the DeepL API, initialize an instance of this class using your
* DeepL Authentication Key as found in your <a href="https://www.deepl.com/pro-account/">DeepL
* account</a>.
*/
public class Translator {
/** Base URL for DeepL API Free accounts. */
private static final String DEEPL_SERVER_URL_FREE = "https://api-free.deepl.com";
/** Base URL for DeepL API Pro accounts */
private static final String DEEPL_SERVER_URL_PRO = "https://api.deepl.com";
protected final Parser jsonParser = new Parser();
protected final HttpClientWrapper httpClientWrapper;
protected final DeepLApiVersion apiVersion;
/**
* Initializes a new Translator object using your Authentication Key.
*
* <p>Note: This function does not establish a connection to the DeepL API. To check connectivity,
* use {@link Translator#getUsage()}.
*
* @param authKey DeepL Authentication Key as found in your <a
* href="https://www.deepl.com/pro-account/">DeepL account</a>.
* @param options Additional options controlling Translator behaviour.
* @throws IllegalArgumentException If authKey is invalid.
* @deprecated Use {@link DeepLClient} instead.
*/
@Deprecated
public Translator(String authKey, TranslatorOptions options) throws IllegalArgumentException {
if (authKey == null || authKey.isEmpty()) {
throw new IllegalArgumentException("authKey cannot be null or empty");
}
String sanitizedAuthKey = authKey.trim();
this.apiVersion = options.apiVersion;
String serverUrl =
(options.getServerUrl() != null)
? options.getServerUrl()
: (isFreeAccountAuthKey(sanitizedAuthKey)
? DEEPL_SERVER_URL_FREE
: DEEPL_SERVER_URL_PRO);
Map<String, String> headers = new HashMap<>();
if (options.getHeaders() != null) {
headers.putAll(options.getHeaders());
}
headers.putIfAbsent("Authorization", "DeepL-Auth-Key " + sanitizedAuthKey);
headers.putIfAbsent(
"User-Agent",
constructUserAgentString(options.getSendPlatformInfo(), options.getAppInfo()));
this.httpClientWrapper =
new HttpClientWrapper(
serverUrl, headers, options.getTimeout(), options.getProxy(), options.getMaxRetries());
}
/**
* Initializes a new Translator object using your Authentication Key.
*
* <p>Note: This function does not establish a connection to the DeepL API. To check connectivity,
* use {@link Translator#getUsage()}.
*
* @param authKey DeepL Authentication Key as found in your <a
* href="https://www.deepl.com/pro-account/">DeepL account</a>.
* @throws IllegalArgumentException If authKey is invalid.
* @deprecated Use {@link DeepLClient} instead.
*/
@Deprecated
public Translator(String authKey) throws IllegalArgumentException {
this(authKey, new TranslatorOptions());
}
/**
* Builds the user-agent String which contains platform information.
*
* @return A string containing the client library version, java version and operating system.
*/
private String constructUserAgentString(boolean sendPlatformInfo, AppInfo appInfo) {
StringBuilder sb = new StringBuilder();
sb.append("deepl-java/1.14.0");
if (sendPlatformInfo) {
sb.append(" (");
Properties props = System.getProperties();
sb.append(props.get("os.name") + "-" + props.get("os.version") + "-" + props.get("os.arch"));
sb.append(") java/");
sb.append(props.get("java.version"));
}
if (appInfo != null) {
sb.append(" " + appInfo.getAppName() + "/" + appInfo.getAppVersion());
}
return sb.toString();
}
/**
* Determines if the given DeepL Authentication Key belongs to an API Free account.
*
* @param authKey DeepL Authentication Key as found in your <a
* href="https://www.deepl.com/pro-account/">DeepL account</a>.
* @return <code>true</code> if the Authentication Key belongs to an API Free account, otherwise
* <code>false</code>.
*/
public static boolean isFreeAccountAuthKey(String authKey) {
return authKey != null && authKey.endsWith(":fx");
}
/**
* Translate specified text from source language into target language.
*
* @param text Text to translate; must not be empty.
* @param sourceLang Language code of the input language, or <code>null</code> to use
* auto-detection.
* @param targetLang Language code of the desired output language.
* @param options Options influencing translation.
* @return Text translated into specified target language, and detected source language.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public TextResult translateText(
String text,
@Nullable String sourceLang,
String targetLang,
@Nullable TextTranslationOptions options)
throws InterruptedException, DeepLException {
ArrayList<String> texts = new ArrayList<>();
texts.add(text);
return translateText(texts, sourceLang, targetLang, options).get(0);
}
/**
* Functions the same as {@link Translator#translateText(String, String, String,
* TextTranslationOptions)} but with default options.
*
* @see Translator#translateText(String, String, String, TextTranslationOptions)
*/
public TextResult translateText(String text, @Nullable String sourceLang, String targetLang)
throws DeepLException, InterruptedException {
return translateText(text, sourceLang, targetLang, null);
}
/**
* Functions the same as {@link Translator#translateText(String, String, String,
* TextTranslationOptions)} but accepts {@link Language} objects for source and target languages,
* and uses default options.
*
* @see Translator#translateText(String, String, String, TextTranslationOptions)
*/
public TextResult translateText(String text, @Nullable Language sourceLang, Language targetLang)
throws DeepLException, InterruptedException {
return translateText(
text, (sourceLang != null) ? sourceLang.getCode() : null, targetLang.getCode(), null);
}
/**
* Functions the same as {@link Translator#translateText(String, String, String,
* TextTranslationOptions)} but accepts {@link Language} objects for source and target languages.
*
* @see Translator#translateText(String, String, String, TextTranslationOptions)
*/
public TextResult translateText(
String text,
@Nullable Language sourceLang,
Language targetLang,
@Nullable TextTranslationOptions options)
throws DeepLException, InterruptedException {
return translateText(
text, (sourceLang != null) ? sourceLang.getCode() : null, targetLang.getCode(), options);
}
/**
* Translate specified texts from source language into target language.
*
* @param texts List of texts to translate; each text must not be empty.
* @param sourceLang Language code of the input language, or <code>null</code> to use
* auto-detection.
* @param targetLang Language code of the desired output language.
* @param options Options influencing translation.
* @return List of texts translated into specified target language, and detected source language.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public List<TextResult> translateText(
List<String> texts,
@Nullable String sourceLang,
String targetLang,
@Nullable TextTranslationOptions options)
throws DeepLException, InterruptedException {
Iterable<KeyValuePair<String, String>> params =
createHttpParams(texts, sourceLang, targetLang, options);
HttpResponse response =
httpClientWrapper.sendRequestWithBackoff(
String.format("/%s/translate", this.apiVersion), params);
checkResponse(response, false, false);
return jsonParser.parseTextResult(response.getBody());
}
/**
* Functions the same as {@link Translator#translateText(List, String, String,
* TextTranslationOptions)} but accepts {@link Language} objects for source and target languages,
* and uses default options.
*
* @see Translator#translateText(List, String, String, TextTranslationOptions)
*/
public List<TextResult> translateText(
List<String> texts, @Nullable Language sourceLang, Language targetLang)
throws DeepLException, InterruptedException {
return translateText(
texts, (sourceLang != null) ? sourceLang.getCode() : null, targetLang.getCode(), null);
}
/**
* Functions the same as {@link Translator#translateText(List, String, String,
* TextTranslationOptions)} but accepts {@link Language} objects for source and target languages.
*
* @see Translator#translateText(List, String, String, TextTranslationOptions)
*/
public List<TextResult> translateText(
List<String> texts,
@Nullable Language sourceLang,
Language targetLang,
@Nullable TextTranslationOptions options)
throws DeepLException, InterruptedException {
return translateText(
texts, (sourceLang != null) ? sourceLang.getCode() : null, targetLang.getCode(), options);
}
/**
* Functions the same as {@link Translator#translateText(List, String, String,
* TextTranslationOptions)} but uses default options.
*
* @see Translator#translateText(List, String, String, TextTranslationOptions)
*/
public List<TextResult> translateText(
List<String> texts, @Nullable String sourceLang, String targetLang)
throws DeepLException, InterruptedException {
return translateText(texts, sourceLang, targetLang, null);
}
/**
* Retrieves the usage in the current billing period for this DeepL account. This function can
* also be used to check connectivity with the DeepL API and that the account has access.
*
* @return {@link Usage} object containing account usage information.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public Usage getUsage() throws DeepLException, InterruptedException {
HttpResponse response =
httpClientWrapper.sendGetRequestWithBackoff(String.format("/%s/usage", apiVersion));
checkResponse(response, false, false);
return jsonParser.parseUsage(response.getBody());
}
/**
* Retrieves the list of supported translation source languages.
*
* @return List of {@link Language} objects representing the available translation source
* languages.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public List<Language> getSourceLanguages() throws DeepLException, InterruptedException {
return getLanguages(LanguageType.Source);
}
/**
* Retrieves the list of supported translation target languages.
*
* @return List of {@link Language} objects representing the available translation target
* languages.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public List<Language> getTargetLanguages() throws DeepLException, InterruptedException {
return getLanguages(LanguageType.Target);
}
/**
* Retrieves the list of supported translation source or target languages.
*
* @param languageType The type of languages to retrieve, source or target.
* @return List of {@link Language} objects representing the available translation source or
* target languages.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public List<Language> getLanguages(LanguageType languageType)
throws DeepLException, InterruptedException {
ArrayList<KeyValuePair<String, String>> params = new ArrayList<>();
if (languageType == LanguageType.Target) {
params.add(new KeyValuePair<>("type", "target"));
}
HttpResponse response =
httpClientWrapper.sendRequestWithBackoff(
String.format("/%s/languages", apiVersion), params);
checkResponse(response, false, false);
return jsonParser.parseLanguages(response.getBody());
}
/**
* Retrieves the list of supported glossary language pairs. When creating glossaries, the source
* and target language pair must match one of the available language pairs.
*
* @return List of {@link GlossaryLanguagePair} objects representing the available glossary
* language pairs.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public List<GlossaryLanguagePair> getGlossaryLanguages()
throws DeepLException, InterruptedException {
HttpResponse response =
httpClientWrapper.sendGetRequestWithBackoff(
String.format("/%s/glossary-language-pairs", apiVersion));
checkResponse(response, false, false);
return jsonParser.parseGlossaryLanguageList(response.getBody());
}
/**
* Translate specified document content from source language to target language and store the
* translated document content to specified stream.
*
* @param inputFile File to upload to be translated.
* @param outputFile File to download translated document to.
* @param sourceLang Language code of the input language, or <code>null</code> to use
* auto-detection.
* @param targetLang Language code of the desired output language.
* @param options Options influencing translation.
* @return Status when document translation completed, this allows the number of billed characters
* to be queried.
* @throws IOException If the output path is occupied or the input file does not exist.
* @throws DocumentTranslationException If any error occurs while communicating with the DeepL
* API, or if the thread is interrupted during execution of this function. The exception
* includes the document handle that may be used to retrieve the document.
*/
public DocumentStatus translateDocument(
File inputFile,
File outputFile,
@Nullable String sourceLang,
String targetLang,
@Nullable DocumentTranslationOptions options)
throws DocumentTranslationException, IOException {
try {
if (outputFile.exists()) {
throw new IOException("File already exists at output path");
}
try (InputStream inputStream = new FileInputStream(inputFile);
OutputStream outputStream = new FileOutputStream(outputFile)) {
return translateDocument(
inputStream, inputFile.getName(), outputStream, sourceLang, targetLang, options);
}
} catch (Exception exception) {
outputFile.delete();
throw exception;
}
}
/**
* Functions the same as {@link Translator#translateDocument(File, File, String, String,
* DocumentTranslationOptions)} but uses default options.
*
* @see Translator#translateDocument(File, File, String, String, DocumentTranslationOptions)
*/
public DocumentStatus translateDocument(
File inputFile, File outputFile, @Nullable String sourceLang, String targetLang)
throws DocumentTranslationException, IOException {
return translateDocument(inputFile, outputFile, sourceLang, targetLang, null);
}
/**
* Translate specified document content from source language to target language and store the
* translated document content to specified stream. On return, input stream will be at end of
* stream and neither stream will be closed.
*
* @param inputStream Stream containing file to upload to be translated.
* @param fileName Name of the input file. The file extension is used to determine file type.
* @param outputStream Stream to download translated document to.
* @param sourceLang Language code of the input language, or <code>null</code> to use
* auto-detection.
* @param targetLang Language code of the desired output language.
* @param options Options influencing translation.
* @return Status when document translation completed, this allows the number of billed characters
* to be queried.
* @throws DocumentTranslationException If any error occurs while communicating with the DeepL
* API, or if the thread is interrupted during execution of this function. The exception
* includes the document handle that may be used to retrieve the document.
*/
public DocumentStatus translateDocument(
InputStream inputStream,
String fileName,
OutputStream outputStream,
@Nullable String sourceLang,
String targetLang,
@Nullable DocumentTranslationOptions options)
throws DocumentTranslationException {
DocumentHandle handle = null;
try {
handle = translateDocumentUpload(inputStream, fileName, sourceLang, targetLang, options);
DocumentStatus status = translateDocumentWaitUntilDone(handle);
translateDocumentDownload(handle, outputStream);
return status;
} catch (Exception exception) {
throw new DocumentTranslationException(
"Error occurred during document translation: " + exception.getMessage(),
exception,
handle);
}
}
/**
* Functions the same as {@link Translator#translateDocument(InputStream, String, OutputStream,
* String, String, DocumentTranslationOptions)} but uses default options.
*
* @see Translator#translateDocument(InputStream, String, OutputStream, String, String,
* DocumentTranslationOptions)
*/
public DocumentStatus translateDocument(
InputStream inputFile,
String fileName,
OutputStream outputFile,
@Nullable String sourceLang,
String targetLang)
throws DocumentTranslationException {
return translateDocument(inputFile, fileName, outputFile, sourceLang, targetLang, null);
}
/**
* Upload document at specified input path for translation from source language to target
* language. See the <a href= "https://www.deepl.com/docs-api/translating-documents/">DeepL API
* documentation</a> for the currently supported document types.
*
* @param inputFile File containing document to be translated.
* @param sourceLang Language code of the input language, or <code>null</code> to use
* auto-detection.
* @param targetLang Language code of the desired output language.
* @param options Options influencing translation.
* @return Handle associated with the in-progress document translation.
* @throws IOException If the input file does not exist.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public DocumentHandle translateDocumentUpload(
File inputFile,
@Nullable String sourceLang,
String targetLang,
@Nullable DocumentTranslationOptions options)
throws DeepLException, IOException, InterruptedException {
Iterable<KeyValuePair<String, String>> params =
createHttpParams(sourceLang, targetLang, options);
try (FileInputStream inputStream = new FileInputStream(inputFile)) {
HttpResponse response =
httpClientWrapper.uploadWithBackoff(
String.format("/%s/document", apiVersion), params, inputFile.getName(), inputStream);
checkResponse(response, false, false);
return jsonParser.parseDocumentHandle(response.getBody());
}
}
/**
* Functions the same as {@link Translator#translateDocumentUpload(File, String, String,
* DocumentTranslationOptions)} but uses default options.
*
* @see Translator#translateDocumentUpload(File, String, String, DocumentTranslationOptions)
*/
public DocumentHandle translateDocumentUpload(
File inputFile, @Nullable String sourceLang, String targetLang)
throws DeepLException, IOException, InterruptedException {
return translateDocumentUpload(inputFile, sourceLang, targetLang, null);
}
/**
* Upload document at specified input path for translation from source language to target
* language. See the <a href= "https://www.deepl.com/docs-api/translating-documents/">DeepL API
* documentation</a> for the currently supported document types.
*
* @param inputStream Stream containing document to be translated. On return, input stream will be
* at end of stream and will not be closed.
* @param fileName Name of the input file. The file extension is used to determine file type.
* @param sourceLang Language code of the input language, or <code>null</code> to use
* auto-detection.
* @param targetLang Language code of the desired output language.
* @param options Options influencing translation.
* @return Handle associated with the in-progress document translation.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public DocumentHandle translateDocumentUpload(
InputStream inputStream,
String fileName,
@Nullable String sourceLang,
String targetLang,
@Nullable DocumentTranslationOptions options)
throws DeepLException, InterruptedException {
Iterable<KeyValuePair<String, String>> params =
createHttpParams(sourceLang, targetLang, options);
HttpResponse response =
httpClientWrapper.uploadWithBackoff(
String.format("/%s/document/", apiVersion), params, fileName, inputStream);
checkResponse(response, false, false);
return jsonParser.parseDocumentHandle(response.getBody());
}
/**
* Functions the same as {@link Translator#translateDocumentUpload(InputStream, String, String,
* String, DocumentTranslationOptions)} but uses default options.
*
* @see Translator#translateDocumentUpload(InputStream, String, String, String,
* DocumentTranslationOptions)
*/
public DocumentHandle translateDocumentUpload(
InputStream inputStream, String fileName, @Nullable String sourceLang, String targetLang)
throws DeepLException, InterruptedException {
return translateDocumentUpload(inputStream, fileName, sourceLang, targetLang, null);
}
/**
* Retrieve the status of in-progress document translation associated with specified handle.
*
* @param handle Handle associated with document translation to check.
* @return Status of the document translation.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public DocumentStatus translateDocumentStatus(DocumentHandle handle)
throws DeepLException, InterruptedException {
ArrayList<KeyValuePair<String, String>> params = new ArrayList<>();
params.add(new KeyValuePair<>("document_key", handle.getDocumentKey()));
String relativeUrl = String.format("/%s/document/%s", apiVersion, handle.getDocumentId());
HttpResponse response = httpClientWrapper.sendRequestWithBackoff(relativeUrl, params);
checkResponse(response, false, false);
return jsonParser.parseDocumentStatus(response.getBody());
}
/**
* Checks document translation status and waits until document translation is complete or fails
* due to an error.
*
* @param handle Handle associated with document translation to wait for.
* @return Status when document translation completed, this allows the number of billed characters
* to be queried.
* @throws InterruptedException If the thread is interrupted while waiting for the document
* translation to complete.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public DocumentStatus translateDocumentWaitUntilDone(DocumentHandle handle)
throws InterruptedException, DeepLException {
DocumentStatus status = translateDocumentStatus(handle);
while (status.ok() && !status.done()) {
Thread.sleep(calculateDocumentWaitTimeMillis(status.getSecondsRemaining()));
status = translateDocumentStatus(handle);
}
if (!status.ok()) {
String message =
(status.getErrorMessage() != null) ? status.getErrorMessage() : "Unknown error";
throw new DeepLException(message);
}
return status;
}
/**
* Downloads the resulting translated document associated with specified handle to the specified
* output file. The document translation must be complete i.e. {@link DocumentStatus#done()} for
* the document status must be <code>true</code>.
*
* @param handle Handle associated with document translation to download.
* @param outputFile File to download translated document to.
* @throws IOException If the output path is occupied.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public void translateDocumentDownload(DocumentHandle handle, File outputFile)
throws DeepLException, IOException, InterruptedException {
try {
if (outputFile.exists()) {
throw new IOException("File already exists at output path");
}
try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
translateDocumentDownload(handle, outputStream);
}
} catch (Exception exception) {
outputFile.delete();
throw exception;
}
}
/**
* Downloads the resulting translated document associated with specified handle to the specified
* output stream. The document translation must be complete i.e. {@link DocumentStatus#done()} for
* the document status must be <code>true</code>. The output stream is not closed.
*
* @param handle Handle associated with document translation to download.
* @param outputStream Stream to download translated document to.
* @throws IOException If an I/O error occurs.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public void translateDocumentDownload(DocumentHandle handle, OutputStream outputStream)
throws DeepLException, IOException, InterruptedException {
ArrayList<KeyValuePair<String, String>> params = new ArrayList<>();
params.add(new KeyValuePair<>("document_key", handle.getDocumentKey()));
String relativeUrl =
String.format("/%s/document/%s/result", apiVersion, handle.getDocumentId());
try (HttpResponseStream response = httpClientWrapper.downloadWithBackoff(relativeUrl, params)) {
checkResponse(response);
assert response.getBody() != null;
StreamUtil.transferTo(response.getBody(), outputStream);
}
}
/**
* Creates a glossary in your DeepL account with the specified details and returns a {@link
* GlossaryInfo} object with details about the newly created glossary. The glossary can be used in
* translations to override translations for specific terms (words). The glossary source and
* target languages must match the languages of translations for which it will be used.
*
* @param name User-defined name to assign to the glossary; must not be empty.
* @param sourceLang Language code of the source terms language.
* @param targetLang Language code of the target terms language.
* @param entries Glossary entries to add to the glossary.
* @return {@link GlossaryInfo} object with details about the newly created glossary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public GlossaryInfo createGlossary(
String name, String sourceLang, String targetLang, GlossaryEntries entries)
throws DeepLException, InterruptedException {
return createGlossaryInternal(name, sourceLang, targetLang, "tsv", entries.toTsv());
}
/**
* Creates a glossary in your DeepL account with the specified details and returns a {@link
* GlossaryInfo} object with details about the newly created glossary. The glossary can be used in
* translations to override translations for specific terms (words). The glossary source and
* target languages must match the languages of translations for which it will be used.
*
* @param name User-defined name to assign to the glossary; must not be empty.
* @param sourceLang Language code of the source terms language.
* @param targetLang Language code of the target terms language.
* @param csvFile File containing CSV content for glossary.
* @return {@link GlossaryInfo} object with details about the newly created glossary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
* @throws IOException If an I/O error occurs.
*/
public GlossaryInfo createGlossaryFromCsv(
String name, String sourceLang, String targetLang, File csvFile)
throws DeepLException, InterruptedException, IOException {
try (FileInputStream stream = new FileInputStream(csvFile)) {
String csvContent = StreamUtil.readStream(stream);
return createGlossaryFromCsv(name, sourceLang, targetLang, csvContent);
}
}
/**
* Creates a glossary in your DeepL account with the specified details and returns a {@link
* GlossaryInfo} object with details about the newly created glossary. The glossary can be used in
* translations to override translations for specific terms (words). The glossary source and
* target languages must match the languages of translations for which it will be used.
*
* @param name User-defined name to assign to the glossary; must not be empty.
* @param sourceLang Language code of the source terms language.
* @param targetLang Language code of the target terms language.
* @param csvContent String containing CSV content.
* @return {@link GlossaryInfo} object with details about the newly created glossary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public GlossaryInfo createGlossaryFromCsv(
String name, String sourceLang, String targetLang, String csvContent)
throws DeepLException, InterruptedException {
return createGlossaryInternal(name, sourceLang, targetLang, "csv", csvContent);
}
/**
* Retrieves information about the glossary with the specified ID and returns a {@link
* GlossaryInfo} object containing details. This does not retrieve the glossary entries; to
* retrieve entries use {@link Translator#getGlossaryEntries(String)}
*
* @param glossaryId ID of glossary to retrieve.
* @return {@link GlossaryInfo} object with details about the specified glossary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public GlossaryInfo getGlossary(String glossaryId) throws DeepLException, InterruptedException {
String relativeUrl = String.format("/%s/glossaries/%s", apiVersion, glossaryId);
HttpResponse response = httpClientWrapper.sendGetRequestWithBackoff(relativeUrl);
checkResponse(response, false, true);
return jsonParser.parseGlossaryInfo(response.getBody());
}
/**
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | true |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/TranslatorOptions.java | deepl-java/src/main/java/com/deepl/api/TranslatorOptions.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import java.net.Proxy;
import java.time.Duration;
import java.util.Map;
import org.jetbrains.annotations.Nullable;
/**
* Options to control translator behaviour. These options may be provided to the {@link Translator}
* constructor.
*
* <p>All properties have corresponding setters in fluent-style, so the following is possible:
* <code>
* TranslatorOptions options = new TranslatorOptions()
* .setTimeout(Duration.ofSeconds(1)).setMaxRetries(2);
* </code>
*/
public class TranslatorOptions {
private int maxRetries = 5;
private Duration timeout = Duration.ofSeconds(10);
@Nullable private Proxy proxy = null;
@Nullable private Map<String, String> headers = null;
@Nullable private String serverUrl = null;
private boolean sendPlatformInfo = true;
@Nullable private AppInfo appInfo = null;
@Nullable protected DeepLApiVersion apiVersion = null;
/** @deprecated Use {@link DeepLClient} instead. */
@Deprecated
public TranslatorOptions() {
apiVersion = DeepLApiVersion.VERSION_2;
}
/**
* Set the maximum number of failed attempts that {@link Translator} will retry, per request. By
* default, 5 retries are made. Note: only errors due to transient conditions are retried.
*/
public TranslatorOptions setMaxRetries(int maxRetries) {
this.maxRetries = maxRetries;
return this;
}
/** Set the connection timeout used for each HTTP request retry, the default is 10 seconds. */
public TranslatorOptions setTimeout(Duration timeout) {
this.timeout = timeout;
return this;
}
/**
* Set the proxy to use for HTTP requests. By default, this value is <code>null</code> and no
* proxy will be used.
*/
public TranslatorOptions setProxy(Proxy proxy) {
this.proxy = proxy;
return this;
}
/**
* Set HTTP headers attached to every HTTP request. By default, this value is <code>null</code>
* and no extra headers are used. Note that in the {@link Translator} constructor the headers for
* Authorization and User-Agent are added, unless they are overridden in this option.
*/
public TranslatorOptions setHeaders(Map<String, String> headers) {
this.headers = headers;
return this;
}
/**
* Set the base URL for DeepL API that may be overridden for testing purposes. By default, this
* value is <code>null</code> and the correct DeepL API base URL is selected based on the API
* account type (free or paid).
*/
public TranslatorOptions setServerUrl(String serverUrl) {
this.serverUrl = serverUrl;
return this;
}
/**
* Set whether to send basic platform information with each API call to improve DeepL products.
* Defaults to `true`, set to `false` to opt out. This option will be overriden if a
* `'User-agent'` header is present in this objects `headers`.
*/
public TranslatorOptions setSendPlatformInfo(boolean sendPlatformInfo) {
this.sendPlatformInfo = sendPlatformInfo;
return this;
}
/**
* Set an identifier and a version for the program/plugin that uses this Client Library. Example:
* `Translator t = new Translator(myAuthKey, new TranslatorOptions()
* .setAppInfo('deepl-hadoop-plugin', '1.2.0'))
*/
public TranslatorOptions setAppInfo(String appName, String appVersion) {
this.appInfo = new AppInfo(appName, appVersion);
return this;
}
/** Gets the current maximum number of retries. */
public int getMaxRetries() {
return maxRetries;
}
/** Gets the current maximum request timeout. */
public Duration getTimeout() {
return timeout;
}
/** Gets the current proxy. */
public @Nullable Proxy getProxy() {
return proxy;
}
/** Gets the current HTTP headers. */
public @Nullable Map<String, String> getHeaders() {
return headers;
}
/** Gets the current custom server URL. */
public @Nullable String getServerUrl() {
return serverUrl;
}
/** Gets the `sendPlatformInfo` option */
public boolean getSendPlatformInfo() {
return sendPlatformInfo;
}
/** Gets the `appInfo` identifiers */
public @Nullable AppInfo getAppInfo() {
return appInfo;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/WritingStyle.java | deepl-java/src/main/java/com/deepl/api/WritingStyle.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/** Represents the style the improved text should be in in a rephrase request. */
public enum WritingStyle {
Academic("academic"),
Business("business"),
Casual("casual"),
Default("default"),
PreferAcademic("prefer_academic"),
PreferBusiness("prefer_business"),
PreferCasual("prefer_casual"),
PreferSimple("prefer_simple"),
Simple("simple");
private final String value;
WritingStyle(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/DeepLException.java | deepl-java/src/main/java/com/deepl/api/DeepLException.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/** Base class for all exceptions thrown by this library. */
public class DeepLException extends Exception {
public DeepLException(String message) {
super(message);
}
public DeepLException(String message, Throwable cause) {
super(message, cause);
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/MultilingualGlossaryDictionaryInfo.java | deepl-java/src/main/java/com/deepl/api/MultilingualGlossaryDictionaryInfo.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import com.google.gson.annotations.SerializedName;
/** Stores the entries of a glossary. */
public class MultilingualGlossaryDictionaryInfo {
@SerializedName(value = "source_lang")
private final String sourceLanguageCode;
@SerializedName(value = "target_lang")
private final String targetLanguageCode;
@SerializedName(value = "entry_count")
private final long entryCount;
/**
* Initializes a new {@link MultilingualGlossaryDictionaryInfo} containing information about a
* glossary dictionary.
*
* @param sourceLanguageCode the source language for this dictionary
* @param targetLanguageCode the target language for this dictionary
* @param entryCount the number of entries in this dictionary
*/
public MultilingualGlossaryDictionaryInfo(
String sourceLanguageCode, String targetLanguageCode, long entryCount) {
this.sourceLanguageCode = sourceLanguageCode;
this.targetLanguageCode = targetLanguageCode;
this.entryCount = entryCount;
}
/** @return the source language code */
public String getSourceLanguageCode() {
return this.sourceLanguageCode;
}
/** @return the target language code */
public String getTargetLanguageCode() {
return this.targetLanguageCode;
}
/** @return the entry count */
public long getEntryCount() {
return this.entryCount;
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/DeepLClient.java | deepl-java/src/main/java/com/deepl/api/DeepLClient.java | // Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
import com.deepl.api.http.HttpResponse;
import com.deepl.api.utils.*;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.jetbrains.annotations.Nullable;
public class DeepLClient extends Translator {
/**
* Initializes a new DeepLClient object using your Authentication Key.
*
* <p>Note: This function does not establish a connection to the DeepL API. To check connectivity,
* use {@link DeepLClient#getUsage()}.
*
* @param authKey DeepL Authentication Key as found in your <a
* href="https://www.deepl.com/pro-account/">DeepL account</a>.
* @throws IllegalArgumentException If authKey is invalid.
*/
public DeepLClient(String authKey) throws IllegalArgumentException {
this(authKey, new DeepLClientOptions());
}
/**
* Initializes a new DeepLClient object using your Authentication Key.
*
* <p>Note: This function does not establish a connection to the DeepL API. To check connectivity,
* use {@link DeepLClient#getUsage()}.
*
* @param authKey DeepL Authentication Key as found in your <a
* href="https://www.deepl.com/pro-account/">DeepL account</a>.
* @param options Additional options controlling Client behaviour.
* @throws IllegalArgumentException If authKey is invalid.
* @deprecated Use the constructor that takes {@link DeepLClientOptions} instead of {@link
* TranslatorOptions}
*/
@Deprecated
public DeepLClient(String authKey, TranslatorOptions options) throws IllegalArgumentException {
super(authKey, options);
}
/**
* Initializes a new DeepLClient object using your Authentication Key.
*
* <p>Note: This function does not establish a connection to the DeepL API. To check connectivity,
* use {@link DeepLClient#getUsage()}.
*
* @param authKey DeepL Authentication Key as found in your <a
* href="https://www.deepl.com/pro-account/">DeepL account</a>.
* @param options Additional options controlling Client behaviour.
* @throws IllegalArgumentException If authKey is invalid.
*/
@SuppressWarnings("deprecation")
public DeepLClient(String authKey, DeepLClientOptions options) throws IllegalArgumentException {
super(authKey, options);
}
public WriteResult rephraseText(
String text, @Nullable String targetLang, @Nullable TextRephraseOptions options)
throws InterruptedException, DeepLException {
ArrayList<String> texts = new ArrayList<>();
texts.add(text);
return this.rephraseText(texts, targetLang, options).get(0);
}
public List<WriteResult> rephraseText(
List<String> texts, @Nullable String targetLang, @Nullable TextRephraseOptions options)
throws InterruptedException, DeepLException {
Iterable<KeyValuePair<String, String>> params =
createWriteHttpParams(texts, targetLang, options);
HttpResponse response =
httpClientWrapper.sendRequestWithBackoff(
String.format("/%s/write/rephrase", apiVersion), params);
checkResponse(response, false, false);
return jsonParser.parseWriteResult(response.getBody());
}
/**
* Creates a glossary in your DeepL account with the specified details and returns a {@link
* MultilingualGlossaryInfo} object with details about the newly created glossary. The glossary
* will contain the glossary dictionaries specified in <paramref name="glossaryDicts" /> each with
* their own source language, target language and entries.The glossary can be used in translations
* to override translations for specific terms (words). The glossary must contain a glossary
* dictionary that matches the languages of translations for which it will be used.
*
* @param name User-defined name to assign to the glossary; must not be empty.
* @param glossaryDicts {@link MultilingualGlossaryDictionaryInfo} The dictionaries of the
* glossary
* @return {@link MultilingualGlossaryInfo} object with details about the newly created glossary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws IllegalArgumentException If any argument is invalid.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
*/
public MultilingualGlossaryInfo createMultilingualGlossary(
String name, List<MultilingualGlossaryDictionaryEntries> glossaryDicts)
throws DeepLException, IllegalArgumentException, InterruptedException {
validateParameter("name", name);
if (glossaryDicts.isEmpty()) {
throw new IllegalArgumentException("Parameter dictionaries must not be empty");
}
ArrayList<KeyValuePair<String, String>> bodyParams =
createGlossaryHttpParams(name, glossaryDicts);
HttpResponse response = httpClientWrapper.sendRequestWithBackoff("/v3/glossaries", bodyParams);
checkResponse(response, false, false);
return jsonParser.parseMultilingualGlossaryInfo(response.getBody());
}
/**
* Creates a glossary in your DeepL account with the specified details and returns a {@link
* MultilingualGlossaryInfo} object with details about the newly created glossary. The glossary
* will contain a glossary dictionary with the source and target language codes specified and
* entries created from the <paramref name="csvFile" />. The glossary can be used in translations
* to override translations for specific terms (words). The glossary must contain a glossary
* dictionary that matches the languages of translations for which it will be used.
*
* @param name User-defined name to assign to the glossary; must not be empty.
* @param sourceLanguageCode Language code of the source terms language.
* @param targetLanguageCode Language code of the target terms language.
* @param csvFile String containing CSV content.
* @return {@link MultilingualGlossaryInfo} object with details about the newly created glossary.
* @throws IllegalArgumentException If any argument is invalid.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
*/
public MultilingualGlossaryInfo createMultilingualGlossaryFromCsv(
String name, String sourceLanguageCode, String targetLanguageCode, String csvFile)
throws DeepLException, IllegalArgumentException, InterruptedException {
return createGlossaryFromCsvInternal(name, sourceLanguageCode, targetLanguageCode, csvFile);
}
/**
* Creates a glossary in your DeepL account with the specified details and returns a {@link
* MultilingualGlossaryInfo} object with details about the newly created glossary. The glossary
* will contain a glossary dictionary with the source and target language codes specified and
* entries created from the <paramref name="csvFile" />. The glossary can be used in translations
* to override translations for specific terms (words). The glossary must contain a glossary
* dictionary that matches the languages of translations for which it will be used.
*
* @param name User-defined name to assign to the glossary; must not be empty.
* @param sourceLanguageCode Language code of the source terms language.
* @param targetLanguageCode Language code of the target terms language.
* @param csvFile String containing CSV content.
* @return {@link MultilingualGlossaryInfo} object with details about the newly created glossary.
* @throws IllegalArgumentException If any argument is invalid.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
* @throws IOException If an I/O error occurs.
*/
public MultilingualGlossaryInfo createMultilingualGlossaryFromCsv(
String name, String sourceLanguageCode, String targetLanguageCode, File csvFile)
throws DeepLException, IllegalArgumentException, InterruptedException, IOException {
try (FileInputStream stream = new FileInputStream(csvFile)) {
String csvContent = StreamUtil.readStream(stream);
return createGlossaryFromCsvInternal(
name, sourceLanguageCode, targetLanguageCode, csvContent);
}
}
/**
* Retrieves information about the glossary with the specified ID and returns a {@link
* MultilingualGlossaryInfo} object containing details. This does not retrieve the glossary
* entries; to retrieve entries use {@link
* DeepLClient#getMultilingualGlossaryDictionaryEntries(String, String, String)}
*
* @param glossaryId ID of glossary to retrieve.
* @return {@link MultilingualGlossaryInfo} object with details about the specified glossary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public MultilingualGlossaryInfo getMultilingualGlossary(String glossaryId)
throws DeepLException, InterruptedException {
String relativeUrl = String.format("/v3/glossaries/%s", glossaryId);
HttpResponse response = httpClientWrapper.sendGetRequestWithBackoff(relativeUrl);
checkResponse(response, false, true);
return jsonParser.parseMultilingualGlossaryInfo(response.getBody());
}
/**
* Retrieves information about all glossaries and returns an array of {@link
* MultilingualGlossaryInfo} objects containing details. This does not retrieve the glossary
* entries; to retrieve entries use {@link
* DeepLClient#getMultilingualGlossaryDictionaryEntries(String, String, String)}
*
* @return List of {@link MultilingualGlossaryInfo} objects with details about each glossary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws DeepLException If any error occurs while communicating with the DeepL API.
*/
public List<MultilingualGlossaryInfo> listMultilingualGlossaries()
throws DeepLException, InterruptedException {
HttpResponse response = httpClientWrapper.sendGetRequestWithBackoff("/v3/glossaries");
checkResponse(response, false, false);
return jsonParser.parseMultilingualGlossaryInfoList(response.getBody());
}
/**
* For the glossary with the specified ID, retrieves the glossary dictionary with its entries for
* the given source and target language code pair.
*
* @param glossaryId ID of glossary for which to retrieve entries.
* @param sourceLanguageCode Source language code for the requested glossary dictionary.
* @param targetLanguageCode Target language code of the requested glossary dictionary.
* @return {@link MultilingualGlossaryDictionaryEntries} object containing a glossary dictionary
* with entries.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws IllegalArgumentException If any argument is invalid.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
*/
public MultilingualGlossaryDictionaryEntries getMultilingualGlossaryDictionaryEntries(
String glossaryId, String sourceLanguageCode, String targetLanguageCode)
throws DeepLException, IllegalArgumentException, InterruptedException {
validateParameter("glossaryId", glossaryId);
String queryString = createLanguageQueryParams(sourceLanguageCode, targetLanguageCode);
String relativeUrl = String.format("/v3/glossaries/%s/entries%s", glossaryId, queryString);
HttpResponse response = httpClientWrapper.sendGetRequestWithBackoff(relativeUrl);
checkResponse(response, false, true);
return jsonParser
.parseMultilingualGlossaryDictionaryListResponse(response.getBody())
.getDictionaries()
.get(0)
.getDictionaryEntries();
}
/**
* For the glossary with the specified ID, retrieves the glossary dictionary with its entries for
* the given {@link MultilingualGlossaryDictionaryInfo} glossary dictionary.
*
* @param glossaryId ID of glossary for which to retrieve entries.
* @param glossaryDict The requested glossary dictionary.
* @return {@link MultilingualGlossaryDictionaryEntries} object containing a glossary dictionary
* with entries.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws IllegalArgumentException If any argument is invalid.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
*/
public MultilingualGlossaryDictionaryEntries getMultilingualGlossaryDictionaryEntries(
String glossaryId, MultilingualGlossaryDictionaryInfo glossaryDict)
throws DeepLException, IllegalArgumentException, InterruptedException {
return getMultilingualGlossaryDictionaryEntries(
glossaryId, glossaryDict.getSourceLanguageCode(), glossaryDict.getTargetLanguageCode());
}
/**
* For the specified glossary, retrieves the glossary dictionary with its entries for the given
* source and target language code pair.
*
* @param glossary The glossary for which to retrieve entries.
* @param sourceLanguageCode Source language code for the requested glossary dictionary.
* @param targetLanguageCode Target language code of the requested glossary dictionary.
* @return {@link MultilingualGlossaryDictionaryEntries} object containing a glossary dictionary
* with entries.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws IllegalArgumentException If any argument is invalid.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
*/
public MultilingualGlossaryDictionaryEntries getMultilingualGlossaryDictionaryEntries(
MultilingualGlossaryInfo glossary, String sourceLanguageCode, String targetLanguageCode)
throws DeepLException, IllegalArgumentException, InterruptedException {
return getMultilingualGlossaryDictionaryEntries(
glossary.getGlossaryId(), sourceLanguageCode, targetLanguageCode);
}
/**
* For the specified glossary, retrieves the glossary dictionary with its entries for the given
* {@link MultilingualGlossaryDictionaryInfo} glossary dictionary.
*
* @param glossary The glossary for which to retrieve entries.
* @param glossaryDict The requested glossary dictionary.
* @return {@link MultilingualGlossaryDictionaryEntries} object containing a glossary dictionary
* with entries.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws IllegalArgumentException If any argument is invalid.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
*/
public MultilingualGlossaryDictionaryEntries getMultilingualGlossaryDictionaryEntries(
MultilingualGlossaryInfo glossary, MultilingualGlossaryDictionaryInfo glossaryDict)
throws DeepLException, IllegalArgumentException, InterruptedException {
return getMultilingualGlossaryDictionaryEntries(
glossary.getGlossaryId(),
glossaryDict.getSourceLanguageCode(),
glossaryDict.getTargetLanguageCode());
}
/**
* Replaces a glossary dictionary with given entries for the source and target language codes. If
* no such glossary dictionary exists for that language pair, a new glossary dictionary will be
* created for that language pair and entries.
*
* @param glossaryId The specified ID of the glossary that contains the dictionary to be
* replaced/created
* @param sourceLanguageCode Language code of the source terms language.
* @param targetLanguageCode Language code of the target terms language.
* @param entries The source-target entry pairs in the new glossary dictionary.
* @return {@link MultilingualGlossaryDictionaryInfo} object with details about the newly replaced
* glossary dictionary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws IllegalArgumentException If any argument is invalid.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
*/
public MultilingualGlossaryDictionaryInfo replaceMultilingualGlossaryDictionary(
String glossaryId,
String sourceLanguageCode,
String targetLanguageCode,
GlossaryEntries entries)
throws DeepLException, IllegalArgumentException, InterruptedException {
return replaceGlossaryDictionaryInternal(
glossaryId, sourceLanguageCode, targetLanguageCode, entries.toTsv(), "tsv");
}
/**
* Replaces a glossary dictionary with given entries for the source and target language codes. If
* no such glossary dictionary exists for that language pair, a new glossary dictionary will be
* created for that language pair and entries.
*
* @param glossaryId The specified ID of the glossary that contains the dictionary to be
* replaced/created
* @param glossaryDict The glossary dictionary to replace the existing glossary dictionary for
* that source/target language code pair or to be newly created if no such glossary dictionary
* exists.
* @return {@link MultilingualGlossaryDictionaryInfo} object with details about the newly replaced
* glossary dictionary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws IllegalArgumentException If any argument is invalid.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
*/
public MultilingualGlossaryDictionaryInfo replaceMultilingualGlossaryDictionary(
String glossaryId, MultilingualGlossaryDictionaryEntries glossaryDict)
throws DeepLException, IllegalArgumentException, InterruptedException {
return replaceGlossaryDictionaryInternal(
glossaryId,
glossaryDict.getSourceLanguageCode(),
glossaryDict.getTargetLanguageCode(),
glossaryDict.getEntries().toTsv(),
"tsv");
}
/**
* Replaces a glossary dictionary with given entries for given glossary dictionary. If no such
* glossary dictionary exists for that language pair, a new glossary dictionary will be created
* for that language pair and entries.
*
* @param glossary The specified glossary that contains the dictionary to be replaced/created
* @param glossaryDict The glossary dictionary to replace the existing glossary dictionary for
* that source/target language code pair or to be newly created if no such glossary dictionary
* exists.
* @return {@link MultilingualGlossaryDictionaryInfo} object with details about the newly replaced
* glossary dictionary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws IllegalArgumentException If any argument is invalid.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
*/
public MultilingualGlossaryDictionaryInfo replaceMultilingualGlossaryDictionary(
MultilingualGlossaryInfo glossary, MultilingualGlossaryDictionaryEntries glossaryDict)
throws DeepLException, IllegalArgumentException, InterruptedException {
return replaceGlossaryDictionaryInternal(
glossary.getGlossaryId(),
glossaryDict.getSourceLanguageCode(),
glossaryDict.getTargetLanguageCode(),
glossaryDict.getEntries().toTsv(),
"tsv");
}
/**
* Replaces a glossary dictionary with given entries for the source and target language codes. If
* no such glossary dictionary exists for that language pair, a new glossary dictionary will be
* created for that language pair and entries.
*
* @param glossary The specified glossary that contains the dictionary to be replaced/created
* @param sourceLanguageCode Language code of the source terms language.
* @param targetLanguageCode Language code of the target terms language.
* @param entries The source-target entry pairs in the new glossary dictionary.
* @return {@link MultilingualGlossaryDictionaryInfo} object with details about the newly replaced
* glossary dictionary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws IllegalArgumentException If any argument is invalid.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
*/
public MultilingualGlossaryDictionaryInfo replaceMultilingualGlossaryDictionary(
MultilingualGlossaryInfo glossary,
String sourceLanguageCode,
String targetLanguageCode,
GlossaryEntries entries)
throws DeepLException, IllegalArgumentException, InterruptedException {
return replaceGlossaryDictionaryInternal(
glossary.getGlossaryId(), sourceLanguageCode, targetLanguageCode, entries.toTsv(), "tsv");
}
/**
* Replaces a glossary dictionary with given entries for the source and target language codes. If
* no such glossary dictionary exists for that language pair, a new glossary dictionary will be
* created for that language pair and entries specified in the {@code csvFile}.
*
* @param glossaryId The specified Id of the glossary that contains the dictionary to be
* replaced/created
* @param sourceLanguageCode Language code of the source terms language.
* @param targetLanguageCode Language code of the target terms language.
* @param csvFile File containing CSV content.
* @return {@link MultilingualGlossaryDictionaryInfo} object with details about the newly replaced
* glossary dictionary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws IllegalArgumentException If any argument is invalid.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
* @throws IOException If an I/O error occurs.
*/
public MultilingualGlossaryDictionaryInfo replaceMultilingualGlossaryDictionaryFromCsv(
String glossaryId, String sourceLanguageCode, String targetLanguageCode, File csvFile)
throws DeepLException, IllegalArgumentException, InterruptedException, IOException {
try (FileInputStream stream = new FileInputStream(csvFile)) {
String csvContent = StreamUtil.readStream(stream);
return replaceGlossaryDictionaryInternal(
glossaryId, sourceLanguageCode, targetLanguageCode, csvContent, "csv");
}
}
/**
* Replaces a glossary dictionary with given entries for the source and target language codes. If
* no such glossary dictionary exists for that language pair, a new glossary dictionary will be
* created for that language pair and entries specified in the {@code csvContent}.
*
* @param glossaryId The specified ID of the glossary that contains the dictionary to be
* replaced/created
* @param sourceLanguageCode Language code of the source terms language.
* @param targetLanguageCode Language code of the target terms language.
* @param csvContent String containing CSV content.
* @return {@link MultilingualGlossaryDictionaryInfo} object with details about the newly replaced
* glossary dictionary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws IllegalArgumentException If any argument is invalid.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
*/
public MultilingualGlossaryDictionaryInfo replaceMultilingualGlossaryDictionaryFromCsv(
String glossaryId, String sourceLanguageCode, String targetLanguageCode, String csvContent)
throws DeepLException, IllegalArgumentException, InterruptedException {
return replaceGlossaryDictionaryInternal(
glossaryId, sourceLanguageCode, targetLanguageCode, csvContent, "csv");
}
/**
* Updates a glossary dictionary with given entries for the source and target language codes. The
* glossary dictionary must belong to the glossary with the ID specified in <paramref
* name="glossaryId" />. If a dictionary for the provided language pair already exists, the
* dictionary entries are merged.
*
* @param glossaryId The specified ID of the glossary that contains the dictionary to be
* updated/created
* @param sourceLanguageCode Language code of the source terms language.
* @param targetLanguageCode Language code of the target terms language.
* @param entries The source-target entry pairs in the new glossary dictionary.
* @return {@link MultilingualGlossaryInfo} object with details about the glossary with the newly
* updated glossary dictionary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws IllegalArgumentException If any argument is invalid.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
*/
public MultilingualGlossaryInfo updateMultilingualGlossaryDictionary(
String glossaryId,
String sourceLanguageCode,
String targetLanguageCode,
GlossaryEntries entries)
throws DeepLException, IllegalArgumentException, InterruptedException {
return updateGlossaryDictionaryInternal(
glossaryId, sourceLanguageCode, targetLanguageCode, entries.toTsv(), "tsv");
}
/**
* Updates a glossary dictionary with given entries for the source and target language codes. The
* glossary dictionary must belong to the glossary specified in <paramref name="glossary" />. If a
* dictionary for the provided language pair already exists, the dictionary entries are merged.
*
* @param glossary The specified ID for the glossary that contains the dictionary to be
* updated/created
* @param sourceLanguageCode Language code of the source terms language.
* @param targetLanguageCode Language code of the target terms language.
* @param entries The source-target entry pairs in the new glossary dictionary.
* @return {@link MultilingualGlossaryInfo} object with details about the glossary with the newly
* updated glossary dictionary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws IllegalArgumentException If any argument is invalid.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
*/
public MultilingualGlossaryInfo updateMultilingualGlossaryDictionary(
MultilingualGlossaryInfo glossary,
String sourceLanguageCode,
String targetLanguageCode,
GlossaryEntries entries)
throws DeepLException, IllegalArgumentException, InterruptedException {
return updateGlossaryDictionaryInternal(
glossary.getGlossaryId(), sourceLanguageCode, targetLanguageCode, entries.toTsv(), "tsv");
}
/**
* Updates a glossary dictionary with given glossary dictionary specified in <paramref
* name="glossaryDict" />. The glossary dictionary must belong to the glossary with the ID
* specified in <paramref name="glossaryId" />. If a dictionary for the provided language pair
* already exists, the dictionary entries are merged.
*
* @param glossaryId The specified ID of the glossary that contains the dictionary to be
* updated/created
* @param glossaryDict The glossary dictionary to be created/updated
* @return {@link MultilingualGlossaryInfo} object with details about the glossary with the newly
* updated glossary dictionary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws IllegalArgumentException If any argument is invalid.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
*/
public MultilingualGlossaryInfo updateMultilingualGlossaryDictionary(
String glossaryId, MultilingualGlossaryDictionaryEntries glossaryDict)
throws DeepLException, IllegalArgumentException, InterruptedException {
return updateGlossaryDictionaryInternal(
glossaryId,
glossaryDict.getSourceLanguageCode(),
glossaryDict.getTargetLanguageCode(),
glossaryDict.getEntries().toTsv(),
"tsv");
}
/**
* Updates a glossary dictionary with given entries for the source and target language codes. If a
* dictionary for the provided language pair already exists, the dictionary entries are merged.
*
* @param glossary The specified glossary that contains the dictionary to be updated/created
* @param glossaryDict The glossary dictionary to be created/updated
* @return {@link MultilingualGlossaryInfo} object with details about the glossary with the newly
* updated glossary dictionary.
* @throws InterruptedException If the thread is interrupted during execution of this function.
* @throws IllegalArgumentException If any argument is invalid.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
*/
public MultilingualGlossaryInfo updateMultilingualGlossaryDictionary(
MultilingualGlossaryInfo glossary, MultilingualGlossaryDictionaryEntries glossaryDict)
throws DeepLException, IllegalArgumentException, InterruptedException {
return updateGlossaryDictionaryInternal(
glossary.getGlossaryId(),
glossaryDict.getSourceLanguageCode(),
glossaryDict.getTargetLanguageCode(),
glossaryDict.getEntries().toTsv(),
"tsv");
}
/**
* Updates a glossary's name with the provided parameter
*
* @param glossaryId The specified ID of the glossary whose name will be updated
* @param name The new name of the glossary
* @return {@link MultilingualGlossaryInfo} object with details about the glossary with the newly
* updated glossary dictionary.
* @throws IllegalArgumentException If any argument is invalid.
* @throws DeepLException If any error occurs while communicating with the DeepL API, a {@link
* DeepLException} or a derived class will be thrown.
*/
public MultilingualGlossaryInfo updateMultilingualGlossaryName(String glossaryId, String name)
throws DeepLException, IllegalArgumentException {
ArrayList<KeyValuePair<String, String>> bodyParams = new ArrayList<>();
bodyParams.add(new KeyValuePair<>("name", name));
String relativeUrl = String.format("/v3/glossaries/%s", glossaryId);
HttpResponse response = httpClientWrapper.sendPatchRequestWithBackoff(relativeUrl, bodyParams);
checkResponse(response, false, true);
return jsonParser.parseMultilingualGlossaryInfo(response.getBody());
}
/**
* Updates a glossary dictionary correlating to the specified ID with given entries in the {@code
* csvFile} for the source and target language codes. If a dictionary for the provided language
* pair already exists, the dictionary entries are merged.
*
* @param glossaryId The specified ID of the glossary that contains the dictionary to be
* updated/created
* @param sourceLanguageCode Language code of the source terms language.
* @param targetLanguageCode Language code of the target terms language.
* @param csvFile {@link File} containing CSV content.
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | true |
DeepLcom/deepl-java | https://github.com/DeepLcom/deepl-java/blob/e91115a0cee340d8770210352bc08144dce1fbe8/deepl-java/src/main/java/com/deepl/api/QuotaExceededException.java | deepl-java/src/main/java/com/deepl/api/QuotaExceededException.java | // Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
package com.deepl.api;
/** Exception thrown when the DeepL translation quota has been reached. */
public class QuotaExceededException extends DeepLException {
public QuotaExceededException(String message) {
super(message);
}
}
| java | MIT | e91115a0cee340d8770210352bc08144dce1fbe8 | 2026-01-05T02:40:38.272108Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.