id
int64
file_name
string
file_path
string
content
string
size
int64
language
string
extension
string
total_lines
int64
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
repo_name
string
repo_stars
int64
repo_forks
int64
repo_open_issues
int64
repo_license
string
repo_extraction_date
string
exact_duplicates_redpajama
bool
near_duplicates_redpajama
bool
exact_duplicates_githubcode
bool
exact_duplicates_stackv2
bool
exact_duplicates_stackv1
bool
near_duplicates_githubcode
bool
near_duplicates_stackv1
bool
near_duplicates_stackv2
bool
length
int64
4,954,878
GlCameraHandle.java
chongtianfeiyu_Simim/Simim/src/com/neuo/glshader/GlCameraHandle.java
package com.neuo.glshader; public interface GlCameraHandle { public float[] getCamera(); }
93
Java
.java
4
21.75
33
0.806818
chongtianfeiyu/Simim
1
0
0
GPL-2.0
9/5/2024, 12:37:05 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
93
3,708,416
pitchoffsetControlPanel.java
yann-ygn_fv1-spincad/SpinCAD-Designer/src-gen/com/holycityaudio/SpinCAD/ControlPanel/pitchoffsetControlPanel.java
/* SpinCAD Designer - DSP Development Tool for the Spin FV-1 * pitchoffsetControlPanel.java * Copyright (C) 2015 - Gary Worsham * Based on ElmGen by Andrew Kilpatrick * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.holycityaudio.SpinCAD.ControlPanel; import org.andrewkilpatrick.elmGen.ElmProgram; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.event.ActionEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.awt.event.ItemEvent; import javax.swing.BoxLayout; import javax.swing.JSlider; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.JLabel; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.Box; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.BorderFactory; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import java.awt.Dimension; import java.text.DecimalFormat; import com.holycityaudio.SpinCAD.SpinCADBlock; import com.holycityaudio.SpinCAD.spinCADControlPanel; import com.holycityaudio.SpinCAD.CADBlocks.pitchoffsetCADBlock; @SuppressWarnings("unused") public class pitchoffsetControlPanel extends spinCADControlPanel { private JFrame frame; private pitchoffsetCADBlock gCB; // declare the controls public pitchoffsetControlPanel(pitchoffsetCADBlock genericCADBlock) { gCB = genericCADBlock; SwingUtilities.invokeLater(new Runnable() { public void run() { frame = new JFrame(); frame.setTitle("PitchOffset"); frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS)); frame.addWindowListener(new MyWindowListener()); frame.pack(); frame.setResizable(false); frame.setLocation(gCB.getX() + 100, gCB.getY() + 100); frame.setAlwaysOnTop(true); frame.setVisible(true); } }); } // add change listener for Sliders, Spinners class pitchoffsetListener implements ChangeListener { public void stateChanged(ChangeEvent ce) { } } // add item state changed listener for Checkbox class pitchoffsetItemListener implements java.awt.event.ItemListener { @Override public void itemStateChanged(ItemEvent arg0) { } } // add action listener for Combo Box class pitchoffsetActionListener implements java.awt.event.ActionListener { @Override public void actionPerformed(ActionEvent arg0) { } } class MyWindowListener implements WindowListener { @Override public void windowActivated(WindowEvent arg0) { } @Override public void windowClosed(WindowEvent arg0) { } @Override public void windowClosing(WindowEvent arg0) { gCB.clearCP(); } @Override public void windowDeactivated(WindowEvent arg0) { } @Override public void windowDeiconified(WindowEvent arg0) { } @Override public void windowIconified(WindowEvent arg0) { } @Override public void windowOpened(WindowEvent arg0) { } } }
3,718
Java
.java
111
30.387387
77
0.779083
yann-ygn/fv1-spincad
3
1
0
GPL-3.0
9/4/2024, 11:39:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,718
3,287,085
TodoActivity.java
gamemaker1_Babble/app/src/main/java/com/vedantinfinity/babble/TodoActivity.java
package com.vedantinfinity.babble; /* Copyright (C) 2019 Vedant K This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/. */ import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.InputFilter; import android.text.format.DateFormat; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.NotificationCompat; import com.firebase.ui.auth.AuthUI; import com.firebase.ui.database.FirebaseListAdapter; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.FirebaseApp; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.EmailAuthProvider; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.UUID; public class TodoActivity extends AppCompatActivity { private ListView listOfTodos; private FirebaseListAdapter<TodoItem> adapter; private ArrayList<String> bubbleInfo; private UserItem user; private int notificationId = 1228; private static final int SIGN_IN_REQUEST_CODE = 2812; private static final int todoLength = 140; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_todo); listOfTodos = findViewById(R.id.list_of_todos); displayTodos(); FirebaseApp.getInstance(); new FirebaseHandler(); FirebaseDatabase.getInstance().getReference().keepSynced(true); final Intent intentAction = getIntent(); String action = intentAction.getAction(); String type = intentAction.getType(); if (Intent.ACTION_SEND.equals(action) && type != null) { if ("text/plain".equals(type)) { receivedSharedTextHandler(intentAction); // Handle text being sent } } else if (Intent.EXTRA_KEY_EVENT.equals(action) && type.equals("text/plain")) { if (FirebaseAuth.getInstance().getCurrentUser() == null) { // Start sign in/sign up activity List<AuthUI.IdpConfig> providers = Arrays.asList( new AuthUI.IdpConfig.EmailBuilder().build()); // Create and launch sign-in intent startActivityForResult( AuthUI.getInstance() .createSignInIntentBuilder() .setAvailableProviders(providers) .setLogo(R.drawable.chat) .setTheme(R.style.AppTheme) .setTosAndPrivacyPolicyUrls("https://github.com/gamemaker1/Babble/blob/master/termsofservice.md", "https://github.com/gamemaker1/Babble/blob/master/privacy.md") .build(), SIGN_IN_REQUEST_CODE); } else { // User is already signed in. Intent intent = getIntent(); bubbleInfo = intent.getStringArrayListExtra("bubbleInfo"); setTitle(bubbleInfo.get(0) + " - Tasks"); final String uid = FirebaseAuth.getInstance().getCurrentUser().getUid(); final String email = FirebaseAuth.getInstance().getCurrentUser().getEmail(); final String displayName = FirebaseAuth.getInstance().getCurrentUser().getDisplayName(); final ArrayList<String> groupArray = new ArrayList<>(); final Query groupToDisplay = FirebaseDatabase.getInstance() .getReference().child("groups") .orderByChild("peopleInGroup"); groupToDisplay.addListenerForSingleValueEvent(new ValueEventListener() { @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot group : dataSnapshot.getChildren()) { Log.w("GroupsActivity", "bello listed - " + group); if (Objects.requireNonNull(group.getValue(GroupItem.class)).getPeopleInGroup().contains(FirebaseAuth.getInstance().getCurrentUser().getEmail())) { groupArray.add(Objects.requireNonNull(group.getValue(GroupItem.class)).getGroupTitle()); Log.w("GroupsActivity", "bello added - " + group); } } Log.w("GroupsActivity", "TEST TEST TEST 11 - " + groupArray); user = new UserItem(displayName, email, uid, groupArray); Log.w("GroupsActivity", "TEST TEST TEST 33 - " + user); final Query userToAdd = FirebaseDatabase.getInstance() .getReference().child("users") .orderByChild("uid") .equalTo(user.getUid()); userToAdd.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { for (DataSnapshot itemToUpdateSnapshot : dataSnapshot.getChildren()) { itemToUpdateSnapshot.getValue(UserItem.class) .setUserDisplayName(user.getUserDisplayName()); itemToUpdateSnapshot.getValue(UserItem.class) .setUserEmailAddress(user.getUserEmailAddress()); itemToUpdateSnapshot.getValue(UserItem.class) .setUserGroups(user.getUserGroups()); } } else { FirebaseDatabase.getInstance().getReference() .child("users") .push().setValue(user); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.e("ItemDetail", "onCancelled", databaseError.toException()); } }); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.e("ItemDetail", "onCancelled", databaseError.toException()); } }); // Load todos displayTodos(); } final Button addTaskButton = findViewById(R.id.add_task_button); addTaskButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = getIntent(); bubbleInfo = intent.getStringArrayListExtra("bubbleInfo"); Log.w("TodoActivity", "Bello 2 - " + bubbleInfo); final EditText addTaskEditText = findViewById(R.id.add_task_box); addTaskEditText.setText(intentAction.getStringExtra("textToShare")); addTaskEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(todoLength)}); final long todoId = UUID.randomUUID().getLeastSignificantBits(); if (addTaskEditText.getText().toString().trim().length() > 0) { Log.w("TodoActivity", "Bello - " + bubbleInfo); if (bubbleInfo != null) { final Query messageToSend = FirebaseDatabase.getInstance() .getReference().child("groups") .orderByChild("groupId") .equalTo(Long.parseLong(bubbleInfo.get(1))); messageToSend.addListenerForSingleValueEvent(new ValueEventListener() { @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot childHeaders : dataSnapshot.getChildren()) { FirebaseDatabase.getInstance() .getReference().child("groups").child(Objects.requireNonNull(childHeaders.getKey())).child("messages") .push() .setValue(new ChatMessage("I have added the " + "task " + addTaskEditText.getText().toString() + " !", FirebaseAuth.getInstance() .getCurrentUser() .getDisplayName(), null) ); FirebaseDatabase.getInstance() .getReference().child("messages") .push() .setValue(new UserMessage("I have added the " + "task " + addTaskEditText.getText().toString() + " !", FirebaseAuth.getInstance() .getCurrentUser() .getDisplayName(), null, bubbleInfo.get(0), Long.valueOf(bubbleInfo.get(1)), new Date().getTime(), false) ); FirebaseDatabase.getInstance() .getReference().child("groups").child(Objects.requireNonNull(childHeaders.getKey())).child("todos") .push() .setValue(new TodoItem(addTaskEditText.getText().toString(), null, todoId) ); FirebaseDatabase.getInstance() .getReference().child("groups").child(Objects.requireNonNull(childHeaders.getKey())).child("messages") .push() .setValue(new ChatMessage("I have added the " + "task " + addTaskEditText.getText().toString() + " !", FirebaseAuth.getInstance() .getCurrentUser() .getDisplayName(), null) ); // Clear the addTaskEditText addTaskEditText.setText(""); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.e("ItemDetail", "onCancelled", databaseError.toException()); } }); } else { // Do nothing } } else { // Do nothing } } }); listOfTodos.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String itemTitle = adapter.getItem(position).getTodoTitle(); String itemClaimedBy = adapter.getItem(position).getClaimedBy(); long itemInitTime = adapter.getItem(position).getTodoInitTime(); Log.w("OnClickItemInList ", "Claimed By " + itemClaimedBy); Intent intent2 = getIntent(); bubbleInfo = intent2.getStringArrayListExtra("bubbleInfo"); ArrayList<String> todoItemInfo = new ArrayList<>(); todoItemInfo.add(itemTitle); todoItemInfo.add(itemClaimedBy); todoItemInfo.add(String.valueOf(itemInitTime)); todoItemInfo.add(String.valueOf(adapter.getItem(position).getTodoItemId())); Log.w("TodoActivity", "Bello - " + bubbleInfo); todoItemInfo.add(String.valueOf(bubbleInfo.get(0))); todoItemInfo.add(String.valueOf(bubbleInfo.get(1))); Intent intent = new Intent(TodoActivity.this, ItemDetail.class); intent.putStringArrayListExtra("todoItemInfo", todoItemInfo); intent.putStringArrayListExtra("bubbleInfo", bubbleInfo); startActivity(intent); } }); } else { if (FirebaseAuth.getInstance().getCurrentUser() == null) { // Start sign in/sign up activity List<AuthUI.IdpConfig> providers = Arrays.asList( new AuthUI.IdpConfig.EmailBuilder().build()); // Create and launch sign-in intent startActivityForResult( AuthUI.getInstance() .createSignInIntentBuilder() .setAvailableProviders(providers) .setLogo(R.drawable.chat) .setTheme(R.style.AppTheme) .build(), SIGN_IN_REQUEST_CODE); } else { // User is already signed in. Intent intent = getIntent(); bubbleInfo = intent.getStringArrayListExtra("bubbleInfo"); setTitle(bubbleInfo.get(0) + " - Tasks"); final String uid = FirebaseAuth.getInstance().getCurrentUser().getUid(); final String email = FirebaseAuth.getInstance().getCurrentUser().getEmail(); final String displayName = FirebaseAuth.getInstance().getCurrentUser().getDisplayName(); final ArrayList<String> groupArray = new ArrayList<>(); final Query groupToDisplay = FirebaseDatabase.getInstance() .getReference().child("groups") .orderByChild("peopleInGroup"); groupToDisplay.addListenerForSingleValueEvent(new ValueEventListener() { @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot group : dataSnapshot.getChildren()) { Log.w("GroupsActivity", "bello listed - " + group); if (Objects.requireNonNull(group.getValue(GroupItem.class)).getPeopleInGroup().contains(FirebaseAuth.getInstance().getCurrentUser().getEmail())) { groupArray.add(Objects.requireNonNull(group.getValue(GroupItem.class)).getGroupTitle()); Log.w("GroupsActivity", "bello added - " + group); } } Log.w("GroupsActivity", "TEST TEST TEST 11 - " + groupArray); user = new UserItem(displayName, email, uid, groupArray); Log.w("GroupsActivity", "TEST TEST TEST 33 - " + user); final Query userToAdd = FirebaseDatabase.getInstance() .getReference().child("users") .orderByChild("uid") .equalTo(user.getUid()); userToAdd.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { for (DataSnapshot itemToUpdateSnapshot : dataSnapshot.getChildren()) { itemToUpdateSnapshot.getValue(UserItem.class) .setUserDisplayName(user.getUserDisplayName()); itemToUpdateSnapshot.getValue(UserItem.class) .setUserEmailAddress(user.getUserEmailAddress()); itemToUpdateSnapshot.getValue(UserItem.class) .setUserGroups(user.getUserGroups()); } } else { FirebaseDatabase.getInstance().getReference() .child("users") .push().setValue(user); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.e("ItemDetail", "onCancelled", databaseError.toException()); } }); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.e("ItemDetail", "onCancelled", databaseError.toException()); } }); // Load todos displayTodos(); } final Button addTaskButton = findViewById(R.id.add_task_button); addTaskButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = getIntent(); bubbleInfo = intent.getStringArrayListExtra("bubbleInfo"); Log.w("TodoActivity", "Bello 2 - " + bubbleInfo); final EditText addTaskEditText = findViewById(R.id.add_task_box); addTaskEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(todoLength)}); final long todoId = UUID.randomUUID().getLeastSignificantBits(); if (addTaskEditText.getText().toString().trim().length() > 0) { Log.w("TodoActivity", "Bello - " + bubbleInfo); if (bubbleInfo != null) { final Query messageToSend = FirebaseDatabase.getInstance() .getReference().child("groups") .orderByChild("groupId") .equalTo(Long.parseLong(bubbleInfo.get(1))); messageToSend.addListenerForSingleValueEvent(new ValueEventListener() { @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot childHeaders : dataSnapshot.getChildren()) { FirebaseDatabase.getInstance() .getReference().child("groups").child(Objects.requireNonNull(childHeaders.getKey())).child("messages") .push() .setValue(new ChatMessage("I have added the " + "task " + addTaskEditText.getText().toString() + " !", FirebaseAuth.getInstance() .getCurrentUser() .getDisplayName(), null) ); FirebaseDatabase.getInstance() .getReference().child("messages") .push() .setValue(new UserMessage("I have added the " + "task " + addTaskEditText.getText().toString() + " !", FirebaseAuth.getInstance() .getCurrentUser() .getDisplayName(), null, bubbleInfo.get(0), Long.valueOf(bubbleInfo.get(1)), new Date().getTime(), false) ); FirebaseDatabase.getInstance() .getReference().child("groups").child(Objects.requireNonNull(childHeaders.getKey())).child("todos") .push() .setValue(new TodoItem(addTaskEditText.getText().toString(), null, todoId) ); // Clear the addTaskEditText addTaskEditText.setText(""); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.e("ItemDetail", "onCancelled", databaseError.toException()); } }); } else { // Do nothing } } else { // Do nothing } } }); listOfTodos.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String itemTitle = adapter.getItem(position).getTodoTitle(); String itemClaimedBy = adapter.getItem(position).getClaimedBy(); long itemInitTime = adapter.getItem(position).getTodoInitTime(); Log.w("OnClickItemInList ", "Claimed By " + itemClaimedBy); Intent intent2 = getIntent(); bubbleInfo = intent2.getStringArrayListExtra("bubbleInfo"); ArrayList<String> todoItemInfo = new ArrayList<>(); todoItemInfo.add(itemTitle); todoItemInfo.add(itemClaimedBy); todoItemInfo.add(String.valueOf(itemInitTime)); todoItemInfo.add(String.valueOf(adapter.getItem(position).getTodoItemId())); Log.w("TodoActivity", "Bello - " + bubbleInfo); todoItemInfo.add(String.valueOf(bubbleInfo.get(0))); todoItemInfo.add(String.valueOf(bubbleInfo.get(1))); Intent intent = new Intent(TodoActivity.this, ItemDetail.class); intent.putStringArrayListExtra("todoItemInfo", todoItemInfo); intent.putStringArrayListExtra("bubbleInfo", bubbleInfo); startActivity(intent); } }); } } private void displayTodos() { final ListView listOfTodos = findViewById(R.id.list_of_todos); Intent intent = getIntent(); final ArrayList<String> bubbleInfo = intent.getStringArrayListExtra("bubbleInfo"); Log.w("TodoActivity", "Bello - " + bubbleInfo); if (bubbleInfo != null) { final Query messageToSend = FirebaseDatabase.getInstance() .getReference().child("groups") .orderByChild("groupId") .equalTo(Long.parseLong(bubbleInfo.get(1))); messageToSend.addListenerForSingleValueEvent(new ValueEventListener() { @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot childHeaders : dataSnapshot.getChildren()) { adapter = new FirebaseListAdapter<TodoItem>(TodoActivity.this, TodoItem.class, R.layout.todo_list_item, FirebaseDatabase.getInstance() .getReference().child("groups").child(Objects.requireNonNull(childHeaders.getKey())).child("todos")) { @Override protected void populateView(View v, TodoItem model, int position) { TextView taskClaimedByTextView = v.findViewById(R.id.task_claimed_by); TextView taskTitleTextView = v.findViewById(R.id.task_title); TextView taskTimeTextView = v.findViewById(R.id.task_time_set); // Set the data for all tasks taskClaimedByTextView.setText(model.getClaimedBy()); taskTitleTextView.setText(model.getTodoTitle()); taskTimeTextView.setText(DateFormat.format("dd-MM-yyyy @ HH:mm", model.getTodoInitTime())); } }; listOfTodos.setAdapter(adapter); listOfTodos.smoothScrollToPosition(adapter.getCount() - 1); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.e("ItemDetail", "onCancelled", databaseError.toException()); } }); } else { // Do nothing } } private void receivedSharedTextHandler(Intent intentAction) { String sharedText = intentAction.getStringExtra(Intent.EXTRA_TEXT); if (sharedText != null) { // Update UI to reflect text being shared Intent intent = new Intent(TodoActivity.this, SharedTextHandler.class); intent.putExtra("textToShare", sharedText); startActivity(intent); } } private void SendNotificationForMessage(String messageBody, String messageUser) { notificationId += 1; Intent intent = new Intent(this, ChatActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); String channelId = getString(R.string.default_notification_channel_id); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId) .setSmallIcon(R.drawable.chat) .setContentTitle("Message Received From " + messageUser) .setContentText(messageBody) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Since android Oreo notification channel is needed. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(channelId, "Babbling Bubble", NotificationManager.IMPORTANCE_DEFAULT); notificationManager.createNotificationChannel(channel); } notificationManager.notify(notificationId, notificationBuilder.build()); } private void SendNotificationForPhoto(String messageUser) { notificationId += 1; Intent intent = new Intent(this, ChatActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); String channelId = getString(R.string.default_notification_channel_id); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId) .setSmallIcon(R.drawable.chat) .setContentTitle("Photo Received From " + messageUser) .setContentText("Photo") .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Since android Oreo notification channel is needed. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(channelId, "Babbling Bubble", NotificationManager.IMPORTANCE_DEFAULT); notificationManager.createNotificationChannel(channel); } notificationManager.notify(notificationId, notificationBuilder.build()); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == SIGN_IN_REQUEST_CODE) { if(resultCode == RESULT_OK) { Toast.makeText(this, "You're successfully signed in. Welcome! :)", Toast.LENGTH_LONG) .show(); displayTodos(); } else { Toast.makeText(this, "Sorry, we couldn't sign you in. Please try again later. :(", Toast.LENGTH_LONG) .show(); // Close the app finish(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.group_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.menu_sign_out) { AuthUI.getInstance() .signOut(this) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull com.google.android.gms.tasks.Task<Void> task) { Toast.makeText(TodoActivity.this, "You have been signed out. Come back soon!", Toast.LENGTH_LONG) .show(); // Close activity List<AuthUI.IdpConfig> providers = Arrays.asList( new AuthUI.IdpConfig.EmailBuilder().build()); // Create and launch sign-in intent startActivityForResult( AuthUI.getInstance() .createSignInIntentBuilder() .setAvailableProviders(providers) .build(), SIGN_IN_REQUEST_CODE); } }); } else if (item.getItemId() == R.id.menu_delete_account) { final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { //You need to get here the token you saved at logging-in time. String token = "userSavedToken"; //You need to get here the password you saved at logging-in time. String password = "userSavedPassword"; AuthCredential credential; //This means you didn't have the token because user used like Facebook Sign-in method. if (token == null) { credential = EmailAuthProvider.getCredential(user.getEmail(), password); } else { //Doesn't matter if it was Facebook Sign-in or others. It will always work using GoogleAuthProvider for whatever the provider. credential = GoogleAuthProvider.getCredential(token, null); } user.reauthenticate(credential) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull com.google.android.gms.tasks.Task<Void> task) { //Calling delete to remove the user and wait for a result. final Query userNodeToRemove = FirebaseDatabase.getInstance() .getReference().child("users") .orderByChild("userEmailAddress") .equalTo(FirebaseAuth.getInstance().getCurrentUser().getEmail()); userNodeToRemove.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot nodeToRemove : dataSnapshot.getChildren()) { Log.w("GroupsActivity", "Removed Node - " + nodeToRemove); nodeToRemove.getRef().removeValue(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.e("ItemDetail", "onCancelled", databaseError.toException()); } }); // Finally deleting the user from FirebaseAuth AuthUI.getInstance() .delete(TodoActivity.this) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(TodoActivity.this, "Your account has been deleted successfully. " + "Please come back with a new account!! :(", Toast.LENGTH_LONG) .show(); // Close activity finish(); } else { task.getException(); } } }); } }); } } else if (item.getItemId() == R.id.menu_add_member) { Intent intent2 = getIntent(); final ArrayList<String> bubbleInfo = intent2.getStringArrayListExtra("bubbleInfo"); Intent intent = new Intent(TodoActivity.this, AddFriend.class); intent.putStringArrayListExtra("bubbleInfo", bubbleInfo); startActivity(intent); } else if (item.getItemId() == R.id.legal) { Intent intent = new Intent(TodoActivity.this, LegalActivity.class); startActivity(intent); } else if (item.getItemId() == R.id.menu_group_info) { Intent intentToReceive = getIntent(); ArrayList<String> bubbleInfo = new ArrayList<>(intentToReceive.getStringArrayListExtra("bubbleInfo")); Intent intent = new Intent(TodoActivity.this, GroupInfoActivity.class); intent.putStringArrayListExtra("bubbleInfo", bubbleInfo); startActivity(intent); /*} else if (item.getItemId() == R.id.menu_delete_group) { Intent intent2 = getIntent(); final ArrayList<String> bubbleInfo = intent2.getStringArrayListExtra("bubbleInfo"); final Query userToRemoveFromGroup = FirebaseDatabase.getInstance() .getReference().child("groups") .orderByChild("groupId") .equalTo(bubbleInfo.get(1)); userToRemoveFromGroup.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot emailToRemove : dataSnapshot.getChildren()) { ArrayList<String> groupInfoArray = new ArrayList<>(emailToRemove.getValue(GroupItem.class).getPeopleInGroup()); groupInfoArray.remove(FirebaseAuth.getInstance().getCurrentUser().getEmail()); emailToRemove.getValue(GroupItem.class).setPeopleInGroup(groupInfoArray); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.e("ItemDetail", "onCancelled", databaseError.toException()); } }); final Query groupToRemoveFromUser = FirebaseDatabase.getInstance() .getReference().child("users") .orderByChild("userGroups") .equalTo(bubbleInfo.get(0)); groupToRemoveFromUser.addValueEventListener(new ValueEventListener() { @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot emailToRemove : dataSnapshot.getChildren()) { Toast.makeText(TodoActivity.this, "Yay!" + emailToRemove, Toast.LENGTH_SHORT).show(); ArrayList<String> userGroupsArray = new ArrayList<>(emailToRemove.getValue(UserItem.class).getUserGroups()); userGroupsArray.remove(Objects.requireNonNull(bubbleInfo.get(0))); emailToRemove.getValue(UserItem.class).setUserGroups(userGroupsArray); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.e("ItemDetail", "onCancelled", databaseError.toException()); } }); Intent intent = new Intent(TodoActivity.this, GroupsActivity.class); startActivity(intent); */ } else if (item.getItemId() == android.R.id.home) { Intent backIntent = new Intent(TodoActivity.this, ChatActivity.class); backIntent.putStringArrayListExtra("bubbleInfo", bubbleInfo); startActivity(backIntent); } return true; } }
43,698
Java
.java
709
37.375176
239
0.499556
gamemaker1/Babble
4
0
6
GPL-3.0
9/4/2024, 11:10:15 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
43,698
3,200,052
UiElementSelector.java
MusalaSoft_atmosphere-commons/src/main/java/com/musala/atmosphere/commons/ui/selector/UiElementSelector.java
// This file is part of the ATMOSPHERE mobile testing framework. // Copyright (C) 2016 MusalaSoft // // ATMOSPHERE is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ATMOSPHERE is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ATMOSPHERE. If not, see <http://www.gnu.org/licenses/>. package com.musala.atmosphere.commons.ui.selector; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.log4j.Logger; import com.musala.atmosphere.commons.geometry.Bounds; import com.musala.atmosphere.commons.ui.UiElementPropertiesContainer; import com.musala.atmosphere.commons.ui.selector.attribute.SelectionAttribute; import com.musala.atmosphere.commons.util.Pair; /** * Selector class for screen UI elements, used to search for a specific element with given attributes. * * @author georgi.gaydarov * */ public class UiElementSelector implements UiElementPropertiesContainer { private static final long serialVersionUID = 8818379696986115875L; private static final Logger LOGGER = Logger.getLogger(UiElementSelector.class); private Map<CssAttribute, Pair<Object, UiElementSelectionOption>> attributeProjectionMap; public UiElementSelector() { this.attributeProjectionMap = new HashMap<CssAttribute, Pair<Object, UiElementSelectionOption>>(); } /** * Initializes a UiElementSelector with the specified selection attribute. * * @param attribute * - the attribute to add a selection expression for * @param attributeValue * - the value to be used in the selection expression */ public UiElementSelector(CssAttribute attribute, Object attributeValue) { this(); addSelectionAttribute(attribute, attributeValue); } /** * Initializes a UiElementSelector with the specified selection attribute. * * @param attribute * - the attribute to add a selection expression for * @param selectionOption * - the selection option. One of the {@link UiElementSelectionOption}. * @param attributeValue * - the value to be used in the selection expression */ public UiElementSelector(CssAttribute attribute, UiElementSelectionOption selectionOption, Object attributeValue) { this(); addSelectionAttribute(attribute, selectionOption, attributeValue); } /** * Initializes a UiElementSelector with the specified selection attributes. * * @param selectionAttributes * - the selection attributes which should be added to the UiElementSelector */ public UiElementSelector(SelectionAttribute... selectionAttributes) { this(); for (SelectionAttribute selectionAttribute : selectionAttributes) { addSelectionAttribute(selectionAttribute.getCssAttribute(), selectionAttribute.getSelectionOption(), selectionAttribute.getAttributeValue()); } } /** * Constructs ui element selector out of node attribute map. * * This is auxiliary constructor needed for some parts of the system. Please prefer to use * other constructors. * * @param nodeAttributeMap * a map between the html attribute names and their corresponding values * @throws IllegalArgumentException * In case the node attribute map contains an entry with no matching {@link CssAttribute} or if the matching * attribute is of type not handled in {@link #determineAttributeValue(CssAttribute, String)}. */ public UiElementSelector(Map<String, String> nodeAttributeMap) throws IllegalArgumentException { this(); for (Entry<String, String> nodeAttributeEntry : nodeAttributeMap.entrySet()) { boolean attributeFound = false; for (CssAttribute cssAttribute : CssAttribute.values()) { if (nodeAttributeEntry.getKey().equalsIgnoreCase("NAF")) { attributeFound = true; } if (cssAttribute.getHtmlAttributeName().equals(nodeAttributeEntry.getKey())) { Object attributeValue = determineAttributeValue(cssAttribute, nodeAttributeEntry.getValue()); if (!shouldSkipAttribute(cssAttribute, attributeValue)) { addSelectionAttribute(cssAttribute, UiElementSelectionOption.EQUALS, attributeValue); } attributeFound = true; break; } } if (!attributeFound) { String message = "Unsupported attribute passed in to UI element selector constructor"; LOGGER.error(message); throw new IllegalArgumentException(message); } } } /** * Adds a new selection attribute for this UI element selector. * If a value is already set for the provided attribute, it will be replaced. * If the provided value is an empty string, the selection attribute will be ignored. * <p> * Example usage would be: * <p> * <code> * uiElementSelector.addSelectionAttribute(CssAttribute.CHECKABLE, UiElementSelectionOption.EQUALS, true); * </code> * * @param attribute * - the attribute to add a selection expression for * @param selectionOption * - the selection option. One of the {@link UiElementSelectionOption}. * @param value * - the value to be used in the selection expression * @throws IllegalArgumentException if the provided value does not match the type of the specified attribute */ public void addSelectionAttribute(CssAttribute attribute, UiElementSelectionOption selectionOption, Object value) throws IllegalArgumentException { if (!attribute.isObjectOfAppropriateType(value)) { String message = String.format("Invalid attributes value for attributes: %s. Expected %s but was %s .", attribute, attribute.getAttributeType(), value.getClass()); LOGGER.error(message); throw new IllegalArgumentException(message); } if (!shouldSkipAttribute(attribute, value)) { attributeProjectionMap.put(attribute, new Pair<Object, UiElementSelectionOption>(value, selectionOption)); } } /** * Adds a new selection attribute for this UI element selector with the {@link UiElementSelectionOption#EQUALS} * selection option. If a value is already set for the provided attribute, it will be replaced. * If the provided value is an empty string, the selection attribute will be ignored. * <p> * Example usage would be: * <p> * <code> * uiElementSelector.addSelectionAttribute(CssAttribute.CHECKABLE, true); * </code> * * @param attribute * - the attribute to add a selection expression for * @param value * - the value to be used in the selection expression * @throws IllegalArgumentException if the provided value does not match the type of the specified attribute */ public void addSelectionAttribute(CssAttribute attribute, Object value) { addSelectionAttribute(attribute, UiElementSelectionOption.EQUALS, value); } /** * Returns a new UiElementSelector instance with the provided resource id value. * * @param resourceId * - the resource id value for the attribute * @return the new UiElementSelector instance */ public static UiElementSelector getSelectorByResourceID(String resourceId) { return new UiElementSelector(CssAttribute.RESOURCE_ID, resourceId); } /** * Returns a new UiElementSelector instance with the provided class name value. * * @param className * - the class name value for the attribute * @return the new UiElementSelector instance */ public static UiElementSelector getSelectorByClass(String className) { return new UiElementSelector(CssAttribute.CLASS_NAME, className); } /** * Returns a new UiElementSelector instance with the provide package name value. * * @param packageName * - the package name value for the attribute * @return the new UiElementSelector instance */ public static UiElementSelector getSelectorByPackageName(String packageName) { return new UiElementSelector(CssAttribute.PACKAGE_NAME, packageName); } /** * Returns a new UiElementSelector instance with the provided text value. * * @param text * - the text value for the attribute * @return the new UiElementSelector instance */ public static UiElementSelector getSelectorByText(String text) { return new UiElementSelector(CssAttribute.TEXT, text); } /** * Returns a new UiElementSelector instance with the provided content description value. * * @param contentDescription * - the content description value for the attribute * @return the new UiElementSelector instance */ public static UiElementSelector getSelectorByContentDescription(String contentDescription) { return new UiElementSelector(CssAttribute.CONTENT_DESCRIPTION, contentDescription); } /** * Returns the value of a boolean {@link CssAttribute}. * * @param attribute * - the boolean attribute to get the value of * @return the boolean attribute's value or <code>null</code> if no value is set for this attribute * @throws IllegalArgumentException if the provided attribute is not a boolean attribute */ public Boolean getBooleanValue(CssAttribute attribute) { return (Boolean) getGenericValue(attribute, Boolean.class); } /** * Returns the value of a string {@link CssAttribute}. * * @param attribute * - the string attribute to get the value of * @return the string attribute's value or <code>null</code> if no value is set for this attribute * @throws IllegalArgumentException if the provided attribute is not a string attribute */ public String getStringValue(CssAttribute attribute) { return (String) getGenericValue(attribute, String.class); } /** * Returns a {@link Pair} of the value of a string {@link CssAttribute} and its {@link UiElementSelectionOption} option. * * @param attribute * - the string attribute to get the value of * @return a {@link Pair} of the attribute's value and its selection option, or <code>null</code> * if the value or the selection option is <code>null</code> * @throws IllegalArgumentException if the provided attribute is not a string attribute */ public Pair<String, UiElementSelectionOption> getStringValueWithSelectionOption(CssAttribute attribute) { String stringValue = getStringValue(attribute); UiElementSelectionOption selectionOption = getUiElementSelectionOption(attribute); if (stringValue == null || selectionOption == null) { return null; } return new Pair<String, UiElementSelectionOption>(stringValue, selectionOption); } /** * Returns the value of an integer {@link CssAttribute}. * * @param attribute * - the integer attribute to get the value of * @return the integer attribute's value or <code>null</code> if no value is set for this attribute * @throws IllegalArgumentException if the provided attribute is not an integer attribute */ public Integer getIntegerValue(CssAttribute attribute) { return (Integer) getGenericValue(attribute, Integer.class); } /** * Returns the value of a {@link Bounds} {@link CssAttribute}. * * @param attribute * - the {@link CssAttribute#BOUNDS} attribute to get the value of * @return the {@link Bounds} attribute's value or <code>null</code> if no value is set for this attribute * @throws IllegalArgumentException if the provided attribute is not of type {@link CssAttribute#BOUNDS} */ public Bounds getBoundsValue(CssAttribute attribute) { return (Bounds) getGenericValue(attribute, Bounds.class); } /** * Builds a CSS select element query based on the contents of this selector. * * @return the built CSS query */ public String buildCssQuery() { StringBuilder builder = new StringBuilder(); for (Entry<CssAttribute, Pair<Object, UiElementSelectionOption>> attributeProjectionMapEntry : attributeProjectionMap.entrySet()) { Object selectionExpression = attributeProjectionMapEntry.getValue().getKey(); if (selectionExpression != null) { CssAttribute attribute = attributeProjectionMapEntry.getKey(); UiElementSelectionOption selectionOption = attributeProjectionMapEntry.getValue().getValue(); builder.append(selectionOption.constructAttributeSelector(attribute, selectionExpression)); } } return builder.toString(); } private boolean shouldSkipAttribute(CssAttribute attribute, Object value) { // Apparently empty strings cause crashes return attribute.getAttributeType().equals(String.class) && (value != null) && ((String) value).isEmpty(); } private Object getGenericValue(CssAttribute attribute, Class<?> clazz) { if (!attributeProjectionMap.containsKey(attribute)) { return null; } if (attribute.getAttributeType().equals(clazz)) { return attributeProjectionMap.get(attribute).getKey(); } else { throw new IllegalArgumentException("Trying to get boolean value of non-boolean attribute " + attribute); } } private UiElementSelectionOption getUiElementSelectionOption(CssAttribute attribute) { if (!attributeProjectionMap.containsKey(attribute)) { return null; } return attributeProjectionMap.get(attribute).getValue(); } private Object determineAttributeValue(CssAttribute cssAttribute, String value) { if (cssAttribute.getAttributeType().equals(String.class)) { return value; } if (cssAttribute.getAttributeType().equals(Integer.class)) { return Integer.parseInt(value); } if (cssAttribute.getAttributeType().equals(Boolean.class)) { return value.equals("true"); } if (cssAttribute.getAttributeType().equals(Bounds.class)) { return UiElementBoundsParser.parse(value); } String message = String.format("Constructing UI element selector with attribute of unsupported type %s .", cssAttribute.getAttributeType()); LOGGER.error(message); throw new IllegalArgumentException(message); } public boolean isEmpty() { return attributeProjectionMap.isEmpty(); } @Override public boolean equals(Object object) { if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } UiElementSelector uiElementSelector = (UiElementSelector) object; return new EqualsBuilder().append(attributeProjectionMap, uiElementSelector.attributeProjectionMap).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder().append(attributeProjectionMap).toHashCode(); } @Override public Integer getIndex() { return getIntegerValue(CssAttribute.INDEX); } @Override public String getText() { return getStringValue(CssAttribute.TEXT); } @Override public Boolean isClickable() { return getBooleanValue(CssAttribute.CLICKABLE); } @Override public Boolean isScrollable() { return getBooleanValue(CssAttribute.SCROLLABLE); } @Override public Boolean isLongClickable() { return getBooleanValue(CssAttribute.LONG_CLICKABLE); } @Override public Boolean isSelected() { return getBooleanValue(CssAttribute.SELECTED); } @Override public Boolean isPassword() { return getBooleanValue(CssAttribute.PASSWORD); } @Override public Bounds getBounds() { return getBoundsValue(CssAttribute.BOUNDS); } @Override public String getClassName() { return getStringValue(CssAttribute.CLASS_NAME); } @Override public String getPackageName() { return getStringValue(CssAttribute.PACKAGE_NAME); } @Override public String getContentDescriptor() { return getStringValue(CssAttribute.CONTENT_DESCRIPTION); } @Override public Boolean isCheckable() { return getBooleanValue(CssAttribute.CHECKABLE); } @Override public Boolean isChecked() { return getBooleanValue(CssAttribute.CHECKED); } @Override public Boolean isFocusable() { return getBooleanValue(CssAttribute.FOCUSED); } @Override public Boolean isFocused() { return getBooleanValue(CssAttribute.FOCUSED); } @Override public Boolean isEnabled() { return getBooleanValue(CssAttribute.ENABLED); } @Override public String getResourceId() { return getStringValue(CssAttribute.RESOURCE_ID); } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append(CssAttribute.INDEX.toString(), getIntegerValue(CssAttribute.INDEX)) .append(CssAttribute.TEXT.toString(), getStringValue(CssAttribute.TEXT)) .append(CssAttribute.CLASS_NAME.toString(), getStringValue(CssAttribute.CLASS_NAME)) .append(CssAttribute.PACKAGE_NAME.toString(), getStringValue(CssAttribute.PACKAGE_NAME)) .append(CssAttribute.CONTENT_DESCRIPTION.toString(), getStringValue(CssAttribute.CONTENT_DESCRIPTION)) .append(CssAttribute.BOUNDS.toString(), getBoundsValue(CssAttribute.BOUNDS)) .append(CssAttribute.CLICKABLE.toString(), getBooleanValue(CssAttribute.CLICKABLE)) .append(CssAttribute.SCROLLABLE.toString(), getBooleanValue(CssAttribute.SCROLLABLE)) .append(CssAttribute.LONG_CLICKABLE.toString(), getBooleanValue(CssAttribute.LONG_CLICKABLE)) .append(CssAttribute.SELECTED.toString(), getBooleanValue(CssAttribute.SELECTED)) .append(CssAttribute.PASSWORD.toString(), getBooleanValue(CssAttribute.PASSWORD)) .append(CssAttribute.CHECKABLE.toString(), getBooleanValue(CssAttribute.CHECKABLE)) .append(CssAttribute.CHECKED.toString(), getBooleanValue(CssAttribute.CHECKED)) .append(CssAttribute.FOCUSABLE.toString(), getBooleanValue(CssAttribute.FOCUSABLE)) .append(CssAttribute.FOCUSED.toString(), getBooleanValue(CssAttribute.FOCUSED)) .append(CssAttribute.ENABLED.toString(), getBooleanValue(CssAttribute.ENABLED)) .append(CssAttribute.RESOURCE_ID.toString(), getStringValue(CssAttribute.RESOURCE_ID)) .toString(); } }
22,566
Java
.java
462
36.179654
139
0.615768
MusalaSoft/atmosphere-commons
4
0
0
GPL-3.0
9/4/2024, 11:04:39 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,566
202,015
PolicyModifyCommandResponseAdapter.java
eclipse-ditto_ditto/protocol/src/main/java/org/eclipse/ditto/protocol/adapter/policies/PolicyModifyCommandResponseAdapter.java
/* * Copyright (c) 2019 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.eclipse.ditto.protocol.adapter.policies; import static java.util.Objects.requireNonNull; import org.eclipse.ditto.base.model.headers.translator.HeaderTranslator; import org.eclipse.ditto.policies.model.signals.commands.modify.PolicyModifyCommandResponse; import org.eclipse.ditto.protocol.Adaptable; import org.eclipse.ditto.protocol.TopicPath; import org.eclipse.ditto.protocol.adapter.ModifyCommandResponseAdapter; import org.eclipse.ditto.protocol.mapper.SignalMapperFactory; import org.eclipse.ditto.protocol.mappingstrategies.MappingStrategiesFactory; /** * Adapter for mapping a {@link PolicyModifyCommandResponse} to and from an {@link Adaptable}. */ final class PolicyModifyCommandResponseAdapter extends AbstractPolicyAdapter<PolicyModifyCommandResponse<?>> implements ModifyCommandResponseAdapter<PolicyModifyCommandResponse<?>> { private PolicyModifyCommandResponseAdapter(final HeaderTranslator headerTranslator) { super(MappingStrategiesFactory.getPolicyModifyCommandResponseMappingStrategies(), SignalMapperFactory.newPolicyModifyResponseSignalMapper(), headerTranslator ); } /** * Returns a new PolicyModifyCommandResponseAdapter. * * @param headerTranslator translator between external and Ditto headers. * @return the adapter. */ public static PolicyModifyCommandResponseAdapter of(final HeaderTranslator headerTranslator) { return new PolicyModifyCommandResponseAdapter(requireNonNull(headerTranslator)); } @Override protected String getTypeCriterionAsString(final TopicPath topicPath) { return RESPONSES_CRITERION; } }
2,080
Java
.java
45
42.266667
108
0.80572
eclipse-ditto/ditto
666
219
87
EPL-2.0
9/4/2024, 7:05:34 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,080
3,869,069
EnumerationsUppercase.java
darkiyy_sonar-gdscript/src/main/java/gdscript_rules/rules/EnumerationsUppercase.java
package gdscript_rules.rules; import gdscript_language.GDScriptParser; import gdscript_language.listener.EnumListener; import gdscript_rules.FlagLineRule; import gdscript_rules.IssuesContainer; import gdscript_rules.GDScriptParserWalker; import org.antlr.v4.runtime.tree.TerminalNode; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.rule.RuleKey; import org.sonar.check.Rule; import java.util.List; @Rule(key = EnumerationsUppercase.RULE_KEY) public class EnumerationsUppercase implements FlagLineRule { public static final String RULE_KEY = "EnumerationsUppercase"; @Override public void execute(SensorContext sensorContext, InputFile file, RuleKey ruleKey) { GDScriptParserWalker walker = GDScriptParserWalker.getInstance(); walker.parseFile(file); EnumListener listener = (EnumListener) walker.getListener(EnumListener.class); for(GDScriptParser.EnumDeclContext enums: listener.getEnumDecl()) { List<TerminalNode> listEntries = enums.enumList().IDENTIFIER(); for (TerminalNode identifier: listEntries) { String entry = identifier.getText(); String entryUpper = entry.toUpperCase(); if(!entry.equals(entryUpper)) // IF entry is not in Uppercase { IssuesContainer.createIssue(ruleKey, file, sensorContext, enums); } } } } }
1,498
Java
.java
34
36.882353
87
0.723521
darkiyy/sonar-gdscript
3
0
0
LGPL-3.0
9/4/2024, 11:46:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,498
3,891,331
UpdateIdentityResourceAndAuthorityListener.java
risesoft-y9_Digital-Infrastructure/y9-digitalbase-module/y9-module-platform/risenet-y9boot-support-platform-service/src/main/java/net/risesoft/listener/UpdateIdentityResourceAndAuthorityListener.java
package net.risesoft.listener; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import org.springframework.transaction.event.TransactionalEventListener; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import net.risesoft.entity.Y9OrgBase; import net.risesoft.entity.Y9Person; import net.risesoft.entity.Y9Position; import net.risesoft.entity.permission.Y9Authorization; import net.risesoft.entity.relation.Y9OrgBasesToRoles; import net.risesoft.entity.relation.Y9PersonsToGroups; import net.risesoft.entity.relation.Y9PersonsToPositions; import net.risesoft.enums.platform.AuthorityEnum; import net.risesoft.enums.platform.AuthorizationPrincipalTypeEnum; import net.risesoft.enums.platform.OrgTypeEnum; import net.risesoft.enums.platform.ResourceTypeEnum; import net.risesoft.service.authorization.Y9AuthorizationService; import net.risesoft.service.identity.IdentityResourceCalculator; import net.risesoft.service.identity.Y9PersonToResourceAndAuthorityService; import net.risesoft.service.identity.Y9PositionToResourceAndAuthorityService; import net.risesoft.service.org.CompositeOrgBaseService; import net.risesoft.service.org.Y9PersonService; import net.risesoft.service.org.Y9PositionService; import net.risesoft.service.relation.Y9OrgBasesToRolesService; import net.risesoft.util.Y9OrgUtil; import net.risesoft.util.Y9ResourceUtil; import net.risesoft.y9.pubsub.event.Y9EntityCreatedEvent; import net.risesoft.y9.pubsub.event.Y9EntityDeletedEvent; import net.risesoft.y9.pubsub.event.Y9EntityUpdatedEvent; import net.risesoft.y9public.entity.resource.Y9ResourceBase; /** * 监听各种需要重新计算权限缓存的事件并执行相应操作 * * @author shidaobang * @date 2022/09/13 */ @Component @RequiredArgsConstructor @Slf4j public class UpdateIdentityResourceAndAuthorityListener { private final Y9PersonToResourceAndAuthorityService y9PersonToResourceAndAuthorityService; private final Y9PositionToResourceAndAuthorityService y9PositionToResourceAndAuthorityService; private final Y9AuthorizationService y9AuthorizationService; private final Y9OrgBasesToRolesService y9OrgBasesToRolesService; private final Y9PersonService y9PersonService; private final Y9PositionService y9PositionService; private final IdentityResourceCalculator identityResourceCalculator; private final CompositeOrgBaseService compositeOrgBaseService; @TransactionalEventListener @Async public void onOrgUnitCreated(Y9EntityCreatedEvent<? extends Y9OrgBase> event) { Y9OrgBase y9OrgBase = event.getEntity(); OrgTypeEnum orgType = y9OrgBase.getOrgType(); if (OrgTypeEnum.PERSON.equals(orgType)) { identityResourceCalculator.recalculateByOrgUnitId(y9OrgBase.getId()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("新增人员触发的重新计算权限缓存执行完成"); } return; } if (OrgTypeEnum.POSITION.equals(orgType)) { identityResourceCalculator.recalculateByOrgUnitId(y9OrgBase.getId()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("新增岗位触发的重新计算权限缓存执行完成"); } return; } } @TransactionalEventListener @Async public void onOrgUnitUpdated(Y9EntityUpdatedEvent<? extends Y9OrgBase> event) { Y9OrgBase originOrgUnit = event.getOriginEntity(); Y9OrgBase updatedOrgUnit = event.getUpdatedEntity(); OrgTypeEnum orgType = updatedOrgUnit.getOrgType(); if (OrgTypeEnum.DEPARTMENT.equals(orgType)) { if (Y9OrgUtil.isMoved(originOrgUnit, updatedOrgUnit)) { // 只需要针对移动部门的情况需要删除重新计算 String departmentId = updatedOrgUnit.getId(); y9PositionToResourceAndAuthorityService.deleteByOrgUnitId(departmentId); y9PersonToResourceAndAuthorityService.deleteByOrgUnitId(departmentId); identityResourceCalculator.recalculateByOrgUnitId(departmentId); if (LOGGER.isDebugEnabled()) { LOGGER.debug("修改部门触发的重新计算权限缓存执行完成"); } } return; } if (OrgTypeEnum.PERSON.equals(orgType)) { if (Y9OrgUtil.isMoved(originOrgUnit, updatedOrgUnit)) { // 只需要针对移动人员的情况需要删除重新计算 String personId = updatedOrgUnit.getId(); y9PersonToResourceAndAuthorityService.deleteByPersonId(personId); identityResourceCalculator.recalculateByOrgUnitId(personId); if (LOGGER.isDebugEnabled()) { LOGGER.debug("修改人员触发的重新计算权限缓存执行完成"); } } return; } if (OrgTypeEnum.POSITION.equals(orgType)) { if (Y9OrgUtil.isMoved(originOrgUnit, updatedOrgUnit)) { // 只需要针对移动岗位的情况需要删除重新计算 String positionId = updatedOrgUnit.getId(); y9PositionToResourceAndAuthorityService.deleteByPositionId(positionId); identityResourceCalculator.recalculateByOrgUnitId(positionId); if (LOGGER.isDebugEnabled()) { LOGGER.debug("修改岗位触发的重新计算权限缓存执行完成"); } } return; } } @TransactionalEventListener @Async public void onResourceCreated(Y9EntityCreatedEvent<? extends Y9ResourceBase> event) { Y9ResourceBase resource = event.getEntity(); ResourceTypeEnum resourceType = resource.getResourceType(); if (ResourceTypeEnum.APP.equals(resourceType)) { // 新建的 APP 肯定没有对该资源授权,不用计算权限 if (LOGGER.isDebugEnabled()) { LOGGER.debug("新建的 APP 肯定没有对该资源授权,不用计算权限"); } return; } // 如果菜单或按钮继承权限,则需计算 if (Boolean.TRUE.equals(resource.getInherit())) { identityResourceCalculator.recalculateByResourceId(resource.getId()); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("新增资源触发的重新计算权限缓存执行完成"); } } @TransactionalEventListener @Async public void onResourceUpdated(Y9EntityUpdatedEvent<? extends Y9ResourceBase> event) { Y9ResourceBase originResource = event.getOriginEntity(); Y9ResourceBase updatedResource = event.getUpdatedEntity(); ResourceTypeEnum resourceType = updatedResource.getResourceType(); if (ResourceTypeEnum.APP.equals(resourceType)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("应用修改不用重新计算权限缓存"); } return; } if (Y9ResourceUtil.isInheritanceChanged(originResource, updatedResource)) { // 菜单和按钮如果修改继承属性,则需计算 identityResourceCalculator.recalculateByResourceId(updatedResource.getId()); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("更新资源触发的重新计算权限缓存执行完成"); } } @TransactionalEventListener @Async public void onY9AuthorizationCreated(Y9EntityCreatedEvent<Y9Authorization> event) { Y9Authorization y9Authorization = event.getEntity(); if (AuthorizationPrincipalTypeEnum.ROLE.equals(y9Authorization.getPrincipalType())) { recalculateByRoleId(y9Authorization.getPrincipalId()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("新增对角色的授权配置触发的重新计算权限缓存执行完成"); } return; } identityResourceCalculator.recalculateByOrgUnitId(y9Authorization.getPrincipalId()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("新增或更新对组织的直接授权配置触发的重新计算权限缓存执行完成"); } } @TransactionalEventListener @Async public void onY9AuthorizationDeleted(Y9EntityDeletedEvent<Y9Authorization> event) { Y9Authorization y9Authorization = event.getEntity(); if (AuthorityEnum.HIDDEN.equals(y9Authorization.getAuthority())) { if (AuthorizationPrincipalTypeEnum.ROLE.equals(y9Authorization.getPrincipalType())) { recalculateByRoleId(y9Authorization.getPrincipalId()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("删除对组织的直接隐藏授权配置触发的重新计算权限缓存执行完成"); } return; } identityResourceCalculator.recalculateByOrgUnitId(y9Authorization.getPrincipalId()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("删除对角色的隐藏授权配置触发的重新计算权限缓存执行完成"); } } } @TransactionalEventListener @Async public void onY9OrgBasesToRolesCreated(Y9EntityCreatedEvent<Y9OrgBasesToRoles> event) { Y9OrgBasesToRoles y9OrgBasesToRoles = event.getEntity(); if (Boolean.TRUE.equals(y9OrgBasesToRoles.getNegative())) { List<Y9Authorization> authorizationList = y9AuthorizationService .listByPrincipalIdAndPrincipalType(y9OrgBasesToRoles.getRoleId(), AuthorizationPrincipalTypeEnum.ROLE); for (Y9Authorization y9Authorization : authorizationList) { if (OrgTypeEnum.PERSON.equals(y9OrgBasesToRoles.getOrgType())) { y9PersonToResourceAndAuthorityService.deleteByAuthorizationIdAndPersonId(y9Authorization.getId(), y9OrgBasesToRoles.getOrgId()); } else if (OrgTypeEnum.POSITION.equals(y9OrgBasesToRoles.getOrgType())) { y9PositionToResourceAndAuthorityService .deleteByAuthorizationIdAndPositionId(y9Authorization.getId(), y9OrgBasesToRoles.getOrgId()); List<Y9Person> y9PersonList = y9PersonService.listByPositionId(y9OrgBasesToRoles.getOrgId(), Boolean.FALSE); for (Y9Person y9Person : y9PersonList) { y9PersonToResourceAndAuthorityService .deleteByAuthorizationIdAndPersonId(y9Authorization.getId(), y9Person.getId()); } } else { y9PersonToResourceAndAuthorityService.deleteByAuthorizationIdAndOrgUnitId(y9Authorization.getId(), y9OrgBasesToRoles.getOrgId()); y9PositionToResourceAndAuthorityService.deleteByAuthorizationIdAndOrgUnitId(y9Authorization.getId(), y9OrgBasesToRoles.getOrgId()); } } return; } else { identityResourceCalculator.recalculateByOrgUnitId(y9OrgBasesToRoles.getOrgId()); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("新建组织和角色的映射触发的重新计算权限缓存执行完成"); } } @TransactionalEventListener @Async public void onY9OrgBasesToRolesDeleted(Y9EntityDeletedEvent<Y9OrgBasesToRoles> event) { Y9OrgBasesToRoles orgBasesToRoles = event.getEntity(); if (Boolean.TRUE.equals(orgBasesToRoles.getNegative())) { identityResourceCalculator.recalculateByOrgUnitId(orgBasesToRoles.getOrgId()); } else { List<Y9Authorization> authorizationList = y9AuthorizationService .listByPrincipalIdAndPrincipalType(orgBasesToRoles.getRoleId(), AuthorizationPrincipalTypeEnum.ROLE); for (Y9Authorization y9Authorization : authorizationList) { if (OrgTypeEnum.PERSON.equals(orgBasesToRoles.getOrgType())) { y9PersonToResourceAndAuthorityService.deleteByAuthorizationIdAndPersonId(y9Authorization.getId(), orgBasesToRoles.getOrgId()); } else if (OrgTypeEnum.POSITION.equals(orgBasesToRoles.getOrgType())) { y9PositionToResourceAndAuthorityService .deleteByAuthorizationIdAndPositionId(y9Authorization.getId(), orgBasesToRoles.getOrgId()); List<Y9Person> y9PersonList = y9PersonService.listByPositionId(orgBasesToRoles.getOrgId(), Boolean.FALSE); for (Y9Person y9Person : y9PersonList) { y9PersonToResourceAndAuthorityService .deleteByAuthorizationIdAndPersonId(y9Authorization.getId(), y9Person.getId()); } } else { y9PersonToResourceAndAuthorityService.deleteByAuthorizationIdAndOrgUnitId(y9Authorization.getId(), orgBasesToRoles.getOrgId()); y9PositionToResourceAndAuthorityService.deleteByAuthorizationIdAndOrgUnitId(y9Authorization.getId(), orgBasesToRoles.getOrgId()); } } identityResourceCalculator.recalculateByOrgUnitId(orgBasesToRoles.getOrgId()); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("删除组织和角色的映射触发的重新计算权限缓存执行完成"); } } @TransactionalEventListener @Async public void onY9PersonsToGroupsCreated(Y9EntityCreatedEvent<Y9PersonsToGroups> event) { Y9PersonsToGroups y9PersonsToGroups = event.getEntity(); identityResourceCalculator.recalculateByOrgUnitId(y9PersonsToGroups.getPersonId()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("用户组加人触发的重新计算权限缓存执行完成"); } } @TransactionalEventListener @Async public void onY9PersonsToGroupsDeleted(Y9EntityDeletedEvent<Y9PersonsToGroups> event) { Y9PersonsToGroups y9PersonsToGroups = event.getEntity(); identityResourceCalculator.recalculateByOrgUnitId(y9PersonsToGroups.getPersonId()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("用户组删人触发的重新计算权限缓存执行完成"); } } @TransactionalEventListener @Async public void onY9PersonsToPositionsCreated(Y9EntityCreatedEvent<Y9PersonsToPositions> event) { Y9PersonsToPositions y9PersonsToPositions = event.getEntity(); identityResourceCalculator.recalculateByOrgUnitId(y9PersonsToPositions.getPersonId()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("新建人员和岗位的映射触发的重新计算权限缓存执行完成"); } } @TransactionalEventListener @Async public void onY9PersonsToPositionsDeleted(Y9EntityDeletedEvent<Y9PersonsToPositions> event) { Y9PersonsToPositions y9PersonsToPositions = event.getEntity(); identityResourceCalculator.recalculateByOrgUnitId(y9PersonsToPositions.getPersonId()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("岗位删人触发的重新计算权限缓存执行完成"); } } private void recalculateByRoleId(String roleId) { Set<Y9Person> y9PersonSet = new HashSet<>(); Set<Y9Position> y9PositionSet = new HashSet<>(); List<Y9OrgBasesToRoles> y9OrgBasesToRolesList = y9OrgBasesToRolesService.listByRoleId(roleId); for (Y9OrgBasesToRoles y9OrgBasesToRoles : y9OrgBasesToRolesList) { if (OrgTypeEnum.PERSON.equals(y9OrgBasesToRoles.getOrgType())) { y9PersonSet.add(y9PersonService.getById(y9OrgBasesToRoles.getOrgId())); } else if (OrgTypeEnum.POSITION.equals(y9OrgBasesToRoles.getOrgType())) { y9PositionSet.add(y9PositionService.getById(y9OrgBasesToRoles.getOrgId())); y9PersonSet.addAll(y9PersonService.listByPositionId(y9OrgBasesToRoles.getOrgId(), Boolean.FALSE)); } else { y9PersonSet.addAll(compositeOrgBaseService.listAllDescendantPersons(y9OrgBasesToRoles.getOrgId())); y9PositionSet .addAll(compositeOrgBaseService.listAllPositionsRecursionDownward(y9OrgBasesToRoles.getOrgId())); } } for (Y9Person y9Person : y9PersonSet) { identityResourceCalculator.recalculateByPerson(y9Person); } for (Y9Position y9Position : y9PositionSet) { identityResourceCalculator.recalculateByPosition(y9Position); } } }
16,945
Java
.java
320
38.884375
120
0.696355
risesoft-y9/Digital-Infrastructure
3
3
0
GPL-3.0
9/4/2024, 11:47:16 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,845
1,201,520
CFRetainedResource.java
keerath_openjdk-8-source/jdk/src/macosx/classes/sun/lwawt/macosx/CFRetainedResource.java
/* * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.lwawt.macosx; /** * Safely holds and disposes of native AppKit resources, using the * correct AppKit threading and Objective-C GC semantics. */ public class CFRetainedResource { private static native void nativeCFRelease(final long ptr, final boolean disposeOnAppKitThread); private final boolean disposeOnAppKitThread; protected volatile long ptr; /** * @param ptr CFRetained native object pointer * @param disposeOnAppKitThread is the object needs to be CFReleased on the main thread */ protected CFRetainedResource(final long ptr, final boolean disposeOnAppKitThread) { this.disposeOnAppKitThread = disposeOnAppKitThread; this.ptr = ptr; } /** * CFReleases previous resource and assigns new pre-retained resource. * @param ptr CFRetained native object pointer */ protected void setPtr(final long ptr) { synchronized (this) { if (this.ptr != 0) dispose(); this.ptr = ptr; } } /** * Manually CFReleases the native resource */ protected void dispose() { long oldPtr = 0L; synchronized (this) { if (ptr == 0) return; oldPtr = ptr; ptr = 0; } nativeCFRelease(oldPtr, disposeOnAppKitThread); // perform outside of the synchronized block } @Override protected void finalize() throws Throwable { dispose(); } }
2,675
Java
.java
68
34.411765
100
0.712856
keerath/openjdk-8-source
39
26
0
GPL-2.0
9/4/2024, 7:24:11 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
2,675
3,823,082
ExaminerRegistration.java
Ad0lphus_Board-Exam-Management-System/src/swing/ExaminerRegistration.java
package swing; import java.awt.Color; import java.awt.EventQueue; import java.awt.Font; import java.awt.List; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import javax.swing.border.EmptyBorder; import javax.swing.*; /** * Student Registration using Swing * @author Project_go_brr_team * */ import java.awt.Color; import java.awt.EventQueue; import java.awt.Font; import java.awt.List; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.util.ArrayList; import javax.swing.border.EmptyBorder; import javax.swing.*; /** * Student Registration using Swing * @author Project_go_brr_team * */ public class ExaminerRegistration extends JFrame { private static final long serialVersionUID = 1L; private JPanel contentPane; private JTextField firstname; private JTextField fathersname; private JTextField mothersname; private JTextField dob; private JTextField gender; private JTextField enrollNum; private JTextField aadhar; private JTextField lastname; private JTextField email; private JTextField username; private JTextField lblStream; private JTextField mob; private JTextField examID; private JPasswordField passwordField; private JButton btnNewButton; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ExaminerRegistration frame = new ExaminerRegistration(); frame.getContentPane().setBackground(new Color(176, 224, 230)); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public ExaminerRegistration() { setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\User\\Desktop\\STDM.jpg")); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(450, 190, 1014, 597); setResizable(false); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblNewExaminerRegister = new JLabel("New Examiner Registeration"); lblNewExaminerRegister.setFont(new Font("Times New Roman", Font.PLAIN, 42)); lblNewExaminerRegister.setBounds(302, 32, 500, 50); contentPane.add(lblNewExaminerRegister); JLabel lblExaminerNumber = new JLabel("<HTML>Examiner<BR>NO:</HTML>"); lblExaminerNumber.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblExaminerNumber.setBounds(58, 100, 110, 43); contentPane.add(lblExaminerNumber); JLabel lblName = new JLabel("First name"); lblName.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblName.setBounds(58, 150, 99, 43); contentPane.add(lblName); JLabel lblNewLabel = new JLabel("Last name"); lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblNewLabel.setBounds(58, 200, 110, 29); contentPane.add(lblNewLabel); JLabel lblEmailAddress = new JLabel("Email\r\n address"); lblEmailAddress.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblEmailAddress.setBounds(58, 235, 124, 36); contentPane.add(lblEmailAddress); JLabel lblIsChecker = new JLabel("Checker"); lblIsChecker.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblIsChecker.setBounds(58, 270, 99, 43); contentPane.add(lblIsChecker); JLabel lblIsSupervisor = new JLabel("Supervisor"); lblIsSupervisor.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblIsSupervisor.setBounds(58, 305, 110, 43); contentPane.add(lblIsSupervisor); JLabel lblIsSetter = new JLabel("Setter"); lblIsSetter.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblIsSetter.setBounds(58, 340, 110, 43); contentPane.add(lblIsSetter); JLabel lblQualification = new JLabel("Qualification"); lblQualification.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblQualification.setBounds(58, 375, 124, 45); contentPane.add(lblQualification); JLabel lblExamId = new JLabel("Exam ID"); lblExamId.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblExamId.setBounds(58, 410, 124, 45); contentPane.add(lblExamId); JLabel lblSchool = new JLabel("Center"); lblSchool.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblSchool.setBounds(542, 120, 99, 29); contentPane.add(lblSchool); JLabel lblUsername = new JLabel("Username"); lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblUsername.setBounds(542, 159, 99, 29); contentPane.add(lblUsername); JLabel lblPassword = new JLabel("Password"); lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblPassword.setBounds(542, 200, 99, 24); contentPane.add(lblPassword); JLabel lblMobileNumber = new JLabel("Mobile number"); lblMobileNumber.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblMobileNumber.setBounds(542, 240, 139, 26); contentPane.add(lblMobileNumber); JLabel lblStateAndCity = new JLabel("State & City"); lblStateAndCity.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblStateAndCity.setBounds(542, 280, 139, 26); contentPane.add(lblStateAndCity); JLabel lblGender = new JLabel("Gender"); lblGender.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblGender.setBounds(542, 320, 139, 26); contentPane.add(lblGender); JLabel lblStream = new JLabel("Stream"); lblStream.setFont(new Font("Tahoma", Font.PLAIN, 18)); lblStream.setBounds(542, 360, 139, 26); contentPane.add(lblStream); enrollNum = new JTextField(); enrollNum.setFont(new Font("Tahoma", Font.PLAIN, 22)); enrollNum.setBounds(214, 111, 228, 25); contentPane.add(enrollNum); enrollNum.setColumns(10); firstname = new JTextField(); firstname.setFont(new Font("Tahoma", Font.PLAIN, 22)); firstname.setBounds(214, 161, 228, 25); contentPane.add(firstname); firstname.setColumns(10); lastname = new JTextField(); lastname.setFont(new Font("Tahoma", Font.PLAIN, 22)); lastname.setBounds(214, 200, 228, 25); contentPane.add(lastname); lastname.setColumns(10); email = new JTextField(); email.setFont(new Font("Tahoma", Font.PLAIN, 22)); email.setBounds(214, 240, 228, 25); contentPane.add(email); email.setColumns(10); JRadioButton yesCheckRadio = new JRadioButton("Yes"); JRadioButton noCheckRadio = new JRadioButton("No"); yesCheckRadio.setBounds(214, 280, 100, 25); yesCheckRadio.setFont(new Font("Tahoma", Font.PLAIN, 18)); yesCheckRadio.setBackground(new Color(176, 224, 230)); contentPane.add(yesCheckRadio); noCheckRadio.setBounds(350, 280, 100, 25); noCheckRadio.setFont(new Font("Tahoma", Font.PLAIN, 18)); noCheckRadio.setBackground(new Color(176, 224, 230)); contentPane.add(noCheckRadio); JRadioButton yesSuperRadio = new JRadioButton("Yes"); JRadioButton noSuperRadio = new JRadioButton("No"); yesSuperRadio.setBounds(214, 315, 100, 25); yesSuperRadio.setFont(new Font("Tahoma", Font.PLAIN, 18)); yesSuperRadio.setBackground(new Color(176, 224, 230)); contentPane.add(yesSuperRadio); noSuperRadio.setBounds(350, 315, 100, 25); noSuperRadio.setFont(new Font("Tahoma", Font.PLAIN, 18)); noSuperRadio.setBackground(new Color(176, 224, 230)); contentPane.add(noSuperRadio); JRadioButton yesSetterRadio = new JRadioButton("Yes"); JRadioButton noSetterRadio = new JRadioButton("No"); yesSetterRadio.setBounds(214, 350, 100, 25); yesSetterRadio.setFont(new Font("Tahoma", Font.PLAIN, 18)); yesSetterRadio.setBackground(new Color(176, 224, 230)); contentPane.add(yesSetterRadio); noSetterRadio.setBounds(350, 350, 100, 25); noSetterRadio.setFont(new Font("Tahoma", Font.PLAIN, 18)); noSetterRadio.setBackground(new Color(176, 224, 230)); contentPane.add(noSetterRadio); String[] qualificationOptionsToChoose = {"BBA- Bachelor of Business Administration", "BMS- Bachelor of Management Science", "BFA- Bachelor of Fine Arts", "BEM- Bachelor of Event Management", "Integrated Law Course- BA + LL.B", "BJMC- Bachelor of Journalism and Mass Communication", "BFD- Bachelor of Fashion Designing", "BSW- Bachelor of Social Work", "BBS- Bachelor of Business Studies", "BTTM- Bachelor of Travel and Tourism Management", "Aviation Courses", "B.Sc- Interior Design", "B.Sc.- Hospitality and Hotel Administration", "Bachelor of Design (B. Design)", "Bachelor of Performing Arts", "BA- Bachelor of Arts", "BE/B.Tech- Bachelor of Technology", "B.Arch- Bachelor of Architecture", "BCA- Bachelor of Computer Applications", "B.Sc.- Information Technology", "B.Sc- Nursing", "BPharma- Bachelor of Pharmacy", "B.Sc- Interior Design", "BDS- Bachelor of Dental Surgery", "Animation, Graphics and Multimedia", "B.Sc. – Nutrition & Dietetics", "BPT- Bachelor of Physiotherapy", "B.Sc- Applied Geology", "BA/B.Sc. Liberal Arts", "B.Sc.- Physics", "B.Sc. Chemistry", "B.Sc. Mathematics", "B.Com- Bachelor of Commerce", "BBA- Bachelor of Business Administration", "B.Com (Hons.)", "BA (Hons.) in Economics", "Integrated Law Program- B.Com LL.B.", "Integarted Law Program- BBA LL.B"}; JComboBox <String> qualificationComboBox = new JComboBox<>(qualificationOptionsToChoose); qualificationComboBox.setBounds(214, 390, 230, 25); contentPane.add(qualificationComboBox); examID = new JTextField(); examID.setFont(new Font("Tahoma", Font.PLAIN, 22)); examID.setBounds(214, 425, 228, 25); contentPane.add(examID); examID.setColumns(10); int ii=0; try { Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Board-Exam-Management-System", "postgres", "prabithgupta"); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT schoolid FROM school ;"); while (rs.next()) { ii=ii+1; } }catch(SQLException err) { System.out.println("SQL exception occured" + err); } String[] schoolOptionsToChoose = new String[ii]; try { Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Board-Exam-Management-System", "postgres", "prabithgupta"); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT schoolid FROM school ;"); int i=0; while (rs.next()) { String sd = rs.getString("schoolid"); schoolOptionsToChoose[i]= sd; i=i+1; } }catch(SQLException err) { System.out.println("SQL exception occured" + err); } //String[] schoolOptionsToChoose = {"1","2","3","4","5","6","7","8","9","10","11","12"}; JComboBox <String> schoolComboBox = new JComboBox<>(schoolOptionsToChoose); schoolComboBox.setBounds(700, 120, 230, 25); contentPane.add(schoolComboBox); username = new JTextField(); username.setFont(new Font("Tahoma", Font.PLAIN, 22)); username.setBounds(707, 160, 228, 25); contentPane.add(username); username.setColumns(10); passwordField = new JPasswordField(); passwordField.setFont(new Font("Tahoma", Font.PLAIN, 22)); passwordField.setBounds(707, 200, 228, 25); contentPane.add(passwordField); mob = new JTextField(); mob.setFont(new Font("Tahoma", Font.PLAIN, 22)); mob.setBounds(707, 240, 228, 25); contentPane.add(mob); mob.setColumns(10); String[] stateOptionsToChoose = {"Andhra Pradesh","Arunachal Pradesh ","Assam","Bihar","Chhattisgarh","Goa","Gujarat","Haryana","Himachal Pradesh","Jammu and Kashmir","Jharkhand","Karnataka","Kerala","Madhya Pradesh","Maharashtra","Manipur","Meghalaya","Mizoram","Nagaland","Odisha","Punjab","Rajasthan","Sikkim","Tamil Nadu","Telangana","Tripura","Uttar Pradesh","Uttarakhand","West Bengal","Andaman and Nicobar Islands","Chandigarh","Dadra and Nagar Haveli","Daman and Diu","Lakshadweep","National Capital Territory of Delhi","Puducherry"}; JComboBox <String> jComboBox = new JComboBox<>(stateOptionsToChoose); jComboBox.setBounds(707, 280, 114, 25); contentPane.add(jComboBox); String[] cityOptionsToChoose = {"Delhi", "Mumbai", "Kolkāta", "Bangalore", "Chennai", "Hyderābād", "Pune", "Ahmedabad", "Sūrat", "Lucknow", "Jaipur", "Cawnpore", "Mirzāpur", "Nāgpur", "Ghāziābād", "Indore", "Vadodara", "Vishākhapatnam", "Bhopāl", "Chinchvad", "Patna", "Ludhiāna", "Āgra", "Kalyān", "Madurai", "Jamshedpur", "Nāsik", "Farīdābād", "Aurangābād", "Rājkot", "Meerut", "Jabalpur", "Thāne", "Dhanbād", "Allahābād", "Vārānasi", "Srīnagar", "Amritsar", "Alīgarh", "Bhiwandi", "Gwalior", "Bhilai", "Hāora", "Rānchi", "Bezwāda", "Chandīgarh", "Mysore", "Raipur", "Kota", "Bareilly", "Jodhpur", "Coimbatore", "Dispur", "Guwāhāti", "Solāpur", "Trichinopoly", "Hubli", "Jalandhar", "Bhubaneshwar", "Bhayandar", "Morādābād", "Kolhāpur", "Thiruvananthapuram", "Sahāranpur", "Warangal", "Salem", "Mālegaon", "Kochi", "Gorakhpur", "Shimoga", "Tiruppūr", "Guntūr", "Raurkela", "Mangalore", "Nānded", "Cuttack", "Chānda", "Dehra", "Dūn", "Durgāpur", "Āsansol", "Bhāvnagar", "Amrāvati", "Nellore", "Ajmer", "Tinnevelly", "Bīkaner", "Agartala", "Ujjain", "Jhānsi", "Ulhāsnagar", "Davangere", "Jammu", "Belgaum", "Gulbarga", "Jamnagar", "Dhūlia", "Gaya", "Jalgaon", "Kurnool", "Udaipur", "Bellary", "Sāngli", "Tuticorin", "Calicut", "Akola", "Bhāgalpur", "Sīkar", "Tumkūr", "Quilon", "Muzaffarnagar", "Bhīlwāra", "Nizāmābād", "Bhātpāra", "Kākināda", "Parbhani", "Pānihāti", "Lātūr", "Rohtak", "Rājapālaiyam", "Ahmadnagar", "Cuddapah", "Rājahmundry", "Alwar", "Muzaffarpur", "Bilāspur", "Mathura", "Kāmārhāti", "Patiāla", "Saugor", "Bijāpur", "Brahmapur", "Shāhjānpur", "Trichūr", "Barddhamān", "Kulti", "Sambalpur", "Purnea", "Hisar", "Fīrozābād", "Bīdar", "Rāmpur", "Shiliguri", "Bāli", "Pānīpat", "Karīmnagar", "Bhuj", "Ichalkaranji", "Tirupati", "Hospet", "Āīzawl", "Sannai", "Bārāsat", "Ratlām", "Handwāra", "Drug", "Imphāl", "Anantapur", "Etāwah", "Rāichūr", "Ongole", "Bharatpur", "Begusarai", "Sonīpat", "Rāmgundam", "Hāpur", "Uluberiya", "Porbandar", "Pāli", "Vizianagaram", "Puducherry", "Karnāl", "Nāgercoil", "Tanjore", "Sambhal", "Naihāti", "Secunderābād", "Kharagpur", "Dindigul", "Shimla", "Ingrāj", "Bāzār", "Ellore", "Puri", "Haldia", "Nandyāl", "Bulandshahr", "Chakradharpur", "Bhiwāni", "Gurgaon", "Burhānpur", "Khammam", "Madhyamgram", "Ghāndīnagar", "Baharampur", "Mahbūbnagar", "Mahesāna", "Ādoni", "Rāiganj", "Bhusāval", "Bahraigh", "Shrīrāmpur", "Tonk", "Sirsa", "Jaunpur", "Madanapalle", "Hugli", "Vellore", "Alleppey", "Cuddalore", "Deo", "Chīrāla", "Machilīpatnam", "Medinīpur", "Bāramūla", "Chandannagar", "Fatehpur", "Udipi", "Tenāli", "Sitalpur", "Conjeeveram", "Proddatūr", "Navsāri", "Godhra", "Budaun", "Chittoor", "Harīpur", "Saharsa", "Vidisha", "Pathānkot", "Nalgonda", "Dibrugarh", "Bālurghāt", "Krishnanagar", "Fyzābād", "Silchar", "Shāntipur", "Hindupur", "Erode", "Jāmuria", "Hābra", "Ambāla", "Mauli", "Kolār", "Shillong", "Bhīmavaram", "New", "Delhi", "Mandsaur", "Kumbakonam", "Tiruvannāmalai", "Chicacole", "Bānkura", "Mandya", "Hassan", "Yavatmāl", "Pīlibhīt", "Pālghāt", "Abohar", "Pālakollu", "Kānchrāpāra", "Port", "Blair", "Alīpur", "Duār", "Hāthras", "Guntakal", "Navadwīp", "Basīrhat", "Hālīsahar", "Rishra", "Dharmavaram", "Baidyabāti", "Darjeeling", "Sopur", "Gudivāda", "Adilābād", "Titāgarh", "Chittaurgarh", "Narasaraopet", "Dam", "Dam", "Vālpārai", "Osmānābād", "Champdani", "Bangaon", "Khardah", "Tādpatri", "Jalpāiguri", "Suriāpet", "Tādepallegūdem", "Bānsbāria", "Negapatam", "Bhadreswar", "Chilakalūrupet", "Kalyani", "Gangtok", "Kohīma", "Khambhāt", "Aurangābād", "Emmiganūr", "Rāyachoti", "Kāvali", "Mancherāl", "Kadiri", "Ootacamund", "Anakāpalle", "Sirsilla", "Kāmāreddipet", "Pāloncha", "Kottagūdem", "Tanuku", "Bodhan", "Karūr", "Mangalagiri", "Kairāna", "Mārkāpur", "Malaut", "Bāpatla", "Badvel", "Jorhāt", "Koratla", "Pulivendla", "Jaisalmer", "Tādepalle", "Armūr", "Jatani", "Gadwāl", "Nagari", "Wanparti", "Ponnūru", "Vinukonda", "Itānagar", "Tezpur", "Narasapur", "Kothāpet", "Mācherla", "Kandukūr", "Sāmalkot", "Bobbili", "Sattenapalle", "Vrindāvan", "Mandapeta", "Belampalli", "Bhīmunipatnam", "Nāndod", "Pithāpuram", "Punganūru", "Puttūr", "Jalor", "Palmaner", "Dholka", "Jaggayyapeta", "Tuni", "Amalāpuram", "Jagtiāl", "Vikārābād", "Venkatagiri", "Sihor", "Jangaon", "Mandamāri", "Metpalli", "Repalle", "Bhainsa", "Jasdan", "Jammalamadugu", "Rāmeswaram", "Addanki", "Nidadavole", "Bodupāl", "Rājgīr", "Rajaori", "Naini", "Tal", "Channarāyapatna", "Maihar", "Panaji", "Junnar", "Amudālavalasa", "Damān", "Kovvūr", "Solan", "Dwārka", "Pathanāmthitta", "Kodaikānal", "Udhampur", "Giddalūr", "Yellandu", "Shrīrangapattana", "Angamāli", "Umaria", "Fatehpur", "Sīkri", "Mangūr", "Pedana", "Uran", "Chimākurti", "Devarkonda", "Bandipura", "Silvassa", "Pāmidi", "Narasannapeta", "Jaynagar-Majilpur", "Khed", "Brahma", "Khajurāho", "Koilkuntla", "Diu", "Kulgam", "Gauripur", "Abu", "Curchorem", "Kavaratti", "Panchkula", "Kagaznāgār"}; JComboBox <String> jiComboBox = new JComboBox<>(cityOptionsToChoose); jiComboBox.setBounds(820, 280, 114, 25); contentPane.add(jiComboBox); JRadioButton genderRadioM = new JRadioButton("Male"); JRadioButton genderRadioF = new JRadioButton("Female"); JRadioButton genderRadioO = new JRadioButton("Others"); genderRadioM.setBounds(707, 320, 95, 25); genderRadioM.setFont(new Font("Tahoma", Font.PLAIN, 18)); genderRadioM.setBackground(new Color(176, 224, 230)); contentPane.add(genderRadioM); genderRadioF.setBounds(800, 320, 95, 25); genderRadioF.setFont(new Font("Tahoma", Font.PLAIN, 18)); genderRadioF.setBackground(new Color(176, 224, 230)); contentPane.add(genderRadioF); genderRadioO.setBounds(900, 320, 95, 25); genderRadioO.setFont(new Font("Tahoma", Font.PLAIN, 18)); genderRadioO.setBackground(new Color(176, 224, 230)); contentPane.add(genderRadioO); int iii=0; try { Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Board-Exam-Management-System", "postgres", "prabithgupta"); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT sid FROM stream ;"); while (rs.next()) { iii=iii+1; } }catch(SQLException err) { System.out.println("SQL exception occured" + err); } String[] streamOptionsToChoose = new String[iii]; try { Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Board-Exam-Management-System", "postgres", "prabithgupta"); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT sid FROM stream ;"); int i=0; while (rs.next()) { String std = rs.getString("sid"); streamOptionsToChoose[i]= std; i=i+1; } }catch(SQLException err) { System.out.println("SQL exception occured" + err); } //String[] streamOptionsToChoose = {"1","2","3","4"}; JComboBox <String> streamComboBox = new JComboBox<>(streamOptionsToChoose); streamComboBox.setBounds(707, 360, 228, 25); contentPane.add(streamComboBox); btnNewButton = new JButton("Register"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String EID = enrollNum.getText(); String firstName = firstname.getText(); String lastName = lastname.getText(); String FullName = firstName+" "+lastName; String isSettr = "null"; if(yesSetterRadio.isSelected()) { isSettr = "true";} if(noSetterRadio.isSelected()) { isSettr = "false";} String isCheckr = "null"; if(yesCheckRadio.isSelected()) { isCheckr = "true";} if(yesCheckRadio.isSelected()) { isCheckr = "false";} String isSuper = "null"; if(yesSuperRadio.isSelected()) { isSuper = "true";} if(noSuperRadio.isSelected()) { isSuper = "false";} String emailID = email.getText(); String userName = username.getText(); String PassWord = String.valueOf(passwordField.getPassword()); String Qualification = qualificationComboBox.getSelectedItem().toString(); String ExamID = examID.getText(); String centerID = schoolComboBox.getSelectedItem().toString(); String state = jComboBox.getSelectedItem().toString(); String city = jiComboBox.getSelectedItem().toString(); String stream = streamComboBox.getSelectedItem().toString(); String mobile = mob.getText(); int mobLen = mobile.length(); String gender_ = "null"; if(genderRadioM.isSelected()) { gender_ = "male";} if(genderRadioF.isSelected()) { gender_ = "female";} if(genderRadioO.isSelected()) { gender_ = "others";} //int aadharLen = aadhar.getText().length(); //String password =String.valueOf( passwordField.getPassword()); String msg = "" + FullName; msg += " \n"; if (mobLen != 10) { JOptionPane.showMessageDialog(btnNewButton, "Enter a valid mobile number"); } try { Class.forName("org.postgresql.Driver"); Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/Board-Exam-Management-System", "postgres", "prabithgupta"); String query = "INSERT INTO examinar values(" + EID + ",'" + firstName + "','" + lastName + "'," +mobile+",'"+emailID+"','"+Qualification+"','"+gender_+"',"+stream+","+isCheckr+","+ isSuper+","+isSettr+","+centerID+","+ExamID+",'"+state+"','"+city+"','"+userName+"','"+PassWord+"');"; System.out.print(query); Statement sta = connection.createStatement(); int x = sta.executeUpdate(query); if (x == 0) { JOptionPane.showMessageDialog(btnNewButton, "Examiner already exists"); } else { JOptionPane.showMessageDialog(btnNewButton, "Welcome, " + msg + "Examiner has been registered sucessfully !"); } connection.close(); } catch (Exception exception) { exception.printStackTrace(); } } }); JButton backButton = new JButton("Back"); backButton.setFont(new Font("Tahoma", Font.PLAIN, 22)); backButton.setBounds(199, 480, 259, 50); contentPane.add(backButton); backButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (JOptionPane.showConfirmDialog(contentPane, "Confirm if you want to logout", "Examinar Registration Systems", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_NO_OPTION) { dispose(); HomePage HomePage = new HomePage(); HomePage.setVisible(true); } } }); btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 22)); btnNewButton.setBounds(699, 480, 259, 50); contentPane.add(btnNewButton); getContentPane().setBackground(new Color(176, 224, 230)); } }
25,844
Java
.java
386
54.813472
4,905
0.635257
Ad0lphus/Board-Exam-Management-System
3
0
0
GPL-3.0
9/4/2024, 11:44:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,596
1,462,799
VirtualizerToolImpl.java
arodchen_MaxSim/graal/graal/com.oracle.graal.virtual/src/com/oracle/graal/virtual/phases/ea/VirtualizerToolImpl.java
/* * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.virtual.phases.ea; import static com.oracle.graal.phases.GraalOptions.*; import com.oracle.graal.api.code.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.graph.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.calc.*; import com.oracle.graal.nodes.spi.Virtualizable.EscapeState; import com.oracle.graal.nodes.spi.Virtualizable.State; import com.oracle.graal.nodes.spi.*; import com.oracle.graal.nodes.virtual.*; class VirtualizerToolImpl implements VirtualizerTool { private final NodeBitMap usages; private final MetaAccessProvider metaAccess; private final Assumptions assumptions; VirtualizerToolImpl(NodeBitMap usages, MetaAccessProvider metaAccess, Assumptions assumptions) { this.usages = usages; this.metaAccess = metaAccess; this.assumptions = assumptions; } private boolean deleted; private PartialEscapeBlockState state; private ValueNode current; private FixedNode position; private GraphEffectList effects; @Override public MetaAccessProvider getMetaAccessProvider() { return metaAccess; } @Override public Assumptions getAssumptions() { return assumptions; } public void reset(PartialEscapeBlockState newState, ValueNode newCurrent, FixedNode newPosition, GraphEffectList newEffects) { deleted = false; state = newState; current = newCurrent; position = newPosition; effects = newEffects; } public boolean isDeleted() { return deleted; } @Override public State getObjectState(ValueNode value) { return state.getObjectState(value); } @Override public void setVirtualEntry(State objectState, int index, ValueNode value) { ObjectState obj = (ObjectState) objectState; assert obj != null && obj.isVirtual() : "not virtual: " + obj; ObjectState valueState = state.getObjectState(value); ValueNode newValue = value; if (valueState == null) { newValue = getReplacedValue(value); assert obj.getEntry(index) == null || obj.getEntry(index).kind() == newValue.kind() || (isObjectEntry(obj.getEntry(index)) && isObjectEntry(newValue)); } else { if (valueState.getState() != EscapeState.Virtual) { newValue = valueState.getMaterializedValue(); assert newValue.kind() == Kind.Object; } else { newValue = valueState.getVirtualObject(); } assert obj.getEntry(index) == null || isObjectEntry(obj.getEntry(index)); } obj.setEntry(index, newValue); } private static boolean isObjectEntry(ValueNode value) { return value.kind() == Kind.Object || value instanceof VirtualObjectNode; } @Override public ValueNode getMaterializedValue(ValueNode value) { ObjectState obj = state.getObjectState(value); return obj != null && !obj.isVirtual() ? obj.getMaterializedValue() : null; } @Override public ValueNode getReplacedValue(ValueNode original) { return state.getScalarAlias(original); } @Override public void replaceWithVirtual(VirtualObjectNode virtual) { state.addAndMarkAlias(virtual, current, usages); if (current instanceof FixedWithNextNode) { effects.deleteFixedNode((FixedWithNextNode) current); } deleted = true; } @Override public void replaceWithValue(ValueNode replacement) { effects.replaceAtUsages(current, state.getScalarAlias(replacement)); state.addScalarAlias(current, replacement); deleted = true; } @Override public void delete() { effects.deleteFixedNode((FixedWithNextNode) current); deleted = true; } @Override public void replaceFirstInput(Node oldInput, Node replacement) { effects.replaceFirstInput(current, oldInput, replacement); } @Override public void addNode(ValueNode node) { if (node instanceof FloatingNode) { effects.addFloatingNode(node, "VirtualizerTool"); } else { effects.addFixedNodeBefore((FixedWithNextNode) node, position); } } @Override public void createVirtualObject(VirtualObjectNode virtualObject, ValueNode[] entryState, int[] locks) { VirtualUtil.trace("{{%s}} ", current); if (virtualObject.isAlive()) { state.addAndMarkAlias(virtualObject, virtualObject, usages); } else { effects.addFloatingNode(virtualObject, "newVirtualObject"); } for (int i = 0; i < entryState.length; i++) { entryState[i] = state.getScalarAlias(entryState[i]); } state.addObject(virtualObject, new ObjectState(virtualObject, entryState, EscapeState.Virtual, locks)); state.addAndMarkAlias(virtualObject, virtualObject, usages); PartialEscapeClosure.METRIC_ALLOCATION_REMOVED.increment(); } @Override public int getMaximumEntryCount() { return MaximumEscapeAnalysisArrayLength.getValue(); } @Override public void replaceWith(ValueNode node) { State resultState = getObjectState(node); if (resultState == null) { replaceWithValue(node); } else { if (resultState.getState() == EscapeState.Virtual) { replaceWithVirtual(resultState.getVirtualObject()); } else { replaceWithValue(resultState.getMaterializedValue()); } } } }
6,682
Java
.java
165
33.70303
163
0.693409
arodchen/MaxSim
27
9
1
GPL-2.0
9/4/2024, 7:52:46 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
6,682
1,034,591
DefaultI18NValidator.java
Naoghuman_lib-i18n/src/main/java/com/github/naoghuman/lib/i18n/internal/DefaultI18NValidator.java
/** * Copyright (C) 2018 Naoghuman's dream * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.github.naoghuman.lib.i18n.internal; import java.util.Arrays; import java.util.Locale; import java.util.Objects; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; /** * An implementation from different {@code validation} methods to check preconditions * in the topic from this library {@code Lib-I18N}. * * @since 0.1.0-PRERELEASE * @version 0.6.1 * @author Naoghuman */ public final class DefaultI18NValidator { /** * Delegates to {@link java.util.Objects#isNull(java.lang.Object)}. * <p> * This method exists to be used as a {@link java.util.function.Predicate}, * {@code filter(Objects::isNull)}. * * @param obj a reference which will be checked against {@code NULL}. * @return {@code TRUE} if the provided reference is {@code NULL} otherwise {@code FALSE}. * @since 0.1.0-PRERELEASE * @version 0.6.1 * @author Naoghuman * @see java.util.function.Predicate */ public static boolean isNull(final Object obj) { return Objects.isNull(obj); } /** * Delegates to {@link java.util.Objects#nonNull(java.lang.Object)}. * <p> * This method exists to be used as a {@link java.util.function.Predicate}, * {@code filter(Objects::nonNull)}. * * @param obj a reference which will be checked against {@code NULL}. * @return {@code TRUE} if the provided reference is {@code NON-NULL} otherwise {@code FALSE}. * @since 0.1.0-PRERELEASE * @version 0.6.1 * @author Naoghuman * @see java.util.function.Predicate */ public static boolean nonNull(final Object obj) { return Objects.nonNull(obj); } /** * Validates if the attribute {@code value} isn't {@code NULL}. * <p> * An additional error message will be added to the error stack: * <ul> * <li>The attribute [value] can't be NULL.</li> * </ul> * * @param <T> the type of the reference. * @param value the attribute which should be validated. * @throws NullPointerException if {@code (value == NULL)}. * @since 0.1.0-PRERELEASE * @version 0.6.1 * @author Naoghuman */ public static <T> void requireNonNull(final T value) throws NullPointerException { Objects.requireNonNull(value, "The attribute [value] can't be NULL."); // NOI18N } /** * Validates if the attribute {@code value} isn't {@code NULL} and not {@code EMPTY}. * <p> * Adds following additional error messages depending from the error to the error stack: * <ul> * <li>The attribute [value] can't be NULL.</li> * <li>The attribute [value] can't be EMPTY.</li> * </ul> * * @param value the attribute which should be validated. * @throws NullPointerException if {@code (value == NULL)}. * @throws IllegalArgumentException if {@code (value.trim() == EMPTY)}. * @since 0.1.0-PRERELEASE * @version 0.6.1 * @author Naoghuman */ public static void requireNonNullAndNotEmpty(final String value) throws NullPointerException, IllegalArgumentException { Objects.requireNonNull(value, "The attribute [value] can't be NULL."); // NOI18N if (value.trim().isEmpty()) { throw new IllegalArgumentException("The attribute [value] can't be EMPTY."); // NOI18N } } /** * Validates if the attribute {@code elements} isn't {@code NULL} and not {@code EMPTY}. * <p> * Adds following additional error messages depending from the error to the error stack: * <ul> * <li>The attribute [elements] can't be NULL.</li> * <li>The attribute [elements] can't be EMPTY.</li> * </ul> * * @param elements the attribute which should be validated. * @throws NullPointerException if {@code (elements == NULL)}. * @throws IllegalArgumentException if {@code (elements == EMPTY)}. * @since 0.1.0-PRERELEASE * @version 0.6.1 * @author Naoghuman */ public static void requireNonNullAndNotEmpty(final Object... elements) throws NullPointerException, IllegalArgumentException { Objects.requireNonNull(elements, "The attribute [elements] can't be NULL."); // NOI18N final ObservableList<Object> elements2 = FXCollections.observableArrayList(); elements2.addAll(Arrays.asList(elements)); if (elements2.isEmpty()) { throw new IllegalArgumentException("The attribute [elements] can't be EMPTY."); // NOI18N } } /** * Validates if the attribute {@code elements} isn't {@code NULL} and not {@code EMPTY}. * <p> * Adds following additional error messages depending from the error to the error stack: * <ul> * <li>The attribute [elements] can't be NULL.</li> * <li>The attribute [elements] can't be EMPTY.</li> * </ul> * * @param <T> the type of the reference. * @param elements the attribute which should be validated. * @throws NullPointerException if {@code (elements == NULL)}. * @throws IllegalArgumentException if {@code (elements == EMPTY)}. * @since 0.1.0-PRERELEASE * @version 0.6.1 * @author Naoghuman */ public static <T> void requireNonNullAndNotEmpty(final ObservableList<T> elements) throws NullPointerException, IllegalArgumentException { Objects.requireNonNull(elements, "The attribute [elements] can't be NULL"); // NOI18N if (elements.isEmpty()) { throw new IllegalArgumentException("The attribute [elements] can't be EMPTY"); // NOI18N } } /** * Checks if a {@link java.util.ResourceBundle} with the given parameters can be loaded. * <p> * If the {@code ResourceBundle} can't be found a {@link java.util.MissingResourceException} * will be thrown. * * @param baseBundleName which should be used to load the {@code ResourceBundle}. * @param actualLocale which should be used to load the {@code ResourceBundle}. * @since 0.7.0 * @version 0.7.0 * @author Naoghuman * @see java.util.MissingResourceException * @see java.util.ResourceBundle */ public static void requireResourceBundleExist(final String baseBundleName, final Locale actualLocale) { DefaultI18NValidator.requireNonNullAndNotEmpty(baseBundleName); DefaultI18NValidator.requireNonNull(actualLocale); ResourceBundle.getBundle(baseBundleName, actualLocale); } }
7,578
Java
.java
171
37.19883
143
0.651513
Naoghuman/lib-i18n
48
3
5
GPL-3.0
9/4/2024, 7:11:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,578
4,989,327
DeviceCache.java
ANierbeck_bcanhome-openhab/bundles/binding/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/ccu/DeviceCache.java
/** * openHAB, the open Home Automation Bus. * Copyright (C) 2010-2013, openHAB.org <admin@openhab.org> * * See the contributors.txt file in the distribution for a * full listing of individual contributors. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or * combining it with Eclipse (or a modified version of that library), * containing parts covered by the terms of the Eclipse Public License * (EPL), the licensors of this Program grant you additional permission * to convey the resulting work. */ package org.openhab.binding.homematic.internal.ccu; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.openhab.binding.homematic.internal.device.physical.HMPhysicalDevice; /** * This class caches instances of PhysicalDevice. Access to this cache will * usually be about a certain device address, so we use a java.util.Map that * maps from the address (String) to the device (PhysicalDevice). * * @author Mathias Ewald * @since 1.2.0 */ public class DeviceCache<T extends HMPhysicalDevice> { private final Logger log = Logger.getLogger(getClass().getName()); private Map<String, T> addressMap; public DeviceCache() { addressMap = Collections.synchronizedMap(new HashMap<String, T>()); } public T getDeviceByAddress(String address) { T dev = addressMap.get(address); if (dev != null) { log.finest("cache hit for device " + address); } else { log.finest("cache miss for device " + address); } return dev; } public Set<HMPhysicalDevice> getAllDevices() { return new HashSet<HMPhysicalDevice>(addressMap.values()); } public Boolean isCached(String address) { return addressMap.containsKey(address); } public boolean addDevice(T device) { T cachedDev = addressMap.get(device.getAddress()); if (cachedDev == null) { log.fine("adding device to cache: " + device.getAddress()); return (addressMap.put(device.getAddress(), device) != null); } else if (device == cachedDev) { log.fine("device already in cache: " + device.getAddress()); return true; } else { throw new RuntimeException("two different instances of the same device found!"); } } public Integer addDevices(Set<? extends T> devices) { if (devices == null) { throw new IllegalArgumentException("devices must no be null"); } int counter = 0; for (T dev : devices) { if (addDevice(dev)) { counter++; } } return counter; } public Integer clearCache() { log.warning("CLEARING CACHE!"); Integer devices = addressMap.size(); addressMap.clear(); return devices; } public void removeDevice(String address) { if (address == null) { throw new IllegalArgumentException("address must no be null"); } addressMap.remove(address); log.log(Level.INFO, "Removed device " + address); } }
3,976
Java
.java
104
32.5
92
0.681381
ANierbeck/bcanhome-openhab
1
0
0
GPL-3.0
9/5/2024, 12:38:09 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,976
5,046,117
LocalOneCMDBConnection.java
luox12_onecmdb/org.onecmdb.graph/src/org/onecmdb/ml/graph/main/LocalOneCMDBConnection.java
/* * Lokomo OneCMDB - An Open Source Software for Configuration * Management of Datacenter Resources * * Copyright (C) 2006 Lokomo Systems AB * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * Lokomo Systems AB can be contacted via e-mail: info@lokomo.com or via * paper mail: Lokomo Systems AB, Svärdvägen 27, SE-182 33 * Danderyd, Sweden. * */ package org.onecmdb.ml.graph.main; import java.util.HashMap; import java.util.List; import org.onecmdb.core.utils.bean.CiBean; public class LocalOneCMDBConnection extends OneCMDBConnection { private HashMap<String, CiBean> aliasMap = new HashMap<String, CiBean>(); public void updateBeans(List<CiBean> beans) { for (CiBean bean : beans) { aliasMap.put(bean.getAlias(), bean); } } @Override public CiBean getBeanFromAlias(String alias) { CiBean bean = aliasMap.get(alias); if (bean != null) { return(bean); } try { setup(); } catch (Exception e) { } return super.getBeanFromAlias(alias); } }
1,733
Java
.java
50
30.96
75
0.728589
luox12/onecmdb
1
2
0
GPL-2.0
9/5/2024, 12:39:40 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,733
2,521,781
RightType.java
whirlplatform_whirl/whirl-app/whirl-app-shared/src/main/java/org/whirlplatform/meta/shared/editor/RightType.java
package org.whirlplatform.meta.shared.editor; import java.io.Serializable; public enum RightType implements Serializable { VIEW, ADD, EDIT, DELETE, EXECUTE, RESTRICT }
176
Java
.java
5
32.6
47
0.814371
whirlplatform/whirl
7
3
6
GPL-3.0
9/4/2024, 9:45:20 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
176
1,482,765
GnapCreditTests.java
globalpayments_java-sdk/src/test/java/com/global/api/tests/network/gnap/GnapCreditTests.java
package com.global.api.tests.network.gnap; import com.global.api.ServicesContainer; import com.global.api.entities.Address; import com.global.api.entities.EncryptionData; import com.global.api.network.entities.gnap.*; import com.global.api.entities.Transaction; import com.global.api.entities.enums.EntryMethod; import com.global.api.entities.enums.Target; import com.global.api.entities.exceptions.ApiException; import com.global.api.entities.exceptions.ConfigurationException; import com.global.api.network.enums.OperatingEnvironment; import com.global.api.network.enums.gnap.*; import com.global.api.paymentMethods.CreditCardData; import com.global.api.paymentMethods.CreditTrackData; import com.global.api.serviceConfigs.AcceptorConfig; import com.global.api.serviceConfigs.NetworkGatewayConfig; import com.global.api.tests.testdata.GnapTestCards; import org.junit.Test; import com.global.api.entities.enums.AccountType; import java.math.BigDecimal; public class GnapCreditTests { private AcceptorConfig acceptorConfig; private NetworkGatewayConfig config; private GnapMessageHeader gnapMessageHeader; private OptionalData optionalData; private GnapPosDetails posData; private TestUtil testUtil = TestUtil.getInstance(); private CreditTrackData track; private CreditCardData manual; private Address billingAdd; public GnapCreditTests() throws ConfigurationException { billingAdd=new Address("A1520 MAIN","YM5X1B1"); acceptorConfig = new AcceptorConfig(); acceptorConfig.setPinCapability(PINCapability.PINEntryCapable); acceptorConfig.setEmvCapable(true); //acceptorConfig.setPinPadSerialNumber("SERIAL02"); //acceptorConfig.setDeviceType("9."); // gateway config config = new NetworkGatewayConfig(Target.GNAP); config.setPrimaryEndpoint("scctesta.globalpaycan.com"); config.setPrimaryPort(443); config.setSecondaryEndpoint("mcctesta.globalpaycan.com"); config.setSecondaryPort(443); config.setTerminalId("711SDKT1"); config.setAcceptorConfig(acceptorConfig); config.setEnableLogging(true); gnapMessageHeader = GnapMessageHeader.builder() .transmissionNumber(String.format("%02d", testUtil.getTransmissionNo())) .messageSubType(MessageSubType.OnlineTransactions) .build(); posData = GnapPosDetails.builder() .cardHolderPresentIndicator(CardHolderPresentIndicator.CardHolderIsPresent) .cardPresentIndicator(CardPresentIndicator.CardPresent) .transactionStatusIndicator(TransactionStatusIndicator.NormalRequest) .transactionSecurityIndicator(TransactionSecurityIndicator.NoSecurityConcern) .cardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.NotACATTransaction) .cardholderIDMethod(CardHolderIDMethod.Signature) .build(); ServicesContainer.configureService(config); optionalData = OptionalData.builder() .terminalType(TerminalType.IntegratedSolutions) .integratedHardwareList(IntegratedHardwareList.BBP) .pinPadComm(PinPadCommunication.RS32) .integratedPinpadVersionType(IntegratedPinpadVersionType.BBPOS) .paymentSolutionProviderCode(PaymentSolutionProviderCode.Tender_Retail) .base24TransactionModifier(Base24TransactionModifier.OtherTransaction) .integratedPinPadVersion("3031") .pinPadSerialNumber("00WA123456") .pOSVARCode("711") .pOSVersionNO("123456789") .paymentSolutionVersionNO("123456789") .cAPKKeyVersion("1200") .tLSCiphers("0123456789") .build(); //-------------Visa track = new CreditTrackData(); track.setValue(";4761739001010119=22122011758909689?"); // //-------------MasterCard // track.setValue(";5413330089020029=2512201062980790?"); // //-------------Discover // track.setValue(";6011005612796527=2512201062980790?"); //-------------UnionPay // track.setValue(";6210948000000029=22122011758909689?"); // //-------------Amex // track.setValue(";372700699251018=22122011758909689?"); track.setEntryMethod(EntryMethod.MagneticStripeAndMSRFallback); //--------------Visa manual manual = new CreditCardData(); manual.setNumber("4761739001010119"); manual.setExpMonth(12); manual.setExpYear(2025); manual.setCvn("123"); manual.setCardPresent(true); manual.setReaderPresent(true); // //--------------Amex manual // manual.setValue("M372700699251018=12250?"); // //--------------MasterCard manual // manual.setValue("M5413330089020029=2512?"); // //--------------MasterCard manual // manual.setValue("M6210948000000029=2512?"); } //Credit Card Swiped Financial Transaction Request Message @Test public void test_1101_CreditCardSwipedFinancialPurchase() throws ApiException { GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = track.charge(new BigDecimal(1)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //Credit Card Manual Entry Financial Transaction Request Message @Test public void test_1102_CreditCardManualEntryFinancialPurchase() throws ApiException { acceptorConfig.setPinCapability(PINCapability.NoPINEntryCapability); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English).posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.charge(new BigDecimal(3)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //Credit Card Manual Entry Financial Transaction Request Message with CVV @Test public void test_1103_CreditCardManualEntryFinancialPurchaseWithCVV() throws ApiException { acceptorConfig.setPinCapability(PINCapability.NoPINEntryCapability); posData.setCardholderIDMethod(CardHolderIDMethod.PIN); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .cardPresenceIndicator(CardIdentifierPresenceIndicator.CVDORCIDValueIsPresent) .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English).posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.charge(BigDecimal.valueOf(1.35)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void test_1106_VisaMSR_PreAuthorizationCancellation() throws ApiException { track = GnapTestCards.VisaTrack2(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.SelfServiceTerminal); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .gnapProdSubFids(prodSubFids) .build(); Transaction response = track.authorize(new BigDecimal(10)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); posData.setTransactionStatusIndicator(TransactionStatusIndicator.NormalRequest); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction preAuthResponse = response.preAuthCompletion(new BigDecimal(0)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthResponse); } // Mastercard Zero Dollar Pre-Authorization Completion @Test public void test_1107_MastercardZeroDollarPreAuthorizationCompletion() throws ApiException { track = GnapTestCards.MCTrack2(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.ElectronicCashRegisterInterfaceIntegrated) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preAuthResponse = track.authorize(new BigDecimal(5)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthResponse); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preAuthResponse.preAuthCompletion(new BigDecimal(0)) .withGnapRequestData(gnapData) .withCurrency("USD") .execute(); testUtil.assertSuccess(response); } //Cash-Point Request Message - Credit Purchase Void @Test public void AX_MSR_SV_14() throws ApiException { track=GnapTestCards.testCard13_MSR(); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); optionalData.setEmployeeID("03"); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .optionalData(optionalData) .sequenceNumber(testUtil.getSequenceNumber()) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = track.charge(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); gnapData.setInvoiceNumber("V100012"); gnapData.setOptionalData(optionalData); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preResponse.voidTransaction(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //Cash-Point Request Message - Credit Purchase Void Manual @Test public void test_1115_Manual_CashPointCreditPurchaseVoidTransaction() throws ApiException { posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .optionalData(optionalData) .sequenceNumber(testUtil.getSequenceNumber()) .gnapProdSubFids(prodSubFids).build(); Transaction preResponse = manual.charge(new BigDecimal(3)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setInvoiceNumber("V100012"); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); optionalData.setEmployeeID("03"); gnapData.setOptionalData(optionalData); Transaction response = preResponse.voidTransaction(new BigDecimal(3)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //Cash-Point Request Message - Credit Merchandise Return Void MSR @Test public void MC_MSR_RV_08() throws ApiException { track=GnapTestCards.testCard6_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = track.refund(new BigDecimal(2.06)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setOptionalData(optionalData); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); Transaction response = preResponse.voidTransaction(new BigDecimal(2.06)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //Cash-Point Request Message - Credit Merchandise Return Void Manual @Test public void VI_MNL_RV11() throws ApiException { manual =GnapTestCards.testCard2_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .gnapProdSubFids(prodSubFids) .optionalData(optionalData) .build(); Transaction preResponse = manual.refund(new BigDecimal(2.09)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setOptionalData(optionalData); Transaction response = preResponse.voidTransaction(new BigDecimal(2.09)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //Cash-Point Request Message - Credit Merchandise Return @Test public void VI_MSR_RE_09() throws ApiException { track=GnapTestCards.testCard1_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.refund(new BigDecimal(2.09)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } // Cash-Point Request Message - Credit Merchandise Return @Test public void MC_MNL_RE_06() throws ApiException { manual =GnapTestCards.testCard6_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.refund(new BigDecimal(2.06)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } // EMV Request Message - Credit Online Purchase @Test public void test_1119_EMVOnlinePurchaseFallback() throws ApiException { track.setEntryMethod(EntryMethod.TechnicalFallback); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.charge(new BigDecimal(1.35)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //Cash-Point Request Message - Telephone Authorized Purchase @Test public void VI_RP_01() throws ApiException { manual.setNumber("4501161107217214"); manual.setExpYear(2025); manual.setExpMonth(07); gnapMessageHeader.setTransactionCode(TransactionCode.TelephoneAuthPurchase); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .approvalCode("123456") .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.charge(new BigDecimal(6.01)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } // Fully approved transaction with Ledger balance passed back from issuer @Test public void test_1501_MCMSR_LedgerBalancePassedPartialAuth() throws ApiException { track = GnapTestCards.MCTrack2(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids gnapProdSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(gnapProdSubFids) .build(); Transaction response = track.authorize(new BigDecimal(2)) .withGnapRequestData(gnapData) .withCurrency("USD") .execute(); testUtil.assertSuccess(response); } //Fully approved transaction with Ledger balance and available balance pass back from issuer @Test public void test_1502_MCMSR_LedgerAndAvailableBalancePassedPartialAuth() throws ApiException { track = GnapTestCards.MCTrack2(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids gnapProdSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(gnapProdSubFids) .build(); Transaction response = track.authorize(new BigDecimal(2)) .withGnapRequestData(gnapData) .withCurrency("USD") .execute(); testUtil.assertSuccess(response); } //Partially approved transaction with Original amount pass back from issuer @Test public void test_1503_MCMSR_PartialApproveWithriginalAmount() throws ApiException { track = GnapTestCards.MCTrack2(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids gnapProdSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(gnapProdSubFids) .build(); Transaction response = track.authorize(new BigDecimal(9.99)) .withGnapRequestData(gnapData) .withCurrency("USD") .execute(); testUtil.assertSuccess(response); } //Partially approved transaction with Original amount and Ledger Balance pass back from issuer @Test public void test_1504_MCMSR_PartialApproveWithOriginalAndLedgerBalance() throws ApiException { track = GnapTestCards.MCTrack2(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids gnapProdSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(gnapProdSubFids) .build(); Transaction response = track.authorize(new BigDecimal(9.99)) .withGnapRequestData(gnapData) .withCurrency("USD") .execute(); testUtil.assertSuccess(response); } /* Partially approved transaction with Original amount and Ledger and Available Balances pass back from issuer (only Original amount and Ledger balance is pass back to terminal)*/ @Test public void test_1505_MCMSR_PartialApprovalWithOnlyOriginalAmountAndLedgerBalancePassedBack() throws ApiException { track = GnapTestCards.MCTrack2(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids gnapProdSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .posConditionCode(POSConditionCode.StandAloneTerminal) .languageCode(LanguageCode.English) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(gnapProdSubFids) .build(); Transaction response = track.authorize(new BigDecimal(9.99)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //Visa Online Card Present Manually Keyed Refund Request @Test public void test_1601_VisaManual_KeyedOnlineRefund() throws ApiException { manual = GnapTestCards.visaManualCard(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preResponse = manual.refund(new BigDecimal(4)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } @Test public void test_1601_VisaMSR_KeyedOnlineRefund() throws ApiException { track = GnapTestCards.VisaTrack2(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preResponse = track.refund(new BigDecimal(15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } // MC Online Card Present Manually Keyed Refund Request @Test public void test_1602_MCManual_KeyedOnlineRefund() throws ApiException { manual = GnapTestCards.MCManualCard(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preResponse = manual.refund(new BigDecimal(15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } // Discover Online Card Present Manually Keyed Refund Request @Test public void test_1603_DiscoverManual_KeyedOnlineRefund() throws ApiException { manual = GnapTestCards.discoverManualCard(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preResponse = manual.refund(new BigDecimal(15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } //Contact MSR Card Present Online Refund FULL Amount VOID (Visa) @Test public void test_1607_VisaMSR_ContactMSRCardPresentOnlineRefundFULLAmountVOID() throws ApiException { track = GnapTestCards.VisaTrack2(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.refund(new BigDecimal(15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction preResponse = response.voidTransaction(new BigDecimal(15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } //Contact Manual Card Present Online Refund FULL Amount VOID (Visa) @Test public void test_1607_VisaManual_ContactManualCardPresentOnlineRefundFULLAmountVOID() throws ApiException { manual = GnapTestCards.visaManualCard(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.refund(new BigDecimal(15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction preResponse = response.voidTransaction(new BigDecimal(15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } //Contact MSR Card Present Online Refund FULL Amount VOID (Visa) @Test public void test_1608_VisaMSR_OnlineRefundPartialAmountVoid() throws ApiException { track = GnapTestCards.VisaTrack2(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.refund(new BigDecimal(10)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); response.getTransactionReference().setOriginalApprovedAmount(BigDecimal.valueOf(9)); Transaction preResponse = response.voidTransaction(new BigDecimal(10)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } //Contact Manual Card Present Online Refund Partial Amount VOID (Visa) @Test public void test_1608_VisaManual_OnlineRefundPartialAmountVoid() throws ApiException { manual = GnapTestCards.visaManualCard(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.refund(new BigDecimal(15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); response.getTransactionReference().setOriginalApprovedAmount(BigDecimal.valueOf(9)); Transaction preResponse = response.voidTransaction(new BigDecimal(15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } //Visa MSR Online Refund Request @Test public void test_1611_VisaMSR_OnlineRefundRequest() throws ApiException { track = GnapTestCards.VisaTrack2(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preResponse = track.refund(new BigDecimal(2)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } //Online Purchase Full void Request Message @Test public void MC_MSR_SV_08() throws ApiException { track=GnapTestCards.testCard6_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = track.charge(new BigDecimal(2.06)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preResponse.voidTransaction(new BigDecimal(2.06)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //Manually Keyed Online Purchase Full void Request Message @Test public void test_1702_Manual_OnlinePurchaseVoidTransaction() throws ApiException { posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = manual.charge(new BigDecimal(10)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preResponse.voidTransaction(new BigDecimal(10)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //Manually Keyed Online Purchase Request Message - Discover @Test public void DI_MNL_SA_15() throws ApiException { manual=GnapTestCards.testCard15_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preResponse = manual.charge(new BigDecimal(2.15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } //Manually Keyed Online Purchase Full void Request Message - Discover @Test public void DI_MSR_SV_16() throws ApiException { track=GnapTestCards.testCard15_MSR(); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .gnapProdSubFids(prodSubFids) .optionalData(optionalData).build(); Transaction preResponse = track.charge(new BigDecimal(2.15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); Transaction response = preResponse.voidTransaction(new BigDecimal(2.15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //Manually Keyed Partial void Request Message - Visa @Test public void test_1707_ManuallyKeyedPartialVoidTransaction() throws ApiException { posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .gnapProdSubFids(prodSubFids) .optionalData(optionalData).build(); Transaction preResponse = manual.charge(new BigDecimal(1)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); preResponse.getTransactionReference().setOriginalApprovedAmount(BigDecimal.valueOf(0.9)); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); Transaction response = preResponse.voidTransaction(new BigDecimal(1)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } // Online Purchase Partial void Request Message - Discover @Test public void test_1708_Discover_ManualOnlinePurchasePartialVoid() throws ApiException { manual = GnapTestCards.discoverManualCard(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .gnapProdSubFids(prodSubFids) .optionalData(optionalData).build(); Transaction preResponse = manual.charge(new BigDecimal(0.9)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); preResponse.getTransactionReference().setOriginalApprovedAmount(BigDecimal.valueOf(0.9)); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); Transaction response = preResponse.voidTransaction(new BigDecimal(1)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //Full Online Purchase void Timeout Reversal Request Message @Test public void MC_MSR_SV_08_TO() throws ApiException { track = GnapTestCards.testCard6_MSR(); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .gnapProdSubFids(prodSubFids) .optionalData(optionalData).build(); Transaction preResponse = track.charge(new BigDecimal(12.08)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setMessageSubType(MessageSubType.TimeoutReversalOnlineTransaction); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); Transaction response = preResponse.reverse(new BigDecimal(12.08)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //Partial Online Purchase void Timeout Reversal Request Message @Test public void test_1711_PartialOnlinePurchaseVoidTimeoutReversal() throws ApiException { GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = track.charge(new BigDecimal(1)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setMessageSubType(MessageSubType.TimeoutReversalOnlineTransaction); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); preResponse.getTransactionReference().setOriginalApprovedAmount(BigDecimal.valueOf(0.9)); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); Transaction response = preResponse.voidTransaction(new BigDecimal(1)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //working @Test public void test_1801_UnionPayMSR_Purchase() throws ApiException { track = GnapTestCards.UnionPayTrack2(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .accountType(AccountType.Savings) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = track.charge(new BigDecimal(1)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //working @Test public void test_1801_UnionPayManual_Purchase() throws ApiException { manual = GnapTestCards.UnionPayManual(); posData.setCardholderIDMethod(CardHolderIDMethod.PIN); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .accountType(AccountType.Savings) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.charge(new BigDecimal(1)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void test_1802_UnionPayMSRPurchase_Cancellation() throws ApiException { track = GnapTestCards.UnionPayTrack2(); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .accountType(AccountType.Savings) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .gnapProdSubFids(prodSubFids) .build(); optionalData.setEmployeeID("03"); gnapData.setOptionalData(optionalData); Transaction preResponse = track.charge(new BigDecimal(1)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setMessageSubType(MessageSubType.OnlineTransactions); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setInvoiceNumber("V100012"); gnapData.setOptionalData(optionalData); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preResponse.voidTransaction(new BigDecimal(1)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void test_1803_UnionPayMSR_AuthorizationPurchase() throws ApiException { track = GnapTestCards.UnionPayTrack2(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.SelfServiceTerminal); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .accountType(AccountType.Savings) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = track.authorize(new BigDecimal(5)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void test_1804_UnionPayMSR_PreAuthorizationCompletion() throws ApiException { track = GnapTestCards.UnionPayTrack2(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .accountType(AccountType.Savings) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData).build(); Transaction preAuthResponse = track.authorize(new BigDecimal(45)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthResponse); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setOptionalData(optionalData); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); Transaction response = preAuthResponse.preAuthCompletion(new BigDecimal(4)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void test_1805_UnionPayMSR_PreAuthorizationCancellation() throws ApiException { track = GnapTestCards.UnionPayTrack2(); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.SelfServiceTerminal); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .accountType(AccountType.Savings) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preAuthResponse = track.authorize(new BigDecimal(4)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthResponse); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setOptionalData(optionalData); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preAuthResponse.preAuthCompletion(new BigDecimal(0)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void test_1806_UnionPay_ManualRefund() throws ApiException { manual = GnapTestCards.UnionPayManual(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .accountType(AccountType.Savings) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .gnapProdSubFids(prodSubFids) .optionalData(optionalData).build(); Transaction preResponse = manual.refund(new BigDecimal(15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } @Test public void test_JcbManual_Purchase() throws ApiException { manual = GnapTestCards.JCBManual(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English).posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.charge(new BigDecimal(3)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void test_JcbMSR_Purchase() throws ApiException { track=GnapTestCards.JCBTrack2(); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = track.charge(new BigDecimal(1)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void test_JcbMSR_Preauthorization() throws ApiException { track=GnapTestCards.JCBTrack2(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.SelfServiceTerminal); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.ElectronicCashRegisterInterfaceIntegrated) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.authorize(new BigDecimal(10)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void test_JcbMSR_PreauthCompletion() throws ApiException{ track=GnapTestCards.JCBTrack2(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.SelfServiceTerminal); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.ElectronicCashRegisterInterfaceIntegrated) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preAuthResponse = track.authorize(new BigDecimal(10)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthResponse); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); posData.setTransactionStatusIndicator(TransactionStatusIndicator.NormalRequest); Transaction response = preAuthResponse.preAuthCompletion(new BigDecimal(10)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void test_JcbMSR_CreditPurchaseVoid() throws ApiException { track=GnapTestCards.JCBTrack2(); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .gnapProdSubFids(prodSubFids) .build(); optionalData.setEmployeeID("03"); gnapData.setOptionalData(optionalData); Transaction preResponse = track.charge(new BigDecimal(1)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setInvoiceNumber("V100012"); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); Transaction response = preResponse.voidTransaction(new BigDecimal(1)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void test_JcbMSR_Return() throws ApiException { track=GnapTestCards.JCBTrack2(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .invoiceNumber("R10032") .approvalCode("12501R") .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .gnapProdSubFids(prodSubFids) .build(); optionalData.setBase24TransactionModifier(Base24TransactionModifier.VoidTransactions); gnapData.setOptionalData(optionalData); Transaction response = track.refund(new BigDecimal(100)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void MC_MNL_SA_06() throws ApiException { manual =GnapTestCards.testCard6_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.charge(new BigDecimal(2.06)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MSR_SA_09() throws ApiException { track=GnapTestCards.testCard2_MSR(); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = track.charge(new BigDecimal(2.09)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MNL_SV_11() throws ApiException { manual = GnapTestCards.testCard2_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = track.charge(new BigDecimal(2.09)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preResponse.voidTransaction(new BigDecimal(2.09)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MNL_SA_12() throws ApiException { manual=GnapTestCards.testCard13_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.charge(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void DI_MNL_RE_15() throws ApiException { manual=GnapTestCards.testCard15_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.refund(new BigDecimal(2.15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void DI_MSR_RV_16() throws ApiException { track=GnapTestCards.testCard15_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = track.refund(new BigDecimal(2.15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setOptionalData(optionalData); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); Transaction response = preResponse.voidTransaction(new BigDecimal(2.15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MSR_RV_14() throws ApiException { track=GnapTestCards.testCard13_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .approvalCode("12501R") .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = track.refund(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setOptionalData(optionalData); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); Transaction response = preResponse.voidTransaction(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MNL_RE_12() throws ApiException { manual=GnapTestCards.testCard13_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .approvalCode("12501R") .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.refund(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void MC_MSR_SA_06() throws ApiException { track =GnapTestCards.testCard6_MSR(); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = track.charge(new BigDecimal(2.06)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void MC_MNL_SV_08() throws ApiException { manual=GnapTestCards.testCard6_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = manual.charge(new BigDecimal(2.06)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preResponse.voidTransaction(new BigDecimal(2.06)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MNL_SA_09() throws ApiException { manual=GnapTestCards.testCard2_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.charge(new BigDecimal(2.09)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MSR_SV_11() throws ApiException { track= GnapTestCards.testCard2_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = track.charge(new BigDecimal(2.09)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preResponse.voidTransaction(new BigDecimal(2.09)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MSR_SA_12() throws ApiException { track=GnapTestCards.testCard13_MSR(); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = track.charge(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MNL_SV_14() throws ApiException { manual=GnapTestCards.testCard13_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); optionalData.setEmployeeID("03"); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .optionalData(optionalData) .sequenceNumber(testUtil.getSequenceNumber()) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = manual.charge(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); gnapData.setInvoiceNumber("V100012"); gnapData.setOptionalData(optionalData); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preResponse.voidTransaction(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void DI_MSR_SA_15() throws ApiException { track=GnapTestCards.testCard15_MSR(); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preResponse = track.charge(new BigDecimal(2.15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } @Test public void DI_MNL_SV_16() throws ApiException { manual=GnapTestCards.testCard15_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .gnapProdSubFids(prodSubFids) .optionalData(optionalData).build(); Transaction preResponse = manual.charge(new BigDecimal(2.15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); Transaction response = preResponse.voidTransaction(new BigDecimal(2.15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void MC_MSR_RE_06() throws ApiException { track=GnapTestCards.testCard6_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.refund(new BigDecimal(2.06)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void MC_MNL_RV_08() throws ApiException { manual=GnapTestCards.testCard6_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = manual.refund(new BigDecimal(2.06)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setOptionalData(optionalData); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); Transaction response = preResponse.voidTransaction(new BigDecimal(2.06)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MNL_RE_09() throws ApiException { manual=GnapTestCards.testCard1_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.refund(new BigDecimal(2.09)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MSR_RV11() throws ApiException { track=GnapTestCards.testCard2_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .gnapProdSubFids(prodSubFids) .optionalData(optionalData) .build(); Transaction preResponse = track.refund(new BigDecimal(2.09)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setOptionalData(optionalData); Transaction response = preResponse.voidTransaction(new BigDecimal(2.09)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MSR_RE_12() throws ApiException { track=GnapTestCards.testCard13_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .approvalCode("12501R") .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.refund(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MNL_RV_14() throws ApiException { manual=GnapTestCards.testCard13_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .approvalCode("12501R") .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = manual.refund(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setOptionalData(optionalData); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); Transaction response = preResponse.voidTransaction(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void DI_MSR_RE_15() throws ApiException { track=GnapTestCards.testCard15_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.refund(new BigDecimal(2.15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void DI_MNL_RV_16() throws ApiException { manual=GnapTestCards.testCard15_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = manual.refund(new BigDecimal(2.15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setOptionalData(optionalData); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); Transaction response = preResponse.voidTransaction(new BigDecimal(2.15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //--------------------------------------Pump Transactions---------------------------------------- //Note:POS condition code always 27 for pay at pump transactions. @Test public void DI_MNL_PA_05() throws ApiException { manual=GnapTestCards.testCard15_MNL(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.AutomatedDispensingMachineWithPIN); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.authorize(new BigDecimal(17)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void DI_MSR_PA_05() throws ApiException { track=GnapTestCards.testCard15_MSR(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.AutomatedDispensingMachineWithPIN); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = track.authorize(new BigDecimal(17)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void DI_MNL_PC_06() throws ApiException { manual= GnapTestCards.testCard15_MNL(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.AutomatedDispensingMachineWithPIN); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preAuthResponse = manual.authorize(new BigDecimal(17)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthResponse); posData.setTransactionStatusIndicator(TransactionStatusIndicator.NormalRequest); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setOptionalData(optionalData); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preAuthResponse.preAuthCompletion(new BigDecimal(15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void DI_MSR_PC_06() throws ApiException { track= GnapTestCards.testCard15_MSR(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.AutomatedDispensingMachineWithPIN); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preAuthResponse = track.authorize(new BigDecimal(17)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthResponse); posData.setTransactionStatusIndicator(TransactionStatusIndicator.NormalRequest); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setOptionalData(optionalData); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preAuthResponse.preAuthCompletion(new BigDecimal(15)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MNL_PA_07() throws ApiException { manual=GnapTestCards.testCard1_MNL(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.AutomatedDispensingMachineWithPIN); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.authorize(new BigDecimal(40.20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MSR_PA_07() throws ApiException { track=GnapTestCards.testCard1_MSR(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.AutomatedDispensingMachineWithPIN); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = track.authorize(new BigDecimal(40.20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MNL_PC_08() throws ApiException { manual= GnapTestCards.testCard1_MNL(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.AutomatedDispensingMachineWithPIN); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preAuthResponse = manual.authorize(new BigDecimal(40.20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthResponse); posData.setTransactionStatusIndicator(TransactionStatusIndicator.NormalRequest); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setOptionalData(optionalData); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preAuthResponse.preAuthCompletion(new BigDecimal(40)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MSR_PC_08() throws ApiException { track= GnapTestCards.testCard1_MSR(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.AutomatedDispensingMachineWithPIN); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preAuthResponse = track.authorize(new BigDecimal(40.20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthResponse); posData.setTransactionStatusIndicator(TransactionStatusIndicator.NormalRequest); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setOptionalData(optionalData); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preAuthResponse.preAuthCompletion(new BigDecimal(40)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void MC_MNL_PA_09() throws ApiException { manual=GnapTestCards.testCard5_MNL(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.AutomatedDispensingMachineWithPIN); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.authorize(new BigDecimal(20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void MC_MSR_PA_09() throws ApiException { track=GnapTestCards.testCard5_MSR(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.AutomatedDispensingMachineWithPIN); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = track.authorize(new BigDecimal(20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void MC_MNL_PC_10() throws ApiException { manual= GnapTestCards.testCard5_MNL(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.AutomatedDispensingMachineWithPIN); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preAuthResponse = manual.authorize(new BigDecimal(20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthResponse); posData.setTransactionStatusIndicator(TransactionStatusIndicator.NormalRequest); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setOptionalData(optionalData); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preAuthResponse.preAuthCompletion(new BigDecimal(20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void MC_MSR_PC_10() throws ApiException { track= GnapTestCards.testCard5_MSR(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.AutomatedDispensingMachineWithPIN); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preAuthResponse = track.authorize(new BigDecimal(20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthResponse); posData.setTransactionStatusIndicator(TransactionStatusIndicator.NormalRequest); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setOptionalData(optionalData); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preAuthResponse.preAuthCompletion(new BigDecimal(20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MNL_PA_11() throws ApiException { manual=GnapTestCards.testCard13_MNL(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.AutomatedDispensingMachineWithPIN); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.authorize(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MSR_PA_11() throws ApiException { track=GnapTestCards.testCard13_MSR(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.AutomatedDispensingMachineWithPIN); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = track.authorize(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MNL_PC_13() throws ApiException { manual= GnapTestCards.testCard13_MNL(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.AutomatedDispensingMachineWithPIN); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.authorize(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); posData.setTransactionStatusIndicator(TransactionStatusIndicator.NormalRequest); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction preResponse = response.preAuthCompletion(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } @Test public void AX_MSR_PC_13() throws ApiException { track= GnapTestCards.testCard13_MSR(); posData.setTransactionStatusIndicator(TransactionStatusIndicator.PreAuthorizationRequest); posData.setCardholderActivatedTerminalIndicator(CardholderActivatedTerminalIndicator.AutomatedDispensingMachineWithPIN); posData.setCardholderIDMethod(CardHolderIDMethod.UnattendedTerminal); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.UnattendedTerminalUnableToRetainCard) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.authorize(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); posData.setTransactionStatusIndicator(TransactionStatusIndicator.NormalRequest); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction preResponse = response.preAuthCompletion(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } //--------------------Pump end------------------------------------------ @Test public void MC_RP_02() throws ApiException { manual.setNumber("5194419000000007"); manual.setExpYear(2025); manual.setExpMonth(07); gnapMessageHeader.setTransactionCode(TransactionCode.TelephoneAuthPurchase); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .approvalCode("78945RT") .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.charge(new BigDecimal(6.02)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MNL_RP_03() throws ApiException { manual=GnapTestCards.testCard1_MNL(); gnapMessageHeader.setTransactionCode(TransactionCode.TelephoneAuthPurchase); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .approvalCode("ASD456") .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.charge(new BigDecimal(6.03)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MSR_RP_03() throws ApiException { track=GnapTestCards.testCard1_MSR(); gnapMessageHeader.setTransactionCode(TransactionCode.TelephoneAuthPurchase); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .approvalCode("ASD456") .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = track.charge(new BigDecimal(6.03)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void MC_MNL_RP_04() throws ApiException { manual=GnapTestCards.testCard6_MNL(); gnapMessageHeader.setTransactionCode(TransactionCode.TelephoneAuthPurchase); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .approvalCode("ASD456") .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.charge(new BigDecimal(20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void MC_MSR_RP_04() throws ApiException { track=GnapTestCards.testCard6_MSR(); gnapMessageHeader.setTransactionCode(TransactionCode.TelephoneAuthPurchase); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .approvalCode("ASD456") .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = track.charge(new BigDecimal(20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void DC_MNL_RP_05() throws ApiException { manual=GnapTestCards.testCard15_MNL(); gnapMessageHeader.setTransactionCode(TransactionCode.TelephoneAuthPurchase); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .approvalCode("ASD456") .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.charge(new BigDecimal(180)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void DC_MSR_RP_05() throws ApiException { track=GnapTestCards.testCard15_MSR(); gnapMessageHeader.setTransactionCode(TransactionCode.TelephoneAuthPurchase); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .approvalCode("ASD456") .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = track.charge(new BigDecimal(180)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MNL_RP_06() throws ApiException { manual=GnapTestCards.testCard13_MNL(); gnapMessageHeader.setTransactionCode(TransactionCode.TelephoneAuthPurchase); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .approvalCode("ASD456") .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.charge(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MSR_RP_06() throws ApiException { track=GnapTestCards.testCard13_MSR(); gnapMessageHeader.setTransactionCode(TransactionCode.TelephoneAuthPurchase); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .approvalCode("ASD456") .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = track.charge(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MNL_RPV_07() throws ApiException { manual=GnapTestCards.testCard1_MNL(); gnapMessageHeader.setTransactionCode(TransactionCode.TelephoneAuthPurchase); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .approvalCode("ASD456") .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = manual.charge(new BigDecimal(6.03)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); optionalData.setEmployeeID("03"); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preResponse.voidTransaction(new BigDecimal(6.03)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MSR_RPV_07() throws ApiException { track=GnapTestCards.testCard1_MSR(); gnapMessageHeader.setTransactionCode(TransactionCode.TelephoneAuthPurchase); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .approvalCode("ASD456") .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = track.charge(new BigDecimal(6.03)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); optionalData.setEmployeeID("03"); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preResponse.voidTransaction(new BigDecimal(6.03)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void MC_MNL_RPV_08() throws ApiException { manual=GnapTestCards.testCard6_MNL(); gnapMessageHeader.setTransactionCode(TransactionCode.TelephoneAuthPurchase); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .approvalCode("ASD456") .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = manual.charge(new BigDecimal(20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); optionalData.setEmployeeID("03"); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preResponse.voidTransaction(new BigDecimal(20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void MC_MSR_RPV_08() throws ApiException { track=GnapTestCards.testCard6_MSR(); gnapMessageHeader.setTransactionCode(TransactionCode.TelephoneAuthPurchase); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .approvalCode("ASD456") .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = track.charge(new BigDecimal(20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); optionalData.setEmployeeID("03"); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preResponse.voidTransaction(new BigDecimal(20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MNL_RPV_09() throws ApiException { manual=GnapTestCards.testCard13_MNL(); gnapMessageHeader.setTransactionCode(TransactionCode.TelephoneAuthPurchase); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .approvalCode("ASD456") .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = manual.charge(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); optionalData.setEmployeeID("03"); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preResponse.voidTransaction(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MSR_RPV_09() throws ApiException { track=GnapTestCards.testCard13_MSR(); gnapMessageHeader.setTransactionCode(TransactionCode.TelephoneAuthPurchase); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .approvalCode("ASD456") .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction preResponse = track.charge(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); optionalData.setEmployeeID("03"); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); Transaction response = preResponse.voidTransaction(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_SA_01() throws ApiException { manual.setNumber("4761739001010119"); manual.setExpYear(2019); manual.setExpMonth(12); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.charge(new BigDecimal(2.09)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void MC_SA_02() throws ApiException { manual.setNumber("5413330089604111"); manual.setExpYear(2019); manual.setExpMonth(12); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids) .build(); Transaction response = manual.charge(new BigDecimal(2.09)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MSR_SV_08_TO() throws ApiException { track = GnapTestCards.testCard13_MSR(); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .gnapProdSubFids(prodSubFids) .optionalData(optionalData).build(); Transaction preResponse = track.charge(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); gnapMessageHeader.setMessageSubType(MessageSubType.TimeoutReversalOnlineTransaction); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); Transaction response = preResponse.reverse(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //Pre-Auth & completion @Test public void DI_MSR_PA_01() throws ApiException { track=GnapTestCards.testCard15_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.authorize(new BigDecimal(17)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void DI_MSR_PC_03() throws ApiException { track=GnapTestCards.testCard15_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.authorize(new BigDecimal(17)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); Transaction preAuthCom = response.preAuthCompletion(new BigDecimal(17)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthCom); } @Test public void DI_MNL_PA_01() throws ApiException { manual=GnapTestCards.testCard15_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.authorize(new BigDecimal(17)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void DI_MNL_PC_03() throws ApiException { manual=GnapTestCards.testCard15_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.authorize(new BigDecimal(17)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); Transaction preAuthCom = response.preAuthCompletion(new BigDecimal(17)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthCom); } @Test public void VI_MSR_PA_04() throws ApiException { track=GnapTestCards.testCard1_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.authorize(new BigDecimal(4.02)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MSR_PC_05() throws ApiException { track=GnapTestCards.testCard1_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.authorize(new BigDecimal(4.02)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); Transaction preAuthCom = response.preAuthCompletion(new BigDecimal(4.02)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthCom); } @Test public void VI_MSR_PCV_06() throws ApiException { track =GnapTestCards.testCard1_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preResponse = track.refund(new BigDecimal(4.02)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } // pre-auth full void @Test public void VI_MSR_PCV_07() throws ApiException { track=GnapTestCards.testCard1_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.authorize(new BigDecimal(4.02)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); Transaction preAuthCom = response.preAuthCompletion(new BigDecimal(0)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthCom); } @Test public void VI_MNL_PA_04() throws ApiException { manual=GnapTestCards.testCard1_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.authorize(new BigDecimal(4.02)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MNL_PC_05() throws ApiException { manual=GnapTestCards.testCard1_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.authorize(new BigDecimal(4.02)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); Transaction preAuthCom = response.preAuthCompletion(new BigDecimal(4.02)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthCom); } @Test public void VI_MNL_PCV_06() throws ApiException { manual =GnapTestCards.testCard1_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preResponse = manual.refund(new BigDecimal(4.0)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } // pre-auth full void @Test public void VI_MNL_PCV_07() throws ApiException { manual=GnapTestCards.testCard1_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.authorize(new BigDecimal(4.02)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); Transaction preAuthCom = response.preAuthCompletion(new BigDecimal(0)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthCom); } @Test public void MC_MSR_PA_08() throws ApiException { track=GnapTestCards.testCard5_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.authorize(new BigDecimal(20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //pre-auth full void @Test public void MC_MSR_PV_09() throws ApiException { track=GnapTestCards.testCard5_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.authorize(new BigDecimal(20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); Transaction preAuthCom = response.preAuthCompletion(new BigDecimal(0)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthCom); } @Test public void MC_MSR_PC_14() throws ApiException { track=GnapTestCards.testCard6_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.authorize(new BigDecimal(4.13)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); Transaction preAuthCom = response.preAuthCompletion(new BigDecimal(4.13)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthCom); } @Test public void MC_MSR_PCV_15() throws ApiException { track =GnapTestCards.testCard5_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preResponse = track.refund(new BigDecimal(4.13)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } @Test public void MC_MNL_PA_08() throws ApiException { manual=GnapTestCards.testCard5_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.authorize(new BigDecimal(20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } //pre-auth full void @Test public void MC_MNL_PV_09() throws ApiException { manual=GnapTestCards.testCard5_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.authorize(new BigDecimal(20)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); Transaction preAuthCom = response.preAuthCompletion(new BigDecimal(0)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthCom); } @Test public void MC_MNL_PC_14() throws ApiException { manual=GnapTestCards.testCard6_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.authorize(new BigDecimal(4.13)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); Transaction preAuthCom = response.preAuthCompletion(new BigDecimal(4.13)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthCom); } @Test public void MC_MNL_PCV_15() throws ApiException { manual =GnapTestCards.testCard5_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction preResponse = manual.refund(new BigDecimal(4.13)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preResponse); } @Test public void AX_MSR_PA_16() throws ApiException { track=GnapTestCards.testCard13_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.authorize(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MSR_PC_18() throws ApiException { track=GnapTestCards.testCard13_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.authorize(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); Transaction preAuthCom = response.preAuthCompletion(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthCom); } @Test public void AX_MNL_PA_16() throws ApiException { manual=GnapTestCards.testCard13_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.authorize(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void AX_MNL_PC_18() throws ApiException { manual=GnapTestCards.testCard13_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.authorize(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); Transaction preAuthCom = response.preAuthCompletion(new BigDecimal(39)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthCom); } @Test public void VI_MSR_PA_19() throws ApiException { track=GnapTestCards.testCard2_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.authorize(new BigDecimal(19)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MSR_PC_21() throws ApiException { track=GnapTestCards.testCard2_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.authorize(new BigDecimal(19)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); Transaction preAuthCom = response.preAuthCompletion(new BigDecimal(19)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthCom); } @Test public void VI_MNL_PA_19() throws ApiException { manual=GnapTestCards.testCard2_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.authorize(new BigDecimal(19)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MNL_PC_21() throws ApiException { manual=GnapTestCards.testCard2_MNL(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = manual.authorize(new BigDecimal(19)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); gnapMessageHeader.setTransmissionNumber(String.format("%02d", testUtil.getTransmissionNo())); gnapMessageHeader.setMessageSubType(MessageSubType.StoreAndForwardTransactions); gnapData.setSequenceNumber(testUtil.getSequenceNumber()); gnapData.setPosConditionCode(POSConditionCode.PreAuthCompletionRequest); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); Transaction preAuthCom = response.preAuthCompletion(new BigDecimal(19)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(preAuthCom); } @Test public void VI_MSR_SA() throws ApiException { track = GnapTestCards.testCard2_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Unknown); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); optionalData.setTerminalType(TerminalType.StandAloneOrSemiIntegratedSolutions); optionalData.setIntegratedHardwareList(IntegratedHardwareList.Unknown); optionalData.setTerminalSoftwareVersion("nnnn"); optionalData.setPinPadModel(PinPadModel.PINPad810); optionalData.setTerminalSerialNumber("000JA123456"); optionalData.setPinPadOSVersion("011A0"); optionalData.setPinPadSerialNumber("SERIAL02"); optionalData.setPinPadSoftwareVersion("523e"); optionalData.setTerminalSoftwareVersion(""); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.charge(new BigDecimal(5)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } @Test public void VI_MSR_PA() throws ApiException { track=GnapTestCards.testCard2_MSR(); posData.setCardholderIDMethod(CardHolderIDMethod.Signature); GnapProdSubFids prodSubFids = GnapProdSubFids.builder() .pointOfServiceData(posData) .build(); optionalData.setTerminalType(TerminalType.StandAloneOrSemiIntegratedSolutions); optionalData.setIntegratedHardwareList(IntegratedHardwareList.Unknown); optionalData.setTerminalSoftwareVersion("nnnn"); optionalData.setPinPadModel(PinPadModel.PINPad810); optionalData.setTerminalSerialNumber("000JA123456"); optionalData.setPinPadOSVersion("011A0"); optionalData.setPinPadSerialNumber("SERIAL02"); optionalData.setPinPadSoftwareVersion("523e"); optionalData.setTerminalSoftwareVersion(""); GnapRequestData gnapData = GnapRequestData.builder() .gnapMessageHeader(gnapMessageHeader) .languageCode(LanguageCode.English) .posConditionCode(POSConditionCode.StandAloneTerminal) .sequenceNumber(testUtil.getSequenceNumber()) .optionalData(optionalData) .gnapProdSubFids(prodSubFids).build(); Transaction response = track.authorize(new BigDecimal(19)) .withCurrency("USD") .withGnapRequestData(gnapData) .execute(); testUtil.assertSuccess(response); } }
183,378
Java
.java
3,609
38.152397
128
0.663799
globalpayments/java-sdk
24
39
17
GPL-2.0
9/4/2024, 7:53:37 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
183,378
2,442,872
AdvancementsProvider.java
Patbox_PolyDecorations/src/main/java/eu/pb4/polydecorations/datagen/AdvancementsProvider.java
package eu.pb4.polydecorations.datagen; import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput; import net.fabricmc.fabric.api.datagen.v1.provider.FabricAdvancementProvider; import net.minecraft.advancement.AdvancementEntry; import net.minecraft.registry.RegistryWrapper; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; class AdvancementsProvider extends FabricAdvancementProvider { protected AdvancementsProvider(FabricDataOutput output, CompletableFuture<RegistryWrapper.WrapperLookup> registryLookup) { super(output, registryLookup); } //@Override public void generateAdvancement(Consumer<AdvancementEntry> exporter) { /*var root = Advancement.Builder.create() .display( FactoryItems.WINDMILL_SAIL, Text.translatable("advancements.polyfactory.root.title"), Text.translatable("advancements.polyfactory.root.description"), id("textures/advancements/background.png"), AdvancementFrame.TASK, false, false, false ) .criterion("any_item", InventoryChangedCriterion.Conditions.items( ItemPredicate.Builder.create().tag(FactoryItemTags.ROOT_ADVANCEMENT) )) .build(exporter, "polyfactory:main/root"); */ } @Override public void generateAdvancement(RegistryWrapper.WrapperLookup registryLookup, Consumer<AdvancementEntry> consumer) { } }
1,623
Java
.java
34
36.352941
126
0.672785
Patbox/PolyDecorations
8
2
3
LGPL-3.0
9/4/2024, 9:26:53 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,623
3,868,402
VersionSettingsPage.java
Glavo_U1-Launcher/HMCL/src/main/java/org/jackhuang/hmcl/ui/versions/VersionSettingsPage.java
/* * Hello Minecraft! Launcher * Copyright (C) 2020 huangyuhui <huanghongxun2008@126.com> and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.jackhuang.hmcl.ui.versions; import com.jfoenix.controls.*; import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.beans.binding.Bindings; import javafx.beans.property.*; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.image.Image; import javafx.scene.layout.*; import javafx.scene.text.Text; import javafx.stage.FileChooser; import org.jackhuang.hmcl.game.*; import org.jackhuang.hmcl.setting.*; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; import org.jackhuang.hmcl.ui.Controllers; import org.jackhuang.hmcl.ui.FXUtils; import org.jackhuang.hmcl.ui.WeakListenerHolder; import org.jackhuang.hmcl.ui.construct.*; import org.jackhuang.hmcl.ui.decorator.DecoratorPage; import org.jackhuang.hmcl.util.Lang; import org.jackhuang.hmcl.util.Pair; import org.jackhuang.hmcl.util.javafx.BindingMapping; import org.jackhuang.hmcl.util.javafx.SafeStringConverter; import org.jackhuang.hmcl.util.platform.Architecture; import org.jackhuang.hmcl.util.platform.JavaVersion; import org.jackhuang.hmcl.util.platform.OperatingSystem; import org.jackhuang.hmcl.util.versioning.VersionNumber; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import static org.jackhuang.hmcl.ui.FXUtils.stringConverter; import static org.jackhuang.hmcl.util.Pair.pair; import static org.jackhuang.hmcl.util.i18n.I18n.i18n; public final class VersionSettingsPage extends StackPane implements DecoratorPage, VersionPage.VersionLoadable, PageAware { private final ReadOnlyObjectWrapper<State> state = new ReadOnlyObjectWrapper<>(new State("", null, false, false, false)); private final boolean globalSetting; private VersionSetting lastVersionSetting = null; private Profile profile; private WeakListenerHolder listenerHolder; private String versionId; private boolean javaItemsLoaded; private final VBox rootPane; private final JFXTextField txtWidth; private final JFXTextField txtHeight; private final JFXTextField txtJVMArgs; private final JFXTextField txtGameArgs; private final JFXTextField txtMetaspace; private final JFXTextField txtWrapper; private final JFXTextField txtPreLaunchCommand; private final JFXTextField txtPostExitCommand; private final JFXTextField txtServerIP; private final ComponentList componentList; private final JFXComboBox<LauncherVisibility> cboLauncherVisibility; private final JFXCheckBox chkAutoAllocate; private final JFXCheckBox chkFullscreen; private final OptionToggleButton noJVMArgsPane; private final OptionToggleButton noGameCheckPane; private final OptionToggleButton noJVMCheckPane; private final OptionToggleButton noNativesPatchPane; private final OptionToggleButton useSoftwareRenderer; private final OptionToggleButton useNativeGLFWPane; private final OptionToggleButton useNativeOpenALPane; private final ComponentSublist javaSublist; private final MultiFileItem<Pair<JavaVersionType, JavaVersion>> javaItem; private final MultiFileItem.Option<Pair<JavaVersionType, JavaVersion>> javaAutoDeterminedOption; private final MultiFileItem.FileOption<Pair<JavaVersionType, JavaVersion>> javaCustomOption; private final ComponentSublist gameDirSublist; private final MultiFileItem<GameDirectoryType> gameDirItem; private final MultiFileItem.FileOption<GameDirectoryType> gameDirCustomOption; private final ComponentSublist nativesDirSublist; private final MultiFileItem<NativesDirectoryType> nativesDirItem; private final MultiFileItem.FileOption<NativesDirectoryType> nativesDirCustomOption; private final JFXComboBox<ProcessPriority> cboProcessPriority; private final OptionToggleButton showLogsPane; private ImagePickerItem iconPickerItem; private final InvalidationListener specificSettingsListener; private final InvalidationListener javaListener = any -> initJavaSubtitle(); private final StringProperty selectedVersion = new SimpleStringProperty(); private final BooleanProperty navigateToSpecificSettings = new SimpleBooleanProperty(false); private final BooleanProperty enableSpecificSettings = new SimpleBooleanProperty(false); private final IntegerProperty maxMemory = new SimpleIntegerProperty(); private final ObjectProperty<OperatingSystem.PhysicalMemoryStatus> memoryStatus = new SimpleObjectProperty<>(OperatingSystem.PhysicalMemoryStatus.INVALID); private final BooleanProperty modpack = new SimpleBooleanProperty(); public VersionSettingsPage(boolean globalSetting) { this.globalSetting = globalSetting; ScrollPane scrollPane = new ScrollPane(); scrollPane.setFitToHeight(true); scrollPane.setFitToWidth(true); scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS); getChildren().setAll(scrollPane); rootPane = new VBox(); rootPane.setFillWidth(true); scrollPane.setContent(rootPane); FXUtils.smoothScrolling(scrollPane); rootPane.getStyleClass().add("card-list"); if (globalSetting) { HintPane skinHint = new HintPane(MessageDialogPane.MessageType.INFO); skinHint.setText(i18n("settings.skin")); rootPane.getChildren().add(skinHint); HintPane specificSettingsHint = new HintPane(MessageDialogPane.MessageType.WARNING); Text text = new Text(); text.textProperty().bind(BindingMapping.of(selectedVersion) .map(selectedVersion -> i18n("settings.type.special.edit.hint", selectedVersion))); JFXHyperlink specificSettingsLink = new JFXHyperlink(); specificSettingsLink.setText(i18n("settings.type.special.edit")); specificSettingsLink.setOnMouseClicked(e -> editSpecificSettings()); specificSettingsHint.setChildren(text, specificSettingsLink); specificSettingsHint.managedProperty().bind(navigateToSpecificSettings); specificSettingsHint.visibleProperty().bind(navigateToSpecificSettings); rootPane.getChildren().addAll(specificSettingsHint); } if (!globalSetting) { HintPane gameDirHint = new HintPane(MessageDialogPane.MessageType.INFO); gameDirHint.setText(i18n("settings.game.working_directory.hint")); rootPane.getChildren().add(gameDirHint); ComponentList iconPickerItemWrapper = new ComponentList(); rootPane.getChildren().add(iconPickerItemWrapper); iconPickerItem = new ImagePickerItem(); iconPickerItem.setImage(new Image("/assets/img/icon.png")); iconPickerItem.setTitle(i18n("settings.icon")); iconPickerItem.setOnSelectButtonClicked(e -> onExploreIcon()); iconPickerItem.setOnDeleteButtonClicked(e -> onDeleteIcon()); iconPickerItemWrapper.getContent().setAll(iconPickerItem); BorderPane settingsTypePane = new BorderPane(); settingsTypePane.disableProperty().bind(modpack); rootPane.getChildren().add(settingsTypePane); JFXCheckBox enableSpecificCheckBox = new JFXCheckBox(); enableSpecificCheckBox.selectedProperty().bindBidirectional(enableSpecificSettings); settingsTypePane.setLeft(enableSpecificCheckBox); enableSpecificCheckBox.setText(i18n("settings.type.special.enable")); BorderPane.setAlignment(enableSpecificCheckBox, Pos.CENTER_RIGHT); JFXButton editGlobalSettingsButton = FXUtils.newRaisedButton(i18n("settings.type.global.edit")); settingsTypePane.setRight(editGlobalSettingsButton); editGlobalSettingsButton.disableProperty().bind(enableSpecificCheckBox.selectedProperty()); BorderPane.setAlignment(editGlobalSettingsButton, Pos.CENTER_RIGHT); editGlobalSettingsButton.setOnMouseClicked(e -> editGlobalSettings()); } { componentList = new ComponentList(); componentList.setDepth(1); javaItem = new MultiFileItem<>(); javaSublist = new ComponentSublist(); javaSublist.getContent().add(javaItem); javaSublist.setTitle(i18n("settings.game.java_directory")); javaSublist.setHasSubtitle(true); javaAutoDeterminedOption = new MultiFileItem.Option<>(i18n("settings.game.java_directory.auto"), pair(JavaVersionType.AUTO, null)); javaCustomOption = new MultiFileItem.FileOption<Pair<JavaVersionType, JavaVersion>>(i18n("settings.custom"), pair(JavaVersionType.CUSTOM, null)) .setChooserTitle(i18n("settings.game.java_directory.choose")); gameDirItem = new MultiFileItem<>(); gameDirSublist = new ComponentSublist(); gameDirSublist.getContent().add(gameDirItem); gameDirSublist.setTitle(i18n("settings.game.working_directory")); gameDirSublist.setHasSubtitle(true); gameDirItem.disableProperty().bind(modpack); gameDirCustomOption = new MultiFileItem.FileOption<>(i18n("settings.custom"), GameDirectoryType.CUSTOM) .setChooserTitle(i18n("settings.game.working_directory.choose")) .setDirectory(true); gameDirItem.loadChildren(Arrays.asList( new MultiFileItem.Option<>(i18n("settings.advanced.game_dir.default"), GameDirectoryType.ROOT_FOLDER), new MultiFileItem.Option<>(i18n("settings.advanced.game_dir.independent"), GameDirectoryType.VERSION_FOLDER), gameDirCustomOption )); VBox maxMemoryPane = new VBox(8); { Label title = new Label(i18n("settings.memory")); VBox.setMargin(title, new Insets(0, 0, 8, 0)); chkAutoAllocate = new JFXCheckBox(i18n("settings.memory.auto_allocate")); VBox.setMargin(chkAutoAllocate, new Insets(0, 0, 8, 5)); HBox lowerBoundPane = new HBox(8); lowerBoundPane.setAlignment(Pos.CENTER); VBox.setMargin(lowerBoundPane, new Insets(0, 0, 0, 16)); { Label label = new Label(); label.textProperty().bind(Bindings.createStringBinding(() -> { if (chkAutoAllocate.isSelected()) { return i18n("settings.memory.lower_bound"); } else { return i18n("settings.memory"); } }, chkAutoAllocate.selectedProperty())); JFXSlider slider = new JFXSlider(0, 1, 0); HBox.setMargin(slider, new Insets(0, 0, 0, 8)); HBox.setHgrow(slider, Priority.ALWAYS); slider.setValueFactory(self -> Bindings.createStringBinding(() -> (int) (self.getValue() * 100) + "%", self.valueProperty())); AtomicBoolean changedByTextField = new AtomicBoolean(false); FXUtils.onChangeAndOperate(maxMemory, maxMemory -> { changedByTextField.set(true); slider.setValue(maxMemory.intValue() * 1.0 / OperatingSystem.TOTAL_MEMORY); changedByTextField.set(false); }); slider.valueProperty().addListener((value, oldVal, newVal) -> { if (changedByTextField.get()) return; maxMemory.set((int) (value.getValue().doubleValue() * OperatingSystem.TOTAL_MEMORY)); }); JFXTextField txtMaxMemory = new JFXTextField(); FXUtils.setLimitWidth(txtMaxMemory, 60); FXUtils.setValidateWhileTextChanged(txtMaxMemory, true); txtMaxMemory.textProperty().bindBidirectional(maxMemory, SafeStringConverter.fromInteger()); txtMaxMemory.setValidators(new NumberValidator(i18n("input.number"), false)); lowerBoundPane.getChildren().setAll(label, slider, txtMaxMemory, new Label("MB")); } StackPane progressBarPane = new StackPane(); progressBarPane.setAlignment(Pos.CENTER_LEFT); VBox.setMargin(progressBarPane, new Insets(8, 0, 0, 16)); { progressBarPane.setMinHeight(4); progressBarPane.getStyleClass().add("memory-total"); StackPane usedMemory = new StackPane(); usedMemory.getStyleClass().add("memory-used"); usedMemory.maxWidthProperty().bind(Bindings.createDoubleBinding(() -> progressBarPane.getWidth() * (memoryStatus.get().getUsed() * 1.0 / memoryStatus.get().getTotal()), progressBarPane.widthProperty(), memoryStatus)); StackPane allocateMemory = new StackPane(); allocateMemory.getStyleClass().add("memory-allocate"); allocateMemory.maxWidthProperty().bind(Bindings.createDoubleBinding(() -> progressBarPane.getWidth() * Math.min(1.0, (double) (HMCLGameRepository.getAllocatedMemory(maxMemory.get() * 1024L * 1024L, memoryStatus.get().getAvailable(), chkAutoAllocate.isSelected()) + memoryStatus.get().getUsed()) / memoryStatus.get().getTotal()), progressBarPane.widthProperty(), maxMemory, memoryStatus, chkAutoAllocate.selectedProperty())); progressBarPane.getChildren().setAll(allocateMemory, usedMemory); } BorderPane digitalPane = new BorderPane(); VBox.setMargin(digitalPane, new Insets(0, 0, 0, 16)); { Label lblPhysicalMemory = new Label(); lblPhysicalMemory.getStyleClass().add("memory-label"); digitalPane.setLeft(lblPhysicalMemory); lblPhysicalMemory.textProperty().bind(Bindings.createStringBinding(() -> { return i18n("settings.memory.used_per_total", memoryStatus.get().getUsedGB(), memoryStatus.get().getTotalGB()); }, memoryStatus)); Label lblAllocateMemory = new Label(); lblAllocateMemory.textProperty().bind(Bindings.createStringBinding(() -> { long maxMemory = Lang.parseInt(this.maxMemory.get(), 0) * 1024L * 1024L; return i18n(memoryStatus.get().hasAvailable() && maxMemory > memoryStatus.get().getAvailable() ? (chkAutoAllocate.isSelected() ? "settings.memory.allocate.auto.exceeded" : "settings.memory.allocate.manual.exceeded") : (chkAutoAllocate.isSelected() ? "settings.memory.allocate.auto" : "settings.memory.allocate.manual"), OperatingSystem.PhysicalMemoryStatus.toGigaBytes(maxMemory), OperatingSystem.PhysicalMemoryStatus.toGigaBytes(HMCLGameRepository.getAllocatedMemory(maxMemory, memoryStatus.get().getAvailable(), chkAutoAllocate.isSelected())), OperatingSystem.PhysicalMemoryStatus.toGigaBytes(memoryStatus.get().getAvailable())); }, memoryStatus, maxMemory, chkAutoAllocate.selectedProperty())); lblAllocateMemory.getStyleClass().add("memory-label"); digitalPane.setRight(lblAllocateMemory); } maxMemoryPane.getChildren().setAll(title, chkAutoAllocate, lowerBoundPane, progressBarPane, digitalPane); } BorderPane launcherVisibilityPane = new BorderPane(); { Label label = new Label(i18n("settings.advanced.launcher_visible")); launcherVisibilityPane.setLeft(label); BorderPane.setAlignment(label, Pos.CENTER_LEFT); cboLauncherVisibility = new JFXComboBox<>(); launcherVisibilityPane.setRight(cboLauncherVisibility); BorderPane.setAlignment(cboLauncherVisibility, Pos.CENTER_RIGHT); FXUtils.setLimitWidth(cboLauncherVisibility, 300); } BorderPane dimensionPane = new BorderPane(); { Label label = new Label(i18n("settings.game.dimension")); dimensionPane.setLeft(label); BorderPane.setAlignment(label, Pos.CENTER_LEFT); BorderPane right = new BorderPane(); dimensionPane.setRight(right); { HBox hbox = new HBox(); right.setLeft(hbox); hbox.setPrefWidth(210); hbox.setSpacing(3); hbox.setAlignment(Pos.CENTER); BorderPane.setAlignment(hbox, Pos.CENTER); { txtWidth = new JFXTextField(); txtWidth.setPromptText("800"); txtWidth.setPrefWidth(100); FXUtils.setValidateWhileTextChanged(txtWidth, true); txtWidth.getValidators().setAll(new NumberValidator(i18n("input.number"), false)); Label x = new Label("x"); txtHeight = new JFXTextField(); txtHeight.setPromptText("480"); txtHeight.setPrefWidth(100); FXUtils.setValidateWhileTextChanged(txtHeight, true); txtHeight.getValidators().setAll(new NumberValidator(i18n("input.number"), false)); hbox.getChildren().setAll(txtWidth, x, txtHeight); } chkFullscreen = new JFXCheckBox(); right.setRight(chkFullscreen); chkFullscreen.setText(i18n("settings.game.fullscreen")); chkFullscreen.setAlignment(Pos.CENTER); BorderPane.setAlignment(chkFullscreen, Pos.CENTER); BorderPane.setMargin(chkFullscreen, new Insets(0, 0, 0, 7)); } } showLogsPane = new OptionToggleButton(); showLogsPane.setTitle(i18n("settings.show_log")); BorderPane processPriorityPane = new BorderPane(); { Label label = new Label(i18n("settings.advanced.process_priority")); processPriorityPane.setLeft(label); BorderPane.setAlignment(label, Pos.CENTER_LEFT); cboProcessPriority = new JFXComboBox<>(); processPriorityPane.setRight(cboProcessPriority); BorderPane.setAlignment(cboProcessPriority, Pos.CENTER_RIGHT); FXUtils.setLimitWidth(cboProcessPriority, 300); } GridPane serverPane = new GridPane(); { ColumnConstraints title = new ColumnConstraints(); ColumnConstraints value = new ColumnConstraints(); value.setFillWidth(true); value.setHgrow(Priority.ALWAYS); value.setHalignment(HPos.RIGHT); serverPane.setHgap(16); serverPane.setVgap(8); serverPane.getColumnConstraints().setAll(title, value); txtServerIP = new JFXTextField(); txtServerIP.setPromptText(i18n("settings.advanced.server_ip.prompt")); FXUtils.setLimitWidth(txtServerIP, 300); serverPane.addRow(0, new Label(i18n("settings.advanced.server_ip")), txtServerIP); } componentList.getContent().setAll(javaSublist, gameDirSublist, maxMemoryPane, launcherVisibilityPane, dimensionPane, showLogsPane, processPriorityPane, serverPane); } HBox advancedHintPane = new HBox(); advancedHintPane.setAlignment(Pos.CENTER); advancedHintPane.setPadding(new Insets(16, 0, 8, 0)); { Label advanced = new Label(i18n("settings.advanced")); advanced.setStyle("-fx-font-size: 12px;"); advancedHintPane.getChildren().setAll(advanced); } ComponentList customCommandsPane = new ComponentList(); customCommandsPane.disableProperty().bind(enableSpecificSettings.not()); { GridPane pane = new GridPane(); pane.setHgap(16); pane.setVgap(8); pane.getColumnConstraints().setAll(new ColumnConstraints(), FXUtils.getColumnHgrowing()); txtGameArgs = new JFXTextField(); txtGameArgs.setPromptText(i18n("settings.advanced.minecraft_arguments.prompt")); txtGameArgs.getStyleClass().add("fit-width"); pane.addRow(0, new Label(i18n("settings.advanced.minecraft_arguments")), txtGameArgs); txtPreLaunchCommand = new JFXTextField(); txtPreLaunchCommand.setPromptText(i18n("settings.advanced.precall_command.prompt")); txtPreLaunchCommand.getStyleClass().add("fit-width"); pane.addRow(1, new Label(i18n("settings.advanced.precall_command")), txtPreLaunchCommand); txtWrapper = new JFXTextField(); txtWrapper.setPromptText(i18n("settings.advanced.wrapper_launcher.prompt")); txtWrapper.getStyleClass().add("fit-width"); pane.addRow(2, new Label(i18n("settings.advanced.wrapper_launcher")), txtWrapper); txtPostExitCommand = new JFXTextField(); txtPostExitCommand.setPromptText(i18n("settings.advanced.post_exit_command.prompt")); txtPostExitCommand.getStyleClass().add("fit-width"); pane.addRow(3, new Label(i18n("settings.advanced.post_exit_command")), txtPostExitCommand); HintPane hintPane = new HintPane(); hintPane.setText(i18n("settings.advanced.custom_commands.hint")); GridPane.setColumnSpan(hintPane, 2); pane.addRow(4, hintPane); customCommandsPane.getContent().setAll(pane); } ComponentList jvmPane = new ComponentList(); jvmPane.disableProperty().bind(enableSpecificSettings.not()); { GridPane pane = new GridPane(); ColumnConstraints title = new ColumnConstraints(); ColumnConstraints value = new ColumnConstraints(); value.setFillWidth(true); value.setHgrow(Priority.ALWAYS); pane.setHgap(16); pane.setVgap(8); pane.getColumnConstraints().setAll(title, value); txtJVMArgs = new JFXTextField(); txtJVMArgs.getStyleClass().add("fit-width"); pane.addRow(0, new Label(i18n("settings.advanced.jvm_args")), txtJVMArgs); HintPane hintPane = new HintPane(); hintPane.setText(i18n("settings.advanced.jvm_args.prompt")); GridPane.setColumnSpan(hintPane, 2); pane.addRow(4, hintPane); txtMetaspace = new JFXTextField(); txtMetaspace.setPromptText(i18n("settings.advanced.java_permanent_generation_space.prompt")); txtMetaspace.getStyleClass().add("fit-width"); FXUtils.setValidateWhileTextChanged(txtMetaspace, true); txtMetaspace.setValidators(new NumberValidator(i18n("input.number"), true)); pane.addRow(1, new Label(i18n("settings.advanced.java_permanent_generation_space")), txtMetaspace); jvmPane.getContent().setAll(pane); } ComponentList workaroundPane = new ComponentList(); workaroundPane.disableProperty().bind(enableSpecificSettings.not()); HintPane workaroundWarning = new HintPane(MessageDialogPane.MessageType.WARNING); workaroundWarning.setText(i18n("settings.advanced.workaround.warning")); { nativesDirItem = new MultiFileItem<>(); nativesDirSublist = new ComponentSublist(); nativesDirSublist.getContent().add(nativesDirItem); nativesDirSublist.setTitle(i18n("settings.advanced.natives_directory")); nativesDirSublist.setHasSubtitle(true); nativesDirCustomOption = new MultiFileItem.FileOption<>(i18n("settings.advanced.natives_directory.custom"), NativesDirectoryType.CUSTOM) .setChooserTitle(i18n("settings.advanced.natives_directory.choose")) .setDirectory(true); nativesDirItem.loadChildren(Arrays.asList( new MultiFileItem.Option<>(i18n("settings.advanced.natives_directory.default"), NativesDirectoryType.VERSION_FOLDER), nativesDirCustomOption )); HintPane nativesDirHint = new HintPane(MessageDialogPane.MessageType.WARNING); nativesDirHint.setText(i18n("settings.advanced.natives_directory.hint")); nativesDirItem.getChildren().add(nativesDirHint); noJVMArgsPane = new OptionToggleButton(); noJVMArgsPane.setTitle(i18n("settings.advanced.no_jvm_args")); noGameCheckPane = new OptionToggleButton(); noGameCheckPane.setTitle(i18n("settings.advanced.dont_check_game_completeness")); noJVMCheckPane = new OptionToggleButton(); noJVMCheckPane.setTitle(i18n("settings.advanced.dont_check_jvm_validity")); noNativesPatchPane = new OptionToggleButton(); noNativesPatchPane.setTitle(i18n("settings.advanced.dont_patch_natives")); useSoftwareRenderer = new OptionToggleButton(); useSoftwareRenderer.setTitle(i18n("settings.advanced.use_software_renderer")); useNativeGLFWPane = new OptionToggleButton(); useNativeGLFWPane.setTitle(i18n("settings.advanced.use_native_glfw")); useNativeOpenALPane = new OptionToggleButton(); useNativeOpenALPane.setTitle(i18n("settings.advanced.use_native_openal")); workaroundPane.getContent().setAll( nativesDirSublist, noJVMArgsPane, noGameCheckPane, noJVMCheckPane, noNativesPatchPane, useSoftwareRenderer, useNativeGLFWPane, useNativeOpenALPane); } rootPane.getChildren().addAll(componentList, advancedHintPane, ComponentList.createComponentListTitle(i18n("settings.advanced.custom_commands")), customCommandsPane, ComponentList.createComponentListTitle(i18n("settings.advanced.jvm")), jvmPane, ComponentList.createComponentListTitle(i18n("settings.advanced.workaround")), workaroundWarning, workaroundPane); initialize(); specificSettingsListener = any -> { enableSpecificSettings.set(!lastVersionSetting.isUsesGlobal()); }; addEventHandler(Navigator.NavigationEvent.NAVIGATED, this::onDecoratorPageNavigating); cboLauncherVisibility.getItems().setAll(LauncherVisibility.values()); cboLauncherVisibility.setConverter(stringConverter(e -> i18n("settings.advanced.launcher_visibility." + e.name().toLowerCase(Locale.ROOT)))); cboProcessPriority.getItems().setAll(ProcessPriority.values()); cboProcessPriority.setConverter(stringConverter(e -> i18n("settings.advanced.process_priority." + e.name().toLowerCase(Locale.ROOT)))); } private void initialize() { memoryStatus.set(OperatingSystem.getPhysicalMemoryStatus().orElse(OperatingSystem.PhysicalMemoryStatus.INVALID)); Task.supplyAsync(JavaVersion::getJavas).thenAcceptAsync(Schedulers.javafx(), list -> { boolean isX86 = Architecture.SYSTEM_ARCH.isX86() && list.stream().allMatch(java -> java.getArchitecture().isX86()); List<MultiFileItem.Option<Pair<JavaVersionType, JavaVersion>>> options = list.stream() .map(javaVersion -> new MultiFileItem.Option<>( i18n("settings.game.java_directory.template", javaVersion.getVersion(), isX86 ? i18n("settings.game.java_directory.bit", javaVersion.getBits().getBit()) : javaVersion.getPlatform().getArchitecture().getDisplayName()), pair(JavaVersionType.DETECTED, javaVersion)) .setSubtitle(javaVersion.getBinary().toString())) .collect(Collectors.toList()); options.add(0, javaAutoDeterminedOption); options.add(javaCustomOption); javaItem.loadChildren(options); javaItemsLoaded = true; initializeSelectedJava(); }).start(); javaItem.setSelectedData(null); if (OperatingSystem.CURRENT_OS == OperatingSystem.WINDOWS) javaCustomOption.getExtensionFilters().add(new FileChooser.ExtensionFilter("Java", "java.exe")); enableSpecificSettings.addListener((a, b, newValue) -> { if (versionId == null) return; // do not call versionSettings.setUsesGlobal(true/false) // because versionSettings can be the global one. // global versionSettings.usesGlobal is always true. if (newValue) profile.getRepository().specializeVersionSetting(versionId); else profile.getRepository().globalizeVersionSetting(versionId); Platform.runLater(() -> loadVersion(profile, versionId)); }); componentList.disableProperty().bind(enableSpecificSettings.not()); } @Override public void loadVersion(Profile profile, String versionId) { this.profile = profile; this.versionId = versionId; this.listenerHolder = new WeakListenerHolder(); if (versionId == null) { enableSpecificSettings.set(true); state.set(State.fromTitle(Profiles.getProfileDisplayName(profile) + " - " + i18n("settings.type.global.manage"))); listenerHolder.add(FXUtils.onWeakChangeAndOperate(profile.selectedVersionProperty(), selectedVersion -> { this.selectedVersion.setValue(selectedVersion); VersionSetting specializedVersionSetting = profile.getRepository().getLocalVersionSetting(selectedVersion); if (specializedVersionSetting != null) { navigateToSpecificSettings.bind(specializedVersionSetting.usesGlobalProperty().not()); } else { navigateToSpecificSettings.unbind(); navigateToSpecificSettings.set(false); } })); } else { navigateToSpecificSettings.unbind(); navigateToSpecificSettings.set(false); } VersionSetting versionSetting = profile.getVersionSetting(versionId); modpack.set(versionId != null && profile.getRepository().isModpack(versionId)); // unbind data fields if (lastVersionSetting != null) { FXUtils.unbind(txtWidth, lastVersionSetting.widthProperty()); FXUtils.unbind(txtHeight, lastVersionSetting.heightProperty()); maxMemory.unbindBidirectional(lastVersionSetting.maxMemoryProperty()); javaCustomOption.valueProperty().unbindBidirectional(lastVersionSetting.javaDirProperty()); gameDirCustomOption.valueProperty().unbindBidirectional(lastVersionSetting.gameDirProperty()); nativesDirCustomOption.valueProperty().unbindBidirectional(lastVersionSetting.nativesDirProperty()); FXUtils.unbind(txtJVMArgs, lastVersionSetting.javaArgsProperty()); FXUtils.unbind(txtGameArgs, lastVersionSetting.minecraftArgsProperty()); FXUtils.unbind(txtMetaspace, lastVersionSetting.permSizeProperty()); FXUtils.unbind(txtWrapper, lastVersionSetting.wrapperProperty()); FXUtils.unbind(txtPreLaunchCommand, lastVersionSetting.preLaunchCommandProperty()); FXUtils.unbind(txtPostExitCommand, lastVersionSetting.postExitCommandProperty()); FXUtils.unbind(txtServerIP, lastVersionSetting.serverIpProperty()); FXUtils.unbindBoolean(chkAutoAllocate, lastVersionSetting.autoMemoryProperty()); FXUtils.unbindBoolean(chkFullscreen, lastVersionSetting.fullscreenProperty()); noGameCheckPane.selectedProperty().unbindBidirectional(lastVersionSetting.notCheckGameProperty()); noJVMCheckPane.selectedProperty().unbindBidirectional(lastVersionSetting.notCheckJVMProperty()); noJVMArgsPane.selectedProperty().unbindBidirectional(lastVersionSetting.noJVMArgsProperty()); noNativesPatchPane.selectedProperty().unbindBidirectional(lastVersionSetting.notPatchNativesProperty()); showLogsPane.selectedProperty().unbindBidirectional(lastVersionSetting.showLogsProperty()); useSoftwareRenderer.selectedProperty().unbindBidirectional(lastVersionSetting.useSoftwareRendererProperty()); useNativeGLFWPane.selectedProperty().unbindBidirectional(lastVersionSetting.useNativeGLFWProperty()); useNativeOpenALPane.selectedProperty().unbindBidirectional(lastVersionSetting.useNativeOpenALProperty()); FXUtils.unbindEnum(cboLauncherVisibility); FXUtils.unbindEnum(cboProcessPriority); lastVersionSetting.usesGlobalProperty().removeListener(specificSettingsListener); lastVersionSetting.javaDirProperty().removeListener(javaListener); lastVersionSetting.javaProperty().removeListener(javaListener); gameDirItem.selectedDataProperty().unbindBidirectional(lastVersionSetting.gameDirTypeProperty()); gameDirSublist.subtitleProperty().unbind(); nativesDirItem.selectedDataProperty().unbindBidirectional(lastVersionSetting.nativesDirTypeProperty()); nativesDirSublist.subtitleProperty().unbind(); } // unbind data fields javaItem.setToggleSelectedListener(null); // bind new data fields FXUtils.bindInt(txtWidth, versionSetting.widthProperty()); FXUtils.bindInt(txtHeight, versionSetting.heightProperty()); maxMemory.bindBidirectional(versionSetting.maxMemoryProperty()); javaCustomOption.bindBidirectional(versionSetting.javaDirProperty()); gameDirCustomOption.bindBidirectional(versionSetting.gameDirProperty()); nativesDirCustomOption.bindBidirectional(versionSetting.nativesDirProperty()); FXUtils.bindString(txtJVMArgs, versionSetting.javaArgsProperty()); FXUtils.bindString(txtGameArgs, versionSetting.minecraftArgsProperty()); FXUtils.bindString(txtMetaspace, versionSetting.permSizeProperty()); FXUtils.bindString(txtWrapper, versionSetting.wrapperProperty()); FXUtils.bindString(txtPreLaunchCommand, versionSetting.preLaunchCommandProperty()); FXUtils.bindString(txtServerIP, versionSetting.serverIpProperty()); FXUtils.bindBoolean(chkAutoAllocate, versionSetting.autoMemoryProperty()); FXUtils.bindBoolean(chkFullscreen, versionSetting.fullscreenProperty()); noGameCheckPane.selectedProperty().bindBidirectional(versionSetting.notCheckGameProperty()); noJVMCheckPane.selectedProperty().bindBidirectional(versionSetting.notCheckJVMProperty()); noJVMArgsPane.selectedProperty().bindBidirectional(versionSetting.noJVMArgsProperty()); noNativesPatchPane.selectedProperty().bindBidirectional(versionSetting.notPatchNativesProperty()); showLogsPane.selectedProperty().bindBidirectional(versionSetting.showLogsProperty()); useSoftwareRenderer.selectedProperty().bindBidirectional(versionSetting.useSoftwareRendererProperty()); useNativeGLFWPane.selectedProperty().bindBidirectional(versionSetting.useNativeGLFWProperty()); useNativeOpenALPane.selectedProperty().bindBidirectional(versionSetting.useNativeOpenALProperty()); FXUtils.bindEnum(cboLauncherVisibility, versionSetting.launcherVisibilityProperty()); FXUtils.bindEnum(cboProcessPriority, versionSetting.processPriorityProperty()); versionSetting.usesGlobalProperty().addListener(specificSettingsListener); if (versionId != null) enableSpecificSettings.set(!versionSetting.isUsesGlobal()); javaItem.setToggleSelectedListener(newValue -> { if (javaCustomOption.isSelected()) { versionSetting.setUsesCustomJavaDir(); } else if (javaAutoDeterminedOption.isSelected()) { versionSetting.setJavaAutoSelected(); } else { //noinspection unchecked versionSetting.setJavaVersion(((Pair<JavaVersionType, JavaVersion>) newValue.getUserData()).getValue()); } }); versionSetting.javaDirProperty().addListener(javaListener); versionSetting.defaultJavaPathPropertyProperty().addListener(javaListener); versionSetting.javaProperty().addListener(javaListener); gameDirItem.selectedDataProperty().bindBidirectional(versionSetting.gameDirTypeProperty()); gameDirSublist.subtitleProperty().bind(Bindings.createStringBinding(() -> Paths.get(profile.getRepository().getRunDirectory(versionId).getAbsolutePath()).normalize().toString(), versionSetting.gameDirProperty(), versionSetting.gameDirTypeProperty())); nativesDirItem.selectedDataProperty().bindBidirectional(versionSetting.nativesDirTypeProperty()); nativesDirSublist.subtitleProperty().bind(Bindings.createStringBinding(() -> Paths.get(profile.getRepository().getRunDirectory(versionId).getAbsolutePath() + "/natives").normalize().toString(), versionSetting.nativesDirProperty(), versionSetting.nativesDirTypeProperty())); lastVersionSetting = versionSetting; initJavaSubtitle(); loadIcon(); } private void initializeSelectedJava() { if (lastVersionSetting == null || !javaItemsLoaded /* JREs are still being loaded */) { return; } if (lastVersionSetting.isUsesCustomJavaDir()) { javaCustomOption.setSelected(true); } else if (lastVersionSetting.isJavaAutoSelected()) { javaAutoDeterminedOption.setSelected(true); } else { // javaLoading.set(true); lastVersionSetting.getJavaVersion(null, null) .thenAcceptAsync(Schedulers.javafx(), javaVersion -> { javaItem.setSelectedData(pair(JavaVersionType.DETECTED, javaVersion)); // javaLoading.set(false); }).start(); } } private void initJavaSubtitle() { FXUtils.checkFxUserThread(); initializeSelectedJava(); VersionSetting versionSetting = lastVersionSetting; if (versionSetting == null) return; Profile profile = this.profile; String versionId = this.versionId; boolean autoSelected = versionSetting.isJavaAutoSelected(); if (autoSelected && versionId == null) { javaSublist.setSubtitle(i18n("settings.game.java_directory.auto")); return; } Task.composeAsync(Schedulers.javafx(), () -> { if (versionId == null) { return versionSetting.getJavaVersion(VersionNumber.asVersion("Unknown"), null); } else { return versionSetting.getJavaVersion( VersionNumber.asVersion(GameVersion.minecraftVersion(profile.getRepository().getVersionJar(versionId)).orElse("Unknown")), profile.getRepository().getVersion(versionId)); } }).thenAcceptAsync(Schedulers.javafx(), javaVersion -> javaSublist.setSubtitle(Optional.ofNullable(javaVersion) .map(JavaVersion::getBinary).map(Path::toString).orElseGet(() -> autoSelected ? i18n("settings.game.java_directory.auto.not_found") : i18n("settings.game.java_directory.invalid")))) .start(); } private void editSpecificSettings() { Versions.modifyGameSettings(profile, profile.getSelectedVersion()); } private void editGlobalSettings() { Versions.modifyGlobalSettings(profile); } private void onExploreIcon() { if (versionId == null) return; Controllers.dialog(new VersionIconDialog(profile, versionId, this::loadIcon)); } private void onDeleteIcon() { if (versionId == null) return; File iconFile = profile.getRepository().getVersionIconFile(versionId); if (iconFile.exists()) iconFile.delete(); VersionSetting localVersionSetting = profile.getRepository().getLocalVersionSettingOrCreate(versionId); if (localVersionSetting != null) { localVersionSetting.setVersionIcon(VersionIconType.DEFAULT); } loadIcon(); } private void loadIcon() { if (versionId == null) { return; } iconPickerItem.setImage(profile.getRepository().getVersionIconImage(versionId)); FXUtils.limitSize(iconPickerItem.getImageView(), 32, 32); } @Override public ReadOnlyObjectProperty<State> stateProperty() { return state.getReadOnlyProperty(); } private enum JavaVersionType { DETECTED, CUSTOM, AUTO, } }
42,988
Java
.java
698
48.700573
201
0.673845
Glavo/U1-Launcher
3
3
1
GPL-3.0
9/4/2024, 11:46:12 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
42,988
2,172,555
FilterChipView.java
bengal-social_megalodon/mastodon/src/main/java/org/joinmastodon/android/ui/views/FilterChipView.java
package org.joinmastodon.android.ui.views; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.Button; import org.joinmastodon.android.R; import org.joinmastodon.android.ui.utils.UiUtils; import androidx.annotation.DrawableRes; import me.grishka.appkit.utils.V; public class FilterChipView extends Button{ private boolean currentlySelected; public FilterChipView(Context context){ this(context, null); } public FilterChipView(Context context, AttributeSet attrs){ this(context, attrs, 0); } public FilterChipView(Context context, AttributeSet attrs, int defStyle){ super(context, attrs, defStyle); setCompoundDrawablePadding(V.dp(8)); setBackgroundResource(R.drawable.bg_filter_chip); setTextAppearance(R.style.m3_label_large); setTextColor(getResources().getColorStateList(R.color.filter_chip_text, context.getTheme())); setCompoundDrawableTintList(ColorStateList.valueOf(UiUtils.getThemeColor(context, R.attr.colorM3OnSurface))); updatePadding(); } @Override protected void drawableStateChanged(){ super.drawableStateChanged(); if(currentlySelected==isSelected()) return; currentlySelected=isSelected(); Drawable start=currentlySelected ? getResources().getDrawable(R.drawable.ic_baseline_check_18, getContext().getTheme()) : null; Drawable end=getCompoundDrawablesRelative()[2]; setCompoundDrawablesRelativeWithIntrinsicBounds(start, null, end, null); updatePadding(); } private void updatePadding(){ int vertical=V.dp(6); Drawable[] drawables=getCompoundDrawablesRelative(); setPaddingRelative(V.dp(drawables[0]==null ? 16 : 8), vertical, V.dp(drawables[2]==null ? 16 : 8), vertical); } public void setDrawableEnd(@DrawableRes int drawable){ setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, drawable, 0); updatePadding(); } }
1,927
Java
.java
48
37.6875
129
0.807816
bengal-social/megalodon
15
1
0
GPL-3.0
9/4/2024, 8:31:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,927
1,514,313
CSVShowWriter.java
KilianB_NetflixViewingActivityVisualizer/src/main/java/com/github/kilianB/fileHandling/out/CSVShowWriter.java
package com.github.kilianB.fileHandling.out; import java.io.File; import java.io.IOException; import org.threeten.bp.format.DateTimeFormatter; import java.util.Arrays; import com.github.kilianB.model.netflix.NetflixShowEpisode; import com.uwetrottmann.trakt5.entities.Show; /** * Rudimentary synchronized CSV writer accepting Show objects to be written to a CSV file * * @author Kilian */ public class CSVShowWriter extends CSVWriter{ public CSVShowWriter(File csvOutPath, String delimiter) throws IOException { super(csvOutPath, delimiter,"Date","Series","Title","Season","Runtime","Certificate","FirstAired","Network","Genres"); } /** * Output date format of the first aired date */ private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MM.yyyy"); /** * Append the data to the end of the csv file in a synchronized manner. * @param show A show object received by trakt * @param netflixShow A matching object parsed from the viewfile.csv * @param runtime The runtime of the episode * @throws IOException if an IO Error occurs */ public void push(Show show, NetflixShowEpisode netflixShow, int runtime) throws IOException { String genres = ""; if(show.genres != null) { genres = Arrays.toString(show.genres.toArray(new String[show.genres.size()])); } try { dtf.format(show.first_aired); }catch(IllegalArgumentException e) { System.out.println("First aired: " + show.first_aired); } writeLine(netflixShow.getViewDate(), netflixShow.getSeries(), netflixShow.getTitle(), netflixShow.getSeason(), runtime, show.certification, show.first_aired.format(dtf), show.network, genres); } }
1,706
Java
.java
48
32.25
120
0.756426
KilianB/NetflixViewingActivityVisualizer
25
3
2
GPL-3.0
9/4/2024, 7:55:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,706
4,295,384
SpecialDataClark.java
vineet1992_tetrad-vineet/tetrad-lib/src/test/java/edu/cmu/tetrad/test/SpecialDataClark.java
package edu.cmu.tetrad.test; import edu.cmu.tetrad.algcomparison.graph.RandomGraph; import edu.cmu.tetrad.algcomparison.graph.SingleGraph; import edu.cmu.tetrad.algcomparison.simulation.Simulation; import edu.cmu.tetrad.bayes.BayesIm; import edu.cmu.tetrad.bayes.BayesPm; import edu.cmu.tetrad.bayes.MlBayesIm; import edu.cmu.tetrad.data.DataModel; import edu.cmu.tetrad.data.DataSet; import edu.cmu.tetrad.data.DataType; import edu.cmu.tetrad.graph.EdgeListGraph; import edu.cmu.tetrad.graph.Graph; import edu.cmu.tetrad.graph.Node; import edu.cmu.tetrad.graph.NodeType; import edu.cmu.tetrad.sem.GeneralizedSemIm; import edu.cmu.tetrad.sem.GeneralizedSemPm; import edu.cmu.tetrad.util.IM; import edu.cmu.tetrad.util.Parameters; import edu.cmu.tetrad.util.RandomUtil; import org.apache.commons.lang3.RandomUtils; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.Random; import static edu.cmu.tetrad.util.StatUtils.skewness; import static java.lang.Math.abs; /** * @author jdramsey */ public class SpecialDataClark implements Simulation { static final long serialVersionUID = 23L; private RandomGraph randomGraph; private BayesPm pm; private BayesIm im; private List<DataSet> dataSets = new ArrayList<>(); private List<Graph> graphs = new ArrayList<>(); private List<BayesIm> ims = new ArrayList<>(); public SpecialDataClark(RandomGraph graph) { this.randomGraph = graph; } @Override public void createData(Parameters parameters) { Graph graph = randomGraph.createGraph(parameters); dataSets = new ArrayList<>(); graphs = new ArrayList<>(); for (int i = 0; i < parameters.getInt("numRuns"); i++) { System.out.println("Simulating dataset #" + (i + 1)); if (parameters.getBoolean("differentGraphs") && i > 0) { graph = randomGraph.createGraph(parameters); } graphs.add(graph); DataSet dataSet = simulate(graph, parameters); dataSet.setName("" + (i + 1)); dataSets.add(dataSet); } } @Override public DataModel getDataModel(int index) { return dataSets.get(index); } @Override public Graph getTrueGraph(int index) { if (graphs.isEmpty()) { return new EdgeListGraph(); } else { return graphs.get(index); } } @Override public String getDescription() { return "Bayes net simulation using " + randomGraph.getDescription(); } public void setInitialGraph(Graph g){throw new UnsupportedOperationException();} public IM getInstantiatedModel(int index){throw new UnsupportedOperationException();} @Override public List<String> getParameters() { List<String> parameters = new ArrayList<>(); if (!(randomGraph instanceof SingleGraph)) { parameters.addAll(randomGraph.getParameters()); } if (pm == null) { parameters.addAll(BayesPm.getParameterNames()); } if (im == null) { parameters.addAll(MlBayesIm.getParameterNames()); } parameters.add("numRuns"); parameters.add("differentGraphs"); parameters.add("sampleSize"); return parameters; } @Override public int getNumDataModels() { return dataSets.size(); } @Override public DataType getDataType() { return DataType.Discrete; } private DataSet simulate(Graph graph, Parameters parameters) { int N = parameters.getInt("sampleSize"); try { GeneralizedSemPm pm = new GeneralizedSemPm(graph); Graph g = pm.getGraph(); for (String p : pm.getParameters()) { double coef = RandomUtil.getInstance().nextUniform(0.3, 0.6); if (RandomUtil.getInstance().nextDouble() < 0.5) { coef *= -1; } pm.setParameterExpression(p, "" + coef); } for (Node x : g.getNodes()) { if (!(x.getNodeType() == NodeType.ERROR)) { String error; double s = RandomUtil.getInstance().nextUniform(.1, .4); double f = getF(s, N); if (s > 0) { error = "pow(Uniform(0, 1), " + (1.0 + f) + ")"; } else { error = "-pow(Uniform(0, 1), " + (1.0 + f) + ")"; } pm.setNodeExpression(pm.getErrorNode(x), error); } } GeneralizedSemIm im = new GeneralizedSemIm(pm); // System.out.println(im); return im.simulateData(N, false); } catch (Exception e) { throw new IllegalArgumentException("Sorry, I couldn't simulate from that Bayes IM; perhaps not all of\n" + "the parameters have been specified."); } } private double getF(double s, int N) { double high = 100.0; double low = 0.0; while (high - low > 1e-10) { double midpoint = (high + low) / 2.0; if (skewf(midpoint, N) < s) { low = midpoint; } else { high = midpoint; } } return high; } private double skewf(double f, int N) { double[] s = new double[N]; for (int i = 0; i < N; i++) { s[i] = Math.pow(RandomUtil.getInstance().nextUniform(0, 1), abs((1 + f))); } return skewness(s); } }
5,649
Java
.java
153
28.196078
118
0.601872
vineet1992/tetrad-vineet
2
1
4
GPL-2.0
9/5/2024, 12:08:25 AM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
5,649
979,612
TrialService_getEcrfStatusEntryTest.java
phoenixctms_ctsms/core/src/test/java/org/phoenixctms/ctsms/service/trial/test/TrialService_getEcrfStatusEntryTest.java
// This file is part of the Phoenix CTMS project (www.phoenixctms.org), // distributed under LGPL v2.1. Copyright (C) 2011 - 2017. // package org.phoenixctms.ctsms.service.trial.test; import org.testng.Assert; import org.testng.annotations.Test; /** * <p> * Test case for method <code>getEcrfStatusEntry</code> of service <code>TrialService</code>. * </p> * * @see org.phoenixctms.ctsms.service.trial.TrialService#getEcrfStatusEntry(org.phoenixctms.ctsms.vo.AuthenticationVO, java.lang.Long, java.lang.Long, java.lang.Long) */ @Test(groups={"service","TrialService"}) public class TrialService_getEcrfStatusEntryTest extends TrialServiceBaseTest { /** * Test succes path for service method <code>getEcrfStatusEntry</code> * * Tests expected behaviour of service method. */ @Test public void testSuccessPath() { Assert.fail( "Test 'TrialService_getEcrfStatusEntryTest.testSuccessPath()}' not implemented." ); } /* * Add test methods for each test case of the 'TrialService.org.andromda.cartridges.spring.metafacades.SpringServiceOperationLogicImpl[org.phoenixctms.ctsms.service.trial.TrialService.getEcrfStatusEntry]()' service method. */ /** * Test special case XYZ for service method <code></code> */ /* @Test public void testCaseXYZ() { } */ }
1,306
Java
.java
36
33.611111
224
0.754344
phoenixctms/ctsms
53
35
19
LGPL-2.1
9/4/2024, 7:10:22 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,306
3,502,196
BasePropertyChecklistImpl.java
openhealthcare_openMAXIMS/openmaxims_workspace/Nursing/src/ims/nursing/domain/base/impl/BasePropertyChecklistImpl.java
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.nursing.domain.base.impl; import ims.domain.impl.DomainImpl; public abstract class BasePropertyChecklistImpl extends DomainImpl implements ims.nursing.domain.PropertyChecklist, ims.domain.impl.Transactional { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") public void validatelist(ims.core.admin.vo.CareContextRefVo careContext) { } @SuppressWarnings("unused") public void validatesave(ims.nursing.vo.PropertyChecklistVo record) { } @SuppressWarnings("unused") public void validatelistWards(String name) { } @SuppressWarnings("unused") public void validateget(ims.nursing.vo.PropertyChecklistRefVo record) { } }
2,400
Java
.java
44
51.818182
146
0.529462
openhealthcare/openMAXIMS
3
1
0
AGPL-3.0
9/4/2024, 11:30:20 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
2,400
4,091,276
ImgtHla3_13_1.java
nmdp-bioinformatics_genotype-list/gl-service-nomenclature-hla/src/main/java/org/nmdp/gl/service/nomenclature/hla/ImgtHla3_13_1.java
/* gl-service-nomenclature-imgt IMGT/HLA nomenclature. Copyright (c) 2012-2015 National Marrow Donor Program (NMDP) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; with out even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. > http://www.fsf.org/licensing/licenses/lgpl.html > http://www.opensource.org/licenses/lgpl-license.php */ package org.nmdp.gl.service.nomenclature.hla; import org.nmdp.gl.service.GlRegistry; import org.nmdp.gl.service.GlstringResolver; import org.nmdp.gl.service.IdResolver; import org.nmdp.gl.service.nomenclature.ClasspathNomenclature; import com.google.inject.Inject; /** * IMGT/HLA version 3.13.1 nomenclature. */ public final class ImgtHla3_13_1 extends ClasspathNomenclature { @Inject public ImgtHla3_13_1(final GlstringResolver glstringResolver, final IdResolver idResolver, final GlRegistry glRegistry) { super("imgt-hla-3.13.1.txt", glstringResolver, idResolver, glRegistry); } @Override public String getName() { return "IMGT/HLA Database"; } @Override public String getVersion() { return "3.13.1"; } @Override public String getURL() { return "http://www.ebi.ac.uk/ipd/imgt/hla/"; } }
1,916
Java
.java
46
36.173913
79
0.724138
nmdp-bioinformatics/genotype-list
2
7
21
LGPL-3.0
9/5/2024, 12:02:29 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,916
2,397,677
AddToCartServlet.java
mbranko_isa19/09-arch/pr01/src/main/java/pr01/servlet/AddToCartServlet.java
package pr01.servlet; import pr01.entity.OrderItem; import pr01.entity.Product; import pr01.entity.PurchaseOrder; import java.io.IOException; import java.util.Date; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class AddToCartServlet extends HttpServlet { @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF8"); ServletContext ctx = getServletConfig().getServletContext(); HttpSession session = request.getSession(true); try { String sQuantity = request.getParameter("quantity"); int quantity = Integer.parseInt(sQuantity); Product prod = (Product)session.getAttribute("product"); PurchaseOrder order = (PurchaseOrder)session.getAttribute("order"); if (order == null) { order = new PurchaseOrder(); order.setDate(new Date()); session.setAttribute("order", order); } OrderItem item = new OrderItem(); item.setOrder(order); item.setProduct(prod); item.setQuantity(quantity); order.add(item); ctx.getRequestDispatcher("/cart.jsp").forward(request, response); } catch (Exception ex) { throw new ServletException(ex); } } private static final long serialVersionUID = -3513730453594660585L; }
1,555
Java
.java
41
33.219512
78
0.751664
mbranko/isa19
8
4
16
GPL-3.0
9/4/2024, 9:19:59 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,555
949,242
Servlet.java
ZapBlasterson_crushpaper/src/main/java/com/crushpaper/Servlet.java
/* Copyright 2015 CrushPaper.com. This file is part of CrushPaper. CrushPaper is free software: you can redistribute it and/or modify it under the terms of version 3 of the GNU Affero General Public License as published by the Free Software Foundation. CrushPaper is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with CrushPaper. If not, see <http://www.gnu.org/licenses/>. */ package com.crushpaper; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.BlockingQueue; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.persistence.PersistenceException; import javax.servlet.MultipartConfigElement; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.Part; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.NCSARequestLog; import org.eclipse.jetty.server.SecureRequestCustomizer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.handler.RequestLogHandler; import org.eclipse.jetty.server.handler.ResourceHandler; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.BlockingArrayQueue; import org.eclipse.jetty.util.MultiMap; import org.eclipse.jetty.util.UrlEncoded; import org.eclipse.jetty.util.resource.JarResource; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.hibernate.search.exception.EmptyQueryException; import org.jsoup.Jsoup; import org.jsoup.safety.Whitelist; import org.pegdown.LinkRenderer; import org.pegdown.PegDownProcessor; import com.crushpaper.DbLogic.Constants; import com.crushpaper.DbLogic.TreeRelType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; /** * This class encapsulates all logic for handling HTTP requests. All logic for * enforcing the consistency of the database is in DbLogic. * */ public class Servlet extends HttpServlet { private static final long serialVersionUID = -1552137926361345398L; ServletText servletText = new ServletText(); Servlet(DbLogic dbLogic, String singleUserName, Boolean allowSelfSignUp, Boolean allowSaveIfNotSignedIn, Boolean loopbackIsAdmin, Integer httpPort, Integer httpsPort, Integer httpsProxiedPort, File keyStorePath, String keyStorePassword, String keyManagerPassword, File temporaryDirectory, File logDirectory, File sessionStoreDirectory, Boolean isOfficialSite, String extraHeader) { this.dbLogic = dbLogic; this.singleUserName = singleUserName != null ? singleUserName .toLowerCase() : null; this.allowSelfSignUp = allowSelfSignUp; this.allowSaveIfNotSignedIn = allowSaveIfNotSignedIn; this.loopbackIsAdmin = loopbackIsAdmin; this.versionNumber = getVersionNumber(); this.httpPort = httpPort; this.httpsPort = httpsPort; this.httpsProxiedPort = httpsProxiedPort; this.keyStorePath = keyStorePath; this.keyStorePassword = keyStorePassword; this.keyManagerPassword = keyManagerPassword; this.temporaryDirectory = temporaryDirectory; this.logDirectory = logDirectory; this.sessionStoreDirectory = sessionStoreDirectory; this.isOfficialSite = isOfficialSite; this.extraHeader = extraHeader; } private final String singleUserName; private final DbLogic dbLogic; private final boolean allowSelfSignUp; private final boolean allowSaveIfNotSignedIn; private final boolean loopbackIsAdmin; private final String versionNumber; private final Integer httpPort; private final Integer httpsPort; private final Integer httpsProxiedPort; private final File keyStorePath; private final String keyStorePassword; private final String keyManagerPassword; private final File temporaryDirectory; private final File logDirectory; private final File sessionStoreDirectory; private Resource helpDirectoryResource; private ExposedShutdownHashSessionManager sessionManager; private boolean isInJar; private final HashMap<String, String> helpMarkdownMap = new HashMap<String, String>(); final String sessionUserIdAttribute = "uid"; final private int defaultNoteDisplayDepth = 3; final private boolean isOfficialSite; final private String extraHeader; /** Returns the session ID for the session and creates it if needed. */ private String getSessionId(RequestAndResponse requestAndResponse) { return requestAndResponse.request.getSession(true).getId(); } /** Wraps the request and Response. */ class RequestAndResponse { RequestAndResponse(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; } /** Prints the value to the response. */ public void print(String value) throws IOException { response.getWriter().print(value); } /** Prints the value followed by a line feed to the response. */ public void println(String value) throws IOException { response.getWriter().println(value); } /** Gets the parameter from the request. */ public String getParameter(String name) { parseParameters(); final String[] values = parameters.get(name); if (values != null && values.length > 0) { return values[0]; } return null; } /** Returns the map of parameters from the request. */ public Map<String, String[]> getParameterMap() { parseParameters(); return parameters; } /** * Returns a "parameter" stored after the second slash in the URL. * Returns null if not found. */ public String getURIParameter() { final String uri = overrideUri; final int slashPos = uri.indexOf("/", 1); if (slashPos == -1) { return null; } int atPos = uri.indexOf("@"); atPos = atPos == -1 ? uri.length() : atPos; return uri.substring(slashPos + 1, atPos); } /** Returns the logical request URI without query parameters. */ public String getRequestURI() { parseParameters(); return requestUri; } public void setOverrideUri(String uri) { parametersAlreadyParsed = false; overrideUri = uri; } /** * Parse query parameters which might be embedded in the URI double * encoded after and @ sign. */ private void parseParameters() { if (parametersAlreadyParsed) { return; } parametersAlreadyParsed = true; final String uri = overrideUri; final int atPos = uri.indexOf("@"); if (atPos == -1) { requestUri = overrideUri; parameters = request.getParameterMap(); return; } requestUri = uri.substring(0, atPos); final String doubleEncodedContent = uri.substring(atPos + 1); final Charset utf8 = Charset.forName("UTF-8"); final String singleEncodedContent = UrlEncoded.decodeString( doubleEncodedContent, 0, doubleEncodedContent.length(), utf8); final MultiMap<String> tempParameters = new MultiMap<String>(); UrlEncoded.decodeTo(singleEncodedContent, tempParameters, utf8, 10); parameters = new HashMap<String, String[]>(); final Iterator<Map.Entry<String, List<String>>> iter = tempParameters .entrySet().iterator(); while (iter.hasNext()) { final Map.Entry<String, List<String>> e = iter.next(); final String key = e.getKey(); final List<String> valsList = e.getValue(); final String[] valsArray = new String[valsList.size()]; valsList.toArray(valsArray); parameters.put(key, valsArray); } } /** Sets the content type of the response to JSON utf8. */ public void setResponseContentTypeJson() { response.setContentType("application/json;charset=utf-8"); } /** Sets the content type of the response to text utf8. */ public void setResponseContentTypeText() { response.setContentType("text/plain;charset=utf-8"); } /** Sets the content type of the response to RTF. */ public void setResponseContentTypeRtf() { response.setContentType("application/rtf"); } private String overrideUri; private String requestUri; private boolean parametersAlreadyParsed; private Map<String, String[]> parameters; public HttpServletRequest request; public HttpServletResponse response; public boolean isLocalAdmin; public boolean skipFooter; public boolean skipHeader; public boolean justGetTitle; public boolean titleAlreadyFormed; public StringBuilder totalTitle; public boolean wasUserAlreadyStashed; public boolean userIsAdmin; public boolean userIsAccountClosed; public String userOptions; public boolean moreThanOneUri; } /** Get the userId corresponding to the session in the request. */ public String getEffectiveUserId(RequestAndResponse requestAndResponse) { if (isInSingleUserMode()) { final User user = dbLogic.getUserByUserName(singleUserName); if (user != null) { return user.getId(); } return null; } return (String) requestAndResponse.request.getSession().getAttribute( sessionUserIdAttribute); } /** Returns true if the user is a local admin. */ private boolean isUserALocalAdmin(RequestAndResponse requestAndResponse) { if (loopbackIsAdmin) { final String remoteAddr = requestAndResponse.request .getRemoteAddr(); if (remoteAddr != null && (remoteAddr.equals("127.0.0.1") || remoteAddr .equals("0:0:0:0:0:0:0:1"))) { requestAndResponse.isLocalAdmin = true; return true; } } return false; } /** * Stashes user information in the requestAndResponse to reduce the number * of queries and transactions. */ private void stashRequestUser(RequestAndResponse requestAndResponse) { if (requestAndResponse.wasUserAlreadyStashed) { return; } requestAndResponse.wasUserAlreadyStashed = true; final User user = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); if (user != null) { requestAndResponse.userIsAdmin = user.getIsAdmin(); requestAndResponse.userIsAccountClosed = user.getIsAccountClosed(); requestAndResponse.userOptions = user.getOptions(); } else { requestAndResponse.userOptions = "{}"; } } /** Returns true if the user is an admin. */ private boolean isUserAnAdmin(RequestAndResponse requestAndResponse) { if (loopbackIsAdmin) { if (isUserALocalAdmin(requestAndResponse)) { return true; } } stashRequestUser(requestAndResponse); return requestAndResponse.userIsAdmin && !requestAndResponse.userIsAccountClosed; } /** Returns true if the user account is closed. */ private boolean isUsersAccountClosed(RequestAndResponse requestAndResponse) { stashRequestUser(requestAndResponse); return requestAndResponse.userIsAccountClosed; } /** * Set request and response defaults. Can be overridden for specific * requests. */ private void standardResponseStuff(RequestAndResponse requestAndResponse) { // Force session ID generation getSessionId(requestAndResponse); // This is the only way I could find to get Chrome to reload the page // when the user hits the back button. requestAndResponse.response.setHeader("Cache-control", "no-store"); // Make this the default. requestAndResponse.response.setContentType("text/html;charset=utf-8"); } /** Splits the URI into individual URIs for panes. */ protected ArrayList<String> splitUris(String uri) { ArrayList<String> uris = new ArrayList<String>(); int start = 0; while (true) { if (uri.charAt(start) != '/') { uris = null; break; } final int secondSlash = uri.indexOf('/', start + 1); if (secondSlash == -1) { uris = null; break; } boolean isDone = false; int thirdSlash = uri.indexOf('/', secondSlash + 1); if (thirdSlash == -1) { thirdSlash = uri.length(); isDone = true; } uris.add(uri.substring(start, thirdSlash)); if (isDone) { break; } start = thirdSlash; } return uris; } /** Route HTTP GET requests. */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { doGetHelper(request, response); } catch (final Exception e) { logger.log(Level.INFO, "Exception", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } dbLogic.rollback(); } /** Does the real work of doGet(). */ private void doGetHelper(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.log(Level.INFO, "request: " + request.getRequestURI()); final RequestAndResponse requestAndResponse = new RequestAndResponse( request, response); standardResponseStuff(requestAndResponse); final String fullUri = request.getRequestURI(); requestAndResponse.setOverrideUri(fullUri); if (fullUri.equals("/")) { handleHtmlIndexPage(requestAndResponse); return; } if (fullUri.equals("/robots.txt")) { handleRobotsTxt(requestAndResponse); return; } final ArrayList<String> uris = splitUris(fullUri); if (uris == null) { returnHtml404(requestAndResponse); return; } requestAndResponse.moreThanOneUri = uris.size() > 1; // Build the title of a multi pane request. if (uris.size() > 1) { requestAndResponse.justGetTitle = true; for (int i = 0; i < uris.size(); ++i) { final String uri = uris.get(i); requestAndResponse.setOverrideUri(uri); routeSingleGetRequest(requestAndResponse, uri); } requestAndResponse.justGetTitle = false; requestAndResponse.titleAlreadyFormed = true; } for (int i = 0; i < uris.size(); ++i) { final String uri = uris.get(i); requestAndResponse.setOverrideUri(uri); if (uris.size() > 1) { if (i == 0) { requestAndResponse.skipFooter = true; } else if (i == uris.size() - 1) { requestAndResponse.skipHeader = true; requestAndResponse.skipFooter = false; } else { requestAndResponse.skipHeader = true; } } routeSingleGetRequest(requestAndResponse, uri); } } /** Handle requests for robots.txt. */ private void handleRobotsTxt(RequestAndResponse requestAndResponse) throws IOException { requestAndResponse.response.setContentType("text/plain;"); if (isOfficialSite) { requestAndResponse.print("User-agent: *\nDisallow:\n"); } else { requestAndResponse.print("User-agent: *\nDisallow: /\n"); } } /** Routes a single GET request. */ private void routeSingleGetRequest(RequestAndResponse requestAndResponse, String uri) throws IOException, ServletException { if (uri.startsWith("/notebooks/")) { handleHtmlShowNotebooks(requestAndResponse); } else if (uri.startsWith("/quotations/")) { handleHtmlShowQuotations(requestAndResponse); } else if (uri.startsWith("/sources/")) { handleHtmlShowSources(requestAndResponse); } else if (uri.startsWith("/source/")) { handleHtmlShowSource(requestAndResponse); } else if (uri.startsWith("/notebook/")) { handleHtmlShowNotebook(requestAndResponse); } else if (uri.startsWith("/search/")) { handleHtmlSearch(requestAndResponse); // ///////// } else if (uri.equals("/help/")) { handleHtmlBasicHelp(requestAndResponse); } else if (uri.equals("/advancedHelp/")) { handleHtmlAdvancedHelp(requestAndResponse); } else if (uri.startsWith("/help/")) { handleHtmlHelp(requestAndResponse); } else if (uri.equals("/backup/")) { handleHtmlUserBackupForm(requestAndResponse); } else if (uri.equals("/restore/")) { handleHtmlUserRestoreForm(requestAndResponse); // /////////// } else if (uri.startsWith("/account/")) { handleHtmlShowAccount(requestAndResponse); } else if (uri.startsWith("/accounts/")) { handleHtmlShowAccounts(requestAndResponse); } else if (uri.equals("/shutdown/")) { handleHtmlShutdownForm(requestAndResponse); } else if (uri.equals("/clear/")) { handleHtmlClearForm(requestAndResponse); } else if (uri.equals("/onlineBackup/")) { handleHtmlOnlineBackupForm(requestAndResponse); } else if (uri.equals("/checkForErrors/")) { handleHtmlCheckForErrorsForm(requestAndResponse); } else if (uri.equals("/backups/")) { handleHtmlShowDBBackups(requestAndResponse); } else if (uri.equals("/offlineBackup/")) { handleHtmlOfflineDbBackupForm(requestAndResponse); // /////////// } else if (uri.equals("/noteJson/")) { handleJsonShowEntry(requestAndResponse); } else if (uri.equals("/noteParentJson/")) { handleJsonShowEntryParent(requestAndResponse); } else if (uri.equals("/noteChildrenJson/")) { handleJsonShowEntryChildren(requestAndResponse); } else if (uri.equals("/searchNotesJson/")) { handleJsonSearchNotes(requestAndResponse); } else if (uri.equals("/newNotebook/")) { handleHtmlNewNotebookForm(requestAndResponse); } else if (uri.equals("/nothing/")) { handleHtmlNothing(requestAndResponse); } else if (uri.equals("/couldNotCreateNote/")) { handleHtmlCouldNotCreateNote(requestAndResponse); } else if (uri.equals("/restoreBackupCommand/")) { handleHtmlShowRestoreDbBackupCommand(requestAndResponse); } else if (uri.equals("/signedOut/")) { handleHtmlShowSignedOut(requestAndResponse); } else if (uri.startsWith("/changePassword/")) { handleHtmlChangePassword(requestAndResponse); } else if (uri.startsWith("/changeAccount/")) { handleHtmlChangeAccount(requestAndResponse); } else if (uri.startsWith("/closeAccount/")) { handleHtmlCloseAccount(requestAndResponse); } else if (uri.equals("/isSignedIn/")) { handleJsonIsSignedIn(requestAndResponse); } else if (uri.equals("/restoreFrame/")) { handleHtmlUserRestoreFrame(requestAndResponse); } else { returnHtml404(requestAndResponse); } } /** Route HTTP POST requests. */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { doPostHelper(request, response); } catch (final Exception e) { logger.log(Level.INFO, "Exception", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } dbLogic.rollback(); } /** Does the real work of doPost(). */ private void doPostHelper(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.log(Level.INFO, "request: " + request.getRequestURI()); final RequestAndResponse requestAndResponse = new RequestAndResponse( request, response); standardResponseStuff(requestAndResponse); final String uri = request.getRequestURI(); requestAndResponse.setOverrideUri(uri); if (uri.equals("/createQuotationJson")) { handleJsonCreateQuotation(requestAndResponse); } else if (uri.equals("/makeNotebook")) { handleHtmlMakeNotebook(requestAndResponse); } else if (uri.equals("/moveNotesJson")) { handleJsonMoveNotes(requestAndResponse); } else if (uri.equals("/noteOpJson")) { handleJsonNoteOp(requestAndResponse); } else if (uri.equals("/getNotebookPathJson")) { handleJsonGetNotebookPath(requestAndResponse); } else if (uri.equals("/makeChildrenJson")) { handleJsonMakeChildren(requestAndResponse); } else if (uri.equals("/makeSiblingsJson")) { handleJsonMakeSiblings(requestAndResponse); } else if (uri.equals("/signIn")) { handleJsonSignIn(requestAndResponse); } else if (uri.equals("/signOut")) { handleJsonSignOut(requestAndResponse); } else if (uri.equals("/createAccount")) { handleJsonCreateAccount(requestAndResponse); } else if (uri.startsWith("/doRestore/")) { handleHtmlDoUserRestore(requestAndResponse); } else if (uri.startsWith("/doOfflineBackup/")) { handleHtmlDoOfflineDbBackup(requestAndResponse); } else if (uri.startsWith("/doOnlineBackup/")) { handleHtmlDoOnlineDbBackup(requestAndResponse); } else if (uri.startsWith("/doClear/")) { handleHtmlDoClear(requestAndResponse); } else if (uri.startsWith("/doBackup/")) { handleHtmlDoUserBackup(requestAndResponse); } else if (uri.startsWith("/doShutdown/")) { handleHtmlDoShutdown(requestAndResponse); } else if (uri.startsWith("/doCheckForErrors/")) { handleHtmlDoCheckForErrors(requestAndResponse); } else if (uri.startsWith("/changePassword/")) { handleHtmlChangePassword(requestAndResponse); } else if (uri.startsWith("/changeAccount/")) { handleHtmlChangeAccount(requestAndResponse); } else if (uri.startsWith("/closeAccount/")) { handleHtmlCloseAccount(requestAndResponse); } else if (uri.equals("/saveOptions")) { handleJsonSaveOptions(requestAndResponse); } else if (uri.startsWith("/doExport/")) { handleHtmlDoExport(requestAndResponse); } else { returnHtml404(requestAndResponse); } } /** Part of the JSON API. Creates a new quotation. */ private void handleJsonCreateQuotation(RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.setResponseContentTypeJson(); String url; String title; String quotation; String note; String sessionId; try { final JsonNodeHelper json = getJsonNode(requestAndResponse); url = json.getString(DbLogic.Constants.url); title = json.getString(DbLogic.Constants.title); quotation = json.getString(DbLogic.Constants.quotation); note = json.getString(DbLogic.Constants.note); sessionId = json.getString("sessionId"); } catch (final IOException e) { returnJson400(requestAndResponse, servletText.errorJson()); return; } if (!EntryAttributeValidator.isNoteValid(note)) { returnJson400(requestAndResponse, servletText.errorNoteIsInvalid()); return; } if (!EntryAttributeValidator.isQuotationValid(quotation)) { returnJson400(requestAndResponse, servletText.errorQuotationIsInvalid()); return; } if (!EntryAttributeValidator.isUrlValid(url)) { returnJson400(requestAndResponse, servletText.errorUrlIsInvalid()); return; } if (!EntryAttributeValidator.isSourceTitleValid(title)) { returnJson400(requestAndResponse, servletText.errorTitleIsInvalid()); return; } final Errors errors = new Errors(); try { final Long time = new Long(System.currentTimeMillis()); String userId = null; if (sessionManager != null) { final HttpSession session = sessionManager .getSession(sessionId); if (session != null && session.getAttribute(sessionUserIdAttribute) != null) { userId = (String) session .getAttribute(sessionUserIdAttribute); } } final User user = dbLogic.getUserById(userId); if (user == null) { returnJson400(requestAndResponse, servletText.errorNoAccountFound()); return; } if (user.getIsAccountClosed()) { returnJson400(requestAndResponse, servletText.errorAccountIsClosed()); return; } final Entry source = dbLogic.updateOrCreateSource(user, null, url, title, time, time, isUserAnAdmin(requestAndResponse), errors); if (source == null) { returnJson400(requestAndResponse, errors); return; } final Entry entry = dbLogic.createEntryQuotation(user, source, quotation, note, time, isUserAnAdmin(requestAndResponse), errors); if (entry == null) { returnJson400(requestAndResponse, errors); return; } requestAndResponse.print("{\"success\":true, " + "\"quotationId\":\"" + entry.getId() + "\"," + "\"sourceId\":\"" + source.getId() + "\"}"); dbLogic.commit(); } catch (final PersistenceException e) { logger.log(Level.INFO, "Exception", e); returnJson500(requestAndResponse, servletText.errorInternalDatabase()); } } /** Returns true if the CSRF token is wrong or null. */ private boolean isTheCsrftWrong(RequestAndResponse requestAndResponse, String csrft) { if (csrft == null || csrft.isEmpty() || csrft.length() > 100) { return true; } return !csrft.equals(getCsrft(requestAndResponse)); } /** Returns the CSRFT for the session. */ private String getCsrft(RequestAndResponse requestAndResponse) { return getSessionId(requestAndResponse); } /** Part of the HTML API. Displays the list of basic help. */ private void handleHtmlBasicHelp(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleHelp(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false).setPaneId("help"); pageWrapper.addHeader(); // Prevent the last link from floating off. requestAndResponse.print("<table><tr><td>"); startHelpSection(requestAndResponse, "Start Here"); addHelpLink(requestAndResponse, "What CrushPaper Is"); addHelpLink(requestAndResponse, "Why I Created CrushPaper"); addHelpLink(requestAndResponse, "Why CrushPaper Is Free"); addHelpLink(requestAndResponse, "User Guide"); addHelpLink(requestAndResponse, "Account Information"); addHelpLink(requestAndResponse, "Search Help"); addHelpLink(requestAndResponse, "Chrome Extension"); addHelpLink(requestAndResponse, "Chrome Extension Permissions"); addHelpLink(requestAndResponse, "Privacy Policy"); addHelpLink(requestAndResponse, "Future Enhancements"); endHelpSection(requestAndResponse); requestAndResponse .print("<a onclick=\"newPaneForLink(event, '" + servletText.pageTitleHelp() + "', 'help'); return false;\" class=\"nextLink\" href=\"/advancedHelp/\">Help for administrators and code contributors.</a>"); requestAndResponse.print("</td></tr></table>"); pageWrapper.addFooter(); } /** Part of the HTML API. Displays the list of advanced help. */ private void handleHtmlAdvancedHelp(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleAdvancedHelp(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false).setPaneId("help"); pageWrapper.addHeader(); startHelpSection(requestAndResponse, "For Administrators"); addHelpLink(requestAndResponse, "Administrator Guide"); addHelpLink(requestAndResponse, "Build, Install, Configure and Run"); addHelpLink(requestAndResponse, "System Overview"); endHelpSection(requestAndResponse); startHelpSection(requestAndResponse, "For Contributors"); addHelpLink(requestAndResponse, "Code Contribution Guidelines"); addHelpLink(requestAndResponse, "Get Started Coding"); addHelpLink(requestAndResponse, "Release Process"); addHelpLink(requestAndResponse, "Testing Strategy"); addHelpLink(requestAndResponse, "Licenses"); endHelpSection(requestAndResponse); pageWrapper.addFooter(); } /** Adds a section header for some help pages. */ private void startHelpSection(RequestAndResponse requestAndResponse, String name) throws IOException { requestAndResponse .println("<div class=\"helpListSection\"><div class=\"helpListHeader\">" + name + "</div>"); } /** Adds a section footer for some help pages. */ private void endHelpSection(RequestAndResponse requestAndResponse) throws IOException { requestAndResponse.println("</div>"); } /** Adds a link to a help page. */ private void addHelpLink(RequestAndResponse requestAndResponse, String name) throws IOException { requestAndResponse .println("<div class=\"helpListItem\">&bull; <a onclick=\"replacePaneForLink(event, uiText.pageTitleHelpPage()); return false;\" href=\"/help/" + name.replace(" ", "-") + "\">" + name + "</a></div>"); } /** Returns the markdown for a help item with the specified name. */ private String getHelpMarkdown(String helpName) { // Basic validation. if (helpName == null || helpName.isEmpty() || helpName.length() > 50 || !StringUtils.isAsciiPrintable(helpName)) { return null; } if (isInJar) { if (helpMarkdownMap.containsKey(helpName)) { return helpMarkdownMap.get(helpName); } } final String helpMarkeddown = getHelpMarkdownHelper(helpName); if (isInJar) { helpMarkdownMap.put(helpName, helpMarkeddown); } return helpMarkeddown; } /** Helper for getHelpMarkdown(). */ private String getHelpMarkdownHelper(String helpName) { String helpMarkdown = null; InputStream inputStream = null; try { final Resource fileResource = helpDirectoryResource.addPath("/" + helpName + ".md"); if (fileResource.exists()) { inputStream = fileResource.getInputStream(); helpMarkdown = IOUtils.toString(inputStream, "UTF-8"); } } catch (final Exception e) { return null; } finally { if (inputStream != null) { try { inputStream.close(); } catch (final IOException e) { } } } String helpMarkedDown = getMarkdownHtml(helpMarkdown, false, true); return helpMarkedDown.replaceAll("( href=\"/)doc(/[^\"\\.]+)\\.md", "$1help$2"); } /** Part of the HTML API. Displays help. */ private void handleHtmlHelp(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String helpName = requestAndResponse.getURIParameter(); final String title = helpName.replace("-", " "); if (addTitle(requestAndResponse, title)) { return; } final String helpMarkdown = getHelpMarkdown(helpName); if (helpMarkdown == null) { returnHtml404(requestAndResponse); return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false).setPaneId("help"); pageWrapper.addHeader(); requestAndResponse.print(helpMarkdown); addCallToAction(requestAndResponse); pageWrapper.addFooter(); } /** * Part of the HTML API. Displays a form that enables a user to create a * note. */ private void handleHtmlNewNotebookForm(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleNewNotebook(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false); pageWrapper.addHeader(); final boolean userIsSignedIn = isUserSignedIn(requestAndResponse); if (!userIsSignedIn && !allowSaveIfNotSignedIn) { requestAndResponse.print(servletText .errorRequiresSignIn(allowSaveIfNotSignedIn)); } else if (userIsSignedIn && isUsersAccountClosed(requestAndResponse)) { requestAndResponse.print(servletText.errorAccountIsClosed()); } else { if (!userIsSignedIn) { requestAndResponse.print(servletText .sentenceAllowSaveIfNotSignedIn()); } requestAndResponse .print("<script type=\"text/javascript\">\n" + "function saveNote() {\n" + " if(document.getElementById(\"note\").value.trim() == \"\") {\n" + " setResponseErrorMessage(errorBlankNote(), \"createResponse\");\n" + " } else {\n" + " document.getElementById(\"putNote\").submit();\n" + " }\n" + "}\n" + "</script>"); requestAndResponse .print("<form action=\"/makeNotebook\" id=\"putNote\" method=\"POST\">" + "<table class=\"nopadding\"><tr><td colspan=\"2\">" + "<input type=\"text\" id=\"note\" name=\"note\" placeholder=\"" + servletText.labelYourNotebookTitle() + "\" autofocus>" + "</td></tr>" + "<tr><td>" + "<input type=\"checkbox\" name=\"isPublic\" id=\"isPublic\"><label for=\"isPublic\">" + servletText.labelAnyoneCanReadThis() + "</label>" + "<input type=\"hidden\" name=\"csrft\" value=\"" + getCsrft(requestAndResponse) + "\">" + "</td></tr>" + "<tr><td><div id=\"createResponse\"></div></td>" + "<td><button id=\"save\" class=\"specialbutton\" onclick=\"saveNote(); return false;\">" + servletText.buttonSave() + "</button></td></tr></table></form>"); } pageWrapper.addFooter(); } /** * Part of the HTML API. Displays a page indicating that a note could not be * created. */ private void handleHtmlCouldNotCreateNote( RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleNewNotebook(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false).setPaneId("welcome"); pageWrapper.addHeader(); requestAndResponse.print(servletText.errorNoteNotCreated()); pageWrapper.addFooter(); } /** Part of the HTML API. Displays the index. */ private void handleHtmlIndexPage(RequestAndResponse requestAndResponse) throws IOException, ServletException { final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, servletText.pageTitleWelcome(), false).setPaneId("welcome"); pageWrapper.addHeader(); final String welcomeText = getHelpMarkdown("What-CrushPaper-Is"); if (welcomeText != null) { requestAndResponse.print(welcomeText); } addCallToAction(requestAndResponse); pageWrapper.addFooter(); } /** Adds the call to action. */ private void addCallToAction(RequestAndResponse requestAndResponse) throws IOException { if (!doesUserHaveAnyNotebooks(requestAndResponse)) { requestAndResponse.print(servletText .callToAction(allowSaveIfNotSignedIn)); } else { requestAndResponse.print(servletText.viewYourNotebooks()); } } /** Returns true if the user has any notebooks. */ private boolean doesUserHaveAnyNotebooks( RequestAndResponse requestAndResponse) throws IOException { boolean hasNotebooks = false; try { final String userId = getEffectiveUserId(requestAndResponse); if (userId != null) { final User user = dbLogic.getUserById(userId); if (user != null) { hasNotebooks = dbLogic .doesTableOfContentsHaveAnyNotebooks(user .getTableOfContentsId()); } } dbLogic.commit(); } catch (final PersistenceException e) { } return hasNotebooks; } /** * Returns true if the current user can see data for the requested user. * Responsible for printing the error if false. * * @throws IOException */ User canUserSeeUsersData(RequestAndResponse requestAndResponse, boolean printError) throws IOException { final String effectiveUserId = getEffectiveUserId(requestAndResponse); final String queryUserId = getURIParameterOrUserId(requestAndResponse); final User effectiveUser = dbLogic.getUserById(effectiveUserId); final User queryUser = dbLogic.getUserById(queryUserId); if (isUserAnAdmin(requestAndResponse)) { return queryUser; } if (effectiveUser == null) { if (printError) { requestAndResponse.print(servletText .errorRequiresSignIn(allowSaveIfNotSignedIn)); } return null; } if (effectiveUser.getIsAccountClosed()) { if (printError) { requestAndResponse.print(servletText.errorAccountIsClosed()); } return null; } if (queryUser == null) { if (printError) { requestAndResponse.print(servletText.errorNoAccountFound()); } return null; } if (queryUser.getUserName().equals(effectiveUser.getUserName())) { return queryUser; } if (printError) { requestAndResponse.print(servletText.errorMayNotSeeList()); } return null; } /** Part of the HTML API. Shows a list of all the user's notebooks. */ private void handleHtmlShowNotebooks(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String paneId = "notebooks"; final String defaultTitle = servletText.pageTitleNotebooks(); final String notFoundMessage = servletText .errorNotebooksCouldNotBeFound(); final String mayNotSeeMessage = servletText.errorMayNotSeeNotebooks(); final String introMessage = servletText.introTextShowNotebooks(false); final String touchIntroMessage = servletText.introTextShowNotebooks(true); final String tooltipNewChild = servletText.tooltipNewNotebook(); final String buttonNewChild = servletText.buttonNewNotebook(); final String titleIfCanSee = defaultTitle; boolean userCanSee = false; final User user = canUserSeeUsersData(requestAndResponse, false); Entry root = null; if (user != null) { root = dbLogic.getEntryById(user.getTableOfContentsId()); userCanSee = true; } handleHtmlShowEntryTree(requestAndResponse, paneId, defaultTitle, notFoundMessage, mayNotSeeMessage, introMessage, touchIntroMessage, tooltipNewChild, buttonNewChild, titleIfCanSee, root, userCanSee, user, false, "showPopupForCreateNotebook", "notebooks", true); } /** * Adds a title to the response if needed. Returns true if the caller should * not build a page at this point. */ private boolean addTitle(RequestAndResponse requestAndResponse, String title) { if (!requestAndResponse.justGetTitle) { return false; } if (requestAndResponse.totalTitle == null) { requestAndResponse.totalTitle = new StringBuilder(); } else { requestAndResponse.totalTitle.append(" | "); } requestAndResponse.totalTitle.append(title.replace("|", "")); return true; } Random random = new Random(); /** * Returns a pseudo-random number between min and max, inclusive. The * difference between min and max can be at most * <code>Integer.MAX_VALUE - 1</code>. * * @param min * Minimum value * @param max * Maximum value. Must be greater than min. * @return Integer between min and max, inclusive. * @see java.util.Random#nextInt(int) */ synchronized private int randInt(int min, int max) { // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive return random.nextInt((max - min) + 1) + min; } /** * Part of the HTML API. Creates a note and forwards to an url to display * it. */ private void handleHtmlMakeNotebook(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String note = requestAndResponse.request .getParameter(DbLogic.Constants.note); final boolean isPublic = getCheckBoxValue(requestAndResponse, "isPublic"); final String csrft = requestAndResponse.getParameter("csrft"); if (isTheCsrftWrong(requestAndResponse, csrft)) { requestAndResponse.response.sendRedirect("/couldNotCreateNote"); return; } String noteId = null; final Errors errors = new Errors(); try { final Long time = new Long(System.currentTimeMillis()); User user = null; final String userId = getEffectiveUserId(requestAndResponse); if (userId == null && allowSaveIfNotSignedIn) { user = createAnonUser(); if (user == null) { requestAndResponse.response .sendRedirect("/couldNotCreateNote"); return; } else { mapSessionToUser(requestAndResponse, user.getId()); } } else { user = dbLogic.getUserById(userId); if (user != null && user.getIsAccountClosed()) { user = null; } } if (user == null) { requestAndResponse.response.sendRedirect("/couldNotCreateNote"); return; } else if (user.getIsAccountClosed()) { requestAndResponse.print(servletText.errorAccountIsClosed()); return; } if (!EntryAttributeValidator.isNotebookTitleValid(note)) { returnJson400(requestAndResponse, servletText.errorNoteIsInvalid()); return; } boolean addSampleNote = !doesUserHaveAnyNotebooks(requestAndResponse); final Entry entry = dbLogic.createEntryNoteBook(user, note, time, null, null, false, false, isPublic, isUserAnAdmin(requestAndResponse), addSampleNote, errors); if (entry == null) { requestAndResponse.response.sendRedirect("/couldNotCreateNote"); return; } noteId = entry.getId(); dbLogic.commit(); } catch (final PersistenceException e) { requestAndResponse.response.sendRedirect("/couldNotCreateNote"); return; } requestAndResponse.response.sendRedirect("/notebook/" + noteId); } /** Tries a few times to create an anonymous user. */ private User createAnonUser() { for (int i = 0; i < 10; ++i) { final User user = dbLogic.createUser("anon" + randInt(1, Integer.MAX_VALUE)); if (user != null) { user.setWasCreatedAsAnon(true); user.setIsAnon(true); return user; } } return null; } /** Part of the JSON API. Moves a note up or down. */ private void handleJsonMoveNotes(RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.setResponseContentTypeJson(); String[] ids; String direction; String csrft; try { final JsonNodeHelper json = getJsonNode(requestAndResponse); ids = json.getStringArray("ids"); direction = json.getString("direction"); csrft = json.getString("csrft"); } catch (final IOException e) { returnJson400(requestAndResponse, servletText.errorJson()); return; } if (isTheCsrftWrong(requestAndResponse, csrft)) { returnJson400(requestAndResponse, servletText.errorRequiresSignIn(false)); return; } try { final Errors errors = new Errors(); final User user = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); if (user == null) { returnJson400(requestAndResponse, servletText.errorRequiresSignIn(false)); return; } if (user.getIsAccountClosed()) { returnJson400(requestAndResponse, servletText.errorAccountIsClosed()); } final HashSet<String> movedIdsSet = new HashSet<String>(); for (int i = 0; i < ids.length; ++i) { final String id = ids[i]; if (!dbLogic.getIdGenerator().isIdWellFormed(id)) { returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat()); return; } final Entry entry = dbLogic.getEntryById(id); if (entry == null) { returnJson400(requestAndResponse, servletText.errorEntryCouldNotBeFound()); return; } if (movedIdsSet.contains(id)) { returnJson400(requestAndResponse, servletText.errorDuplicateEntry()); return; } movedIdsSet.add(id); if (!dbLogic.moveEntry(user, entry, direction, isUserAnAdmin(requestAndResponse), errors)) { returnJson400(requestAndResponse, errors); return; } } dbLogic.commit(); returnJson200(requestAndResponse); } catch (final PersistenceException e) { logger.log(Level.INFO, "Exception", e); returnJson500(requestAndResponse, servletText.errorInternalDatabase()); } } /** Part of the JSON API. Makes entry a child of another one. */ private void handleJsonMakeChildren(RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.setResponseContentTypeJson(); String targetId; String[] movedIds; boolean justTheEntry; String csrft; try { final JsonNodeHelper json = getJsonNode(requestAndResponse); targetId = json.getString("targetId"); movedIds = json.getStringArray("movedIds"); justTheEntry = json.getBoolean("justTheEntry"); csrft = json.getString("csrft"); } catch (final IOException e) { returnJson400(requestAndResponse, servletText.errorJson()); return; } if (isTheCsrftWrong(requestAndResponse, csrft)) { returnJson400(requestAndResponse, servletText.errorRequiresSignIn(false)); return; } if (!dbLogic.getIdGenerator().isIdWellFormed(targetId)) { returnJson400(requestAndResponse, servletText.errorTargetIdInvalidFormat()); return; } try { final Errors errors = new Errors(); final User user = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); if (user == null) { returnJson400(requestAndResponse, servletText.errorRequiresSignIn(false)); return; } if (user.getIsAccountClosed()) { returnJson400(requestAndResponse, servletText.errorAccountIsClosed()); } final Entry parent = dbLogic.getEntryById(targetId); if (parent == null) { returnJson400(requestAndResponse, servletText.errorTargetParentCouldNotBeFound()); return; } final LinkedList<EntryAndIsFromList> entriesToMove = new LinkedList<EntryAndIsFromList>(); final String errorMessage = validateEntriesParentsBeforeChildren( requestAndResponse, movedIds, entriesToMove); if (errorMessage != null) { returnJson400(requestAndResponse, errorMessage); return; } final StringBuilder result = new StringBuilder(); result.append("["); boolean isFirst = true; for (final EntryAndIsFromList entryToMove : entriesToMove) { if (parent.getId().equals(entryToMove.entry.getId())) { returnJson400(requestAndResponse, servletText.errorTargetAndObjectCanNotBeTheSame()); return; } if (!dbLogic.makeEntryAChildOfAParent(user, parent, entryToMove.entry, justTheEntry, isUserAnAdmin(requestAndResponse), errors)) { returnJson400(requestAndResponse, errors); return; } if (entryToMove.isFromList) { if (!isFirst) { result.append(","); } result.append("{"); result.append("\"id\":\"" + entryToMove.entry.getId() + "\",\n"); addJsonForEntry(result, entryToMove.entry, false, false, false, true); result.append("}"); isFirst = false; } } result.append("]"); dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { logger.log(Level.INFO, "Exception", e); returnJson500(requestAndResponse, servletText.errorInternalDatabase()); } } static class EntryAndIsFromList { EntryAndIsFromList(Entry entry, boolean isFromList) { this.entry = entry; this.isFromList = isFromList; } public Entry entry; public final boolean isFromList; } /** * Validates a list of entries, in that the IDs must be well formed, the * entries must exist and the parents must be placed before the children. * Put the validated Entries in the same order as the IDs in the * validatedEntriesList parameter. Returns null if there was no error. God, * how I long to code in a better language. */ private String validateEntriesParentsBeforeChildren( RequestAndResponse requestAndResponse, String[] idsToValidate, LinkedList<EntryAndIsFromList> validatedEntriesList) throws ServletException, IOException { // Iterate in reverse to validate that parents are moved before // children. final HashSet<String> validatedIdsSet = new HashSet<String>(); for (int i = idsToValidate.length - 1; i >= 0; --i) { final String[] idToValidateArray = idsToValidate[i].split(":"); final String idToValidate = idToValidateArray[idToValidateArray.length == 1 ? 0 : 1]; final boolean isFromList = idToValidateArray.length != 1; if (!dbLogic.getIdGenerator().isIdWellFormed(idToValidate)) { return servletText.errorIdIsInvalidFormat(); } final Entry movedEntry = dbLogic.getEntryById(idToValidate); if (movedEntry == null) { return servletText.errorEntryCouldNotBeFound(); } if (validatedIdsSet.contains(idToValidate)) { return servletText.errorDuplicateEntry(); } // Validate that parents are moved before children. validatedIdsSet.add(idToValidate); final Entry oldParentOfMovedEntry = dbLogic.getEntryById(movedEntry .getParentId()); if (oldParentOfMovedEntry != null && validatedIdsSet.contains(oldParentOfMovedEntry.getId())) { servletText.errorParentMustBeMovedBeforeChild(); } validatedEntriesList.addFirst(new EntryAndIsFromList(movedEntry, isFromList)); } return null; } /** Part of the JSON API. Makes entry a sibling of another one. */ private void handleJsonMakeSiblings(RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.setResponseContentTypeJson(); String[] movedIds; String targetId; String placement; boolean justTheEntry; String csrft; try { final JsonNodeHelper json = getJsonNode(requestAndResponse); movedIds = json.getStringArray("movedIds"); targetId = json.getString("targetId"); placement = json.getString("placement"); justTheEntry = json.getBoolean("justTheEntry"); csrft = json.getString("csrft"); } catch (final IOException e) { returnJson400(requestAndResponse, servletText.errorJson()); return; } if (isTheCsrftWrong(requestAndResponse, csrft)) { returnJson400(requestAndResponse, servletText.errorRequiresSignIn(false)); return; } if (placement == null || !(placement.equals("next") || placement.equals("previous"))) { returnJson400(requestAndResponse, servletText.errorInvalidPlacementValue()); return; } if (!dbLogic.getIdGenerator().isIdWellFormed(targetId)) { returnJson400(requestAndResponse, servletText.errorTargetIdInvalidFormat()); return; } try { final Errors errors = new Errors(); final User user = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); if (user == null) { returnJson400(requestAndResponse, servletText.errorRequiresSignIn(false)); return; } if (user.getIsAccountClosed()) { returnJson400(requestAndResponse, servletText.errorAccountIsClosed()); } final Entry sibling = dbLogic.getEntryById(targetId); if (sibling == null) { returnJson400(requestAndResponse, servletText.errorTargetNoteCouldNotBeFound()); return; } final LinkedList<EntryAndIsFromList> entriesToMove = new LinkedList<EntryAndIsFromList>(); final String errorMessage = validateEntriesParentsBeforeChildren( requestAndResponse, movedIds, entriesToMove); if (errorMessage != null) { returnJson400(requestAndResponse, errorMessage); return; } final StringBuilder result = new StringBuilder(); result.append("["); boolean isFirst = true; for (final EntryAndIsFromList entryToMove : entriesToMove) { if (sibling.getId().equals(entryToMove.entry.getId())) { returnJson400(requestAndResponse, servletText.errorTargetAndObjectCanNotBeTheSame()); return; } if (!dbLogic.makeEntrySiblingOfAnother(user, sibling, entryToMove.entry, justTheEntry, placement, isUserAnAdmin(requestAndResponse), errors)) { returnJson400(requestAndResponse, errors); return; } if (entryToMove.isFromList) { if (!isFirst) { result.append(","); } result.append("{"); result.append("\"id\":\"" + entryToMove.entry.getId() + "\",\n"); addJsonForEntry(result, entryToMove.entry, false, false, false, true); result.append("}"); isFirst = false; } } result.append("]"); dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { logger.log(Level.INFO, "Exception", e); returnJson500(requestAndResponse, servletText.errorInternalDatabase()); } } /** Part of the JSON API. Gets the path to the notebook for the entry. */ private void handleJsonGetNotebookPath(RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.setResponseContentTypeJson(); String entryId; String csrft; try { final JsonNodeHelper json = getJsonNode(requestAndResponse); entryId = json.getString("entryId"); csrft = json.getString("csrft"); } catch (final IOException e) { returnJson400(requestAndResponse, servletText.errorJson()); return; } if (isTheCsrftWrong(requestAndResponse, csrft)) { returnJson400(requestAndResponse, servletText.errorRequiresSignIn(false)); return; } if (!dbLogic.getIdGenerator().isIdWellFormed(entryId)) { returnJson400(requestAndResponse, servletText.errorTargetIdInvalidFormat()); return; } try { final User user = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); if (user == null) { returnJson400(requestAndResponse, servletText.errorRequiresSignIn(false)); return; } if (user.getIsAccountClosed()) { returnJson400(requestAndResponse, servletText.errorAccountIsClosed()); } Entry entry = dbLogic.getEntryById(entryId); if (entry == null) { returnJson400(requestAndResponse, servletText.errorTargetNoteCouldNotBeFound()); return; } final StringBuilder result = new StringBuilder(); result.append("["); boolean isFirst = true; while (entry != null) { if (!isFirst) { result.append(","); } isFirst = false; result.append(JsonBuilder.quote(entry.getId())); entry = dbLogic.getEntryById(entry.getParentId()); if (entry != null && entry.isRoot()) { entry = dbLogic.getEntryById(entry.getNotebookId()); result.append(","); result.append(JsonBuilder.quote(entry.getId())); break; } } result.append("]"); dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { logger.log(Level.INFO, "Exception", e); returnJson500(requestAndResponse, servletText.errorInternalDatabase()); } } /** Part of the JSON API. Handles many note operations. */ private void handleJsonNoteOp(RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.setResponseContentTypeJson(); String type = null; String note = null; String quotation = null; String id = null; String ids = null; String noteop = null; String childrenAction = null; boolean insertAsFirstChild = false; boolean isPublic = false; String csrft = null; boolean unlinkOnly = false; try { final JsonNodeHelper json = getJsonNode(requestAndResponse); type = json.getString(DbLogic.Constants.type); note = json.getString(DbLogic.Constants.note); quotation = json.getString(DbLogic.Constants.quotation); id = json.getString(DbLogic.Constants.id); ids = json.getString("ids"); noteop = json.getString("noteop"); childrenAction = json.getString("childrenAction"); insertAsFirstChild = json.getBoolean("insertAsFirstChild"); isPublic = json.getBoolean("isPublic"); unlinkOnly = json.getBoolean("unlinkOnly"); csrft = json.getString("csrft"); } catch (final IOException e) { returnJson400(requestAndResponse, servletText.errorJson()); return; } if (isTheCsrftWrong(requestAndResponse, csrft)) { returnJson400(requestAndResponse, servletText.errorRequiresSignIn(false)); return; } if (!EntryAttributeValidator.isNoteValid(note)) { returnJson400(requestAndResponse, servletText.errorNoteIsInvalid()); return; } if (type != null && type.equals(Constants.note) && !EntryAttributeValidator.isNoteValid(note)) { returnJson400(requestAndResponse, servletText.errorNoteIsInvalid()); return; } if (type != null && type.equals(Constants.notebook) && !EntryAttributeValidator.isNotebookTitleValid(note)) { returnJson400(requestAndResponse, servletText.errorNoteIsInvalid()); return; } if (!EntryAttributeValidator.isQuotationValid(quotation)) { returnJson400(requestAndResponse, servletText.errorQuotationIsInvalid()); return; } try { final Long time = new Long(System.currentTimeMillis()); final Errors errors = new Errors(); final StringBuilder result = new StringBuilder(); User user = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); boolean userWasSignedIn = false; // Create the user if needed and possible. if (user == null) { if (allowSaveIfNotSignedIn && noteop != null && noteop.equals("newNotebook")) { user = createAnonUser(); if (user == null) { returnJson400(requestAndResponse, servletText.errorCouldNotCreateAccount()); return; } else { mapSessionToUser(requestAndResponse, user.getId()); userWasSignedIn = true; } } else { returnJson400(requestAndResponse, servletText.errorRequiresSignIn(false)); return; } } if (user.getIsAccountClosed()) { returnJson400(requestAndResponse, servletText.errorAccountIsClosed()); return; } result.append("{\"modTime\": " + time + "\n"); Entry entry = null; boolean includeNote = false; boolean success = false; ArrayList<String> deletedEntryIds = null; if (noteop != null) { if (noteop.equals("edit") || noteop.equals("editNotebook") || noteop.equals("editSource") || noteop.equals("editNoteText")) { if (id == null) { returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat()); return; } final String[] idParts = id.split(":"); final String trueId = idParts[idParts.length == 1 ? 0 : 1]; if (!dbLogic.getIdGenerator().isIdWellFormed(trueId)) { returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat()); return; } if (noteop.equals("editNoteText")) { entry = dbLogic.getEntryById(trueId); if (entry == null) { Errors.add(errors, servletText.errorEntryCouldNotBeFound()); } else { entry = dbLogic.editEntry(user, trueId, note, entry.getQuotation(), entry.getIsPublic(), time, isUserAnAdmin(requestAndResponse), errors); } } else { entry = dbLogic.editEntry(user, trueId, note, quotation, isPublic, time, isUserAnAdmin(requestAndResponse), errors); } includeNote = true; success = entry != null; } else if (noteop.equals("delete") || noteop.equals("deleteNotebook") || noteop.equals("deleteSource")) { deletedEntryIds = new ArrayList<String>(); if (ids == null) { returnJson400(requestAndResponse, servletText.errorIdsAreInvalidFormat()); return; } final String[] idsArray = ids.split(","); // Do this here so that we don't need to delete the orphan // functionality or tests. // It has also been disabled in the UI because probably no // one will want this feature unless it is more polished. if (childrenAction != null && childrenAction.equals("orphan")) { childrenAction = "parent"; } if (noteop.equals("deleteNotebook") || noteop.equals("deleteSource")) { childrenAction = "parent"; } success = true; final LinkedList<EntryAndIsFromList> entriesToDeleteOrUnlink = new LinkedList<EntryAndIsFromList>(); String errorMessage = validateEntriesParentsBeforeChildren( requestAndResponse, idsArray, entriesToDeleteOrUnlink); for (final EntryAndIsFromList entryToDeleteOrUnlink : entriesToDeleteOrUnlink) { if (entryToDeleteOrUnlink.entry.getType().equals( Constants.tableofcontents) || entryToDeleteOrUnlink.entry.getType().equals( Constants.root)) { errorMessage = servletText .errorEntryCanNotBeDeleted(); } } final LinkedList<Entry> entriesToOnlyUnlink = new LinkedList<Entry>(); if (unlinkOnly) { for (final EntryAndIsFromList entryToDeleteOrUnlink : entriesToDeleteOrUnlink) { if (entryToDeleteOrUnlink.entry.isQuotation() || entryToDeleteOrUnlink.entry.isSource()) { entriesToOnlyUnlink.push(entryToDeleteOrUnlink.entry); entryToDeleteOrUnlink.entry = null; } } } if (errorMessage != null) { success = false; errors.add(errorMessage); } else { for (final Entry entryToUnlink : entriesToOnlyUnlink) { success &= dbLogic.unlinkEntry(user, entryToUnlink, isUserAnAdmin(requestAndResponse), errors); } for (final EntryAndIsFromList entryToDelete : entriesToDeleteOrUnlink) { // Check to make sure the entry has not already been // deleted. if (entryToDelete.entry == null || dbLogic .wasEntryDeletedInThisTransaction(entryToDelete.entry)) { continue; } success &= dbLogic.deleteEntry(user, entryToDelete.entry, childrenAction, isUserAnAdmin(requestAndResponse), deletedEntryIds, errors); } } /** * Disable for now because probably no one will want this * feature unless it is more polished } else if * (noteop.equals("makeNotebook")) { String[] idsArray = * ids.split(","); * * success = true; * * final LinkedList<Entry> entriesToMakeNotebooks = new * LinkedList<Entry>(); final String errorMessage = * validateEntriesParentsBeforeChildren( requestAndResponse, * idsArray, entriesToMakeNotebooks); if (errorMessage != * null) { success = false; errors.add(errorMessage); } else * { for (Entry entryToMakeNotebook : * entriesToMakeNotebooks) { success &= * dbLogic.makeNotebookEntry( user, entryToMakeNotebook, * isUserAnAdmin(requestAndResponse), errors); } } */ } else if (noteop.equals("insert")) { if (id == null || !dbLogic.getIdGenerator().isIdWellFormed(id)) { returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat()); return; } entry = dbLogic.createSimpleEntry(user, note, time, id, TreeRelType.Child, false, false, isPublic, isUserAnAdmin(requestAndResponse), type, errors, null); includeNote = true; success = entry != null; } else if (noteop.equals("putUnderneath")) { if (id == null || !dbLogic.getIdGenerator().isIdWellFormed(id)) { returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat()); return; } entry = dbLogic.createSimpleEntry(user, note, time, id, TreeRelType.Parent, true, false, isPublic, isUserAnAdmin(requestAndResponse), type, errors, null); includeNote = true; success = entry != null; } else if (noteop.equals("createChild")) { if (id == null || !dbLogic.getIdGenerator().isIdWellFormed(id)) { returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat()); return; } entry = dbLogic.createSimpleEntry(user, note, time, id, TreeRelType.Parent, false, insertAsFirstChild, isPublic, isUserAnAdmin(requestAndResponse), type, errors, null); includeNote = true; success = entry != null; } else if (noteop.equals("newNotebook")) { boolean addSampleNote = !doesUserHaveAnyNotebooks(requestAndResponse); entry = dbLogic.createEntryNoteBook(user, note, time, null, null, false, false, isPublic, isUserAnAdmin(requestAndResponse), addSampleNote, errors); includeNote = true; success = entry != null; } else if (noteop.equals("putBefore")) { if (id == null || !dbLogic.getIdGenerator().isIdWellFormed(id)) { returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat()); return; } entry = dbLogic.createSimpleEntry(user, note, time, id, TreeRelType.Next, false, false, isPublic, isUserAnAdmin(requestAndResponse), type, errors, null); includeNote = true; success = entry != null; } else if (noteop.equals("putAfter")) { if (id == null || !dbLogic.getIdGenerator().isIdWellFormed(id)) { returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat()); return; } entry = dbLogic.createSimpleEntry(user, note, time, id, TreeRelType.Previous, false, isPublic, isUserAnAdmin(requestAndResponse), false, type, errors, null); includeNote = true; success = entry != null; } else { errors.add(servletText.errorInvalidOperation()); } } else { errors.add(servletText.errorMissingOperation()); } if (!success) { requestAndResponse.response .setStatus(HttpServletResponse.SC_BAD_REQUEST); result.append(",\"success\":false"); result.append(","); errorsToJson(errors, result); } else { result.append(",\"success\":true"); } if (entry != null) { result.append(",\"id\":\"" + entry.getId() + "\"\n"); if (includeNote) { result.append(","); addJsonForEntry( result, entry, noteop.equals("edit") || noteop.equals("editNotebook") || noteop.equals("editSource") || noteop.equals("editNoteText"), noteop.equals("newNotebook"), userWasSignedIn, true); } } if (deletedEntryIds != null) { result.append(", \"deleted\": ["); boolean isFirst = true; for (final String deletedEntryId : deletedEntryIds) { if (!isFirst) { result.append(","); } isFirst = false; result.append("\"" + deletedEntryId + "\""); } result.append("]"); } result.append("}\n"); dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { logger.log(Level.INFO, "Exception", e); returnJson500(requestAndResponse, servletText.errorInternalDatabase()); } } /** Adds JSON for the entry. */ private void addJsonForEntry(final StringBuilder result, Entry entry, boolean includeJustTextFields, boolean includeUserWasSignIn, boolean userWasSignedIn, boolean forceQuotationToNote) throws IOException { result.append("\"note\":" + JsonBuilder.quote(entry.getNoteOrTitle("")) + "\n"); result.append(",\"quotation\":" + JsonBuilder.quote(entry.getQuotation("")) + "\n"); result.append(",\"isPublic\":" + entry.getIsPublic() + "\n"); String typeToAdd = entry.getType(); if (typeToAdd.equals(DbLogic.Constants.quotation)) { typeToAdd = DbLogic.Constants.note; } result.append(",\"type\":\"" + typeToAdd + "\"\n"); if (includeUserWasSignIn) { result.append(",\"userWasSignedIn\":" + userWasSignedIn + "\n"); } if (includeJustTextFields) { result.append(",\"noteHtml\":" + JsonBuilder.quote(getNoteHtml(entry, false, entry.hasQuotation(), true)) + "\n"); result.append(",\"quotationHtml\":" + JsonBuilder.quote(getQuotationHtml(entry, true)) + "\n"); } else { final StringBuilder innerResult = new StringBuilder(); addEntryHtmlToTreeSimple(entry, innerResult, null, 0, !entry.isNotebook()); result.append(",\"subtreeHtml\":" + JsonBuilder.quote(innerResult.toString()) + "\n"); } } /** Part of the JSON API. Handles sign out requests. */ private void handleJsonSignOut(RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.setResponseContentTypeJson(); String csrft; boolean noMatterWhat; try { final JsonNodeHelper json = getJsonNode(requestAndResponse); csrft = json.getString("csrft"); noMatterWhat = json.getBoolean("noMatterWhat"); } catch (final IOException e) { returnJson400(requestAndResponse, servletText.errorJson()); return; } if (isTheCsrftWrong(requestAndResponse, csrft)) { returnJson400(requestAndResponse, servletText.errorRequiresSignIn(false)); return; } final User currentUser = dbLogic.getUserById(getEffectiveUserId(requestAndResponse)); boolean needsPassword = false; boolean needsUsername = false; if (currentUser != null) { needsPassword = doesUserNotHavePasswordAndNeedsIt(currentUser); needsUsername = currentUser.getIsAnon(); } if((needsUsername || needsPassword) && noMatterWhat == false) { requestAndResponse.setResponseContentTypeJson(); requestAndResponse.response.setStatus(HttpServletResponse.SC_BAD_REQUEST); requestAndResponse.print("{\"needsPassword\":" + needsPassword + ",\"needsUsername\":" + needsUsername + "}"); return; } unmapSessionToUser(requestAndResponse); returnJson200(requestAndResponse); } /** Part of the JSON API. Handles sign in requests. */ private void handleJsonSignIn(RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.setResponseContentTypeJson(); String userName; String password; String csrft; try { final JsonNodeHelper json = getJsonNode(requestAndResponse); userName = json.getString("username"); password = json.getString("password"); csrft = json.getString("csrft"); } catch (final IOException e) { returnJson400(requestAndResponse, servletText.errorJson()); return; } if (userName != null) { userName = userName.toLowerCase(); } if (isTheCsrftWrong(requestAndResponse, csrft)) { returnJson400(requestAndResponse, servletText.errorWrongCsrft()); return; } if (userName == null || userName.isEmpty()) { returnJson400(requestAndResponse, servletText.errorUsernameMustNotBeBlank()); return; } if (password == null || password.isEmpty()) { returnJson400(requestAndResponse, servletText.errorPasswordMustNotBeBlank()); return; } if (!AccountAttributeValidator.isUserNameValid(userName)) { returnJson400(requestAndResponse, servletText.errorUserNameIsNotValid()); return; } if (!AccountAttributeValidator.isPasswordValid(password)) { returnJson400(requestAndResponse, servletText.errorPasswordIsNotValid()); return; } try { final User user = dbLogic.getUserByUserName(userName); if (user == null) { returnJson400(requestAndResponse, servletText.errorNoAccountFound()); return; } if (user.getIsAccountClosed()) { returnJson400(requestAndResponse, servletText.errorAccountIsClosed()); return; } final String realPassword = user.getPassword(); if (realPassword == null || !realPassword.equals(DigestUtils.sha1Hex(password))) { returnJson400(requestAndResponse, servletText.errorPasswordIsIncorrect()); return; } mapSessionToUser(requestAndResponse, user.getId()); dbLogic.commit(); returnJson200(requestAndResponse); } catch (final PersistenceException e) { logger.log(Level.INFO, "Exception", e); returnJson500(requestAndResponse, servletText.errorInternalDatabase()); } } /** Maps the session to the user. */ private void mapSessionToUser(RequestAndResponse requestAndResponse, String userId) { requestAndResponse.request.getSession().setAttribute( sessionUserIdAttribute, userId); } /** Unmaps the session from the user. */ private void unmapSessionToUser(RequestAndResponse requestAndResponse) { requestAndResponse.request.getSession().removeAttribute( sessionUserIdAttribute); } /** Part of the JSON API. Handles sign in requests. */ private void handleJsonCreateAccount(RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.setResponseContentTypeJson(); String userName, password, password2, email; boolean mayContact = false; String csrft; try { final JsonNodeHelper json = getJsonNode(requestAndResponse); userName = json.getString("username"); password = json.getString("password"); password2 = json.getString("password2"); email = json.getString("email"); mayContact = json.getBoolean("mayContact"); csrft = json.getString("csrft"); } catch (final IOException e) { returnJson400(requestAndResponse, servletText.errorJson()); return; } if (userName != null) { userName = userName.toLowerCase(); } if (isTheCsrftWrong(requestAndResponse, csrft)) { returnJson400(requestAndResponse, servletText.errorWrongCsrft()); return; } if (!allowSelfSignUp) { returnJson400(requestAndResponse, servletText.errorSelfSignUpNotAllowed()); return; } if (userName == null || userName.isEmpty()) { returnJson400(requestAndResponse, servletText.errorUsernameMustNotBeBlank()); return; } if (password == null || password.isEmpty()) { returnJson400(requestAndResponse, servletText.errorFirstPasswordMustBeSet(true, null)); return; } if (password == null || password2.isEmpty()) { returnJson400(requestAndResponse, servletText.errorSecondPasswordMustBeSet(true, null)); return; } if (!password2.equals(password)) { returnJson400(requestAndResponse, servletText.errorPasswordsMustMatch()); return; } if (!AccountAttributeValidator.isUserNameValid(userName)) { returnJson400(requestAndResponse, servletText.errorUserNameIsNotValid()); return; } if (!AccountAttributeValidator.isPasswordValid(password)) { returnJson400(requestAndResponse, servletText.errorPasswordIsNotValid()); return; } if (email != null && email.isEmpty()) { email = null; } if (email != null && !AccountAttributeValidator.isEmailValid(email)) { returnJson400(requestAndResponse, servletText.errorEmailIsNotValid()); return; } try { User user = dbLogic.getUserByUserName(userName); if (user != null) { returnJson400(requestAndResponse, servletText.errorUserNameIsAlreadyTaken()); return; } user = dbLogic.createUser(userName); if (user == null) { returnJson400(requestAndResponse, servletText.errorCouldNotCreateAccount()); return; } user.setPassword(DigestUtils.sha1Hex(password)); user.setEmail(email); user.setMayContact(mayContact); mapSessionToUser(requestAndResponse, user.getId()); dbLogic.commit(); returnJson200(requestAndResponse); } catch (final PersistenceException e) { logger.log(Level.INFO, "Exception", e); returnJson500(requestAndResponse, servletText.errorInternalDatabase()); } } /** Part of the JSON API. Handles save option requests. */ private void handleJsonSaveOptions(RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.setResponseContentTypeJson(); boolean showTimestamps = false; boolean saveOnEnter = false; String csrft; try { final JsonNodeHelper json = getJsonNode(requestAndResponse); showTimestamps = json.getBoolean("showTimestamps"); saveOnEnter = json.getBoolean("saveOnEnter"); csrft = json.getString("csrft"); } catch (final IOException e) { returnJson400(requestAndResponse, servletText.errorJson()); return; } if (isTheCsrftWrong(requestAndResponse, csrft)) { requestAndResponse.print(servletText.errorRequiresSignIn(false)); return; } try { final User user = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); if (user == null) { requestAndResponse .print(servletText.errorRequiresSignIn(false)); return; } final String options = "{\"showTimestamps\":" + showTimestamps + ",\"saveOnEnter\":" + saveOnEnter + "}"; user.setOptions(options); dbLogic.commit(); returnJson200(requestAndResponse); } catch (final PersistenceException e) { logger.log(Level.INFO, "Exception", e); returnJson500(requestAndResponse, servletText.errorInternalDatabase()); } } /** * Returns a JSON node for the request's data. * * @throws IOException */ private JsonNodeHelper getJsonNode(RequestAndResponse requestAndResponse) throws IOException { final InputStream stream = requestAndResponse.request.getInputStream(); final InputStreamReader streamReader = new InputStreamReader(stream, Charset.forName("UTF-8")); final ObjectMapper mapper = new ObjectMapper(); final JsonNode node = mapper.readTree(streamReader); return new JsonNodeHelper(node); } /** Creates the user for single user mode. */ private void createTheUserForSingleUserMode() { if (!isInSingleUserMode()) { return; } try { final User user = dbLogic.getOrCreateUser(singleUserName); if (user == null) { logger.log(Level.SEVERE, "Could not create single user user"); return; } if (!user.getIsSingleUser()) { user.setIsSingleUser(true); } if (!user.getIsAdmin()) { user.setIsAdmin(true); } dbLogic.commit(); } catch (final PersistenceException e) { logger.log(Level.SEVERE, "Could not create single user user", e); } } /** Returns the sanitized Markdown HTML for some text. */ private String getMarkdownHtml(String text, boolean noLinks, boolean skipSanitizing) { if (text == null) { return ""; } final String markdown = (noLinks ? pegDownNolinkProcessor : pegDownProcessor).get().markdownToHtml(text, linkRenderer.get()); if (skipSanitizing) { return markdown; } final String cleaned = Jsoup.clean(markdown, whitelist.get()); return cleaned; } private static final ThreadLocal<Whitelist> whitelist = new ThreadLocal<Whitelist>() { @Override protected Whitelist initialValue() { return Whitelist.relaxed() .addEnforcedAttribute("a", "rel", "nofollow") .addEnforcedAttribute("a", "target", "_blank"); } }; private static final ThreadLocal<PegDownNoLinkProcessor> pegDownNolinkProcessor = new ThreadLocal<PegDownNoLinkProcessor>() { @Override protected PegDownNoLinkProcessor initialValue() { return new PegDownNoLinkProcessor(); } }; private static final ThreadLocal<PegDownProcessor> pegDownProcessor = new ThreadLocal<PegDownProcessor>() { @Override protected PegDownProcessor initialValue() { return new PegDownProcessor(); } }; private static final ThreadLocal<LinkRenderer> linkRenderer = new ThreadLocal<LinkRenderer>() { @Override protected LinkRenderer initialValue() { return new LinkRenderer(); } }; String standardCss = "<link rel=\"shortcut icon\" href=\"/images/favicon.ico\">\n" + "<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/ui.css\">\n"; /** * Holds settings related to how the header and footer for a response should * be created. Has a fluent interface to minimize boiler plate code. */ class PageWrapper { PageWrapper(RequestAndResponse requestAndResponse, String title, boolean needsAdmin) { this.requestAndResponse = requestAndResponse; this.title = title; this.needsAdmin = needsAdmin; } /** * Adds text to introduce the page. * * @throws IOException */ private void addPageIntroText(String clickText, String touchText) throws IOException { requestAndResponse.println("<div class=\"infotext\">" + clickText + "</div>"); addMetaData(new KeyAndValue("touchInfoText", touchText)); } /** * Appends an HTML header to a response. */ public void addHeader() throws IOException { final boolean onlyContent = getNoHeader(); final boolean isUserAnAdmin = isUserAnAdmin(requestAndResponse); addMetaData(new KeyAndValue("title", title)); if (!onlyContent) { if (!requestAndResponse.skipHeader) { final boolean isForPageRefresh = getIsForPageRefresh(); if (!isForPageRefresh) { requestAndResponse .print("<!doctype html>" + "<html>" + "<head>" // So that android renders text with the // correct font sizes. + "<meta name=\"HandheldFriendly\" content=\"true\"/>" + "<meta name=\"viewport\" content=\"width=device-width\" />" + "<title>"); requestAndResponse .print(requestAndResponse.titleAlreadyFormed ? requestAndResponse.totalTitle .toString() : title.replace("|", "")); if (paneId == null || !paneId.equals("welcome")) { requestAndResponse.print(" - " + servletText.labelApplicationName()); } else { requestAndResponse.print(servletText .pageTitleWelcomeExtra()); } requestAndResponse .print("</title>" + standardCss + (extraHeader != null ? extraHeader : "") + "</head>\n" + "<body><div id=\"siteRequirements\">" + servletText.errorJavaScriptNeeded() + "</div><script type=\"text/javascript\">\n" + "document.getElementById(\"siteRequirements\").style.display=\"none\";\n" + "var asyncScripts = [\n" + " '/js/mousetrap.min.js',\n" + " '/js/uiTextEn.js',\n" + " '/js/ui.js'\n" + "];\n" + "function loadScript(src, callback) {\n" + " var script = document.createElement('script');\n" + " script.type = 'text/javascript';\n" + " script.src = src;\n" + " script.onload = callback;\n" + " script.onreadystatechange = function() {\n" + " if (this.readyState == 'complete') {\n" + " callback();\n" + " }\n" + " }\n" + " document.head.appendChild(script);\n" + "}\n" + "var srcsLoaded = 0;\n" + "function maybeCallFinish() {\n" + " if(++srcsLoaded === asyncScripts.length + 1) {" + " onFinishFullPageLoad();\n" + " }\n" + "}\n" + "for(var scriptIndex = 0; scriptIndex < asyncScripts.length; ++scriptIndex) {\n" + " var script = document.createElement('script');\n" + " loadScript(asyncScripts[scriptIndex], maybeCallFinish);\n" + "}" + "</script>\n"); } requestAndResponse.print("<div id=\"allPanes\">"); // Add the portion of the left hand menu that is for all // users. requestAndResponse .print("<div><div class=\"paneContainer\"><div class=\"pane\" id=\"menu\">" + "<div class=\"paneSection\"><span><a id=\"appName\" title=\"" + servletText.labelApplicationNameTooltip() + "\" href=\"/\">" + servletText.labelApplicationName() + "</a></span><a onclick=\"showOrHideMenu();\" id=\"showMenu\" title=\"" + servletText.tooltipMenu() + "\">" + servletText.linkMenu() + "</a></div>"); // Add account, sign in, create account links as needed. if (!isUserSignedIn(requestAndResponse)) { requestAndResponse .print("<div class=\"paneSection\">\n"); requestAndResponse .print("<a onclick=\"closeMenuIfSmallDisplay(); signIn(); return false;\" title=\"" + servletText.tooltipSignIn() + "\">" + servletText.linkSignIn() + "</a>"); if (allowSelfSignUp) { requestAndResponse .print("<a onclick=\"closeMenuIfSmallDisplay(); createAccount(); return false;\" title=\"" + servletText .tooltipCreateAccount() + "\">" + servletText.linkCreateAccount() + "</a>"); } requestAndResponse.print("</div>\n"); } boolean startedCommandPaneSection = false; if (isUserSignedIn(requestAndResponse) || allowSaveIfNotSignedIn) { requestAndResponse .print("<div class=\"paneSection\">\n"); startedCommandPaneSection = true; requestAndResponse .print("<a onclick=\"closeMenuIfSmallDisplay(); showPopupForCreateNotebook(); return false;\" title=\"" + servletText .pageTitleCreateNoteTooltip() + "\" href=\"/newNotebook/\">" + servletText.pageTitleNewNotebook() + "</a>\n"); } if (isUserSignedIn(requestAndResponse)) { if (!startedCommandPaneSection) { startedCommandPaneSection = true; requestAndResponse .print("<div class=\"paneSection\">\n"); } requestAndResponse .print("<a onclick=\"newPaneForLink(event, '" + servletText.pageTitleNotebooks() + "', 'notebooks'); return false;\" title=\"" + servletText .pageTitleNotebooksTooltip() + "\" href=\"/notebooks/\">" + servletText.pageTitleNotebooks() + "</a>\n"); requestAndResponse .print("<a onclick=\"newPaneForLink(event, '" + servletText.pageTitleQuotations() + "', 'quotations'); return false;\" title=\"" + servletText .pageTitleQuotationsTooltip() + "\" href=\"/quotations/\">" + servletText.pageTitleQuotations() + "</a>\n"); requestAndResponse .print("<a onclick=\"newPaneForLink(event, '" + servletText.pageTitleSources() + "', 'sources'); return false;\" title=\"" + servletText .pageTitleSourcesTooltip() + "\" href=\"/sources/\">" + servletText.pageTitleSources() + "</a>\n"); requestAndResponse .print("<a onclick=\"newPaneForLink(event, '" + servletText.pageTitleSearch() + "', 'search'); return false;\" title=\"" + servletText .pageTitleSearchTooltip() + "\" href=\"/search/\">" + servletText.pageTitleSearch() + "</a>\n"); requestAndResponse .print("<a onclick=\"closeMenuIfSmallDisplay(); closeAllPanes(); return false;\" title=\"" + servletText .pageTitleCloseAllTooltip() + "\">" + servletText.pageTitleCloseAll() + "</a>\n"); } if (startedCommandPaneSection) { requestAndResponse.print("</div>\n"); } requestAndResponse .print("<div class=\"paneSection\">\n"); requestAndResponse .print("<a onclick=\"newPaneForLink(event, '" + servletText.pageTitleHelp() + "', 'help'); return false;\" title=\"" + servletText.pageTitleHelpTooltip() + "\" href=\"/help/\">" + servletText.pageTitleHelp() + "</a>\n"); requestAndResponse .print("<a onclick=\"closeMenuIfSmallDisplay(); showPopupForHelp(event); return false;\" title=\"" + servletText.pageTitleUiHelpTooltip() + "\" href=\"/help/\">" + servletText.pageTitleUiHelp() + "</a>\n"); if (isUserSignedIn(requestAndResponse)) { requestAndResponse .print("<a onclick=\"closeMenuIfSmallDisplay(); showPopupForOptions(); return false;\" title=\"" + servletText.tooltipOptions() + "\">" + servletText.linkOptions() + "</a>"); } requestAndResponse.print("</div>\n"); if (isUserSignedIn(requestAndResponse)) { requestAndResponse .print("<div class=\"paneSection\">\n"); if (!isInSingleUserMode()) { requestAndResponse .print("<a onclick=\"signOut(); return false;\" title=\"" + servletText.tooltipSignOut() + "\">" + servletText.linkSignOut() + "</a>"); requestAndResponse .print("<a onclick=\"newPaneForLink(event, '" + servletText.linkAccount() + "', 'account'); return false;\" href=\"/account/\" title=\"" + servletText.tooltipEditAccount() + "\">" + servletText.linkAccount() + "</a>"); } requestAndResponse .print("<a onclick=\"newPaneForLink(event, '" + servletText.pageTitleUserBackup() + "', 'backup'); return false;\" title=\"" + servletText.pageTitleUserBackupTooltip() + "\" href=\"/backup/\">" + servletText.pageTitleUserBackup() + "</a>\n"); requestAndResponse .print("<a onclick=\"newPaneForLink(event, '" + servletText.pageTitleUserRestore() + "', 'restore'); return false;\" title=\"" + servletText.pageTitleUserRestoreTooltip() + "\" href=\"/restore/\">" + servletText.pageTitleUserRestore() + "</a>\n"); requestAndResponse.print("</div>\n"); } // Add the portion of the left hand menu that is for admin // users. if (isUserAnAdmin) { requestAndResponse .print("<div class=\"paneSection\">\n"); requestAndResponse .print("<a onclick=\"newPaneForLink(event, '" + servletText.pageTitleAccounts() + "', 'accounts'); return false;\" title=\"" + servletText .pageTitleAccountsTooltip() + "\" href=\"/accounts/\">" + servletText.pageTitleAccounts() + "</a>\n"); requestAndResponse .print("<a onclick=\"newPaneForLink(event, '" + servletText.pageTitleShutdown() + "', 'shutdown'); return false;\" title=\"" + servletText .pageTitleShutdownTooltip() + "\" href=\"/shutdown/\">" + servletText.pageTitleShutdown() + "</a>\n"); requestAndResponse .print("<a onclick=\"newPaneForLink(event, '" + servletText.pageTitleClearDb() + "', 'clear'); return false;\" title=\"" + servletText.pageTitleClearDbTooltip() + "\" href=\"/clear/\">" + servletText.pageTitleClearDb() + "</a>\n"); requestAndResponse .print("<a onclick=\"newPaneForLink(event, '" + servletText.pageTitleOnlineBackupDb() + "', 'onlineBackup'); return false;\" title=\"" + servletText .pageTitleOnlineBackupDbTooltip() + "\" href=\"/onlineBackup/\">" + servletText.pageTitleOnlineBackupDb() + "</a>\n"); requestAndResponse .print("<a onclick=\"newPaneForLink(event, '" + servletText .pageTitleCheckDbForErrors() + "', 'checkForErrors'); return false;\" title=\"" + servletText .pageTitleCheckDbForErrorsTooltip() + "\" href=\"/checkForErrors/\">" + servletText .pageTitleCheckDbForErrors() + "</a>\n"); requestAndResponse .print("<a onclick=\"newPaneForLink(event, '" + servletText.pageTitleShowDbBackups() + "', 'backups'); return false;\" title=\"" + servletText .pageTitleShowDbBackupsTooltip() + "\" href=\"/backups/\">" + servletText.pageTitleShowDbBackups() + "</a>\n"); requestAndResponse .print("<a onclick=\"newPaneForLink(event, '" + servletText .pageTitleOfflineBackupDb() + "', 'offlineBackup'); return false;\" title=\"" + servletText .pageTitleOfflineBackupDbTooltip() + "\" href=\"/offlineBackup/\">" + servletText .pageTitleOfflineBackupDb() + "</a>\n"); requestAndResponse.print("</div>\n"); } requestAndResponse.print("<div class=\"paneSection\">\n"); if (!isOfficialSite) { requestAndResponse .print("<a target=\"_blank\" class=\"externalsite\" title=\"" + servletText .labelCrushPaperComTooltip() + "\" href=\"http://www.crushpaper.com\">crushpaper.com</a>"); if (versionNumber != null) { requestAndResponse .print("<span class=\"versionNumber\">v" + versionNumber + "</span>"); } } requestAndResponse .print("<a target=\"_blank\" class=\"externalsite\" title=\"" + servletText.labelChromeExtensionTooltip() + "\" href=\"" + servletText.urlChromeExtension() + "\">" + servletText.labelChromeExtension() + "</a>"); requestAndResponse .print("<a target=\"_blank\" class=\"externalsite\" title=\"" + servletText.labelDemoMovieTooltip() + "\" href=\"" + servletText.demoMovieUrl() + "\">" + servletText.labelDemoMovie() + "</a>"); requestAndResponse .print("<a target=\"_blank\" class=\"externalsite\" title=\"" + servletText.labelTwitterTooltip() + "\" href=\"https://twitter.com/ZapBlasterson\">Twitter</a>"); requestAndResponse .print("<a target=\"_blank\" class=\"externalsite\" title=\"" + servletText.labelGithubTooltip() + "\" href=\"https://github.com/ZapBlasterson/crushpaper\">GitHub</a>"); requestAndResponse .print("<a target=\"_blank\" class=\"externalsite\" title=\"" + servletText.labelGoogleGroupTooltip() + "\" href=\"https://groups.google.com/d/forum/crushpaper\">" + servletText.labelGoogleGroup() + "</a>"); requestAndResponse.print("</div>"); requestAndResponse.print("</div></div></div>"); } requestAndResponse .print("<div><div class=\"paneContainer\"><div " + (paneId != null ? "id=\"" + paneId + "\" " : "") + " class=\"pane contentPane\">"); } final boolean isWelcomePane = paneId != null && paneId.equals("welcome"); if (!getNoTitle()) { requestAndResponse .print("<div class=\"headerpane paneSection\" onmousedown=\"paneMoveOnMouseDown(event);\">" + "<div class=\"" + (isWelcomePane ? "welcomePaneTitle " : "") + " paneTitle\">" + (!isUserAnAdmin && needsAdmin ? servletText .notAllowedTitle() : title) + "</div>"); if (!isWelcomePane) { requestAndResponse .print("<div class=\"paneButtonsBg\"><div " + (paneId != null ? "id=\"buttons_" + paneId + "\" " : "") + " class=\"paneButtons\">"); if (includeExport) { requestAndResponse .print("<div class=\"exportIcon\" onclick=\"paneExportOnClick(event); return false;\"></div>"); } if (includeEdit) { requestAndResponse .print("<div class=\"editIcon\" onmouseover=\"panePencilOnMouseOver(event); return false;\" onmouseout=\"panePencilOnMouseOut(event); return false;\" onclick=\"panePencilOnClick(event); return false;\"></div>"); } if (includeDelete) { requestAndResponse .print("<div class=\"deleteIcon\" onclick=\"paneTrashOnClick(event); return false;\"></div>"); } requestAndResponse .print("<div title=\"" + servletText.tooltipRefreshPane() + "\" class=\"refreshIcon\" onclick=\"refreshPane(event); return false;\"></div>"); requestAndResponse .print("<div title=\"" + servletText.tooltipClosePane() + "\" class=\"paneCloseIcon\" onclick=\"closePane(event); return false;\"></div>"); requestAndResponse.print("</div></div>"); } requestAndResponse.print("</div><div class=\"paneSection\">\n"); } } /** Returns true if the request is for a refresh. */ private boolean getIsForPageRefresh() { final String value = requestAndResponse.request .getHeader("X-for-refresh"); return Boolean.valueOf(value); } /** Returns true if the request does not want the header. */ private boolean getNoHeader() { final String value = requestAndResponse.request .getHeader("X-no-header"); return Boolean.valueOf(value); } /** Returns true if the request does not want the title. */ private boolean getNoTitle() { final String value = requestAndResponse.request .getHeader("X-no-title"); return Boolean.valueOf(value); } /** Appends an HTML footer to a response. */ public void addFooter() throws IOException { requestAndResponse .print("\n<script type=\"application/json\" class=\"metaDataDictJson\">\n{\n"); final StringBuilder result = new StringBuilder(); boolean addedAnyYet = false; for (final KeyAndValue keyAndValue : metaData) { addedAnyYet = JsonBuilder.addPropertyToJsonString(result, keyAndValue.value, addedAnyYet, keyAndValue.key); } requestAndResponse.print(result.toString()); requestAndResponse.print("\n}\n</script>\n"); if(!getNoTitle()) { requestAndResponse .print("<div class=\"dragNsPane\" onmousedown=\"paneResizeOnMouseDown(event);\"></div>" + "<div class=\"dragEwPane\" onmousedown=\"paneResizeOnMouseDown(event);\"><div class=\"dragDiagPane\"></div></div>"); } requestAndResponse.print("</div></div></div></div>"); final boolean onlyContent = getNoHeader(); if (!onlyContent) { if (!requestAndResponse.skipFooter) { requestAndResponse .print("</div><div id=\"top\"></div><div id=\"bottom\"></div>"); requestAndResponse.print("<div id=\"overlay\"></div>\n"); // For user options. stashRequestUser(requestAndResponse); requestAndResponse .print("\n<script type=\"application/json\" id=\"optionsDictJson\">\n"); requestAndResponse.print(requestAndResponse.userOptions); requestAndResponse.print("\n</script>\n"); requestAndResponse .print("\n<script type=\"application/json\" id=\"sessionDictJson\">{\n"); if (httpsProxiedPort != null) { requestAndResponse.print("\"httpsPort\":" + httpsProxiedPort.intValue() + ","); } else if (httpsPort != null) { requestAndResponse.print("\"httpsPort\":" + httpsPort.intValue() + ","); } requestAndResponse.print("\"isSignedIn\":" + isUserSignedIn(requestAndResponse)); requestAndResponse.print("\n}</script>\n"); final boolean isForPageRefresh = getIsForPageRefresh(); if (!isForPageRefresh) { requestAndResponse.print("<script type=\"text/javascript\">\n" + "maybeCallFinish();\n" + "</script>\n"); requestAndResponse.print("</body>" + "</html>"); } } } } public PageWrapper setTitle(String title) { this.title = title; return this; } public PageWrapper setPaneId(String paneId) { this.paneId = paneId; return this; } public PageWrapper setIncludeEdit() { this.includeEdit = true; return this; } public PageWrapper setIncludeDelete() { this.includeDelete = true; return this; } public PageWrapper setIncludeExport() { this.includeExport = true; return this; } /** Adds meta data to the page that will be served to the client. */ public void addMetaData(KeyAndValue keyAndValue) { metaData.add(keyAndValue); } private final RequestAndResponse requestAndResponse; private String title; private String paneId; private final boolean needsAdmin; private boolean includeEdit; private boolean includeDelete; private boolean includeExport; private final ArrayList<KeyAndValue> metaData = new ArrayList<KeyAndValue>(); } static class KeyAndValue { public KeyAndValue(String key, Object value) { this.key = key; this.value = value; } final String key; final Object value; } /** Returns true if the user is signed in. */ private boolean isUserSignedIn(RequestAndResponse requestAndResponse) { return isInSingleUserMode() || requestAndResponse.request.getSession().getAttribute( sessionUserIdAttribute) != null; } /** Returns true if the server is in single user mode. */ private boolean isInSingleUserMode() { return singleUserName != null; } /** Returns an HTML 404. */ private void returnHtml404(RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.response.setStatus(HttpServletResponse.SC_NOT_FOUND); final String title = "Error 404"; if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false).setPaneId("404"); pageWrapper.addHeader(); requestAndResponse.print(servletText.errorPageNotFound()); pageWrapper.addFooter(); } /** Returns a JSON 200. */ private void returnJson200(RequestAndResponse requestAndResponse) throws ServletException, IOException { requestAndResponse.setResponseContentTypeJson(); requestAndResponse.print("{\"success\":true}"); } /** Returns a JSON 400. */ private void returnJson400(RequestAndResponse requestAndResponse, String text) throws ServletException, IOException { requestAndResponse.setResponseContentTypeJson(); requestAndResponse.response .setStatus(HttpServletResponse.SC_BAD_REQUEST); requestAndResponse.print("{\"errors\":[" + JsonBuilder.quote(text) + "] }"); } /** Returns a JSON 500. */ private void returnJson500(RequestAndResponse requestAndResponse, String text) throws ServletException, IOException { requestAndResponse.setResponseContentTypeJson(); requestAndResponse.response .setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); requestAndResponse.print("{\"errors\":[" + JsonBuilder.quote(text) + "] }"); } /** Returns a JSON 400. */ private void returnJson400(RequestAndResponse requestAndResponse, Errors errors) throws ServletException, IOException { requestAndResponse.setResponseContentTypeJson(); requestAndResponse.response .setStatus(HttpServletResponse.SC_BAD_REQUEST); requestAndResponse.print("{"); errorsToJson(errors, requestAndResponse.response.getWriter()); requestAndResponse.print("}"); } /** Helper method. Converts `errors` to JSON. */ private void errorsToJson(Errors errors, PrintWriter writer) { final StringBuilder result = new StringBuilder(); errorsToJson(errors, result); writer.print(result.toString()); } /** Helper method. Converts `errors` to JSON. */ private void errorsToJson(Errors errors, StringBuilder result) { result.append("\"errors\":["); if (errors != null && errors.hasErrors()) { boolean first = true; for (final String text : errors.getTexts()) { if (!first) { result.append(","); } first = false; result.append(JsonBuilder.quote(text)); } } result.append("]"); } /** Helper method. Converts `errors` to HTML. */ private void errorsToHTML(Errors errors, PrintWriter writer) { if (errors != null && errors.hasErrors()) { writer.print("<ol>"); for (final String text : errors.getTexts()) { writer.print("<li>"); writer.print(StringEscapeUtils.escapeHtml4(text)); writer.print("</li>"); } writer.print("</ol>"); } } /** Part of the HTML API. Shows the user's sources. */ private void handleHtmlShowSources(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleSources(); if (addTitle(requestAndResponse, title)) { return; } final String paneId = "sources"; final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false).setPaneId(paneId); pageWrapper.addHeader(); pageWrapper.addMetaData(new KeyAndValue("paneType", paneId)); pageWrapper.addPageIntroText(servletText.introTextShowSources(false), servletText.introTextShowSources(true)); try { final StringBuilder result = new StringBuilder(); User queryUser = null; if (null != (queryUser = canUserSeeUsersData(requestAndResponse, true))) { final ResultsPaginator paginator = new ResultsPaginator( requestAndResponse, servletText.sentenceNoSourcesExist(), result, servletText); startItemList(result, paneId); final ArrayList<EntryInfo> entryInfoList = new ArrayList<EntryInfo>(); final List<?> sources = dbLogic .getEntriesByUserIdAndType(queryUser.getId(), DbLogic.Constants.source, paginator.getStartPosition(), paginator.getMaxResults()); for (final Object sourceUncasted : sources) { final Entry entry = (Entry) sourceUncasted; final int resultNumber = paginator.next(); if (resultNumber == -1) { continue; } else if (resultNumber == 0) { break; } addSourceHtml(entry, result, SourceEmbedContext.InSources, null, resultNumber, paneId); addEntryToInfoList(entry, entryInfoList); } finishItemList(result); result.append("\n<script type=\"application/json\" class=\"entryInfoDictJson\">\n"); addJsonForEntryInfos(result, entryInfoList, paneId); result.append("\n</script>\n"); paginator.done(); } dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { requestAndResponse.print(servletText.errorInternalDatabase()); } pageWrapper.addFooter(); } /** Part of the HTML API. Shows search results and displays form. */ private void handleHtmlSearch(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleSearch(); if (addTitle(requestAndResponse, title)) { return; } String query = requestAndResponse.getParameter("q"); final boolean queryWasNull = query == null; if (query == null) { query = ""; } String dataSet = requestAndResponse.getParameter("s"); if (dataSet == null || (!dataSet.equals("quotations") && !dataSet.equals("sources") && !dataSet.equals("accounts") && !dataSet .equals("notebooks"))) { dataSet = "notes"; } if (!isUserAnAdmin(requestAndResponse) && dataSet.equals("accounts")) { dataSet = "notes"; } query = query.trim(); final String paneId = "search"; final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false).setPaneId(paneId); pageWrapper.addHeader(); requestAndResponse .print("<form action=\"" + StringEscapeUtils.escapeHtml4(requestAndResponse .getRequestURI()) + "\" method=\"GET\"><table class=\"nopadding\"><tr><td>" + "<input class=\"searchbox\" title=\"" + servletText.tooltipSearch() + "\" placeholder=\"" + servletText.placeholderSearch() + "\" type=\"text\" name=\"q\" value=\"" + StringEscapeUtils.escapeHtml4(query) + "\" autofocus></td></tr><tr><td>" + "<span class=\"searchRadio\"><input type=\"radio\" name=\"s\" value=\"notes\" id=\"searchNotes\"" + isInputChecked(dataSet, "notes") + "><label for=\"searchNotes\">" + servletText.labelSearchNotes() + "</label></span> " + "<span class=\"searchRadio\"><input type=\"radio\" name=\"s\" value=\"quotations\" id=\"searchQuotations\"" + isInputChecked(dataSet, "quotations") + "><label for=\"searchQuotations\">" + servletText.labelSearchQuotations() + "</label></span> " + "<span class=\"searchRadio\"><input type=\"radio\" name=\"s\" value=\"sources\" id=\"searchSources\"" + isInputChecked(dataSet, "sources") + "><label for=\"searchSources\">" + servletText.labelSearchSources() + "</label></span> " + "<span class=\"searchRadio\"><input type=\"radio\" name=\"s\" value=\"notebooks\" id=\"searchNotebooks\"" + isInputChecked(dataSet, "notebooks") + "><label for=\"searchNotebooks\">" + servletText.labelSearchNotebooks() + "</label></span>" + (!isUserAnAdmin(requestAndResponse) ? "" : "<input type=\"radio\" name=\"s\" value=\"accounts\" id=\"searchAccounts\"" + isInputChecked(dataSet, "accounts") + "><label for=\"searchAccounts\">" + servletText.labelSearchAccounts() + "</label>") + "</td></tr>" + "<tr><td><button onclick=\"replacePaneForForm(event, '" + servletText.buttonSearch() + "'); return false;\" class=\"specialbutton\" style=\"margin:10px 0px 10px 0px\">" + servletText.buttonSearch() + "</button></td></tr></table></form>"); if (!queryWasNull && query.isEmpty()) { requestAndResponse.print(servletText.errorQueryIsRequired()); } else if (dataSet == null || dataSet.isEmpty()) { requestAndResponse .print(servletText.errorSearchDataSetIsRequired()); } else if (!query.isEmpty()) { pageWrapper.addMetaData(new KeyAndValue("paneType", dataSet)); if (dataSet.equals("notes")) { handleHtmlSearchNotes(pageWrapper, requestAndResponse, query, paneId); } else if (dataSet.equals("quotations")) { handleHtmlSearchQuotations(pageWrapper, requestAndResponse, query, paneId); } else if (dataSet.equals("sources")) { handleHtmlSearchSources(pageWrapper, requestAndResponse, query, paneId); } else if (dataSet.equals("notebooks")) { handleHtmlSearchNotebooks(pageWrapper, requestAndResponse, query, paneId); } else if (dataSet.equals("accounts")) { pageWrapper.addMetaData(new KeyAndValue("notEditable", true)); handleHtmlSearchAccounts(pageWrapper, requestAndResponse, query, paneId); } else { requestAndResponse.print(servletText .errorSearchDataSetIsRequired()); } } pageWrapper.addFooter(); } /** * Returns a string which indicates if the input was checked in a submitted * form. */ private String isInputChecked(String dataSet, String value) { if (dataSet != null && dataSet.equals(value)) { return " checked"; } return ""; } /** Helper method. Shows search results within quotations. */ private void handleHtmlSearchQuotations(PageWrapper pageWrapper, RequestAndResponse requestAndResponse, String query, String paneId) throws IOException, ServletException { pageWrapper.addPageIntroText( servletText.introTextSearchQuotations(false), servletText.introTextSearchQuotations(true)); try { final StringBuilder result = new StringBuilder(); User queryUser = null; if (null != (queryUser = canUserSeeUsersData(requestAndResponse, true))) { final ResultsPaginator paginator = new ResultsPaginator( requestAndResponse, servletText.sentenceThereWereNoMatches(), result, servletText); try { final List<?> results = dbLogic .searchEntriesForUserByQuotation(queryUser.getId(), query, paginator.getStartPosition(), paginator.getMaxResults()); entryListToHtmlAndJson(paneId, result, paginator, results); } catch (EmptyQueryException e) { requestAndResponse.print(servletText.errorNeedLongerQuery()); } } dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { requestAndResponse.print(servletText.errorInternalDatabase()); } } /** Converts the entry list to HTML and JSON. */ private void entryListToHtmlAndJson(String paneId, final StringBuilder result, ResultsPaginator paginator, List<?> results) throws IOException { entryListToHtmlAndJson(paneId, result, paginator, results, SourceEmbedContext.InQuotations); } /** Converts the entry list to HTML and JSON. */ private void entryListToHtmlAndJson(String paneId, final StringBuilder result, ResultsPaginator paginator, List<?> results, SourceEmbedContext embedContext) throws IOException { startItemList(result, paneId); final ArrayList<EntryInfo> entryInfoList = new ArrayList<EntryInfo>(); for (final Object entryUncasted : results) { final Entry entry = (Entry) entryUncasted; final int resultNumber = paginator.next(); if (resultNumber == -1) { continue; } else if (resultNumber == 0) { break; } addEntryHtmlToList(entry, result, resultNumber, paneId, embedContext); addEntryToInfoList(entry, entryInfoList); } finishItemList(result); result.append("\n<script type=\"application/json\" class=\"entryInfoDictJson\">\n"); addJsonForEntryInfos(result, entryInfoList, paneId); result.append("\n</script>\n"); paginator.done(); } /** Helper method. Shows search results within notes. */ private void handleHtmlSearchNotes(PageWrapper pageWrapper, RequestAndResponse requestAndResponse, String query, String paneId) throws IOException, ServletException { pageWrapper.addPageIntroText(servletText.introTextSearchNotes(false), servletText.introTextSearchNotes(true)); try { final StringBuilder result = new StringBuilder(); User queryUser = null; if (null != (queryUser = canUserSeeUsersData(requestAndResponse, true))) { final ResultsPaginator paginator = new ResultsPaginator( requestAndResponse, servletText.sentenceThereWereNoMatches(), result, servletText); try { final List<?> results = dbLogic.searchEntriesForUserByNote( queryUser.getId(), query, paginator.getStartPosition(), paginator.getMaxResults()); entryListToHtmlAndJson(paneId, result, paginator, results); } catch (EmptyQueryException e) { requestAndResponse.print(servletText.errorNeedLongerQuery()); } } dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { requestAndResponse.print(servletText.errorInternalDatabase()); } } /** Helper method. Shows search results within notebooks. */ private void handleHtmlSearchNotebooks(PageWrapper pageWrapper, RequestAndResponse requestAndResponse, String query, String paneId) throws IOException, ServletException { pageWrapper.addPageIntroText( servletText.introTextSearchNotebooks(false), servletText.introTextSearchNotebooks(true)); try { final StringBuilder result = new StringBuilder(); User queryUser = null; if (null != (queryUser = canUserSeeUsersData(requestAndResponse, true))) { final ResultsPaginator paginator = new ResultsPaginator( requestAndResponse, servletText.sentenceThereWereNoMatches(), result, servletText); try { final List<?> results = dbLogic .searchEntriesForUserByNotebookTitle(queryUser.getId(), query, paginator.getStartPosition(), paginator.getMaxResults()); entryListToHtmlAndJson(paneId, result, paginator, results); } catch (EmptyQueryException e) { requestAndResponse.print(servletText.errorNeedLongerQuery()); } } dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { requestAndResponse.print(servletText.errorInternalDatabase()); } } /** Part of the JSON API. Returns the matches as JSON. */ private void handleJsonSearchNotes(RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.setResponseContentTypeJson(); String query = requestAndResponse.getParameter("q"); if (query == null) { query = ""; } query = query.trim(); if (!isUserSignedIn(requestAndResponse)) { returnJson400(requestAndResponse, servletText.errorRequiresSignIn(allowSaveIfNotSignedIn)); } else if (isUsersAccountClosed(requestAndResponse)) { returnJson400(requestAndResponse, servletText.errorAccountIsClosed()); } else { try { final StringBuilder result = new StringBuilder(); final User user = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); if (user != null) { final ResultsPaginator paginator = new ResultsPaginator( requestAndResponse, null, result, null); result.append("{ \"results\": ["); if (user != null) { boolean first = true; final List<?> results = dbLogic .searchEntriesForUserByNote(user.getId(), query, paginator.getStartPosition(), paginator.getMaxResults()); for (final Object entryUncasted : results) { final Entry entry = (Entry) entryUncasted; final int resultNumber = paginator.next(); if (resultNumber == -1) { continue; } else if (resultNumber == 0) { break; } if (!first) { result.append(","); first = false; } result.append("\n"); result.append("{ \"id\":\""); result.append(entry.getId()); result.append("\", \"note\":\""); result.append(StringEscapeUtils.escapeJson(entry .getNoteOrTitle(""))); result.append("\", \"quotation\":\""); result.append(StringEscapeUtils.escapeJson(entry .getQuotation(""))); result.append("\"}"); } } result.append("\n],\n\"more\": " + (paginator.hasMore() ? "true" : "false") + " }\n"); } dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (EmptyQueryException e) { returnJson400(requestAndResponse, servletText.errorNeedLongerQuery()); } catch (final PersistenceException e) { logger.log(Level.INFO, "Exception", e); returnJson500(requestAndResponse, servletText.errorInternalDatabase()); } } } /** Returns the entry's note html. */ private String getNoteHtml(Entry entry, boolean noLinks, boolean noPlaceholder, boolean nbsps) { final String value = entry.getNoteOrTitle(); if (value == null || value.isEmpty()) { if(noPlaceholder) { return ""; } String placeholder = servletText.fragmentBlankNote(); if (entry.isSource() || entry.isNotebook()) { placeholder = servletText.fragmentBlankTitle(); } return "<span class=\"placeholder\">" + placeholder + "</span>"; } return textToPreishHtml(value, nbsps); } /** Converts to preish HTML. */ private String textToPreishHtml(final String value, boolean nbsps) { if (value == null) { return ""; } String lines = StringEscapeUtils.escapeHtml4(value).replace("\n", "<br>"); if (nbsps) { return lines.replace(" ", "&nbsp;"); } return lines; } /** Returns the entry's quotation html. */ private String getQuotationHtml(Entry entry, boolean nbsps) { final String value = entry.getQuotation(); if (value == null || value.isEmpty()) { return "<span class=\"placeholder\">" + servletText.fragmentBlankQuotation() + "</span>"; } return "<div>" + textToPreishHtml(value, nbsps) + "</div>"; } /** Returns the destination directory for a new backup. */ private File getDbBackupDestination() { final SimpleDateFormat dayFormat = new SimpleDateFormat( "yyyy-MM-dd-HH-mm-ss"); final String daytime = dayFormat.format(new Date()); return new File(new File(dbLogic.getDbDirectory().getParentFile(), "backups"), daytime); } /** Part of the HTML API. Performs an offline backup of the database. */ private void handleHtmlDoOfflineDbBackup(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String csrft = requestAndResponse.getParameter("csrft"); final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, servletText.pageTitleOfflineBackupDb(), true) .setPaneId("offlineBackup"); pageWrapper.addHeader(); if (isTheCsrftWrong(requestAndResponse, csrft)) { requestAndResponse.print(servletText.errorRequiresSignIn(false)); } else if (!isUserAnAdmin(requestAndResponse)) { requestAndResponse.print(servletText.errorPageNotAllowed()); } else { final String source = dbLogic.getDbDirectory().getAbsolutePath(); final String destination = getDbBackupDestination().getAbsolutePath(); // This would be simpler but it throws exceptions on some files: // FileUtils.copyRecursively(); final StringBuffer out = new StringBuffer(); final StringBuffer err = new StringBuffer(); final int result = CommandLineUtil.copyDirectory(out, err, source, destination); if (result == 0) { requestAndResponse.print(servletText .sentenceOfflineDbBackupWasSuccessful()); } else { requestAndResponse.print(servletText .sentenceOfflineDbBackupWasNotSuccessful()); } } pageWrapper.addFooter(); } /** Part of the HTML API. Performs an online backup of the database. */ private void handleHtmlDoOnlineDbBackup(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String csrft = requestAndResponse.getParameter("csrft"); final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, servletText.pageTitleOnlineBackupDb(), true) .setPaneId("onlineBackup"); pageWrapper.addHeader(); if (isTheCsrftWrong(requestAndResponse, csrft)) { requestAndResponse.print(servletText.errorRequiresSignIn(false)); } else if (!isUserAnAdmin(requestAndResponse)) { requestAndResponse.print(servletText.errorPageNotAllowed()); } else { final String destination = getDbBackupDestination().getPath(); final int numRowsExtracted = dbLogic.doCsvDbBackup(destination); if (numRowsExtracted != -1) { requestAndResponse.print(servletText .sentenceOnlineDbBackupWasSuccessful(numRowsExtracted)); } else { requestAndResponse.print(servletText .sentenceOnlineDbBackupWasNotSuccessful()); } } pageWrapper.addFooter(); } /** Part of the HTML API. Show the offline DB backup form. */ private void handleHtmlOfflineDbBackupForm( RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleOfflineBackupDb(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, true).setPaneId("offlineBackup"); pageWrapper.addHeader(); if (!isUserAnAdmin(requestAndResponse)) { requestAndResponse.print(servletText.errorPageNotAllowed()); } else { requestAndResponse.print("<table class=\"nopadding\"><tr><td>"); requestAndResponse.print(servletText .pageTitleOfflineBackupDbTooltip()); requestAndResponse.print("<br><br>"); requestAndResponse.print(servletText.offlineBackupDbAreYouSure()); requestAndResponse.print("</td></tr><tr><td>"); requestAndResponse .print("<form action=\"/doOfflineBackup/" + "\" method=\"POST\">" + "<input type=\"hidden\" name=\"csrft\" value=\"" + getCsrft(requestAndResponse) + "\">" + "<button onclick=\"replacePaneForForm(event, '" + servletText.pageTitleOfflineBackupDb() + "', refreshBackupsPane); return false;\" class=\"specialbutton withTopMargin\">" + servletText.pageTitleOfflineBackupDb() + "</button></form>"); requestAndResponse.print("</td></tr></table>"); } pageWrapper.addFooter(); } /** Part of the HTML API. Show the online DB backup form. */ private void handleHtmlOnlineBackupForm( RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleOnlineBackupDb(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, true).setPaneId("onlineBackup"); pageWrapper.addHeader(); if (!isUserAnAdmin(requestAndResponse)) { requestAndResponse.print(servletText.errorPageNotAllowed()); } else { requestAndResponse.print("<table class=\"nopadding\"><tr><td>"); requestAndResponse.print(servletText .pageTitleOnlineBackupDbTooltip()); requestAndResponse.print("<br><br>"); requestAndResponse.print(servletText.onlineBackupDbAreYouSure()); requestAndResponse.print("</td></tr><tr><td>"); requestAndResponse .print("<form action=\"/doOnlineBackup/" + "\" method=\"POST\">" + "<input type=\"hidden\" name=\"csrft\" value=\"" + getCsrft(requestAndResponse) + "\">" + "<button onclick=\"replacePaneForForm(event, '" + servletText.pageTitleOnlineBackupDb() + "', refreshBackupsPane); return false;\" class=\"specialbutton withTopMargin\">" + servletText.pageTitleOnlineBackupDb() + "</button></form>"); requestAndResponse.print("</td></tr></table>"); } pageWrapper.addFooter(); } /** Part of the HTML API. Show the clear form. */ private void handleHtmlClearForm(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleClearDb(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, true).setPaneId("clear"); pageWrapper.addHeader(); if (!isUserAnAdmin(requestAndResponse)) { requestAndResponse.print(servletText.errorPageNotAllowed()); } else { requestAndResponse.print("<table class=\"nopadding\"><tr><td>"); requestAndResponse.print(servletText.pageTitleClearDbTooltip()); requestAndResponse.print("<br><br>"); requestAndResponse.print(servletText.clearAreYouSure()); requestAndResponse.print("</td></tr><tr><td>"); requestAndResponse .print("<form action=\"/doClear/" + "\" method=\"POST\">" + "<input type=\"hidden\" name=\"csrft\" value=\"" + getCsrft(requestAndResponse) + "\">" + "<button onclick=\"replacePaneForForm(event, '" + servletText.pageTitleClearDb() + "'); return false;\" class=\"specialbutton withTopMargin\">" + servletText.pageTitleClearDb() + "</button></form>"); requestAndResponse.print("</td></tr></table>"); } pageWrapper.addFooter(); } /** Part of the HTML API. Clears the database. */ private void handleHtmlDoClear(RequestAndResponse requestAndResponse) throws IOException, ServletException { final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, servletText.pageTitleClearDb(), true).setPaneId("clear"); pageWrapper.addHeader(); final String csrft = requestAndResponse.getParameter("csrft"); if (isTheCsrftWrong(requestAndResponse, csrft)) { requestAndResponse.print(servletText.errorRequiresSignIn(false)); } else if (!isUserAnAdmin(requestAndResponse)) { requestAndResponse.print(servletText.errorPageNotAllowed()); } else { dbLogic.clearData(); if (sessionManager != null) { try { sessionManager.reallyShutdownSessions(); } catch (final Exception e) { } } createTheUserForSingleUserMode(); requestAndResponse.print(servletText.sentenceCleared()); } pageWrapper.addFooter(); } /** Part of the HTML API. Shuts the process down. */ private void handleHtmlDoShutdown(RequestAndResponse requestAndResponse) throws IOException, ServletException { final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, servletText.pageTitleShutdown(), true).setPaneId("shutdown"); pageWrapper.addHeader(); final String csrft = requestAndResponse.getParameter("csrft"); if (isTheCsrftWrong(requestAndResponse, csrft)) { requestAndResponse.print(servletText.errorRequiresSignIn(false)); } else if (!isUserAnAdmin(requestAndResponse)) { requestAndResponse.print(servletText.errorPageNotAllowed()); } else { requestAndResponse.print(servletText.sentenceShuttingdown()); new Thread() { @Override public void run() { try { Thread.sleep(1000); } catch (final InterruptedException e) { } System.exit(0); } }.start(); } pageWrapper.addFooter(); } /** Part of the HTML API. Show the shutdown form. */ private void handleHtmlShutdownForm(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleShutdown(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, true).setPaneId("shutdown"); pageWrapper.addHeader(); if (!isUserAnAdmin(requestAndResponse)) { requestAndResponse.print(servletText.errorPageNotAllowed()); } else { requestAndResponse.print("<table class=\"nopadding\"><tr><td>"); requestAndResponse.print(servletText.shutdownAreYouSure()); requestAndResponse.print("</td></tr><tr><td>"); requestAndResponse .print("<form action=\"/doShutdown/" + "\" method=\"POST\">" + "<input type=\"hidden\" name=\"csrft\" value=\"" + getCsrft(requestAndResponse) + "\">" + "<button onclick=\"replacePaneForForm(event, '" + servletText.pageTitleShutdown() + "'); return false;\" class=\"specialbutton withTopMargin\">" + servletText.pageTitleShutdown() + "</button></form>"); requestAndResponse.print("</td></tr></table>"); } pageWrapper.addFooter(); } /** Part of the HTML API. Restores a db backup. */ private void handleHtmlShowRestoreDbBackupCommand( RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleRestoreBackupCommandDb(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, true); pageWrapper.addHeader(); if (!isUserAnAdmin(requestAndResponse)) { requestAndResponse.print(servletText.errorPageNotAllowed()); } else { final String name = requestAndResponse.getParameter("name"); if (name == null) { requestAndResponse.print(servletText .errorNoNameSpecifiedForRestoration()); } else { final File source = new File(new File(dbLogic.getDbDirectory() .getParent(), "backups"), name); boolean isOnlineBackup = false; // Determine if the backup directory is the result of an online // or offline backup. final File[] listOfFiles = source.listFiles(); if (listOfFiles != null) { for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].getName().endsWith(".csv")) { isOnlineBackup = true; break; } } } String cmd = null; if (isOnlineBackup) { cmd = "DELETE * FROM USR;\n"; cmd += "DELETE * FROM ENTRY;\n"; cmd += "INSERT INTO USR SELECT * FROM CSVREAD('" + (source.getAbsolutePath() + File.separator).replace("\\", "\\\\") + "usr.csv');\n"; cmd += "INSERT INTO ENTRY SELECT * FROM CSVREAD('" + (source.getAbsolutePath() + File.separator).replace("\\", "\\\\") + "entry.csv');"; } else { final String destination = dbLogic.getDbDirectory() .getAbsolutePath(); cmd = CommandLineUtil .getArgsForCopyAndPaste(CommandLineUtil .getRmDirArgs(destination)) + " && " + CommandLineUtil .getArgsForCopyAndPaste(CommandLineUtil .getCopyDirectoryArgs( source.getAbsolutePath(), destination)); } String htmlCmd = StringEscapeUtils.escapeHtml4(cmd); htmlCmd = htmlCmd.replace("\n", "<br><br>"); requestAndResponse.print(servletText.sentenceCmdForDbRestore() + "<br><br>" + htmlCmd); } } pageWrapper.addFooter(); } /** Part of the HTML API. Show the check for errors form. */ private void handleHtmlCheckForErrorsForm( RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleCheckDbForErrors(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, true).setPaneId("checkForErrors"); pageWrapper.addHeader(); if (!isUserAnAdmin(requestAndResponse)) { requestAndResponse.print(servletText.errorPageNotAllowed()); } else { requestAndResponse.print("<table class=\"nopadding\"><tr><td>"); requestAndResponse.print(servletText.checkDbForErrorsAreYouSure()); requestAndResponse.print("</td></tr><tr><td>"); requestAndResponse .print("<form action=\"/doCheckForErrors/" + "\" method=\"POST\">" + "<input type=\"hidden\" name=\"csrft\" value=\"" + getCsrft(requestAndResponse) + "\">" + "<button onclick=\"replacePaneForForm(event, '" + servletText.pageTitleCheckDbForErrors() + "'); return false;\" class=\"specialbutton withTopMargin\">" + servletText.pageTitleCheckDbForErrors() + "</button></form>"); requestAndResponse.print("</td></tr></table>"); } pageWrapper.addFooter(); } /** Part of the HTML API. Checks the database for errors. */ private void handleHtmlDoCheckForErrors( RequestAndResponse requestAndResponse) throws IOException, ServletException { final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, servletText.pageTitleCheckDbForErrors(), true) .setPaneId("checkForErrors"); pageWrapper.addHeader(); final String csrft = requestAndResponse.getParameter("csrft"); if (isTheCsrftWrong(requestAndResponse, csrft)) { requestAndResponse.print(servletText.errorRequiresSignIn(false)); } else if (!isUserAnAdmin(requestAndResponse)) { requestAndResponse.print(servletText.errorPageNotAllowed()); } else { final Errors errors = new Errors(); final boolean hasErrors = dbLogic.hasErrors(errors); requestAndResponse.print(hasErrors ? servletText .sentenceTheDatabaseHasErrors() : servletText .sentenceTheDatabaseHasNoErrors()); errorsToHTML(errors, requestAndResponse.response.getWriter()); } pageWrapper.addFooter(); } /** Part of the HTML API. Show the list of DB backups. */ private void handleHtmlShowDBBackups(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleShowDbBackups(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, true).setPaneId("backups"); pageWrapper.addHeader(); if (!isUserAnAdmin(requestAndResponse)) { requestAndResponse.print(servletText.errorPageNotAllowed()); } else { final File backupsDirectory = new File(dbLogic.getDbDirectory() .getParent(), "backups"); requestAndResponse.print(servletText.fragmentShowingContentsOf() + " " + backupsDirectory.getAbsolutePath() + "<br><br>"); boolean anyBackups = false; final StringBuilder result = new StringBuilder(); result.append("<ol>"); try { for (final File file : backupsDirectory.listFiles()) { anyBackups = true; result.append("<li>"); result.append(" <a onclick=\"showPopupWithPage(event, '" + servletText.pageTitleRestoreBackupCommandDb() + "'); return false;\" class=\"cursorIsPointer\" title=\"" + servletText.linkShowRestoreDbBackupCmdTooltip() + "\" href=\"/restoreBackupCommand/?name=" + file.getName() + "\">"); result.append(file.getName()); result.append("</a></li>"); } } catch (final Exception e) { } result.append("</ol>"); if (!anyBackups) { requestAndResponse.print(servletText .textNoDbBackupsHaveBeenCreated()); } else { requestAndResponse.print(servletText.sentenceToRestoreDbCommand() + "<br>"); requestAndResponse.print(result.toString()); } } pageWrapper.addFooter(); } /** Part of the HTML API. Show nothing. */ private void handleHtmlNothing(RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.print(servletText.sentenceNothingHere()); } /** Part of the HTML API. Show the restore form. */ private void handleHtmlUserRestoreForm(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleUserRestore(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false).setPaneId("restore"); pageWrapper.addHeader(); if (!isUserSignedIn(requestAndResponse)) { requestAndResponse.print(servletText .errorRequiresSignIn(allowSaveIfNotSignedIn)); } else if (isUsersAccountClosed(requestAndResponse)) { requestAndResponse.print(servletText.errorAccountIsClosed()); } else { pageWrapper.addPageIntroText(servletText.introTextRestore(), null); requestAndResponse .print("<iframe src=\"/restoreFrame/\" allowtransparency=\"true\"></iframe>"); } pageWrapper.addFooter(); } /** Part of the HTML API. Show the restore frame. */ private void handleHtmlUserRestoreFrame(RequestAndResponse requestAndResponse) throws IOException, ServletException { addIFrameHeader(requestAndResponse); if (!isUserSignedIn(requestAndResponse)) { requestAndResponse.print(servletText .errorRequiresSignIn(allowSaveIfNotSignedIn)); } else if (isUsersAccountClosed(requestAndResponse)) { requestAndResponse.print(servletText.errorAccountIsClosed()); } else { requestAndResponse .print("<form action=\"/doRestore/\" method=\"POST\" enctype=\"multipart/form-data\">" + "<input type=\"hidden\" name=\"csrft\" value=\"" + getCsrft(requestAndResponse) + "\">" + "<table class=\"nopadding\"><tr><td>" + "<input type=\"file\" name=\"file\"/>" + "</td></tr>" + "<tr><td>" + "<input type=\"checkbox\" name=\"reuseIds\" id=\"reuseIds\" checked><label for=\"reuseIds\">" + servletText.sentenceReuseIds() + "</label><br>" + "</td></tr>" + "<tr><td>" + "<input type=\"checkbox\" name=\"msWordListFormat\" id=\"msWordListFormat\"><label for=\"msWordListFormat\">" + servletText.sentenceMsWordListFormat() + "</label><br>" + "</td></tr>" + "<tr><td>" + "<button class=\"specialbutton withTopMargin\">" + servletText.buttonRestore() + "</button>" + "</td></tr></table>" + "</form>"); } addIFrameFooter(requestAndResponse); } /** * Adds a success message to the response. * * @throws IOException */ private void addSuccessMessage(RequestAndResponse requestAndResponse, String message) throws IOException { requestAndResponse.print("<span class=\"successMessage\">" + message + "</span>"); } /** * Adds a success message to the response. * * @throws IOException */ private void addErrorMessage(RequestAndResponse requestAndResponse, String message) throws IOException { requestAndResponse.print("<span class=\"errorMessage\">" + message + "</span>"); } /** Part of the HTML API. Show the account page. */ private void handleHtmlShowAccount(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleViewAccount(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false).setPaneId("account"); pageWrapper.addHeader(); if (isUserALocalAdminOrNotClosed(requestAndResponse)) { try { final String userId = getURIParameterOrUserId(requestAndResponse); final User currentUser = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); final User editedUser = dbLogic.getUserById(userId); if (editedUser == null) { requestAndResponse.print(servletText.errorNoAccountFound()); } else { final boolean currentIsEditedUser = isCurrentUserTheEditedUser( currentUser, editedUser); final boolean isUserAdmin = isUserAnAdmin(requestAndResponse); if (!isUserAdmin && !currentIsEditedUser) { requestAndResponse.print(servletText .errorPageNotAllowed()); } else { final boolean canChangeIsAdmin = isUserAdmin; requestAndResponse.print(servletText .sentenceUsernameIs(currentIsEditedUser, StringEscapeUtils .escapeHtml4(editedUser .getUserName())) + "<br>"); requestAndResponse.print(servletText.sentenceEmailIs( currentIsEditedUser, StringEscapeUtils .escapeHtml4(editedUser .getEmailOrBlank())) + "<br>"); requestAndResponse.print(servletText .sentenceMayBeContacted(currentIsEditedUser, editedUser.getMayContact()) + "<br>"); if (canChangeIsAdmin) { if (editedUser.getIsAccountClosed()) { requestAndResponse .print(servletText .sentenceAccountIsClosed(currentIsEditedUser) + "<br>"); } if (editedUser.getIsAdmin()) { requestAndResponse.print(servletText .sentenceIsAnAdmin(currentIsEditedUser) + "<br>"); } } requestAndResponse .print("<table class=\"accountButtons\"><tr><td>"); requestAndResponse .print("<form action=\"/changeAccount/" + (currentIsEditedUser ? "" : userId) + "\" method=\"GET\">" + "<button onclick=\"replacePaneForForm(event, '" + servletText .buttonChangeAccountDetails() + "'); return false;\" class=\"specialbutton\">" + servletText .buttonChangeAccountDetails() + "</button></form><br>"); requestAndResponse.print("</td><td>"); requestAndResponse .print("<form action=\"/changePassword/" + (currentIsEditedUser ? "" : userId) + "\" method=\"GET\">" + "<button onclick=\"replacePaneForForm(event, '" + servletText.buttonChangePassword() + "'); return false;\" class=\"specialbutton\">" + servletText.buttonChangePassword() + "</button></form><br>"); if (!editedUser.getIsAccountClosed()) { requestAndResponse.print("</td><td>"); requestAndResponse .print("<form action=\"/closeAccount/" + (currentIsEditedUser ? "" : userId) + "\" method=\"GET\">" + "<button onclick=\"replacePaneForForm(event, '" + servletText.buttonCloseAccount() + "'); return false;\" class=\"specialbutton\">" + servletText.buttonCloseAccount() + "</button></form><br>"); } requestAndResponse.print("</td></tr></table>"); if (!currentIsEditedUser) { requestAndResponse.print("<hr class=\"title\"/>" + servletText.sentenceSeeWhatTheUserSees() + "<ul>"); addUserLink(requestAndResponse, servletText.pageTitleNotebooks(), servletText .pageTitleUsersNotebooksTooltip(), "/notebooks", "notebooks", editedUser); addUserLink(requestAndResponse, servletText.pageTitleQuotations(), servletText .pageTitleUsersQuotationsTooltip(), "/quotations", "quotations", editedUser); addUserLink(requestAndResponse, servletText.pageTitleSources(), servletText.pageTitleUsersSourcesTooltip(), "/sources", "sources", editedUser); addUserLink(requestAndResponse, servletText.pageTitleSearch(), servletText.pageTitleUsersSearchTooltip(), "/search", "search", editedUser); requestAndResponse.print("</ul>"); } } } dbLogic.commit(); } catch (final PersistenceException e) { requestAndResponse.print(servletText.errorInternalDatabase()); } } pageWrapper.addFooter(); } /** Returns true if the current user is the edited user. */ private boolean isCurrentUserTheEditedUser(final User currentUser, final User editedUser) { return currentUser != null && editedUser != null && editedUser.getUserName().equals(currentUser.getUserName()); } /** Part of the HTML API. Show the change account form. */ private void handleHtmlChangeAccount(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleChangeAccount(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false).setPaneId("account"); pageWrapper.addHeader(); if (isUserALocalAdminOrNotClosed(requestAndResponse)) { try { final String userId = getURIParameterOrUserId(requestAndResponse); final User currentUser = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); final User editedUser = dbLogic.getUserById(userId); if (editedUser == null) { requestAndResponse.print(servletText.errorNoAccountFound()); } else { final boolean currentIsEditedUser = isCurrentUserTheEditedUser( currentUser, editedUser); final boolean isUserAdmin = isUserAnAdmin(requestAndResponse); if (!isUserAdmin && !currentIsEditedUser) { requestAndResponse.print(servletText .errorPageNotAllowed()); } else { final boolean canChangeIsAdmin = isUserAdmin; final String submitted = requestAndResponse.request .getParameter("save"); boolean needsForm = true; if (submitted != null) { boolean needsChange = false; boolean hasErrors = false; if (isTheCsrftWrong(requestAndResponse, requestAndResponse.request .getParameter("csrft"))) { requestAndResponse.print(servletText .errorRequiresSignIn(false)); needsForm = false; } // Validate the new password. String changedPassword = null; if (doesUserNotHavePasswordAndNeedsIt(editedUser)) { final String newPassword = requestAndResponse.request .getParameter("newpassword"); final String newPassword2 = requestAndResponse.request .getParameter("newpassword2"); hasErrors = validateNewPassword(requestAndResponse, editedUser, currentIsEditedUser, newPassword, newPassword2); if (!hasErrors) { changedPassword = newPassword; needsChange = true; } } // Validate the new username. String changedUserName = null; String newUserName = requestAndResponse.request .getParameter("username"); if (newUserName != null) { newUserName = newUserName.toLowerCase(); } final String oldUserName = editedUser.getUserName(); if (newUserName != null && !newUserName.isEmpty() && !newUserName.equals(oldUserName)) { if (!editedUser.getIsAnon()) { addErrorMessage( requestAndResponse, servletText .errorUsernameMayNotBeChanged()); hasErrors = true; } else if (!AccountAttributeValidator .isUserNameValid(newUserName)) { addErrorMessage(requestAndResponse, servletText .errorUserNameIsNotValid()); hasErrors = true; } else if (dbLogic .getUserByUserName(newUserName) != null) { addErrorMessage( requestAndResponse, servletText .errorUserNameIsAlreadyTaken()); hasErrors = true; } else { changedUserName = newUserName; needsChange = true; } } // Validate email. String changedEmail = null; String email = requestAndResponse.request .getParameter("email"); if (email != null && email.isEmpty()) { email = null; } boolean emailIsChanged = false; if (email == null && editedUser.getEmail() != null) { changedEmail = email; needsChange = true; emailIsChanged = true; } else if (email != null && !AccountAttributeValidator .isEmailValid(email)) { addErrorMessage(requestAndResponse, servletText.errorEmailIsNotValid()); hasErrors = true; } else if (email != null) { changedEmail = email; needsChange = true; emailIsChanged = true; } // Validate mayContact. final boolean mayContact = getCheckBoxValue(requestAndResponse, "mayContact"); if (mayContact != editedUser.getMayContact()) { needsChange = true; } // Validate isAccountClosed. final boolean isAccountClosed = getCheckBoxValue(requestAndResponse, "isAccountClosed"); if (isAccountClosed != editedUser .getIsAccountClosed()) { needsChange = true; } // Validate isAdmin. final boolean isAdmin = getCheckBoxValue(requestAndResponse, "isAdmin"); if (isAdmin != editedUser.getIsAdmin()) { if (!isAdmin && editedUser.getIsSingleUser()) { hasErrors = true; addErrorMessage( requestAndResponse, servletText .errorSingleUserMustStayAnAdmin()); } if (!canChangeIsAdmin) { hasErrors = true; addErrorMessage( requestAndResponse, servletText .errorOnlyAnAdminCanChangeIsAdmin()); } needsChange = true; } // Make the changes. if (needsChange && !hasErrors) { final Long time = new Long( System.currentTimeMillis()); editedUser.setModTime(time); if (changedPassword != null) { editedUser.setPassword(DigestUtils .sha1Hex(changedPassword)); } if (changedUserName != null) { editedUser.setUserName(changedUserName); editedUser.setIsAnon(false); } if (emailIsChanged) { editedUser.setEmail(changedEmail); } editedUser.setMayContact(mayContact); if (canChangeIsAdmin) { editedUser.setIsAdmin(isAdmin); editedUser .setIsAccountClosed(isAccountClosed); } addSuccessMessage(requestAndResponse, servletText.sentenceChangesWereSaved()); needsForm = false; } else if (hasErrors) { addErrorMessage(requestAndResponse, servletText.errorChangesWereNotSaved()); } else { addErrorMessage(requestAndResponse, servletText.errorNoChangesToSave()); } } if (needsForm) { requestAndResponse .print("<div class=\"infoheader\">" + servletText .sentenceEnterNewAccountDetailsHere( currentIsEditedUser, editedUser .getUserName()) + "</div>"); requestAndResponse .print("<form action=\"/changeAccount/" + (currentIsEditedUser ? "" : userId) + "\" method=\"POST\"><div class=\"account\">" + "<input type=\"hidden\" name=\"csrft\" value=\"" + getCsrft(requestAndResponse) + "\">"); if (editedUser.getIsAnon()) { requestAndResponse .print("<div class=\"infoheader\">" + servletText .sentencePleaseChangeNameFromGenerated( currentIsEditedUser, editedUser .getUserName()) + "</div>"); requestAndResponse .print("<input autocorrect=\"off\" type=\"text\" id=\"username\" name=\"username\" placeholder=\"" + servletText .sentenceChooseAUserName() + "\" maxlength=\"20\"><br>"); } // Validate new passwords. if (doesUserNotHavePasswordAndNeedsIt(editedUser)) { addNewPasswordFormFields(requestAndResponse, editedUser, currentIsEditedUser); } requestAndResponse .print("<input type=\"email\" id=\"email\" name=\"email\" placeholder=\"" + servletText .sentenceEmailOptional() + "\" maxlength=\"100\" value=\"" + StringEscapeUtils .escapeHtml4(editedUser .getEmailOrBlank()) + "\"><br>"); requestAndResponse .print("<input type=\"checkbox\" name=\"mayContact\" id=\"mayContact\"" + (editedUser.getMayContact() ? " checked" : "") + "><label for=\"mayContact\">" + (currentIsEditedUser ? servletText .sentenceIMayBeContacted() : servletText .sentenceUserMayBeContacted()) + "</label><br>"); if (canChangeIsAdmin) { requestAndResponse .print("<input type=\"checkbox\" name=\"isAccountClosed\" id=\"isAccountClosed\"" + (editedUser .getIsAccountClosed() ? " checked" : "") + "><label for=\"isAccountClosed\">" + servletText .sentenceIsAccountClosed() + "</label><br>"); requestAndResponse .print("<input type=\"checkbox\" name=\"isAdmin\" id=\"isAdmin\"" + (editedUser.getIsAdmin() ? " checked" : "") + "><label for=\"isAdmin\">" + servletText .sentenceUserIsAnAdmin() + "</label><br>"); } requestAndResponse .print("<table class=\"responseAndSave\"><tr>" + "<td><div id=\"response\"></div></td>" + "<td><button onclick=\"replacePaneForForm(event, '" + servletText .buttonChangeAccountDetails() + "'); return false;\" id=\"save\" name=\"save\" class=\"specialbutton\" style=\"float:right; margin-top:10px;\">" + servletText .buttonChangeAccountDetails() + "</button></td>" + "</tr></table></div>" + "</form>"); } } } dbLogic.commit(); } catch (final PersistenceException e) { requestAndResponse.print(servletText.errorInternalDatabase()); } } pageWrapper.addFooter(); } /** * Returns true if the user is either local admin or a signed in user whose * account is not closed. */ boolean isUserALocalAdminOrNotClosed(RequestAndResponse requestAndResponse) throws IOException { if (isUserALocalAdmin(requestAndResponse)) { return true; } if (!isUserSignedIn(requestAndResponse)) { requestAndResponse.print(servletText.errorRequiresSignIn(false)); return false; } else if (isUsersAccountClosed(requestAndResponse)) { requestAndResponse.print(servletText.errorAccountIsClosed()); return false; } return true; } /** Part of the HTML API. Show the close account form. */ private void handleHtmlCloseAccount(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleCloseAccount(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false).setPaneId("account"); pageWrapper.addHeader(); if (isUserALocalAdminOrNotClosed(requestAndResponse)) { try { final String userId = getURIParameterOrUserId(requestAndResponse); final User currentUser = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); final User editedUser = dbLogic.getUserById(userId); if (editedUser == null) { requestAndResponse.print(servletText.errorNoAccountFound()); } else { final boolean currentIsEditedUser = isCurrentUserTheEditedUser( currentUser, editedUser); final boolean isUserAdmin = isUserAnAdmin(requestAndResponse); if (!isUserAdmin && !currentIsEditedUser) { requestAndResponse.print(servletText .errorPageNotAllowed()); } else { boolean needsForm = true; boolean needsCurrentPassword = isCurrentPasswordNeeded( editedUser, currentIsEditedUser, isUserAdmin); final String submitted = requestAndResponse.request .getParameter("save"); if (submitted != null) { boolean needsChange = false; boolean hasErrors = false; if (isTheCsrftWrong(requestAndResponse, requestAndResponse.request .getParameter("csrft"))) { requestAndResponse.print(servletText .errorRequiresSignIn(false)); needsForm = false; } else { // Validate old password. if (needsCurrentPassword) { final String realPassword = editedUser .getPassword(); final String currentPassword = requestAndResponse.request .getParameter("currentpassword"); if (currentPassword == null || currentPassword.isEmpty()) { addErrorMessage( requestAndResponse, servletText .errorPasswordMustNotBeBlank()); hasErrors = true; } else if (!AccountAttributeValidator .isPasswordValid(currentPassword)) { addErrorMessage( requestAndResponse, servletText .errorCurrentPasswordIsIncorrect()); hasErrors = true; } else if (realPassword == null || !realPassword.equals(DigestUtils .sha1Hex(currentPassword))) { addErrorMessage( requestAndResponse, servletText .errorCurrentPasswordIsIncorrect()); hasErrors = true; } } needsChange = !editedUser.getIsAccountClosed(); // Make the changes. if (needsChange && !hasErrors) { final Long time = new Long( System.currentTimeMillis()); editedUser.setModTime(time); editedUser.setIsAccountClosed(true); addSuccessMessage(requestAndResponse, servletText .sentenceChangesWereSaved()); needsForm = false; } else if (hasErrors) { addErrorMessage(requestAndResponse, servletText .errorChangesWereNotSaved()); } else { addErrorMessage(requestAndResponse, servletText.errorNoChangesToSave()); needsForm = false; } } } if (needsForm) { // Recompute this in case the values have changed. needsCurrentPassword = isCurrentPasswordNeeded( editedUser, currentIsEditedUser, isUserAdmin); requestAndResponse .print("<form action=\"/closeAccount/" + (currentIsEditedUser ? "" : userId) + "\" method=\"POST\"><div class=\"account\">" + "<input type=\"hidden\" name=\"csrft\" value=\"" + getCsrft(requestAndResponse) + "\">" + "<div class=\"infoheader\">" + servletText .sentenceSureYouWantToCloseAccount( currentIsEditedUser, StringEscapeUtils .escapeHtml4(editedUser .getUserName())) + "</div>"); if (needsCurrentPassword) { requestAndResponse .print("<input type=\"password\" id=\"currentpassword\" name=\"currentpassword\" placeholder=\"" + servletText .sentenceCurrentPassword(currentIsEditedUser) + "\" maxlength=\"20\"><br>"); } requestAndResponse .print("<table class=\"responseAndSave\"><tr>" + "<td><div id=\"response\"></div></td>" + "<td><button onclick=\"replacePaneForForm(event, '" + servletText.buttonCloseAccount() + "'); return false;\" id=\"save\" name=\"save\" class=\"specialbutton\" style=\"float:right; margin-top:10px;\">" + servletText.buttonCloseAccount() + "</button></td>" + "</tr></table></div>" + "</form>"); } } } dbLogic.commit(); } catch (final PersistenceException e) { requestAndResponse.print(servletText.errorInternalDatabase()); } } pageWrapper.addFooter(); } /** Part of the HTML API. Change the password. */ private void handleHtmlChangePassword(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleChangePassword(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false).setPaneId("account"); pageWrapper.addHeader(); if (isUserALocalAdminOrNotClosed(requestAndResponse)) { try { final String userId = getURIParameterOrUserId(requestAndResponse); final User currentUser = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); final User editedUser = dbLogic.getUserById(userId); if (editedUser == null) { requestAndResponse.print(servletText.errorNoAccountFound()); } else { final boolean currentIsEditedUser = isCurrentUserTheEditedUser( currentUser, editedUser); final boolean isUserAdmin = isUserAnAdmin(requestAndResponse); if (!isUserAdmin && !currentIsEditedUser) { requestAndResponse.print(servletText .errorPageNotAllowed()); } else { boolean needsCurrentPassword = isCurrentPasswordNeeded( editedUser, currentIsEditedUser, isUserAdmin); boolean showForm = true; final String submitted = requestAndResponse.request .getParameter("save"); if (submitted != null) { boolean needsChange = false; if (isTheCsrftWrong(requestAndResponse, requestAndResponse.request .getParameter("csrft"))) { requestAndResponse.print(servletText .errorRequiresSignIn(false)); showForm = false; } // Validate new passwords. final String newPassword = requestAndResponse.request .getParameter("newpassword"); final String newPassword2 = requestAndResponse.request .getParameter("newpassword2"); boolean hasErrors = validateNewPassword(requestAndResponse, editedUser, currentIsEditedUser, newPassword, newPassword2); if (!hasErrors && editedUser.getPasswordOrBlank().equals( DigestUtils.sha1Hex(newPassword))) { addErrorMessage( requestAndResponse, servletText .errorNewPasswordIsTheSameAsTheCurrent()); hasErrors = true; } String changedPassword = null; if (!hasErrors) { changedPassword = newPassword; needsChange = true; } // Validate old password. if (needsCurrentPassword) { final String realPassword = editedUser .getPassword(); final String currentPassword = requestAndResponse.request .getParameter("currentpassword"); if (!AccountAttributeValidator .isPasswordValid(currentPassword)) { addErrorMessage( requestAndResponse, servletText .errorCurrentPasswordIsNotValid()); hasErrors = true; } else if (realPassword == null || !realPassword.equals(DigestUtils .sha1Hex(currentPassword))) { addErrorMessage( requestAndResponse, servletText .errorCurrentPasswordIsIncorrect()); hasErrors = true; } } // Make the changes. if (needsChange && !hasErrors) { final Long time = new Long( System.currentTimeMillis()); editedUser.setModTime(time); if (changedPassword != null) { editedUser.setPassword(DigestUtils .sha1Hex(changedPassword)); } addSuccessMessage(requestAndResponse, servletText.sentenceChangesWereSaved()); showForm = false; } else if (hasErrors) { addErrorMessage(requestAndResponse, servletText.errorChangesWereNotSaved()); } else { addErrorMessage(requestAndResponse, servletText.errorNoChangesToSave()); showForm = false; } } if (showForm) { // Recompute this in case the values have changed. needsCurrentPassword = isCurrentPasswordNeeded( editedUser, currentIsEditedUser, isUserAdmin); requestAndResponse .print("<form action=\"/changePassword/" + (currentIsEditedUser ? "" : userId) + "\" method=\"POST\"><div class=\"account\">" + "<input type=\"hidden\" name=\"csrft\" value=\"" + getCsrft(requestAndResponse) + "\">"); if (needsCurrentPassword) { requestAndResponse .print("<div class=\"infoheader\">" + servletText .sentenceEnterYourCurrentPasswordHere() + "</div>"); requestAndResponse .print("<input type=\"password\" id=\"currentpassword\" name=\"currentpassword\" placeholder=\"" + servletText .sentenceCurrentPassword(currentIsEditedUser) + "\" maxlength=\"20\"><br>"); } addNewPasswordFormFields(requestAndResponse, editedUser, currentIsEditedUser); requestAndResponse .print("<table class=\"responseAndSave\"><tr>" + "<td><div id=\"response\"></div></td>" + "<td><button onclick=\"replacePaneForForm(event, '" + servletText .buttonChangePassword() + "'); return false;\" id=\"save\" name=\"save\" class=\"specialbutton\" style=\"float:right; margin-top:10px;\">" + servletText .buttonChangePassword() + "</button></td>" + "</tr></table></div>" + "</form>"); } } } dbLogic.commit(); } catch (final PersistenceException e) { requestAndResponse.print(servletText.errorInternalDatabase()); } } pageWrapper.addFooter(); } /*** Validates the new password fields. */ private boolean validateNewPassword(RequestAndResponse requestAndResponse, final User editedUser, final boolean currentIsEditedUser, final String newPassword, final String newPassword2) throws IOException { boolean hasErrors = false; if (newPassword == null || newPassword.isEmpty()) { addErrorMessage(requestAndResponse, servletText .errorFirstPasswordMustBeSet( currentIsEditedUser, editedUser .getUserName())); hasErrors = true; } if (newPassword2 == null || newPassword2.isEmpty()) { addErrorMessage(requestAndResponse, servletText .errorSecondPasswordMustBeSet( currentIsEditedUser, editedUser .getUserName())); hasErrors = true; } if (!hasErrors && newPassword != null && newPassword2 != null && !newPassword2.equals(newPassword)) { addErrorMessage(requestAndResponse, servletText.errorPasswordsMustMatch()); hasErrors = true; } if (!hasErrors && !AccountAttributeValidator .isPasswordValid(newPassword)) { addErrorMessage(requestAndResponse, servletText.errorPasswordIsNotValid()); hasErrors = true; } return hasErrors; } /** Adds the new password and verify password form fields. */ private void addNewPasswordFormFields( RequestAndResponse requestAndResponse, final User editedUser, final boolean currentIsEditedUser) throws IOException { requestAndResponse .print("<div class=\"infoheader\">" + servletText .sentenceEnterNewPasswordHereTwice( currentIsEditedUser, editedUser .getUserName()) + "</div>"); requestAndResponse .print("<input type=\"password\" id=\"newpassword\" name=\"newpassword\" placeholder=\"" + servletText.sentenceNewPassword() + "\" maxlength=\"20\"><br>" + "<input type=\"password\" id=\"newpassword2\" name=\"newpassword2\" placeholder=\"" + servletText .sentenceVerifyNewPassword() + "\" maxlength=\"20\"><br>"); } /** * Return the parameter from the URL or if there is none then the ID of the * current user. */ private String getURIParameterOrUserId(RequestAndResponse requestAndResponse) { final String userId = requestAndResponse.getURIParameter(); if (userId != null && !userId.isEmpty()) { return userId; } return getEffectiveUserId(requestAndResponse); } /** * Adds the HTML for a link with the userid appended. * * @throws IOException */ private void addUserLink(RequestAndResponse requestAndResponse, String title, String tooltip, String url, String paneId, User user) throws IOException { requestAndResponse.println("<li><a onclick=\"newPaneForLink(event, '" + title + "', '" + paneId + "'); return false;\" title=\"" + tooltip + "\" href=\"" + url + "/" + user.getId() + "\">" + title + "</a></li>"); } /** * Returns true if the old password is needed to authenticate the account * changes. */ private boolean isCurrentPasswordNeeded(final User editedUser, boolean currentIsEditedUser, boolean isUserAdmin) { return (!isUserAdmin || currentIsEditedUser) && !editedUser.getIsSingleUser() && editedUser.getPassword() != null; } /** Returns true if the user does not have a password and needs it. */ private boolean doesUserNotHavePasswordAndNeedsIt(final User editedUser) { return !editedUser.getIsSingleUser() && editedUser.getPassword() == null; } /** Part of the HTML API. Handle a restore. */ private void handleHtmlDoUserRestore(RequestAndResponse requestAndResponse) throws IOException, ServletException { final Errors errors = new Errors(); final Part part = requestAndResponse.request.getPart("file"); final boolean reuseIds = getCheckBoxValue(requestAndResponse, "reuseIds"); final boolean msWordListFormat = getCheckBoxValue(requestAndResponse, "msWordListFormat"); final String csrft = requestAndResponse.getParameter("csrft"); addIFrameHeader(requestAndResponse); if (isTheCsrftWrong(requestAndResponse, csrft)) { requestAndResponse.print(servletText.errorRequiresSignIn(false)); } else if (!isUserSignedIn(requestAndResponse)) { requestAndResponse.print(servletText.errorRequiresSignIn(false)); } else if (isUsersAccountClosed(requestAndResponse)) { requestAndResponse.print(servletText.errorAccountIsClosed()); } else if (part == null) { requestAndResponse.print(servletText.errorNoFileUploaded()); } else { final InputStream stream = part.getInputStream(); final InputStreamReader streamReader = new InputStreamReader( stream, Charset.forName("UTF-8")); boolean result = false; if (msWordListFormat) { result = dbLogic.restoreMsWordListFormatForUser( getEffectiveUserId(requestAndResponse), streamReader, isUserAnAdmin(requestAndResponse), errors); } else { result = dbLogic.restoreJsonForUser( getEffectiveUserId(requestAndResponse), streamReader, reuseIds, isUserAnAdmin(requestAndResponse), errors); } if (!result) { requestAndResponse.print(servletText.errorRestoreFailed() + "<br>"); for (final String text : errors.getTexts()) { requestAndResponse.print(text); requestAndResponse.print("<br>"); } } else { requestAndResponse.print(servletText.sentenceRestored()); } // This is so that if this gets reloaded a page can actually be // loaded. requestAndResponse.print("<script type=\"text/javascript\">\n" + "history.replaceState(null, null, '/restoreFrame/');\n" + "</script>"); } addIFrameFooter(requestAndResponse); } /** Returns the boolean value of a checkbox input field. */ private boolean getCheckBoxValue(RequestAndResponse requestAndResponse, String fieldName) { final String valueString = requestAndResponse.request .getParameter(fieldName); return valueString != null && valueString.equals("on"); } /* Prints an HTML header for an iframe page. */ private void addIFrameHeader(RequestAndResponse requestAndResponse) throws IOException { requestAndResponse.print("<!doctype html>" + "<html>" + "<head>" + standardCss + "</head>\n" + "<style type=\"text/css\">" + "html, body { background:none transparent }" + "</style>" + "<body>"); } /* Prints an HTML footer for an iframe page. */ private void addIFrameFooter(RequestAndResponse requestAndResponse) throws IOException { requestAndResponse.print("</body><html>"); } /** Part of the HTML API. Handle a user backup. */ private void handleHtmlDoUserBackup(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String pageTitle = servletText.pageTitleUserBackup(); final String csrft = requestAndResponse.getParameter("csrft"); final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, pageTitle, false).setPaneId("backup"); if (isTheCsrftWrong(requestAndResponse, csrft)) { pageWrapper.addHeader(); requestAndResponse.print(servletText.errorRequiresSignIn(false)); pageWrapper.addFooter(); } else if (!isUserSignedIn(requestAndResponse)) { pageWrapper.addHeader(); requestAndResponse.print(servletText .errorRequiresSignIn(allowSaveIfNotSignedIn)); pageWrapper.addFooter(); } else if (isUsersAccountClosed(requestAndResponse)) { pageWrapper.addHeader(); requestAndResponse.print(servletText.errorAccountIsClosed()); pageWrapper.addFooter(); } else { requestAndResponse.setResponseContentTypeJson(); final StringBuilder result = new StringBuilder(); try { final String userId = getEffectiveUserId(requestAndResponse); final User user = dbLogic.getUserById(userId); if (user != null) { requestAndResponse.response.setHeader( "Content-Disposition", "attachment; filename=crushpaper-backup-" + user.getUserName() + "-" + formatDateTimeForFileName(System .currentTimeMillis()) + ".json"); dbLogic.backupJsonForUser(user, result); } dbLogic.commit(); } catch (final PersistenceException e) { } requestAndResponse.print(result.toString()); } } /** Part of the HTML API. Show the user backup form. */ private void handleHtmlUserBackupForm(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleUserBackup(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false).setPaneId("backup"); pageWrapper.addHeader(); if (!isUserSignedIn(requestAndResponse)) { requestAndResponse.print(servletText .errorRequiresSignIn(allowSaveIfNotSignedIn)); } else if (isUsersAccountClosed(requestAndResponse)) { requestAndResponse.print(servletText.errorAccountIsClosed()); } else { requestAndResponse.print("<table class=\"nopadding\"><tr><td>"); requestAndResponse.print(servletText.userBackupAreYouSure()); requestAndResponse.print("</td></tr><tr><td>"); requestAndResponse.print("<form action=\"/doBackup/" + "\" method=\"POST\">" + "<input type=\"hidden\" name=\"csrft\" value=\"" + getCsrft(requestAndResponse) + "\">" + "<button class=\"specialbutton withTopMargin\">" + servletText.pageTitleUserBackup() + "</button></form>"); requestAndResponse.print("</td></tr></table>"); } pageWrapper.addFooter(); } /** Helper method. Handle searching sources. */ private void handleHtmlSearchSources(PageWrapper pageWrapper, RequestAndResponse requestAndResponse, String query, String paneId) throws IOException, ServletException { pageWrapper.addPageIntroText( servletText.introTextSearchSources(false), servletText.introTextSearchSources(true)); try { final StringBuilder result = new StringBuilder(); User queryUser = null; if (null != (queryUser = canUserSeeUsersData(requestAndResponse, true))) { final ArrayList<EntryInfo> entryInfoList = new ArrayList<EntryInfo>(); if (query.startsWith("http://") || query.startsWith("https://")) { final Entry entry = dbLogic.getEntryByUserIdAndUrl( queryUser.getId(), query); if (entry == null) { servletText.sentenceThereWereNoMatches(); } else { startItemList(result, paneId); addSourceHtml(entry, result, SourceEmbedContext.InSources, null, 1, paneId); addEntryToInfoList(entry, entryInfoList); finishItemList(result); } } else { final ResultsPaginator paginator = new ResultsPaginator( requestAndResponse, servletText.sentenceThereWereNoMatches(), result, servletText); try { final List<?> results = dbLogic .searchEntriesForUserBySourceTitle( queryUser.getId(), query, paginator.getStartPosition(), paginator.getMaxResults()); startItemList(result, paneId); for (final Object entryUncasted : results) { final Entry entry = (Entry) entryUncasted; final int resultNumber = paginator.next(); if (resultNumber == -1) { continue; } else if (resultNumber == 0) { break; } addSourceHtml(entry, result, SourceEmbedContext.InSources, null, resultNumber, paneId); addEntryToInfoList(entry, entryInfoList); } finishItemList(result); paginator.done(); } catch (EmptyQueryException e) { requestAndResponse.print(servletText.errorNeedLongerQuery()); } } result.append("\n<script type=\"application/json\" class=\"entryInfoDictJson\">\n"); addJsonForEntryInfos(result, entryInfoList, paneId); result.append("\n</script>\n"); } dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { requestAndResponse.print(servletText.errorInternalDatabase()); } } /** Part of the HTML API. Shows search results within users. */ private void handleHtmlSearchAccounts(PageWrapper pageWrapper, RequestAndResponse requestAndResponse, String query, String paneId) throws IOException, ServletException { pageWrapper.addPageIntroText(servletText.introTextSearchUsers(), null); if (!isUserAnAdmin(requestAndResponse)) { requestAndResponse.print(servletText.errorPageNotAllowed()); } else { try { final StringBuilder result = new StringBuilder(); final User user = dbLogic .getUserByUserName(query.toLowerCase()); if (user == null) { result.append(servletText.sentenceThereWereNoMatches()); } else { startItemList(result, paneId); addUserHtml(user, result, 1, paneId); finishItemList(result); } dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { requestAndResponse.print(servletText.errorInternalDatabase()); } } } /** Part of the HTML API. Handle showing quotations. */ private void handleHtmlShowQuotations(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleQuotations(); if (addTitle(requestAndResponse, title)) { return; } final String paneId = "quotations"; final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false).setPaneId(paneId); pageWrapper.addHeader(); pageWrapper.addMetaData(new KeyAndValue("paneType", paneId)); pageWrapper.addPageIntroText( servletText.introTextShowQuotations(false), servletText.introTextShowQuotations(true)); try { final StringBuilder result = new StringBuilder(); User queryUser = null; if (null != (queryUser = canUserSeeUsersData(requestAndResponse, true))) { final ResultsPaginator paginator = new ResultsPaginator( requestAndResponse, servletText.sentenceNoQuotationsExist(), result, servletText); final List<?> results = dbLogic .getEntriesByUserIdAndType(queryUser.getId(), DbLogic.Constants.quotation, paginator.getStartPosition(), paginator.getMaxResults()); entryListToHtmlAndJson(paneId, result, paginator, results); } dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { requestAndResponse.print(servletText.errorInternalDatabase()); } pageWrapper.addFooter(); } /** Part of the HTML API. Handle showing users. */ private void handleHtmlShowAccounts(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleAccounts(); if (addTitle(requestAndResponse, title)) { return; } final String paneId = "accounts"; final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, true).setPaneId(paneId); pageWrapper.addHeader(); pageWrapper.addMetaData(new KeyAndValue("notEditable", true)); pageWrapper.addMetaData(new KeyAndValue("paneType", "accounts")); if (!isUserAnAdmin(requestAndResponse)) { requestAndResponse.print(servletText.errorPageNotAllowed()); } else { pageWrapper.addPageIntroText( servletText.introTextShowAccounts(false), servletText.introTextShowAccounts(true)); try { final StringBuilder result = new StringBuilder(); final ResultsPaginator paginator = new ResultsPaginator( requestAndResponse, servletText.sentenceNoAccountsExist(), result, servletText); startItemList(result, paneId); final List<?> users = dbLogic .getAllUsers(paginator.getStartPosition(), paginator.getMaxResults()); for (final Object userUncasted : users) { final User user = (User) userUncasted; final int resultNumber = paginator.next(); if (resultNumber == -1) { continue; } else if (resultNumber == 0) { break; } addUserHtml(user, result, resultNumber, paneId); } finishItemList(result); paginator.done(); dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { requestAndResponse.print(servletText.errorInternalDatabase()); } } pageWrapper.addFooter(); } /** Part of the HTML API. Show a source. */ private void handleHtmlShowSource(RequestAndResponse requestAndResponse) throws IOException, ServletException { String title = servletText.pageTitleSource(); final String paneId = "source"; final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false).setPaneId(paneId); final String id = requestAndResponse.getURIParameter(); boolean headerAdded = false; // Do not check if the session is signed in or the account is closed in // case the page is public. try { final StringBuilder result = new StringBuilder(); final Entry source = dbLogic.getEntryById(id); final User user = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); if (source != null) { pageWrapper.setPaneId(source.getId()); } if (source == null) { if (addTitle(requestAndResponse, title)) { dbLogic.commit(); return; } if (!requestAndResponse.moreThanOneUri) { requestAndResponse.response .setStatus(HttpServletResponse.SC_NOT_FOUND); } pageWrapper.addHeader(); headerAdded = true; result.append(servletText.errorNoSourceFound()); } else if (!dbLogic.canUserSeeEntry(user, source, isUserAnAdmin(requestAndResponse))) { if (addTitle(requestAndResponse, title)) { dbLogic.commit(); return; } pageWrapper.addHeader(); headerAdded = true; if (user == null) { result.append(servletText.errorRequiresSignIn(false)); } else { result.append(servletText.errorMayNotSeeSource()); } } else { title = source.getSourceTitle(); if (addTitle(requestAndResponse, title)) { dbLogic.commit(); return; } pageWrapper.setIncludeEdit(); pageWrapper.setIncludeDelete(); pageWrapper.setTitle(title); pageWrapper.addMetaData(new KeyAndValue("paneType", "source")); pageWrapper.addHeader(); headerAdded = true; pageWrapper.addPageIntroText( servletText.introTextShowSource(false), servletText.introTextShowSource(true)); addSourceHtml(source, result, SourceEmbedContext.InSource, null, -1, paneId); final ResultsPaginator paginator = new ResultsPaginator( requestAndResponse, servletText.sentenceNoQuotationsForThisSourceExist(), result, servletText); final List<?> results = dbLogic.getEntriesBySourceId( source.getId(), paginator.getStartPosition(), paginator.getMaxResults()); entryListToHtmlAndJson(paneId, result, paginator, results, SourceEmbedContext.InSourceQuotations); } dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { if (!headerAdded) { pageWrapper.addHeader(); } requestAndResponse.print(servletText.errorInternalDatabase()); } pageWrapper.addFooter(); } /** Part of the HTML API. Show that the session has been signed out. */ private void handleHtmlShowSignedOut(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String title = servletText.pageTitleSignedOut(); if (addTitle(requestAndResponse, title)) { return; } final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, title, false).setPaneId("welcome"); pageWrapper.addHeader(); if (!isUserSignedIn(requestAndResponse)) { requestAndResponse .print(servletText.sentenceYouHaveBeenSignedOut()); } else { requestAndResponse.print(servletText .sentenceYouHaveNotBeenSignedOut()); } pageWrapper.addFooter(); } /** Formats a timestamp into a datetime for file names. */ String formatDateTimeForFileName(long unixTime) { final Date date = new Date(unixTime); final SimpleDateFormat format = filenameDateAndTimeFormat.get(); return format.format(date); } /** Formats a timestamp into a date and time of day with the default format. */ String formatDateAndTime(Long unixTime) { final Date date = new Date(unixTime); final SimpleDateFormat format = defaultDateAndTimeFormat.get(); return format.format(date); } private static final ThreadLocal<SimpleDateFormat> filenameDateAndTimeFormat = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { final SimpleDateFormat dayFormat = new SimpleDateFormat( "yyyy-MM-dd-HH-mm-ss"); return dayFormat; } }; private static final ThreadLocal<SimpleDateFormat> defaultDateAndTimeFormat = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { final SimpleDateFormat dayFormat = new SimpleDateFormat( "E, MMM d, yyyy @ h:mm a"); return dayFormat; } }; /** Called to start an item list. */ private void startItemList(StringBuilder result, String rootId) { result.append("<div class=\"container\"" + "><div class=\"alone fakealone\" id=\"alone_ef_" + rootId + "\"></div><div class=\"justchildren fakejustchildren\">"); } /** Called to start adding an item to an item list. */ private void startItemListItem(StringBuilder result, String rootId, String itemId) { result.append("<div class=\"subtree\">"); result.append("<div class=\"alone " + itemId + "\" id=\"alone_" + rootId + ":" + itemId + "\">"); } /** Called to finish adding an item to an item list. */ private void finishItemListItem(StringBuilder result) { result.append("</div><div class=\"justchildren\"></div></div>"); } /** Called to finish an item list. */ private void finishItemList(StringBuilder result) { result.append("</div></div>"); } /** Helper method. Adds the HTML for an entry to a list. */ private void addEntryHtmlToList(Entry entry, StringBuilder result, int resultNumber, String rootId, SourceEmbedContext embedContext) throws IOException { startItemListItem(result, rootId, entry.getId()); result.append("<table class=\"magic nopadding\"><tr><td class=\"resultNumber\">"); result.append(getItemMetaDataJsonHtml(entry.getType(), entry.getId())) .toString(); result.append(resultNumber + ".</td>"); result.append("<td><input type=\"checkbox\" class=\"justDrag aloneCheckbox mousetrap\" onclick=\"checkboxOnClick(event); return true;\"></td>"); result.append("<td class=\"listItem\">"); if (entry.hasQuotation()) { result.append("<div class=\"quotation\" title=\"" + servletText.quotationInListTooltip() + "\">"); result.append(getQuotationHtml(entry, true)); result.append("</div><br>"); } String noteHtml = getNoteHtml(entry, true, entry.hasQuotation(), true); if (!noteHtml.isEmpty()) { result.append("<div class=\"note mousetrap\" title=\"" + servletText.noteInListTooltip(entry.getType()) + "\">"); result.append(noteHtml); result.append("</div>"); } final StringBuilder atString = new StringBuilder(); atString.append("<div class=\"listModTime\" title=\"" + servletText.modTimeInListTooltip(entry.getType()) + "\">" + servletText.fragmentLastModified() + " <span>"); atString.append(formatDateAndTime(entry.getModTime()) + "<span class=\"rawDateTime\">" + entry.getModTime() + "</span></span></div>"); boolean sourceIncluded = false; if (embedContext != SourceEmbedContext.InSourceQuotations) { final Entry source = dbLogic.getEntryById(entry.getSourceId()); if (source != null) { addSourceHtml(source, result, embedContext, atString.toString(), -1, null); sourceIncluded = true; } } if (!sourceIncluded) { result.append("<div class=\"listItemFooter\">" + atString.toString() + "</div>"); } result.append("</td></tr></table>"); finishItemListItem(result); } /** Helper method. Adds the HTML for a user to a list. */ private void addUserHtml(User user, StringBuilder result, int resultNumber, String rootId) throws IOException { if (resultNumber != -1) { startItemListItem(result, rootId, user.getId()); result.append("<table class=\"magic nopadding\"><tr><td class=\"resultNumber\">"); result.append(getItemMetaDataJsonHtml("user", user.getId())) .toString(); result.append(resultNumber + ".</td><td class=\"listItem\">"); } result.append("Username: " + user.getUserName()); if (user.getEmail() != null) { result.append(", email: " + user.getEmail()); } if (user.getIsAdmin()) { result.append(", is an admin"); } if (user.getMayContact()) { result.append(", may be contacted"); } result.append("<br>"); if (resultNumber != -1) { result.append("<div class=\"listItemFooter\">"); result.append("<div title=\"" + servletText.modTimeInListTooltip("account") + "\">" + servletText.fragmentLastModified() + " <span>"); result.append(formatDateAndTime(user.getModTime()) + "<span class=\"rawDateTime\">" + user.getModTime() + "</span></span>"); result.append("</div></div>"); result.append("</td></tr></table>"); finishItemListItem(result); } else { result.append(servletText.fragmentLastModified() + " <span>"); result.append(formatDateAndTime(user.getModTime()) + "<span class=\"rawDateTime\">" + user.getModTime() + "</span></span>"); result.append(". " + servletText.fragmentCreated() + " <span>"); result.append(formatDateAndTime(user.getCreateTime()) + "<span class=\"rawDateTime\">" + user.getModTime() + "</span></span>"); } } /** * A simple class that contains the straight text for an entry to make it * editable rather than just displayable as html. */ class EntryInfo { public EntryInfo(String id, String note, String quotation, boolean isPublic, boolean hasChildren, boolean hasParent, String type) { this.id = id; this.note = note; this.quotation = quotation; this.isPublic = isPublic; this.hasChildren = hasChildren; this.hasParent = hasParent; this.type = type; } String id; String note; String quotation; boolean isPublic; boolean hasChildren; boolean hasParent; String type; } /** * Helper method. A wrapper function for addEntryHtmlToTree that defaults * onlyChildren to false and idOfEntryToSkip to null. */ private void addEntryHtmlToTreeSimple(Entry entry, StringBuilder result, List<EntryInfo> entryInfoList, int levelsOfChildrenToInclude, boolean showCheckboxes) throws IOException { addEntryHtmlToTree(entry, result, entryInfoList, levelsOfChildrenToInclude, false, null, true, showCheckboxes); } /** * Helper method. Adds the HTML for an entry to a tree. */ private int addEntryHtmlToTree(Entry entry, StringBuilder result, List<EntryInfo> entryInfoList, int levelsOfChildrenToInclude, boolean onlyChildren, String idOfEntryToSkip, boolean includeRootInEntryInfoList, boolean showCheckboxes) throws IOException { if (!onlyChildren) { result.append("<div class=\"subtree\">"); result.append("<div class=\"alone " + entry.getId() + "\" id=\"alone_" + entry.getId() + "\" ondragover=\"onDragOverAloneEl(event)\" ondrop=\"onDropAloneEl(event)\">"); result.append("<table class=\"nopadding alonetd\"><tr><td onmousedown=\"triangleOnMouseDown(event); return false;\" class=\"triTd justDrag\">" + "<div></div></td><td>" + "<table class=\"nopadding\"><tr><td class=\"nowords\"><img onmouseover=\"plusOnMouseOver(event);\" onmouseout=\"plusOnMouseOut(event);\" alt=\"plus\" title=\"" + servletText.plusTooltip() + "\" class=\"justDrag plusOrMinus\" onmousedown=\"plusOnMouseDown(event); return false;\" src=\"/images/plus.png\"></td></tr>" + "<tr><td class=\"nowords\"><img onmouseover=\"minusOnMouseOver(event);\" onmouseout=\"minusOnMouseOut(event);\" alt=\"minus\" title=\"" + servletText.minusTooltip() + "\" class=\"justDrag plusOrMinus\" onmousedown=\"minusOnMouseDown(event); return false;\" src=\"/images/minus.png\"></td></tr></table>" + "</td>"); if (showCheckboxes) { result.append("<td><input type=\"checkbox\" class=\"justDrag aloneCheckbox mousetrap\" onclick=\"checkboxOnClick(event); return true;\"></td>"); } result.append("<td class=\"content\">"); if (entry.hasQuotation()) { result.append("<div class=\"quotation\">"); result.append(getQuotationHtml(entry, true)); result.append("</div><br>"); } String noteHtml = getNoteHtml(entry, false, entry.hasQuotation(), true); if (!noteHtml.isEmpty()) { result.append("<div class=\"note mousetrap\">"); result.append(noteHtml); result.append("</div>"); } result.append("<span class=\"entryDaytime\">" + servletText.fragmentLastModified() + " " + "<span class=\"modTime\">" + formatDateAndTime(entry.getModTime()) + "<span class=\"rawDateTime\">" + entry.getModTime() + "</span></span></span>"); final Entry source = dbLogic.getEntryById(entry.getSourceId()); if (source != null) { addSourceHtml(source, result, SourceEmbedContext.InQuotation, null, -1, null); } // Good for debugging. if (false) { result.append("<br>id: " + entry.getId()); result.append("<br>parent: " + entry.getParentId("")); result.append("<br>first child: " + entry.getFirstChildId("")); result.append("<br>last child: " + entry.getLastChildId("")); result.append("<br>previous sibling: " + entry.getPreviousSiblingId("")); result.append("<br>next sibling: " + entry.getNextSiblingId("")); } result.append("</td></tr></table></div>"); result.append("<div class=\"justchildren\">"); } if (includeRootInEntryInfoList) { addEntryToInfoList(entry, entryInfoList); } int indexOfEntryToSkip = -1; if (levelsOfChildrenToInclude > 0) { --levelsOfChildrenToInclude; final Hashtable<String, Entry> children = new Hashtable<String, Entry>(); Entry first = null; for (final Object childObject : dbLogic.getEntriesByParentId(entry .getId())) { final Entry child = (Entry) childObject; children.put(child.getId(), child); if (!child.hasPreviousSiblingId()) { first = child; } } if (first != null) { // This is the code path if there is no DB corruption. Entry child = first; for (int i = 0; i < children.size(); ++i) { if (child == null) { break; } if (idOfEntryToSkip != null && idOfEntryToSkip.equals(child.getId())) { indexOfEntryToSkip = i; } else { addEntryHtmlToTree(child, result, entryInfoList, levelsOfChildrenToInclude, false, null, true, showCheckboxes); } if (!child.hasNextSiblingId()) { break; } final String nextId = child.getNextSiblingId(); child = children.get(nextId); } } else { // This is an error code path. It should only happen if there is // DB corruption. final Iterator<Map.Entry<String, Entry>> iterator = children .entrySet().iterator(); int i = 0; while (iterator.hasNext()) { final Map.Entry<String, Entry> mapEntry = iterator.next(); final Entry child = mapEntry.getValue(); if (idOfEntryToSkip != null && idOfEntryToSkip.equals(child.getId())) { indexOfEntryToSkip = i; } else { addEntryHtmlToTree(child, result, entryInfoList, levelsOfChildrenToInclude, false, null, true, showCheckboxes); } ++i; } } } if (!onlyChildren) { result.append("</div>"); result.append("</div>"); } return indexOfEntryToSkip; } /** Adds the entry to the entry list. */ private void addEntryToInfoList(Entry entry, List<EntryInfo> entryInfoList) { if (entryInfoList != null) { String typeToAdd = entry.getType(); if (typeToAdd.equals(DbLogic.Constants.quotation)) { typeToAdd = DbLogic.Constants.note; } entryInfoList.add(new EntryInfo(entry.getId(), entry .getNoteOrTitle(""), entry.getQuotation(""), entry .getIsPublic(), entry.hasFirstChildId(), entry .hasParentId(), typeToAdd)); } } enum SourceEmbedContext { InSources, InSource, InQuotations, InQuotation, InSourceQuotations }; /** * Returns JSON HTML suitable for injecting into a list describes the item. * * @throws IOException */ private StringBuilder getItemMetaDataJsonHtml(String type, String id) throws IOException { final StringBuilder result = new StringBuilder(); result.append("\n<script type=\"application/json\" class=\"itemMetaDataDictJson\">\n{\n"); final boolean addedAnyYet = false; JsonBuilder.addPropertyToJsonString(result, type, addedAnyYet, "type"); JsonBuilder.addPropertyToJsonString(result, id, addedAnyYet, "id"); result.append("\n}\n</script>\n"); return result; } /** Helper method. Adds the HTML for a source to a list. */ private void addSourceHtml(Entry source, StringBuilder result, SourceEmbedContext embedContext, String prefix, int resultNumber, String rootId) throws IOException { final String url = source.getSourceUrl(); final StringBuilder header = new StringBuilder(); final StringBuilder footer = new StringBuilder(); if (embedContext == SourceEmbedContext.InQuotation || embedContext == SourceEmbedContext.InQuotations) { header.append("<div class=\"listItemFooter\">"); footer.append("</div>"); } else if (embedContext == SourceEmbedContext.InSources) { startItemListItem(result, rootId, source.getId()); header.append("<table class=\"magic nopadding\"><tr><td class=\"resultNumber\">"); header.append(getItemMetaDataJsonHtml(source.getType(), source.getId()).toString()); header.append(resultNumber + ".</td>"); header.append("<td><input type=\"checkbox\" class=\"justDrag aloneCheckbox\" onclick=\"checkboxOnClick(event); return true;\"></td>"); header.append("<td class=\"listItem\">"); footer.append("</td></tr></table>"); finishItemListItem(footer); } else { header.append("<div>"); footer.append("</div>"); } result.append(header); if (prefix != null) { result.append(prefix); } if (embedContext == SourceEmbedContext.InQuotation || embedContext == SourceEmbedContext.InQuotation) { result.append(servletText.fragmentFrom()); result.append(" "); } String domain = null; try { if (url != null) { final URI uri = new URI(url); domain = uri.getHost(); } } catch (final URISyntaxException e) { } if (embedContext == SourceEmbedContext.InSources) { result.append("<div class=\"sourceHeader\">"); } result.append("<div class=\"sourceTitle\">"); if (domain != null && embedContext != SourceEmbedContext.InSources) { result.append("<a onclick=\"newTab(event); return false;\" target=\"_blank\" title=\"" + servletText.showExternalSourceLinkTooltip() + "\" href=\""); result.append(StringEscapeUtils.escapeHtml4(url)); result.append("\">"); } String title = source.getSourceTitle(); if (title == null || title.isEmpty()) { title = servletText.fragmentBlankTitle(); } if (embedContext == SourceEmbedContext.InSource) { title = servletText.fragmentVisitExternalSource(); } result.append(StringEscapeUtils.escapeHtml4(title)); if (domain != null && embedContext != SourceEmbedContext.InSources) { result.append("</a>"); } result.append("</div>"); result.append(" "); if (domain != null) { result.append("<span class=\"domain\">"); if (embedContext != SourceEmbedContext.InSource) { result.append("("); } result.append(domain); if (embedContext != SourceEmbedContext.InSource) { result.append(")"); } result.append("</span>"); } if (embedContext == SourceEmbedContext.InQuotation || embedContext == SourceEmbedContext.InQuotations || embedContext == SourceEmbedContext.InSources) { result.append(" <a onclick=\"newPaneForLink(event, 'Source', '" + source.getId() + "'); return false;\" class=\"sourceMore\" title=\"" + servletText.moreFromThisSourceTooltip() + "\" href=\"/source/"); result.append(source.getId()); result.append("\">"); result.append(servletText.buttonMoreQuotations()); result.append("</a>"); } if (embedContext == SourceEmbedContext.InSources) { result.append("</div>"); } if (embedContext == SourceEmbedContext.InSource || embedContext == SourceEmbedContext.InSources) { result.append("<div class=\"" + (embedContext == SourceEmbedContext.InSource ? "sourceFooter" : "listItemFooter") + "\">"); result.append(servletText.fragmentLastModified() + " <span>"); result.append(formatDateAndTime(source.getModTime()) + "<span class=\"rawDateTime\">" + source.getModTime() + "</span></span></div>"); } result.append(footer); } /** * Part of the JSON API. Returns the JSON describing the parent of an entry. */ private void handleJsonShowEntryParent(RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.setResponseContentTypeJson(); final String id = requestAndResponse.request .getParameter(DbLogic.Constants.id); if (!dbLogic.getIdGenerator().isIdWellFormed(id)) { returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat()); return; } try { final User user = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); final Entry entry = dbLogic.getEntryById(id); if (entry == null) { returnJson400(requestAndResponse, servletText.errorEntryCouldNotBeFound()); return; } final StringBuilder result = new StringBuilder(); // Do not check if the session is signed in or the account is closed // in case the page is public. if (!dbLogic.canUserSeeEntry(user, entry, isUserAnAdmin(requestAndResponse))) { if (user == null) { returnJson400(requestAndResponse, servletText.errorRequiresSignIn(false)); } else { returnJson400(requestAndResponse, servletText.errorMayNotSeeEntry()); } } else { final String parentId = entry.getParentId(); if (parentId == null) { returnJson400(requestAndResponse, servletText.errorHasNoParent()); } else { final Entry parentEntry = dbLogic.getEntryById(parentId); if (parentEntry == null) { returnJson400(requestAndResponse, servletText.errorParentCouldNotBeFound()); } else if (!dbLogic.canUserSeeEntry(user, parentEntry, isUserAnAdmin(requestAndResponse))) { returnJson400(requestAndResponse, servletText.errorMayNotSeeEntry()); } else { final ArrayList<EntryInfo> entryInfoList = new ArrayList<EntryInfo>(); final StringBuilder innerResult = new StringBuilder(); final int skippedIndex = addEntryHtmlToTree( parentEntry, innerResult, entryInfoList, defaultNoteDisplayDepth, false, id, true, !entry.isNotebook()); result.append("{ \"subtreeHtml\": " + JsonBuilder.quote(innerResult.toString())); result.append(",\n\"id\": \"" + parentEntry.getId() + "\""); result.append(",\n\"skippedIndex\": " + skippedIndex); result.append(",\n\"entryInfoDict\":"); addJsonForEntryInfos(result, entryInfoList, null); result.append("}"); } } } dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { returnJson500(requestAndResponse, servletText.errorInternalDatabase()); } } /** * Part of the JSON API. Returns JSON indicating if the session exists and * is signed in. */ private void handleJsonIsSignedIn(RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.setResponseContentTypeJson(); final String sessionId = requestAndResponse.request .getParameter("sessionId"); boolean signedIn = false; if (sessionManager != null) { final HttpSession session = sessionManager.getSession(sessionId); if (session != null && session.getAttribute(sessionUserIdAttribute) != null) { signedIn = true; } } requestAndResponse.println("{ \"isSignedIn\": " + signedIn + " }"); } /** Part of the JSON API. Returns the JSON describing an entry. */ private void handleJsonShowEntry(RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.setResponseContentTypeJson(); final String id = requestAndResponse.request .getParameter(DbLogic.Constants.id); if (!dbLogic.getIdGenerator().isIdWellFormed(id)) { returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat()); return; } try { final User user = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); final Entry entry = dbLogic.getEntryById(id); if (entry == null) { returnJson400(requestAndResponse, servletText.errorEntryCouldNotBeFound()); return; } final StringBuilder result = new StringBuilder(); // Do not check if the session is signed in or the account is closed // in case the page is public. if (!dbLogic.canUserSeeEntry(user, entry, isUserAnAdmin(requestAndResponse))) { if (user == null) { returnJson400(requestAndResponse, servletText.errorRequiresSignIn(false)); } else { returnJson400(requestAndResponse, servletText.errorMayNotSeeEntry()); } } else { final String parentId = entry.getParentId(); if (parentId == null) { returnJson400(requestAndResponse, servletText.errorHasNoParent()); } else { final Entry parentEntry = dbLogic.getEntryById(parentId); if (parentEntry == null) { returnJson400(requestAndResponse, servletText.errorParentCouldNotBeFound()); } else if (!dbLogic.canUserSeeEntry(user, parentEntry, isUserAnAdmin(requestAndResponse))) { returnJson400(requestAndResponse, servletText.errorMayNotSeeEntry()); } else { final ArrayList<EntryInfo> entryInfoList = new ArrayList<EntryInfo>(); final StringBuilder innerResult = new StringBuilder(); addEntryHtmlToTreeSimple(entry, innerResult, entryInfoList, defaultNoteDisplayDepth, !entry.isNotebook()); result.append("{ \"subtreeHtml\": " + JsonBuilder.quote(innerResult.toString()) + "\n"); result.append(", \"id\": " + JsonBuilder.quote(entry.getId()) + "\n"); result.append(", \"entryInfoDict\": "); addJsonForEntryInfos(result, entryInfoList, null); result.append(" }"); } } } dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { returnJson500(requestAndResponse, servletText.errorInternalDatabase()); } } /** * Part of the JSON API. Returns the JSON describing the children of an * entry. */ private void handleJsonShowEntryChildren( RequestAndResponse requestAndResponse) throws IOException, ServletException { requestAndResponse.setResponseContentTypeJson(); final String id = requestAndResponse.request .getParameter(DbLogic.Constants.id); final String levels = requestAndResponse.getParameter("levels"); if (!dbLogic.getIdGenerator().isIdWellFormed(id)) { returnJson400(requestAndResponse, servletText.errorIdIsInvalidFormat()); return; } if (levels == null || levels.length() > 3 || (!Pattern.compile("^\\d+$").matcher(levels).find() && levels .equals("max"))) { returnJson400(requestAndResponse, servletText.errorLevelsIsInvalid()); return; } int numLevels = Integer.MAX_VALUE; if (!levels.equals("max")) { numLevels = Integer.parseInt(levels); } try { final User user = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); final Entry entry = dbLogic.getEntryById(id); if (entry == null) { returnJson400(requestAndResponse, servletText.errorEntryCouldNotBeFound()); return; } final StringBuilder result = new StringBuilder(); // Do not check if the session is signed in or the account is closed // in case the page is public. if (!dbLogic.canUserSeeEntry(user, entry, isUserAnAdmin(requestAndResponse))) { if (user == null) { returnJson400(requestAndResponse, servletText.errorRequiresSignIn(false)); } else { returnJson400(requestAndResponse, servletText.errorMayNotSeeEntry()); } } else { final ArrayList<EntryInfo> entryInfoList = new ArrayList<EntryInfo>(); final StringBuilder innerResult = new StringBuilder(); addEntryHtmlToTree(entry, innerResult, entryInfoList, numLevels, true, null, false, !entry.isNotebook()); result.append("{ \"childrenHtml\": " + JsonBuilder.quote(innerResult.toString()) + "\n"); result.append(", \"id\": " + JsonBuilder.quote(entry.getId()) + "\n"); result.append(", \"entryInfoDict\": "); addJsonForEntryInfos(result, entryInfoList, null); result.append(" }"); } dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { returnJson500(requestAndResponse, servletText.errorInternalDatabase()); } } /** Part of the HTML API. Returns the HTML for a notebook. */ private void handleHtmlShowNotebook(RequestAndResponse requestAndResponse) throws IOException, ServletException { String paneId = "notebook"; final String defaultTitle = servletText.pageTitleNotebook(); final String notFoundMessage = servletText .errorNotebookCouldNotBeFound(); final String mayNotSeeMessage = servletText.errorMayNotSeeNotebook(); final String introMessage = servletText.introTextShowNotebook(false); final String touchIntroMessage = servletText.introTextShowNotebook(true); final String tooltipNewChild = servletText.tooltipNewNote(); final String buttonNewChild = servletText.buttonNewNote(); String titleIfCanSee = defaultTitle; final String id = requestAndResponse.getURIParameter(); Entry entry = dbLogic.getEntryById(id); if (entry != null && !entry.getType("").equals(DbLogic.Constants.notebook)) { entry = null; } final User user = dbLogic .getUserById(getEffectiveUserId(requestAndResponse)); boolean userCanSee = false; Entry root = null; if (entry != null) { titleIfCanSee = entry.getNoteOrTitle(""); paneId = entry.getId(); root = dbLogic.getEntryById(entry.getRootId()); userCanSee = dbLogic.canUserSeeEntry(user, entry, isUserAnAdmin(requestAndResponse)); } handleHtmlShowEntryTree(requestAndResponse, paneId, defaultTitle, notFoundMessage, mayNotSeeMessage, introMessage, touchIntroMessage, tooltipNewChild, buttonNewChild, titleIfCanSee, root, userCanSee, user, true, "newSubNote", "notebook", false); } /** Show a tree of notes. */ private void handleHtmlShowEntryTree(RequestAndResponse requestAndResponse, String paneId, String defaultTitle, String notFoundMessage, String mayNotSeeMessage, String introMessage, String touchIntroMessage, String tooltipNewChild, String buttonNewChild, String titleIfCanSee, Entry root, boolean userCanSee, User user, boolean showDeleteAndExport, String buttonFunction, String paneType, Boolean notEditable) throws IOException, ServletException { final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, defaultTitle, false).setPaneId(paneId); pageWrapper.addMetaData(new KeyAndValue("paneType", paneType)); pageWrapper.addMetaData(new KeyAndValue("notEditable", notEditable)); pageWrapper.addMetaData(new KeyAndValue("tree", true)); boolean headerAdded = false; try { final StringBuilder result = new StringBuilder(); if (root == null) { if (addTitle(requestAndResponse, defaultTitle)) { dbLogic.commit(); return; } pageWrapper.addHeader(); headerAdded = true; if (!requestAndResponse.moreThanOneUri) { requestAndResponse.response .setStatus(HttpServletResponse.SC_NOT_FOUND); } if (user == null) { result.append(servletText.errorRequiresSignIn(false)); } else { result.append(notFoundMessage); } } else if (!userCanSee) { if (addTitle(requestAndResponse, defaultTitle)) { dbLogic.commit(); return; } pageWrapper.addHeader(); headerAdded = true; if (user == null) { result.append(servletText.errorRequiresSignIn(false)); } else { result.append(mayNotSeeMessage); } } else { if (addTitle(requestAndResponse, titleIfCanSee)) { dbLogic.commit(); return; } pageWrapper.setTitle(titleIfCanSee); pageWrapper.setIncludeEdit(); if (showDeleteAndExport) { pageWrapper.setIncludeExport(); pageWrapper.setIncludeDelete(); } pageWrapper.addHeader(); pageWrapper.addPageIntroText(introMessage, touchIntroMessage); headerAdded = true; result.append("<div class=\"container\"" + "><div class=\"alone fakealone\" id=\"alone_" + root.getId() + "\"></div><div class=\"justchildren fakejustchildren\">"); final ArrayList<EntryInfo> entryInfoList = new ArrayList<EntryInfo>(); addEntryHtmlToTree(root, result, entryInfoList, defaultNoteDisplayDepth, true, null, true, !notEditable); result.append("</div></div>"); result.append("<div class=\"centered\"><button title=\"" + tooltipNewChild + "\" class=\"centered specialbutton\" onclick=\"" + buttonFunction + "(event); return false;\">" + buttonNewChild + "</button></div>"); result.append("\n<script type=\"application/json\" class=\"entryInfoDictJson\">\n"); addJsonForEntryInfos(result, entryInfoList, null); result.append("\n</script>\n"); } dbLogic.commit(); requestAndResponse.print(result.toString()); } catch (final PersistenceException e) { if (!headerAdded) { pageWrapper.addHeader(); } requestAndResponse.print(servletText.errorInternalDatabase()); } pageWrapper.addFooter(); } /** Adds the JSON for note and quotation text. */ private void addJsonForEntryInfos(StringBuilder result, ArrayList<EntryInfo> entryInfoList, String paneId) { result.append("{\n"); boolean addedOneAlready = false; for (final EntryInfo entryInfo : entryInfoList) { if (addedOneAlready) { result.append(",\n"); } addedOneAlready = true; result.append(JsonBuilder .quote((paneId != null ? paneId + ":" : "") + entryInfo.id)); result.append(":"); result.append("[" + JsonBuilder.quote(entryInfo.note) + ", " + JsonBuilder.quote(entryInfo.quotation) + ", " + entryInfo.isPublic + ", " + entryInfo.hasChildren + ", \"" + entryInfo.type + "\", " + entryInfo.hasParent + "]"); } result.append("\n}"); } private static Logger logger = Logger.getLogger(Servlet.class.getName()); /** * Runs the server. * * @throws IOException */ public boolean run() throws IOException { createTheUserForSingleUserMode(); int numThreads = 8; if (httpsPort != null) { numThreads += 3; } final int idleTimeout = 60000; final BlockingQueue<Runnable> queue = new BlockingArrayQueue<>(10000); final Server server = new Server(new QueuedThreadPool(numThreads, numThreads, idleTimeout, queue)); // HTTP Configuration final HttpConfiguration http_config = new HttpConfiguration(); http_config.setSecureScheme("https"); if (httpsPort != null) { http_config.setSecurePort(httpsPort); } http_config.setOutputBufferSize(32768); // HTTP connector final ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config)); http.setPort(httpPort); http.setIdleTimeout(30000); final ArrayList<Connector> connectors = new ArrayList<Connector>(); connectors.add(http); if (keyStorePath != null) { // SSL requires a certificate so we configure a factory for SSL // contents // with information pointing to what keystore the SSL connection // needs // to know about. final SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath(keyStorePath.getAbsolutePath()); if (keyStorePassword != null) { sslContextFactory.setKeyStorePassword(keyStorePassword); } if (keyManagerPassword != null) { sslContextFactory.setKeyManagerPassword(keyManagerPassword); } // HTTPS configuration. final HttpConfiguration https_config = new HttpConfiguration( http_config); https_config.addCustomizer(new SecureRequestCustomizer()); // HTTPS connector. final ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(https_config)); https.setPort(httpsPort); https.setIdleTimeout(500000); connectors.add(https); } server.setConnectors(connectors.toArray(new Connector[connectors.size()])); final ContextHandlerCollection contexts = createContexts( temporaryDirectory, sessionStoreDirectory); // Set a handler if (logDirectory == null) { server.setHandler(contexts); } else { logDirectory.mkdirs(); // Configure HTTP request logging. final HandlerCollection handlers = new HandlerCollection(); final RequestLogHandler requestLogHandler = new RequestLogHandler(); handlers.setHandlers(new Handler[] { contexts, requestLogHandler }); server.setHandler(handlers); final NCSARequestLog requestLog = new NCSARequestLog( new File(logDirectory, "jetty-yyyy_mm_dd.request.log") .getAbsolutePath()); requestLog.setRetainDays(90); requestLog.setAppend(true); requestLog.setExtended(false); requestLog.setLogTimeZone("GMT"); requestLog.setLogLatency(true); requestLogHandler.setRequestLog(requestLog); } // Start the server try { server.start(); server.join(); } catch (final Throwable t) { logger.log(Level.SEVERE, t.getStackTrace().toString()); } return true; } /** Returns a resource for the directory. */ Resource getDirectoryResource(String directory, boolean isInJar, File installRootDirectory) { if (isInJar) { try { return JarResource.newJarResource(Resource .newResource(Servlet.class.getClassLoader() .getResource(directory))); } catch (final IOException e) { } return null; } else { return Resource.newResource(new File(installRootDirectory, directory)); } } /** Creates a context handler for the directory. */ private ContextHandler createContextHandler(String directory, boolean isInJar, File installRootDirectory, int expiresInSeconds) { final ContextHandler contextHandler = new ContextHandler(); final ResourceHandler resourceHandler = new ExpiresResourceHandler(expiresInSeconds); final String directoryWithSlash = "/" + directory; contextHandler.setContextPath(directoryWithSlash); Resource directoryResource = getDirectoryResource(directory, isInJar, installRootDirectory); directoryResource = new JsMinifyingResource(directoryResource); if (isInJar) { directoryResource = new CachingResource(directoryResource, directoryWithSlash); } resourceHandler.setBaseResource(directoryResource); if (!isInJar) { // This makes development easier because Eclipse can copy files // to the target directory on each save on Windows. resourceHandler.setMinMemoryMappedContentLength(0); } contextHandler.setHandler(resourceHandler); return contextHandler; } /** * Creates the context that handle HTTP requests. * * @throws IOException */ public ContextHandlerCollection createContexts(File temporaryDirectory, File sessionStoreDirectory) throws IOException { // Enable HTTP session tracking with cookies. final ExposedShutdownServletContextHandler htmlJsonContext = new ExposedShutdownServletContextHandler( ServletContextHandler.SESSIONS); if (sessionStoreDirectory != null) { sessionManager = ((ExposedShutdownHashSessionManager) htmlJsonContext .getSessionHandler().getSessionManager()); sessionManager.setStoreDirectory(sessionStoreDirectory); sessionManager.setSavePeriod(30); } htmlJsonContext.setContextPath("/"); // Enable uploading files. final ServletHolder holder = new ServletHolder(this); holder.getRegistration().setMultipartConfig( new MultipartConfigElement(temporaryDirectory.getPath())); htmlJsonContext.addServlet(holder, "/"); // Get the location static files will be served from. final URL location = Servlet.class.getProtectionDomain() .getCodeSource().getLocation(); final File installRootDirectory = new File(location.getFile()); isInJar = getClassResourceName().startsWith("jar:"); int dynamicContexExpiresInSeconds = 2 * 60; final ContextHandler cssContextHandler = createContextHandler("css", isInJar, installRootDirectory, dynamicContexExpiresInSeconds); final ContextHandler jsContextHandler = createContextHandler("js", isInJar, installRootDirectory, dynamicContexExpiresInSeconds); final ContextHandler imagesContextHandler = createContextHandler( "images", isInJar, installRootDirectory, 3600); helpDirectoryResource = getDirectoryResource("doc", isInJar, installRootDirectory); // Create a ContextHandlerCollection and set the context handlers to it. final ContextHandlerCollection contextHandlers = new ContextHandlerCollection(); contextHandlers.setHandlers(new Handler[] { imagesContextHandler, jsContextHandler, cssContextHandler, htmlJsonContext }); return contextHandlers; } /** Manages a list of unique sources, each with a small contiguous integer ID. */ static class SourcesHashList { /** Add a source to the hash list and return its ID. */ int add(Entry source) { Integer id = hash.get(source); if (id == null) { id = hash.size() + 1; list.add(source); hash.put(source, id); } return id; } /** Return the list of sources. */ public List<Entry> getSources() { return list; } private List<Entry> list = new ArrayList<Entry>(); private HashMap<Entry, Integer> hash = new HashMap<Entry, Integer>(); } /** Part of the HTML API. Handle an export. */ private void handleHtmlDoExport(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String pageTitle = servletText.pageTitleExportNotebook(); final String csrft = requestAndResponse.getParameter("csrft"); final String id = requestAndResponse.getParameter("id"); String format = requestAndResponse.getParameter("format"); if (format == null || (!format.equals("markdown") && !format.equals("rtf") && !format.equals("html"))) { format = "html"; } String htmlStructure = requestAndResponse.getParameter("htmlStructure"); if (htmlStructure == null || (!htmlStructure.equals("nestedLists") && !htmlStructure.equals("paragraphs"))) { htmlStructure = "paragraphs"; } final boolean includeQuotations = getCheckBoxValue(requestAndResponse, "includeQuotations"); final boolean includeReferencesSection = getCheckBoxValue(requestAndResponse, "includeReferencesSection"); final PageWrapper pageWrapper = new PageWrapper(requestAndResponse, pageTitle, false).setPaneId("export"); if (isTheCsrftWrong(requestAndResponse, csrft)) { pageWrapper.addHeader(); requestAndResponse.print(servletText.errorRequiresSignIn(false)); pageWrapper.addFooter(); } else if (!isUserSignedIn(requestAndResponse)) { pageWrapper.addHeader(); requestAndResponse.print(servletText .errorRequiresSignIn(false)); pageWrapper.addFooter(); } else if (isUsersAccountClosed(requestAndResponse)) { pageWrapper.addHeader(); requestAndResponse.print(servletText.errorAccountIsClosed()); pageWrapper.addFooter(); } else { final StringBuilder result = new StringBuilder(); try { final String userId = getEffectiveUserId(requestAndResponse); final User user = dbLogic.getUserById(userId); if (user != null) { Entry entry = dbLogic.getEntryById(id); if (entry != null && !entry.getType("").equals(DbLogic.Constants.notebook)) { entry = null; } if (entry == null) { pageWrapper.addHeader(); requestAndResponse.print(servletText.errorNotebookCouldNotBeFound()); pageWrapper.addFooter(); return; } boolean userCanSee = false; Entry root = null; if (entry != null) { root = dbLogic.getEntryById(entry.getRootId()); userCanSee = dbLogic.canUserSeeEntry(user, entry, isUserAnAdmin(requestAndResponse)); } if (!userCanSee) { pageWrapper.addHeader(); requestAndResponse.print(servletText.errorMayNotSeeNotebook()); pageWrapper.addFooter(); return; } String extension = null; if (format.equals("html")) { getNotebookHtmlForExport(result, entry, root, htmlStructure.equals("nestedLists"), includeQuotations, includeReferencesSection); extension = "html"; } else if (format.equals("markdown")) { getNotebookMarkdownForExport(result, entry, root, includeQuotations, includeReferencesSection); extension = "md"; requestAndResponse.setResponseContentTypeText(); } else if (format.equals("rtf")) { getNotebookRtfForExport(result, entry, root, includeQuotations, includeReferencesSection); extension = "rtf"; requestAndResponse.setResponseContentTypeRtf(); } requestAndResponse.response.setHeader( "Content-Disposition", "attachment; filename=crushpaper-export-" + user.getUserName() + "-" + formatDateTimeForFileName(System .currentTimeMillis()) + "." + extension); } dbLogic.commit(); } catch (final PersistenceException e) { } requestAndResponse.print(result.toString()); } } /** * Helper method. Adds the HTML for an entry to an export. */ private void addEntryHtmlToExport(Entry entry, StringBuilder result, SourcesHashList sources, boolean asNestedLists, boolean includeQuotations, boolean includeReferencesSection, boolean skipThisLevel) throws IOException { if (!skipThisLevel) { if (asNestedLists) { result.append("<div class=\"noteAndQuotation\">\n"); } final Entry source = dbLogic.getEntryById(entry.getSourceId()); int sourceId = 0; if (source != null) { sourceId = sources.add(source); } if (includeQuotations && entry.hasQuotation()) { result.append("<p class=\"quotation\">"); result.append(textToPreishHtml(entry.getQuotation(), false)); if (includeReferencesSection) { if (sourceId != 0) { result.append(" <a href=\"#reference" + sourceId + "\">[" + sourceId + "]</a>"); } } result.append("</p>\n"); } if (entry.hasNote()) { String noteHtml = textToPreishHtml(entry.getNote(), false); if (!noteHtml.isEmpty()) { result.append("<p class=\"note\">"); result.append(noteHtml); result.append("</p>\n"); } } } List<?> childrenFromDb = dbLogic.getEntriesByParentId(entry .getId()); if (!childrenFromDb.isEmpty()) { if (asNestedLists) { result.append("<ol class=\"subnotes\">\n"); } final Hashtable<String, Entry> children = new Hashtable<String, Entry>(); Entry first = null; for (final Object childObject : childrenFromDb) { final Entry child = (Entry) childObject; children.put(child.getId(), child); if (!child.hasPreviousSiblingId()) { first = child; } } if (first != null) { // This is the code path if there is no DB corruption. Entry child = first; for (int i = 0; i < children.size(); ++i) { if (child == null) { break; } if (asNestedLists) { result.append("<li>\n"); } addEntryHtmlToExport(child, result, sources, asNestedLists, includeQuotations, includeReferencesSection, false); if (asNestedLists) { result.append("</li>\n"); } if (!child.hasNextSiblingId()) { break; } final String nextId = child.getNextSiblingId(); child = children.get(nextId); } } else { // This is an error code path. It should only happen if there is // DB corruption. final Iterator<Map.Entry<String, Entry>> iterator = children .entrySet().iterator(); while (iterator.hasNext()) { final Map.Entry<String, Entry> mapEntry = iterator.next(); final Entry child = mapEntry.getValue(); if (asNestedLists) { result.append("<li>\n"); } addEntryHtmlToExport(child, result, sources, asNestedLists, includeQuotations, includeReferencesSection, false); if (asNestedLists) { result.append("</li>\n"); } } } if (asNestedLists) { result.append("</ol>\n"); } } if (!skipThisLevel && asNestedLists) { result.append("</div>\n"); } } /** Helper method. Adds the HTML for a source to a list. */ private void addSourceHtmlToExport(Entry source, StringBuilder result) throws IOException { final String url = source.getSourceUrl(); result.append("<div class=\"source\">\n"); result.append("<div class=\"sourceTitle\">"); String title = source.getSourceTitle(); if (title == null || title.isEmpty()) { title = servletText.fragmentBlankTitle(); } result.append(StringEscapeUtils.escapeHtml4(title)); result.append("</div>\n"); if (url != null && !url.isEmpty()) { result.append("<a target=\"_blank\" href=\""); result.append(StringEscapeUtils.escapeHtml4(url)); result.append("\">"); result.append(StringEscapeUtils.escapeHtml4(url)); result.append("</a>\n"); } result.append("</div>\n"); } /** Export the notebook in HTML format. */ private void getNotebookHtmlForExport(final StringBuilder result, Entry entry, Entry root, boolean asNestedLists, boolean includeQuotations, boolean includeReferencesSection) throws IOException { String title = StringEscapeUtils.escapeHtml4(entry.getNoteOrTitle()); result.append("<!doctype html><html>\n"); result.append("<head>\n"); result.append("<title>"); result.append(title); result.append("</title>\n"); result.append("<style type=\"text/css\">" + "p.quotation { font-family:Georgia, serif; background:#FDFFAA; padding:4px 8px 4px 8px; border-left:1px solid #dedede; }\n" + "</style>"); result.append("</head>\n"); result.append("<body>\n"); result.append("<h1>"); result.append(title); result.append("</h1>\n"); SourcesHashList sources = new SourcesHashList(); addEntryHtmlToExport(root, result, sources, asNestedLists, includeQuotations, includeReferencesSection, true); if (includeReferencesSection) { List<Entry> sourcesList = sources.getSources(); if (!sourcesList.isEmpty()) { result.append("<h2>References</h2>\n<ol>\n"); int i = 0; for (Entry source : sourcesList) { result.append("<li>\n"); result.append("<a name=\"reference" + (++i) + "\">\n"); addSourceHtmlToExport(source, result); result.append("</a>\n</li>\n"); } result.append("</ol>\n"); } } result.append("</body>\n</html>\n"); } /** Blockquotes a string in Markdown format. */ private String markdownBlockquote(String value) { return "> " + value.replace("\n", "\n> "); } /** * Helper method. Adds the Markdown for an entry to an export. */ private void addEntryMarkdownToExport(Entry entry, StringBuilder result, SourcesHashList sources, boolean includeQuotations, boolean includeReferencesSection, boolean skipThisLevel) throws IOException { if (!skipThisLevel) { final Entry source = dbLogic.getEntryById(entry.getSourceId()); int sourceId = 0; if (source != null) { sourceId = sources.add(source); } if (includeQuotations && entry.hasQuotation()) { result.append(markdownBlockquote(entry.getQuotation(""))); if (includeReferencesSection) { if (sourceId != 0) { result.append(" [Reference" + sourceId + "] [Reference" + sourceId + "]"); } } result.append("\n\n"); } if (entry.hasNote()) { result.append(entry.getNote("").replace("\n", " \n") + "\n\n"); } } List<?> childrenFromDb = dbLogic.getEntriesByParentId(entry .getId()); if (!childrenFromDb.isEmpty()) { final Hashtable<String, Entry> children = new Hashtable<String, Entry>(); Entry first = null; for (final Object childObject : childrenFromDb) { final Entry child = (Entry) childObject; children.put(child.getId(), child); if (!child.hasPreviousSiblingId()) { first = child; } } if (first != null) { // This is the code path if there is no DB corruption. Entry child = first; for (int i = 0; i < children.size(); ++i) { if (child == null) { break; } addEntryMarkdownToExport(child, result, sources, includeQuotations, includeReferencesSection, false); if (!child.hasNextSiblingId()) { break; } final String nextId = child.getNextSiblingId(); child = children.get(nextId); } } else { // This is an error code path. It should only happen if there is // DB corruption. final Iterator<Map.Entry<String, Entry>> iterator = children .entrySet().iterator(); while (iterator.hasNext()) { final Map.Entry<String, Entry> mapEntry = iterator.next(); final Entry child = mapEntry.getValue(); addEntryMarkdownToExport(child, result, sources, includeQuotations, includeReferencesSection, false); } } } } /** Helper method. Adds the Markdown for a source to a list. */ private void addSourceMarkdownToExport(Entry source, int index, StringBuilder result) throws IOException { result.append("Reference " + index + " "); final String title = source.getNoteOrTitle(""); result.append(title); final String url = source.getSourceUrl(); if (url != null && !url.isEmpty()) { result.append(" \n"); result.append(" [" + url + "] [Reference" + index + "]"); result.append("\n"); } else { result.append("\n"); } result.append("\n"); result.append("[Reference" + index + "]: "); if (url != null && !url.isEmpty()) { result.append(url); } result.append(" \""); result.append(title); result.append("\"\n"); } /** Export the notebook in Markdown format. */ private void getNotebookMarkdownForExport(final StringBuilder result, Entry entry, Entry root, boolean includeQuotations, boolean includeReferencesSection) throws IOException { result.append("# "); result.append(entry.getNoteOrTitle()); result.append("\n\n"); SourcesHashList sources = new SourcesHashList(); addEntryMarkdownToExport(root, result, sources, includeQuotations, includeReferencesSection, true); if (includeReferencesSection) { List<Entry> sourcesList = sources.getSources(); if (!sourcesList.isEmpty()) { result.append("## References\n\n"); int i = 0; for (Entry source : sourcesList) { addSourceMarkdownToExport(source, ++i, result); } result.append("\n"); } } } /** Appends the string the a RTF value escaping for unicode. This is a slow function. */ private void appendRtfString(StringBuilder result, String value) { // Inspired by http://blog.stuartlewis.com/2010/09/18/java-rtf-and-unicode-characters/ for (int i = 0; i < value.length(); i++) { int codePoint = value.codePointAt(i); // If the character value is above the // 7-bit range of RTF ASCII if (codePoint == 10) { result.append("\\par\n"); } else if (codePoint > 127) { result.append("\\u" + codePoint + "?"); } else { result.append(value.substring(i, i + 1)); } } } /** * Helper method. Adds the RTF for an entry to an export. */ private void addEntryRtfToExport(Entry entry, StringBuilder result, SourcesHashList sources, boolean includeQuotations, boolean includeReferencesSection, boolean skipThisLevel) throws IOException { if (!skipThisLevel) { final Entry source = dbLogic.getEntryById(entry.getSourceId()); int sourceId = 0; if (source != null) { sourceId = sources.add(source); } if (includeQuotations && entry.hasQuotation()) { appendRtfString(result, entry.getQuotation("")); result.append("\\par\n"); if (includeReferencesSection) { if (sourceId != 0) { result.append("[Reference " + sourceId + "]\\par\n"); } } result.append("\\par\n"); } if (entry.hasNote()) { appendRtfString(result, entry.getNote("")); result.append("\\par\n\\par\n"); } } List<?> childrenFromDb = dbLogic.getEntriesByParentId(entry .getId()); if (!childrenFromDb.isEmpty()) { final Hashtable<String, Entry> children = new Hashtable<String, Entry>(); Entry first = null; for (final Object childObject : childrenFromDb) { final Entry child = (Entry) childObject; children.put(child.getId(), child); if (!child.hasPreviousSiblingId()) { first = child; } } if (first != null) { // This is the code path if there is no DB corruption. Entry child = first; for (int i = 0; i < children.size(); ++i) { if (child == null) { break; } addEntryRtfToExport(child, result, sources, includeQuotations, includeReferencesSection, false); if (!child.hasNextSiblingId()) { break; } final String nextId = child.getNextSiblingId(); child = children.get(nextId); } } else { // This is an error code path. It should only happen if there is // DB corruption. final Iterator<Map.Entry<String, Entry>> iterator = children .entrySet().iterator(); while (iterator.hasNext()) { final Map.Entry<String, Entry> mapEntry = iterator.next(); final Entry child = mapEntry.getValue(); addEntryRtfToExport(child, result, sources, includeQuotations, includeReferencesSection, false); } } } } /** Helper method. Adds the RTF for a source to a list. */ private void addSourceRtfToExport(Entry source, int index, StringBuilder result) throws IOException { final String title = source.getNoteOrTitle(""); final String url = source.getSourceUrl(); result.append("Reference " + index + ": "); appendRtfString(result, title); result.append("\\par\n"); if (url != null && !url.isEmpty()) { appendRtfString(result, url); result.append("\\par\n"); } result.append("\\par\n"); } /** Export the notebook in RTF format. */ private void getNotebookRtfForExport(final StringBuilder result, Entry entry, Entry root, boolean includeQuotations, boolean includeReferencesSection) throws IOException { // This is the spec: http://www.biblioscape.com/rtf15_spec.htm result.append("{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fnil\\fcharset0 Calibri;}}\\viewkind4\\uc1\\pard\\sl240\\slmult1\\lang9\\f0\\fs22"); result.append("\\b "); appendRtfString(result, entry.getNoteOrTitle()); result.append("\\b0 \\par\n\\par\n"); SourcesHashList sources = new SourcesHashList(); addEntryRtfToExport(root, result, sources, includeQuotations, includeReferencesSection, true); if (includeReferencesSection) { List<Entry> sourcesList = sources.getSources(); if (!sourcesList.isEmpty()) { result.append("\\b "); result.append("References"); result.append("\\b0\\par\n\\par\n"); int i = 0; for (Entry source : sourcesList) { addSourceRtfToExport(source, ++i, result); } result.append("\\par\n"); } } result.append(" } \0"); } /** * Returns the name of the resource this class is embedded in which might be * a JAR. */ private String getClassResourceName() { return this.getClass().getResource("Servlet.class").toString(); } /** Returns the version number embedded in the JAR name or null. */ private String getVersionNumber() { final String maybeJarName = getClassResourceName(); final Pattern pattern = Pattern .compile("^.*\\-(\\d+\\.\\d+\\.\\d+[^.]*)\\.jar.*$"); final Matcher matcher = pattern.matcher(maybeJarName); if (matcher.matches()) { return matcher.group(1); } else { return null; } } }
248,353
Java
.java
6,367
32.502906
220
0.680224
ZapBlasterson/crushpaper
57
5
0
AGPL-3.0
9/4/2024, 7:10:21 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
248,353
4,641,464
IWizardBranding.java
ARCAD-Software_arcad-evolution/bundles/aev.core.ui/src/com/arcadsoftware/aev/core/ui/wizards/IWizardBranding.java
package com.arcadsoftware.aev.core.ui.wizards; import org.eclipse.jface.resource.ImageDescriptor; public interface IWizardBranding { ImageDescriptor getBrandingImage(); }
174
Java
.java
5
33.2
50
0.862275
ARCAD-Software/arcad-evolution
2
0
0
EPL-2.0
9/5/2024, 12:20:18 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
174
497,409
SearchUtils.java
trol73_mucommander/src/main/ru/trolsoft/utils/search/SearchUtils.java
/* * This file is part of trolCommander, http://www.trolsoft.ru/en/soft/trolcommander * Copyright (C) 2013-2016 Oleg Trifonov * * trolCommander is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * trolCommander is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ru.trolsoft.utils.search; /** * @author Oleg Trifonov * Created on 16/11/14. */ public class SearchUtils { public static long indexOf(SearchSourceStream source, SearchPattern pattern) throws SearchException { if (!source.hasNext() || pattern.length() == 0) { return -1; } int[] failure = computeFailure(pattern); int j = 0; long i = 0; while (source.hasNext()) { int b = source.next(); i++; while (j > 0 && !pattern.checkByte(j, b)) { j = failure[j - 1]; } if (pattern.checkByte(j, b)) { j++; } if (j == pattern.length()) { return i - pattern.length() + 1; } } source.close(); return -1; } /** * Computes the failure function using a boot-strapping process, * where the pattern is matched against itself. */ private static int[] computeFailure(SearchPattern pattern) { int[] failure = new int[pattern.length()]; int j = 0; for (int i = 1; i < pattern.length(); i++) { while (j > 0 && !pattern.checkSelf(i, j)) { j = failure[j - 1]; } if (pattern.checkSelf(i, j)) { j++; } failure[i] = j; } return failure; } }
2,206
Java
.java
65
26.461538
105
0.586692
trol73/mucommander
179
43
47
GPL-3.0
9/4/2024, 7:07:37 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
2,206
2,201,892
Object.java
atsb_NuBuildGDX/src/ru/m210projects/Powerslave/Object.java
// This file is part of PowerslaveGDX. // Copyright (C) 2019 Alexander Makarov-[M210] (m210-2007@mail.ru) // // PowerslaveGDX is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // PowerslaveGDX is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with PowerslaveGDX. If not, see <http://www.gnu.org/licenses/>. package ru.m210projects.Powerslave; import static ru.m210projects.Build.Net.Mmulti.numplayers; import static ru.m210projects.Build.Engine.*; import static ru.m210projects.Powerslave.Main.*; import static ru.m210projects.Powerslave.Player.*; import static ru.m210projects.Powerslave.Globals.*; import static ru.m210projects.Powerslave.Seq.*; import static ru.m210projects.Powerslave.Anim.*; import static ru.m210projects.Powerslave.Bullet.BuildBullet; import static ru.m210projects.Powerslave.Random.*; import static ru.m210projects.Powerslave.RunList.*; import static ru.m210projects.Powerslave.Sound.*; import ru.m210projects.Build.FileHandle.Resource; import ru.m210projects.Build.Types.SECTOR; import ru.m210projects.Build.Types.SPRITE; import ru.m210projects.Powerslave.Type.BobStruct; import ru.m210projects.Powerslave.Type.Channel; import ru.m210projects.Powerslave.Type.DripStruct; import ru.m210projects.Powerslave.Type.ElevStruct; import ru.m210projects.Powerslave.Type.ObjectStruct; import ru.m210projects.Powerslave.Type.SafeLoader; import ru.m210projects.Powerslave.Type.TrailPointStruct; import ru.m210projects.Powerslave.Type.TrailStruct; import ru.m210projects.Powerslave.Type.TrapStruct; import ru.m210projects.Powerslave.Type.WallFaceStruct; import static ru.m210projects.Powerslave.Sprites.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import static ru.m210projects.Powerslave.Map.*; import static ru.m210projects.Powerslave.Light.*; public class Object { public static int ElevCount; public static ElevStruct Elevator[] = new ElevStruct[1024]; public static int WallFaceCount; public static WallFaceStruct WallFace[] = new WallFaceStruct[4096]; public static void InitElev() { ElevCount = 1024; for (int i = 0; i < 1024; i++) Elevator[i] = new ElevStruct(); } public static ByteBuffer saveElevs() { ByteBuffer bb = ByteBuffer.allocate((1024 - ElevCount) * ElevStruct.size + 2); bb.order(ByteOrder.LITTLE_ENDIAN); bb.putShort((short)ElevCount); for(int i = ElevCount; i < 1024; i++) Elevator[i].save(bb); return bb; } public static void loadElevs(SafeLoader loader, Resource bb) { if(bb != null) { loader.ElevCount = bb.readShort(); for(int i = loader.ElevCount; i < 1024; i++) { if(loader.Elevator[i] == null) loader.Elevator[i] = new ElevStruct(); loader.Elevator[i].load(bb); } } else { ElevCount = loader.ElevCount; for(int i = loader.ElevCount; i < 1024; i++) { if(Elevator[i] == null) Elevator[i] = new ElevStruct(); Elevator[i].copy(loader.Elevator[i]); } } } public static int BuildElevC(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int... a8) { if (ElevCount <= 0) { game.ThrowError("ElevCount>0"); return -1; } if (ElevCount <= 0) return -1; int i = --ElevCount; Elevator[i].field_0 = (short) a1; if ((a1 & 4) != 0) a5 /= 2; Elevator[i].field_6 = a5; Elevator[i].field_E = 0; Elevator[i].field_36 = 0; Elevator[i].field_10 = 0; Elevator[i].field_A = a6; Elevator[i].field_32 = -1; Elevator[i].channel = (short) a2; Elevator[i].sectnum = (short) a3; if (a4 < 0) a4 = BuildWallSprite(a3); Elevator[i].field_34 = (short) a4; for (int j = 0; j < a7; j++) { Elevator[i].field_12[Elevator[i].field_E] = a8[j]; Elevator[i].field_E++; } return i; } public static int BuildElevF(int a1, int a2, int a3, int a4, int a5, int a6, int... a7) { if (ElevCount <= 0) { game.ThrowError("ElevCount>0"); return -1; } if (ElevCount <= 0) return -1; int i = --ElevCount; if ((a1 & 4) != 0) a5 /= 2; Elevator[i].field_0 = 2; Elevator[i].field_6 = a4; Elevator[i].field_32 = -1; Elevator[i].field_A = a5; Elevator[i].channel = (short) a1; Elevator[i].sectnum = (short) a2; Elevator[i].field_E = 0; Elevator[i].field_10 = 0; Elevator[i].field_36 = 0; if (a3 < 0) a3 = BuildWallSprite(a2); Elevator[i].field_34 = (short) a3; for (int j = 0; j < a6; j++) { Elevator[i].field_12[Elevator[i].field_E] = a7[j]; Elevator[i].field_E++; } return i; } public static void FuncElev(int a1, int a2, int RunPtr) { short elev = (short) (RunData[RunPtr].RunEvent & 0xFFFF); if (elev < 0 || elev >= 1024) { game.ThrowError("elev>=0 && elev<MAXELEV"); return; } int nRun = a1 & 0x7F0000; if(nRun != 0x20000 && nRun != 0x10000) return; int chan = Elevator[elev].channel; if (chan < 0 || chan >= 4096) { game.ThrowError("chan>=0 && chan<MAXCHAN"); return; } Channel pChannel = channel[chan]; int nFlags = Elevator[elev].field_0; switch (nRun) { case 0x20000: if ((nFlags & 2) != 0) { game.pInt.setfloorinterpolate(Elevator[elev].sectnum, sector[Elevator[elev].sectnum]); int v18 = LongSeek(sector[Elevator[elev].sectnum].floorz, Elevator[elev].field_12[Elevator[elev].field_10], Elevator[elev].field_6, Elevator[elev].field_A); sector[Elevator[elev].sectnum].floorz = longSeek_out; if (v18 == 0) { if ((nFlags & 0x10) != 0) { Elevator[elev].field_10 ^= 1; StartElevSound(Elevator[elev].field_34, nFlags); } else { StopSpriteSound(Elevator[elev].field_34); SubRunRec(RunPtr); Elevator[elev].field_32 = -1; ReadyChannel(chan); D3PlayFX(StaticSound[nStopSound], Elevator[elev].field_34); } int v16 = Elevator[elev].field_34; while (v16 != -1) { int v29 = v16; v16 = sprite[v29].owner; game.pInt.setsprinterpolate(v29, sprite[v29]); sprite[v29].z += v18; } return; } MoveSectorSprites(Elevator[elev].sectnum, v18); if (v18 >= 0 || !CheckSectorSprites(Elevator[elev].sectnum, 2)) { int v16 = Elevator[elev].field_34; while (v16 != -1) { int v29 = v16; v16 = sprite[v29].owner; game.pInt.setsprinterpolate(v29, sprite[v29]); sprite[v29].z += v18; } return; } ChangeChannel(chan, channel[chan].field_4 == 0 ? 1 : 0); return; } SECTOR v34 = sector[Elevator[elev].sectnum]; game.pInt.setceilinterpolate(Elevator[elev].sectnum, sector[Elevator[elev].sectnum]); int v30 = sector[Elevator[elev].sectnum].ceilingz; int v27 = LongSeek(v30, Elevator[elev].field_12[Elevator[elev].field_10], Elevator[elev].field_6, Elevator[elev].field_A); v30 = longSeek_out; if (v27 != 0) { if (v27 > 0) { if (v30 == Elevator[elev].field_12[Elevator[elev].field_10]) { if ((nFlags & 4) != 0) SetQuake(Elevator[elev].field_34, 30); PlayFXAtXYZ(StaticSound[26], sprite[Elevator[elev].field_34].x, sprite[Elevator[elev].field_34].y, sprite[Elevator[elev].field_34].z, sprite[Elevator[elev].field_34].sectnum); } if ((nFlags & 4) != 0) { if (CheckSectorSprites(Elevator[elev].sectnum, 1)) return; } else if (CheckSectorSprites(Elevator[elev].sectnum, 0)) { ChangeChannel(chan, channel[chan].field_4 == 0 ? 1 : 0); return; } } v34.ceilingz = v30; int v16 = Elevator[elev].field_34; while (v16 != -1) { int v29 = v16; v16 = sprite[v29].owner; game.pInt.setsprinterpolate(v29, sprite[v29]); sprite[v29].z += v27; } return; } if ((nFlags & 0x10) == 0) { SubRunRec(RunPtr); Elevator[elev].field_32 = -1; StopSpriteSound(Elevator[elev].field_34); D3PlayFX(StaticSound[nStopSound], Elevator[elev].field_34); ReadyChannel(chan); return; } Elevator[elev].field_10 ^= 1; StartElevSound(Elevator[elev].field_34, nFlags); return; case 0x10000: int a4 = 0; if ((nFlags & 8) == 0) { if ((nFlags & 0x10) != 0) { if (Elevator[elev].field_32 < 0) { Elevator[elev].field_32 = (short) AddRunRec(NewRun, RunData[RunPtr].RunEvent); a4 = 1; StartElevSound(Elevator[elev].field_34, nFlags); } if (a4 != 0) { if (Elevator[elev].field_32 >= 0) return; Elevator[elev].field_32 = (short) AddRunRec(NewRun, RunData[RunPtr].RunEvent); StartElevSound(Elevator[elev].field_34, nFlags); return; } if (Elevator[elev].field_32 >= 0) { SubRunRec(Elevator[elev].field_32); Elevator[elev].field_32 = -1; } return; } if (pChannel.field_4 >= 0) { if (pChannel.field_4 == Elevator[elev].field_10 || pChannel.field_4 >= Elevator[elev].field_E) { Elevator[elev].field_36 = pChannel.field_4; } else { Elevator[elev].field_10 = channel[chan].field_4; } if (Elevator[elev].field_32 >= 0) return; Elevator[elev].field_32 = (short) AddRunRec(NewRun, RunData[RunPtr].RunEvent); StartElevSound(Elevator[elev].field_34, nFlags); return; } if (Elevator[elev].field_32 >= 0) { SubRunRec(Elevator[elev].field_32); Elevator[elev].field_32 = -1; } return; } if (pChannel.field_4 == 0) { if (Elevator[elev].field_32 >= 0) { SubRunRec(Elevator[elev].field_32); Elevator[elev].field_32 = -1; } return; } if (Elevator[elev].field_32 >= 0) return; Elevator[elev].field_32 = (short) AddRunRec(NewRun, RunData[RunPtr].RunEvent); StartElevSound(Elevator[elev].field_34, nFlags); return; } } public static void BuildObject(int a1, int a2, int a3) { int v3 = a1; int v4 = a2; int v24 = a3; int v20 = ObjectCount; if (ObjectCount >= 128) { game.ThrowError("Too many objects!"); return; } if (ObjectList[v20] == null) ObjectList[v20] = new ObjectStruct(); int v5 = ObjectStatnum[a2]; ObjectCount++; int v6 = a1; engine.changespritestat((short) a1, (short) v5); sprite[v6].cstat = (short) ((sprite[v6].cstat | 0x101) & (~(0x8000 | 2))); sprite[v6].xvel = 0; sprite[v6].yvel = 0; sprite[v6].zvel = 0; sprite[v6].extra = -1; sprite[v6].lotag = (short) (HeadRun() + 1); int v8 = v20; int v9 = sprite[v6].lotag; sprite[v6].hitag = 0; sprite[v6].owner = (short) AddRunRec(v9 - 1, 0x170000 | v20); int v12 = v8; if (sprite[v6].statnum == 97) ObjectList[v12].obj_2 = 4; else ObjectList[v12].obj_2 = 120; int v13 = v20; int v14 = NewRun; ObjectList[v13].field_6 = (short) v3; ObjectList[v13].field_4 = (short) AddRunRec(v14, 0x170000 | v20); int v15 = ObjectSeq[v4]; if (v15 <= -1) { ObjectList[v13].field_0 = 0; int v23 = sprite[v3].statnum; ObjectList[v13].field_8 = -1; if (v23 == 97) ObjectList[v13].obj_A = -1; else ObjectList[v13].obj_A = (short) -v24; } else { int v16 = SeqOffsets[v15]; ObjectList[v13].field_8 = (short) v16; if (v4 == 0) { int v17 = SeqSize[v16] - 1; int v18 = RandomSize(4); ObjectList[v13].field_0 = (short) (v18 % v17); } int v19 = v3; int v21 = engine.insertsprite(sprite[v19].sectnum, (short) 0); ObjectList[v20].obj_A = (short) v21; sprite[v21].cstat = (short) 32768; sprite[v21].x = sprite[v19].x; sprite[v21].y = sprite[v19].y; sprite[v21].z = sprite[v19].z; } } public static ByteBuffer saveObjects() { ByteBuffer bb = ByteBuffer.allocate(ObjectCount * ObjectStruct.size + 2); bb.order(ByteOrder.LITTLE_ENDIAN); bb.putShort((short)ObjectCount); for (short i = 0; i < ObjectCount; i++) { ObjectList[i].save(bb); } return bb; } public static void loadObjects(SafeLoader loader, Resource bb) { if(bb != null) { loader.ObjectCount = bb.readShort(); for (short i = 0; i < loader.ObjectCount; i++) { if(loader.ObjectList[i] == null) loader.ObjectList[i] = new ObjectStruct(); loader.ObjectList[i].load(bb); } } else { ObjectCount = loader.ObjectCount; for (short i = 0; i < loader.ObjectCount; i++) { if(ObjectList[i] == null) ObjectList[i] = new ObjectStruct(); ObjectList[i].copy(loader.ObjectList[i]); } } } public static void FuncObject(int a1, int a2, int a3) { ObjectStruct v5 = ObjectList[RunData[a3].RunEvent & 0xFFFF]; int v4 = v5.field_6; int v6 = v4; int v7 = v4; int v45 = v4; int v43 = sprite[v7].statnum; int v8 = (a1 & 0x7F0000); int v9 = v5.field_8; switch (v8) { case 0x20000: if (v43 != 97 && (sprite[v7].cstat & 0x101) != 0) { if (v43 != 152) Gravity(v6); if (v9 != -1) { int v10 = v5.field_0 + 1; v5.field_0 = (short) v10; if (v10 >= SeqSize[v9]) v5.field_0 = 0; sprite[v45].picnum = (short) GetSeqPicnum2(v9, v5.field_0); } if (v5.obj_2 >= 0 || (v5.obj_2++ != -1)) { if (v43 != 152) { int v23 = v45; int v24 = engine.movesprite((short) v45, sprite[v23].xvel << 6, sprite[v23].yvel << 6, sprite[v23].zvel, 0, 0, 0); if (sprite[v23].statnum == 141) sprite[v23].pal = 1; if ((v24 & 0x20000) != 0) { sprite[v45].xvel -= sprite[v45].xvel >> 3; sprite[v45].yvel -= sprite[v45].yvel >> 3; } if ((v24 & 0xC000) == 49152) { sprite[v45].yvel = 0; sprite[v45].xvel = 0; } } } else { int v44; if (v43 != 152 && sprite[v45].z >= sector[sprite[v45].sectnum].floorz) v44 = 34; else v44 = 36; int v13 = v45; AddFlash(sprite[v13].sectnum, sprite[v13].x, sprite[v13].y, sprite[v13].z, 128); BuildAnim(-1, v44, 0, sprite[v13].x, sprite[v13].y, sector[sprite[v13].sectnum].floorz, sprite[v13].sectnum, 0xF0, 4); int v14 = v45 | 0x4000; if (v43 == 141) { for (int i = 4; i < 8; i++) BuildCreatureChunk(v14, GetSeqPicnum(46, (i >> 2) + 1, 0)); RadialDamageEnemy(v45, 200, 20); } else if (v43 == 152) { for (int i = 0; i < 8; i++) BuildCreatureChunk(v14, GetSeqPicnum(46, (i >> 1) + 3, 0)); } if (levelnum <= 20 || v43 != 141) { SubRunRec(sprite[v45].owner); SubRunRec(v5.field_4); engine.mydeletesprite((short) v45); } else { StartRegenerate(v45); int v19 = v5.obj_A; v5.obj_2 = 120; sprite[v45].x = sprite[v19].x; sprite[v45].y = sprite[v19].y; sprite[v45].z = sprite[v19].z; engine.mychangespritesect((short) v45, sprite[v19].sectnum); } } } return; case 0x80000: if (v43 >= 150) return; if (v5.obj_2 <= 0) return; if (v43 == 98) { D3PlayFX((RandomSize(2) << 9) | StaticSound[47] | 0x2000, v5.field_6); return; } v5.obj_2 -= a2; if (v5.obj_2 > 0) return; if (v43 == 97) { ExplodeScreen(v6); return; } v5.obj_2 = (short) -(RandomSize(3) + 1); return; case 0x90000: if (v9 > -1) PlotSequence(a1 & 0xFFFF, v9, v5.field_0, 1); return; case 0xA0000: if (v5.obj_2 > 0 && (sprite[v7].cstat & 0x101) != 0 && (v43 != 152 || sprite[nRadialSpr].statnum == 201 || nRadialBullet != 3 && nRadialBullet > -1 || sprite[nRadialSpr].statnum == 141)) { int v28 = CheckRadialDamage(v45); if (v28 > 0) { if (sprite[v45].statnum != 98) v5.obj_2 -= v28; int v30 = v45; int v31 = sprite[v30].statnum; if (v31 == 152) { sprite[v30].zvel = 0; sprite[v30].yvel = 0; sprite[v30].xvel = 0; } else if (v31 != 98) { sprite[v30].xvel >>= 1; sprite[v30].yvel >>= 1; sprite[v30].zvel >>= 1; } if (v5.obj_2 <= 0) { int v34 = v45; int v35 = sprite[v45].statnum; if (v35 == 152) { int v36 = v5.obj_A; v5.obj_2 = -1; if (v36 >= 0) { if (ObjectList[v36].obj_2 > 0) ObjectList[v36].obj_2 = -1; } return; } if (v35 == 97) { v5.obj_2 = 0; ExplodeScreen(v34); return; } v5.obj_2 = (short) -(RandomSize(4) + 1); } } } return; } } public static void StartRegenerate(int a1) { int v2 = -1; SPRITE v4 = sprite[a1]; int v5 = nFirstRegenerate; int v3 = 0; while (true) { if (v3 >= nRegenerates) { v4.xvel = v4.xrepeat; v4.zvel = v4.shade; v4.yvel = v4.pal; break; } if (v5 == a1) { if (v2 == -1) nFirstRegenerate = v4.ang; else sprite[v2].ang = sprite[a1].ang; --nRegenerates; break; } v2 = v5; v5 = sprite[v5].ang; v3++; } v4.extra = 1350; v4.ang = (short) nFirstRegenerate; if (levelnum <= 20) v4.extra /= 5; v4.cstat = -32768; v4.xrepeat = 1; v4.yrepeat = 1; v4.pal = 1; nFirstRegenerate = a1; nRegenerates++; } public static void DoRegenerates() { int spr = nFirstRegenerate; SPRITE pSprite; for (int i = nRegenerates; i > 0; i--, spr = pSprite.ang) { pSprite = sprite[spr]; if (pSprite.extra <= 0) { if (pSprite.xrepeat < pSprite.xvel) { pSprite.xrepeat += 2; pSprite.yrepeat += 2; continue; } } else { pSprite.extra--; if (pSprite.extra > 0) continue; BuildAnim(-1, 38, 0, pSprite.x, pSprite.y, pSprite.z, pSprite.sectnum, 0x40, 4); D3PlayFX(StaticSound[12], spr); } pSprite.xrepeat = pSprite.xvel; pSprite.yrepeat = pSprite.xvel; pSprite.pal = pSprite.yvel; pSprite.xvel = 0; pSprite.yvel = 0; pSprite.zvel = 0; nRegenerates--; if (pSprite.statnum == 141) pSprite.cstat = 257; else pSprite.cstat = 0; if (nRegenerates == 0) nFirstRegenerate = -1; } } private static void MoveSectorSprites(short a1, int a2) { for (int i = headspritesect[a1]; i != -1; i = nextspritesect[i]) { if (sprite[i].statnum != 200) { game.pInt.setsprinterpolate(i, sprite[i]); sprite[i].z += a2; } } } private static boolean CheckSectorSprites(short a1, int a2) { int v9 = a2; boolean v10 = false; if (a2 != 0) { int v4 = headspritesect[a1]; int v5 = sector[a1].floorz - sector[a1].ceilingz; while (v4 != -1) { if ((sprite[v4].cstat & 0x101) != 0 && v5 < GetSpriteHeight(v4)) { if (v9 != 1) return true; v10 = true; DamageEnemy(v4, -1, 5); if (sprite[v4].statnum == 100 && PlayerList[GetPlayerFromSprite(v4)].HealthAmount <= 0) { int v8 = sprite[v4].sectnum | 0x4000; PlayFXAtXYZ(StaticSound[60], sprite[v4].x, sprite[v4].y, sprite[v4].z, v8); } } v4 = nextspritesect[v4]; } return v10; } else { for (int i = headspritesect[a1]; i != -1; i = nextspritesect[i]) { if ((sprite[i].cstat & 0x101) != 0) return true; } } return false; } public static void SetQuake(int a1, int a2) { int v2 = a1; int v3 = 0; int v4 = 0; int v5 = a2 << 8; int v11 = sprite[v2].x; int v10 = sprite[v2].y; int v6 = 0; while (v3 < numplayers) { int v7 = PlayerList[v4].spriteId; int v8 = engine.ksqrt(((sprite[v7].x - v11) >> 8) * ((sprite[v7].x - v11) >> 8) + ((sprite[v7].y - v10) >> 8) * ((sprite[v7].y - v10) >> 8)); int v9 = v5; if (v8 != 0) { v9 = v5 / v8; if (v5 / v8 >= 256) { if (v9 > 3840) v9 = 3840; } else { v9 = 0; } } if (v9 > nQuake[v6]) nQuake[v6] = (short) v9; ++v4; ++v6; ++v3; } } public static int longSeek_out; public static int LongSeek(int a1, int a2, int a3, int a4) { longSeek_out = a1; int v4 = a2 - longSeek_out; if (v4 < 0) { int v5 = -a3; if (v5 > v4) v4 = v5; longSeek_out += v4; } if (v4 > 0) { if (a4 < v4) v4 = a4; longSeek_out += v4; } return v4; } public static int BuildWallSprite(int a1) { int nWall = sector[a1].wallptr; int nPoint2 = sector[a1].wallptr + 1; int i = engine.insertsprite((short) a1, (short) 401); sprite[i].x = (wall[nWall].x + wall[nPoint2].x) / 2; sprite[i].y = (wall[nWall].y + wall[nPoint2].y) / 2; sprite[i].z = (sector[a1].ceilingz + sector[a1].floorz) / 2; sprite[i].cstat = (short) 32768; return i; } public static void InitWallFace() { WallFaceCount = 4096; for (int i = 0; i < 4096; i++) WallFace[i] = new WallFaceStruct(); } public static ByteBuffer saveWallFaces() { ByteBuffer bb = ByteBuffer.allocate((4096 - WallFaceCount) * WallFaceStruct.size + 2); bb.order(ByteOrder.LITTLE_ENDIAN); bb.putShort((short)WallFaceCount); for(int i = WallFaceCount; i < 4096; i++) WallFace[i].save(bb); return bb; } public static void loadWallFaces(SafeLoader loader, Resource bb) { if(bb != null) { loader.WallFaceCount = bb.readShort(); for(int i = loader.WallFaceCount; i < 4096; i++) { if(loader.WallFace[i] == null) loader.WallFace[i] = new WallFaceStruct(); loader.WallFace[i].load(bb); } } else { WallFaceCount = loader.WallFaceCount; for(int i = loader.WallFaceCount; i < 4096; i++) { if(WallFace[i] == null) WallFace[i] = new WallFaceStruct(); WallFace[i].copy(loader.WallFace[i]); } } } public static int BuildWallFace(int a1, short a2, int a3, int... a4) { if (WallFaceCount <= 0) { game.ThrowError("Too many wall faces!"); return -1; } int i = --WallFaceCount; WallFace[i].field_4 = 0; WallFace[i].field_2 = a2; WallFace[i].field_0 = (short) a1; if (a3 > 8) a3 = 8; for (int j = 0; j < a3; j++) { WallFace[i].field_6[WallFace[i].field_4] = (short) a4[j]; WallFace[i].field_4++; } return i | nEvent6; } public static void FuncWallFace(int a1, int a2, int a3) { short ws = (short) (RunData[a3].RunEvent & 0xFFFF); if (ws < 0 || ws >= 4096) { game.ThrowError("ws>=0 && ws<MAXWALLFACE"); return; } if ((a1 & 0x7F0000) == 0x10000) { int v6 = channel[WallFace[ws].field_0].field_4; if (v6 <= WallFace[ws].field_4 && v6 >= 0) { wall[WallFace[ws].field_2].picnum = WallFace[ws].field_6[v6]; } } } public static int FindTrail(int a1) { int v2 = 0; int v3 = 0; while (v2 < nTrails) { if (a1 == sTrail[v3].field_2) return v2; ++v3; ++v2; } sTrail[nTrails].field_2 = (short) a1; sTrail[nTrails].field_0 = -1; return nTrails++; } public static ByteBuffer saveTrails() { ByteBuffer bb = ByteBuffer.allocate(4 + (TrailStruct.size * nTrails) + nTrailPoints * (TrailPointStruct.size) + 600); bb.order(ByteOrder.LITTLE_ENDIAN); bb.putShort((short)nTrails); bb.putShort((short)nTrailPoints); for(int i = 0; i < nTrails; i++) sTrail[i].save(bb); for(int i = 0; i < nTrailPoints; i++) { sTrailPoint[i].save(bb); } for(int i = 0; i < 100; i++) { bb.putShort(nTrailPointVal[i]); bb.putShort(nTrailPointNext[i]); bb.putShort(nTrailPointPrev[i]); } return bb; } public static void loadTrails(SafeLoader loader, Resource bb) { if(bb != null) { loader.nTrails = bb.readShort(); loader.nTrailPoints = bb.readShort(); for(int i = 0; i < loader.nTrails; i++) { if(loader.sTrail[i] == null) loader.sTrail[i] = new TrailStruct(); loader.sTrail[i].load(bb); } for(int i = 0; i < loader.nTrailPoints; i++) { if(loader.sTrailPoint[i] == null) loader.sTrailPoint[i] = new TrailPointStruct(); loader.sTrailPoint[i].load(bb); } for(int i = 0; i < 100; i++) { loader.nTrailPointVal[i] = bb.readShort(); loader.nTrailPointNext[i] = bb.readShort(); loader.nTrailPointPrev[i] = bb.readShort(); } } else { nTrails = loader.nTrails; nTrailPoints = loader.nTrailPoints; for(int i = 0; i < loader.nTrails; i++) { if(sTrail[i] == null) sTrail[i] = new TrailStruct(); sTrail[i].copy(loader.sTrail[i]); } for(int i = 0; i < loader.nTrailPoints; i++) { if(sTrailPoint[i] == null) sTrailPoint[i] = new TrailPointStruct(); sTrailPoint[i].copy(loader.sTrailPoint[i]); } System.arraycopy(loader.nTrailPointVal, 0, nTrailPointVal, 0, nTrailPoints); System.arraycopy(loader.nTrailPointNext, 0, nTrailPointNext, 0, 100); System.arraycopy(loader.nTrailPointPrev, 0, nTrailPointPrev, 0, 100); } } public static int BuildSpark(int a1, int a2) { int i = engine.insertsprite(sprite[a1].sectnum, (short) 0); if (i != -1) { SPRITE pSprite = sprite[i]; pSprite.x = sprite[a1].x; pSprite.y = sprite[a1].y; pSprite.cstat = 0; pSprite.shade = -127; pSprite.pal = 1; pSprite.xrepeat = 50; pSprite.xoffset = 0; pSprite.yoffset = 0; pSprite.yrepeat = 50; if (a2 >= 2) { pSprite.picnum = 3605; nSmokeSparks++; if (a2 == 3) { pSprite.xrepeat = pSprite.yrepeat = 120; } else { pSprite.xrepeat = pSprite.yrepeat = (short) (sprite[a1].xrepeat + 15); } } else { int v11 = (sprite[a1].ang + 256) - RandomSize(9); if (a2 != 0) { pSprite.xvel = (short) (sintable[(v11 + 512) & 0x7FF] >> 5); pSprite.yvel = (short) (sintable[v11 & 0x7FF] >> 5); } else { pSprite.xvel = (short) (sintable[(v11 + 512) & 0x7FF] >> 6); pSprite.yvel = (short) (sintable[v11 & 0x7FF] >> 6); } pSprite.zvel = (short) (-128 * RandomSize(4)); pSprite.picnum = (short) (a2 + 985); } pSprite.z = sprite[a1].z; pSprite.lotag = (short) (HeadRun() + 1); pSprite.clipdist = 1; pSprite.hitag = 0; pSprite.extra = -1; pSprite.owner = (short) AddRunRec(pSprite.lotag - 1, 0x260000 | i); pSprite.hitag = (short) AddRunRec(NewRun, 0x260000 | i); } return i; } public static void FuncSpark(int a1, int a2, int RunPtr) { short spr = (short) (RunData[RunPtr].RunEvent & 0xFFFF); if (spr < 0 || spr >= MAXSPRITES) { game.ThrowError("spr>=0 && spr<MAXSPRITES"); return; } if ((a1 & 0x7F0000) == 0x20000) { sprite[spr].shade += 3; sprite[spr].xrepeat -= 2; if (sprite[spr].xrepeat >= 4 && sprite[spr].shade < 100) { sprite[spr].yrepeat -= 2; if (sprite[spr].picnum == 986 && (sprite[spr].xrepeat & 2) != 0) BuildSpark(spr, 2); if (sprite[spr].picnum >= 3000) return; sprite[spr].zvel += 128; int result = engine.movesprite((short) spr, sprite[spr].xvel << 12, sprite[spr].yvel << 12, sprite[spr].zvel, 2560, -2560, 1); if (result == 0 || sprite[spr].zvel <= 0) return; } sprite[spr].zvel = 0; sprite[spr].yvel = 0; sprite[spr].xvel = 0; if (sprite[spr].picnum > 3000) --nSmokeSparks; DoSubRunRec(sprite[spr].owner); FreeRun(sprite[spr].lotag - 1); SubRunRec(sprite[spr].hitag); engine.mydeletesprite((short) spr); } } public static int BuildFireBall(int a1, int a2, int a3) { return BuildTrap(a1, 1, a2, a3); } public static int BuildArrow(int a1, int a2) { return BuildTrap(a1, 0, -1, a2); } public static ByteBuffer saveTraps() { ByteBuffer bb = ByteBuffer.allocate(nTraps * (TrapStruct.size) + 2 + 40 * 2); bb.order(ByteOrder.LITTLE_ENDIAN); bb.putShort((short)nTraps); for (short i = 0; i < 40; i++) bb.putShort(nTrapInterval[i]); for (short i = 0; i < nTraps; i++) sTrap[i].save(bb); return bb; } public static void loadTraps(SafeLoader loader, Resource bb) { if(bb != null) { loader.nTraps = bb.readShort(); for (short i = 0; i < 40; i++) loader.nTrapInterval[i] = bb.readShort(); for (short i = 0; i < loader.nTraps; i++) { if(loader.sTrap[i] == null) loader.sTrap[i] = new TrapStruct(); loader.sTrap[i].load(bb); } } else { nTraps = loader.nTraps; System.arraycopy(loader.nTrapInterval, 0, nTrapInterval, 0, nTraps); for (short i = 0; i < loader.nTraps; i++) { if(sTrap[i] == null) sTrap[i] = new TrapStruct(); sTrap[i].copy(loader.sTrap[i]); } } } public static int BuildTrap(int a1, int a2, int a3, int a4) { if (nTraps >= 40) { game.ThrowError("Too many traps!"); return -1; } int v5 = nTraps++; engine.changespritestat((short) a1, (short) 0); sprite[a1].cstat = (short) 32768; sprite[a1].xvel = 0; sprite[a1].yvel = 0; sprite[a1].zvel = 0; sprite[a1].extra = -1; sprite[a1].lotag = (short) (HeadRun() + 1); sprite[a1].hitag = (short) AddRunRec(NewRun, 0x1F0000 | v5); sprite[a1].owner = (short) AddRunRec(sprite[a1].lotag - 1, 0x1F0000 | v5); if (sTrap[v5] == null) sTrap[v5] = new TrapStruct(); sTrap[v5].field_2 = (short) a1; sTrap[v5].field_4 = (short) (((a2 == 0) ? 1 : 0) + 14); sTrap[v5].field_0 = -1; nTrapInterval[v5] = (short) (64 - 2 * a4); if (nTrapInterval[v5] < 5) nTrapInterval[v5] = 5; sTrap[v5].field_C = 0; sTrap[v5].field_A = 0; if (a3 != -1) { sTrap[v5].nWall = -1; sTrap[v5].nWall2 = -1; SECTOR v15 = sector[sprite[a1].sectnum]; int v16 = 0; int v17 = v15.wallptr; while (v16 < v15.wallnum) { if (a3 == wall[v17].hitag) { if (sTrap[v5].nWall != -1) { sTrap[v5].nWall2 = (short) v17; sTrap[v5].field_C = wall[v17].picnum; return 0x1F0000 | v5; } sTrap[v5].nWall = (short) v17; sTrap[v5].field_A = wall[v17].picnum; } ++v16; ++v17; } } return 0x1F0000 | v5; } public static void FuncTrap(int a1, int a2, int RunPtr) { short nTrap = (short) (RunData[RunPtr].RunEvent & 0xFFFF); TrapStruct pTrap = sTrap[nTrap]; int v21 = pTrap.field_2; switch (a1 & 0x7F0000) { case 0x10000: if (channel[a1 & 0x3FFF].field_4 <= 0) pTrap.field_0 = -1; else pTrap.field_0 = 12; return; case 0x20000: int v8 = pTrap.field_0; if (pTrap.field_0 >= 0) { if (--pTrap.field_0 <= 10) { int v10 = pTrap.field_4; if (v8 == 1) { pTrap.field_0 = nTrapInterval[nTrap]; if (v10 == 14) { if (pTrap.nWall > -1) wall[pTrap.nWall].picnum = pTrap.field_A; if (pTrap.nWall2 > -1) wall[pTrap.nWall2].picnum = pTrap.field_C; } } else if (pTrap.field_0 == 5) { short nBullet = (short) (BuildBullet(v21, v10, 0, 0, 0, sprite[v21].ang, 0, 1) & 0xFFFF); if (nBullet == -1) return; if (v10 == 15) { sprite[nBullet].ang = (short) ((sprite[nBullet].ang - 512) & 0x7FF); D3PlayFX(StaticSound[32], v21); } else { sprite[nBullet].clipdist = 50; if (pTrap.nWall > -1) wall[pTrap.nWall].picnum = (short) (pTrap.field_A + 1); if (pTrap.nWall2 > -1) wall[pTrap.nWall2].picnum = (short) (pTrap.field_C + 1); D3PlayFX(StaticSound[36], v21); } } } } return; } } public static ByteBuffer saveDrips() { ByteBuffer bb = ByteBuffer.allocate(nDrips * DripStruct.size + 2); bb.order(ByteOrder.LITTLE_ENDIAN); bb.putShort((short)nDrips); for (short i = 0; i < nDrips; i++) { sDrip[i].save(bb); } return bb; } public static void loadDrips(SafeLoader loader, Resource bb) { if(bb != null) { loader.nDrips = bb.readShort(); for (short i = 0; i < loader.nDrips; i++) { if(loader.sDrip[i] == null) loader.sDrip[i] = new DripStruct(); loader.sDrip[i].load(bb); } } else { nDrips = loader.nDrips; for (short i = 0; i < loader.nDrips; i++) { if(sDrip[i] == null) sDrip[i] = new DripStruct(); sDrip[i].copy(loader.sDrip[i]); } } } public static void BuildDrip(int a1) { if (nDrips >= 50) { game.ThrowError("Too many drips!"); return; } if (sDrip[nDrips] == null) sDrip[nDrips] = new DripStruct(); DripStruct v4 = sDrip[nDrips]; ++nDrips; v4.field_0 = (short) a1; v4.field_2 = (short) (RandomSize(8) + 90); sprite[a1].cstat = (short) 32768; } public static ByteBuffer saveBobs() { ByteBuffer bb = ByteBuffer.allocate(nBobs * BobStruct.size + 2 + 200 * 2); bb.order(ByteOrder.LITTLE_ENDIAN); bb.putShort((short)nBobs); for (short i = 0; i < 200; i++) bb.putShort(sBobID[i]); for (short i = 0; i < nBobs; i++) { sBob[i].save(bb); } return bb; } public static void loadBobs(SafeLoader loader, Resource bb) { if(bb != null) { loader.nBobs = bb.readShort(); for (short i = 0; i < 200; i++) loader.sBobID[i] = bb.readShort(); for (short i = 0; i < loader.nBobs; i++) { if(loader.sBob[i] == null) loader.sBob[i] = new BobStruct(); loader.sBob[i].load(bb); } } else { nBobs = loader.nBobs; System.arraycopy(loader.sBobID, 0, sBobID, 0, nBobs); for (short i = 0; i < loader.nBobs; i++) { if(sBob[i] == null) sBob[i] = new BobStruct(); sBob[i].copy(loader.sBob[i]); } } } public static void DoDrips() { for (int i = 0; i < nDrips; i++) { if (--sDrip[i].field_2 <= 0) { int v3 = SeqOffsets[62]; if ((SectFlag[sprite[sDrip[i].field_0].sectnum] & 0x4000) == 0) v3 = SeqOffsets[62] + 1; MoveSequence(sDrip[i].field_0, v3, RandomSize(2) % SeqSize[v3]); sDrip[i].field_2 = (short) (RandomSize(8) + 90); } } for (int i = 0; i < nBobs; i++) { sBob[i].field_2 += 4; int v10 = sintable[8 * sBob[i].field_2 & 0x7FF] >> 4; if (sBob[i].field_3 != 0) { game.pInt.setceilinterpolate(sBob[i].field_0, sector[sBob[i].field_0]); sector[sBob[i].field_0].ceilingz = sBob[i].field_4 + v10; } else { int v13 = v10 + sBob[i].field_4; int v14 = v13 - sector[sBob[i].field_0].floorz; game.pInt.setfloorinterpolate(sBob[i].field_0, sector[sBob[i].field_0]); sector[sBob[i].field_0].floorz = v13; MoveSectorSprites(sBob[i].field_0, v14); } } } private static int FinaleMoves; private static int FinaleClock; public static void DoFinale() { if (lFinaleStart == 0) return; if (++FinaleMoves >= 90) { DimLights(); if (nDronePitch <= -2400) { if (nFinaleStage < 2) { if (nFinaleStage == 1) { StopLocalSound(); PlayLocalSound(StaticSound[76], 0); FinaleClock = totalclock + 120; ++nFinaleStage; } } else if (nFinaleStage <= 2) { if (totalclock >= FinaleClock) { PlayLocalSound(StaticSound[77], 0); ++nFinaleStage; FinaleClock = totalclock + 360; } } else if (nFinaleStage == 3 && totalclock >= FinaleClock) { FinishLevel(); } } else { nDronePitch -= 128; BendAmbientSound(); nFinaleStage = 1; } } else { if ((FinaleMoves & 2) == 0) { sprite[nFinaleSpr].ang = (short) RandomSize(11); BuildSpark(nFinaleSpr, 1); } if (RandomSize(2) == 0) { PlayFX2(StaticSound[78] | 0x2000, nFinaleSpr); for (int i = 0; i < numplayers; i++) { nQuake[i] = 1280; } } } } private static boolean bLightTrig; private static void DimLights() { bLightTrig = !bLightTrig; if (!bLightTrig) return; for (int i = 0; i < numsectors; i++) { if (sector[i].ceilingshade < 100) sector[i].ceilingshade++; if (sector[i].floorshade < 100) sector[i].floorshade++; for(int s = 0, w = sector[i].wallptr; s < sector[i].wallnum; s++, w++) { if (wall[w].shade < 100) wall[w].shade++; } } } }
35,289
Java
.java
1,196
25.081104
119
0.6167
atsb/NuBuildGDX
18
0
6
GPL-3.0
9/4/2024, 8:32:30 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,289
1,280,749
BlessedBeastSpiritShot.java
L2jOrg_L2jOrg/Script/src/main/org.l2j.scripts/org/l2j/scripts/handlers/itemhandlers/BlessedBeastSpiritShot.java
/* * Copyright © 2019-2021 L2JOrg * * This file is part of the L2JOrg project. * * L2JOrg is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * L2JOrg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.l2j.scripts.handlers.itemhandlers; import org.l2j.gameserver.model.actor.Summon; /** * @author JoeAlisson */ public class BlessedBeastSpiritShot extends BeastSpiritShot { @Override protected boolean isBlessed() { return true; } @Override protected double getBonus(Summon summon) { return super.getBonus(summon) * 2; } }
1,070
Java
.java
33
30.424242
71
0.767667
L2jOrg/L2jOrg
36
30
47
GPL-3.0
9/4/2024, 7:31:11 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,070
4,702,286
BaseController.java
Ywen27_libraryProject/src/main/java/com/yx/controller/BaseController.java
package com.yx.controller; import com.github.pagehelper.PageInfo; import com.yx.po.Notice; import com.yx.service.NoticeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import java.util.List; @Controller public class BaseController { @Autowired private NoticeService noticeService; /** * Page index * @return */ @GetMapping("/index") public String index(){ return "index"; } /** * Page d'accueil * @return */ @GetMapping("/welcome") public String welcome(Model model){ // Fournir les cinq dernières annonces PageInfo<Notice> pageInfo = noticeService.queryAllNotice(null,1,5); if (pageInfo!=null){ List<Notice> noticeList = pageInfo.getList(); model.addAttribute("noticeList",noticeList); } return "welcome"; } @GetMapping("/updatePassword") public String updatePwd(){ return "pwdUpdate/updatePwd"; } }
1,144
Java
.java
40
23.3
76
0.691042
Ywen27/libraryProject
2
0
0
GPL-3.0
9/5/2024, 12:21:59 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,144
3,274,382
RenderDebugGraphView.java
yiotro_Shmatoosto/yio/tro/shmatoosto/menu/menu_renders/RenderDebugGraphView.java
package yio.tro.shmatoosto.menu.menu_renders; import com.badlogic.gdx.graphics.g2d.TextureRegion; import yio.tro.shmatoosto.Fonts; import yio.tro.shmatoosto.menu.elements.DebugGraphView; import yio.tro.shmatoosto.menu.elements.InterfaceElement; import yio.tro.shmatoosto.stuff.GraphicsYio; import yio.tro.shmatoosto.stuff.PointYio; import java.util.ArrayList; public class RenderDebugGraphView extends RenderInterfaceElement{ private TextureRegion background; private DebugGraphView debugGraphView; @Override public void loadTextures() { background = GraphicsYio.loadTextureRegion("pixels/white.png", false); } @Override public void renderFirstLayer(InterfaceElement element) { renderShadow(element.getViewPosition(), element.getFactor().get()); } @Override public void renderSecondLayer(InterfaceElement element) { debugGraphView = (DebugGraphView) element; GraphicsYio.setBatchAlpha(batch, debugGraphView.getFactor().get()); renderBackground(); renderGraph(); renderName(); GraphicsYio.setBatchAlpha(batch, 1); } private void renderName() { if (!debugGraphView.hasName()) return; if (!debugGraphView.isNameActive()) return; GraphicsYio.setFontAlpha(Fonts.gameFont, debugGraphView.getFactor().get()); Fonts.gameFont.draw( batch, debugGraphView.getName(), debugGraphView.getNamePosition().x, debugGraphView.getNamePosition().y ); GraphicsYio.setFontAlpha(Fonts.gameFont, 1); } private void renderGraph() { ArrayList<PointYio> views = debugGraphView.getViews(); for (int i = 0; i < views.size() - 1; i++) { PointYio current = views.get(i); PointYio next = views.get(i + 1); GraphicsYio.drawLine(batch, blackPixel, current, next, 0.01 * GraphicsYio.width); } } private void renderBackground() { GraphicsYio.drawByRectangle(batch, background, debugGraphView.getViewPosition()); GraphicsYio.renderBorder(batch, blackPixel, debugGraphView.getViewPosition()); } @Override public void renderThirdLayer(InterfaceElement element) { } }
2,287
Java
.java
56
33.410714
93
0.700409
yiotro/Shmatoosto
4
0
0
GPL-3.0
9/4/2024, 11:09:22 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,287
460,286
ApportionmentValidator.java
arthurgregorio_web-budget/src/main/java/br/com/webbudget/application/validator/apportionment/ApportionmentValidator.java
/* * Copyright (C) 2019 Arthur Gregorio, AG.Software * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package br.com.webbudget.application.validator.apportionment; import br.com.webbudget.domain.entities.financial.Apportionment; import br.com.webbudget.domain.entities.financial.Movement; import br.com.webbudget.domain.exceptions.BusinessLogicException; /** * Validation interface to provide a contract to all {@link Apportionment} validators * * @author Arthur Gregorio * * @version 1.0.0 * @since 3.0.0, 06/01/2019 */ public interface ApportionmentValidator { /** * Validate a single apportionment * * This validator should be used before insert the {@link Apportionment} in the {@link Movement} * * @param apportionment the {@link Apportionment} to be validated * @param movement the {@link Movement} to extract some values used to validate the {@link Apportionment} * @throws BusinessLogicException if any problem is found */ void validate(Apportionment apportionment, Movement movement); }
1,659
Java
.java
40
38.65
109
0.761139
arthurgregorio/web-budget
201
97
43
GPL-3.0
9/4/2024, 7:07:11 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,659
613,643
XGBoostDatasets.java
jpmml_jpmml-xgboost/pmml-xgboost/src/test/java/org/jpmml/xgboost/testing/XGBoostDatasets.java
/* * Copyright (c) 2022 Villu Ruusmann * * This file is part of JPMML-XGBoost * * JPMML-XGBoost is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-XGBoost is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-XGBoost. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.xgboost.testing; import org.jpmml.converter.testing.Datasets; public interface XGBoostDatasets extends Datasets { String AUDIT_LIMIT = AUDIT + "@31"; String AUDIT_NA_LIMIT = AUDIT_NA + "@31"; String IRIS_LIMIT = IRIS + "@11"; String IRIS_NA_LIMIT = IRIS_NA + "@11"; String LUNG = "Lung"; String LUNG_NA = LUNG + "NA"; }
1,104
Java
.java
28
37.535714
78
0.746741
jpmml/jpmml-xgboost
128
43
2
AGPL-3.0
9/4/2024, 7:08:18 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,104
5,132,978
Player.java
uaEquals42_JAC/src/main/java/jac/engine/Player.java
/* * JAC Copyright (C) 2015 Gregory Jordan * * This file is part of JAC. * * JAC is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jac.engine; import jac.engine.mapstuff.GameMap; import jac.unit.GenericUnit; import java.util.List; /** * * @author Gregory Jordan */ interface Player{ boolean pick_faction(); void imReady(boolean ready); GameMap viewMap(); List<GenericUnit> getListMyUnits(); void turnStart(); void endTurn(); void giveUnitCommand(); }
1,091
Java
.java
35
28.457143
72
0.739752
uaEquals42/JAC
1
0
0
GPL-3.0
9/5/2024, 12:42:05 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,091
4,942,507
PercentValueNode.java
bartvbl_relay/Relay/src/relay/nodes/expressions/PercentValueNode.java
package relay.nodes.expressions; import relay.nodes.ExpressionNode; import relay.nodes.RelayNode; import relay.parser.LocationRange; import relay.parser.symbols.types.ExpressionType; public class PercentValueNode extends ExpressionNode { private double percentValue; private VariableAccessNode accessNode; public PercentValueNode(LocationRange location, double value, VariableAccessNode accessNode) { super(location, ExpressionType.PERCENTAGE_VALUE, new RelayNode[]{accessNode}); this.percentValue = value; this.accessNode = accessNode; } @Override public double evaluate() { return (percentValue / 100d) * accessNode.evaluate(); } public String toString() { return percentValue + "% of " + accessNode.toString(); } }
745
Java
.java
21
33.190476
95
0.811453
bartvbl/relay
1
0
0
GPL-2.0
9/5/2024, 12:36:54 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
745
281,651
PillarAxis.java
PowerNukkitX_PowerNukkitX/src/main/java/cn/nukkit/block/property/enums/PillarAxis.java
package cn.nukkit.block.property.enums; /** * Automatically generated by {@code org.allaymc.codegen.VanillaBlockPropertyTypeGen} <br> * Allay Project <p> * * Placeholder,use {@link cn.nukkit.math.BlockFace.Axis} * @author daoge_cmd */ @Deprecated public enum PillarAxis {}
282
Java
.java
10
26.5
90
0.774908
PowerNukkitX/PowerNukkitX
461
116
6
LGPL-3.0
9/4/2024, 7:06:07 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
282
3,730,659
AMaskEdit.java
yangzhongke_NAHAIDE/src/cn/com/agree/naha/designer/components/amaskedit/AMaskEdit.java
package cn.com.agree.naha.designer.components.amaskedit; import java.util.ArrayList; import java.util.List; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.ui.views.properties.IPropertyDescriptor; import org.eclipse.ui.views.properties.TextPropertyDescriptor; import org.python.pydev.parser.jython.ast.Assign; import org.python.pydev.parser.jython.ast.Num; import org.python.pydev.parser.jython.ast.Str; import org.python.pydev.parser.jython.ast.exprType; import org.python.pydev.parser.jython.ast.stmtType; import cn.com.agree.naha.designer.common.ComponentUtils; import cn.com.agree.naha.designer.components.aedit.AEdit; import cn.com.agree.naha.designer.parser.ParserUtils; import com.cownew.ctk.common.StringUtils; public class AMaskEdit extends AEdit { private static final long serialVersionUID = 1L; public static final String MASK = "MASK"; private static IPropertyDescriptor[] descriptors = new IPropertyDescriptor[] { new TextPropertyDescriptor( MASK, "格式") }; private String mask; public AMaskEdit() { super(); mask = ""; } public String getMask() { return mask; } public void setMask(String mask) { String oldValue = getMask(); this.mask = mask; this.firePropertyChange(MASK, oldValue, mask); } public IPropertyDescriptor[] getPropertyDescriptors() { IPropertyDescriptor[] sd = super.getPropertyDescriptors(); return ComponentUtils.mergePropDesc(sd, descriptors); } protected boolean isTextValid(String text) { //TODO:根据mask来判断是否正确 return true; } public Object getPropertyValue(Object id) { Object v = super.getPropertyValue(id); if (v != null) { return v; } if (id.equals(MASK)) { return getMask(); } return null; } public void setPropertyValue(Object id, Object value) { super.setPropertyValue(id, value); if (id.equals(MASK)) { setMask((String) value); } } public List generateCode(String parentId) { StringBuffer line1 = new StringBuffer(); line1.append(getId()).append("=AMaskEdit("); Rectangle rect = getBounds(); line1.append(rect.x).append(",").append(rect.y).append(",").append( rect.width).append(",").append( StringUtils.doubleQuoted(getMask())).append(")"); StringBuffer line2 = new StringBuffer(); line2.append(getId()).append(".settext(").append( StringUtils.doubleQuoted(getText())).append(")"); StringBuffer line3 = new StringBuffer(); line3.append(parentId).append(".add(").append(getId()).append(")"); List<String> list = new ArrayList<String>(); list.add("global " + getId()); list.add(line1.toString()); list.add(line2.toString()); list.add(line3.toString()); return list; } @Override public void fillAttr(String id, stmtType[] stmts) { super.fillAttr(id, stmts); // 构造函数 exprType[] createArgs = ParserUtils.getArgs((Assign) stmts[1]); Num xStmt = (Num) createArgs[0]; Num yStmt = (Num) createArgs[1]; Num widthStmt = (Num) createArgs[2]; Str maskStr = (Str) createArgs[3]; int x = Integer.parseInt(xStmt.num); int y = Integer.parseInt(yStmt.num); int width = Integer.parseInt(widthStmt.num); String mask = maskStr.s; setMask(mask); Rectangle bounds = new Rectangle(); bounds.x = x; bounds.y = y; bounds.width = width; bounds.height = 1; setBounds(bounds); // settext语句 String text = ParserUtils.getSetterStrValue(stmts, "settext"); setText(text); } }
3,414
Java
.java
114
27.078947
107
0.742708
yangzhongke/NAHAIDE
3
0
0
GPL-3.0
9/4/2024, 11:40:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,397
195,560
IcyDataSource.java
segler-alex_RadioDroid/app/src/main/java/net/programmierecke/radiodroid2/players/exoplayer/IcyDataSource.java
package net.programmierecke.radiodroid2.players.exoplayer; import android.net.Uri; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.exoplayer2.upstream.DataSpec; import com.google.android.exoplayer2.upstream.DefaultHttpDataSource; import com.google.android.exoplayer2.upstream.HttpDataSource; import com.google.android.exoplayer2.upstream.TransferListener; import net.programmierecke.radiodroid2.station.live.ShoutcastInfo; import net.programmierecke.radiodroid2.station.live.StreamLiveInfo; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import static net.programmierecke.radiodroid2.Utils.getMimeType; import static okhttp3.internal.Util.closeQuietly; /** * An {@link HttpDataSource} that uses {@link OkHttpClient}, * retrieves stream's {@link ShoutcastInfo} and {@link StreamLiveInfo} if any, * attempts to reconnect if connection is lost. These distinguishes it from {@link DefaultHttpDataSource}. * <p> * When connection is lost attempts to reconnect will made alongside with calling * {@link IcyDataSourceListener#onDataSourceConnectionLost()}. * After reconnecting time has passed * {@link IcyDataSourceListener#onDataSourceConnectionLostIrrecoverably()} will be called. **/ public class IcyDataSource implements HttpDataSource { public static final long DEFAULT_TIME_UNTIL_STOP_RECONNECTING = 2 * 60 * 1000; // 2 minutes public static final long DEFAULT_DELAY_BETWEEN_RECONNECTIONS = 0; public interface IcyDataSourceListener { /** * Called on first connection and after successful reconnection. */ void onDataSourceConnected(); /** * Called when connection is lost and reconnection attempts will be made. */ void onDataSourceConnectionLost(); /** * Called when data source gives up reconnecting. */ void onDataSourceConnectionLostIrrecoverably(); void onDataSourceShoutcastInfo(@Nullable ShoutcastInfo shoutcastInfo); void onDataSourceStreamLiveInfo(StreamLiveInfo streamLiveInfo); void onDataSourceBytesRead(byte[] buffer, int offset, int length); } private static final String TAG = "IcyDataSource"; private DataSpec dataSpec; private final OkHttpClient httpClient; private final TransferListener transferListener; private final IcyDataSourceListener dataSourceListener; private Request request; private ResponseBody responseBody; private Map<String, List<String>> responseHeaders; int metadataBytesToSkip = 0; int remainingUntilMetadata = Integer.MAX_VALUE; private boolean opened; ShoutcastInfo shoutcastInfo; private StreamLiveInfo streamLiveInfo; public IcyDataSource(@NonNull OkHttpClient httpClient, @NonNull TransferListener listener, @NonNull IcyDataSourceListener dataSourceListener) { this.httpClient = httpClient; this.transferListener = listener; this.dataSourceListener = dataSourceListener; } @Override public long open(DataSpec dataSpec) throws HttpDataSourceException { close(); this.dataSpec = dataSpec; final boolean allowGzip = (dataSpec.flags & DataSpec.FLAG_ALLOW_GZIP) != 0; HttpUrl url = HttpUrl.parse(dataSpec.uri.toString()); Request.Builder builder = new Request.Builder().url(url) .addHeader("Icy-MetaData", "1"); if (!allowGzip) { builder.addHeader("Accept-Encoding", "identity"); } request = builder.build(); return connect(); } private long connect() throws HttpDataSourceException { Response response; try { response = httpClient.newCall(request).execute(); } catch (IOException e) { throw new HttpDataSourceException("Unable to connect to " + dataSpec.uri.toString(), e, dataSpec, HttpDataSourceException.TYPE_OPEN); } final int responseCode = response.code(); if (!response.isSuccessful()) { final Map<String, List<String>> headers = request.headers().toMultimap(); throw new InvalidResponseCodeException(responseCode, headers, dataSpec); } responseBody = response.body(); assert responseBody != null; responseHeaders = response.headers().toMultimap(); final MediaType contentType = responseBody.contentType(); final String type = contentType == null ? getMimeType(dataSpec.uri.toString(), "audio/mpeg") : contentType.toString().toLowerCase(); if (!REJECT_PAYWALL_TYPES.apply(type)) { close(); throw new InvalidContentTypeException(type, dataSpec); } opened = true; dataSourceListener.onDataSourceConnected(); transferListener.onTransferStart(this, dataSpec, true); if (type.equals("application/vnd.apple.mpegurl") || type.equals("application/x-mpegurl")) { return responseBody.contentLength(); } else { // try to get shoutcast information from stream connection shoutcastInfo = ShoutcastInfo.Decode(response); dataSourceListener.onDataSourceShoutcastInfo(shoutcastInfo); metadataBytesToSkip = 0; if (shoutcastInfo != null) { remainingUntilMetadata = shoutcastInfo.metadataOffset; } else { remainingUntilMetadata = Integer.MAX_VALUE; } return responseBody.contentLength(); } } @Override public void close() throws HttpDataSourceException { if (opened) { opened = false; transferListener.onTransferEnd(this, dataSpec, true); } if (responseBody != null) { closeQuietly(responseBody); responseBody = null; } } @Override public int read(byte[] buffer, int offset, int readLength) throws HttpDataSourceException { try { final int bytesTransferred = readInternal(buffer, offset, readLength); transferListener.onBytesTransferred(this, dataSpec, true, bytesTransferred); return bytesTransferred; } catch (HttpDataSourceException readError) { dataSourceListener.onDataSourceConnectionLost(); throw readError; } } void sendToDataSourceListenersWithoutMetadata(byte[] buffer, int offset, int bytesAvailable) { int canSkip = Math.min(metadataBytesToSkip, bytesAvailable); offset += canSkip; bytesAvailable -= canSkip; remainingUntilMetadata -= canSkip; while (bytesAvailable > 0) { if (bytesAvailable > remainingUntilMetadata) { // do we need to handle a metadata frame at all? if (remainingUntilMetadata > 0) { // is there any audio data before the metadata frame? dataSourceListener.onDataSourceBytesRead(buffer, offset, remainingUntilMetadata); offset += remainingUntilMetadata; bytesAvailable -= remainingUntilMetadata; } metadataBytesToSkip = buffer[offset] * 16 + 1; remainingUntilMetadata = shoutcastInfo.metadataOffset + metadataBytesToSkip; } int bytesLeft = Math.min(bytesAvailable, remainingUntilMetadata); if (bytesLeft > metadataBytesToSkip) { // is there audio data left we need to send? dataSourceListener.onDataSourceBytesRead(buffer, offset + metadataBytesToSkip, bytesLeft - metadataBytesToSkip); metadataBytesToSkip = 0; } else { metadataBytesToSkip -= bytesLeft; } offset += bytesLeft; bytesAvailable -= bytesLeft; remainingUntilMetadata -= bytesLeft; } } private int readInternal(byte[] buffer, int offset, int readLength) throws HttpDataSourceException { if (responseBody == null) { throw new HttpDataSourceException(dataSpec, HttpDataSourceException.TYPE_READ); } InputStream stream = responseBody.byteStream(); int bytesRead = 0; try { bytesRead = stream.read(buffer, offset, readLength); } catch (IOException e) { throw new HttpDataSourceException(e, dataSpec, HttpDataSourceException.TYPE_READ); } sendToDataSourceListenersWithoutMetadata(buffer, offset, bytesRead); return bytesRead; } @Override public Uri getUri() { return dataSpec.uri; } @Override public void setRequestProperty(String name, String value) { // Ignored } @Override public void clearRequestProperty(String name) { // Ignored } @Override public void clearAllRequestProperties() { // Ignored } @Override public Map<String, List<String>> getResponseHeaders() { return responseHeaders; } @Override public int getResponseCode() { return 0; } @Override public void addTransferListener(TransferListener transferListener) { } }
9,440
Java
.java
217
34.981567
140
0.684934
segler-alex/RadioDroid
719
151
292
GPL-3.0
9/4/2024, 7:05:26 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
9,440
928,193
ClassFinder.java
Riverside-Software_sonar-openedge/proparse/src/main/java/org/prorefactor/proparse/support/ClassFinder.java
/******************************************************************************** * Copyright (c) 2003-2015 John Green * Copyright (c) 2015-2024 Riverside Software * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the Eclipse * Public License, v. 2.0 are satisfied: GNU Lesser General Public License v3.0 * which is available at https://www.gnu.org/licenses/lgpl-3.0.txt * * SPDX-License-Identifier: EPL-2.0 OR LGPL-3.0 ********************************************************************************/ package org.prorefactor.proparse.support; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ClassFinder { private static final Logger LOGGER = LoggerFactory.getLogger(ClassFinder.class); private IProparseEnvironment session; private Map<String, String> namesMap = new HashMap<>(); public ClassFinder(IProparseEnvironment session) { this.session = session; } /** * Add a USING class name or path glob to the class finder. */ void addPath(String nodeText) { LOGGER.trace("Entering addPath {}", nodeText); String dequoted = dequote(nodeText); if (dequoted.length() == 0) return; if (dequoted.endsWith("*")) { String pkgName = dequoted.substring(0, dequoted.length() - 2); for (String str : session.getAllClassesFromPackage(pkgName)) { addQualifiedName(str); } } else { addQualifiedName(dequoted); } } private void addQualifiedName(String qName) { int dotPos = qName.lastIndexOf('.'); String unqualified = dotPos > 0 ? qName.substring(dotPos + 1) : qName; unqualified = unqualified.toLowerCase(); // First match takes precedence. namesMap.putIfAbsent(unqualified, qName); } /** * Returns a string with quotes and string attributes removed. Can't just use StringFuncs.qstringStrip because a class * name might have embedded quoted text, to quote embedded spaces and such in the file name. The embedded quotation * marks have to be stripped too. */ static String dequote(String s1) { StringBuilder s2 = new StringBuilder(); int len = s1.length(); char[] c1 = s1.toCharArray(); int numQuotes = 0; for (int i = 0; i < len; ++i) { char c = c1[i]; if (c == '"' || c == '\'') { // If we have a colon after a quote, assume we have string // attributes at the end of a quoted class name, and we're done. if (++numQuotes > 1 && i + 1 < len && c1[i + 1] == ':') break; } else { s2.append(c); } } return s2.toString(); } /** * Find a class file for a *qualified* class name. */ String findClassFile(String qualClassName) { String slashName = qualClassName.replace('.', '/'); return session.findFile(slashName + ".cls"); } /** * Lookup a qualified class name on the USING list and/or PROPATH:<ul> * <li>If input name is already qualified, just returns that name dequoted</li> * <li>Checks for explicit USING</li> * <li>Checks for USING globs on PROPATH</li> * <li>Checks for "no package" class file on PROPATH</li> * <li>Returns empty String if all of the above fail</li> * </ul> */ String lookup(String rawRefName) { LOGGER.trace("Entering lookup {}", rawRefName); String dequotedName = dequote(rawRefName); // If already qualified, then return the dequoted name, no check against USING. if (dequotedName.contains(".")) return dequotedName; // Check if USING class name, or if the class file has already been found. String ret = namesMap.get(dequotedName.toLowerCase()); if (ret != null) return ret; // The last chance is for a "no package" name in RefactorSession if (session.getTypeInfo(dequotedName) != null) return dequotedName; // No class source was found, return empty String. return ""; } }
4,193
Java
.java
107
34.775701
120
0.659789
Riverside-Software/sonar-openedge
62
25
67
LGPL-3.0
9/4/2024, 7:09:48 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,193
2,577,783
mustspecify001.java
JPortal-system_system/jdk12-06222165c35f/test/hotspot/jtreg/vmTestbase/nsk/jdi/Argument/mustSpecify/mustspecify001.java
/* * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package nsk.jdi.Argument.mustSpecify; import java.io.PrintStream; import java.io.Serializable; import java.util.Map; import java.util.Set; import java.util.List; import java.util.Iterator; import java.util.NoSuchElementException; import com.sun.jdi.VirtualMachineManager; import com.sun.jdi.Bootstrap; import com.sun.jdi.connect.Connector; import com.sun.jdi.connect.Connector.IntegerArgument; /** * The test for the implementation of an object of the type <BR> * Connector_Argument. <BR> * <BR> * The test checks up that the method <BR> * <code>com.sun.jdi.connect.Connector.Argument.mustSpecify()</code> <BR> * complies with its specification. <BR> * <BR> * In case of Connector has no Argument needed to be specified, <BR> * the test prints warning message. <BR> * The test is always passed and produces <BR> * the return value 95. <BR> */ // public class mustspecify001 { public static void main(String argv[]) { System.exit(run(argv, System.out) + 95); // JCK-compatible exit status } public static int run(String argv[], PrintStream out) { int exitCode = 0; int exitCode0 = 0; int exitCode2 = 2; // String sErr1 = "WARNING\n" + "Method tested: " + "jdi.Connector.IntegerArgument.intValue\n" ; // String sErr2 = "ERROR\n" + "Method tested: " + "jdi.Connector.IntegerArgument.intValue()\n" ; VirtualMachineManager vmm = Bootstrap.virtualMachineManager(); List connectorsList = vmm.allConnectors(); Iterator connectorsListIterator = connectorsList.iterator(); // Connector.Argument argument = null; for ( ; ; ) { try { Connector connector = (Connector) connectorsListIterator.next(); Map defaultArguments = connector.defaultArguments(); Set keyset = defaultArguments.keySet(); int keysetSize = defaultArguments.size(); Iterator keysetIterator = keyset.iterator(); for ( ; ; ) { try { String argName = (String) keysetIterator.next(); try { // argument = (Connector.Argument) defaultArguments.get(argName); break ; } catch ( ClassCastException e) { } } catch ( NoSuchElementException e) { break ; } } if ((argument != null) && argument.mustSpecify()) { break ; } } catch ( NoSuchElementException e) { out.println(sErr1 + // "no Connector with Argument must be specified, found\n"); return exitCode0; } } /* argument.setValue("0"); if (argument.mustSpecify()) { out.println("mustSpecify is the same\n"); } else { out.println("mustSpecify is changed\n"); } if (exitCode != exitCode0) { out.println("TEST FAILED"); } */ return exitCode0; } }
4,468
Java
.java
115
30.086957
79
0.595249
JPortal-system/system
7
2
1
GPL-3.0
9/4/2024, 9:49:36 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
4,468
28,194
QuickAccess.java
Freeyourgadget_Gadgetbridge/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/devices/sony/headphones/prefs/QuickAccess.java
/* Copyright (C) 2022-2024 José Rebelo This file is part of Gadgetbridge. Gadgetbridge is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Gadgetbridge is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ package nodomain.freeyourgadget.gadgetbridge.devices.sony.headphones.prefs; import android.content.SharedPreferences; import java.util.HashMap; import java.util.Locale; import java.util.Map; import nodomain.freeyourgadget.gadgetbridge.activities.devicesettings.DeviceSettingsPreferenceConst; public class QuickAccess { public enum Mode { OFF((byte) 0x00), SPOTIFY((byte) 0x01), ; private final byte code; Mode(final byte code) { this.code = code; } public byte getCode() { return this.code; } public static Mode fromCode(final byte code) { for (Mode value : Mode.values()) { if (value.getCode() == code) { return value; } } return null; } } final Mode doubleTap; final Mode tripleTap; public QuickAccess(final Mode doubleTap, final Mode tripleTap) { this.doubleTap = doubleTap; this.tripleTap = tripleTap; } public Mode getModeDoubleTap() { return doubleTap; } public Mode getModeTripleTap() { return tripleTap; } public Map<String, Object> toPreferences() { return new HashMap<String, Object>() {{ put(DeviceSettingsPreferenceConst.PREF_SONY_QUICK_ACCESS_DOUBLE_TAP, doubleTap.name().toLowerCase(Locale.getDefault())); put(DeviceSettingsPreferenceConst.PREF_SONY_QUICK_ACCESS_TRIPLE_TAP, tripleTap.name().toLowerCase(Locale.getDefault())); }}; } public static QuickAccess fromPreferences(final SharedPreferences prefs) { return new QuickAccess( Mode.valueOf(prefs.getString(DeviceSettingsPreferenceConst.PREF_SONY_QUICK_ACCESS_DOUBLE_TAP, "off").toUpperCase()), Mode.valueOf(prefs.getString(DeviceSettingsPreferenceConst.PREF_SONY_QUICK_ACCESS_TRIPLE_TAP, "off").toUpperCase()) ); } }
2,728
Java
.java
64
34.890625
132
0.684688
Freeyourgadget/Gadgetbridge
4,239
655
461
AGPL-3.0
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,728
250,602
CompositePasswordEncoder.java
entropy-cloud_nop-entropy/nop-auth/nop-auth-core/src/main/java/io/nop/auth/core/password/CompositePasswordEncoder.java
/** * Copyright (c) 2017-2024 Nop Platform. All rights reserved. * Author: canonical_entropy@163.com * Blog: https://www.zhihu.com/people/canonical-entropy * Gitee: https://gitee.com/canonical-entropy/nop-entropy * Github: https://github.com/entropy-cloud/nop-entropy */ package io.nop.auth.core.password; public class CompositePasswordEncoder implements IPasswordEncoder { private IPasswordEncoder firstEncoder; private IPasswordEncoder secondEncoder; private boolean useSecondSalt; public boolean isUseSecondSalt() { return useSecondSalt; } public void setUseSecondSalt(boolean useSecondSalt) { this.useSecondSalt = useSecondSalt; } public IPasswordEncoder getFirstEncoder() { return firstEncoder; } public void setFirstEncoder(IPasswordEncoder firstEncoder) { this.firstEncoder = firstEncoder; } public IPasswordEncoder getSecondEncoder() { return secondEncoder; } public void setSecondEncoder(IPasswordEncoder secondEncoder) { this.secondEncoder = secondEncoder; } @Override public String generateSalt() { if (useSecondSalt) return secondEncoder.generateSalt(); return firstEncoder.generateSalt(); } @Override public String encodePassword(String type, String salt, String password) { String encoded = firstEncoder.encodePassword(type, salt, password); return secondEncoder.encodePassword(type, salt, encoded); } @Override public boolean passwordMatches(String type, String salt, String password, String encodedPassword) { String encoded = firstEncoder.encodePassword(type, salt, password); return secondEncoder.passwordMatches(type, salt, encoded, encodedPassword); } }
1,797
Java
.java
47
32.553191
103
0.735057
entropy-cloud/nop-entropy
526
68
1
AGPL-3.0
9/4/2024, 7:05:59 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,797
318,166
ReflectionUtil.java
NoCheatPlus_NoCheatPlus/NCPCommons/src/main/java/fr/neatmonster/nocheatplus/utilities/ReflectionUtil.java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package fr.neatmonster.nocheatplus.utilities; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * Auxiliary methods for dealing with reflection. * * @author asofold * */ public class ReflectionUtil { /** * Convenience method to check if members exist and fail if not. This checks * getField(...) == null. * * @param prefix * @param specs * @throws RuntimeException * If any member is not present. */ public static void checkMembers(String prefix, String[]... specs){ try { for (String[] spec : specs){ Class<?> clazz = Class.forName(prefix + spec[0]); for (int i = 1; i < spec.length; i++){ if (clazz.getField(spec[i]) == null) { throw new NoSuchFieldException(prefix + spec[0] + " : " + spec[i]); } } } } catch (SecurityException e) { // Let this one pass. //throw new RuntimeException(e); } catch (Throwable t) { throw new RuntimeException(t); } } /** * Convenience method to check if members exist and fail if not. This checks * getField(...) == null. * * @param clazz * The class for which to check members for. * @param type * The expected type of fields. * @param fieldNames * The field names. * @throws RuntimeException * If any member is not present or of wrong type. */ public static void checkMembers(Class<?> clazz, Class<?> type, String... fieldNames){ try { for (String fieldName : fieldNames){ Field field = clazz.getField(fieldName); if (field == null) { throw new NoSuchFieldException(clazz.getName() + "." + fieldName + " does not exist."); } else if (field.getType() != type) { throw new NoSuchFieldException(clazz.getName() + "." + fieldName + " has wrong type: " + field.getType()); } } } catch (SecurityException e) { // Let this one pass. //throw new RuntimeException(e); } catch (Throwable t) { throw new RuntimeException(t); } } /** * Check for the given names if the method returns the desired type of * result (exact check). * * @param methodNames * @param returnType * @throws RuntimeException * If one method is not existing or not matching return type or * has arguments. */ public static void checkMethodReturnTypesNoArgs(Class<?> objClass, String[] methodNames, Class<?> returnType){ // TODO: Add check: boolean isStatic. // TODO: Overloading !? try { for (String methodName : methodNames){ Method m = objClass.getMethod(methodName); if (m.getParameterTypes().length != 0){ throw new RuntimeException("Expect method without arguments for " + objClass.getName() + "." + methodName); } if (m.getReturnType() != returnType){ throw new RuntimeException("Wrong return type for: " + objClass.getName() + "." + methodName); } } } catch (SecurityException e) { // Let this one pass. //throw new RuntimeException(e); } catch (Throwable t) { throw new RuntimeException(t); } } /** * Dirty method to call a declared method with a generic parameter type. * Does try+catch for method invocation and should not throw anything for * the normal case. Purpose for this is generic factory registration, having * methods with type Object alongside methods with more specialized types. * * @param obj * @param methodName * @param arg * Argument or invoke the method with. * @return null in case of errors (can not be distinguished). */ public static Object invokeGenericMethodOneArg(final Object obj, final String methodName, final Object arg){ // TODO: Isn't there a one-line-call for this ?? final Class<?> objClass = obj.getClass(); final Class<?> argClass = arg.getClass(); // Collect methods that might work. Method methodFound = null; boolean denyObject = false; for (final Method method : objClass.getDeclaredMethods()){ if (method.getName().equals(methodName)){ final Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 1 ){ // Prevent using Object as argument if there exists a method with a specialized argument. if (parameterTypes[0] != Object.class && !parameterTypes[0].isAssignableFrom(argClass)){ denyObject = true; } // Override the found method if none found yet and assignment is possible, or if it has a specialized argument of an already found one. if ((methodFound == null && parameterTypes[0].isAssignableFrom(argClass) || methodFound != null && methodFound.getParameterTypes()[0].isAssignableFrom(parameterTypes[0]))){ methodFound = method; } } } } if (denyObject && methodFound.getParameterTypes()[0] == Object.class){ // TODO: Throw something !? return null; } else if (methodFound != null && methodFound.getParameterTypes()[0].isAssignableFrom(argClass)){ try{ final Object res = methodFound.invoke(obj, arg); return res; } catch (Throwable t){ // TODO: Throw something !? return null; } } else{ // TODO: Throw something !? return null; } } /** * Invoke a method without arguments, get the method matching the return * types best, i.e. first type is preferred. At present a result is * returned, even if the return type does not match at all. * * @param obj * @param methodName * @param returnTypePreference * Most preferred return type first, might return null, might * return a method with a completely different return type, * comparison with ==, no isAssignableForm. TODO: really ? * @return */ public static Object invokeMethodNoArgs(final Object obj, final String methodName, final Class<?> ... returnTypePreference){ // TODO: Isn't there a one-line-call for this ?? final Class<?> objClass = obj.getClass(); // Try to get it directly first. Method methodFound = getMethodNoArgs(objClass, methodName, returnTypePreference); if (methodFound == null){ // Fall-back to seek it. methodFound = seekMethodNoArgs(objClass, methodName, returnTypePreference); } // Invoke if found. if (methodFound != null){ try{ final Object res = methodFound.invoke(obj); return res; } catch (Throwable t){ // TODO: Throw something !? return null; } } else{ // TODO: Throw something !? return null; } } /** * More fail-safe method invocation. * * @param method * @param object * @return null in case of failures (!). */ public static Object invokeMethodNoArgs(Method method, Object object) { try { return method.invoke(object); } catch (IllegalAccessException e) {} catch (IllegalArgumentException e) {} catch (InvocationTargetException e) {} return null; } /** * Fail-safe call. * * @param method * @param object * @param arguments * @return null in case of errors. */ public static Object invokeMethod(Method method, Object object, Object... arguments) { try { return method.invoke(object, arguments); } catch (IllegalAccessException e) {} catch (IllegalArgumentException e) {} catch (InvocationTargetException e) {} return null; } /** * Direct getMethod attempt. * * @param objClass * @param methodName * @param returnTypePreference * @return */ public static Method getMethodNoArgs(final Class<?> objClass, final String methodName, final Class<?>... returnTypePreference) { try { final Method methodFound = objClass.getMethod(methodName); if (methodFound != null) { if (returnTypePreference == null || returnTypePreference.length == 0) { return methodFound; } final Class<?> returnType = methodFound.getReturnType(); for (int i = 0; i < returnTypePreference.length; i++){ if (returnType == returnTypePreference[i]){ return methodFound; } } } } catch (SecurityException e) { } catch (NoSuchMethodException e) { } return null; } /** * Iterate over all methods, attempt to return best matching return type * (earliest in array). * * @param objClass * @param methodName * @param returnTypePreference * @return */ public static Method seekMethodNoArgs(final Class<?> objClass, final String methodName, final Class<?>[] returnTypePreference) { return seekMethodNoArgs(objClass, methodName, false, returnTypePreference); } /** * Iterate over all methods, attempt to return best matching return type * (earliest in array). * * @param objClass * @param methodName * @param returnTypePreference * @return */ public static Method seekMethodIgnoreArgs(final Class<?> objClass, final String methodName, final Class<?>... returnTypePreference) { return seekMethodNoArgs(objClass, methodName, true, returnTypePreference); } private static Method seekMethodNoArgs(final Class<?> objClass, final String methodName, boolean ignoreArgs, final Class<?>... returnTypePreference) { // Collect methods that might work. Method methodFound = null; int returnTypeIndex = returnTypePreference.length; // This can be 0 for no preferences given. // TODO: Does there exist an optimized method for getting all by name? for (final Method method : objClass.getMethods()){ if (method.getName().equals(methodName)){ final Class<?>[] parameterTypes = method.getParameterTypes(); if (ignoreArgs || parameterTypes.length == 0){ // Override the found method if none found yet or if the return type matches the preferred policy. final Class<?> returnType = method.getReturnType(); if (methodFound == null){ methodFound = method; for (int i = 0; i < returnTypeIndex; i++){ if (returnTypePreference[i] == returnType){ returnTypeIndex = i; break; } } } else{ // Check if the return type is preferred over previously found ones. for (int i = 0; i < returnTypeIndex; i++){ if (returnTypePreference[i] == returnType){ methodFound = method; returnTypeIndex = i; break; } } } if (returnTypeIndex == 0){ // "Quick" return. break; } } } } return methodFound; } /** * Get the field by name (and type). Failsafe. * * @param clazz * @param fieldName * @param type * Set to null to get any type of field. * @return Field or null. */ public static Field getField(Class<?> clazz, String fieldName, Class<?> type) { try { Field field = clazz.getField(fieldName); if (type == null || field.getType() == type) { return field; } } catch (NoSuchFieldException e) {} catch (SecurityException e) {} return null; } /** * Set the field fail-safe. * * @param field * @param object * @param value * @return */ public static boolean set(Field field, Object object, Object value) { try { field.set(object, value); return true; } catch (IllegalArgumentException e) {} catch (IllegalAccessException e) {} return false; } public static boolean getBoolean(Field field, Object object, boolean defaultValue) { try { return field.getBoolean(object); } catch (IllegalArgumentException e) {} catch (IllegalAccessException e) {} return defaultValue; } public static int getInt(Field field, Object object, int defaultValue) { try { return field.getInt(object); } catch (IllegalArgumentException e) {} catch (IllegalAccessException e) {} return defaultValue; } public static float getFloat(Field field, Object object, float defaultValue) { try { return field.getFloat(object); } catch (IllegalArgumentException e) {} catch (IllegalAccessException e) {} return defaultValue; } public static double getDouble(Field field, Object object, double defaultValue) { try { return field.getDouble(object); } catch (IllegalArgumentException e) {} catch (IllegalAccessException e) {} return defaultValue; } public static Object get(Field field, Object object, Object defaultValue) { try { return field.get(object); } catch (IllegalArgumentException e) {} catch (IllegalAccessException e) {} return defaultValue; } /** * Fail-safe getMethod. * * @param clazz * @param methodName * @param arguments * @return null in case of errors. */ public static Method getMethod(Class<?> clazz, String methodName, Class<?>... arguments) { try { return clazz.getMethod(methodName, arguments); } catch (NoSuchMethodException e) {} catch (SecurityException e) {} return null; } /** * Get a method matching one of the declared argument specifications. * * @param clazz * @param methodName * @param argumentLists * @return The first matching method (given order). */ public static Method getMethod(Class<?> clazz, String methodName, Class<?>[]... argumentLists) { Method method = null; for (Class<?>[] arguments : argumentLists) { method = getMethod(clazz, methodName, arguments); if (method != null) { return method; } } return null; } /** * Fail-safe. * * @param clazz * @param parameterTypes * @return null on errors. */ public static Constructor<?> getConstructor(Class<?> clazz, Class<?>... parameterTypes) { try { return clazz.getConstructor(parameterTypes); } catch (NoSuchMethodException e) {} catch (SecurityException e) {} return null; } /** * Fail-safe. * * @param constructor * @param arguments * @return null on errors. */ public static Object newInstance(Constructor<?> constructor, Object... arguments) { try { return constructor.newInstance(arguments); } catch (InstantiationException e) {} catch (IllegalAccessException e) {} catch (IllegalArgumentException e) {} catch (InvocationTargetException e) {} return null; } /** * Fail-safe class getting. * @param fullName * @return */ public static Class<?> getClass(String fullName) { try { return Class.forName(fullName); } catch (ClassNotFoundException e) { // Ignore. } return null; } /** * Convenience for debugging: Print fields and methods with types separated * by line breaks. Probably not safe for production use. * * @param clazz * @return */ public static String getClassDescription(final Class<?> clazz) { // TODO: Option to sort by names ? final StringBuilder builder = new StringBuilder(512); builder.append("Class: "); builder.append(clazz); // TODO: superclass, interfaces, generics for (final Field field : clazz.getFields()) { builder.append("\n "); builder.append(getSimpleMemberModifierDescription(field)); builder.append(field.getType().getName()); builder.append(' '); builder.append(field.getName()); } for (final Method method : clazz.getMethods()) { builder.append("\n "); builder.append(getSimpleMemberModifierDescription(method)); builder.append(method.getReturnType().getName()); builder.append(' '); builder.append(method.getName()); builder.append("("); for (Class<?> type : method.getParameterTypes()) { builder.append(type.getName()); builder.append(", "); } builder.append(")"); } return builder.toString(); } private static String getSimpleMemberModifierDescription(final Member member) { final boolean accessible = member instanceof AccessibleObject && ((AccessibleObject) member).isAccessible(); final int mod = member.getModifiers(); final String out = Modifier.isPublic(mod) ? "(public" : (accessible ? "(accessible" : "( -"); return out + (Modifier.isStatic(mod) ? " static) " : ") "); } }
20,338
Java
.java
529
27.644612
193
0.5582
NoCheatPlus/NoCheatPlus
384
278
7
GPL-3.0
9/4/2024, 7:06:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
20,338
3,954,856
ObjectFactory.java
StratusLab_claudia/clotho/src/main/java/org/dmtf/schemas/wbem/wscim/_1/cim_schema/_2/cim_softwarefeature/ObjectFactory.java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-833 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2011.12.12 at 03:51:35 PM CET // package org.dmtf.schemas.wbem.wscim._1.cim_schema._2.cim_softwarefeature; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; import org.dmtf.schemas.wbem.wscim._1.common.CimDateTime; import org.dmtf.schemas.wbem.wscim._1.common.CimString; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the org.dmtf.schemas.wbem.wscim._1.cim_schema._2.cim_softwarefeature package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _OperatingStatus_QNAME = new QName("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", "OperatingStatus"); private final static QName _CIMSoftwareFeature_QNAME = new QName("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", "CIM_SoftwareFeature"); private final static QName _Status_QNAME = new QName("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", "Status"); private final static QName _Description_QNAME = new QName("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", "Description"); private final static QName _ElementName_QNAME = new QName("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", "ElementName"); private final static QName _InstanceID_QNAME = new QName("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", "InstanceID"); private final static QName _CommunicationStatus_QNAME = new QName("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", "CommunicationStatus"); private final static QName _DetailedStatus_QNAME = new QName("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", "DetailedStatus"); private final static QName _StatusDescriptions_QNAME = new QName("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", "StatusDescriptions"); private final static QName _PrimaryStatus_QNAME = new QName("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", "PrimaryStatus"); private final static QName _Caption_QNAME = new QName("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", "Caption"); private final static QName _HealthState_QNAME = new QName("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", "HealthState"); private final static QName _InstallDate_QNAME = new QName("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", "InstallDate"); private final static QName _OperationalStatus_QNAME = new QName("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", "OperationalStatus"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.dmtf.schemas.wbem.wscim._1.cim_schema._2.cim_softwarefeature * */ public ObjectFactory() { } /** * Create an instance of {@link CommunicationStatus } * */ public CommunicationStatus createCommunicationStatus() { return new CommunicationStatus(); } /** * Create an instance of {@link HealthState } * */ public HealthState createHealthState() { return new HealthState(); } /** * Create an instance of {@link PrimaryStatus } * */ public PrimaryStatus createPrimaryStatus() { return new PrimaryStatus(); } /** * Create an instance of {@link IdentifyingNumber } * */ public IdentifyingNumber createIdentifyingNumber() { return new IdentifyingNumber(); } /** * Create an instance of {@link OperationalStatus } * */ public OperationalStatus createOperationalStatus() { return new OperationalStatus(); } /** * Create an instance of {@link Version } * */ public Version createVersion() { return new Version(); } /** * Create an instance of {@link Name } * */ public Name createName() { return new Name(); } /** * Create an instance of {@link Caption } * */ public Caption createCaption() { return new Caption(); } /** * Create an instance of {@link ProductName } * */ public ProductName createProductName() { return new ProductName(); } /** * Create an instance of {@link CIMSoftwareFeatureType } * */ public CIMSoftwareFeatureType createCIMSoftwareFeatureType() { return new CIMSoftwareFeatureType(); } /** * Create an instance of {@link OperatingStatus } * */ public OperatingStatus createOperatingStatus() { return new OperatingStatus(); } /** * Create an instance of {@link Vendor } * */ public Vendor createVendor() { return new Vendor(); } /** * Create an instance of {@link Status } * */ public Status createStatus() { return new Status(); } /** * Create an instance of {@link DetailedStatus } * */ public DetailedStatus createDetailedStatus() { return new DetailedStatus(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OperatingStatus }{@code >}} * */ @XmlElementDecl(namespace = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", name = "OperatingStatus") public JAXBElement<OperatingStatus> createOperatingStatus(OperatingStatus value) { return new JAXBElement<OperatingStatus>(_OperatingStatus_QNAME, OperatingStatus.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CIMSoftwareFeatureType }{@code >}} * */ @XmlElementDecl(namespace = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", name = "CIM_SoftwareFeature") public JAXBElement<CIMSoftwareFeatureType> createCIMSoftwareFeature(CIMSoftwareFeatureType value) { return new JAXBElement<CIMSoftwareFeatureType>(_CIMSoftwareFeature_QNAME, CIMSoftwareFeatureType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Status }{@code >}} * */ @XmlElementDecl(namespace = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", name = "Status") public JAXBElement<Status> createStatus(Status value) { return new JAXBElement<Status>(_Status_QNAME, Status.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CimString }{@code >}} * */ @XmlElementDecl(namespace = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", name = "Description") public JAXBElement<CimString> createDescription(CimString value) { return new JAXBElement<CimString>(_Description_QNAME, CimString.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CimString }{@code >}} * */ @XmlElementDecl(namespace = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", name = "ElementName") public JAXBElement<CimString> createElementName(CimString value) { return new JAXBElement<CimString>(_ElementName_QNAME, CimString.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CimString }{@code >}} * */ @XmlElementDecl(namespace = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", name = "InstanceID") public JAXBElement<CimString> createInstanceID(CimString value) { return new JAXBElement<CimString>(_InstanceID_QNAME, CimString.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CommunicationStatus }{@code >}} * */ @XmlElementDecl(namespace = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", name = "CommunicationStatus") public JAXBElement<CommunicationStatus> createCommunicationStatus(CommunicationStatus value) { return new JAXBElement<CommunicationStatus>(_CommunicationStatus_QNAME, CommunicationStatus.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link DetailedStatus }{@code >}} * */ @XmlElementDecl(namespace = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", name = "DetailedStatus") public JAXBElement<DetailedStatus> createDetailedStatus(DetailedStatus value) { return new JAXBElement<DetailedStatus>(_DetailedStatus_QNAME, DetailedStatus.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CimString }{@code >}} * */ @XmlElementDecl(namespace = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", name = "StatusDescriptions") public JAXBElement<CimString> createStatusDescriptions(CimString value) { return new JAXBElement<CimString>(_StatusDescriptions_QNAME, CimString.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link PrimaryStatus }{@code >}} * */ @XmlElementDecl(namespace = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", name = "PrimaryStatus") public JAXBElement<PrimaryStatus> createPrimaryStatus(PrimaryStatus value) { return new JAXBElement<PrimaryStatus>(_PrimaryStatus_QNAME, PrimaryStatus.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Caption }{@code >}} * */ @XmlElementDecl(namespace = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", name = "Caption") public JAXBElement<Caption> createCaption(Caption value) { return new JAXBElement<Caption>(_Caption_QNAME, Caption.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link HealthState }{@code >}} * */ @XmlElementDecl(namespace = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", name = "HealthState") public JAXBElement<HealthState> createHealthState(HealthState value) { return new JAXBElement<HealthState>(_HealthState_QNAME, HealthState.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CimDateTime }{@code >}} * */ @XmlElementDecl(namespace = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", name = "InstallDate") public JAXBElement<CimDateTime> createInstallDate(CimDateTime value) { return new JAXBElement<CimDateTime>(_InstallDate_QNAME, CimDateTime.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link OperationalStatus }{@code >}} * */ @XmlElementDecl(namespace = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_SoftwareFeature", name = "OperationalStatus") public JAXBElement<OperationalStatus> createOperationalStatus(OperationalStatus value) { return new JAXBElement<OperationalStatus>(_OperationalStatus_QNAME, OperationalStatus.class, null, value); } }
12,101
Java
.java
260
40.880769
178
0.699111
StratusLab/claudia
2
2
0
AGPL-3.0
9/4/2024, 11:56:50 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
12,101
4,372,497
SlackAttachmentField.java
rossonet_EdgeAgentAr4k/ar4k-core/src/main/java/org/ar4k/agent/mattermost/model/SlackAttachmentField.java
// Generated by delombok at Sun Apr 18 22:20:18 CEST 2021 /* * Copyright (c) 2017-present, Takayuki Maruyama * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.ar4k.agent.mattermost.model; import com.fasterxml.jackson.annotation.JsonProperty; public class SlackAttachmentField { @JsonProperty("title") private String title; @JsonProperty("value") private Object value; @JsonProperty("short") private boolean shortField; @java.lang.SuppressWarnings("all") public SlackAttachmentField() { } @java.lang.SuppressWarnings("all") public String getTitle() { return this.title; } @java.lang.SuppressWarnings("all") public Object getValue() { return this.value; } @java.lang.SuppressWarnings("all") public boolean isShortField() { return this.shortField; } @JsonProperty("title") @java.lang.SuppressWarnings("all") public void setTitle(final String title) { this.title = title; } @JsonProperty("value") @java.lang.SuppressWarnings("all") public void setValue(final Object value) { this.value = value; } @JsonProperty("short") @java.lang.SuppressWarnings("all") public void setShortField(final boolean shortField) { this.shortField = shortField; } @java.lang.Override @java.lang.SuppressWarnings("all") public boolean equals(final java.lang.Object o) { if (o == this) return true; if (!(o instanceof SlackAttachmentField)) return false; final SlackAttachmentField other = (SlackAttachmentField) o; if (!other.canEqual((java.lang.Object) this)) return false; if (this.isShortField() != other.isShortField()) return false; final java.lang.Object this$title = this.getTitle(); final java.lang.Object other$title = other.getTitle(); if (this$title == null ? other$title != null : !this$title.equals(other$title)) return false; final java.lang.Object this$value = this.getValue(); final java.lang.Object other$value = other.getValue(); if (this$value == null ? other$value != null : !this$value.equals(other$value)) return false; return true; } @java.lang.SuppressWarnings("all") protected boolean canEqual(final java.lang.Object other) { return other instanceof SlackAttachmentField; } @java.lang.Override @java.lang.SuppressWarnings("all") public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + (this.isShortField() ? 79 : 97); final java.lang.Object $title = this.getTitle(); result = result * PRIME + ($title == null ? 43 : $title.hashCode()); final java.lang.Object $value = this.getValue(); result = result * PRIME + ($value == null ? 43 : $value.hashCode()); return result; } @java.lang.Override @java.lang.SuppressWarnings("all") public java.lang.String toString() { return "SlackAttachmentField(title=" + this.getTitle() + ", value=" + this.getValue() + ", shortField=" + this.isShortField() + ")"; } }
3,382
Java
.java
98
31.979592
105
0.738001
rossonet/EdgeAgentAr4k
2
5
82
AGPL-3.0
9/5/2024, 12:10:54 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,382
2,339,232
OpeningInitializer.java
ucarion_godot/src/opening/OpeningInitializer.java
package opening; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class OpeningInitializer { private static final String OPENING_DB = "IB1219.pgn"; private static final String OUTPUT = "F:\\workspace\\Godot\\opening.txt"; public static void init() { int count = 0; try { BufferedReader br = new BufferedReader(new InputStreamReader(new DataInputStream( new FileInputStream(OUTPUT)))); if (br.readLine() != null) { br.close(); throw new Exception(); } br.close(); } catch (Exception e) { System.out.println("Output is either not empty or nonexistent!"); System.exit(0); } try { BufferedReader br = new BufferedReader(new InputStreamReader(new DataInputStream( new FileInputStream(OPENING_DB)))); String line; ArrayList<String> games = new ArrayList<String>(); String game = ""; while ( (line = br.readLine()) != null) { count++; System.out.println(count); if (line.startsWith("[") || line.startsWith(" ")) { if ( !game.isEmpty()) games.add(game); game = ""; } else game += " " + line.trim(); if (count % 100000 == 0) { StringBuilder sb = new StringBuilder(); for (String s : games) { s = s.replaceAll("\\{.+?\\} ", ""); s = s.replaceAll("\\d+\\.", ""); s = s.replaceAll("\\s\\s+", " "); sb.append(s.trim() + "\n"); } writeFile(OUTPUT, sb.toString()); games.clear(); } } br.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Done"); } private static void writeFile(String path, String content) { try { FileWriter fw = new FileWriter(path, true); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { init(); } }
2,086
Java
.java
76
23.328947
74
0.648092
ucarion/godot
8
7
0
GPL-3.0
9/4/2024, 9:08:14 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
2,086
1,023,683
RuntimeConstantInfo.java
waleedyaseen_RuneScript/runescript-commons/src/main/java/me/waliedyassen/runescript/compiler/symbol/impl/RuntimeConstantInfo.java
/* * Copyright (c) 2020 Walied K. Yassen, All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package me.waliedyassen.runescript.compiler.symbol.impl; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; import me.waliedyassen.runescript.compiler.symbol.Symbol; import me.waliedyassen.runescript.type.primitive.PrimitiveType; /** * The symbol information for a runtime constant value, which is a constant that is replaced at runtime with another value. * * @author Walied K. Yassen */ @RequiredArgsConstructor @EqualsAndHashCode(callSuper = true) @Getter public final class RuntimeConstantInfo extends Symbol { /** * The name of the constant. */ private final String name; private final int id; /** * The type of the constant. */ private final PrimitiveType type; /** * The value of the constant. */ private final Object value; }
1,118
Java
.java
36
28
123
0.746283
waleedyaseen/RuneScript
49
11
1
MPL-2.0
9/4/2024, 7:11:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,118
3,440,059
JpaManager.java
levants_lightmare/lightmare-ejb/src/main/java/org/lightmare/jpa/JpaManager.java
/* * Lightmare, Lightweight embedded EJB container (works for stateless session beans) with JPA / Hibernate support * * Copyright (c) 2013, Levan Tsinadze, or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.lightmare.jpa; import java.io.IOException; import java.lang.reflect.Field; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.spi.PersistenceProvider; import org.apache.log4j.Logger; import org.hibernate.jpa.HibernatePersistenceProvider; import org.lightmare.cache.ConnectionContainer; import org.lightmare.cache.ConnectionSemaphore; import org.lightmare.config.Configuration; import org.lightmare.jndi.JndiManager; import org.lightmare.jpa.hibernate.jpa.HibernatePersistenceProviderExt; import org.lightmare.jpa.jta.HibernateConfig; import org.lightmare.jpa.spring.SpringORM; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; import org.lightmare.utils.collections.CollectionUtils; import org.lightmare.utils.namimg.NamingUtils; /** * Creates and caches {@link EntityManagerFactory} for each EJB bean * {@link Class}'s appropriate {@link Field} (annotated by @PersistenceContext) * value * * @author Levan Tsinadze * @since 0.0.79-SNAPSHOT */ public class JpaManager { // Entity classes private List<String> classes; // Path for configuration XML file private String path; // URL for configuration XML file private URL url; // Additional properties private Map<Object, Object> properties; // Cache JTA data source with RESOURCE_LOCAL type private boolean swapDataSource; // Scan archives in classpath to find entities private boolean scanArchives; // Initialize level class loader private ClassLoader loader; // Check if JPA is configured by Spring data private boolean springPersistence; // Data source name for Spring data configuration private String dataSourceName; // Error message for connection binding to JNDI names private static final String COULD_NOT_BIND_JNDI_ERROR = "could not bind connection"; private static final String NOT_IN_PROG_ERROR = "Connection %s was not in progress"; private static final Logger LOG = Logger.getLogger(JpaManager.class); /** * Private constructor to avoid initialization beside * {@link JpaManager.Builder} class */ private JpaManager() { } /** * Initializes {@link Map} of additional properties * * @return {@link Map} additional properties */ private Map<Object, Object> getProperties() { if (properties == null) { properties = new HashMap<Object, Object>(); } return properties; } /** * Adds JPA JNDI properties to additional configuration */ private void addJndiProperties() { getProperties().putAll(JndiManager.JNDIConfigs.INIT.hinbernateConfig); } /** * Gets appropriated prefix for passed key * * @param key * @return {@link Object} key with prefix */ private Object getKeyWithPerfix(Object key) { Object validKey; if (key instanceof String) { String textKey = ObjectUtils.cast(key, String.class); validKey = HibernatePrefixes.validKey(textKey); } else { validKey = key; } return validKey; } /** * Validates modifies and adds parameters to global JPA configuration * * @param entry * @param config */ private void configure(Map.Entry<Object, Object> entry, Map<Object, Object> config) { Object key = entry.getKey(); Object value = entry.getValue(); Object validKey = getKeyWithPerfix(key); config.put(validKey, value); } /** * Adds appropriated prefixes to JPA configuration properties * * @param properties */ private Map<Object, Object> configure(Map<Object, Object> properties) { Map<Object, Object> config; if (properties == null || properties.isEmpty()) { config = properties; } else { config = new HashMap<Object, Object>(); Set<Map.Entry<Object, Object>> entries = properties.entrySet(); for (Map.Entry<Object, Object> entry : entries) { configure(entry, config); } } return config; } /** * Checks if entity persistence.xml {@link URL} is provided * * @return boolean */ private boolean checkForURL() { return ObjectUtils.notNull(url) && StringUtils.valid(url.toString()); } /** * Adds default transaction properties for JTA data sources */ private void addTransactionManager() { HibernateConfig[] hibernateConfigs = HibernateConfig.values(); Map<Object, Object> configMap = getProperties(); for (HibernateConfig hibernateConfig : hibernateConfigs) { CollectionUtils.putIfAbscent(configMap, hibernateConfig.key, hibernateConfig.value); } } /** * Initializes {@link SpringORM} with appropriate configuration for Spring * data JPA configuration * * @param provider * @param unitName * @return {@link SpringORM} * @throws IOException */ private SpringORM getSpringORM(PersistenceProvider provider, String unitName) throws IOException { return new SpringORM.Builder(dataSourceName, provider, unitName).properties(properties).classLoader(loader) .swapDataSource(swapDataSource).build(); } /** * Builds {@link EntityManagerFactory} from Spring ORM module * * @param provider * @param unitName * @return {@link EntityManagerFactory} * @throws IOException */ private EntityManagerFactory getFromSpring(PersistenceProvider provider, String unitName) throws IOException { EntityManagerFactory emf; SpringORM springORM = getSpringORM(provider, unitName); emf = springORM.getEmf(); return emf; } /** * Gets {@link List} persistence XML configuration {@link URL} addresses * * @param pathCheck * @param configLoader * @return {@link List} of {@link URL} addresses * @throws IOException */ private List<URL> readFromPath(boolean pathCheck, XMLInitializer configLoader) throws IOException { List<URL> xmls; if (pathCheck) { xmls = configLoader.readFile(path); } else { xmls = configLoader.readURL(url); } return xmls; } /** * Initializes persistence.xml file path * * @param builder * @throws IOException */ private void initPersisteceXmlPath(HibernatePersistenceProviderExt.Builder builder) throws IOException { boolean pathCheck = StringUtils.valid(path); boolean urlCheck = checkForURL(); if (pathCheck || urlCheck) { List<URL> xmls; XMLInitializer configLoader = new XMLInitializer(); xmls = readFromPath(pathCheck, configLoader); builder.setXmls(xmls); String shortPath = configLoader.getShortPath(); builder.setShortPath(shortPath); } } /** * Initializes {@link ClassLoader} instance * * @return {@link ClassLoader} */ private ClassLoader getLoader() { if (loader == null) { loader = LibraryLoader.getContextClassLoader(); } return loader; } /** * Sets entity types * * @param builder * @param overriden * @throws IOException */ private void loadEntities(HibernatePersistenceProviderExt.Builder builder, ClassLoader loader) throws IOException { if (CollectionUtils.valid(classes)) { builder.setClasses(classes); // Loads entity classes to current ClassLoader instance LibraryLoader.loadClasses(classes, loader); } } /** * Configures and adds parameters to * {@link HibernatePersistenceProviderExt.Builder} instance * * @see #buildEntityManagerFactory(String) * @see HibernatePersistenceProviderExt * * @param builder * @throws IOException */ private void configureProvider(HibernatePersistenceProviderExt.Builder builder) throws IOException { ClassLoader overriden = getLoader(); loadEntities(builder, overriden); // configureProvider initPersisteceXmlPath(builder); // Sets additional parameters builder.setSwapDataSource(swapDataSource); builder.setScanArchives(scanArchives); builder.setOverridenClassLoader(overriden); } /** * Checks configuration and sets appropriated transaction manager */ private void configureTransactionManager() { if (Boolean.FALSE.equals(swapDataSource)) { addTransactionManager(); } } /** * Creates {@link EntityManagerFactory} by * <a href="http://hibernate.org">"Hibernate"</a> or by extended builder * {@link Ejb3ConfigurationImpl} if entity classes or persistence.xml file * path are provided * * @see Ejb3ConfigurationImpl#configure(String, Map) and * Ejb3ConfigurationImpl#createEntityManagerFactory() * * @param unitName * @return {@link EntityManagerFactory} */ private EntityManagerFactory buildEntityManagerFactory(String unitName) throws IOException { EntityManagerFactory emf; HibernatePersistenceProvider provider; HibernatePersistenceProviderExt.Builder builder = new HibernatePersistenceProviderExt.Builder(); configureProvider(builder); provider = builder.build(); configureTransactionManager(); // Adds JNDI properties addJndiProperties(); if (springPersistence) { emf = getFromSpring(provider, unitName); } else { emf = provider.createEntityManagerFactory(unitName, properties); } return emf; } /** * Checks if entity classes or persistence.xml file path are provided to * create {@link EntityManagerFactory} * * @see #buildEntityManagerFactory(String, String, Map, List) * * @param unitName * @return {@link EntityManagerFactory} * @throws IOException */ private EntityManagerFactory createEntityManagerFactory(String unitName) throws IOException { EntityManagerFactory emf = buildEntityManagerFactory(unitName); return emf; } /** * Re-binds JNDI name for JPA unit * * @param semaphore * @param fullJndiName * @throws IOException */ private void rebindJNDIName(ConnectionSemaphore semaphore, String fullJndiName) throws IOException { if (JndiManager.lookup(fullJndiName) == null) { JndiManager.rebind(fullJndiName, semaphore.getEmf()); } } /** * Binds {@link EntityManagerFactory} from passed * {@link ConnectionSemaphore} to appropriate JNDI name * * @param jndiName * @param semaphore * @throws IOException */ private void bindJndiName(String jndiName, ConnectionSemaphore semaphore) throws IOException { try { String fullJndiName = NamingUtils.createJpaJndiName(jndiName); rebindJNDIName(semaphore, fullJndiName); } catch (IOException ex) { LOG.error(ex.getMessage(), ex); String errorMessage = StringUtils.concat(COULD_NOT_BIND_JNDI_ERROR, semaphore.getUnitName()); throw new IOException(errorMessage, ex); } } /** * Checks if JDNI is bound and if not bind passed connection for this name * * @param semaphore * @param bound * @throws IOException */ private void checkAndBindJNDIName(ConnectionSemaphore semaphore, boolean bound) throws IOException { if (Boolean.FALSE.equals(bound)) { String jndiName = semaphore.getJndiName(); if (StringUtils.valid(jndiName)) { bindJndiName(jndiName, semaphore); } } } /** * Binds {@link EntityManagerFactory} to {@link javax.naming.InitialContext} * * @param semaphore * @throws IOException */ private void bindJndiName(ConnectionSemaphore semaphore) throws IOException { boolean bound = semaphore.isBound(); checkAndBindJNDIName(semaphore, bound); semaphore.setBound(Boolean.TRUE); } /** * Builds connection, wraps it in {@link ConnectionSemaphore} locks and * caches appropriate instance * * @param unitName * @throws IOException */ public void create(String unitName) throws IOException { ConnectionSemaphore semaphore = ConnectionContainer.getSemaphore(unitName); if (semaphore.isInProgress()) { EntityManagerFactory emf = createEntityManagerFactory(unitName); semaphore.setEmf(emf); semaphore.setInProgress(Boolean.FALSE); bindJndiName(semaphore); } else if (semaphore.getEmf() == null) { String errorMessage = String.format(NOT_IN_PROG_ERROR, unitName); throw new IOException(errorMessage); } else { bindJndiName(semaphore); } } /** * Closes passed {@link EntityManagerFactory} * * @param emf */ public static void closeEntityManagerFactory(EntityManagerFactory emf) { if (ObjectUtils.notNull(emf) && emf.isOpen()) { emf.close(); } } /** * Closes passed {@link EntityManager} instance if it is not null and it is * open * * @param em */ public static void closeEntityManager(EntityManager em) { if (ObjectUtils.notNull(em) && em.isOpen()) { em.close(); } } /** * Builder class to create {@link JpaManager} class object * * @author Levan Tsinadze * @since 0.0.79-SNAPSHOT */ public static class Builder { private JpaManager manager; public Builder() { manager = new JpaManager(); manager.scanArchives = Boolean.TRUE; } /** * Sets {@link javax.persistence.Entity} class names to initialize * * @param classes * @return {@link Builder} */ public Builder setClasses(List<String> classes) { manager.classes = classes; return this; } /** * Sets {@link URL} for persistence.xml file * * @param url * @return {@link Builder} */ public Builder setURL(URL url) { manager.url = url; return this; } /** * Sets path for persistence.xml file * * @param path * @return {@link Builder} */ public Builder setPath(String path) { manager.path = path; return this; } /** * Sets additional persistence properties * * @param properties * @return {@link Builder} */ public Builder setProperties(Map<Object, Object> properties) { manager.properties = manager.configure(properties); return this; } /** * Sets boolean check property to swap JTA data source value with non * JTA data source value * * @param swapDataSource * @return {@link Builder} */ public Builder setSwapDataSource(boolean swapDataSource) { manager.swapDataSource = swapDataSource; return this; } /** * Sets boolean check to scan deployed archive files for * {@link javax.persistence.Entity} annotated classes * * @param scanArchives * @return {@link Builder} */ public Builder setScanArchives(boolean scanArchives) { manager.scanArchives = scanArchives; return this; } /** * Sets {@link ClassLoader} for persistence classes * * @param loader * @return {@link Builder} */ public Builder setClassLoader(ClassLoader loader) { manager.loader = loader; return this; } /** * Sets if JPA is configured over Spring data * * @param springPersistence * @return {@link Builder} */ public Builder springPersistence(boolean springPersistence) { manager.springPersistence = springPersistence; return this; } /** * Sets data source name for Spring data configuration * * @param dataSourceName * @return {@link Builder} */ public Builder dataSourceName(String dataSourceName) { manager.dataSourceName = dataSourceName; return this; } /** * Sets all parameters from passed {@link Configuration} instance * * @param configuration * @return {@link Builder} */ public Builder configure(Configuration configuration) { // Sets all parameters from Configuration class setPath(configuration.getPersXmlPath()).setProperties(configuration.getPersistenceProperties()) .setSwapDataSource(configuration.isSwapDataSource()).setScanArchives(configuration.isScanArchives()) .springPersistence(configuration.isSpringPersistence()); return this; } public JpaManager build() { return manager; } } } /** * Enumeration for JPA configuration prefixes * * @author Levan Tsinadze * @since 0.1.2 * */ enum HibernatePrefixes { SPRING("spring."), JPA("jpa."), DAO("dao."); // Configuration properties prefixes private static final String HIBERNATE = "hibernate."; private final String prefix; /** * Validation class for key prefixes * * @author Levan Tsinadze * */ private static class KeyValidator { String text; HibernatePrefixes prefix; boolean modified; String key; public KeyValidator(String text) { this.text = text; this.key = text; } public String getPrefix() { return this.prefix.prefix; } public boolean hibernateKey() { return Boolean.FALSE.equals(modified) && Boolean.FALSE.equals(text.startsWith(HIBERNATE)); } } private HibernatePrefixes(String prefix) { this.prefix = prefix; } private static String replacePrefix(KeyValidator validator) { String key; String text = validator.text; if (validator.modified) { String prefix = validator.getPrefix(); key = text.replace(prefix, HIBERNATE); } else { key = text; } return key; } private static void validateKey(KeyValidator validator) { HibernatePrefixes[] prefixes = HibernatePrefixes.values(); int length = prefixes.length; String prefix; for (int i = CollectionUtils.FIRST_INDEX; i < length && Boolean.FALSE.equals(validator.modified); i++) { validator.prefix = prefixes[i]; prefix = validator.getPrefix(); validator.modified = validator.text.startsWith(prefix); validator.key = replacePrefix(validator); } } /** * Checks if passed key has appropriate prefix and if not adds this prefix * to passed key * * @param text * @return {@link String} key with appropriate prefix */ public static String validKey(String text) { String key; KeyValidator validator = new KeyValidator(text); validateKey(validator); key = validator.key; if (validator.hibernateKey()) { key = StringUtils.concat(HIBERNATE, text); } return key; } }
21,261
Java
.java
619
26.781906
120
0.64738
levants/lightmare
3
1
15
LGPL-2.1
9/4/2024, 11:27:52 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,261
1,768,432
StringAtom.java
Skyost_Algogo/core/src/main/java/xyz/algogo/core/evaluator/atom/StringAtom.java
package xyz.algogo.core.evaluator.atom; /** * Represents a string atom. */ public class StringAtom extends Atom<String> { /** * Creates a new string atom. * * @param value The string value. */ public StringAtom(final String value) { super(value); } @Override public boolean hasSameType(final Atom atom) { return hasStringType(atom); } @Override public StringAtom copy() { return new StringAtom(this.getValue()); } /** * Checks whether the given atom has a string type. * <br>In fact, we check if the value of the provided atom is an instance of String. * * @param atom The given atom. * * @return Whether the given atom has a string type. */ public static boolean hasStringType(final Atom atom) { return atom != null && atom.getValue() instanceof String; } }
811
Java
.java
33
22
85
0.719481
Skyost/Algogo
14
6
2
GPL-3.0
9/4/2024, 8:17:59 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
811
2,662,915
ServerStateListener.java
foosbar_mailsnag/mailsnag/src/com/foosbar/mailsnag/events/ServerStateListener.java
/******************************************************************************* * Copyright (c) 2010-2013 Foos-Bar.com * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Enrico - initial API and implementation * Kevin Kelley - Added ServerState enum *******************************************************************************/ package com.foosbar.mailsnag.events; import com.foosbar.mailsnag.smtp.ServerState; /** * Adds event handling capabilities for the SMTP Server Status. */ public interface ServerStateListener { /** * Event triggered when the servers state has changed. Currently there are * three states: STARTING, LISTENING and STOPPED. * * @param state * the current state of the server */ public void serverStateChanged(ServerState state); }
1,012
Java
.java
26
36.692308
81
0.641182
foosbar/mailsnag
6
3
4
EPL-2.0
9/4/2024, 10:02:38 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,012
3,224,960
FilterOperation.java
LIBCAS_ARCLib/system/src/main/java/cz/cas/lib/core/index/dto/FilterOperation.java
package cz.cas.lib.core.index.dto; import cz.cas.lib.arclib.index.solr.IndexQueryUtils; /** * Filter operation to do. */ public enum FilterOperation { /** * Equal. */ EQ, /** * Not equal. */ NEQ, /** * Greater than. * * <p> * Applicable to number or date attributes. * </p> */ GT, /** * Less than. * * <p> * Applicable to number or date attributes. * </p> */ LT, /** * Greater than or equals. * * <p> * Applicable to number or date attributes. * </p> */ GTE, /** * Less than or equals. * * <p> * Applicable to number or date attributes. * </p> */ LTE, /** * Starts with. * * <p> * Applicable to string attributes. * </p> */ STARTWITH, /** * Ends with. * * <p> * Applicable to string attributes. * </p> */ ENDWITH, /** * Contains. * * <p> * Applicable to string attributes. * </p> */ CONTAINS, /** * Logical AND. * * <p> * Applicable to sub-filters. * </p> */ AND, /** * Logical OR. * * <p> * Applicable to sub-filters. * </p> */ OR, /** * Is not set * * <p> * Applicable to all attributes. * </p> */ IS_NULL, /** * Is set * * <p> * Applicable to all attributes. * </p> */ NOT_NULL, /** * Work with nested objects * * <p> * Used to filter parents which has at least one child matching nested {@link Filter#filter} condition. * </p> * <p> * Parent and child entities must be in the same Solr collection. {@link Filter#value} must be set to index type which * exists as key in {@link IndexQueryUtils#INDEXED_FIELDS_MAP}. {@link Filter#filter} contains * filters which are executed on child collection. * </p> */ NESTED, /** * Negates inner filter */ NEGATE, /** * IN(v1,v2) is a shortcut for (EQ=v1 OR EQ=v2) */ IN };
2,186
Java
.java
124
12.024194
122
0.490714
LIBCAS/ARCLib
4
1
18
GPL-3.0
9/4/2024, 11:06:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,186
298,350
AbstractOpImpl.java
vassalengine_vassal/vassal-app/src/main/java/VASSAL/tools/imageop/AbstractOpImpl.java
/* * * Copyright (c) 2007-2008 by Joel Uckelman * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASSAL.tools.imageop; import java.awt.Dimension; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import VASSAL.tools.ErrorDialog; import VASSAL.tools.opcache.OpCache; /** * An abstract representation of an operation which may be applied to an * {@link Image}. <code>ImageOp</code> is the base class for all such * operations. The results of all operations are memoized (using a * memory-sensitive cache), so retrieving results is both fast and * memory-efficient. * * <p><b>Warning:</b> For efficiency reasons, the methods {@link #getImage} * and {@link #getTile} do <em>not</em> return <code>Image</code>s * defensively, nor do the {@code Future<Image>}s returned by * {@link #getFutureImage} and {@link #getFutureTile}. That is, the * <code>Image</code> returned is possibly the one retained internally by * the <code>ImageOp</code>. Therefore, <code>Image</code>s obtained from * an <code>ImageOp</code> <em>must not</em> be altered, as this might * interfere with image caching. If an <code>Image</code> obtained this way * needs to be modified, copy the <code>Image</code> first and alter the * copy.</p> * * @since 3.1.0 * @author Joel Uckelman */ @SuppressFBWarnings(value = "NM_SAME_SIMPLE_NAME_AS_SUPERCLASS") public abstract class AbstractOpImpl extends VASSAL.tools.opcache.AbstractOpImpl<BufferedImage> implements ImageOp { /** The cached size of this operation's resulting <code>Image</code>. */ protected Dimension size; /** The cache which contains calculated <code>Image</code>s. */ protected static final OpCache cache = new OpCache(); public static void clearCache() { cache.clear(); } public AbstractOpImpl() { super(cache); } /** {@inheritDoc} */ @Override public abstract BufferedImage eval() throws Exception; /** {@inheritDoc} */ @Override public BufferedImage getImage() { try { return getImage(null); } catch (CancellationException | InterruptedException e) { // FIXME: bug until we permit cancellation ErrorDialog.bug(e); } catch (ExecutionException e) { if (!Op.handleException(e)) ErrorDialog.bug(e); } return null; } /** {@inheritDoc} */ @Override public BufferedImage getImage(ImageOpObserver obs) throws CancellationException, InterruptedException, ExecutionException { return get(obs); } /** {@inheritDoc} */ @Override public Future<BufferedImage> getFutureImage(ImageOpObserver obs) throws ExecutionException { return getFuture(obs); } /** * A utility method for retrieving the size of the computed * <code>Image</code> from the cache if the <code>Image</code> * is cached. * * @return the size of the cached <code>Image</code>, or * <code>null</code> if the <code>Image</code> isn't cached */ protected Dimension getSizeFromCache() { final BufferedImage im = cache.getIfDone(newKey()); return im == null ? null : new Dimension(im.getWidth(), im.getHeight()); } /** * Sets the <code>size</code> which is used by {@link #getSize}, * {@link #getHeight}, and {@link #getWidth}. */ protected abstract void fixSize(); /** {@inheritDoc} */ @Override public Dimension getSize() { if (size == null) fixSize(); return new Dimension(size); } /** {@inheritDoc} */ @Override public int getWidth() { if (size == null) fixSize(); return size.width; } /** {@inheritDoc} */ @Override public int getHeight() { if (size == null) fixSize(); return size.height; } /** {@inheritDoc} */ @Override public abstract Dimension getTileSize(); /** {@inheritDoc} */ @Override public abstract int getTileHeight(); /** {@inheritDoc} */ @Override public abstract int getTileWidth(); /** {@inheritDoc} */ @Override public abstract int getNumXTiles(); /** {@inheritDoc} */ @Override public abstract int getNumYTiles(); /** {@inheritDoc} */ @Override public BufferedImage getTile(Point p, ImageOpObserver obs) throws CancellationException, InterruptedException, ExecutionException { return getTile(p.x, p.y, obs); } /** {@inheritDoc} */ @Override public abstract BufferedImage getTile(int tileX, int tileY, ImageOpObserver obs) throws CancellationException, InterruptedException, ExecutionException; /** {@inheritDoc} */ @Override public Future<BufferedImage> getFutureTile(Point p, ImageOpObserver obs) throws ExecutionException { return getFutureTile(p.x, p.y, obs); } /** {@inheritDoc} */ @Override public abstract Future<BufferedImage> getFutureTile( int tileX, int tileY, ImageOpObserver obs) throws ExecutionException; /** {@inheritDoc} */ @Override public ImageOp getTileOp(Point p) { return getTileOp(p.x, p.y); } /** {@inheritDoc} */ @Override public abstract ImageOp getTileOp(int tileX, int tileY); /** {@inheritDoc} */ @Override public abstract Point[] getTileIndices(Rectangle rect); }
6,008
Java
.java
177
30.19774
79
0.709332
vassalengine/vassal
413
97
384
LGPL-2.1
9/4/2024, 7:06:16 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
6,008
1,118,337
OptionsDlg.java
SemanticBeeng_jpdfbookmarks/jpdfbookmarks_core/src/it/flavianopetrocchi/jpdfbookmarks/OptionsDlg.java
/* * OptionsDialog.java * * Copyright (c) 2010 Flaviano Petrocchi <flavianopetrocchi at gmail.com>. * All rights reserved. * * This file is part of JPdfBookmarks. * * JPdfBookmarks is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPdfBookmarks is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JPdfBookmarks. If not, see <http://www.gnu.org/licenses/>. */ package it.flavianopetrocchi.jpdfbookmarks; import java.awt.BorderLayout; import javax.swing.JOptionPane; public class OptionsDlg extends javax.swing.JDialog { public final static int GENERAL_PANEL = 0; public final static int PROXY_PANEL = 1; public final static int TOOLBARS_PANEL = 2; private Prefs userPrefs = new Prefs(); private SeparatorsPanel separatorsOptions = new SeparatorsPanel(userPrefs); private ConnectionOptionsPanel connectionOptions = new ConnectionOptionsPanel(userPrefs); private ToolbarsOptionsPanel toolbarsOptions = new ToolbarsOptionsPanel(userPrefs); private GeneralOptionsPanel generalOptions = new GeneralOptionsPanel(userPrefs); // private EncodingOptionsPanel encodingOptions = new EncodingOptionsPanel(userPrefs); private JPdfBookmarksGui gui; /** Creates new form OptionsDlg */ public OptionsDlg(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); gui = (JPdfBookmarksGui) parent; mainTabPane.addTab(Res.getString("TAB_GENERAL_OPTIONS"), generalOptions); mainTabPane.setMnemonicAt(0, Res.mnemonicFromRes("TAB_GENERAL_OPTIONS_MNEMONIC")); mainTabPane.addTab(Res.getString("TAB_SEPARATOR_OPTIONS"), separatorsOptions); mainTabPane.setMnemonicAt(0, Res.mnemonicFromRes("TAB_SEPARATOR_OPTIONS_MNEMONIC")); mainTabPane.addTab(Res.getString("TAB_CONNECTION_OPTIONS"), connectionOptions); mainTabPane.setMnemonicAt(0, Res.mnemonicFromRes("TAB_CONNECTION_OPTIONS_MNEMONIC")); mainTabPane.add(Res.getString("TAB_TOOLBARS_MANAGER"), toolbarsOptions); // mainTabPane.setMnemonicAt(0, Res.mnemonicFromRes("TAB_ENCODING_OPTIONS_MNEMONIC")); // mainTabPane.add(Res.getString("TAB_ENCODING_OPTIONS"), encodingOptions); pack(); } public void setVisibleTab(int tab) { mainTabPane.setSelectedIndex(tab); } private boolean checkDifferentValuesAndEmptyValues() { String pag = separatorsOptions.getPageSeparator(); String ind = separatorsOptions.getIndentationString(); String sep = separatorsOptions.getAttributesSeparator(); if (pag.equals(ind) || pag.equals(sep) || ind.equals(sep)) { JOptionPane.showMessageDialog(this, Res.getString("ERROR_DUPLICATED_VALUES"), JPdfBookmarks.APP_NAME, JOptionPane.WARNING_MESSAGE); return false; } if (pag.isEmpty() || sep.isEmpty() || ind.isEmpty()) { JOptionPane.showMessageDialog(this, Res.getString("ERROR_EMPTY_FIELD"), JPdfBookmarks.APP_NAME, JOptionPane.WARNING_MESSAGE); return false; } return true; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); mainPanel = new javax.swing.JPanel(); buttonsPanel = new javax.swing.JPanel(); btnCancel = new javax.swing.JButton(); btnOk = new javax.swing.JButton(); tabsPanel = new javax.swing.JPanel(); mainTabPane = new javax.swing.JTabbedPane(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("JPdfBookmarks"); // NOI18N mainPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5)); mainPanel.setLayout(new java.awt.BorderLayout()); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("it/flavianopetrocchi/jpdfbookmarks/locales/localizedText"); // NOI18N btnCancel.setText(bundle.getString("CANCEL")); // NOI18N btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelActionPerformed(evt); } }); btnOk.setText(bundle.getString("OK")); // NOI18N btnOk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnOkActionPerformed(evt); } }); javax.swing.GroupLayout buttonsPanelLayout = new javax.swing.GroupLayout(buttonsPanel); buttonsPanel.setLayout(buttonsPanelLayout); buttonsPanelLayout.setHorizontalGroup( buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(buttonsPanelLayout.createSequentialGroup() .addGap(475, 475, 475) .addComponent(btnOk) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnCancel) .addContainerGap()) ); buttonsPanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnCancel, btnOk}); buttonsPanelLayout.setVerticalGroup( buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(buttonsPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(buttonsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnCancel) .addComponent(btnOk)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); mainPanel.add(buttonsPanel, java.awt.BorderLayout.PAGE_END); tabsPanel.setLayout(new java.awt.BorderLayout()); tabsPanel.add(mainTabPane, java.awt.BorderLayout.CENTER); mainPanel.add(tabsPanel, java.awt.BorderLayout.CENTER); jScrollPane1.setViewportView(mainPanel); getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold>//GEN-END:initComponents private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed if (!checkDifferentValuesAndEmptyValues()) { return; } String pag = separatorsOptions.getPageSeparator(); String ind = separatorsOptions.getIndentationString(); String sep = separatorsOptions.getAttributesSeparator(); userPrefs.setPageSeparator(pag); userPrefs.setIndentationString(ind); userPrefs.setAttributesSeparator(sep); userPrefs.setConvertNamedDestinations(generalOptions.convertNamedDestinations()); userPrefs.setUseThousandths(generalOptions.useThousandths()); userPrefs.setCharsetEncoding(generalOptions.getCharsetEncoding()); userPrefs.setNumClicks(generalOptions.getNumClicks()); userPrefs.setUseProxy(connectionOptions.useProxy()); userPrefs.setProxyType(connectionOptions.getProxyType()); userPrefs.setProxyAddress(connectionOptions.getProxyAddress()); userPrefs.setProxyPort(connectionOptions.getProxyPort()); userPrefs.setCheckUpdatesOnStart(connectionOptions.checkUpdatesOnStart()); userPrefs.setNeverAskWebAccess(connectionOptions.neverAskWebAccess()); toolbarsOptions.saveToolbarPreferences(); gui.updateToolbars(); dispose(); }//GEN-LAST:event_btnOkActionPerformed private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed dispose(); }//GEN-LAST:event_btnCancelActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnCancel; private javax.swing.JButton btnOk; private javax.swing.JPanel buttonsPanel; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JPanel mainPanel; private javax.swing.JTabbedPane mainTabPane; private javax.swing.JPanel tabsPanel; // End of variables declaration//GEN-END:variables }
9,108
Java
.java
170
44.682353
147
0.709797
SemanticBeeng/jpdfbookmarks
41
5
2
GPL-3.0
9/4/2024, 7:11:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
9,108
2,243,031
GroupManagerMonitoringDataConsumer.java
snoozesoftware_snoozenode/src/main/java/org/inria/myriads/snoozenode/groupmanager/monitoring/consumer/GroupManagerMonitoringDataConsumer.java
package org.inria.myriads.snoozenode.groupmanager.monitoring.consumer; import java.io.IOException; import java.util.concurrent.BlockingQueue; import org.inria.myriads.snoozecommon.communication.NetworkAddress; import org.inria.myriads.snoozecommon.guard.Guard; import org.inria.myriads.snoozenode.comunicator.CommunicatorFactory; import org.inria.myriads.snoozenode.comunicator.api.Communicator; import org.inria.myriads.snoozenode.configurator.database.DatabaseSettings; import org.inria.myriads.snoozenode.groupmanager.monitoring.transport.GroupManagerDataTransporter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * Group Manager Monitoring Data Consumer. * * @author msimonin * */ public class GroupManagerMonitoringDataConsumer implements Runnable { /** Define the logger. */ private static final Logger log_ = LoggerFactory.getLogger(GroupManagerMonitoringDataConsumer.class); /** Group manager id. */ private String groupManagerId_; /** Data queue. */ private BlockingQueue<GroupManagerDataTransporter> dataQueue_; /** Signals termination. */ private boolean isTerminated_; /** Communicator (with the upper level).*/ private Communicator communicator_; /** * * Constructor. * * @param groupManagerId The group Manager Id. * @param groupLeaderAddress The group Leader address. * @param databaseSettings The databse Settings. * @param dataQueue The data queue. * @throws IOException IOException */ public GroupManagerMonitoringDataConsumer( String groupManagerId, NetworkAddress groupLeaderAddress, DatabaseSettings databaseSettings, BlockingQueue<GroupManagerDataTransporter> dataQueue ) throws IOException { Guard.check(groupManagerId, databaseSettings); groupManagerId_ = groupManagerId; dataQueue_ = dataQueue; isTerminated_ = false; communicator_ = CommunicatorFactory.newGroupManagerCommunicator(groupLeaderAddress, databaseSettings); } @Override public void run() { try { while (!isTerminated_) { log_.debug("Waiting for group manager monitoring data to arrive..."); GroupManagerDataTransporter groupManagerData = dataQueue_.take(); if (groupManagerData.getSummary() == null) { sendHeartbeatData(groupManagerId_); continue; } sendRegularData(groupManagerId_, groupManagerData); } } catch (InterruptedException exception) { log_.error("group manager monitoring data consumer thread was interruped", exception); } log_.debug("Group monitoring data consumer stopped!"); terminate(); } /** * * Sends regular data (monitoring data). * * @param groupManagerId The group manager id. * @param groupManagerData The monitoring data. * @throws InterruptedException Exception */ private void sendRegularData( String groupManagerId, GroupManagerDataTransporter groupManagerData ) throws InterruptedException { try { communicator_.sendRegularData(groupManagerData); } catch (Exception exception) { log_.debug(String.format("I/O error during data sending (%s)! Did the group manager close " + "its connection unexpectedly?", exception.getMessage())); throw new InterruptedException(); } } /** * * Sends heartbeat datas. * * @param groupManagerId The group manager id. * @throws InterruptedException Exception */ private void sendHeartbeatData(String groupManagerId) throws InterruptedException { GroupManagerDataTransporter data = new GroupManagerDataTransporter(groupManagerId, null); try { communicator_.sendHeartbeatData(data); } catch (Exception exception) { log_.debug(String.format("I/O error during data sending (%s)! Did the group manager close " + "its connection unexpectedly?", exception.getMessage())); throw new InterruptedException(); } } /** * Terminates the consumer. */ public void terminate() { log_.debug("Terminating the virtual machine monitoring data consumer"); isTerminated_ = true; } }
4,824
Java
.java
131
27.977099
111
0.65036
snoozesoftware/snoozenode
9
3
23
GPL-2.0
9/4/2024, 8:40:51 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,824
3,507,990
UltrasoundImpl.java
openhealthcare_openMAXIMS/openmaxims_workspace/Therapies/src/ims/therapies/domain/impl/UltrasoundImpl.java
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Charlotte Murphy using IMS Development Environment (version 1.42 build 2202.25904) // Copyright (C) 1995-2006 IMS MAXIMS plc. All rights reserved. package ims.therapies.domain.impl; import ims.admin.domain.HcpAdmin; import ims.admin.domain.impl.HcpAdminImpl; import ims.core.vo.CareContextLiteVo; import ims.core.vo.ClinicalContactShortVo; import ims.core.vo.HcpLiteVoCollection; import ims.domain.DomainFactory; import ims.domain.exceptions.DomainRuntimeException; import ims.domain.exceptions.StaleObjectException; import ims.domain.exceptions.UniqueKeyViolationException; import ims.framework.exceptions.CodingRuntimeException; import ims.therapies.domain.TreatmentEquipmentConfig; import ims.therapies.domain.base.impl.BaseUltrasoundImpl; import ims.therapies.treatment.domain.objects.ElectrotherapyUltrasound; import ims.therapies.treatment.vo.ElectrotherapyUltrasoundRefVo; import ims.therapies.vo.ElectrotherapyUltrasoundShortVoCollection; import ims.therapies.vo.ElectrotherapyUltrasoundVo; import ims.therapies.vo.TreatmentEquipmentConfigVoCollection; import ims.therapies.vo.domain.ElectrotherapyUltrasoundShortVoAssembler; import ims.therapies.vo.domain.ElectrotherapyUltrasoundVoAssembler; import ims.therapies.vo.lookups.TreatmentEquipmentTypeConfig; public class UltrasoundImpl extends BaseUltrasoundImpl { private static final long serialVersionUID = 1L; /** * WDEV-13598 * List records by Care Context and take into account the RIE records. */ public ElectrotherapyUltrasoundShortVoCollection listByCareContext(CareContextLiteVo voCareContext) { String hql = "from ElectrotherapyUltrasound eu where eu.clinicalContact.careContext.id = :CC"; return ElectrotherapyUltrasoundShortVoAssembler.createElectrotherapyUltrasoundShortVoCollectionFromElectrotherapyUltrasound(getDomainFactory().find(hql, "CC", voCareContext.getID_CareContext())); } /** * WDEV-13648 * Get ElectrotherapyUltrasoundVo record by id */ public ElectrotherapyUltrasoundVo getUltrasound(ElectrotherapyUltrasoundRefVo ultrasound) { // Check parameter if (ultrasound == null || !ultrasound.getID_ElectrotherapyUltrasoundIsNotNull()) return null; return ElectrotherapyUltrasoundVoAssembler.create((ElectrotherapyUltrasound) getDomainFactory().getDomainObject(ElectrotherapyUltrasound.class, ultrasound.getID_ElectrotherapyUltrasound())); } public HcpLiteVoCollection listHcpLiteByName(String hcpName) { HcpAdmin impl = (HcpAdmin) getDomainImpl(HcpAdminImpl.class); return impl.listHcpLiteByName(hcpName); } public ElectrotherapyUltrasoundVo save(ElectrotherapyUltrasoundVo voElectroUltrasound) throws StaleObjectException, UniqueKeyViolationException { if(!voElectroUltrasound.isValidated()) throw new DomainRuntimeException("This Ultrasound has not been validated"); DomainFactory factory = getDomainFactory(); if (voElectroUltrasound.getID_ElectrotherapyUltrasound() == null)//Inserting a record { ElectrotherapyUltrasoundVo vo = getUltrasoundByClinicalContact(voElectroUltrasound.getClinicalContact()); if(vo != null) throw new UniqueKeyViolationException("The screen will be refreshed"); } ElectrotherapyUltrasound doUltrasound = ElectrotherapyUltrasoundVoAssembler.extractElectrotherapyUltrasound(factory, voElectroUltrasound); factory.save(doUltrasound); return ElectrotherapyUltrasoundVoAssembler.create(doUltrasound); } private ElectrotherapyUltrasoundVo getUltrasoundByClinicalContact(ClinicalContactShortVo voClinicalContact) { if(voClinicalContact == null) throw new CodingRuntimeException("ElectrotherapyUltrasound Filter not provided for get call. "); String hql = "from ElectrotherapyUltrasound e where e.clinicalContact.id = :CLINICAL_CONTACT_ID and e.isRIE is null"; return ElectrotherapyUltrasoundVoAssembler.create((ElectrotherapyUltrasound) getDomainFactory().findFirst(hql, "CLINICAL_CONTACT_ID", voClinicalContact.getID_ClinicalContact())); } public TreatmentEquipmentConfigVoCollection listTreatmentEquipmentConfigs(TreatmentEquipmentTypeConfig lkpTreatmentEquipmentConfig) { TreatmentEquipmentConfig impl = (TreatmentEquipmentConfig) getDomainImpl(TreatmentEquipmentConfigImpl.class); return impl.list(lkpTreatmentEquipmentConfig); } }
5,865
Java
.java
98
56.295918
198
0.718312
openhealthcare/openMAXIMS
3
1
0
AGPL-3.0
9/4/2024, 11:30:20 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
5,865
135,092
LiquidBitcoinAddressValidator.java
haveno-dex_haveno/assets/src/main/java/haveno/asset/LiquidBitcoinAddressValidator.java
package haveno.asset; public class LiquidBitcoinAddressValidator extends RegexAddressValidator { static private final String REGEX = "^([a-km-zA-HJ-NP-Z1-9]{26,35}|[a-km-zA-HJ-NP-Z1-9]{80}|[a-z]{2,5}1[ac-hj-np-z02-9]{8,87}|[A-Z]{2,5}1[AC-HJ-NP-Z02-9]{8,87})$"; public LiquidBitcoinAddressValidator() { super(REGEX, "validation.crypto.liquidBitcoin.invalidAddress"); } }
392
Java
.java
7
51.857143
167
0.70235
haveno-dex/haveno
975
107
106
AGPL-3.0
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
392
1,334,181
ProgressManager.java
Ammar64_Sharing/app/src/main/java/com/ammar/sharing/custom/io/ProgressManager.java
package com.ammar.sharing.custom.io; import android.os.Bundle; import com.ammar.sharing.common.Data; import com.ammar.sharing.common.utils.Utils; import com.ammar.sharing.models.Sharable; import com.ammar.sharing.models.User; import java.io.IOException; import java.net.Socket; import java.util.ArrayList; public class ProgressManager { private final Sharable sharable; private Socket socket; private String displayName = null; // The other device receiving or sending private final User user; public enum OP {DOWNLOAD, UPLOAD} private final OP op; // if loaded is -1 it's completed. private long loaded; // total file size private long total; // when we started transferring file private long startTime; // total time taken to finish. -1 if not finished private long totalFinishTime = -1; private int index; private String uuid = null; private void setIndex(int index) { this.index = index; this.progress_info.putInt("index", index); } public int getIndex() { return index; } public static ArrayList<ProgressManager> progresses = new ArrayList<>(); public static void removeProgress(int index) { for (int i = index + 1; i < progresses.size(); i++) { progresses.get(i).setIndex(progresses.get(i).index - 1); } progresses.remove(index); Bundle b = new Bundle(); b.putChar("action", 'R'); b.putInt("index", index); Data.filesSendNotifier.forcePostValue(b); } public ProgressManager(Sharable sharable, Socket socket, long total, User user, OP opType) { this.sharable = sharable; this.socket = socket; this.total = total; this.user = user; this.op = opType; progresses.add(this); index = progresses.lastIndexOf(this); // notify the UI item is added Bundle info_add = new Bundle(); info_add.putChar("action", 'A'); info_add.putInt("index", index); Data.filesSendNotifier.forcePostValue(info_add); // set action to P for later use progress_info.putChar("action", 'P'); progress_info.putInt("index", index); startTime = System.currentTimeMillis(); } public long getTotal() { return total; } public String getFileName() { return sharable.getFileName(); } public String getDisplayName() { return displayName == null ? sharable.getName() : displayName; } public Sharable getSharable() { return sharable; } public String getFileType() { return Utils.getMimeType(sharable.getName()); } public User getUser() { return user; } public long getLoaded() { return loaded; } public String getUUID() { return uuid; } long transferSpeed = 0; public long getSpeed() { return (long) (transferSpeed * (1000.0f / 300.0f)); } public OP getOperation() { return op; } long previouslyLoaded = 0; public void setLoaded(long n) { loaded = n; reportProgress(); } public void accumulateLoaded(int bytesRead) { if (loaded >= 0) loaded += bytesRead; reportProgress(); } public void setTotal(long n) { total = n; } public void setDisplayName(String name) { displayName = name; } public int getPercentage() { if (loaded < 0) return 100; return (int) ((float) loaded / (float) total * 100.0f); } // totalFinishTime is -1 if not finished public long getTotalTime() { return totalFinishTime; } public void setUUID(String uuid) { this.uuid = uuid; } private long lastTime = 0; private final Bundle progress_info = new Bundle(); public void reportProgress() { if (System.currentTimeMillis() - lastTime >= 300) { Data.filesSendNotifier.postValue(progress_info); // notify the UI of changes transferSpeed = getLoaded() - previouslyLoaded; previouslyLoaded = getLoaded(); lastTime = System.currentTimeMillis(); } } public static final int COMPLETED = -1; public static final int STOPPED_BY_REMOTE = -2; public static final int STOPPED_BY_USER = -3; // didn't work properly that's why not used public void reportCompleted() { totalFinishTime = System.currentTimeMillis() - startTime; setLoaded(COMPLETED); Data.filesSendNotifier.forcePostValue(progress_info); } public void reportStopped() { setLoaded(STOPPED_BY_REMOTE); Data.filesSendNotifier.forcePostValue(progress_info); } public void stop() { try { socket.getInputStream().close(); socket.getOutputStream().close(); socket.close(); } catch (IOException ignore) {} setLoaded(STOPPED_BY_REMOTE); // Passing STOPPED_BY_USER doesn't work properly Data.filesSendNotifier.forcePostValue(progress_info); } }
5,119
Java
.java
151
26.887417
96
0.642596
Ammar64/Sharing
37
2
11
GPL-3.0
9/4/2024, 7:37:36 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
5,119
135,286
NonBsqCoinSelector.java
haveno-dex_haveno/core/src/main/java/haveno/core/xmr/wallet/NonBsqCoinSelector.java
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package haveno.core.xmr.wallet; import com.google.inject.Inject; import haveno.core.user.Preferences; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence; import org.bitcoinj.core.TransactionOutput; /** * We use a specialized version of the CoinSelector based on the DefaultCoinSelector implementation. * We lookup for spendable outputs which matches our address of our address. */ @Slf4j public class NonBsqCoinSelector extends HavenoDefaultCoinSelector { @Setter private Preferences preferences; @Inject public NonBsqCoinSelector() { super(false); } @Override protected boolean isTxOutputSpendable(TransactionOutput output) { // output.getParentTransaction() cannot be null as it is checked in calling method Transaction parentTransaction = output.getParentTransaction(); if (parentTransaction == null) return false; // It is important to not allow pending txs as otherwise unconfirmed BSQ txs would be considered nonBSQ as // below outputIsNotInBsqState would be true. if (parentTransaction.getConfidence().getConfidenceType() != TransactionConfidence.ConfidenceType.BUILDING) return false; return true; } // Prevent usage of dust attack utxos @Override protected boolean isDustAttackUtxo(TransactionOutput output) { return output.getValue().value < preferences.getIgnoreDustThreshold(); } }
2,220
Java
.java
54
36.962963
115
0.758573
haveno-dex/haveno
975
107
106
AGPL-3.0
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,220
661,495
MinioUploadUtil.java
LoveMyOrange_ding-flowable-vue2-enhance/src/main/java/com/dingding/mid/utils/MinioUploadUtil.java
package com.dingding.mid.utils; import io.minio.*; import io.minio.http.Method; import io.minio.messages.Bucket; import io.minio.messages.Item; import lombok.Cleanup; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * minio文件上传工具类 */ @Component @Slf4j public class MinioUploadUtil { @Resource(name = "minioClient") private MinioClient minioClient; /** * 上传文件 * * @param file * @param bucketName * @param fileName * @return */ public void uploadFile(MultipartFile file, String bucketName, String fileName) { //判断文件是否为空 if (null == file || 0 == file.getSize()) { log.error("文件不能为空"); } //判断存储桶是否存在 bucketExists(bucketName); //文件名 if(file != null){ String originalFilename = file.getOriginalFilename(); //新的文件名 = 存储桶文件名_时间戳.后缀名 assert originalFilename != null; //开始上传 try { @Cleanup InputStream inputStream = file.getInputStream(); minioClient.putObject( PutObjectArgs.builder().bucket(bucketName).object(fileName).stream( inputStream, file.getSize(), -1) .contentType(file.getContentType()) .build()); } catch (Exception e) { log.error(e.getMessage()); } } } /** * 上传文件(可以传空) 数据备份使用 * @param filePath * @param bucketName * @param fileName * @throws IOException */ public void uploadFiles(String filePath, String bucketName, String fileName) throws IOException { MultipartFile file = FileUtil.createFileItem(new File(XSSEscape.escapePath(filePath))); //开始上传 try { @Cleanup InputStream inputStream = file.getInputStream(); minioClient.putObject( PutObjectArgs.builder().bucket(bucketName).object(fileName).stream( inputStream, file.getSize(), -1) .contentType(file.getContentType()) .build()); } catch (Exception e) { log.error(e.getMessage()); } } /** * 下载文件 * * @param fileName 文件名 * @param bucketName 桶名(文件夹) * @return */ public void downFile(String fileName, String bucketName, String downName) { InputStream inputStream = null; try { inputStream = minioClient.getObject( GetObjectArgs.builder() .bucket(bucketName) .object(fileName) .build()); //下载文件 HttpServletResponse response = ServletUtil.getResponse(); HttpServletRequest request = ServletUtil.getRequest(); try { @Cleanup BufferedInputStream bis = new BufferedInputStream(inputStream); if (StringUtils.isNotEmpty(downName)) { fileName = downName; } response.setCharacterEncoding("UTF-8"); response.setContentType("text/plain"); if(fileName.contains(".svg")){ response.setContentType("image/svg+xml"); } //编码的文件名字,关于中文乱码的改造 String codeFileName = ""; String agent = request.getHeader("USER-AGENT").toLowerCase(); if (-1 != agent.indexOf("msie") || -1 != agent.indexOf("trident")) { //IE codeFileName = URLEncoder.encode(fileName, "UTF-8"); } else if (-1 != agent.indexOf("mozilla")) { //火狐,谷歌 codeFileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1"); } else { codeFileName = URLEncoder.encode(fileName, "UTF-8"); } response.setHeader("Content-Disposition", "attachment;filename=" + XSSEscape.escape(new String(codeFileName.getBytes(), "utf-8"))); @Cleanup OutputStream os = response.getOutputStream(); int i; byte[] buff = new byte[1024 * 8]; while ((i = bis.read(buff)) != -1) { os.write(buff, 0, i); } os.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } catch (Exception e) { log.error(e.getMessage()); } finally { if (inputStream!=null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 返回图片 * * @param fileName 文件名 * @param bucketName 桶名(文件夹) * @return */ public void dowloadMinioFile(String fileName, String bucketName) { try { @Cleanup InputStream inputStream = minioClient.getObject( GetObjectArgs.builder() .bucket(bucketName) .object(fileName) .build()); @Cleanup ServletOutputStream outputStream1 = ServletUtil.getResponse().getOutputStream(); //读取指定路径下面的文件 @Cleanup OutputStream outputStream = new BufferedOutputStream(outputStream1); //创建存放文件内容的数组 byte[] buff = new byte[1024]; //所读取的内容使用n来接收 int n; //当没有读取完时,继续读取,循环 while ((n = inputStream.read(buff)) != -1) { //将字节数组的数据全部写入到输出流中 outputStream.write(buff, 0, n); } //强制将缓存区的数据进行输出 outputStream.flush(); } catch (Exception e) { e.printStackTrace(); } } /** * 获取資源 * * @param fileName * @param bucketName */ public String getFile(String fileName, String bucketName) { String objectUrl = null; try { objectUrl = minioClient.getPresignedObjectUrl( GetPresignedObjectUrlArgs.builder() .method(Method.GET) .bucket(bucketName) .object(fileName) .build()); } catch (Exception e) { log.error(e.getMessage()); } return objectUrl; } /** * 下载文件 * * @param fileName 文件名称 * @param bucketName 存储桶名称 * @return */ public InputStream downloadMinio(String fileName, String bucketName) { try { @Cleanup InputStream stream = minioClient.getObject( GetObjectArgs.builder().bucket(bucketName).object(fileName).build()); return stream; } catch (Exception e) { e.printStackTrace(); log.info(e.getMessage()); return null; } } /** * 获取全部bucket * * @return */ public List<String> getAllBuckets() throws Exception { return minioClient.listBuckets().stream().map(Bucket::name).collect(Collectors.toList()); } /** * 根据bucketName删除信息 * * @param bucketName bucket名称 */ public void removeBucket(String bucketName) throws Exception { minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build()); } /** * 删除一个对象 * * @param name * @return */ public boolean removeFile(String bucketName, String name) { boolean isOK = true; try { minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(name).build()); } catch (Exception e) { e.printStackTrace(); isOK = false; } return isOK; } /** * 检查存储桶是否已经存在(不存在不创建) * * @param name * @return */ public boolean bucketExists(String name) { boolean isExist = false; try { isExist = minioClient.bucketExists(getBucketExistsArgs(name)); } catch (Exception e) { e.printStackTrace(); } return isExist; } /** * 检查存储桶是否已经存在(不存在则创建) * * @param name * @return */ public void bucketExistsCreate(String name) { try { minioClient.bucketExists(getBucketExistsArgs(name)); minioClient.makeBucket(getMakeBucketArgs(name)); } catch (Exception e) { e.printStackTrace(); } } /** * String转MakeBucketArgs * * @param name * @return */ public static MakeBucketArgs getMakeBucketArgs(String name) { return MakeBucketArgs.builder().bucket(name).build(); } /** * String转BucketExistsArgs * * @param name * @return */ public static BucketExistsArgs getBucketExistsArgs(String name) { return BucketExistsArgs.builder().bucket(name).build(); } }
10,326
Java
.java
301
21.833887
147
0.540718
LoveMyOrange/ding-flowable-vue2-enhance
114
11
1
GPL-3.0
9/4/2024, 7:08:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
9,770
3,565,311
CurrenciesTablePage.java
innovad_4mila-1_0/com.rtiming.client/src/main/java/com/rtiming/client/settings/currency/CurrenciesTablePage.java
package com.rtiming.client.settings.currency; import java.util.Set; import org.eclipse.scout.rt.client.ui.action.menu.AbstractMenu; import org.eclipse.scout.rt.client.ui.action.menu.IMenu; import org.eclipse.scout.rt.client.ui.action.menu.IMenuType; import org.eclipse.scout.rt.client.ui.action.menu.TableMenuType; import org.eclipse.scout.rt.client.ui.basic.table.AbstractTable; import org.eclipse.scout.rt.client.ui.basic.table.ITableRow; import org.eclipse.scout.rt.client.ui.basic.table.columns.AbstractLongColumn; import org.eclipse.scout.rt.client.ui.basic.table.columns.AbstractSmartColumn; import org.eclipse.scout.rt.client.ui.basic.table.columns.AbstractStringColumn; import org.eclipse.scout.rt.client.ui.desktop.outline.pages.AbstractPageWithTable; import org.eclipse.scout.rt.platform.BEANS; import org.eclipse.scout.rt.platform.Order; import org.eclipse.scout.rt.platform.exception.ProcessingException; import org.eclipse.scout.rt.platform.util.CollectionUtility; import org.eclipse.scout.rt.platform.util.CompareUtility; import org.eclipse.scout.rt.shared.AbstractIcons; import org.eclipse.scout.rt.shared.ScoutTexts; import org.eclipse.scout.rt.shared.TEXTS; import org.eclipse.scout.rt.shared.data.basic.FontSpec; import org.eclipse.scout.rt.shared.services.common.code.ICodeType; import org.eclipse.scout.rt.shared.services.common.jdbc.SearchFilter; import com.rtiming.client.AbstractDoubleColumn; import com.rtiming.client.common.help.IHelpEnabledPage; import com.rtiming.client.common.ui.action.AbstractSeparatorMenu; import com.rtiming.shared.Icons; import com.rtiming.shared.Texts; import com.rtiming.shared.settings.IDefaultProcessService; import com.rtiming.shared.settings.ISettingsOutlineService; import com.rtiming.shared.settings.currency.CurrencyCodeType; import com.rtiming.shared.settings.currency.CurrencyFormData; import com.rtiming.shared.settings.currency.ICurrencyProcessService; public class CurrenciesTablePage extends AbstractPageWithTable<CurrenciesTablePage.Table> implements IHelpEnabledPage { @Override protected String getConfiguredIconId() { return AbstractIcons.Folder; } @Override protected String getConfiguredTitle() { return Texts.get("Currencies"); } @Override protected void execLoadData(SearchFilter filter) throws ProcessingException { importTableData(BEANS.get(ISettingsOutlineService.class).getCurrencyTableData()); } @Order(10.0) public class Table extends AbstractTable { @Override protected Class<? extends IMenu> getConfiguredDefaultMenu() { return EditMenu.class; } public ShortcutColumn getShortcutColumn() { return getColumnSet().getColumnByClass(ShortcutColumn.class); } @Override protected void execDecorateRow(ITableRow row) throws ProcessingException { if (CompareUtility.equals(getCurrencyUidColumn().getValue(row), getDefaultCurrencyUidColumn().getValue(row))) { FontSpec font = FontSpec.parse("bold"); row.setFont(font); } } @Override protected String getConfiguredDefaultIconId() { return Icons.PAYMENT; } public DefaultCurrencyUidColumn getDefaultCurrencyUidColumn() { return getColumnSet().getColumnByClass(DefaultCurrencyUidColumn.class); } public ExchangeRateColumn getExchangeRateColumn() { return getColumnSet().getColumnByClass(ExchangeRateColumn.class); } public CurrencyNameColumn getCurrencyNameColumn() { return getColumnSet().getColumnByClass(CurrencyNameColumn.class); } public CurrencyUidColumn getCurrencyUidColumn() { return getColumnSet().getColumnByClass(CurrencyUidColumn.class); } @Order(10.0) public class CurrencyUidColumn extends AbstractSmartColumn<Long> { @Override protected boolean getConfiguredDisplayable() { return false; } @Override protected String getConfiguredHeaderText() { return Texts.get("Currency"); } @Override protected Class<? extends ICodeType<Long, Long>> getConfiguredCodeType() { return CurrencyCodeType.class; } } @Order(20.0) public class DefaultCurrencyUidColumn extends AbstractLongColumn { @Override protected boolean getConfiguredDisplayable() { return false; } } @Order(30.0) public class CurrencyNameColumn extends AbstractStringColumn { @Override protected String getConfiguredHeaderText() { return TEXTS.get("Currency"); } @Override protected int getConfiguredWidth() { return 150; } } @Order(40.0) public class ShortcutColumn extends AbstractStringColumn { @Override protected String getConfiguredHeaderText() { return Texts.get("Shortcut"); } @Override protected int getConfiguredWidth() { return 150; } @Override protected int getConfiguredSortIndex() { return 1; } } @Order(50.0) public class ExchangeRateColumn extends AbstractDoubleColumn { @Override protected String getConfiguredHeaderText() { return Texts.get("ExchangeRate"); } @Override protected int getConfiguredMaxFractionDigits() { return 6; } @Override protected int getConfiguredMinFractionDigits() { return 6; } @Override protected int getConfiguredWidth() { return 150; } } @Order(10.0) public class NewMenu extends AbstractMenu { @Override protected String getConfiguredText() { return ScoutTexts.get("NewButton"); } @Override protected Set<? extends IMenuType> getConfiguredMenuTypes() { return CollectionUtility.<IMenuType> hashSet(TableMenuType.EmptySpace); } @Override protected void execAction() throws ProcessingException { CurrencyForm form = new CurrencyForm(); form.startNew(); form.waitFor(); if (form.isFormStored()) { reloadPage(); } } } @Order(20.0) public class EditMenu extends AbstractMenu { @Override protected String getConfiguredText() { return ScoutTexts.get("EditMenu"); } @Override protected void execAction() throws ProcessingException { CurrencyForm form = new CurrencyForm(); form.setCurrencyUid(getCurrencyUidColumn().getSelectedValue()); form.startModify(); form.waitFor(); if (form.isFormStored()) { reloadPage(); } } } @Order(30.0) public class SeparatorMenu extends AbstractSeparatorMenu { } @Order(40.0) public class CurrencySetDefaultCurrencyMenu extends AbstractMenu { @Override protected String getConfiguredText() { return Texts.get("CurrencySetDefaultCurrency"); } @Override protected void execAction() throws ProcessingException { // set as default BEANS.get(IDefaultProcessService.class).setDefaultCurrencyUid(getCurrencyUidColumn().getSelectedValue()); // default currency must have exchange rate 1 CurrencyFormData currency = new CurrencyFormData(); currency.setCurrencyUid(getCurrencyUidColumn().getSelectedValue()); currency = BEANS.get(ICurrencyProcessService.class).load(currency); currency.getExchangeRate().setValue(1D); BEANS.get(ICurrencyProcessService.class).store(currency); reloadPage(); } } } }
7,816
Java
.java
206
30.76699
120
0.713582
innovad/4mila-1.0
3
1
1
GPL-3.0
9/4/2024, 11:33:23 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,816
2,116,025
WtsJeiPlugin.java
Gegy_whats-that-slot/neoforge/src/main/java/dev/gegy/whats_that_slot/integration/jei/WtsJeiPlugin.java
package dev.gegy.whats_that_slot.integration.jei; import dev.gegy.whats_that_slot.WhatsThatSlot; import dev.gegy.whats_that_slot.ui.SlotQueryingScreen; import mezz.jei.api.IModPlugin; import mezz.jei.api.JeiPlugin; import mezz.jei.api.constants.VanillaTypes; import mezz.jei.api.gui.handlers.IGuiContainerHandler; import mezz.jei.api.ingredients.ITypedIngredient; import mezz.jei.api.registration.IGuiHandlerRegistration; import mezz.jei.api.runtime.IClickableIngredient; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; import net.minecraft.client.renderer.Rect2i; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import java.util.Optional; @JeiPlugin public final class WtsJeiPlugin implements IModPlugin { @Override public ResourceLocation getPluginUid() { return ResourceLocation.fromNamespaceAndPath(WhatsThatSlot.ID, "jei_plugin"); } @Override public void registerGuiHandlers(IGuiHandlerRegistration registration) { registration.addGuiContainerHandler(AbstractContainerScreen.class, new IGuiContainerHandler<>() { @Override public Optional<IClickableIngredient<?>> getClickableIngredientUnderMouse(AbstractContainerScreen screen, double mouseX, double mouseY) { if (screen instanceof SlotQueryingScreen queryingScreen) { var item = queryingScreen.whats_that_slot$getHoveredItemAt(mouseX, mouseY); if (item != null) { var ingredientManager = registration.getJeiHelpers().getIngredientManager(); return ingredientManager.createTypedIngredient(VanillaTypes.ITEM_STACK, item.stack()).map(ingredient -> new IClickableIngredient<ItemStack>() { @Override public ITypedIngredient<ItemStack> getTypedIngredient() { return ingredient; } @Override public Rect2i getArea() { return item.bounds().toRect(); } }); } } return Optional.empty(); } }); } }
2,315
Java
.java
47
37.595745
167
0.662395
Gegy/whats-that-slot
15
2
9
LGPL-3.0
9/4/2024, 8:29:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,315
4,843,140
MotifFinderTest.java
ISA-tools_Automacron/src/test/java/org/isatools/macros/motiffinder/MotifFinderTest.java
package org.isatools.macros.motiffinder; import org.isatools.macros.graph.graphloader.Neo4JConnector; import org.isatools.macros.gui.DBGraph; import org.isatools.macros.io.graphml.GraphMLCreator; import org.isatools.macros.utils.MotifProcessingUtils; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.Transaction; import java.io.File; import java.util.HashSet; import java.util.Map; import java.util.Set; import static junit.framework.Assert.assertTrue; /** * Created by the ISA team * * @author Eamonn Maguire (eamonnmag@gmail.com) * <p/> * Date: 23/10/2012 * Time: 13:10 */ public class MotifFinderTest { Node mixedRelationTestNode; Node sameRelationTestNode; Node sameRelationTestNodeMoreComplex; Node linearTestNode; Node mergeTestNode; Node complicatedCombinationTestCaseNode; Node largeBranchAndMergeTestNode; Node largeBranchingTestNode; private static Neo4JConnector connector = new Neo4JConnector(); @Before public void setUp() throws Exception { GraphDatabaseService graphDatabaseService = connector.getGraphDB(); Transaction tx = graphDatabaseService.beginTx(); try { createMixedRelationTestNode(graphDatabaseService); createSameRelationTestCase(graphDatabaseService); createComplexSameRelationTestCase(graphDatabaseService); createLinearRelationTestCase(graphDatabaseService); createMergeRelationTestCase(graphDatabaseService); createComplicatedCombinationTestCase(graphDatabaseService); createLargeBranchAndMergeTestCase(graphDatabaseService); createLargeBranchingTestCase(graphDatabaseService); tx.success(); } catch (Exception e) { e.printStackTrace(); } finally { tx.finish(); } } private void createLinearRelationTestCase(GraphDatabaseService graphDatabaseService) { linearTestNode = createNode(graphDatabaseService, "start", "root"); Node nodeA = createNode(graphDatabaseService, "typeA", "Value1"); Node nodeB = createNode(graphDatabaseService, "typeB", "Value2"); Node nodeC = createNode(graphDatabaseService, "typeC", "Value3"); nodeA.createRelationshipTo(linearTestNode, TestRelationshipTypes.REL_A); nodeB.createRelationshipTo(nodeA, TestRelationshipTypes.REL_B); nodeC.createRelationshipTo(nodeB, TestRelationshipTypes.REL_B); } private void createMergeRelationTestCase(GraphDatabaseService graphDatabaseService) { mergeTestNode = createNode(graphDatabaseService, "start", "root"); Node nodeA = createNode(graphDatabaseService, "typeA", "Value1"); Node nodeB = createNode(graphDatabaseService, "typeB", "Value2"); Node nodeC = createNode(graphDatabaseService, "typeC", "Value3"); Node nodeD = createNode(graphDatabaseService, "typeD", "Value4"); nodeA.createRelationshipTo(mergeTestNode, TestRelationshipTypes.REL_A); nodeB.createRelationshipTo(nodeA, TestRelationshipTypes.REL_B); nodeC.createRelationshipTo(nodeA, TestRelationshipTypes.REL_B); nodeD.createRelationshipTo(nodeB, TestRelationshipTypes.REL_A); nodeD.createRelationshipTo(nodeC, TestRelationshipTypes.REL_A); } private void createMixedRelationTestNode(GraphDatabaseService graphDatabaseService) { mixedRelationTestNode = createNode(graphDatabaseService, "start", "root"); Node nodeA = createNode(graphDatabaseService, "typeA", "Value1"); Node nodeB = createNode(graphDatabaseService, "typeB", "Value2"); Node nodeC = createNode(graphDatabaseService, "typeC", "Value3"); nodeA.createRelationshipTo(mixedRelationTestNode, TestRelationshipTypes.REL_A); nodeB.createRelationshipTo(nodeA, TestRelationshipTypes.REL_A); nodeC.createRelationshipTo(nodeA, TestRelationshipTypes.REL_B); } private void createSameRelationTestCase(GraphDatabaseService graphDatabaseService) { sameRelationTestNode = createNode(graphDatabaseService, "start", "root"); Node nodeA = createNode(graphDatabaseService, "typeA", "Value1"); Node nodeB = createNode(graphDatabaseService, "typeB", "Value2"); Node nodeC = createNode(graphDatabaseService, "typeB", "Value3"); nodeA.createRelationshipTo(sameRelationTestNode, TestRelationshipTypes.REL_A); nodeB.createRelationshipTo(nodeA, TestRelationshipTypes.REL_B); nodeC.createRelationshipTo(nodeA, TestRelationshipTypes.REL_B); } private void createComplexSameRelationTestCase(GraphDatabaseService graphDatabaseService) { sameRelationTestNodeMoreComplex = createNode(graphDatabaseService, "start", "root"); Node nodeA = createNode(graphDatabaseService, "typeA", "Value1"); Node nodeB = createNode(graphDatabaseService, "typeB", "Value2"); Node nodeBB = createNode(graphDatabaseService, "typeB", "Value3"); Node nodeC = createNode(graphDatabaseService, "typeC", "Value3"); Node nodeD = createNode(graphDatabaseService, "typeD", "Value4"); Node nodeD2 = createNode(graphDatabaseService, "typeD", "Value5"); Node nodeE = createNode(graphDatabaseService, "typeE", "Value6"); nodeA.createRelationshipTo(sameRelationTestNodeMoreComplex, TestRelationshipTypes.REL_A); nodeBB.createRelationshipTo(nodeA, TestRelationshipTypes.REL_A); nodeB.createRelationshipTo(nodeA, TestRelationshipTypes.REL_A); nodeC.createRelationshipTo(nodeA, TestRelationshipTypes.REL_A); nodeD.createRelationshipTo(nodeC, TestRelationshipTypes.REL_A); nodeD2.createRelationshipTo(nodeC, TestRelationshipTypes.REL_A); nodeE.createRelationshipTo(nodeD2, TestRelationshipTypes.REL_B); } private void createComplicatedCombinationTestCase(GraphDatabaseService graphDatabaseService) { complicatedCombinationTestCaseNode = createNode(graphDatabaseService, "start", "root"); Node nodeA = createNode(graphDatabaseService, "typeA", "Value1"); Node nodeB = createNode(graphDatabaseService, "typeB", "Value2"); Node nodeB2 = createNode(graphDatabaseService, "typeB", "Value3"); // B branch Node nodeC = createNode(graphDatabaseService, "typeC", "Value3"); Node nodeC2 = createNode(graphDatabaseService, "typeC", "Value4"); Node nodeD = createNode(graphDatabaseService, "typeD", "Value4"); Node nodeD2 = createNode(graphDatabaseService, "typeD", "Value5"); Node nodeE = createNode(graphDatabaseService, "typeE", "Value4"); Node nodeF = createNode(graphDatabaseService, "typeE", "Value4"); nodeA.createRelationshipTo(complicatedCombinationTestCaseNode, TestRelationshipTypes.REL_A); nodeB.createRelationshipTo(nodeA, TestRelationshipTypes.REL_A); nodeB2.createRelationshipTo(nodeA, TestRelationshipTypes.REL_A); nodeC.createRelationshipTo(nodeB, TestRelationshipTypes.REL_A); nodeC2.createRelationshipTo(nodeB, TestRelationshipTypes.REL_A); nodeD.createRelationshipTo(nodeC, TestRelationshipTypes.REL_A); nodeD2.createRelationshipTo(nodeC2, TestRelationshipTypes.REL_A); nodeE.createRelationshipTo(nodeD, TestRelationshipTypes.REL_A); nodeE.createRelationshipTo(nodeD2, TestRelationshipTypes.REL_A); nodeF.createRelationshipTo(nodeB2, TestRelationshipTypes.REL_B); } private void createLargeBranchAndMergeTestCase(GraphDatabaseService graphDatabaseService) { largeBranchAndMergeTestNode = createNode(graphDatabaseService, "start", "root"); Node nodeA = createNode(graphDatabaseService, "typeA", "Value1"); Node nodeB1 = createNode(graphDatabaseService, "typeB", "Value2"); Node nodeB2 = createNode(graphDatabaseService, "typeB", "Value3"); Node nodeB3 = createNode(graphDatabaseService, "typeB", "Value4"); Node nodeB4 = createNode(graphDatabaseService, "typeB", "Value5"); Node nodeB5 = createNode(graphDatabaseService, "typeB", "Value6"); Node nodeB6 = createNode(graphDatabaseService, "typeB", "Value7"); // B branch Node nodeC = createNode(graphDatabaseService, "typeC", "Value3"); nodeA.createRelationshipTo(largeBranchAndMergeTestNode, TestRelationshipTypes.REL_A); nodeB1.createRelationshipTo(nodeA, TestRelationshipTypes.REL_A); nodeB2.createRelationshipTo(nodeA, TestRelationshipTypes.REL_A); nodeB3.createRelationshipTo(nodeA, TestRelationshipTypes.REL_A); nodeB4.createRelationshipTo(nodeA, TestRelationshipTypes.REL_A); nodeB5.createRelationshipTo(nodeA, TestRelationshipTypes.REL_A); nodeB6.createRelationshipTo(nodeA, TestRelationshipTypes.REL_A); nodeC.createRelationshipTo(nodeB1, TestRelationshipTypes.REL_A); nodeC.createRelationshipTo(nodeB2, TestRelationshipTypes.REL_A); nodeC.createRelationshipTo(nodeB3, TestRelationshipTypes.REL_A); nodeC.createRelationshipTo(nodeB4, TestRelationshipTypes.REL_A); nodeC.createRelationshipTo(nodeB5, TestRelationshipTypes.REL_A); nodeC.createRelationshipTo(nodeB6, TestRelationshipTypes.REL_A); } private void createLargeBranchingTestCase(GraphDatabaseService graphDatabaseService) { largeBranchingTestNode = createNode(graphDatabaseService, "start", "root"); Node nodeA = createNode(graphDatabaseService, "typeA", "Value1"); Node nodeB = createNode(graphDatabaseService, "typeB", "Value2"); Node nodeC = createNode(graphDatabaseService, "typeC", "Value3"); Node nodeD = createNode(graphDatabaseService, "typeD", "Value4"); Node nodeE = createNode(graphDatabaseService, "typeE", "Value5"); Node nodeF = createNode(graphDatabaseService, "typeF", "Value6"); Node nodeF1 = createNode(graphDatabaseService, "typeF", "Value7"); Node nodeF2 = createNode(graphDatabaseService, "typeF", "Value8"); Node nodeF3 = createNode(graphDatabaseService, "typeF", "Value9"); Node nodeF4 = createNode(graphDatabaseService, "typeF", "Value10"); Node nodeF5 = createNode(graphDatabaseService, "typeF", "Value11"); Node nodeG = createNode(graphDatabaseService, "typeG", "Value6"); Node nodeG1 = createNode(graphDatabaseService, "typeG", "Value7"); Node nodeG2 = createNode(graphDatabaseService, "typeG", "Value8"); Node nodeG3 = createNode(graphDatabaseService, "typeG", "Value9"); Node nodeG4 = createNode(graphDatabaseService, "typeG", "Value10"); Node nodeG5 = createNode(graphDatabaseService, "typeG", "Value11"); Node nodeH = createNode(graphDatabaseService, "typeH", "Value7"); Node nodeI = createNode(graphDatabaseService, "typeI", "Value7"); nodeA.createRelationshipTo(largeBranchingTestNode, TestRelationshipTypes.REL_B); nodeB.createRelationshipTo(nodeA, TestRelationshipTypes.REL_B); nodeC.createRelationshipTo(nodeB, TestRelationshipTypes.REL_B); nodeD.createRelationshipTo(nodeC, TestRelationshipTypes.REL_B); nodeE.createRelationshipTo(nodeD, TestRelationshipTypes.REL_B); nodeF.createRelationshipTo(nodeE, TestRelationshipTypes.REL_B); nodeF1.createRelationshipTo(nodeE, TestRelationshipTypes.REL_B); nodeF2.createRelationshipTo(nodeE, TestRelationshipTypes.REL_B); nodeF3.createRelationshipTo(nodeE, TestRelationshipTypes.REL_B); nodeF4.createRelationshipTo(nodeE, TestRelationshipTypes.REL_B); nodeF5.createRelationshipTo(nodeE, TestRelationshipTypes.REL_B); nodeG.createRelationshipTo(nodeF, TestRelationshipTypes.REL_B); nodeG1.createRelationshipTo(nodeF1, TestRelationshipTypes.REL_B); nodeG2.createRelationshipTo(nodeF2, TestRelationshipTypes.REL_B); nodeG3.createRelationshipTo(nodeF3, TestRelationshipTypes.REL_B); nodeG4.createRelationshipTo(nodeF4, TestRelationshipTypes.REL_B); nodeG5.createRelationshipTo(nodeF5, TestRelationshipTypes.REL_B); nodeH.createRelationshipTo(nodeG, TestRelationshipTypes.REL_B); nodeH.createRelationshipTo(nodeG1, TestRelationshipTypes.REL_B); nodeH.createRelationshipTo(nodeG2, TestRelationshipTypes.REL_B); nodeH.createRelationshipTo(nodeG3, TestRelationshipTypes.REL_B); nodeH.createRelationshipTo(nodeG4, TestRelationshipTypes.REL_B); nodeH.createRelationshipTo(nodeG5, TestRelationshipTypes.REL_B); nodeI.createRelationshipTo(nodeH, TestRelationshipTypes.REL_B); } private Node createNode(GraphDatabaseService graphDatabaseService, String type, String value) { Node nodeE = graphDatabaseService.createNode(); nodeE.setProperty("type", type); nodeE.setProperty("value", value); return nodeE; } @Test public void testRelationshipsOfDifferentTypesForMotif() { MotifFinder motifFinder = new AlternativeCompleteMotifFinder(4); motifFinder.performAnalysis(new DBGraph(mixedRelationTestNode), new GraphMLCreator(new File("data/test.xml"))); System.out.println(mixedRelationTestNode.getRelationships().iterator().next().getType()); Map<String, Motif> motifs = motifFinder.getMotifs(); printMotifs(motifs); System.out.println(motifs.size()); assertTrue("Awww, motif size not as expected", motifs.size() == 3); } private void printMotifs(Map<String, Motif> motifs) { System.out.println("In printmotifs()"); System.out.println(String.format("Found %d motifs.", motifs.size())); for (String motif : motifs.keySet()) { System.out.println(String.format("%s -> #%d (%d)", motif, motifs.get(motif).getCumulativeUsage(), MotifProcessingUtils.getNumberOfGroupsInMotifString(motif))); } } @Test public void testRelationshipsOfSameTypeForMotif() { MotifFinder motifFinder = new AlternativeCompleteMotifFinder(4); motifFinder.performAnalysis(new DBGraph(sameRelationTestNode), new GraphMLCreator(new File("data/test.xml"))); Map<String, Motif> motifs = motifFinder.getMotifs(); printMotifs(motifs); System.out.println(motifs.size()); assertTrue("Awww, motif size not as expected", motifs.size() == 3); } @Test public void testRelationshipsOfSameTypeForMotifMoreComplex() { MotifFinder motifFinder = new AlternativeCompleteMotifFinder(8); motifFinder.performAnalysis(new DBGraph(sameRelationTestNodeMoreComplex), new GraphMLCreator(new File("data/test.xml"))); Map<String, Motif> motifs = motifFinder.getMotifs(); printMotifs(motifs); assertTrue("Awww, motif size not as expected.", motifs.size() == 8); } @Test public void testPatternFindLinear() { Set<String> targets = new HashSet<String>(); targets.add("typeA:{REL_B#typeB}"); TargetedMotifFinderImpl motifFinder = new TargetedMotifFinderImpl(targets); motifFinder.performAnalysis(new DBGraph(linearTestNode), new GraphMLCreator(new File("data/test.xml"))); Map<String, Motif> motifs = motifFinder.getMotifs(); printMotifs(motifs); assertTrue("Awww, motif size not as expected", motifs.size() == 1); } @Test public void testPatternFindMerge() { MotifFinder motifFinder = new AlternativeCompleteMotifFinder(8); motifFinder.performAnalysis(new DBGraph(mergeTestNode), new GraphMLCreator(new File("data/test.xml"))); Map<String, Motif> motifs = motifFinder.getMotifs(); printMotifs(motifs); assertTrue("Awww, motif size not as expected", motifs.size() == 7); } @Test public void testComplicatedCombination() { MotifFinder motifFinder = new AlternativeCompleteMotifFinder(4); motifFinder.performAnalysis(new DBGraph(complicatedCombinationTestCaseNode), new GraphMLCreator(new File("data/test.xml"))); Map<String, Motif> motifs = motifFinder.getMotifs(); System.out.println(); printMotifs(motifs); assertTrue("Awww, motif size not as expected", motifs.size() == 12); } @Test public void testLargeBranchAndMergeTest() { AlternativeCompleteMotifFinder motifFinder = new AlternativeCompleteMotifFinder(4); motifFinder.performAnalysis(new DBGraph(largeBranchAndMergeTestNode), new GraphMLCreator(new File("data/test.xml"))); Map<String, Motif> motifs = motifFinder.getMotifs(); printMotifs(motifs); assertTrue("Awww, motif size not as expected", motifs.size() == 5); } @Test public void testLargeBranchingEvent() { MotifFinder motifFinder = new AlternativeCompleteMotifFinder(8); motifFinder.performAnalysis(new DBGraph(largeBranchingTestNode), new GraphMLCreator(new File("data/test.xml"))); Map<String, Motif> motifs = motifFinder.getMotifs(); System.out.println(); printMotifs(motifs); assertTrue("Awww, motif size not as expected", motifs.size() == 22); } @Test public void testExampleISATab() { } enum TestRelationshipTypes implements RelationshipType { REL_A, REL_B } }
17,523
Java
.java
297
51
132
0.732633
ISA-tools/Automacron
1
1
0
GPL-3.0
9/5/2024, 12:33:21 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
17,523
1,887,111
IfcRailingTypeImpl.java
shenan4321_BIMplatform/generated/cn/dlb/bim/models/ifc2x3tc1/impl/IfcRailingTypeImpl.java
/** * Copyright (C) 2009-2014 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cn.dlb.bim.models.ifc2x3tc1.impl; import org.eclipse.emf.ecore.EClass; import cn.dlb.bim.models.ifc2x3tc1.Ifc2x3tc1Package; import cn.dlb.bim.models.ifc2x3tc1.IfcRailingType; import cn.dlb.bim.models.ifc2x3tc1.IfcRailingTypeEnum; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Ifc Railing Type</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link cn.dlb.bim.models.ifc2x3tc1.impl.IfcRailingTypeImpl#getPredefinedType <em>Predefined Type</em>}</li> * </ul> * * @generated */ public class IfcRailingTypeImpl extends IfcBuildingElementTypeImpl implements IfcRailingType { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IfcRailingTypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Ifc2x3tc1Package.Literals.IFC_RAILING_TYPE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IfcRailingTypeEnum getPredefinedType() { return (IfcRailingTypeEnum) eGet(Ifc2x3tc1Package.Literals.IFC_RAILING_TYPE__PREDEFINED_TYPE, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setPredefinedType(IfcRailingTypeEnum newPredefinedType) { eSet(Ifc2x3tc1Package.Literals.IFC_RAILING_TYPE__PREDEFINED_TYPE, newPredefinedType); } } //IfcRailingTypeImpl
2,214
Java
.java
69
29.782609
116
0.721703
shenan4321/BIMplatform
19
9
5
AGPL-3.0
9/4/2024, 8:22:09 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
2,214
4,632,343
OldPlayingCard.java
BogdanIancu_CTS2023/Curs08/src/ro/ase/acs/composite/OldPlayingCard.java
package ro.ase.acs.composite; public class OldPlayingCard implements SoldableItem{ @Override public double getPrice() { return 50; } @Override public void addNode(SoldableItem node) { throw new UnsupportedOperationException(); } @Override public void deleteNode(SoldableItem node) { throw new UnsupportedOperationException(); } @Override public SoldableItem getNode(int id) { throw new UnsupportedOperationException(); } }
507
Java
.java
19
21.263158
52
0.704545
BogdanIancu/CTS2023
2
1
0
GPL-3.0
9/5/2024, 12:19:57 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
507
3,119,623
TcpIpServer.java
awltech_org_parallelj/parallelj-launching-parent/parallelj-launching-api/src/main/java/org/parallelj/launching/transport/tcp/TcpIpServer.java
/* * ParallelJ, framework for parallel computing * * Copyright (C) 2010, 2011, 2012 Atos Worldline or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.parallelj.launching.transport.tcp; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.Charset; import org.apache.mina.core.service.IoAcceptor; import org.apache.mina.core.service.IoHandler; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineDecoder; import org.apache.mina.filter.logging.LoggingFilter; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; import org.parallelj.launching.LaunchingMessageKind; /** * Class representing a Parallelj RcpIpServer Server for remote launching */ @Deprecated public class TcpIpServer { private final static String ENCODING = "UTF-8"; private static final int BUFFER_READER_SIZE = 2048; private static final int IDLE_TIME = 10; private final IoAcceptor acceptor = new NioSocketAcceptor(); private String host; private int port; /** * Default constructor * * @param host * @param port * @param handler */ public TcpIpServer(final String host, final int port, final IoHandler handler) { this(host, port); this.acceptor.setHandler(handler); } /** * Default constructor * * @param host * @param port */ public TcpIpServer(final String host, final int port) { this.host = host; this.port = port; // Initialize the acceptor this.acceptor.getFilterChain().addLast("logger", new LoggingFilter()); this.acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TcpIpTextLineEncoder(Charset.forName(ENCODING)), new TextLineDecoder(Charset.forName(ENCODING)) )); this.acceptor.getSessionConfig().setReadBufferSize(BUFFER_READER_SIZE); this.acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, IDLE_TIME); } /** * Start the TcpIpServer * * @throws IOException */ public final synchronized void start() throws IOException { if (this.acceptor != null) { if (this.acceptor.getHandler() == null) { this.acceptor.setHandler(new TcpIpHandlerAdapter()); } LaunchingMessageKind.ITCPIP0001.format(this.host, this.port); this.acceptor.bind(new InetSocketAddress(this.host, this.port)); } } /** * Stop the TcpIpServer */ public final synchronized void stop() { if (this.acceptor != null) { LaunchingMessageKind.ITCPIP0002.format(); this.acceptor.dispose(true); } } public void setHandler(final IoHandler handler) { this.acceptor.setHandler(handler); } public boolean isStarted() { return this.acceptor.isActive(); } }
3,591
Java
.java
105
31.457143
83
0.753824
awltech/org.parallelj
4
2
26
LGPL-2.1
9/4/2024, 10:56:27 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,591
1,781,615
ImportBatchItemDataSource.java
proarc_proarc/proarc-webapp/src/main/java/cz/cas/lib/proarc/webapp/client/ds/ImportBatchItemDataSource.java
/* * Copyright (C) 2011 Jan Pokorsky * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cz.cas.lib.proarc.webapp.client.ds; import com.google.gwt.core.client.Callback; import com.google.gwt.core.shared.GWT; import com.smartgwt.client.data.DSCallback; import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; import com.smartgwt.client.data.DataSource; import com.smartgwt.client.data.DataSourceField; import com.smartgwt.client.data.Record; import com.smartgwt.client.data.fields.DataSourceImageField; import com.smartgwt.client.data.fields.DataSourceIntegerField; import com.smartgwt.client.data.fields.DataSourceTextField; import com.smartgwt.client.types.FieldType; import com.smartgwt.client.types.PromptStyle; import cz.cas.lib.proarc.webapp.client.ClientMessages; import cz.cas.lib.proarc.webapp.client.ClientUtils; import cz.cas.lib.proarc.webapp.client.widget.StatusView; import cz.cas.lib.proarc.webapp.shared.rest.ImportResourceApi; import java.util.ArrayList; import java.util.Arrays; /** * * @author Jan Pokorsky */ public final class ImportBatchItemDataSource extends ProarcDataSource { public static final String ID = "ImportBatchItemDataSource"; public static final String FIELD_BATCHID = ImportResourceApi.BATCHITEM_BATCHID; public static final String FIELD_FILENAME = ImportResourceApi.BATCHITEM_FILENAME; public static final String FIELD_PID = ImportResourceApi.BATCHITEM_PID; public static final String FIELD_MODEL = ImportResourceApi.BATCHITEM_MODEL; public static final String FIELD_PAGE_TYPE = ImportResourceApi.BATCHITEM_PAGETYPE; public static final String FIELD_PAGE_TYPE_LABEL = ImportResourceApi.BATCHITEM_PAGETYPELABEL; public static final String FIELD_PAGE_INDEX = ImportResourceApi.BATCHITEM_PAGEINDEX; public static final String FIELD_PAGE_NUMBER = ImportResourceApi.BATCHITEM_PAGENUMBER; public static final String FIELD_TIMESTAMP = ImportResourceApi.BATCHITEM_TIMESTAMP; public static final String FIELD_USER = ImportResourceApi.BATCHITEM_USER; /** synthetic field holding batchid and pid URL parameters */ public static final String FIELD_PREVIEW = "preview"; /** synthetic field holding batchid and pid URL parameters */ public static final String FIELD_THUMBNAIL = "thumbnail"; public ImportBatchItemDataSource() { setID(ID); setDataURL(RestConfig.URL_IMPORT_BATCH_ITEM); DataSourceField pid = new DataSourceField(FIELD_PID, FieldType.TEXT); pid.setPrimaryKey(true); DataSourceIntegerField batchId = new DataSourceIntegerField(FIELD_BATCHID); batchId.setPrimaryKey(true); batchId.setForeignKey(ImportBatchDataSource.ID + '.' + ImportBatchDataSource.FIELD_ID); DataSourceField timestamp = new DataSourceField(FIELD_TIMESTAMP, FieldType.TEXT); timestamp.setRequired(true); timestamp.setHidden(true); DataSourceTextField filename = new DataSourceTextField(FIELD_FILENAME); DataSourceTextField user = new DataSourceTextField(FIELD_USER); DataSourceTextField model = new DataSourceTextField(FIELD_MODEL); model.setForeignKey(MetaModelDataSource.ID + '.' + MetaModelDataSource.FIELD_PID); DataSourceImageField preview = new DataSourceImageField(FIELD_PREVIEW); preview.setImageURLPrefix(RestConfig.URL_DIGOBJECT_PREVIEW + "?"); DataSourceImageField thumbnail = new DataSourceImageField(FIELD_THUMBNAIL); thumbnail.setImageURLPrefix(RestConfig.URL_DIGOBJECT_THUMBNAIL + "?"); DataSourceField pageType = new DataSourceField(FIELD_PAGE_TYPE, FieldType.TEXT); DataSourceField pageTypeLabel = new DataSourceField(FIELD_PAGE_TYPE_LABEL, FieldType.TEXT); DataSourceField pageIndex = new DataSourceField(FIELD_PAGE_INDEX, FieldType.INTEGER, "Page Index"); DataSourceField pageNumber = new DataSourceField(FIELD_PAGE_NUMBER, FieldType.TEXT, "Page Number"); setFields(pid, batchId, timestamp, filename, user, model, preview, thumbnail, pageIndex, pageNumber, pageType, pageTypeLabel); setOperationBindings(RestConfig.createDeleteOperation()); setRequestProperties(RestConfig.createRestRequest(getDataFormat())); } @Override protected void transformResponse(DSResponse response, DSRequest request, Object data) { super.transformResponse(response, request, data); if (RestConfig.isStatusOk(response)) { for (Record record : response.getData()) { String pid = record.getAttribute(FIELD_PID); String batchId = record.getAttribute(FIELD_BATCHID); String imgParams = ClientUtils.format("%s=%s&%s=%s", FIELD_PID, pid, FIELD_BATCHID, batchId); record.setAttribute(FIELD_PREVIEW, imgParams); record.setAttribute(FIELD_THUMBNAIL, imgParams); } } else { // In case of any error DataSource invokes further fetches in never ending loop // Following seems to help. response.setEndRow(0); response.setTotalRows(0); } } /** * Removes list of digital objects from the given batch import. * @param callback callback to get the result * @param batchId import ID * @param pids digital object IDs */ public void delete(final Callback<Record[], String> callback, String batchId, String... pids) { DeleteTask task = new DeleteTask(this, batchId, pids, callback); task.delete(); } public static ImportBatchItemDataSource getInstance() { ImportBatchItemDataSource ds = (ImportBatchItemDataSource) DataSource.get(ID); ds = ds != null ? ds : new ImportBatchItemDataSource(); return ds; } /** * Deletes objects from a given batch import. * It splits PIDs array to chunks not to exceed URL length limit (8k). * <p>The alternative is to increase {@code Connector@maxHttpHeaderSize} * at {@code server.xml}. * <p>SmartGWT does not allow to use HTTP DELETE method with body. */ private static class DeleteTask { private static int CHUNK_LIMIT = 100; private int itemIndex = 0; private final DataSource ds; private final String batchId; private final String[] pids; private final Callback<Record[], String> callback; private final ClientMessages i18n; private final ArrayList<Record> deleted; public DeleteTask(DataSource ds, String batchId, String[] pids, Callback<Record[], String> callback) { this.ds = ds; this.pids = pids; this.callback = callback; this.i18n = GWT.create(ClientMessages.class); this.batchId = batchId; this.deleted = new ArrayList<Record>(pids.length); } public void delete() { deleteItem(); } private void deleteItem() { String[] chunk = nextChunk(); if (chunk == null) { StatusView.getInstance().show(i18n.DeleteAction_Done_Msg()); callback.onSuccess(deleted.toArray(new Record[0])); return ; } Record query = new Record(); query.setAttribute(FIELD_BATCHID, batchId); query.setAttribute(FIELD_PID, chunk); DSRequest dsRequest = new DSRequest(); dsRequest.setPromptStyle(PromptStyle.DIALOG); dsRequest.setPrompt(i18n.DeleteAction_Deleting_Msg()); // TileGrid.removeSelectedData uses queuing support in case of multi-selection. // It will require extra support on server. For now remove data in separate requests. //thumbGrid.removeSelectedData(); ds.removeData(query, new DSCallback() { @Override public void execute(DSResponse response, Object rawData, DSRequest request) { if (RestConfig.isStatusOk(response)) { ds.updateCaches(response, request); deleted.addAll(Arrays.asList(response.getData())); deleteItem(); } else { if (deleted.isEmpty()) { callback.onFailure(null); } else { callback.onSuccess(deleted.toArray(new Record[0])); callback.onFailure(null); } } } }, dsRequest); } private String[] nextChunk() { String[] chunk = null; int remainingLength = pids.length - itemIndex; if (remainingLength > 0) { if (pids.length <= CHUNK_LIMIT) { chunk = pids; } else { int sliceLength = remainingLength > CHUNK_LIMIT ? CHUNK_LIMIT : remainingLength; chunk = new String[sliceLength]; System.arraycopy(pids, itemIndex, chunk, 0, sliceLength); } itemIndex += chunk.length; } return chunk; } } }
9,880
Java
.java
196
40.979592
134
0.67499
proarc/proarc
15
9
53
GPL-3.0
9/4/2024, 8:18:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
9,880
4,627,319
Variance.java
kipe-io_kipes-sdk/streams-kafka/src/main/java/io/kipe/streams/kafka/processors/expressions/stats/Variance.java
/* * Kipes SDK for Kafka - The High-Level Event Processing SDK. * Copyright © 2023 kipe.io * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package io.kipe.streams.kafka.processors.expressions.stats; import io.kipe.streams.kafka.processors.StatsExpression; import org.apache.kafka.streams.errors.StreamsException; /** * The Variance class calculates the variance of values in a data stream using Welford's algorithm for better numerical * stability. * <p> * The fields for this statistical expression are as follows: * <pre> * | field | internal | type | description | * |-------------|----------|--------|------------------------------------------------------| * | var or varp | no | double | the variance of values at the measured value field | * | count | yes | long | the number of values processed | * | mean | yes | double | the running mean of the values | * | ssd | yes | double | the running sum of squared differences from the mean | * </pre> */ public class Variance extends StatsExpression { public static final String DEFAULT_SAMPLE_VARIANCE_FIELD = "var"; public static final String DEFAULT_POPULATION_VARIANCE_FIELD = "varp"; public enum VarianceType { SAMPLE, POPULATION } /** * Returns a new Variance instance for the specified field and variance type. * * @param fieldNameToVariance the field for which the variance will be calculated * @param varianceType the type of variance to calculate (sample or population) * @return a new Variance instance for the given field */ public static Variance var(String fieldNameToVariance, VarianceType varianceType) { String defaultField = varianceType == VarianceType.SAMPLE ? DEFAULT_SAMPLE_VARIANCE_FIELD : DEFAULT_POPULATION_VARIANCE_FIELD; return new Variance(fieldNameToVariance, varianceType, defaultField); } /** * Returns a new Variance instance for the specified field, calculating sample variance. * * @param fieldNameToVariance the field for which the variance will be calculated * @return a new Variance instance for the given field */ public static Variance var(String fieldNameToVariance) { return var(fieldNameToVariance, VarianceType.SAMPLE); } /** * Returns a new Variance instance for the specified field, calculating population variance. * * @param fieldNameToVariance the field for which the variance will be calculated * @return a new Variance instance for the given field */ public static Variance varp(String fieldNameToVariance) { return var(fieldNameToVariance, VarianceType.POPULATION); } /** * Initializes the statsFunction to calculate the variance for the specified field. */ private Variance(String fieldNameToVariance, VarianceType varianceType, String defaultField) { super(defaultField); this.statsFunction = (groupKey, value, aggregate) -> { String fieldNameCount = createInternalFieldName("count"); String fieldNameMean = createInternalFieldName("mean"); String fieldNameSsd = createInternalFieldName("ssd"); Double fieldValue = value.getDouble(fieldNameToVariance); if (fieldValue == null) { return aggregate.getDouble(this.fieldName); } double previousMean = aggregate.get(fieldNameMean, () -> 0.0); long previousCount = aggregate.get(fieldNameCount, () -> 0L); previousCount += 1; double updatedMean = previousMean + (fieldValue - previousMean) / previousCount; double previousSsd = aggregate.get(fieldNameSsd, () -> 0.0); double updatedSsd = previousSsd + (fieldValue - previousMean) * (fieldValue - updatedMean); aggregate.set(fieldNameCount, previousCount); aggregate.set(fieldNameMean, updatedMean); aggregate.set(fieldNameSsd, updatedSsd); double variance = updatedSsd / (varianceType.equals(VarianceType.POPULATION) ? previousCount : previousCount - 1); return previousCount <= 1 ? 0.0 : variance; }; } }
4,943
Java
.java
96
45.5
134
0.677766
kipe-io/kipes-sdk
2
0
3
LGPL-3.0
9/5/2024, 12:19:46 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,943
1,234,047
NumericAttribute.java
starlibs_AILibs/JAICore/jaicore-ml/src/main/java/ai/libs/jaicore/ml/core/dataset/schema/attribute/NumericAttribute.java
package ai.libs.jaicore.ml.core.dataset.schema.attribute; import org.apache.commons.lang3.math.NumberUtils; import org.api4.java.ai.ml.core.dataset.schema.attribute.IAttributeValue; import org.api4.java.ai.ml.core.dataset.schema.attribute.INumericAttribute; import org.api4.java.ai.ml.core.dataset.schema.attribute.INumericAttributeValue; public class NumericAttribute extends AAttribute implements INumericAttribute { private static final long serialVersionUID = 657993241775006166L; public NumericAttribute(final String name) { super(name); } @Override public boolean isValidValue(final Object value) { return (value == null || value instanceof Number || value instanceof INumericAttributeValue); } @Override public String getStringDescriptionOfDomain() { return "[Num] " + this.getName(); } private double getAttributeValueAsDouble(final Object attributeValue) { if (attributeValue == null || attributeValue.toString().trim().isEmpty()) { return Double.NaN; } if (attributeValue instanceof INumericAttributeValue) { return ((INumericAttributeValue) attributeValue).getValue(); } else if (attributeValue instanceof Integer) { return ((Integer) attributeValue); } else if (attributeValue instanceof Long) { return ((Long) attributeValue); } else if (attributeValue instanceof Double) { return (Double) attributeValue; } else if (attributeValue instanceof String && NumberUtils.isCreatable((String) attributeValue)) { return NumberUtils.createDouble((String) attributeValue); } else { throw new IllegalArgumentException("No valid attribute value " + attributeValue + " for attribute " + this.getClass().getName()); } } @Override public INumericAttributeValue getAsAttributeValue(final Object obj) { return new NumericAttributeValue(this, this.getAttributeValueAsDouble(obj)); } @Override public double encodeValue(final Object attributeValue) { if (!this.isValidValue(attributeValue)) { throw new IllegalArgumentException("No valid attribute value"); } return this.getAttributeValueAsDouble(attributeValue); } @Override public Double decodeValue(final double encodedAttributeValue) { return encodedAttributeValue; } @Override public IAttributeValue getAsAttributeValue(final double encodedAttributeValue) { return new NumericAttributeValue(this, encodedAttributeValue); } @Override public double toDouble(final Object object) { return this.getAttributeValueAsDouble(object); } @Override public String serializeAttributeValue(final Object value) { if (value == null) { return null; } Double doubleValue = this.getAttributeValueAsDouble(value); if (doubleValue % 1 == 0) { if (doubleValue > Integer.MAX_VALUE) { return doubleValue.longValue() + ""; } else { return doubleValue.intValue() + ""; } } return doubleValue + ""; } @Override public Double deserializeAttributeValue(final String string) { return string.equals("null") ? null : Double.parseDouble(string); } }
3,103
Java
.java
79
35.278481
133
0.762859
starlibs/AILibs
37
36
7
AGPL-3.0
9/4/2024, 7:26:07 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,103
1,947,600
PotionOfMight.java
HappyAlfred_fushigi-no-pixel-dungeon/core/src/main/java/com/fushiginopixel/fushiginopixeldungeon/items/potions/PotionOfMight.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2018 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.fushiginopixel.fushiginopixeldungeon.items.potions; import com.fushiginopixel.fushiginopixeldungeon.Badges; import com.fushiginopixel.fushiginopixeldungeon.actors.hero.Hero; import com.fushiginopixel.fushiginopixeldungeon.messages.Messages; import com.fushiginopixel.fushiginopixeldungeon.sprites.CharSprite; import com.fushiginopixel.fushiginopixeldungeon.utils.GLog; public class PotionOfMight extends Potion { { initials = 6; bones = true; } @Override public void apply( Hero hero ) { knownByUse(); if(hero.STR < hero.STRMAX) { hero.STR++; } else{ hero.STR++; hero.STRMAX++; } hero.HTBoost += 5; hero.updateHT( true ); hero.sprite.showStatus( CharSprite.POSITIVE, Messages.get(this, "msg_1") ); GLog.p( Messages.get(this, "msg_2") ); Badges.validateStrengthAttained(); } @Override public int price() { return isKnown() ? 100 * quantity : super.price(); } }
1,706
Java
.java
52
30.423077
77
0.762165
HappyAlfred/fushigi-no-pixel-dungeon
18
5
0
GPL-3.0
9/4/2024, 8:24:22 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,706
3,515,554
CtrlUnit106Validator.java
ftsrg_mondo-collab-framework/archive/mondo-access-control/CollaborationIncQuery/WTSpec/src/WTSpec/validation/CtrlUnit106Validator.java
/** * * $Id$ */ package WTSpec.validation; import WTSpec.WTCInput; import WTSpec.WTCOutput; import WTSpec.WTCTimer; /** * A sample validator interface for {@link WTSpec.CtrlUnit106}. * This doesn't really do anything, and it's not a real EMF artifact. * It was generated by the org.eclipse.emf.examples.generator.validator plug-in to illustrate how EMF's code generator can be extended. * This can be disabled with -vmargs -Dorg.eclipse.emf.examples.generator.validator=false. */ public interface CtrlUnit106Validator { boolean validate(); boolean validateInput__i1(WTCInput value); boolean validateOutput__o1(WTCOutput value); boolean validateTimer__t1(WTCTimer value); boolean validateTimer__t2(WTCTimer value); boolean validateBhvParam__bpMode(String value); }
781
Java
.java
22
33.727273
135
0.792328
ftsrg/mondo-collab-framework
3
1
13
EPL-1.0
9/4/2024, 11:30:57 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
781
1,448,293
YourkitProfilerController.java
excelsior-oss_xds-ide/product/com.excelsior.xds.core/src/com/excelsior/xds/core/utils/YourkitProfilerController.java
package com.excelsior.xds.core.utils; /** * Sample usage: * YourkitProfilerController.startProfiler(); YourkitProfilerController.startCpuProfiling(YourkitProfilerController.CPU_SAMPLING, YourkitProfilerController.DEFAULT_FILTERS); YourkitProfilerController.captureSnapshot(YourkitProfilerController.SNAPSHOT_WITHOUT_HEAP); */ public class YourkitProfilerController { private static Object profiler; public static long CPU_SAMPLING; public static long CPU_TRACING; public static long CPU_J2EE; public static long SNAPSHOT_WITHOUT_HEAP; public static long SNAPSHOT_WITH_HEAP; public static String DEFAULT_FILTERS; public static void startProfiler() { Class<?> controllerClazz; Class<?> profilingModesClazz; try { controllerClazz = Class.forName("com.yourkit.api.Controller"); profilingModesClazz = Class.forName("com.yourkit.api.ProfilingModes"); DEFAULT_FILTERS = (String)ReflectionUtils.getField(controllerClazz, "DEFAULT_FILTERS", null, true); DEFAULT_FILTERS += System.getProperty("line.separator")+"com.excelsior.asda.dashmap.core.utils.YourkitProfilerController"; DEFAULT_FILTERS += System.getProperty("line.separator")+"com.excelsior.asda.dashmap.ui.gis.JMapPaneProfiler"; System.out.println("DEFAULT_FILTERS:"+DEFAULT_FILTERS); CPU_SAMPLING = (Long)ReflectionUtils.getField(profilingModesClazz, "CPU_SAMPLING", null, true); CPU_TRACING = (Long)ReflectionUtils.getField(profilingModesClazz, "CPU_TRACING", null, true); CPU_J2EE = (Long)ReflectionUtils.getField(profilingModesClazz, "CPU_J2EE", null, true); SNAPSHOT_WITHOUT_HEAP = (Long)ReflectionUtils.getField(profilingModesClazz, "SNAPSHOT_WITHOUT_HEAP", null, true); SNAPSHOT_WITH_HEAP = (Long)ReflectionUtils.getField(profilingModesClazz, "SNAPSHOT_WITH_HEAP", null, true); } catch (Exception e) { System.out.println("Profiler not present:" + e); return; } try { profiler = controllerClazz.newInstance(); } catch (Exception e) { System.out.println("startProfiler: Profiler was active, but failed due: " + e); } } public static void takeMemorySnapshot() { if (profiler != null) { try { profiler.getClass().getMethod("forceGC").invoke(profiler); profiler.getClass().getMethod("captureMemorySnapshot").invoke(profiler); } catch (Exception e) { System.out.println("takeMemorySnapshot: Profiler was active, but failed due: " + e); } } else{ System.out.println("takeMemorySnapshot: Profiler not present"); } } public static void startCpuProfiling(long mode, String filters) { if (profiler != null) { try { profiler.getClass().getMethod("startCPUProfiling", long.class, String.class).invoke(profiler, mode, filters); } catch (Exception e) { System.out.println("startCpuProfiling: Profiler was active, but failed due: " + e); } } else{ System.out.println("startCpuProfiling: Profiler not present"); } } public static void stopCPUProfiling() { if (profiler != null) { try { profiler.getClass().getMethod("stopCPUProfiling").invoke(profiler); } catch (Exception e) { System.out.println("stopCPUProfiling: Profiler was active, but failed due: " + e); } } else{ System.out.println("stopCPUProfiling: Profiler not present"); } } public static void captureSnapshot(long snapshotFlags) { if (profiler != null) { try { String path = (String)profiler.getClass().getMethod("captureSnapshot", long.class).invoke(profiler, snapshotFlags); System.out.println(); System.out.println("Snapshot was captured to path:" + path); } catch (Exception e) { System.out.println("captureSnapshot: Profiler was active, but failed due: " + e); } } else{ System.out.println("captureSnapshot: Profiler not present"); } } }
4,108
Java
.java
92
37.554348
132
0.69258
excelsior-oss/xds-ide
26
8
0
EPL-1.0
9/4/2024, 7:51:46 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,108
4,137,225
ProtoBufRegistryConsistencyHandler.java
openbase_jul/module/storage/src/main/java/org/openbase/jul/storage/registry/ProtoBufRegistryConsistencyHandler.java
package org.openbase.jul.storage.registry; /* * #%L * JUL Storage * %% * Copyright (C) 2015 - 2022 openbase.org * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ import com.google.protobuf.AbstractMessage; import org.openbase.jul.extension.protobuf.IdentifiableMessage; import org.openbase.jul.extension.protobuf.container.ProtoBufMessageMap; /** * * @author <a href="mailto:divine@openbase.org">Divine Threepwood</a> * ConsistencyHandler can be registered at any registry type and will be informed about data changes via the processData Method. * The handler can be used to establish a registry data consistency. * @param <KEY> the registry key type. * @param <M> * @param <MB> */ public interface ProtoBufRegistryConsistencyHandler<KEY extends Comparable<KEY>, M extends AbstractMessage, MB extends M.Builder<MB>, REGISTRY extends ProtoBufRegistry<KEY, M, MB>> extends ConsistencyHandler<KEY, IdentifiableMessage<KEY, M, MB>, ProtoBufMessageMap<KEY, M, MB>, REGISTRY> { }
1,648
Java
.java
36
43.666667
289
0.76995
openbase/jul
2
2
9
LGPL-3.0
9/5/2024, 12:04:01 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,648
353,343
IslandBanCommandTest.java
BentoBoxWorld_BentoBox/src/test/java/world/bentobox/bentobox/api/commands/island/IslandBanCommandTest.java
package world.bentobox.bentobox.api.commands.island; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; import org.bukkit.scheduler.BukkitScheduler; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.stubbing.Answer; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.google.common.collect.ImmutableSet; import world.bentobox.bentobox.BentoBox; import world.bentobox.bentobox.RanksManagerBeforeClassTest; import world.bentobox.bentobox.Settings; import world.bentobox.bentobox.api.addons.Addon; import world.bentobox.bentobox.api.commands.CompositeCommand; import world.bentobox.bentobox.api.localization.TextVariables; import world.bentobox.bentobox.api.user.User; import world.bentobox.bentobox.managers.CommandsManager; import world.bentobox.bentobox.managers.IslandWorldManager; import world.bentobox.bentobox.managers.LocalesManager; import world.bentobox.bentobox.managers.PlaceholdersManager; import world.bentobox.bentobox.managers.PlayersManager; import world.bentobox.bentobox.managers.RanksManager; import world.bentobox.bentobox.util.Util; /** * @author tastybento * */ @RunWith(PowerMockRunner.class) @PrepareForTest({ Bukkit.class, BentoBox.class, Util.class }) public class IslandBanCommandTest extends RanksManagerBeforeClassTest { @Mock private CompositeCommand ic; private UUID uuid; @Mock private User user; @Mock private PlayersManager pm; @Mock private Addon addon; private IslandBanCommand ibc; @Before public void setUp() throws Exception { super.setUp(); User.setPlugin(plugin); // Command manager CommandsManager cm = mock(CommandsManager.class); when(plugin.getCommandsManager()).thenReturn(cm); // Settings Settings s = mock(Settings.class); when(plugin.getSettings()).thenReturn(s); // Player Player p = mock(Player.class); // Sometimes use Mockito.withSettings().verboseLogging() when(user.isOp()).thenReturn(false); uuid = UUID.randomUUID(); when(user.getUniqueId()).thenReturn(uuid); when(user.getPlayer()).thenReturn(p); when(user.getName()).thenReturn("tastybento"); when(user.getDisplayName()).thenReturn("&Ctastybento"); when(user.getPermissionValue(anyString(), anyInt())).thenReturn(-1); when(user.getTranslation(any())).thenAnswer(invocation -> invocation.getArgument(0, String.class)); // Parent command has no aliases when(ic.getSubCommandAliases()).thenReturn(new HashMap<>()); // Player has island to begin with when(im.hasIsland(any(), eq(uuid))).thenReturn(true); // when(im.isOwner(any(), eq(uuid))).thenReturn(true); when(plugin.getIslands()).thenReturn(im); // Has team when(im.inTeam(any(), eq(uuid))).thenReturn(true); when(island.getMemberSet()).thenReturn(ImmutableSet.of(uuid)); when(plugin.getPlayers()).thenReturn(pm); // Server & Scheduler BukkitScheduler sch = mock(BukkitScheduler.class); when(Bukkit.getScheduler()).thenReturn(sch); // Island Banned list initialization when(island.getBanned()).thenReturn(new HashSet<>()); when(island.isBanned(any())).thenReturn(false); when(island.getRank(any(User.class))).thenReturn(RanksManager.OWNER_RANK); when(im.getIsland(any(), any(User.class))).thenReturn(island); when(im.getIsland(any(), any(UUID.class))).thenReturn(island); when(im.getPrimaryIsland(any(), any())).thenReturn(island); // IWM friendly name IslandWorldManager iwm = mock(IslandWorldManager.class); when(iwm.getFriendlyName(any())).thenReturn("BSkyBlock"); when(plugin.getIWM()).thenReturn(iwm); // Server and Plugin Manager for events PluginManager pim = mock(PluginManager.class); when(Bukkit.getPluginManager()).thenReturn(pim); // Addon when(ic.getAddon()).thenReturn(addon); // Locales LocalesManager lm = mock(LocalesManager.class); when(lm.get(any(), any())).thenAnswer(invocation -> invocation.getArgument(1, String.class)); when(plugin.getLocalesManager()).thenReturn(lm); PlaceholdersManager phm = mock(PlaceholdersManager.class); when(phm.replacePlaceholders(any(), any())).thenAnswer(invocation -> invocation.getArgument(1, String.class)); // Placeholder manager when(plugin.getPlaceholdersManager()).thenReturn(phm); // Target bill - default target. Non Op, online, no ban prevention permission UUID uuid = UUID.randomUUID(); when(pm.getUUID(anyString())).thenReturn(uuid); when(mockPlayer.getName()).thenReturn("bill"); when(mockPlayer.getDisplayName()).thenReturn("&Cbill"); when(mockPlayer.getUniqueId()).thenReturn(uuid); when(mockPlayer.isOp()).thenReturn(false); when(mockPlayer.isOnline()).thenReturn(true); when(mockPlayer.hasPermission(anyString())).thenReturn(false); User.getInstance(mockPlayer); // Island Ban Command ibc = new IslandBanCommand(ic); } /** * Test method for * {@link world.bentobox.bentobox.api.commands.island.IslandBanCommand#execute(User, String, List)}. */ // Island ban command by itself // *** Error conditions *** // Ban without an island // Ban as not an owner // Ban unknown user // Ban self // Ban team mate // Ban someone you have already banned // Ban an Op // *** Working conditions *** // Ban offline user // Ban online user @Test public void testNoArgs() { assertFalse(ibc.canExecute(user, ibc.getLabel(), new ArrayList<>())); } @Test public void testNoIsland() { when(im.hasIsland(any(), eq(uuid))).thenReturn(false); //when(im.isOwner(any(), eq(uuid))).thenReturn(false); when(im.inTeam(any(), eq(uuid))).thenReturn(false); assertFalse(ibc.canExecute(user, ibc.getLabel(), Collections.singletonList("bill"))); verify(user).sendMessage("general.errors.no-island"); } @Test public void testTooLowRank() { when(island.getRank(any(User.class))).thenReturn(RanksManager.MEMBER_RANK); when(island.getRankCommand(anyString())).thenReturn(RanksManager.OWNER_RANK); assertFalse(ibc.canExecute(user, ibc.getLabel(), Collections.singletonList("bill"))); verify(user).sendMessage("general.errors.insufficient-rank", TextVariables.RANK, ""); } @Test public void testUnknownUser() { when(pm.getUUID(Mockito.anyString())).thenReturn(null); assertFalse(ibc.canExecute(user, ibc.getLabel(), Collections.singletonList("bill"))); verify(user).sendMessage("general.errors.unknown-player", "[name]", "bill"); } @Test public void testBanSelf() { when(pm.getUUID(anyString())).thenReturn(uuid); assertFalse(ibc.canExecute(user, ibc.getLabel(), Collections.singletonList("bill"))); verify(user).sendMessage("commands.island.ban.cannot-ban-yourself"); } @Test public void testBanTeamMate() { UUID teamMate = UUID.randomUUID(); when(pm.getUUID(anyString())).thenReturn(teamMate); when(island.getMemberSet()).thenReturn(ImmutableSet.of(uuid, teamMate)); when(island.inTeam(teamMate)).thenReturn(true); assertFalse(ibc.canExecute(user, ibc.getLabel(), Collections.singletonList("bill"))); verify(user).sendMessage("commands.island.ban.cannot-ban-member"); } @Test public void testBanAlreadyBanned() { UUID bannedUser = UUID.randomUUID(); when(pm.getUUID(anyString())).thenReturn(bannedUser); when(island.isBanned(eq(bannedUser))).thenReturn(true); assertFalse(ibc.canExecute(user, ibc.getLabel(), Collections.singletonList("bill"))); verify(user).sendMessage("commands.island.ban.player-already-banned"); } @Test public void testBanOp() { when(mockPlayer.isOp()).thenReturn(true); assertFalse(ibc.canExecute(user, ibc.getLabel(), Collections.singletonList("bill"))); verify(user).sendMessage("commands.island.ban.cannot-ban"); } @Test public void testBanOnlineNoBanPermission() { when(mockPlayer.hasPermission(anyString())).thenReturn(true); User.getInstance(mockPlayer); assertFalse(ibc.canExecute(user, ibc.getLabel(), Collections.singletonList("billy"))); verify(user).sendMessage("commands.island.ban.cannot-ban"); } @Test public void testBanOfflineUserSuccess() { when(mockPlayer.isOnline()).thenReturn(false); assertTrue(ibc.canExecute(user, ibc.getLabel(), Collections.singletonList("bill"))); // Allow adding to ban list when(island.ban(any(), any())).thenReturn(true); // Run execute assertTrue(ibc.execute(user, ibc.getLabel(), Collections.singletonList("bill"))); verify(user).sendMessage("commands.island.ban.player-banned", TextVariables.NAME, "bill", TextVariables.DISPLAY_NAME, "&Cbill"); checkSpigotMessage("commands.island.ban.owner-banned-you"); } @Test public void testBanOnlineUserSuccess() { assertTrue(ibc.canExecute(user, ibc.getLabel(), Collections.singletonList("bill"))); // Allow adding to ban list when(island.ban(any(), any())).thenReturn(true); assertTrue(ibc.execute(user, ibc.getLabel(), Collections.singletonList("bill"))); verify(user).sendMessage("commands.island.ban.player-banned", TextVariables.NAME, "bill", TextVariables.DISPLAY_NAME, "&Cbill"); checkSpigotMessage("commands.island.ban.owner-banned-you"); } @Test public void testCancelledBan() { assertTrue(ibc.canExecute(user, ibc.getLabel(), Collections.singletonList("bill"))); // Disallow adding to ban list - event cancelled when(island.ban(any(), any())).thenReturn(false); assertFalse(ibc.execute(user, ibc.getLabel(), Collections.singletonList("bill"))); verify(user, never()).sendMessage("commands.island.ban.player-banned", TextVariables.NAME, mockPlayer.getName(), TextVariables.DISPLAY_NAME, mockPlayer.getDisplayName()); verify(mockPlayer, never()).sendMessage("commands.island.ban.owner-banned-you"); } @Test public void testTabCompleteNoIsland() { // No island when(im.getIsland(any(), any(UUID.class))).thenReturn(null); // Set up the user User user = mock(User.class); when(user.getUniqueId()).thenReturn(UUID.randomUUID()); // Get the tab-complete list with one argument LinkedList<String> args = new LinkedList<>(); args.add(""); Optional<List<String>> result = ibc.tabComplete(user, "", args); assertFalse(result.isPresent()); // Get the tab-complete list with one letter argument args = new LinkedList<>(); args.add("d"); result = ibc.tabComplete(user, "", args); assertFalse(result.isPresent()); // Get the tab-complete list with one letter argument args = new LinkedList<>(); args.add("fr"); result = ibc.tabComplete(user, "", args); assertFalse(result.isPresent()); } @Test public void testTabComplete() { String[] names = { "adam", "ben", "cara", "dave", "ed", "frank", "freddy", "george", "harry", "ian", "joe" }; Map<UUID, String> online = new HashMap<>(); Set<UUID> banned = new HashSet<>(); Set<Player> onlinePlayers = new HashSet<>(); for (int j = 0; j < names.length; j++) { Player p = mock(Player.class); UUID uuid = UUID.randomUUID(); when(p.getUniqueId()).thenReturn(uuid); when(p.getName()).thenReturn(names[j]); online.put(uuid, names[j]); // Ban the first 3 players if (j < 3) { banned.add(uuid); } onlinePlayers.add(p); } when(island.isBanned(any(UUID.class))) .thenAnswer((Answer<Boolean>) invocation -> banned.contains(invocation.getArgument(0, UUID.class))); // Create the names when(pm.getName(any(UUID.class))).then((Answer<String>) invocation -> online .getOrDefault(invocation.getArgument(0, UUID.class), "tastybento")); // Return a set of online players when(Bukkit.getOnlinePlayers()).then((Answer<Set<Player>>) invocation -> onlinePlayers); // Set up the user User user = mock(User.class); when(user.getUniqueId()).thenReturn(UUID.randomUUID()); Player player = mock(Player.class); // Player can see every other player except Ian when(player.canSee(any(Player.class))).thenAnswer((Answer<Boolean>) invocation -> { Player p = invocation.getArgument(0, Player.class); return !p.getName().equals("ian"); }); when(user.getPlayer()).thenReturn(player); // Get the tab-complete list with no argument Optional<List<String>> result = ibc.tabComplete(user, "", new LinkedList<>()); assertFalse(result.isPresent()); // Get the tab-complete list with one argument LinkedList<String> args = new LinkedList<>(); args.add(""); result = ibc.tabComplete(user, "", args); assertFalse(result.isPresent()); // Get the tab-complete list with one letter argument args = new LinkedList<>(); args.add("d"); result = ibc.tabComplete(user, "", args); assertTrue(result.isPresent()); List<String> r = result.get().stream().sorted().toList(); // Compare the expected with the actual String[] expectedName = { "dave" }; assertTrue(Arrays.equals(expectedName, r.toArray())); // Get the tab-complete list with one letter argument args = new LinkedList<>(); args.add("fr"); result = ibc.tabComplete(user, "", args); assertTrue(result.isPresent()); r = result.get().stream().sorted().toList(); // Compare the expected with the actual String[] expected = { "frank", "freddy" }; assertTrue(Arrays.equals(expected, r.toArray())); } }
15,353
Java
.java
331
39.175227
136
0.676646
BentoBoxWorld/BentoBox
328
137
215
EPL-2.0
9/4/2024, 7:06:38 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,353
4,466,189
AdvancedPinPreferenceFragment.java
Sweet-Xu_Signal-Android-master/app/src/main/java/org/thoughtcrime/securesms/preferences/AdvancedPinPreferenceFragment.java
package org.thoughtcrime.securesms.preferences; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.preference.Preference; import com.google.android.material.snackbar.Snackbar; import org.thoughtcrime.securesms.ApplicationPreferencesActivity; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.keyvalue.SignalStore; import org.thoughtcrime.securesms.lock.v2.CreateKbsPinActivity; import org.thoughtcrime.securesms.pin.PinOptOutDialog; import org.thoughtcrime.securesms.util.TextSecurePreferences; public class AdvancedPinPreferenceFragment extends ListSummaryPreferenceFragment { private static final String PREF_ENABLE = "pref_pin_enable"; private static final String PREF_DISABLE = "pref_pin_disable"; @Override public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); } @Override public void onCreatePreferences(@Nullable Bundle savedInstanceState, String rootKey) { addPreferencesFromResource(R.xml.preferences_advanced_pin); } @Override public void onResume() { super.onResume(); updatePreferenceState(); } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (requestCode == CreateKbsPinActivity.REQUEST_NEW_PIN && resultCode == CreateKbsPinActivity.RESULT_OK) { Snackbar.make(requireView(), R.string.ApplicationPreferencesActivity_pin_created, Snackbar.LENGTH_LONG).setTextColor(Color.WHITE).show(); } } private void updatePreferenceState() { Preference enable = this.findPreference(PREF_ENABLE); Preference disable = this.findPreference(PREF_DISABLE); if (SignalStore.kbsValues().hasOptedOut()) { enable.setVisible(true); disable.setVisible(false); enable.setOnPreferenceClickListener(preference -> { onPreferenceChanged(true); return true; }); } else { enable.setVisible(false); disable.setVisible(true); disable.setOnPreferenceClickListener(preference -> { onPreferenceChanged(false); return true; }); } ((ApplicationPreferencesActivity) getActivity()).getSupportActionBar().setTitle(R.string.preferences__advanced_pin_settings); } private void onPreferenceChanged(boolean enabled) { boolean hasRegistrationLock = TextSecurePreferences.isV1RegistrationLockEnabled(requireContext()) || SignalStore.kbsValues().isV2RegistrationLockEnabled(); if (!enabled && hasRegistrationLock) { new AlertDialog.Builder(requireContext()) .setMessage(R.string.ApplicationPreferencesActivity_pins_are_required_for_registration_lock) .setCancelable(true) .setPositiveButton(android.R.string.ok, (d, which) -> d.dismiss()) .show(); } else if (!enabled) { PinOptOutDialog.show(requireContext(), () -> { updatePreferenceState(); Snackbar.make(requireView(), R.string.ApplicationPreferencesActivity_pin_disabled, Snackbar.LENGTH_SHORT).setTextColor(Color.WHITE).show(); }); } else { startActivityForResult(CreateKbsPinActivity.getIntentForPinCreate(requireContext()), CreateKbsPinActivity.REQUEST_NEW_PIN); } } }
3,498
Java
.java
77
38.519481
168
0.731199
Sweet-Xu/Signal-Android-master
2
0
0
GPL-3.0
9/5/2024, 12:14:06 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,498
4,932,197
DSCluster.java
Taulukko_taulukko-commons-ceu/system/src/main/java/com/taulukko/ceu/cassandra/datastax/DSCluster.java
package com.taulukko.ceu.cassandra.datastax; import com.datastax.driver.mapping.MappingManager; import com.taulukko.ceu.CEUException; import com.taulukko.ceu.data.Cluster; import com.taulukko.ceu.data.Configuration; import com.taulukko.ceu.data.Connection; import com.taulukko.ceu.data.Metadata; import com.taulukko.ceu.data.Metrics; public class DSCluster implements Cluster { private com.datastax.driver.core.Cluster coreCluster; private String keyspaceDefault = null; public DSCluster(com.datastax.driver.core.Cluster cluster, String keyspaceDefault) { this.coreCluster = cluster; this.keyspaceDefault = keyspaceDefault; } public com.datastax.driver.core.Cluster getCoreCluster() { return coreCluster; } /* * (non-Javadoc) * * @see com.taulukko.cassandra.datastax.Cluster#hashCode() */ @Override public int hashCode() { return coreCluster.hashCode(); } /* * (non-Javadoc) * * @see com.taulukko.cassandra.datastax.Cluster#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { return coreCluster.equals(obj); } /* * (non-Javadoc) * * @see Cluster#init() */ @Override public Cluster init() { return new DSCluster(coreCluster.init(), keyspaceDefault); } /* * (non-Javadoc) * * @see com.taulukko.cassandra.datastax.Cluster#newSession() */ @Override public Connection newSession() throws CEUException { DSConnection dsConnection = new DSConnection(this, coreCluster.newSession()); if (keyspaceDefault != null) { dsConnection.execute("USE " + keyspaceDefault + ";"); } // não precisa guardar pra manipular posteriormente ? new MappingManager(dsConnection.getCoreSession()); return dsConnection; } /* * (non-Javadoc) * * @see com.taulukko.cassandra.datastax.Cluster#toString() */ @Override public String toString() { return coreCluster.toString(); } /* * (non-Javadoc) * * @see com.taulukko.cassandra.datastax.Cluster#connect() */ @Override public Connection connect() throws CEUException { DSConnection dsConnection = null; if (keyspaceDefault != null) { dsConnection = new DSConnection(this, coreCluster.connect(keyspaceDefault)); // não precisa guardar pra manipular posteriormente ? new MappingManager(dsConnection.getCoreSession()); } else { dsConnection = new DSConnection(this, coreCluster.connect()); } return dsConnection; } /* * (non-Javadoc) * * @see com.taulukko.cassandra.datastax.Cluster#connect(java.lang.String) */ @Override public Connection connect(String keyspace) throws CEUException { DSConnection dsConnection = new DSConnection(this, coreCluster.connect(keyspace)); // não precisa guardar pra manipular posteriormente ? new MappingManager(dsConnection.getCoreSession()); return dsConnection; } /* * (non-Javadoc) * * @see com.taulukko.cassandra.datastax.Cluster#getClusterName() */ @Override public String getClusterName() { return coreCluster.getClusterName(); } /* * (non-Javadoc) * * @see com.taulukko.cassandra.datastax.Cluster#getMetadata() */ @Override public Metadata getMetadata() { return new DSMetadata(coreCluster.getMetadata()); } /* * (non-Javadoc) * * @see com.taulukko.cassandra.datastax.Cluster#getConfiguration() */ @Override public Configuration getConfiguration() { return new DSConfiguration(coreCluster.getConfiguration()); } /* * (non-Javadoc) * * @see com.taulukko.cassandra.datastax.Cluster#getMetrics() */ @Override public Metrics getMetrics() { return new DSMetrics(coreCluster.getMetrics()); } /* * (non-Javadoc) * * @see com.taulukko.cassandra.datastax.Cluster#close() */ @Override public void close() { coreCluster.close(); } /* * (non-Javadoc) * * @see com.taulukko.cassandra.datastax.Cluster#isClosed() */ @Override public boolean isClosed() { return coreCluster.isClosed(); } }
3,937
Java
.java
157
22.235669
74
0.743672
Taulukko/taulukko-commons-ceu
1
0
1
GPL-3.0
9/5/2024, 12:36:19 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,934
4,070,321
BanditLeader.java
vlehtola_darkwood/fi/darkwood/level/three/monsters/BanditLeader.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package fi.darkwood.level.three.monsters; import fi.darkwood.Monster; import fi.mirake.Local; /** * * @author Ville */ public class BanditLeader extends Monster { public BanditLeader() { super(Local.get("bandit leader"), "/images/monster/bandit_leader.png", 59); setCreatureType(super.HUMANOID); } }
437
Java
.java
17
22.352941
83
0.709135
vlehtola/darkwood
2
2
0
GPL-2.0
9/5/2024, 12:01:44 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
437
2,190,392
BUImpl.java
eclipse-emf_org_eclipse_emf/tests/org.eclipse.emf.test.common/src/org/eclipse/emf/test/models/ref/unsettable/impl/BUImpl.java
/** * Copyright (c) 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v2.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v20.html * * Contributors: * IBM - Initial API and implementation */ package org.eclipse.emf.test.models.ref.unsettable.impl; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.eclipse.emf.ecore.util.EObjectResolvingEList; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.ecore.util.InternalEList; import org.eclipse.emf.test.models.ref.unsettable.AU; import org.eclipse.emf.test.models.ref.unsettable.BU; import org.eclipse.emf.test.models.ref.unsettable.C2U; import org.eclipse.emf.test.models.ref.unsettable.DU; import org.eclipse.emf.test.models.ref.unsettable.URefPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>BU</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.eclipse.emf.test.models.ref.unsettable.impl.BUImpl#getAu <em>Au</em>}</li> * <li>{@link org.eclipse.emf.test.models.ref.unsettable.impl.BUImpl#getC2u <em>C2u</em>}</li> * <li>{@link org.eclipse.emf.test.models.ref.unsettable.impl.BUImpl#getDu <em>Du</em>}</li> * </ul> * * @generated */ public class BUImpl extends EObjectImpl implements BU { /** * The cached value of the '{@link #getAu() <em>Au</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getAu() * @generated * @ordered */ protected AU au; /** * This is true if the Au reference has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean auESet; /** * The cached value of the '{@link #getDu() <em>Du</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDu() * @generated * @ordered */ protected EList<DU> du; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected BUImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return URefPackage.Literals.BU; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public AU getAu() { if (au != null && au.eIsProxy()) { InternalEObject oldAu = (InternalEObject)au; au = (AU)eResolveProxy(oldAu); if (au != oldAu) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, URefPackage.BU__AU, oldAu, au)); } } return au; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public AU basicGetAu() { return au; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetAu(AU newAu, NotificationChain msgs) { AU oldAu = au; au = newAu; boolean oldAuESet = auESet; auESet = true; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, URefPackage.BU__AU, oldAu, newAu, !oldAuESet); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setAu(AU newAu) { if (newAu != au) { NotificationChain msgs = null; if (au != null) msgs = ((InternalEObject)au).eInverseRemove(this, URefPackage.AU__BU, AU.class, msgs); if (newAu != null) msgs = ((InternalEObject)newAu).eInverseAdd(this, URefPackage.AU__BU, AU.class, msgs); msgs = basicSetAu(newAu, msgs); if (msgs != null) msgs.dispatch(); } else { boolean oldAuESet = auESet; auESet = true; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, URefPackage.BU__AU, newAu, newAu, !oldAuESet)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicUnsetAu(NotificationChain msgs) { AU oldAu = au; au = null; boolean oldAuESet = auESet; auESet = false; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.UNSET, URefPackage.BU__AU, oldAu, null, oldAuESet); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void unsetAu() { if (au != null) { NotificationChain msgs = null; msgs = ((InternalEObject)au).eInverseRemove(this, URefPackage.AU__BU, AU.class, msgs); msgs = basicUnsetAu(msgs); if (msgs != null) msgs.dispatch(); } else { boolean oldAuESet = auESet; auESet = false; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.UNSET, URefPackage.BU__AU, null, null, oldAuESet)); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean isSetAu() { return auESet; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public C2U getC2u() { if (eContainerFeatureID() != URefPackage.BU__C2U) return null; return (C2U)eInternalContainer(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetC2u(C2U newC2u, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject)newC2u, URefPackage.BU__C2U, msgs); return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setC2u(C2U newC2u) { if (newC2u != eInternalContainer() || (eContainerFeatureID() != URefPackage.BU__C2U && newC2u != null)) { if (EcoreUtil.isAncestor(this, newC2u)) throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); NotificationChain msgs = null; if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); if (newC2u != null) msgs = ((InternalEObject)newC2u).eInverseAdd(this, URefPackage.C2U__BU, C2U.class, msgs); msgs = basicSetC2u(newC2u, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, URefPackage.BU__C2U, newC2u, newC2u)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EList<DU> getDu() { if (du == null) { du = new EObjectResolvingEList.Unsettable<DU>(DU.class, this, URefPackage.BU__DU); } return du; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void unsetDu() { if (du != null) ((InternalEList.Unsettable<?>)du).unset(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean isSetDu() { return du != null && ((InternalEList.Unsettable<?>)du).isSet(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case URefPackage.BU__AU: if (au != null) msgs = ((InternalEObject)au).eInverseRemove(this, URefPackage.AU__BU, AU.class, msgs); return basicSetAu((AU)otherEnd, msgs); case URefPackage.BU__C2U: if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); return basicSetC2u((C2U)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case URefPackage.BU__AU: return basicUnsetAu(msgs); case URefPackage.BU__C2U: return basicSetC2u(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) { switch (eContainerFeatureID()) { case URefPackage.BU__C2U: return eInternalContainer().eInverseRemove(this, URefPackage.C2U__BU, C2U.class, msgs); } return super.eBasicRemoveFromContainerFeature(msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case URefPackage.BU__AU: if (resolve) return getAu(); return basicGetAu(); case URefPackage.BU__C2U: return getC2u(); case URefPackage.BU__DU: return getDu(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case URefPackage.BU__AU: setAu((AU)newValue); return; case URefPackage.BU__C2U: setC2u((C2U)newValue); return; case URefPackage.BU__DU: getDu().clear(); getDu().addAll((Collection<? extends DU>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case URefPackage.BU__AU: unsetAu(); return; case URefPackage.BU__C2U: setC2u((C2U)null); return; case URefPackage.BU__DU: unsetDu(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case URefPackage.BU__AU: return isSetAu(); case URefPackage.BU__C2U: return getC2u() != null; case URefPackage.BU__DU: return isSetDu(); } return super.eIsSet(featureID); } } //BUImpl
11,189
Java
.java
430
21.497674
131
0.624639
eclipse-emf/org.eclipse.emf
10
13
1
EPL-2.0
9/4/2024, 8:31:57 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
11,189
4,610,978
ClassNamePatternFilterUtilsTests.java
mearvk_JUnit5/platform-tests/src/test/java/org/junit/platform/commons/util/ClassNamePatternFilterUtilsTests.java
/* * Copyright 2015-2022 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v2.0 which * accompanies this distribution and is available at * * https://www.eclipse.org/legal/epl-v20.html */ package org.junit.platform.commons.util; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.api.extension.ExecutionCondition; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.junit.platform.commons.util.classes.AExecutionConditionClass; import org.junit.platform.commons.util.classes.ATestExecutionListenerClass; import org.junit.platform.commons.util.classes.AVanillaEmpty; import org.junit.platform.commons.util.classes.BExecutionConditionClass; import org.junit.platform.commons.util.classes.BTestExecutionListenerClass; import org.junit.platform.commons.util.classes.BVanillaEmpty; import org.junit.platform.launcher.TestExecutionListener; /** * Unit tests for {@link ClassNamePatternFilterUtils}. * * @since 1.7 */ @TestInstance(Lifecycle.PER_CLASS) class ClassNamePatternFilterUtilsTests { //@formatter:off @ValueSource(strings = { "org.junit.jupiter.*", "org.junit.platform.*.NonExistentClass", "*.NonExistentClass*", "*NonExistentClass*", "AExecutionConditionClass, BExecutionConditionClass" }) //@formatter:on @ParameterizedTest void alwaysEnabledConditions(String pattern) { List<? extends ExecutionCondition> executionConditions = List.of(new AExecutionConditionClass(), new BExecutionConditionClass()); assertThat(executionConditions).filteredOn( ClassNamePatternFilterUtils.excludeMatchingClasses(pattern)).isNotEmpty(); } //@formatter:off @ValueSource(strings = { "org.junit.platform.*", "*.platform.*", "*", "*AExecutionConditionClass, *BExecutionConditionClass", "*ExecutionConditionClass" }) //@formatter:on @ParameterizedTest void alwaysDisabledConditions(String pattern) { List<? extends ExecutionCondition> executionConditions = List.of(new AExecutionConditionClass(), new BExecutionConditionClass()); assertThat(executionConditions).filteredOn( ClassNamePatternFilterUtils.excludeMatchingClasses(pattern)).isEmpty(); } //@formatter:off @ValueSource(strings = { "org.junit.jupiter.*", "org.junit.platform.*.NonExistentClass", "*.NonExistentClass*", "*NonExistentClass*", "ATestExecutionListenerClass, BTestExecutionListenerClass" }) //@formatter:on @ParameterizedTest void alwaysEnabledListeners(String pattern) { List<? extends TestExecutionListener> executionConditions = List.of(new ATestExecutionListenerClass(), new BTestExecutionListenerClass()); assertThat(executionConditions).filteredOn( ClassNamePatternFilterUtils.excludeMatchingClasses(pattern)).isNotEmpty(); } //@formatter:off @ValueSource(strings = { "org.junit.platform.*", "*.platform.*", "*", "*ATestExecutionListenerClass, *BTestExecutionListenerClass", "*TestExecutionListenerClass" }) //@formatter:on @ParameterizedTest void alwaysDisabledListeners(String pattern) { List<? extends TestExecutionListener> executionConditions = List.of(new ATestExecutionListenerClass(), new BTestExecutionListenerClass()); assertThat(executionConditions).filteredOn( ClassNamePatternFilterUtils.excludeMatchingClasses(pattern)).isEmpty(); } //@formatter:off @ValueSource(strings = { "org.junit.jupiter.*", "org.junit.platform.*.NonExistentClass", "*.NonExistentClass*", "*NonExistentClass*", "AVanillaEmpty, BVanillaEmpty" }) //@formatter:on @ParameterizedTest void alwaysEnabledClass(String pattern) { var executionConditions = List.of(new AVanillaEmpty(), new BVanillaEmpty()); assertThat(executionConditions).filteredOn( ClassNamePatternFilterUtils.excludeMatchingClasses(pattern)).isNotEmpty(); } //@formatter:off @ValueSource(strings = { "org.junit.platform.*", "*.platform.*", "*", "*AVanillaEmpty, *BVanillaEmpty", "*VanillaEmpty" }) //@formatter:on @ParameterizedTest void alwaysDisabledClass(String pattern) { var executionConditions = List.of(new AVanillaEmpty(), new BVanillaEmpty()); assertThat(executionConditions).filteredOn( ClassNamePatternFilterUtils.excludeMatchingClasses(pattern)).isEmpty(); } }
4,523
Java
.java
126
33.238095
104
0.795714
mearvk/JUnit5
2
0
3
EPL-2.0
9/5/2024, 12:19:08 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,523
1,515,996
TbNewEntityHandler.java
antonnazarov_apricot/apricot-application/apricot-ui/src/main/java/za/co/apricotdb/ui/toolbar/TbNewEntityHandler.java
package za.co.apricotdb.ui.toolbar; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Button; import za.co.apricotdb.ui.MainAppController; /** * The tool bar button: New Entity. * * @author Anton Nazarov * @since 21/09/2019 */ @Component public class TbNewEntityHandler extends TbButtonHandlerState { @Autowired MainAppController appController; @Override public void initButton(Button btn) { init(btn); btn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { if (isEnabled()) { appController.newEntity(null); } } }); } @Override public String getEnabledImageName() { return "tbNewEntityEnabled.png"; } @Override public String getDisabledImageName() { return "tbNewEntityDisabled.png"; } @Override public String getToolpitText() { return "New Entity"; } }
1,167
Java
.java
42
21.761905
62
0.679856
antonnazarov/apricot
20
2
5
GPL-3.0
9/4/2024, 7:55:26 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,167
2,487,492
WebBuffer.java
gnooth_j/src/org/armedbear/j/WebBuffer.java
/* * WebBuffer.java * * Copyright (C) 1998-2003 Peter Graves * $Id: WebBuffer.java,v 1.9 2003/08/13 15:13:51 piso Exp $ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.armedbear.j; import java.awt.AWTEvent; import java.awt.Cursor; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.io.InputStream; import java.util.Hashtable; import javax.swing.SwingUtilities; public final class WebBuffer extends Buffer implements WebConstants { private String ref; private WebHistory history; private Hashtable refs; private String contentType; private String errorText; private WebBuffer(File file, File cache, String ref) { super(); setFile(file); setCache(cache); this.ref = ref; init(); } private void init() { initializeUndo(); type = TYPE_NORMAL; forceReadOnly = true; mode = Editor.getModeList().getMode(WEB_MODE); formatter = new WebFormatter(this); setInitialized(true); } public final WebHistory getHistory() { return history; } public final void setHistory(WebHistory history) { this.history = history; } public final String getContentType() { return contentType; } public final void setContentType(String contentType) { this.contentType = contentType; } private int maxChars; private final int maxChars() { if (maxChars == 0) { Display display = Editor.currentEditor().getDisplay(); int charWidth = display.getCharWidth(); if (charWidth > 0) maxChars = display.getWidth() / charWidth - 2; else maxChars = 80; } return maxChars; } public Position getInitialDotPos() { if (ref != null) { Position pos = findRef(ref); if (pos != null) return pos; } return new Position(getFirstLine(), 0); } public static void browse(Editor editor, File file, String ref) { if (file == null) return; Buffer buf = null; // Look for existing buffer. for (BufferIterator it = new BufferIterator(); it.hasNext();) { Buffer b = it.nextBuffer(); if (b instanceof WebBuffer && b.getFile().equals(file)) { buf = b; break; } } if (buf == null) buf = createWebBuffer(file, null, ref); editor.makeNext(buf); editor.switchToBuffer(buf); } public static WebBuffer createWebBuffer(File file, File cache, String ref) { return new WebBuffer(file, cache, ref); } public Position findRef(String ref) { if (ref != null && refs != null) { Object obj = refs.get(ref); if (obj instanceof Integer) { Position pos = getPosition(((Integer) obj).intValue()); if (pos != null) pos.skipWhitespace(); return pos; } } return null; } public static void viewPage() { final Editor editor = Editor.currentEditor(); if (editor.getModeId() != HTML_MODE) return; final Buffer buffer = editor.getBuffer(); File file = buffer.getFile(); if (file == null) return; Buffer buf = null; for (BufferIterator it = new BufferIterator(); it.hasNext();) { Buffer b = it.nextBuffer(); if (b instanceof WebBuffer && file.equals(b.getFile())) { buf = b; break; } } if (buf == null) { buf = WebBuffer.createWebBuffer(file, buffer.getCache(), null); ((WebBuffer)buf).setContentType("text/html"); } editor.makeNext(buf); editor.activate(buf); } public static void viewSource() { final Editor editor = Editor.currentEditor(); final Buffer buffer = editor.getBuffer(); if (!(buffer instanceof WebBuffer)) return; final Line dotLine = editor.getDotLine(); File file = buffer.getFile(); Buffer buf = Editor.getBufferList().findBuffer(file); if (buf == null) buf = Buffer.createBuffer(file, buffer.getCache(), null); if (buf != null) { editor.makeNext(buf); editor.activate(buf); if (dotLine instanceof WebLine) { int sourceOffset = ((WebLine)dotLine).getSourceOffset(); Position pos = buf.getPosition(sourceOffset); editor.moveDotTo(pos); } } } private boolean empty = true; public int load() { if (getFirstLine() == null) setText(""); setLoaded(true); go(getFile(), 0, contentType); return LOAD_COMPLETED; } protected void loadFile(File localFile) { WebLoader loader = new WebLoader(localFile); LineSequence lines = loader.load(); if (lines != null) { try { lockWrite(); } catch (InterruptedException e) { Log.debug(e); return; } try { setFirstLine(lines.getFirstLine()); setLastLine(lines.getLastLine()); renumberOriginal(); empty = false; } finally { unlockWrite(); } } refs = loader.getRefs(); final File file = getFile(); if (file != null && file.equals(localFile)) setLastModified(localFile.lastModified()); setLoaded(true); } public Cursor getDefaultCursor(Position pos) { if (pos != null && pos.getLine() instanceof WebLine) { HtmlLineSegment segment = ((WebLine)pos.getLine()).findSegment(pos.getOffset()); if (segment != null && segment.getLink() != null) return Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); } return super.getDefaultCursor(); } public final int getMaximumColumns() { return maxChars(); } public static void followLink() { followLink(false); } public static void mouseFollowLink() { final Editor editor = Editor.currentEditor(); // If this method is invoked via a mouse event mapping, move dot to // location of mouse click first. AWTEvent e = editor.getDispatcher().getLastEvent(); if (e instanceof MouseEvent) editor.mouseMoveDotToPoint((MouseEvent) e); followLink(true); } public static void followLink(boolean exact) { final Editor editor = Editor.currentEditor(); final Buffer buffer = editor.getBuffer(); if (!(buffer instanceof WebBuffer)) return; final WebBuffer wb = (WebBuffer) buffer; if (wb.getFile() == null) return; final Line dotLine = editor.getDotLine(); if (!(dotLine instanceof WebLine)) return; final File historyFile = wb.getFile(); final int historyOffset = wb.getAbsoluteOffset(editor.getDot()); final String historyContentType = wb.getContentType(); final int dotOffset = editor.getDotOffset(); Link link = null; HtmlLineSegment segment = ((WebLine)dotLine).findSegment(dotOffset); if (segment != null) link = segment.getLink(); if (link == null) { if (exact) return; segment = findLink(dotLine, dotOffset); if (segment == null) return; link = segment.getLink(); } if (link == null) return; Debug.assertTrue(link == segment.getLink()); final String target = link.getTarget(); if (target == null) { Debug.bug("target is null"); return; } if (target.startsWith("mailto:")) { MessageDialog.showMessageDialog(editor, "Sorry, mailto URLs are not yet supported.", "Sorry..."); return; } int index = target.indexOf('#'); if (index == 0) { // It's a fragment identifier referring to a location in the same // buffer. Position pos = wb.findRef(target.substring(1)); if (pos != null) { wb.saveHistory(historyFile, historyOffset, historyContentType); editor.moveDotTo(pos); editor.setUpdateFlag(REFRAME); } return; } String filename; String ref = null; if (index >= 0) { filename = target.substring(0, index); ref = target.substring(index + 1); } else filename = target; final File destination = resolve(wb.getFile().getParentFile(), filename); if (destination.equals(wb.getFile())) { Position pos = wb.findRef(ref); if (pos != null) { wb.saveHistory(historyFile, historyOffset, historyContentType); editor.moveDotTo(pos); } return; } final HtmlLineSegment theSegment = segment; final Link theLink = link; if (destination instanceof HttpFile) { final String theRef = ref; final HttpLoadProcess httpLoadProcess = new HttpLoadProcess(wb, (HttpFile) destination); Runnable successRunnable = new Runnable() { public void run() { final String contentType = httpLoadProcess.getContentType(); Log.debug("content-type = " + contentType); boolean isImage = false; if (contentType != null && contentType.toLowerCase().startsWith("image/")) isImage = true; else { String extension = Utilities.getExtension(destination); if (extension != null) { extension = extension.toLowerCase(); if (extension.equals(".jpg") || extension.equals(".gif") || extension.equals(".png")) isImage = true; } } if (isImage) { if (theLink instanceof ImageLink) { ImageLoader loader = new ImageLoader(httpLoadProcess.getCache()); java.awt.Image image = loader.loadImage(); if (image != null) wb.insertImage(editor, dotLine, theSegment, image); } else { // Normal link. // BUG!! This isn't right either. We should display the image in // the current buffer. ImageBuffer buf = ImageBuffer.createImageBuffer(destination, httpLoadProcess.getCache(), null); editor.makeNext(buf); editor.activate(buf); editor.updateDisplay(); } return; } if (wb.loadLocalFile(httpLoadProcess.getCache(), contentType, httpLoadProcess.getCache().getEncoding())) { wb.saveHistory(historyFile, historyOffset, historyContentType); wb.setFile(httpLoadProcess.getFile()); wb.setCache(httpLoadProcess.getCache()); Position pos = null; if (theRef != null) pos = wb.findRef(theRef); if (pos == null) pos = new Position(wb.getFirstLine(), 0); wb.update(pos); } for (EditorIterator it = new EditorIterator(); it.hasNext();) { Editor ed = it.nextEditor(); if (ed != null && ed.getBuffer() == wb) ed.setDefaultCursor(); } } }; ErrorRunnable errorRunnable = new ErrorRunnable("Operation failed") { public void run() { Log.debug("followLink errorRunnable.run"); String errorText = httpLoadProcess.getErrorText(); if (errorText == null || errorText.length() == 0) errorText = "Unable to load " + destination.netPath(); setMessage(errorText); super.run(); } }; httpLoadProcess.setSuccessRunnable(successRunnable); httpLoadProcess.setErrorRunnable(errorRunnable); httpLoadProcess.setProgressNotifier(new StatusBarProgressNotifier(wb)); editor.setWaitCursor(); new Thread(httpLoadProcess).start(); } else { // Local file. String extension = Utilities.getExtension(destination); if (extension != null) { extension = extension.toLowerCase(); if (extension.equals(".jpg") || extension.equals(".gif") || extension.equals(".png")) { if (theLink instanceof ImageLink) { ImageLoader loader = new ImageLoader(destination); java.awt.Image image = loader.loadImage(); if (image != null) wb.insertImage(editor, dotLine, theSegment, image); } else { // BUG!! Should display image in same buffer. ImageBuffer buf = ImageBuffer.createImageBuffer(destination, null, null); editor.makeNext(buf); editor.activate(buf); editor.updateDisplay(); } return; } } if (wb.loadLocalFile(destination)) { wb.saveHistory(historyFile, historyOffset, historyContentType); wb.setFile(destination); wb.setCache(null); Position pos = null; if (ref != null) pos = wb.findRef(ref); if (pos == null) pos = new Position(wb.getFirstLine(), 0); wb.update(pos); } } } public static HtmlLineSegment findLink(Line line, int offset) { HtmlLineSegment segment = null; if (line instanceof WebLine) { LineSegmentList segmentList = ((WebLine)line).getSegmentList(); if (segmentList != null) { int where = 0; final int size = segmentList.size(); for (int i = 0; i < size; i++) { HtmlLineSegment seg = (HtmlLineSegment) segmentList.getSegment(i); if (seg.getLink() != null) { if (segment == null || where < offset) segment = seg; } where += seg.length(); if (where > offset && segment != null) break; } } } return segment; } private static File resolve(File base, String fileName) { while (fileName.startsWith("../")) { File parent = base.getParentFile(); if (parent != null) { base = parent; fileName = fileName.substring(3); } else break; } // Strip any remaining (i.e. bogus) lead dots. while (fileName.startsWith("../")) { fileName = fileName.substring(3); } return File.getInstance(base, fileName); } // BUG!! Optimize this - containsImageLine flag public int getDisplayHeight() { int height = 0; for (Line line = getFirstLine(); line != null; line = line.nextVisible()) height += line.getHeight(); return height; } private void insertImage(final Editor editor, final Line line, final HtmlLineSegment segment, final Image image) { final int imageHeight = image.getHeight(null); if (imageHeight == 0) return; LineSegmentList segments = ((WebLine)line).getSegmentList(); segments.removeSegment(segment); // Force next call to line.getText() to enumerate the segments again. line.setText(null); Line before; if (line.isBlank() && line.previous() != null) { // Current line is blank. Put image in its place. before = line.previous(); } else { // Put image after current line. before = line; } final int lineHeight = new TextLine("").getHeight(); final int imageWidth = image.getWidth(null); Line dotLine = null; for (int y = 0; y < imageHeight; y += lineHeight) { Rectangle r = new Rectangle(0, y, imageWidth, Math.min(lineHeight, imageHeight - y)); ImageLine imageLine = new ImageLine(image, r); imageLine.insertAfter(before); before = imageLine; if (dotLine == null) dotLine = imageLine; } renumber(); Debug.assertTrue(dotLine != null); for (EditorIterator it = new EditorIterator(); it.hasNext();) { Editor ed = it.nextEditor(); if (ed.getBuffer() == this) { ed.getDot().moveTo(dotLine, 0); ed.setMark(null); // Enforce sanity. ed.setUpdateFlag(REFRAME | REPAINT); ed.updateDisplay(); } } } public void saveHistory(File historyFile, int historyOffset, String historyContentType) { if (history == null) history = new WebHistory(); else history.truncate(); history.append(historyFile, historyOffset, historyContentType); history.reset(); } private boolean loadLocalFile(File localFile) { return loadLocalFile(localFile, "text/html"); } private boolean loadLocalFile(File localFile, String contentType) { return loadLocalFile(localFile, contentType, null); } private boolean loadLocalFile(File localFile, String contentType, String encoding) { // Look for Unicode byte order mark. If we find it, use it to // determine the encoding. InputStream inputStream; try { inputStream = localFile.getInputStream(); } catch (Exception e) { Log.error(e); errorText = "File not found"; return false; // File not found. } byte[] buf = new byte[2]; try { int bytesRead = inputStream.read(buf); inputStream.close(); if (bytesRead == 2) { byte byte1 = buf[0]; byte byte2 = buf[1]; if (byte1 == (byte) 0xfe && byte2 == (byte) 0xff) encoding = "UnicodeBig"; else if (byte1 == (byte) 0xff && byte2 == (byte) 0xfe) encoding = "UnicodeLittle"; } } catch (Exception e) { Log.error(e); return false; } try { inputStream = localFile.getInputStream(); } catch (Exception e) { Log.error(e); errorText = "File not found"; return false; // File not found. } boolean isHtml = false; if (contentType != null) { if (contentType.toLowerCase().startsWith("text/html")) isHtml = true; } else { if (Editor.getModeList().modeAccepts(HTML_MODE, localFile.getName())) isHtml = true; } try { lockWrite(); } catch (InterruptedException e) { Log.debug(e); return false; } try { empty(); if (isHtml) { loadFile(localFile); setContentType(contentType); setFormatter(new WebFormatter(this)); } else { super.load(inputStream, encoding); if (getFirstLine() == null) { // New or 0-byte file. appendLine(""); lineSeparator = System.getProperty("line.separator"); } renumberOriginal(); setContentType(contentType); Mode mode = Editor.getModeList().getModeForContentType(contentType); if (mode == null) { File file = getFile(); if (file != null) mode = Editor.getModeList().getModeForFileName(file.getName()); } if (mode != null) { setFormatter(mode.getFormatter(this)); formatter.parseBuffer(); } else setFormatter(new PlainTextFormatter(this)); } } finally { unlockWrite(); } return true; } public static void back() { final Editor editor = Editor.currentEditor(); final Buffer buffer = editor.getBuffer(); if (!(buffer instanceof WebBuffer)) return; final WebBuffer wb = (WebBuffer) buffer; WebHistory history = wb.getHistory(); if (history == null) return; boolean atEnd = history.atEnd(); WebHistoryEntry current = history.getCurrent(); WebHistoryEntry previous = history.getPrevious(); if (previous != null) { if (atEnd) history.append(wb.getFile(), wb.getAbsoluteOffset(editor.getDot()), wb.getContentType()); else if (current != null) current.setOffset(wb.getAbsoluteOffset(editor.getDot())); else Debug.bug(); if (previous.getFile().equals(wb.getFile())) wb.update(previous.getOffset()); else wb.go(previous.getFile(), previous.getOffset(), previous.getContentType()); } } public static void forward() { final Editor editor = Editor.currentEditor(); final Buffer buffer = editor.getBuffer(); if (!(buffer instanceof WebBuffer)) return; final WebBuffer wb = (WebBuffer) buffer; WebHistory history = wb.getHistory(); if (history == null) return; WebHistoryEntry current = history.getCurrent(); WebHistoryEntry next = history.getNext(); if (next != null) { if (current != null) current.setOffset(wb.getAbsoluteOffset(editor.getDot())); else Debug.bug(); if (next.getFile().equals(wb.getFile())) wb.update(next.getOffset()); else wb.go(next.getFile(), next.getOffset(), next.getContentType()); } } public static void refresh() { final Editor editor = Editor.currentEditor(); final Buffer buffer = editor.getBuffer(); if (buffer instanceof WebBuffer) ((WebBuffer)buffer).reload(editor); } private void reload(Editor editor) { final File file = getFile(); if (file instanceof HttpFile) { HttpFile httpFile = (HttpFile) file; File cache = httpFile.getCache(); if (cache != null) { if (cache.isFile()) cache.delete(); httpFile.setCache(null); } } int offset = getAbsoluteOffset(editor.getDot()); go(file, offset, contentType); } public void go(final File destination, final int offset, String contentType) { if (destination == null) return; if (destination.isLocal()) { if (loadLocalFile(destination, contentType)) { setFile(destination); update(offset); setLastModified(destination.lastModified()); } else { // Error! Runnable errorRunnable = new Runnable() { public void run() { if (empty && Editor.getBufferList().contains(WebBuffer.this)) kill(); for (EditorIterator it = new EditorIterator(); it.hasNext();) { Editor ed = it.nextEditor(); if (empty || ed.getBuffer() == WebBuffer.this) { ed.updateLocation(); ed.updateDisplay(); } } if (errorText == null) errorText = "Unable to load " + destination.canonicalPath(); MessageDialog.showMessageDialog(errorText, "Error"); } }; SwingUtilities.invokeLater(errorRunnable); } return; } // Destination is not local. if (destination.equals(getFile())) { File cache = getCache(); if (cache != null && cache.isFile()) { // We have a cache. if (loadLocalFile(cache, contentType)) { setFile(destination); update(offset); } return; } } Debug.assertTrue(destination instanceof HttpFile); final HttpFile httpFile = (HttpFile) destination; File cache = httpFile.getCache(); if (cache != null) { if (cache.isFile()) { if (contentType == null) contentType = httpFile.getContentType(); if (loadLocalFile(cache, contentType)) { setFile(destination); setCache(cache); update(offset); } return; } cache = null; httpFile.setCache(null); } Debug.assertTrue(cache == null); Log.debug("go cache is null"); final File oldFile = getFile(); setFile(destination); final HttpLoadProcess httpLoadProcess = new HttpLoadProcess(this, httpFile); Runnable httpSuccessRunnable = new Runnable() { public void run() { File localCache = httpLoadProcess.getCache(); if (localCache != null && localCache.isFile()) { if (loadLocalFile(localCache, httpLoadProcess.getContentType(), localCache.getEncoding())) { setFile(httpLoadProcess.getFile()); setCache(localCache); setContentType(httpLoadProcess.getContentType()); update(offset); } } } }; Runnable httpCancelRunnable = new Runnable() { public void run() { setFile(oldFile); setBusy(false); if (empty && Editor.getBufferList().contains(WebBuffer.this)) kill(); for (EditorIterator it = new EditorIterator(); it.hasNext();) { Editor ed = it.nextEditor(); if (ed != null && ed.getBuffer() == WebBuffer.this) { ed.status("Transfer cancelled"); ed.setDefaultCursor(); } } Editor.currentEditor().updateDisplay(); MessageDialog.showMessageDialog("Transfer cancelled", httpFile.netPath()); } }; ErrorRunnable httpErrorRunnable = new ErrorRunnable("Load failed") { public void run() { setFile(oldFile); setBusy(false); if (empty && Editor.getBufferList().contains(WebBuffer.this)) kill(); if (!httpLoadProcess.cancelled()) { errorText = httpLoadProcess.getErrorText(); if (errorText == null || errorText.length() == 0) errorText = "Unable to load " + httpFile.netPath(); setMessage(errorText); } super.run(); } }; httpLoadProcess.setSuccessRunnable(httpSuccessRunnable); httpLoadProcess.setCancelRunnable(httpCancelRunnable); httpLoadProcess.setErrorRunnable(httpErrorRunnable); httpLoadProcess.setProgressNotifier(new StatusBarProgressNotifier(WebBuffer.this)); httpLoadProcess.start(); } private void update(int offset) { Position pos = getPosition(offset); if (pos == null) pos = new Position(getFirstLine(), 0); setBusy(false); update(pos); } private void update(Position pos) { for (EditorIterator it = new EditorIterator(); it.hasNext();) { Editor ed = it.nextEditor(); if (ed.getBuffer() == this) { ed.setDot(pos.copy()); ed.setMark(null); ed.moveCaretToDotCol(); ed.setTopLine(getFirstLine()); ed.setUpdateFlag(REFRAME); ed.repaintDisplay(); ed.updateDisplay(); ed.updateLocation(); } } Sidebar.setUpdateFlagInAllFrames(SIDEBAR_BUFFER_LIST_CHANGED); Sidebar.repaintBufferListInAllFrames(); Editor.currentEditor().status("Loading complete"); } public boolean isTransient() { if (super.isTransient()) return true; File file = getFile(); if (file != null && file.isLocal()) { if (file.equals(Help.getBindingsFile())) return true; File dir = file.getParentFile(); if (dir != null && dir.equals(Help.getDocumentationDirectory())) return true; } return false; } public boolean save() { // We shouldn't be trying to save a WebBuffer. Debug.bug(); return true; } public static void copyLink() { final Editor editor = Editor.currentEditor(); final Buffer buffer = editor.getBuffer(); if (buffer instanceof WebBuffer) { Position pos = editor.getDot(); if (pos != null && pos.getLine() instanceof WebLine) { HtmlLineSegment segment = ((WebLine)pos.getLine()).findSegment(pos.getOffset()); if (segment != null) { Link link = segment.getLink(); if (link == null) return; String copy = null; String target = link.getTarget(); if (target == null) return; if (target.startsWith("mailto:")) { copy = target; } else { int index = target.indexOf('#'); String filename; String ref = null; if (index == 0) { filename = buffer.getFile().netPath(); ref = target; } else if (index > 0) { filename = target.substring(0, index); ref = target.substring(index); } else filename = target; final File destination = resolve(buffer.getFile().getParentFile(), filename); if (destination != null) { copy = destination.netPath(); if (ref != null) copy = copy.concat(ref); } } if (copy != null) { KillRing killRing = editor.getKillRing(); killRing.appendNew(copy); killRing.copyLastKillToSystemClipboard(); editor.status("Link copied to clipboard"); } } } } } }
33,930
Java
.java
897
24.74359
126
0.513647
gnooth/j
7
3
0
GPL-2.0
9/4/2024, 9:40:04 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
33,930
965,729
package-info.java
sakerbuild_saker_build/thirdparty/rmi/api/src/saker/build/thirdparty/saker/rmi/io/wrap/package-info.java
/* * Copyright (C) 2020 Bence Sipka * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Package for RMI wrapping related classes. * * @see RMIWrapper */ @PublicApi package saker.build.thirdparty.saker.rmi.io.wrap; import saker.apiextract.api.PublicApi;
827
Java
.java
23
33.043478
73
0.739726
sakerbuild/saker.build
55
1
11
GPL-3.0
9/4/2024, 7:10:21 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
827
3,498,568
GraphicAssessmentComponent.java
openhealthcare_openMAXIMS/openmaxims_workspace/Assessment/src/ims/assessment/domain/GraphicAssessmentComponent.java
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.assessment.domain; // Generated from form domain impl public interface GraphicAssessmentComponent extends ims.domain.DomainInterface { }
1,851
Java
.java
27
66.37037
112
0.454396
openhealthcare/openMAXIMS
3
1
0
AGPL-3.0
9/4/2024, 11:30:20 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,851
1,853,697
CustomModelsInfo.java
Alfresco_alfresco-data-model/src/main/java/org/alfresco/repo/dictionary/CustomModelsInfo.java
/* * #%L * Alfresco Data model classes * %% * Copyright (C) 2005 - 2016 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of * the paid license agreement will prevail. Otherwise, the software is * provided under the following open source license terms: * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.alfresco.repo.dictionary; /** * A simple POJO to encapsulate the custom models' statistics information. * * @author Jamal Kaabi-Mofrad */ public class CustomModelsInfo { private int numberOfActiveModels; private int numberOfActiveTypes; private int numberOfActiveAspects; public int getNumberOfActiveModels() { return this.numberOfActiveModels; } public void setNumberOfActiveModels(int numberOfActiveModels) { this.numberOfActiveModels = numberOfActiveModels; } public int getNumberOfActiveTypes() { return this.numberOfActiveTypes; } public void setNumberOfActiveTypes(int numberOfActiveTypes) { this.numberOfActiveTypes = numberOfActiveTypes; } public int getNumberOfActiveAspects() { return this.numberOfActiveAspects; } public void setNumberOfActiveAspects(int numberOfActiveAspects) { this.numberOfActiveAspects = numberOfActiveAspects; } }
2,109
Java
.java
61
29.590164
79
0.72687
Alfresco/alfresco-data-model
16
18
3
LGPL-3.0
9/4/2024, 8:20:57 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
2,109
4,091,093
CacheIdResolverTest.java
nmdp-bioinformatics_genotype-list/gl-service/src/test/java/org/nmdp/gl/service/cache/CacheIdResolverTest.java
/* gl-service URI-based RESTful service for the gl project. Copyright (c) 2012-2015 National Marrow Donor Program (NMDP) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; with out even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. > http://www.fsf.org/licensing/licenses/lgpl.html > http://www.opensource.org/licenses/lgpl-license.php */ package org.nmdp.gl.service.cache; import org.nmdp.gl.Allele; import org.nmdp.gl.AlleleList; import org.nmdp.gl.Genotype; import org.nmdp.gl.GenotypeList; import org.nmdp.gl.Haplotype; import org.nmdp.gl.Locus; import org.nmdp.gl.MultilocusUnphasedGenotype; import org.nmdp.gl.service.AbstractIdResolverTest; import org.nmdp.gl.service.IdResolver; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.ImmutableList; /** * Unit test for CacheIdResolver. */ public final class CacheIdResolverTest extends AbstractIdResolverTest { @Override protected IdResolver createIdResolver() { Cache<String, Locus> loci = CacheBuilder.newBuilder().build(); Cache<String, Allele> alleles = CacheBuilder.newBuilder().build(); Cache<String, AlleleList> alleleLists = CacheBuilder.newBuilder().build(); Cache<String, Haplotype> haplotypes = CacheBuilder.newBuilder().build(); Cache<String, Genotype> genotypes = CacheBuilder.newBuilder().build(); Cache<String, GenotypeList> genotypeLists = CacheBuilder.newBuilder().build(); Cache<String, MultilocusUnphasedGenotype> multilocusUnphasedGenotypes = CacheBuilder.newBuilder().build(); Locus locus = new Locus(validLocusId, "HLA-A"); Allele allele = new Allele(validAlleleId, "A01234", "HLA-A*01:01:01:01", locus); AlleleList alleleList0 = new AlleleList(validAlleleListId, allele); AlleleList alleleList1 = new AlleleList(validAlleleListId, allele); Haplotype haplotype0 = new Haplotype(validHaplotypeId, alleleList0); Haplotype haplotype = new Haplotype(validHaplotypeId, ImmutableList.of(alleleList0, alleleList1)); Genotype genotype = new Genotype("http://immunogenomics.org/genotype/0", haplotype0); GenotypeList genotypeList0 = new GenotypeList(validGenotypeListId, genotype); GenotypeList genotypeList1 = new GenotypeList(validGenotypeListId, genotype); MultilocusUnphasedGenotype multilocusUnphasedGenotype = new MultilocusUnphasedGenotype(validMultilocusUnphasedGenotypeId, ImmutableList.of(genotypeList0, genotypeList1)); loci.asMap().put(validLocusId, locus); alleles.asMap().put(validAlleleId, allele); alleleLists.asMap().put(validAlleleListId, alleleList0); haplotypes.asMap().put(validHaplotypeId, haplotype); genotypes.asMap().put(validGenotypeId, genotype); genotypeLists.asMap().put(validGenotypeListId, genotypeList0); multilocusUnphasedGenotypes.asMap().put(validMultilocusUnphasedGenotypeId, multilocusUnphasedGenotype); return new CacheIdResolver(loci, alleles, alleleLists, haplotypes, genotypes, genotypeLists, multilocusUnphasedGenotypes); } }
3,773
Java
.java
63
54.349206
178
0.764738
nmdp-bioinformatics/genotype-list
2
7
21
LGPL-3.0
9/5/2024, 12:02:29 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,773
3,859,857
ArbitraryPrecisionDemo.java
JLinAlg_JLinAlg/src/test/java/org/jlinalg/demo/ArbitraryPrecisionDemo.java
/* * This file is part of JLinAlg (<http://jlinalg.sourceforge.net/>). * * JLinAlg is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * JLinAlg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with JLinALg. If not, see <http://www.gnu.org/licenses/>. */ package org.jlinalg.demo; import org.jlinalg.DivisionByZeroException; import org.jlinalg.rational.Rational; /** * Example that shows how easily simple floating point arithmetic can go wrong. * Only with arbitrary precision your code will realize that you are dividing by * zero. * * @author Andreas Keilhauer */ public class ArbitraryPrecisionDemo { private final static String INTERMEDIATE_CALCULATION_STR = "(3 / 5000) * 5000"; private final static String FIRST_CALCULATION_STR = "1 / ((3 / 5000) * 5000 + 3)"; /** * start the demonstration * * @param argv * is ignored */ public static void main(String[] argv) { demoFloat(); demoDouble(); demoArbitraryPrecision(); } private static void demoFloat() { System.out.println("============================================"); System.out.println("Demo Float:"); float intermediateResult = (3.0f / 5000.0f) * 5000.0f; System.out.println(INTERMEDIATE_CALCULATION_STR + " = " + intermediateResult + " (only slightly wrong)"); float wrongResult = 1.0f / (intermediateResult - 3.0f); System.out.println(FIRST_CALCULATION_STR + " = " + wrongResult + " (wrong) "); System.out.println("116 / 406 = " + (116.0f / 406.0f) + " (not exact and bulky)"); } private static void demoDouble() { System.out.println("============================================"); System.out.println("Demo Double: "); double intermediateResult = (3.0 / 5000.0) * 5000.0; System.out.println(INTERMEDIATE_CALCULATION_STR + " = " + intermediateResult + " (only slightly wrong)"); double wrongResult = 1.0 / (intermediateResult - 3.0); System.out.println(FIRST_CALCULATION_STR + " = " + wrongResult + " (wrong)"); System.out.println("116 / 406 = " + (116.0 / 406.0) + " (not exact and bulky)"); } private static void demoArbitraryPrecision() { System.out.println("============================================"); System.out.println("Demo Rational with arbitrary precision:"); Rational one = Rational.FACTORY.get(1.0); Rational three = Rational.FACTORY.get(3.0); Rational fiveThousand = Rational.FACTORY.get(5000.0); Rational intermediateResult = (three.divide(fiveThousand)) .multiply(fiveThousand); System.out.println(INTERMEDIATE_CALCULATION_STR + " = " + intermediateResult + " (correct)"); try { // This will throw a DivisionByZeroException one.divide(intermediateResult.subtract(three)); } catch (DivisionByZeroException d) { System.out.println(FIRST_CALCULATION_STR + " => Division by zero detected. (correct)"); } Rational oneHundredSixteen = Rational.FACTORY.get(116); Rational fourHundredSix = Rational.FACTORY.get(406); System.out.println("116 / 406 = " + oneHundredSixteen.divide(fourHundredSix) + " (exact and concise solution)"); } }
3,545
Java
.java
93
35.247312
83
0.687772
JLinAlg/JLinAlg
3
0
0
LGPL-3.0
9/4/2024, 11:46:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,545
2,168,629
ServerPlayer3D.java
pama1234_just-some-other-libgdx-game/game0001/game0001-server/src/main/java/pama1234/server/game/app/server0002/game/net/data/ServerPlayer3D.java
package pama1234.server.game.app.server0002.game.net.data; import pama1234.math.gdx.temp.ServerFrustum; import pama1234.math.physics.PathPoint3D; import pama1234.util.UtilServer; import pama1234.util.entity.ServerPoint3DEntity; public class ServerPlayer3D extends ServerPoint3DEntity<UtilServer,PathPoint3D>{ // public String name; public PlayerInfo3D info; public ServerFrustum viewFrustum; // public ServerPlayer3D(ServerCore p,String name,PathPoint3D in) { public ServerPlayer3D(String name,PathPoint3D in) {//TODO super(null,in); info=new PlayerInfo3D(name,in); } // public ServerPlayer3D(ServerCore p,String name,float x,float y,float z) { public ServerPlayer3D(String name,float x,float y,float z) { this(name,new PathPoint3D(x,y,z)); } @Override public void update() { // viewFrustum. } @Override public void display() {} @Override public void dispose() {} @Override public void init() {} @Override public void pause() {} @Override public void resume() {} public String name() { return info.name; } }
1,078
Java
.java
36
27
80
0.756731
pama1234/just-some-other-libgdx-game
12
4
3
AGPL-3.0
9/4/2024, 8:31:22 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,078
1,284,914
ProcessingToolHeadPickaxe.java
Nukepowered_GregTech4/src/main/java/gregtechmod/loaders/oreprocessing/ProcessingToolHeadPickaxe.java
package gregtechmod.loaders.oreprocessing; import java.util.List; import gregtechmod.api.enums.GT_ToolDictNames; import gregtechmod.api.enums.Materials; import gregtechmod.api.enums.OrePrefixes; import gregtechmod.api.enums.SubTag; import gregtechmod.api.interfaces.IOreRecipeRegistrator; import gregtechmod.api.util.GT_ModHandler; import gregtechmod.api.util.GT_Utility; import gregtechmod.api.util.OreDictEntry; import gregtechmod.common.RecipeHandler; import net.minecraft.item.ItemStack; public class ProcessingToolHeadPickaxe implements IOreRecipeRegistrator { public ProcessingToolHeadPickaxe() { OrePrefixes.toolHeadPickaxe.add(this); } public void registerOre(OrePrefixes aPrefix, List<OreDictEntry> entries) { for (OreDictEntry entry : entries) { Materials aMaterial = this.getMaterial(aPrefix, entry); if (this.isExecutable(aPrefix, aMaterial) && !aMaterial.contains(SubTag.NO_SMASHING)) { for (ItemStack aStack : entry.ores) { RecipeHandler.executeOnFinish(() -> { GT_ModHandler.addCraftingRecipe(GT_Utility.copyAmount(1L, aStack), false, true, new Object[] { "PII", "F H", Character.valueOf('P'), OrePrefixes.plate.get(aMaterial), Character.valueOf('I'), OrePrefixes.ingot.get(aMaterial), Character.valueOf('H'), GT_ToolDictNames.craftingToolHardHammer, Character.valueOf('F'), GT_ToolDictNames.craftingToolFile }); }); } } } } }
1,429
Java
.java
33
39.666667
94
0.774982
Nukepowered/GregTech4
30
17
9
GPL-3.0
9/4/2024, 7:31:27 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,429
1,681,335
Isomorphism.java
CvO-Theory_apt/src/module/uniol/apt/analysis/isomorphism/Isomorphism.java
/*- * APT - Analysis of Petri Nets and labeled Transition systems * Copyright (C) 2012-2015 Members of the project group APT * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package uniol.apt.analysis.isomorphism; import org.apache.commons.collections4.BidiMap; import org.apache.commons.collections4.bidimap.DualHashBidiMap; import uniol.apt.adt.ts.State; /** * This class represents an isomorphism. It is needed for the module system. * @author Uli Schlachter */ public class Isomorphism extends DualHashBidiMap<State, State> { public static final long serialVersionUID = 0x1l; /** * Construct a Isomorphism from the given map. * @param m The map to copy. */ public Isomorphism(BidiMap<? extends State, ? extends State> m) { super(m); } } // vim: ft=java:noet:sw=8:sts=8:ts=8:tw=120
1,484
Java
.java
37
38.081081
76
0.765441
CvO-Theory/apt
19
9
2
GPL-2.0
9/4/2024, 8:14:07 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,484
424,803
EBEEvents.java
FoundationGames_EnhancedBlockEntities/src/main/java/foundationgames/enhancedblockentities/event/EBEEvents.java
package foundationgames.enhancedblockentities.event; import net.fabricmc.fabric.api.event.Event; import net.fabricmc.fabric.api.event.EventFactory; import net.minecraft.client.render.model.ModelLoader; import net.minecraft.resource.ResourceManager; import net.minecraft.util.profiler.Profiler; public enum EBEEvents {; public static final Event<Runnable> RESOURCE_RELOAD = EventFactory.createArrayBacked(Runnable.class, (callbacks) -> () -> { for (var event : callbacks) { event.run(); } }); }
532
Java
.java
13
37
127
0.762089
FoundationGames/EnhancedBlockEntities
232
57
106
LGPL-3.0
9/4/2024, 7:07:11 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
532
1,967,286
PodKube.java
dlr-eoc_prosEO/planner/src/main/java/de/dlr/proseo/planner/rest/model/PodKube.java
/** * PodKube.java * * © 2019 Prophos Informatik GmbH */ package de.dlr.proseo.planner.rest.model; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import de.dlr.proseo.model.rest.model.PlannerPod; import io.kubernetes.client.openapi.models.V1Job; /** * Handle a Kubernetes pod/job * * @author Ernst Melchinger * */ public class PodKube extends PlannerPod { private static final long serialVersionUID = 287477937477814477L; private static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("dd.MM.uuuu' 'HH:mm:ss").withZone(ZoneId.of("UTC")); /** * Set instance variables and convert data to text * * @param job Kubernetes job */ public PodKube(V1Job job) { super(); if (job != null) { this.id = job.getMetadata().getUid(); this.name = job.getMetadata().getName(); this.starttime = ""; this.completiontime = ""; this.succeded = ""; this.type = ""; this.status = ""; if (job.getStatus() != null) { if (job.getStatus().getStartTime() != null) { starttime = timeFormatter.format(job.getStatus().getStartTime().toInstant()); type = "running"; } if (job.getStatus().getCompletionTime() != null) { completiontime = timeFormatter.format(job.getStatus().getCompletionTime().toInstant()); } if (job.getStatus() != null) { if (job.getStatus().getSucceeded() != null) { succeded = job.getStatus().getSucceeded().toString(); } if (job.getStatus().getConditions() != null && job.getStatus().getConditions().size() > 0) { type = job.getStatus().getConditions().get(0).getType(); status = job.getStatus().getConditions().get(0).getStatus(); } } } } } /** * @return true if job has been completed */ public boolean isCompleted() { return (this.hasStatus("complete") || type.equalsIgnoreCase("completed")); } /** * @param status to look for * @return true if job state equals status or Kubernetes job state and type is completed */ public boolean hasStatus(String status) { if (type.equalsIgnoreCase(status) || (status.equalsIgnoreCase("complete") && type.equalsIgnoreCase("completed"))) { return true; } else { return false; } } }
2,222
Java
.java
72
27.416667
130
0.684874
dlr-eoc/prosEO
14
1
59
GPL-3.0
9/4/2024, 8:24:57 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,222
2,172,602
CreateList.java
bengal-social_megalodon/mastodon/src/main/java/org/joinmastodon/android/api/requests/lists/CreateList.java
package org.joinmastodon.android.api.requests.lists; import org.joinmastodon.android.api.MastodonAPIRequest; import org.joinmastodon.android.model.ListTimeline; public class CreateList extends MastodonAPIRequest<ListTimeline> { public CreateList(String title, ListTimeline.RepliesPolicy repliesPolicy) { super(HttpMethod.POST, "/lists", ListTimeline.class); Request req = new Request(); req.title = title; req.repliesPolicy = repliesPolicy; setRequestBody(req); } public static class Request { public String title; public ListTimeline.RepliesPolicy repliesPolicy; } }
589
Java
.java
16
34.5
76
0.819298
bengal-social/megalodon
15
1
0
GPL-3.0
9/4/2024, 8:31:40 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
589
4,393,393
ValueObject.java
carte018_CAR/arpsi/src/main/java/edu/internet2/consent/arpsi/model/ValueObject.java
/* * Copyright 2015 - 2019 Duke University This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License Version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License Version 2 along with this program. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0.txt>. */ package edu.internet2.consent.arpsi.model; import java.util.Objects; import javax.persistence.Embeddable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; @Embeddable @Entity public class ValueObject { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @JsonIgnore private Long valueKey; private String value; @JsonIgnore public Long getValueKey() { return valueKey; } @JsonIgnore public void setValueKey(Long valueKey) { this.valueKey = valueKey; } @JsonProperty("value") public String getValue() { return value; } @JsonProperty("value") public void setValue(String value) { this.value = value; } public ValueObject(String x) { this.value = x; } public ValueObject() { // do nothing } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || this.getClass() != o.getClass()) { return false; } ValueObject v = (ValueObject) o; return (v.getValue().equals(this.getValue())); } @Override public int hashCode() { return Objects.hash(value); } @Override public String toString() { return "value="+value; } }
1,998
Java
.java
71
25.380282
98
0.760504
carte018/CAR
2
0
53
GPL-2.0
9/5/2024, 12:11:26 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,998
4,982,844
MemArrayAccess.java
riedelcastro_thebeast/src/thebeast/nodmem/expression/MemArrayAccess.java
package thebeast.nodmem.expression; import thebeast.nod.expression.ArrayAccess; import thebeast.nod.expression.ArrayExpression; import thebeast.nod.expression.ExpressionVisitor; import thebeast.nod.expression.IntExpression; import thebeast.nod.type.Type; /** * Created by IntelliJ IDEA. User: s0349492 Date: 23-Jan-2007 Time: 17:28:15 */ public abstract class MemArrayAccess<T extends Type> extends AbstractMemExpression<T> implements ArrayAccess<T> { private IntExpression index; private ArrayExpression array; public MemArrayAccess(T type, ArrayExpression array, IntExpression index) { super(type); this.array = array; this.index = index; } public ArrayExpression array() { return array; } public IntExpression index() { return index; } }
785
Java
.java
24
29.875
113
0.789404
riedelcastro/thebeast
1
0
10
LGPL-3.0
9/5/2024, 12:38:04 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
785
2,480,637
OptimizeDistance.java
kouylekov_edits/edits-genetic/src/main/java/org/edits/genetic/OptimizeDistance.java
package org.edits.genetic; import java.util.HashMap; import java.util.List; import java.util.Map; import lombok.Getter; import lombok.extern.log4j.Log4j; import org.edits.distance.algorithm.EditDistanceAlgorithm; import org.edits.engines.thread.EditsThread; import org.edits.etaf.AnnotatedEntailmentPair; import org.jgap.Chromosome; import org.jgap.Configuration; import org.jgap.Genotype; import org.jgap.IChromosome; import org.jgap.impl.BooleanGene; import org.jgap.impl.DefaultConfiguration; import org.jgap.impl.DoubleGene; import org.jgap.impl.job.MaxFunction; import com.google.common.collect.Lists; import com.google.common.util.concurrent.AtomicDouble; @Log4j public class OptimizeDistance extends MaxFunction { private static final long serialVersionUID = 1L; private final EditDistanceAlgorithm algorithm; private Map<String, Double> cache; @Getter private final AlgorithmInitializator initializator; private final int iterations; private GeneticResult result; private List<GeneticResult> results; private final List<AnnotatedEntailmentPair> training; public OptimizeDistance(EditDistanceAlgorithm algorithm_, List<AnnotatedEntailmentPair> training_, int iterations_) { algorithm = algorithm_; iterations = iterations_; initializator = new AlgorithmInitializator(algorithm_); training = training_; cache = new HashMap<String, Double>(); } @Override public double evaluate(IChromosome a_subject) { EditsChromosome ec = new EditsChromosome(a_subject); String key = ec.key(); if (cache.containsKey(key)) return cache.get(key); try { initializator.initialize(algorithm, ec); log.debug(AlgorithmInitializator.toString(algorithm)); final AtomicDouble distd = new AtomicDouble(0); EditsThread<AnnotatedEntailmentPair> thread = new EditsThread<AnnotatedEntailmentPair>() { @Override public void process(AnnotatedEntailmentPair p) throws Exception { double score = Double.parseDouble(p.getAttributes().get("score")); double ns = 5 * (1 - algorithm.distance(p.getT().get(0), p.getH().get(0), p.getId())); distd.addAndGet(Math.abs(score - ns)); } }; thread.start(training.iterator()); double dist = 5.0 - distd.get() / training.size(); GeneticResult r = new GeneticResult(dist, ec); log.debug(r.getValue()); if (result == null || result.getValue() < dist) result = r; cache.put(key, dist); results.add(r); return dist; } catch (Exception e1) { e1.printStackTrace(); System.exit(1); } cache.put(key, 0.0); return 0; } public GeneticResult run(boolean useBooleanGenes) throws Exception { results = Lists.newArrayList(); result = null; cache = new HashMap<String, Double>(); Configuration.reset(); DefaultConfiguration gaConf = new DefaultConfiguration(); int chromeSize = initializator.size(algorithm); IChromosome sampleChromosome = null; if (useBooleanGenes) sampleChromosome = new Chromosome(gaConf, new BooleanGene(gaConf), chromeSize); else sampleChromosome = new Chromosome(gaConf, new DoubleGene(gaConf, 0, 1), chromeSize); gaConf.setSampleChromosome(sampleChromosome); gaConf.setPopulationSize(20); gaConf.setFitnessFunction(this); Genotype genotype = Genotype.randomInitialGenotype(gaConf); genotype.evolve(iterations); return result; } }
3,318
Java
.java
91
33.571429
118
0.776463
kouylekov/edits
7
2
0
LGPL-3.0
9/4/2024, 9:39:31 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,318
1,928,430
ShaclInValidationTest.java
eclipse_lyo/validation/src/test/java/org/eclipse/lyo/validation/ShaclInValidationTest.java
/* * Copyright (c) 2020 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License 1.0 * which is available at http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause */ /** * @since 2.3.0 */ package org.eclipse.lyo.validation; import java.math.BigInteger; import java.net.URI; import java.util.Date; import org.junit.Assert; import org.junit.Test; /** * The Class ShaclInValidationTest. */ public class ShaclInValidationTest { /** The a resource. */ AResource aResource; /** * Shacl in negativetest. * * This test is failing because the allowed values for the * anotherintegerproperty are 5, 7, 9 or 12. */ @Test public void ShaclInNegativetest() { try { aResource = new AResource(new URI("http://www.sampledomain.org/sam#AResource")); aResource.setAStringProperty("Between"); aResource.addASetOfDates(new Date()); aResource.setAnotherIntegerProperty(new BigInteger("6")); // Invalid value. Allowed values are "A" or "B" or "C". aResource.setAnotherStringProperty("D"); TestHelper.assertNegative(TestHelper.performTest(aResource), "In violation. Expected \"D\" to be in List(LiteralValue(\"C\"), LiteralValue(\"B\"), LiteralValue(\"A\"))"); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception should not be thrown"); } } /** * Shacl in positivetest. */ @Test public void ShaclInPositivetest() { try { aResource = new AResource(new URI("http://www.sampledomain.org/sam#AResource")); aResource.setAnotherIntegerProperty(new BigInteger("12")); aResource.setAStringProperty("Between"); aResource.addASetOfDates(new Date()); TestHelper.assertPositive(TestHelper.performTest(aResource)); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception should not be thrown"); } } }
2,423
Java
.java
67
29.671642
129
0.660539
eclipse/lyo
13
16
148
EPL-2.0
9/4/2024, 8:23:29 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,423
1,791,132
VersionTest_GreaterThan.java
Adrodoc_MPL/compiler/src/test/java/de/adrodoc55/commons/VersionTest_GreaterThan.java
/* * Minecraft Programming Language (MPL): A language for easy development of command block * applications including an IDE. * * © Copyright (C) 2016 Adrodoc55 * * This file is part of MPL. * * MPL is free software: you can redistribute it and/or modify it under the terms of the GNU General * Public License as published by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MPL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. * * You should have received a copy of the GNU General Public License along with MPL. If not, see * <http://www.gnu.org/licenses/>. * * * * Minecraft Programming Language (MPL): Eine Sprache für die einfache Entwicklung von Commandoblock * Anwendungen, inklusive einer IDE. * * © Copyright (C) 2016 Adrodoc55 * * Diese Datei ist Teil von MPL. * * MPL ist freie Software: Sie können diese unter den Bedingungen der GNU General Public License, * wie von der Free Software Foundation, Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren * veröffentlichten Version, weiterverbreiten und/oder modifizieren. * * MPL wird in der Hoffnung, dass es nützlich sein wird, aber OHNE JEDE GEWÄHRLEISTUNG, * bereitgestellt; sogar ohne die implizite Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN * BESTIMMTEN ZWECK. Siehe die GNU General Public License für weitere Details. * * Sie sollten eine Kopie der GNU General Public License zusammen mit MPL erhalten haben. Wenn * nicht, siehe <http://www.gnu.org/licenses/>. */ package de.adrodoc55.commons; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class VersionTest_GreaterThan { private final String a; private final String b; public VersionTest_GreaterThan(String a, String b) { this.a = a; this.b = b; } @Test public void test_compareTo() { // expect: assertThat(new Version(a)).isGreaterThan(new Version(b)); } @Parameters(name = "{index}: {0} > {1}") public static Iterable<String[]> data() { return VersionTestDataFactory.greaterThan(); } }
2,450
Java
.java
63
36.365079
100
0.764458
Adrodoc/MPL
18
4
24
GPL-3.0
9/4/2024, 8:18:52 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
2,438
2,808,921
Text.java
Ketuer_Dandelion/src/main/java/dandelion/ui/lang/Text.java
package dandelion.ui.lang; /** * 包含参数替换的文本类型,用于i18n多语言切换。某些组件可以使用 * 该类型作为参数。 * * @author Ketuer * @since 1.0 */ public class Text { String text; Object[] objects; public Text(String text, Object... objects){ this.objects = objects; this.text = text; } @Override public String toString() { return text; } }
439
Java
.java
20
14.3
48
0.630814
Ketuer/Dandelion
6
0
0
GPL-2.0
9/4/2024, 10:17:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
367
901,190
KcaApplication.java
qly5213_kcanotify_h5-master/app/src/main/java/com/antest1/kcanotify/h5/KcaApplication.java
package com.antest1.kcanotify.h5; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.support.multidex.MultiDex; import android.support.multidex.MultiDexApplication; import org.acra.ACRA; import org.acra.annotation.AcraCore; import java.util.Locale; import static com.antest1.kcanotify.h5.KcaConstants.PREF_KCA_LANGUAGE; @AcraCore(buildConfigClass = BuildConfig.class) /*@AcraMailSender( mailTo = "", reportAsFile = false )*/ public class KcaApplication extends MultiDexApplication { public static Locale defaultLocale; public static Activity gameActivity; public static boolean isCheckVersion = false; public static long checkVersionDate = 0; private static final String PROCESSNAME = "com.antest1.kcanotify.h5"; @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); ACRA.init(this); } @Override public void onCreate() { super.onCreate(); application = this; String language, country; defaultLocale = Locale.getDefault(); SharedPreferences pref = getSharedPreferences("pref", MODE_PRIVATE); String[] pref_locale = pref.getString(PREF_KCA_LANGUAGE, "").split("-"); if (pref_locale.length == 2) { if (pref_locale[0].equals("default")) { LocaleUtils.setLocale(defaultLocale); } else { language = pref_locale[0]; country = pref_locale[1]; LocaleUtils.setLocale(new Locale(language, country)); } } else { pref.edit().remove(PREF_KCA_LANGUAGE).apply(); LocaleUtils.setLocale(defaultLocale); } LocaleUtils.updateConfig(this, getBaseContext().getResources().getConfiguration()); ACRA.init(this); /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { String processName = getProcessName(); if (!PROCESSNAME.equals(processName)) { WebView.setDataDirectorySuffix("modWeb"); } }*/ } private static KcaApplication application; public static KcaApplication getInstance(){ return application; } }
2,307
Java
.java
61
30.327869
91
0.671889
qly5213/kcanotify_h5-master
65
11
1
GPL-3.0
9/4/2024, 7:09:48 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
2,307
4,740,359
TreeSwingNonprismatic.java
jogjayr_InTEL-Project/exercises/TreeSwing/src/treeswing/TreeSwingNonprismatic.java
/* * This file is part of InTEL, the Interactive Toolkit for Engineering Learning. * http://intel.gatech.edu * * InTEL is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * InTEL is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with InTEL. If not, see <http://www.gnu.org/licenses/>. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package treeswing; import edu.gatech.statics.exercise.persistence.test.A; import edu.gatech.statics.math.Unit; import edu.gatech.statics.math.Vector; import edu.gatech.statics.math.Vector3bd; import edu.gatech.statics.modes.description.Description; import edu.gatech.statics.modes.description.layouts.ScrollbarLayout; import edu.gatech.statics.modes.distributed.objects.DistributedForce; import edu.gatech.statics.modes.distributed.objects.TrapezoidalDistributedForce; import edu.gatech.statics.objects.Point; import edu.gatech.statics.objects.bodies.Beam; import java.math.BigDecimal; /** * * @author vignesh */ public class TreeSwingNonprismatic extends TreeSwingBase { @Override public Description getDescription() { Description description = new Description(); description.setNarrative("Jared is a Civil Engineering Student at Georgia Tech " + "and he built a tree swing for his little sister Andrea. He is a little concerned " + "that the branch might not be strong enough to handle his sister swinging on it. " + "Before letting her try it out, he wants to make sure that he placed it appropriately " + "along the length of the branch and he wants to calculate the forces that the branch will be exposed to."); description.setProblemStatement("Assume the branch is not prismatic (varies along the length of the branch) and its mass per unit length " + "can be expressed by F(x) = -5x + 30, where x denotes the position along the branch measured from where the branch connects " + "to the trunk of tree. Assume that the leaves on the branch are evenly distributed through the entire length and have " + "a mass per unit length of 2 kg/m. Andrea’s mass is 30 kg and neglect the weight of the swing."); description.setGoals("Draw a FBD of the branch and solve for the reaction forces. Solve for the total equivalent concentrated force and find its location."); //description.setLayout(new ScrollbarLayout()); description.addImage("treeswing/assets/swing1.jpg"); description.addImage("treeswing/assets/swing2.jpg"); return description; } @Override protected DistributedForce createDistributedForce(Beam AB, Point A, Point B) { DistributedForce distributedtreeswing = new TrapezoidalDistributedForce("treeSwing", AB, A, B, new Vector(Unit.forceOverDistance, Vector3bd.UNIT_Y.negate(), new BigDecimal("32")), new BigDecimal("12")); return distributedtreeswing; } }
3,488
Java
.java
62
50.741935
210
0.73394
jogjayr/InTEL-Project
1
0
0
GPL-3.0
9/5/2024, 12:29:04 AM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,488
3,551,907
BatchUpdateHandlerTest.java
c0c0n3_ome-smuggler/components/server/src/test/java/ome/smuggler/core/service/imports/impl/BatchUpdateHandlerTest.java
package ome.smuggler.core.service.imports.impl; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import static ome.smuggler.core.service.imports.impl.Utils.*; import ome.smuggler.core.msg.RepeatAction; import ome.smuggler.core.types.ImportBatch; import ome.smuggler.core.types.ImportBatchStatus; import ome.smuggler.core.types.ProcessedImport; import org.junit.Before; import org.junit.Test; public class BatchUpdateHandlerTest { private BatchUpdateHandler target; private ImportEnv env; @Before public void setup() { env = mockedImportEnvWithMemBatchStore(); target = new BatchUpdateHandler(env); } @Test public void repeatOnException() { ProcessedImport processed = succeededProcessedImport(); try { env.batchManager().updateBatchOf(processed); } catch (IllegalArgumentException e) { // batch key not in batch store ==> exc when trying to access value. RepeatAction actual = target.consume(processed); assertThat(actual, is(RepeatAction.Repeat)); } } @Test public void stopIfNoExceptions() { ImportBatch batch = env.batchManager() .createBatchFor(newImportRequests(2)); ProcessedImport processed = ProcessedImport.succeeded( batch.imports().findFirst().get()); RepeatAction actual = target.consume(processed); assertThat(actual, is(RepeatAction.Stop)); ImportBatchStatus status = batchStoreData(env).get(processed.batchId()); assertTrue(status.succeeded().contains(processed.queued())); } @Test(expected = NullPointerException.class) public void ctorThrowsIfNullEnv() { new BatchUpdateHandler(null); } @Test(expected = NullPointerException.class) public void consumeThrowsIfNullProcessedImport() { target.consume(null); } }
1,938
Java
.java
49
32.673469
80
0.704691
c0c0n3/ome-smuggler
3
3
1
GPL-3.0
9/4/2024, 11:32:47 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,938