lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
53ffae02b1edd9f02bfe9166a8043233cd8464db
0
chengmaoning/jroad,chengmaoning/jroad
/** * */ package com.chengmaoning.jroad.jdbc; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.Assert; /** * @author chengmaoning * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context.xml") public class JdbcStudentDaoTest { @Autowired StudentDao studentDao; /** * Test method for * {@link com.chengmaoning.jroad.jdbc.JdbcStudentDao#findAllStudents()}. */ @Test public void testFindAllStudents() { List<Student> students = studentDao.findAllStudents(); System.out.println(students); Assert.isTrue(true, null); } }
src/test/java/com/chengmaoning/jroad/jdbc/JdbcStudentDaoTest.java
/** * */ package com.chengmaoning.jroad.jdbc; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.Assert; /** * @author chengmaoning * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context.xml") public class JdbcStudentDaoTest { @Autowired StudentDao studentDao; /** * Test method for * {@link com.chengmaoning.jroad.jdbc.JdbcStudentDao#findAllStudents()}. */ @Test public void testFindAllStudents() { List<Student> students = studentDao.findAllStudents(); System.out.println(students); Assert.isTrue(true, null); } }
re Signed-off-by: chengmaoning <[email protected]>
src/test/java/com/chengmaoning/jroad/jdbc/JdbcStudentDaoTest.java
re
<ide><path>rc/test/java/com/chengmaoning/jroad/jdbc/JdbcStudentDaoTest.java <ide> public void testFindAllStudents() { <ide> List<Student> students = studentDao.findAllStudents(); <ide> System.out.println(students); <del> <ide> Assert.isTrue(true, null); <ide> } <ide>
Java
apache-2.0
c2beec3f2e39757dab933dfc2178db00cd12026b
0
nhpatt/RxInPractice
package com.nhpatt.rxjava; import io.reactivex.Completable; import io.reactivex.Single; import retrofit2.http.*; import java.util.List; public interface TalksService { @GET("/talks") Single<List<Talk>> listTalks(); @GET("/talks") Single<SearchResult> filterTalks(@Query(value = "search", encoded = true) String search); @DELETE("/talks") Completable deleteTalks(); @POST("/talks") Completable addTalk(@Body Talk talk); }
RxJavaInAction/src/main/java/com/nhpatt/rxjava/TalksService.java
package com.nhpatt.rxjava; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import io.reactivex.Observable; import io.reactivex.Single; import retrofit2.http.*; import java.util.List; public interface TalksService { @GET("/talks") Single<List<Talk>> listTalks(); @DELETE("/talks") Observable<Void> deleteTalks(); @POST("/talks") Observable<Void> addTalk(@Body Talk talk); @GET("/talks") Single<List<Talk>> filterTalks(@Query(value = "search", encoded = true) String search); }
sort interface methods
RxJavaInAction/src/main/java/com/nhpatt/rxjava/TalksService.java
sort interface methods
<ide><path>xJavaInAction/src/main/java/com/nhpatt/rxjava/TalksService.java <ide> package com.nhpatt.rxjava; <ide> <del>import com.google.gson.JsonElement; <del>import com.google.gson.JsonObject; <del>import io.reactivex.Observable; <add>import io.reactivex.Completable; <ide> import io.reactivex.Single; <ide> import retrofit2.http.*; <ide> <ide> @GET("/talks") <ide> Single<List<Talk>> listTalks(); <ide> <add> @GET("/talks") <add> Single<SearchResult> filterTalks(@Query(value = "search", encoded = true) String search); <add> <ide> @DELETE("/talks") <del> Observable<Void> deleteTalks(); <add> Completable deleteTalks(); <ide> <ide> @POST("/talks") <del> Observable<Void> addTalk(@Body Talk talk); <del> <del> @GET("/talks") <del> Single<List<Talk>> filterTalks(@Query(value = "search", encoded = true) String search); <add> Completable addTalk(@Body Talk talk); <ide> }
Java
mit
error: pathspec 'src/com/parnswir/unmp/DirectoryChooserDialog.java' did not match any file(s) known to git
615898efa84a21bedd13817a13e0ddb4432f4017
1
Parnswir/unmp
package com.parnswir.unmp; // The following code was created by Gregory Shpitalnik under The Code Project Open License // http://www.codeproject.com/Articles/547636/Android-Ready-to-use-simple-directory-chooser-dial import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnKeyListener; import android.os.Environment; import android.text.Editable; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class DirectoryChooserDialog { private boolean m_isNewFolderEnabled = true; private String m_sdcardDirectory = ""; private Context m_context; private TextView m_titleView; private String m_dir = ""; private List<String> m_subdirs = null; private ChosenDirectoryListener m_chosenDirectoryListener = null; private ArrayAdapter<String> m_listAdapter = null; ////////////////////////////////////////////////////// // Callback interface for selected directory ////////////////////////////////////////////////////// public interface ChosenDirectoryListener { public void onChosenDir(String chosenDir); } public DirectoryChooserDialog(Context context, ChosenDirectoryListener chosenDirectoryListener) { m_context = context; m_sdcardDirectory = Environment.getExternalStorageDirectory().getAbsolutePath(); m_chosenDirectoryListener = chosenDirectoryListener; try { m_sdcardDirectory = new File(m_sdcardDirectory).getCanonicalPath(); } catch (IOException ioe) { } } /////////////////////////////////////////////////////////////////////// // setNewFolderEnabled() - enable/disable new folder button /////////////////////////////////////////////////////////////////////// public void setNewFolderEnabled(boolean isNewFolderEnabled) { m_isNewFolderEnabled = isNewFolderEnabled; } public boolean getNewFolderEnabled() { return m_isNewFolderEnabled; } /////////////////////////////////////////////////////////////////////// // chooseDirectory() - load directory chooser dialog for initial // default sdcard directory /////////////////////////////////////////////////////////////////////// public void chooseDirectory() { // Initial directory is sdcard directory chooseDirectory(m_sdcardDirectory); } //////////////////////////////////////////////////////////////////////////////// // chooseDirectory(String dir) - load directory chooser dialog for initial // input 'dir' directory //////////////////////////////////////////////////////////////////////////////// public void chooseDirectory(String dir) { File dirFile = new File(dir); if (! dirFile.exists() || ! dirFile.isDirectory()) { dir = m_sdcardDirectory; } try { dir = new File(dir).getCanonicalPath(); } catch (IOException ioe) { return; } m_dir = dir; m_subdirs = getDirectories(dir); class DirectoryOnClickListener implements DialogInterface.OnClickListener { public void onClick(DialogInterface dialog, int item) { // Navigate into the sub-directory m_dir += "/" + ((AlertDialog) dialog).getListView().getAdapter().getItem(item); updateDirectory(); } } AlertDialog.Builder dialogBuilder = createDirectoryChooserDialog(dir, m_subdirs, new DirectoryOnClickListener()); dialogBuilder.setPositiveButton("OK", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Current directory chosen if (m_chosenDirectoryListener != null) { // Call registered listener supplied with the chosen directory m_chosenDirectoryListener.onChosenDir(m_dir); } } }).setNegativeButton("Cancel", null); final AlertDialog dirsDialog = dialogBuilder.create(); dirsDialog.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { // Back button pressed if ( m_dir.equals(m_sdcardDirectory) ) { // The very top level directory, do nothing return false; } else { // Navigate back to an upper directory m_dir = new File(m_dir).getParent(); updateDirectory(); } return true; } else { return false; } } }); // Show directory chooser dialog dirsDialog.show(); } private boolean createSubDir(String newDir) { File newDirFile = new File(newDir); if (! newDirFile.exists() ) { return newDirFile.mkdir(); } return false; } private List<String> getDirectories(String dir) { List<String> dirs = new ArrayList<String>(); try { File dirFile = new File(dir); if (! dirFile.exists() || ! dirFile.isDirectory()) { return dirs; } for (File file : dirFile.listFiles()) { if ( file.isDirectory() ) { dirs.add( file.getName() ); } } } catch (Exception e) { } Collections.sort(dirs, new Comparator<String>() { public int compare(String o1, String o2) { return o1.compareTo(o2); } }); return dirs; } private AlertDialog.Builder createDirectoryChooserDialog(String title, List<String> listItems, DialogInterface.OnClickListener onClickListener) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(m_context); // Create custom view for AlertDialog title containing // current directory TextView and possible 'New folder' button. // Current directory TextView allows long directory path to be wrapped to multiple lines. LinearLayout titleLayout = new LinearLayout(m_context); titleLayout.setOrientation(LinearLayout.VERTICAL); m_titleView = new TextView(m_context); m_titleView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); m_titleView.setTextAppearance(m_context, android.R.style.TextAppearance_Large); m_titleView.setTextColor( m_context.getResources().getColor(android.R.color.white) ); m_titleView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL); m_titleView.setText(title); Button newDirButton = new Button(m_context); newDirButton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); newDirButton.setText("New folder"); newDirButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final EditText input = new EditText(m_context); // Show new folder name input dialog new AlertDialog.Builder(m_context). setTitle("New folder name"). setView(input).setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Editable newDir = input.getText(); String newDirName = newDir.toString(); // Create new directory if ( createSubDir(m_dir + "/" + newDirName) ) { // Navigate into the new directory m_dir += "/" + newDirName; updateDirectory(); } else { Toast.makeText( m_context, "Failed to create '" + newDirName + "' folder", Toast.LENGTH_SHORT).show(); } } }).setNegativeButton("Cancel", null).show(); } }); if (! m_isNewFolderEnabled) { newDirButton.setVisibility(View.GONE); } titleLayout.addView(m_titleView); titleLayout.addView(newDirButton); dialogBuilder.setCustomTitle(titleLayout); m_listAdapter = createListAdapter(listItems); dialogBuilder.setSingleChoiceItems(m_listAdapter, -1, onClickListener); dialogBuilder.setCancelable(false); return dialogBuilder; } private void updateDirectory() { m_subdirs.clear(); m_subdirs.addAll( getDirectories(m_dir) ); m_titleView.setText(m_dir); m_listAdapter.notifyDataSetChanged(); } private ArrayAdapter<String> createListAdapter(List<String> items) { return new ArrayAdapter<String>(m_context, android.R.layout.select_dialog_item, android.R.id.text1, items) { @Override public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); if (v instanceof TextView) { // Enable list item (directory) text wrapping TextView tv = (TextView) v; tv.getLayoutParams().height = LayoutParams.WRAP_CONTENT; tv.setEllipsize(null); } return v; } }; } }
src/com/parnswir/unmp/DirectoryChooserDialog.java
Add DirectoryChooserDialog class
src/com/parnswir/unmp/DirectoryChooserDialog.java
Add DirectoryChooserDialog class
<ide><path>rc/com/parnswir/unmp/DirectoryChooserDialog.java <add>package com.parnswir.unmp; <add> <add>// The following code was created by Gregory Shpitalnik under The Code Project Open License <add>// http://www.codeproject.com/Articles/547636/Android-Ready-to-use-simple-directory-chooser-dial <add> <add>import java.io.File; <add>import java.io.IOException; <add>import java.util.ArrayList; <add>import java.util.Collections; <add>import java.util.Comparator; <add>import java.util.List; <add> <add>import android.app.AlertDialog; <add>import android.content.Context; <add>import android.content.DialogInterface; <add>import android.content.DialogInterface.OnClickListener; <add>import android.content.DialogInterface.OnKeyListener; <add>import android.os.Environment; <add>import android.text.Editable; <add>import android.view.Gravity; <add>import android.view.KeyEvent; <add>import android.view.View; <add>import android.view.ViewGroup; <add>import android.view.ViewGroup.LayoutParams; <add>import android.widget.ArrayAdapter; <add>import android.widget.Button; <add>import android.widget.EditText; <add>import android.widget.LinearLayout; <add>import android.widget.TextView; <add>import android.widget.Toast; <add> <add>public class DirectoryChooserDialog <add>{ <add> private boolean m_isNewFolderEnabled = true; <add> private String m_sdcardDirectory = ""; <add> private Context m_context; <add> private TextView m_titleView; <add> <add> private String m_dir = ""; <add> private List<String> m_subdirs = null; <add> private ChosenDirectoryListener m_chosenDirectoryListener = null; <add> private ArrayAdapter<String> m_listAdapter = null; <add> <add> ////////////////////////////////////////////////////// <add> // Callback interface for selected directory <add> ////////////////////////////////////////////////////// <add> public interface ChosenDirectoryListener <add> { <add> public void onChosenDir(String chosenDir); <add> } <add> <add> public DirectoryChooserDialog(Context context, ChosenDirectoryListener chosenDirectoryListener) <add> { <add> m_context = context; <add> m_sdcardDirectory = Environment.getExternalStorageDirectory().getAbsolutePath(); <add> m_chosenDirectoryListener = chosenDirectoryListener; <add> <add> try <add> { <add> m_sdcardDirectory = new File(m_sdcardDirectory).getCanonicalPath(); <add> } <add> catch (IOException ioe) <add> { <add> } <add> } <add> <add> /////////////////////////////////////////////////////////////////////// <add> // setNewFolderEnabled() - enable/disable new folder button <add> /////////////////////////////////////////////////////////////////////// <add> <add> public void setNewFolderEnabled(boolean isNewFolderEnabled) <add> { <add> m_isNewFolderEnabled = isNewFolderEnabled; <add> } <add> <add> public boolean getNewFolderEnabled() <add> { <add> return m_isNewFolderEnabled; <add> } <add> <add> /////////////////////////////////////////////////////////////////////// <add> // chooseDirectory() - load directory chooser dialog for initial <add> // default sdcard directory <add> /////////////////////////////////////////////////////////////////////// <add> <add> public void chooseDirectory() <add> { <add> // Initial directory is sdcard directory <add> chooseDirectory(m_sdcardDirectory); <add> } <add> <add> //////////////////////////////////////////////////////////////////////////////// <add> // chooseDirectory(String dir) - load directory chooser dialog for initial <add> // input 'dir' directory <add> //////////////////////////////////////////////////////////////////////////////// <add> <add> public void chooseDirectory(String dir) <add> { <add> File dirFile = new File(dir); <add> if (! dirFile.exists() || ! dirFile.isDirectory()) <add> { <add> dir = m_sdcardDirectory; <add> } <add> <add> try <add> { <add> dir = new File(dir).getCanonicalPath(); <add> } <add> catch (IOException ioe) <add> { <add> return; <add> } <add> <add> m_dir = dir; <add> m_subdirs = getDirectories(dir); <add> <add> class DirectoryOnClickListener implements DialogInterface.OnClickListener <add> { <add> public void onClick(DialogInterface dialog, int item) <add> { <add> // Navigate into the sub-directory <add> m_dir += "/" + ((AlertDialog) dialog).getListView().getAdapter().getItem(item); <add> updateDirectory(); <add> } <add> } <add> <add> AlertDialog.Builder dialogBuilder = <add> createDirectoryChooserDialog(dir, m_subdirs, new DirectoryOnClickListener()); <add> <add> dialogBuilder.setPositiveButton("OK", new OnClickListener() <add> { <add> @Override <add> public void onClick(DialogInterface dialog, int which) <add> { <add> // Current directory chosen <add> if (m_chosenDirectoryListener != null) <add> { <add> // Call registered listener supplied with the chosen directory <add> m_chosenDirectoryListener.onChosenDir(m_dir); <add> } <add> } <add> }).setNegativeButton("Cancel", null); <add> <add> final AlertDialog dirsDialog = dialogBuilder.create(); <add> <add> dirsDialog.setOnKeyListener(new OnKeyListener() <add> { <add> @Override <add> public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) <add> { <add> if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) <add> { <add> // Back button pressed <add> if ( m_dir.equals(m_sdcardDirectory) ) <add> { <add> // The very top level directory, do nothing <add> return false; <add> } <add> else <add> { <add> // Navigate back to an upper directory <add> m_dir = new File(m_dir).getParent(); <add> updateDirectory(); <add> } <add> <add> return true; <add> } <add> else <add> { <add> return false; <add> } <add> } <add> }); <add> <add> // Show directory chooser dialog <add> dirsDialog.show(); <add>} <add> <add>private boolean createSubDir(String newDir) <add>{ <add> File newDirFile = new File(newDir); <add> if (! newDirFile.exists() ) <add> { <add> return newDirFile.mkdir(); <add> } <add> <add> return false; <add>} <add> <add>private List<String> getDirectories(String dir) <add>{ <add> List<String> dirs = new ArrayList<String>(); <add> <add> try <add> { <add> File dirFile = new File(dir); <add> if (! dirFile.exists() || ! dirFile.isDirectory()) <add> { <add> return dirs; <add> } <add> <add> for (File file : dirFile.listFiles()) <add> { <add> if ( file.isDirectory() ) <add> { <add> dirs.add( file.getName() ); <add> } <add> } <add> } <add> catch (Exception e) <add> { <add> } <add> <add> Collections.sort(dirs, new Comparator<String>() <add> { <add> public int compare(String o1, String o2) <add> { <add> return o1.compareTo(o2); <add> } <add> }); <add> <add> return dirs; <add>} <add> <add>private AlertDialog.Builder createDirectoryChooserDialog(String title, List<String> listItems, <add> DialogInterface.OnClickListener onClickListener) <add>{ <add> AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(m_context); <add> <add> // Create custom view for AlertDialog title containing <add> // current directory TextView and possible 'New folder' button. <add> // Current directory TextView allows long directory path to be wrapped to multiple lines. <add> LinearLayout titleLayout = new LinearLayout(m_context); <add> titleLayout.setOrientation(LinearLayout.VERTICAL); <add> <add> m_titleView = new TextView(m_context); <add> m_titleView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); <add> m_titleView.setTextAppearance(m_context, android.R.style.TextAppearance_Large); <add> m_titleView.setTextColor( m_context.getResources().getColor(android.R.color.white) ); <add> m_titleView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL); <add> m_titleView.setText(title); <add> <add> Button newDirButton = new Button(m_context); <add> newDirButton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); <add> newDirButton.setText("New folder"); <add> newDirButton.setOnClickListener(new View.OnClickListener() <add> { <add> @Override <add> public void onClick(View v) <add> { <add> final EditText input = new EditText(m_context); <add> <add> // Show new folder name input dialog <add> new AlertDialog.Builder(m_context). <add> setTitle("New folder name"). <add> setView(input).setPositiveButton("OK", new DialogInterface.OnClickListener() <add> { <add> public void onClick(DialogInterface dialog, int whichButton) <add> { <add> Editable newDir = input.getText(); <add> String newDirName = newDir.toString(); <add> // Create new directory <add> if ( createSubDir(m_dir + "/" + newDirName) ) <add> { <add> // Navigate into the new directory <add> m_dir += "/" + newDirName; <add> updateDirectory(); <add> } <add> else <add> { <add> Toast.makeText( <add> m_context, "Failed to create '" + newDirName + <add> "' folder", Toast.LENGTH_SHORT).show(); <add> } <add> } <add> }).setNegativeButton("Cancel", null).show(); <add> } <add> }); <add> <add> if (! m_isNewFolderEnabled) <add> { <add> newDirButton.setVisibility(View.GONE); <add> } <add> <add> titleLayout.addView(m_titleView); <add> titleLayout.addView(newDirButton); <add> <add> dialogBuilder.setCustomTitle(titleLayout); <add> <add> m_listAdapter = createListAdapter(listItems); <add> <add> dialogBuilder.setSingleChoiceItems(m_listAdapter, -1, onClickListener); <add> dialogBuilder.setCancelable(false); <add> <add> return dialogBuilder; <add>} <add> <add>private void updateDirectory() <add>{ <add> m_subdirs.clear(); <add> m_subdirs.addAll( getDirectories(m_dir) ); <add> m_titleView.setText(m_dir); <add> <add> m_listAdapter.notifyDataSetChanged(); <add>} <add> <add>private ArrayAdapter<String> createListAdapter(List<String> items) <add>{ <add> return new ArrayAdapter<String>(m_context, <add> android.R.layout.select_dialog_item, android.R.id.text1, items) <add> { <add> @Override <add> public View getView(int position, View convertView, <add> ViewGroup parent) <add> { <add> View v = super.getView(position, convertView, parent); <add> <add> if (v instanceof TextView) <add> { <add> // Enable list item (directory) text wrapping <add> TextView tv = (TextView) v; <add> tv.getLayoutParams().height = LayoutParams.WRAP_CONTENT; <add> tv.setEllipsize(null); <add> } <add> return v; <add> } <add> }; <add>} <add>}
Java
mit
error: pathspec 'src/assembler/Assembler.java' did not match any file(s) known to git
d32b9ca9c9f82ad20b52a28ae506c101f0ba6615
1
profolsen/Footnote,profolsen/Footnote
package assembler; import java.io.File; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; /** * Created by po917265 on 6/3/17. */ public class Assembler { public static void main(String[] args) throws Exception { Scanner scan = new Scanner(new File("program.txt")); PrintStream out = new PrintStream("output.txt"); HashMap<String, Integer> symbolTable = new HashMap<String, Integer>(); ArrayList<String> program = new ArrayList<String>(); ArrayList<Integer> pc = new ArrayList<Integer>(); int index = 0; //the index for variable addresses. int variableCount = 0; pc.add(0); boolean declare = false; while(scan.hasNextLine()) { String line = scan.nextLine(); line = killComments(line).trim(); if(line.equals("")) continue; if(line.equals(".declare")) { declare = true; } else if(line.equals(".begin")) { declare = false; } else if(declare) { String[] parts = line.split("\\s+"); if(parts.length == 1) { symbolTable.put(line, --index); variableCount++; } else if(parts.length == 2) { symbolTable.put(parts[0], parse(parts[1])); } else { System.out.println("Illegal constant or variable declaration: " + line); } } else if(line.startsWith(":")) { symbolTable.put(line, pc.get(0)); } else { String[] parts = line.split("\\s+"); syntaxCheck(parts); assemble(parts, symbolTable, program, pc); } } for(int i = 0; i < program.size(); i++) { if(program.get(i).startsWith(":")) { Integer address = symbolTable.get(program.get(i)); if(address == null) { System.out.println("Undefined branch label: " + program.get(i)); } program.set(i, "" + address); } } for(int i = 0; i < variableCount; i++) { program.add("0"); } //System.out.println(program); for(String s : program) { out.println(s); } } private static void syntaxCheck(String[] parts) { if(parts[0].equals("jmp")) { checkThat(parts, true, true, false); } else if(parts[0].equals("beq")) { checkThat(parts, true, true, false); } else if(parts[0].equals("ld")) { checkThat(parts, true, true, true); } else if(parts[0].equals("print") || parts[0].equals("println") || parts[0].equals("printch")) { checkThat(parts, false, false, false); } else if(parts[0].equals("add") || parts[0].equals("sub") || parts[0].equals("mul") || parts[0].equals("div")) { checkThat(parts, false, false, false); } else if(parts[0].equals("zero") || parts[0].equals("one")) { checkThat(parts, false, false, false); } else if(parts[0].equals("dup") || parts[0].equals("dup2") || parts[0].equals("dupn")) { checkThat(parts, false, false, false); } else if(parts[0].equals("ldi")) { checkThat(parts, true, true, true); } else if(parts[0].equals("st")) { checkThat(parts, true, true, true); } else if(parts[0].equals("hlt")) { checkThat(parts, false, false, false); } else { System.out.println("Undefined Instruction: " + parts[0]); } } private static void checkThat(String[] parts, boolean takesArguments, boolean takesLabels, boolean takesAddresses) { if(parts.length != (takesArguments ? 2 : 1)) { System.out.println("Incorrect argument count: " + parts[0]); return; } if(!takesArguments) return; boolean label = parts[1].startsWith(":"); boolean number = parses(parts[1]); if(!((takesLabels & label) || takesAddresses & number)) { System.out.println("Incorrect argument type: " + parts[1]); } } private static boolean parses(String string) { try { Integer.parseInt(string); return true; } catch(Exception e) { return false; } } private static void assemble(String[] parts, HashMap<String, Integer> symbolTable, ArrayList<String> program, ArrayList<Integer> pc) { if(parts[0].equals("dup")) { program.add("" + 0xA); inc(pc); } else if(parts[0].equals("dup2")) { program.add("" + 0xB); inc(pc); } else if(parts[0].equals("dupn")) { program.add("" + 0xC); inc(pc); } else if(parts[0].equals("add")) { program.add("" + 0x4); inc(pc); } else if(parts[0].equals("sub")) { program.add("" + 0x5); inc(pc); } else if(parts[0].equals("mul")) { program.add("" + 0x6); inc(pc); } else if(parts[0].equals("div")) { program.add("" + 0x7); inc(pc); } else if(parts[0].equals("ld")) { program.add("" + 0x2); inc(pc); Integer address = symbolTable.get(parts[1]); // System.out.println(symbolTable); // System.out.println(parts[1] + " :: " + symbolTable.get(parts[1])); if(address == null) { System.out.println("Undefined variable: " + parts[1]); } inc(pc); program.add("" + address); } else if(parts[0].equals("st")) { program.add("" + 0xE); inc(pc); Integer address = symbolTable.get(parts[1]); if(address == null) { System.out.println("Undefined variable: " + parts[1]); } inc(pc); program.add("" + address); } else if(parts[0].equals("ldi")) { program.add("" + 0xD); inc(pc); if(parts[1].startsWith(":")) { Integer value = symbolTable.get(parts[1]); if(value == null) { System.out.println("Undefined constant: " + parts[1]); } program.add("" + value); } else { program.add(parts[1]); } inc(pc); } else if(parts[0].equals("beq")) { Integer address = symbolTable.get(parts[1]); program.add("" + 0xD); inc(pc); if(address == null) { program.add(parts[1]); } else { program.add("" + address); } inc(pc); program.add("" + 0x1); inc(pc); } else if(parts[0].equals("jmp")) { Integer address = symbolTable.get(parts[1]); program.add("" + 0xD); inc(pc); if(address == null) { program.add(parts[1]); } else { program.add("" + address); } inc(pc); program.add("" + 0x0); inc(pc); } else if(parts[0].equals("hlt")) { program.add("" + 0xF); inc(pc); } else if(parts[0].equals("print")) { program.add("" + 0x3); inc(pc); program.add("" + 0x1); inc(pc); } else if(parts[0].equals("println")) { program.add("" + 0x3); inc(pc); program.add("" + 0x3); inc(pc); } else if(parts[0].equals("printch")) { program.add("" + 0x3); inc(pc); program.add("" + 0x2); inc(pc); } else if(parts[0].equals("one")) { program.add("" + 0x8); inc(pc); } else if(parts[0].equals("zero")) { program.add("" + 0x9); inc(pc); } } private static void inc(ArrayList<Integer> pc) { pc.set(0, pc.get(0) + 1); } private static String killComments(String line) { if(line.startsWith(";")) return ""; if(! line.contains(";")) { return line; } return line.substring(0, line.indexOf(';') - 1); } public static int parse(String number) { try { return Integer.parseInt(number); } catch(Exception e) { System.out.println("Expected a number but instead saw: " + number); return Integer.MIN_VALUE; } } }
src/assembler/Assembler.java
assembler Here's an assembler.
src/assembler/Assembler.java
assembler
<ide><path>rc/assembler/Assembler.java <add>package assembler; <add> <add>import java.io.File; <add>import java.io.PrintStream; <add>import java.util.ArrayList; <add>import java.util.HashMap; <add>import java.util.Scanner; <add> <add>/** <add> * Created by po917265 on 6/3/17. <add> */ <add>public class Assembler { <add> <add> public static void main(String[] args) throws Exception { <add> Scanner scan = new Scanner(new File("program.txt")); <add> PrintStream out = new PrintStream("output.txt"); <add> HashMap<String, Integer> symbolTable = new HashMap<String, Integer>(); <add> ArrayList<String> program = new ArrayList<String>(); <add> ArrayList<Integer> pc = new ArrayList<Integer>(); <add> int index = 0; //the index for variable addresses. <add> int variableCount = 0; <add> pc.add(0); <add> boolean declare = false; <add> while(scan.hasNextLine()) { <add> String line = scan.nextLine(); <add> line = killComments(line).trim(); <add> if(line.equals("")) continue; <add> if(line.equals(".declare")) { <add> declare = true; <add> } else if(line.equals(".begin")) { <add> declare = false; <add> } else if(declare) { <add> String[] parts = line.split("\\s+"); <add> if(parts.length == 1) { <add> symbolTable.put(line, --index); <add> variableCount++; <add> } else if(parts.length == 2) { <add> symbolTable.put(parts[0], parse(parts[1])); <add> } else { <add> System.out.println("Illegal constant or variable declaration: " + line); <add> } <add> } else if(line.startsWith(":")) { <add> symbolTable.put(line, pc.get(0)); <add> } else { <add> String[] parts = line.split("\\s+"); <add> syntaxCheck(parts); <add> assemble(parts, symbolTable, program, pc); <add> } <add> } <add> for(int i = 0; i < program.size(); i++) { <add> if(program.get(i).startsWith(":")) { <add> Integer address = symbolTable.get(program.get(i)); <add> if(address == null) { <add> System.out.println("Undefined branch label: " + program.get(i)); <add> } <add> program.set(i, "" + address); <add> } <add> } <add> for(int i = 0; i < variableCount; i++) { <add> program.add("0"); <add> } <add> //System.out.println(program); <add> for(String s : program) { <add> out.println(s); <add> } <add> } <add> <add> private static void syntaxCheck(String[] parts) { <add> if(parts[0].equals("jmp")) { <add> checkThat(parts, true, true, false); <add> } else if(parts[0].equals("beq")) { <add> checkThat(parts, true, true, false); <add> } else if(parts[0].equals("ld")) { <add> checkThat(parts, true, true, true); <add> } else if(parts[0].equals("print") || parts[0].equals("println") || parts[0].equals("printch")) { <add> checkThat(parts, false, false, false); <add> } else if(parts[0].equals("add") || parts[0].equals("sub") || parts[0].equals("mul") || parts[0].equals("div")) { <add> checkThat(parts, false, false, false); <add> } else if(parts[0].equals("zero") || parts[0].equals("one")) { <add> checkThat(parts, false, false, false); <add> } else if(parts[0].equals("dup") || parts[0].equals("dup2") || parts[0].equals("dupn")) { <add> checkThat(parts, false, false, false); <add> } else if(parts[0].equals("ldi")) { <add> checkThat(parts, true, true, true); <add> } else if(parts[0].equals("st")) { <add> checkThat(parts, true, true, true); <add> } else if(parts[0].equals("hlt")) { <add> checkThat(parts, false, false, false); <add> } else { <add> System.out.println("Undefined Instruction: " + parts[0]); <add> } <add> } <add> <add> private static void checkThat(String[] parts, boolean takesArguments, boolean takesLabels, boolean takesAddresses) { <add> if(parts.length != (takesArguments ? 2 : 1)) { <add> System.out.println("Incorrect argument count: " + parts[0]); <add> return; <add> } <add> if(!takesArguments) return; <add> boolean label = parts[1].startsWith(":"); <add> boolean number = parses(parts[1]); <add> if(!((takesLabels & label) || takesAddresses & number)) { <add> System.out.println("Incorrect argument type: " + parts[1]); <add> } <add> } <add> <add> private static boolean parses(String string) { <add> try { <add> Integer.parseInt(string); <add> return true; <add> } catch(Exception e) { <add> return false; <add> } <add> } <add> <add> private static void assemble(String[] parts, HashMap<String, Integer> symbolTable, ArrayList<String> program, ArrayList<Integer> pc) { <add> if(parts[0].equals("dup")) { <add> program.add("" + 0xA); <add> inc(pc); <add> } else if(parts[0].equals("dup2")) { <add> program.add("" + 0xB); <add> inc(pc); <add> } else if(parts[0].equals("dupn")) { <add> program.add("" + 0xC); <add> inc(pc); <add> } else if(parts[0].equals("add")) { <add> program.add("" + 0x4); <add> inc(pc); <add> } else if(parts[0].equals("sub")) { <add> program.add("" + 0x5); <add> inc(pc); <add> <add> } else if(parts[0].equals("mul")) { <add> program.add("" + 0x6); <add> inc(pc); <add> <add> } else if(parts[0].equals("div")) { <add> program.add("" + 0x7); <add> inc(pc); <add> <add> } else if(parts[0].equals("ld")) { <add> program.add("" + 0x2); <add> inc(pc); <add> Integer address = symbolTable.get(parts[1]); <add>// System.out.println(symbolTable); <add>// System.out.println(parts[1] + " :: " + symbolTable.get(parts[1])); <add> if(address == null) <add> { <add> System.out.println("Undefined variable: " + parts[1]); <add> } <add> inc(pc); <add> program.add("" + address); <add> <add> } else if(parts[0].equals("st")) { <add> program.add("" + 0xE); <add> inc(pc); <add> Integer address = symbolTable.get(parts[1]); <add> if(address == null) <add> { <add> System.out.println("Undefined variable: " + parts[1]); <add> } <add> inc(pc); <add> program.add("" + address); <add> <add> } else if(parts[0].equals("ldi")) { <add> program.add("" + 0xD); <add> inc(pc); <add> if(parts[1].startsWith(":")) { <add> Integer value = symbolTable.get(parts[1]); <add> if(value == null) { <add> System.out.println("Undefined constant: " + parts[1]); <add> } <add> program.add("" + value); <add> } else { <add> program.add(parts[1]); <add> } <add> inc(pc); <add> <add> } else if(parts[0].equals("beq")) { <add> Integer address = symbolTable.get(parts[1]); <add> program.add("" + 0xD); <add> inc(pc); <add> if(address == null) <add> { <add> program.add(parts[1]); <add> } else { <add> program.add("" + address); <add> } <add> inc(pc); <add> program.add("" + 0x1); <add> inc(pc); <add> <add> } else if(parts[0].equals("jmp")) { <add> Integer address = symbolTable.get(parts[1]); <add> program.add("" + 0xD); <add> inc(pc); <add> if(address == null) <add> { <add> program.add(parts[1]); <add> } else { <add> program.add("" + address); <add> } <add> inc(pc); <add> program.add("" + 0x0); <add> inc(pc); <add> <add> } else if(parts[0].equals("hlt")) { <add> program.add("" + 0xF); <add> inc(pc); <add> <add> } else if(parts[0].equals("print")) { <add> program.add("" + 0x3); <add> inc(pc); <add> program.add("" + 0x1); <add> inc(pc); <add> <add> } else if(parts[0].equals("println")) { <add> program.add("" + 0x3); <add> inc(pc); <add> program.add("" + 0x3); <add> inc(pc); <add> <add> } else if(parts[0].equals("printch")) { <add> program.add("" + 0x3); <add> inc(pc); <add> program.add("" + 0x2); <add> inc(pc); <add> <add> } else if(parts[0].equals("one")) { <add> program.add("" + 0x8); <add> inc(pc); <add> <add> } else if(parts[0].equals("zero")) { <add> program.add("" + 0x9); <add> inc(pc); <add> <add> } <add> } <add> <add> private static void inc(ArrayList<Integer> pc) { <add> pc.set(0, pc.get(0) + 1); <add> } <add> <add> private static String killComments(String line) { <add> if(line.startsWith(";")) return ""; <add> if(! line.contains(";")) { <add> return line; <add> } <add> return line.substring(0, line.indexOf(';') - 1); <add> } <add> <add> public static int parse(String number) { <add> try { <add> return Integer.parseInt(number); <add> } catch(Exception e) { <add> System.out.println("Expected a number but instead saw: " + number); <add> return Integer.MIN_VALUE; <add> } <add> } <add>}
Java
apache-2.0
error: pathspec 'samples/benchmark/src/main/java/org/teavm/samples/benchmark/jvm/JvmBenchmarkStarter.java' did not match any file(s) known to git
84628b7008f73e7b2f0e80c3a45a5da84f819524
1
shannah/cn1-teavm-builds,jtulach/teavm,shannah/cn1-teavm-builds,jtulach/teavm,shannah/cn1-teavm-builds,jtulach/teavm,konsoletyper/teavm,konsoletyper/teavm,konsoletyper/teavm,konsoletyper/teavm,shannah/cn1-teavm-builds,konsoletyper/teavm,jtulach/teavm,shannah/cn1-teavm-builds
/* * Copyright 2016 Alexey Andreev. * * 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.teavm.samples.benchmark.jvm; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.geom.Arc2D; import java.awt.geom.Path2D; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.WindowConstants; import org.jbox2d.collision.shapes.CircleShape; import org.jbox2d.collision.shapes.PolygonShape; import org.jbox2d.collision.shapes.Shape; import org.jbox2d.collision.shapes.ShapeType; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.Fixture; import org.teavm.samples.benchmark.shared.Scene; public class JvmBenchmarkStarter { private static Scene scene = new Scene(); private static int currentSecond; private static long startMillisecond; private static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1); private static JRenderer renderer = new JRenderer(); private static double timeSpentCalculating; private JvmBenchmarkStarter() { } public static void main(String[] args) { startMillisecond = System.currentTimeMillis(); JFrame window = new JFrame(); window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); window.add(renderer); window.setVisible(true); EventQueue.invokeLater(() -> { window.pack(); makeStep(); }); } private static void makeStep() { long start = System.nanoTime(); scene.calculate(); long end = System.nanoTime(); int second = (int) ((System.currentTimeMillis() - startMillisecond) / 1000); if (second > currentSecond) { System.out.println("Computing second " + second + " took " + timeSpentCalculating / 1000000 + " ms"); currentSecond = second; timeSpentCalculating = 0; } timeSpentCalculating += end - start; renderer.repaint(); executor.schedule(() -> EventQueue.invokeLater(JvmBenchmarkStarter::makeStep), scene.timeUntilNextStep(), TimeUnit.MILLISECONDS); } private static class JRenderer extends JComponent { @Override public void paint(Graphics g) { Graphics2D gfx = (Graphics2D) g; gfx.setBackground(Color.white); gfx.setPaint(Color.black); gfx.clearRect(0, 0, 600, 600); AffineTransform originalTransformation = gfx.getTransform(); gfx.translate(0, 600); gfx.scale(1, -1); gfx.scale(100, 100); gfx.setStroke(new BasicStroke(0.01f)); for (Body body = scene.getWorld().getBodyList(); body != null; body = body.getNext()) { Vec2 center = body.getPosition(); AffineTransform bodyTransform = gfx.getTransform(); gfx.translate(center.x, center.y); gfx.rotate(body.getAngle()); for (Fixture fixture = body.getFixtureList(); fixture != null; fixture = fixture.getNext()) { Shape shape = fixture.getShape(); if (shape.getType() == ShapeType.CIRCLE) { CircleShape circle = (CircleShape) shape; Arc2D arc = new Arc2D.Float(circle.m_p.x - circle.getRadius(), circle.m_p.y - circle.getRadius(), circle.getRadius() * 2, circle.getRadius() * 2, 0, 360, Arc2D.CHORD); gfx.draw(arc); } else if (shape.getType() == ShapeType.POLYGON) { PolygonShape poly = (PolygonShape) shape; Vec2[] vertices = poly.getVertices(); Path2D path = new Path2D.Float(Path2D.WIND_EVEN_ODD); path.moveTo(vertices[0].x, vertices[0].y); for (int i = 1; i < poly.getVertexCount(); ++i) { path.lineTo(vertices[i].x, vertices[i].y); } path.closePath(); gfx.draw(path); } } gfx.setTransform(bodyTransform); } gfx.setTransform(originalTransformation); } @Override public Dimension getPreferredSize() { return new Dimension(600, 600); } @Override public Dimension getMinimumSize() { return new Dimension(600, 600); } } }
samples/benchmark/src/main/java/org/teavm/samples/benchmark/jvm/JvmBenchmarkStarter.java
Add JVM benchmark for jbox2d
samples/benchmark/src/main/java/org/teavm/samples/benchmark/jvm/JvmBenchmarkStarter.java
Add JVM benchmark for jbox2d
<ide><path>amples/benchmark/src/main/java/org/teavm/samples/benchmark/jvm/JvmBenchmarkStarter.java <add>/* <add> * Copyright 2016 Alexey Andreev. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.teavm.samples.benchmark.jvm; <add> <add>import java.awt.BasicStroke; <add>import java.awt.Color; <add>import java.awt.Dimension; <add>import java.awt.EventQueue; <add>import java.awt.Graphics; <add>import java.awt.Graphics2D; <add>import java.awt.geom.AffineTransform; <add>import java.awt.geom.Arc2D; <add>import java.awt.geom.Path2D; <add>import java.util.concurrent.ScheduledThreadPoolExecutor; <add>import java.util.concurrent.TimeUnit; <add>import javax.swing.JComponent; <add>import javax.swing.JFrame; <add>import javax.swing.WindowConstants; <add>import org.jbox2d.collision.shapes.CircleShape; <add>import org.jbox2d.collision.shapes.PolygonShape; <add>import org.jbox2d.collision.shapes.Shape; <add>import org.jbox2d.collision.shapes.ShapeType; <add>import org.jbox2d.common.Vec2; <add>import org.jbox2d.dynamics.Body; <add>import org.jbox2d.dynamics.Fixture; <add>import org.teavm.samples.benchmark.shared.Scene; <add> <add>public class JvmBenchmarkStarter { <add> private static Scene scene = new Scene(); <add> private static int currentSecond; <add> private static long startMillisecond; <add> private static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1); <add> private static JRenderer renderer = new JRenderer(); <add> private static double timeSpentCalculating; <add> <add> private JvmBenchmarkStarter() { <add> } <add> <add> public static void main(String[] args) { <add> startMillisecond = System.currentTimeMillis(); <add> JFrame window = new JFrame(); <add> window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); <add> window.add(renderer); <add> window.setVisible(true); <add> <add> EventQueue.invokeLater(() -> { <add> window.pack(); <add> makeStep(); <add> }); <add> } <add> <add> private static void makeStep() { <add> long start = System.nanoTime(); <add> scene.calculate(); <add> long end = System.nanoTime(); <add> <add> int second = (int) ((System.currentTimeMillis() - startMillisecond) / 1000); <add> if (second > currentSecond) { <add> System.out.println("Computing second " + second + " took " + timeSpentCalculating / 1000000 + " ms"); <add> currentSecond = second; <add> timeSpentCalculating = 0; <add> } <add> timeSpentCalculating += end - start; <add> renderer.repaint(); <add> <add> executor.schedule(() -> EventQueue.invokeLater(JvmBenchmarkStarter::makeStep), <add> scene.timeUntilNextStep(), TimeUnit.MILLISECONDS); <add> } <add> <add> private static class JRenderer extends JComponent { <add> @Override <add> public void paint(Graphics g) { <add> Graphics2D gfx = (Graphics2D) g; <add> <add> gfx.setBackground(Color.white); <add> gfx.setPaint(Color.black); <add> gfx.clearRect(0, 0, 600, 600); <add> <add> AffineTransform originalTransformation = gfx.getTransform(); <add> <add> gfx.translate(0, 600); <add> gfx.scale(1, -1); <add> gfx.scale(100, 100); <add> gfx.setStroke(new BasicStroke(0.01f)); <add> for (Body body = scene.getWorld().getBodyList(); body != null; body = body.getNext()) { <add> Vec2 center = body.getPosition(); <add> <add> AffineTransform bodyTransform = gfx.getTransform(); <add> gfx.translate(center.x, center.y); <add> gfx.rotate(body.getAngle()); <add> for (Fixture fixture = body.getFixtureList(); fixture != null; fixture = fixture.getNext()) { <add> Shape shape = fixture.getShape(); <add> if (shape.getType() == ShapeType.CIRCLE) { <add> CircleShape circle = (CircleShape) shape; <add> Arc2D arc = new Arc2D.Float(circle.m_p.x - circle.getRadius(), <add> circle.m_p.y - circle.getRadius(), circle.getRadius() * 2, circle.getRadius() * 2, <add> 0, 360, Arc2D.CHORD); <add> gfx.draw(arc); <add> } else if (shape.getType() == ShapeType.POLYGON) { <add> PolygonShape poly = (PolygonShape) shape; <add> Vec2[] vertices = poly.getVertices(); <add> <add> Path2D path = new Path2D.Float(Path2D.WIND_EVEN_ODD); <add> <add> path.moveTo(vertices[0].x, vertices[0].y); <add> for (int i = 1; i < poly.getVertexCount(); ++i) { <add> path.lineTo(vertices[i].x, vertices[i].y); <add> } <add> path.closePath(); <add> gfx.draw(path); <add> } <add> } <add> gfx.setTransform(bodyTransform); <add> } <add> <add> gfx.setTransform(originalTransformation); <add> } <add> <add> @Override <add> public Dimension getPreferredSize() { <add> return new Dimension(600, 600); <add> } <add> <add> @Override <add> public Dimension getMinimumSize() { <add> return new Dimension(600, 600); <add> } <add> } <add>}
JavaScript
apache-2.0
53bf0d266252a3e9dea690f9c68953c997661a30
0
papswell/jsonexport,Cnova/jsonexport,kauegimenes/jsonexport
var chai = require('chai'); var expect = chai.expect; var jsonexport = require('../lib/index'); describe('Options', () => { it('headerPathString', () => { jsonexport({a: {b: true}}, { headerPathString: '|' }, (err, csv) => { expect(csv).to.have.string('a|b'); }); }); it('rowDelimiter', () => { jsonexport({a: true, b: true}, { rowDelimiter: '|' }, (err, csv) => { expect(csv).to.have.string('a|true'); }); }); it('textDelimiter with linebreak', () => { jsonexport({a: '\n', b: true}, { textDelimiter: '|' }, (err, csv) => { expect(csv).to.have.string('|\n|'); }); }); it('textDelimiter with double quote', () => { jsonexport({a: '"', b: true}, { textDelimiter: '"' }, (err, csv) => { expect(csv).to.have.string('a,""'); }); }); it('endOfLine', () => { jsonexport({a: true, b: true}, { endOfLine: '|' }, (err, csv) => { expect(csv).to.have.string('a,true|b,true'); }); }); it('mainPathItem', () => { // Object jsonexport({a: true, b: true}, { mainPathItem: 'main' }, (err, csv) => { expect(csv).to.have.string('main.a,true\nmain.b,true'); }); // Array jsonexport([{a: true}, {b: true}], { mainPathItem: 'main' }, (err, csv) => { expect(csv).to.have.string('main.a,main.b'); }); }); it('mainPathItem', () => { jsonexport({a: [1, 2], b: true}, { arrayPathString: '|' }, (err, csv) => { expect(csv).to.have.string('a,1|2'); }); }); it('booleanTrueString', () => { jsonexport({a: true, b: true}, { booleanTrueString: 'test' }, (err, csv) => { expect(csv).to.have.string('a,test'); }); }); it('booleanFalseString', () => { jsonexport({a: false, b: true}, { booleanFalseString: 'test' }, (err, csv) => { expect(csv).to.have.string('a,test'); }); }); it('includeHeaders', () => { jsonexport([{a: true}, {a: false}], { includeHeaders: false }, (err, csv) => { expect(csv).to.have.string('true\nfalse'); }); }); it('orderHeaders', () => { jsonexport([{b: false}, {a: true}, {a: true}], { orderHeaders: true }, (err, csv) => { expect(csv).to.have.string('a,b'); }); jsonexport([{b: false}, {a: true}, {a: true}], { orderHeaders: false }, (err, csv) => { expect(csv).to.have.string('b,a'); }); }); it('verticalOutput', () => { jsonexport({a: true, b: true}, { verticalOutput: false }, (err, csv) => { expect(csv).to.have.string('a,b'); }); }); describe('Handlers', () => { it('handleString', () => { jsonexport({a: 'test', b: true}, { handleString: (value, name) => value + "|||" }, (err, csv) => { expect(csv).to.have.string('a,test|||'); }); }); it('handleNumber', () => { jsonexport({a: 1, b: true}, { handleNumber: (value, name) => value + "|||" }, (err, csv) => { expect(csv).to.have.string('a,1|||'); }); }); it('handleBoolean', () => { jsonexport({a: true, b: true}, { handleBoolean: (value, name) => value + "|||" }, (err, csv) => { expect(csv).to.have.string('a,true|||'); }); }); it('handleDate', () => { var date = new Date(); jsonexport({a: date, b: true}, { handleDate: (value, name) => value + "|||" }, (err, csv) => { expect(csv).to.have.string('a,' + date + '|||'); }); }); }); });
tests/options.js
var chai = require('chai'); var expect = chai.expect; var jsonexport = require('../lib/index'); describe('Options', () => { it('headerPathString', () => { jsonexport({a: {b: true}}, { headerPathString: '|' }, (err, csv) => { expect(csv).to.have.string('a|b'); }); }); it('rowDelimiter', () => { jsonexport({a: true, b: true}, { rowDelimiter: '|' }, (err, csv) => { expect(csv).to.have.string('a|true'); }); }); it('textDelimiter with linebreak', () => { jsonexport({a: '\n', b: true}, { textDelimiter: '|' }, (err, csv) => { expect(csv).to.have.string('|\n|'); }); }); it('textDelimiter with double quote', () => { jsonexport({a: '"', b: true}, { textDelimiter: '"' }, (err, csv) => { expect(csv).to.have.string('a,""'); }); }); it('endOfLine', () => { jsonexport({a: true, b: true}, { endOfLine: '|' }, (err, csv) => { expect(csv).to.have.string('a,true|b,true'); }); }); it('mainPathItem', () => { // Object jsonexport({a: true, b: true}, { mainPathItem: 'main' }, (err, csv) => { expect(csv).to.have.string('main.a,true\nmain.b,true'); }); // Array jsonexport([{a: true}, {b: true}], { mainPathItem: 'main' }, (err, csv) => { expect(csv).to.have.string('main.a,main.b'); }); }); it('mainPathItem', () => { jsonexport({a: [1, 2], b: true}, { arrayPathString: '|' }, (err, csv) => { expect(csv).to.have.string('a,1|2'); }); }); it('booleanTrueString', () => { jsonexport({a: true, b: true}, { booleanTrueString: 'test' }, (err, csv) => { expect(csv).to.have.string('a,test'); }); }); it('booleanFalseString', () => { jsonexport({a: false, b: true}, { booleanFalseString: 'test' }, (err, csv) => { expect(csv).to.have.string('a,test'); }); }); it('includeHeaders', () => { jsonexport([{a: true}, {a: false}], { includeHeaders: false }, (err, csv) => { expect(csv).to.have.string('true\nfalse'); }); }); it('orderHeaders', () => { jsonexport([{b: false}, {a: true}, {a: true}], { orderHeaders: true }, (err, csv) => { expect(csv).to.have.string('a,b'); }); jsonexport([{b: false}, {a: true}, {a: true}], { orderHeaders: false }, (err, csv) => { expect(csv).to.have.string('b,a'); }); }); it('verticalOutput', () => { jsonexport({a: true, b: true}, { verticalOutput: false }, (err, csv) => { expect(csv).to.have.string('a,b'); }); }); describe('Handlers', () => { it('handleString', () => { jsonexport({a: 'test', b: true}, { handleString: (value, name) => value + "|||" }, (err, csv) => { expect(csv).to.have.string('a,test|||'); }); }); it('handleNumber', () => { jsonexport({a: 1, b: true}, { handleNumber: (value, name) => value + "|||" }, (err, csv) => { expect(csv).to.have.string('a,1|||'); }); }); it('handleBoolean', () => { jsonexport({a: true, b: true}, { handleBoolean: (value, name) => value + "|||" }, (err, csv) => { expect(csv).to.have.string('a,true|||'); }); }); it('handleDate', () => { var date = new Date(); jsonexport({a: date, b: true}, { handleDate: (value, name) => value + "|||" }, (err, csv) => { expect(csv).to.have.string('a,' + date + '|||'); }); }); }) })
fix #12
tests/options.js
fix #12
<ide><path>ests/options.js <ide> expect(csv).to.have.string('a,' + date + '|||'); <ide> }); <ide> }); <del> }) <del> <del>}) <add> }); <add>});
Java
mit
d62bf62424443713c35c780a9dba93911c29ec51
0
Danghor/WHOAMI,BigDaddy-Germany/WHOAMI,Danghor/WHOAMI
package de.aima13.whoami.modules; import de.aima13.whoami.Analyzable; import de.aima13.whoami.support.Utilities; import org.stringtemplate.v4.ST; import java.nio.file.Path; import java.util.*; /** * Modul zum Analysieren der Häufigkeit der verschiedenen Programmiersprachen, * die der Nutzer verwendet * * @author Marco Dörfler */ public class CodeStatistics implements Analyzable { private static final String TEMPLATE_LOCATION = "/data/programmStats.html"; private static final String WEB_TYPE ="web"; private static final String NORMAL_CODE = "native"; private final FileExtension[] fileExtensions; private String getTopLanguage() { String topLanguage=""; int counter = -1; for (Map.Entry<FileExtension, Integer> statisticsEntry : this.statisticResults.entrySet()) { if(statisticsEntry.getValue() > counter){ topLanguage = statisticsEntry.getKey().lang; counter = statisticsEntry.getValue(); } } return topLanguage; } // Inhaltstyp der JSon Datei private class FileExtension { public String ext; public String lang; public String type; } private final String REPORT_TITLE = "Coding Statistiken"; private final String CSV_PREFIX = "codestatistics"; private List<Path> fileInput; private Map<FileExtension, Integer> statisticResults; /** * Im Konstruktor wird die JSon Datei der Dateiendungen eingelesen und gespeichert (wird * schon bei der Ausgabe der Filter benötigt. Des weiteren wird die Map der Ergebnisse * initialisiert */ public CodeStatistics() { this.fileExtensions = Utilities.loadDataFromJson("/data/CodeStatistics_FileExtensions" + ".json", FileExtension[].class); this.statisticResults = new HashMap<>(); for (FileExtension fileExtension : this.fileExtensions) { this.statisticResults.put(fileExtension, 0); } } /** * Konstruiert die Filtereinstellungen aus der Liste der unterstützten Dateiendungen * @return Die erstellte Liste der Filter */ @Override public List<String> getFilter() { List<String> filter = new ArrayList<>(); for (FileExtension fileExtension : this.fileExtensions) { filter.add("**." + fileExtension.ext); } return filter; } /** * Dateien werden einfach gespeichert und später genutzt * @param files Liste der gefundenen Dateien * @throws Exception */ @Override public void setFileInputs(List<Path> files) throws Exception { this.fileInput = files; } @Override public String getHtml() { // Template laden ST template = new ST(Utilities.getResourceAsString(TEMPLATE_LOCATION), '$', '$'); template.add("topLanguage",getTopLanguage()); if(moreWebCoding()){ template.add("moreWebLanguage",true); // template.add("moreNativeLanguage",null); }else{ template.add("moreNativeLanguage",true); // template.add("moreWebLanguage",null); } for (Map.Entry<FileExtension, Integer> statisticsEntry : this.statisticResults.entrySet()) { template.addAggr("programm.{extension, counter}",statisticsEntry.getKey().lang, statisticsEntry.getValue().toString()); } return template.render(); } private boolean moreWebCoding() { int webFiles=0; int nativeFiles=0; for (Map.Entry<FileExtension, Integer> statisticsEntry : this.statisticResults.entrySet()) { if(statisticsEntry.getKey().type.equals(WEB_TYPE)){ webFiles++; }else{ nativeFiles++; } } return webFiles > nativeFiles; } @Override public String getReportTitle() { return REPORT_TITLE; } @Override public String getCsvPrefix() { return CSV_PREFIX; } /** * Iteriere über die Statistiken und füge sie in die Ergebnis-Map für die CSV Datei ein * @return Die fertige CSV-Datei */ @Override public SortedMap<String, String> getCsvContent() { SortedMap<String, String> csvContent = new TreeMap<>(); for (Map.Entry<FileExtension, Integer> statisticsEntry : this.statisticResults.entrySet()) { csvContent.put(statisticsEntry.getKey().lang, statisticsEntry.getValue().toString()); } return csvContent; } /** * Iteriert über die Dateien und sortiert diese nach den verschiedenen Endungen */ @Override public void run() { // Über Dateien iterieren for (Path file : this.fileInput) { // Über Sprache entscheiden for (FileExtension fileExtension : this.fileExtensions) { // Wenn die Dateiendung passt, Wert um eins erhöhen if (file.toString().endsWith(fileExtension.ext)) { this.statisticResults.put(fileExtension, this.statisticResults.get (fileExtension) + 1); } } } } }
WHOAMI/src/de/aima13/whoami/modules/CodeStatistics.java
package de.aima13.whoami.modules; import de.aima13.whoami.Analyzable; import de.aima13.whoami.support.Utilities; import org.stringtemplate.v4.ST; import java.nio.file.Path; import java.util.*; /** * Modul zum Analysieren der Häufigkeit der verschiedenen Programmiersprachen, * die der Nutzer verwendet * * @author Marco Dörfler */ public class CodeStatistics implements Analyzable { private static final String TEMPLATE_LOCATION = "/data/programmStats.html"; private static final String WEB_TYPE ="web"; private static final String NORMAL_CODE = "native"; private final FileExtension[] fileExtensions; private String getTopLanguage() { String topLanguage=""; int counter = -1; for (Map.Entry<FileExtension, Integer> statisticsEntry : this.statisticResults.entrySet()) { if(statisticsEntry.getValue() > counter){ topLanguage = statisticsEntry.getKey().lang; counter = statisticsEntry.getValue(); } } return topLanguage; } // Inhaltstyp der JSon Datei private class FileExtension { public String ext; public String lang; public String type; } private final String REPORT_TITLE = "Coding Statistiken"; private final String CSV_PREFIX = "codestatistics"; private List<Path> fileInput; private Map<FileExtension, Integer> statisticResults; /** * Im Konstruktor wird die JSon Datei der Dateiendungen eingelesen und gespeichert (wird * schon bei der Ausgabe der Filter benötigt. Des weiteren wird die Map der Ergebnisse * initialisiert */ public CodeStatistics() { this.fileExtensions = Utilities.loadDataFromJson("/data/CodeStatistics_FileExtensions" + ".json", FileExtension[].class); this.statisticResults = new HashMap<>(); for (FileExtension fileExtension : this.fileExtensions) { this.statisticResults.put(fileExtension, 0); } } /** * Konstruiert die Filtereinstellungen aus der Liste der unterstützten Dateiendungen * @return Die erstellte Liste der Filter */ @Override public List<String> getFilter() { List<String> filter = new ArrayList<>(); for (FileExtension fileExtension : this.fileExtensions) { filter.add("**." + fileExtension.ext); } return filter; } /** * Dateien werden einfach gespeichert und später genutzt * @param files Liste der gefundenen Dateien * @throws Exception */ @Override public void setFileInputs(List<Path> files) throws Exception { this.fileInput = files; } @Override public String getHtml() { // Template laden ST template = new ST(Utilities.getResourceAsString(TEMPLATE_LOCATION), '$', '$'); template.add("topLanguage",getTopLanguage()); if(moreWebCoding()){ template.add("moreWebLanguage",true); template.add("moreNativeLanguage",null); }else{ template.add("moreNativeLanguage",true); template.add("moreWebLanguage",null); } for (Map.Entry<FileExtension, Integer> statisticsEntry : this.statisticResults.entrySet()) { template.addAggr("programm.{extension, counter}",statisticsEntry.getKey().lang, statisticsEntry.getValue().toString()); } System.out.println(template.render()); return template.render(); } private boolean moreWebCoding() { int webFiles=0; int nativeFiles=0; for (Map.Entry<FileExtension, Integer> statisticsEntry : this.statisticResults.entrySet()) { if(statisticsEntry.getKey().type.equals(WEB_TYPE)){ webFiles++; }else{ nativeFiles++; } } return webFiles > nativeFiles; } @Override public String getReportTitle() { return REPORT_TITLE; } @Override public String getCsvPrefix() { return CSV_PREFIX; } /** * Iteriere über die Statistiken und füge sie in die Ergebnis-Map für die CSV Datei ein * @return Die fertige CSV-Datei */ @Override public SortedMap<String, String> getCsvContent() { SortedMap<String, String> csvContent = new TreeMap<>(); for (Map.Entry<FileExtension, Integer> statisticsEntry : this.statisticResults.entrySet()) { csvContent.put(statisticsEntry.getKey().lang, statisticsEntry.getValue().toString()); } return csvContent; } /** * Iteriert über die Dateien und sortiert diese nach den verschiedenen Endungen */ @Override public void run() { // Über Dateien iterieren for (Path file : this.fileInput) { // Über Sprache entscheiden for (FileExtension fileExtension : this.fileExtensions) { // Wenn die Dateiendung passt, Wert um eins erhöhen if (file.toString().endsWith(fileExtension.ext)) { this.statisticResults.put(fileExtension, this.statisticResults.get (fileExtension) + 1); } } } } }
Println ernfernt
WHOAMI/src/de/aima13/whoami/modules/CodeStatistics.java
Println ernfernt
<ide><path>HOAMI/src/de/aima13/whoami/modules/CodeStatistics.java <ide> template.add("topLanguage",getTopLanguage()); <ide> if(moreWebCoding()){ <ide> template.add("moreWebLanguage",true); <del> template.add("moreNativeLanguage",null); <add>// template.add("moreNativeLanguage",null); <ide> }else{ <ide> template.add("moreNativeLanguage",true); <del> template.add("moreWebLanguage",null); <add>// template.add("moreWebLanguage",null); <ide> } <ide> for (Map.Entry<FileExtension, Integer> statisticsEntry : this.statisticResults.entrySet()) { <ide> template.addAggr("programm.{extension, counter}",statisticsEntry.getKey().lang, <ide> statisticsEntry.getValue().toString()); <ide> } <del> System.out.println(template.render()); <ide> return template.render(); <ide> } <ide>
Java
agpl-3.0
868b12c9aaa0a960245f51a1c52e796223691ec1
0
Hunter522/qgroundcontrol,Hunter522/qgroundcontrol,Hunter522/qgroundcontrol,Hunter522/qgroundcontrol,Hunter522/qgroundcontrol,Hunter522/qgroundcontrol
package org.mavlink.qgroundcontrol; /* Copyright 2013 Google Inc. * * 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, or (at your option) any later version. * * 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. * * Project home page: http://code.google.com/p/usb-serial-for-android/ */ /////////////////////////////////////////////////////////////////////////////////////////// // Written by: Mike Goza April 2014 // // These routines interface with the Android USB Host devices for serial port communication. // The code uses the usb-serial-for-android software library. The QGCActivity class is the // interface to the C++ routines through jni calls. Do not change the functions without also // changing the corresponding calls in the C++ routines or you will break the interface. // //////////////////////////////////////////////////////////////////////////////////////////// import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.Timer; import java.util.TimerTask; import java.io.IOException; import android.app.Activity; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.hardware.usb.UsbAccessory; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbManager; import android.widget.Toast; import android.util.Log; import android.os.PowerManager; import android.os.Bundle; import android.app.PendingIntent; import android.view.WindowManager; import com.hoho.android.usbserial.driver.*; import org.qtproject.qt5.android.bindings.QtActivity; import org.qtproject.qt5.android.bindings.QtApplication; public class QGCActivity extends QtActivity { public static int BAD_DEVICE_ID = 0; private static QGCActivity _instance = null; private static UsbManager _usbManager = null; private static List<UsbSerialDriver> _drivers; private static HashMap<Integer, UsbIoManager> m_ioManager; private static HashMap<Integer, Integer> _userDataHashByDeviceId; private static final String TAG = "QGC_QGCActivity"; private static PowerManager.WakeLock _wakeLock; // private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION"; private static final String ACTION_USB_PERMISSION = "org.mavlink.qgroundcontrol.action.USB_PERMISSION"; private static PendingIntent _usbPermissionIntent = null; private TaiSync taiSync = null; public static Context m_context; private final static ExecutorService m_Executor = Executors.newSingleThreadExecutor(); private final static UsbIoManager.Listener m_Listener = new UsbIoManager.Listener() { @Override public void onRunError(Exception eA, int userData) { Log.e(TAG, "onRunError Exception"); nativeDeviceException(userData, eA.getMessage()); } @Override public void onNewData(final byte[] dataA, int userData) { nativeDeviceNewData(userData, dataA); } }; private final BroadcastReceiver mOpenAccessoryReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_USB_PERMISSION.equals(action)) { UsbAccessory accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY); if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { openAccessory(accessory); } } else if( UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) { UsbAccessory accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY); if (accessory != null) { closeAccessory(accessory); } } } }; private static UsbSerialDriver _findDriverByDeviceId(int deviceId) { for (UsbSerialDriver driver: _drivers) { if (driver.getDevice().getDeviceId() == deviceId) { return driver; } } return null; } private static UsbSerialDriver _findDriverByDeviceName(String deviceName) { for (UsbSerialDriver driver: _drivers) { if (driver.getDevice().getDeviceName().equals(deviceName)) { return driver; } } return null; } private final static BroadcastReceiver _usbReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.i(TAG, "BroadcastReceiver USB action " + action); if (ACTION_USB_PERMISSION.equals(action)) { synchronized (_instance) { UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (device != null) { UsbSerialDriver driver = _findDriverByDeviceId(device.getDeviceId()); if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { qgcLogDebug("Permission granted to " + device.getDeviceName()); driver.setPermissionStatus(UsbSerialDriver.permissionStatusSuccess); } else { qgcLogDebug("Permission denied for " + device.getDeviceName()); driver.setPermissionStatus(UsbSerialDriver.permissionStatusDenied); } } } } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) { UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (device != null) { if (_userDataHashByDeviceId.containsKey(device.getDeviceId())) { nativeDeviceHasDisconnected(_userDataHashByDeviceId.get(device.getDeviceId())); } } } } }; // Native C++ functions which connect back to QSerialPort code private static native void nativeDeviceHasDisconnected(int userData); private static native void nativeDeviceException(int userData, String messageA); private static native void nativeDeviceNewData(int userData, byte[] dataA); // Native C++ functions called to log output public static native void qgcLogDebug(String message); public static native void qgcLogWarning(String message); // QGCActivity singleton public QGCActivity() { _instance = this; _drivers = new ArrayList<UsbSerialDriver>(); _userDataHashByDeviceId = new HashMap<Integer, Integer>(); m_ioManager = new HashMap<Integer, UsbIoManager>(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PowerManager pm = (PowerManager)_instance.getSystemService(Context.POWER_SERVICE); _wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "QGroundControl"); if(_wakeLock != null) { _wakeLock.acquire(); } else { Log.i(TAG, "SCREEN_BRIGHT_WAKE_LOCK not acquired!!!"); } _instance.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); _usbManager = (UsbManager)_instance.getSystemService(Context.USB_SERVICE); // Register for USB Detach and USB Permission intent IntentFilter filter = new IntentFilter(); filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); filter.addAction(ACTION_USB_PERMISSION); _instance.registerReceiver(_instance._usbReceiver, filter); // Create intent for usb permission request _usbPermissionIntent = PendingIntent.getBroadcast(_instance, 0, new Intent(ACTION_USB_PERMISSION), 0); try { taiSync = new TaiSync(); IntentFilter accessoryFilter = new IntentFilter(ACTION_USB_PERMISSION); filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED); registerReceiver(mOpenAccessoryReceiver, accessoryFilter); probeAccessories(); } catch(Exception e) { Log.e(TAG, "Exception: " + e); } } @Override protected void onDestroy() { unregisterReceiver(mOpenAccessoryReceiver); try { if(_wakeLock != null) { _wakeLock.release(); } } catch(Exception e) { Log.e(TAG, "Exception onDestroy()"); } super.onDestroy(); } public void onInit(int status) { } /// Incrementally updates the list of drivers connected to the device private static void updateCurrentDrivers() { List<UsbSerialDriver> currentDrivers = UsbSerialProber.findAllDevices(_usbManager); // Remove stale drivers for (int i=_drivers.size()-1; i>=0; i--) { boolean found = false; for (UsbSerialDriver currentDriver: currentDrivers) { if (_drivers.get(i).getDevice().getDeviceId() == currentDriver.getDevice().getDeviceId()) { found = true; break; } } if (!found) { qgcLogDebug("Remove stale driver " + _drivers.get(i).getDevice().getDeviceName()); _drivers.remove(i); } } // Add new drivers for (int i=0; i<currentDrivers.size(); i++) { boolean found = false; for (int j=0; j<_drivers.size(); j++) { if (currentDrivers.get(i).getDevice().getDeviceId() == _drivers.get(j).getDevice().getDeviceId()) { found = true; break; } } if (!found) { UsbSerialDriver newDriver = currentDrivers.get(i); UsbDevice device = newDriver.getDevice(); String deviceName = device.getDeviceName(); _drivers.add(newDriver); qgcLogDebug("Adding new driver " + deviceName); // Request permission if needed if (_usbManager.hasPermission(device)) { qgcLogDebug("Already have permission to use device " + deviceName); newDriver.setPermissionStatus(UsbSerialDriver.permissionStatusSuccess); } else { qgcLogDebug("Requesting permission to use device " + deviceName); newDriver.setPermissionStatus(UsbSerialDriver.permissionStatusRequested); _usbManager.requestPermission(device, _usbPermissionIntent); } } } } /// Returns array of device info for each unopened device. /// @return Device info format DeviceName:Company:ProductId:VendorId public static String[] availableDevicesInfo() { updateCurrentDrivers(); if (_drivers.size() <= 0) { return null; } List<String> deviceInfoList = new ArrayList<String>(); for (int i=0; i<_drivers.size(); i++) { String deviceInfo; UsbSerialDriver driver = _drivers.get(i); if (driver.permissionStatus() != UsbSerialDriver.permissionStatusSuccess) { continue; } UsbDevice device = driver.getDevice(); deviceInfo = device.getDeviceName() + ":"; if (driver instanceof FtdiSerialDriver) { deviceInfo = deviceInfo + "FTDI:"; } else if (driver instanceof CdcAcmSerialDriver) { deviceInfo = deviceInfo + "Cdc Acm:"; } else if (driver instanceof Cp2102SerialDriver) { deviceInfo = deviceInfo + "Cp2102:"; } else if (driver instanceof ProlificSerialDriver) { deviceInfo = deviceInfo + "Prolific:"; } else { deviceInfo = deviceInfo + "Unknown:"; } deviceInfo = deviceInfo + Integer.toString(device.getProductId()) + ":"; deviceInfo = deviceInfo + Integer.toString(device.getVendorId()) + ":"; deviceInfoList.add(deviceInfo); } String[] rgDeviceInfo = new String[deviceInfoList.size()]; for (int i=0; i<deviceInfoList.size(); i++) { rgDeviceInfo[i] = deviceInfoList.get(i); } return rgDeviceInfo; } /// Open the specified device /// @param userData Data to associate with device and pass back through to native calls. /// @return Device id public static int open(Context parentContext, String deviceName, int userData) { int deviceId = BAD_DEVICE_ID; m_context = parentContext; UsbSerialDriver driver = _findDriverByDeviceName(deviceName); if (driver == null) { qgcLogWarning("Attempt to open unknown device " + deviceName); return BAD_DEVICE_ID; } if (driver.permissionStatus() != UsbSerialDriver.permissionStatusSuccess) { qgcLogWarning("Attempt to open device with incorrect permission status " + deviceName + " " + driver.permissionStatus()); return BAD_DEVICE_ID; } UsbDevice device = driver.getDevice(); deviceId = device.getDeviceId(); try { driver.setConnection(_usbManager.openDevice(device)); driver.open(); driver.setPermissionStatus(UsbSerialDriver.permissionStatusOpen); _userDataHashByDeviceId.put(deviceId, userData); UsbIoManager ioManager = new UsbIoManager(driver, m_Listener, userData); m_ioManager.put(deviceId, ioManager); m_Executor.submit(ioManager); qgcLogDebug("Port open successful"); } catch(IOException exA) { driver.setPermissionStatus(UsbSerialDriver.permissionStatusRequestRequired); _userDataHashByDeviceId.remove(deviceId); if(m_ioManager.get(deviceId) != null) { m_ioManager.get(deviceId).stop(); m_ioManager.remove(deviceId); } qgcLogWarning("Port open exception: " + exA.getMessage()); return BAD_DEVICE_ID; } return deviceId; } public static void startIoManager(int idA) { if (m_ioManager.get(idA) != null) return; UsbSerialDriver driverL = _findDriverByDeviceId(idA); if (driverL == null) return; UsbIoManager managerL = new UsbIoManager(driverL, m_Listener, _userDataHashByDeviceId.get(idA)); m_ioManager.put(idA, managerL); m_Executor.submit(managerL); } public static void stopIoManager(int idA) { if(m_ioManager.get(idA) == null) return; m_ioManager.get(idA).stop(); m_ioManager.remove(idA); } /////////////////////////////////////////////////////////////////////////////////////////////////////// // // Sets the parameters on an open port. // // Args: idA - ID number from the open command // baudRateA - Decimal value of the baud rate. I.E. 9600, 57600, 115200, etc. // dataBitsA - number of data bits. Valid numbers are 5, 6, 7, 8 // stopBitsA - number of stop bits. Valid numbers are 1, 2 // parityA - No Parity=0, Odd Parity=1, Even Parity=2 // // Returns: T/F Success/Failure // //////////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean setParameters(int idA, int baudRateA, int dataBitsA, int stopBitsA, int parityA) { UsbSerialDriver driverL = _findDriverByDeviceId(idA); if (driverL == null) return false; try { driverL.setParameters(baudRateA, dataBitsA, stopBitsA, parityA); return true; } catch(IOException eA) { return false; } } //////////////////////////////////////////////////////////////////////////////////////////////////////// // // Close the device. // // Args: idA - ID number from the open command // // Returns: T/F Success/Failure // //////////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean close(int idA) { UsbSerialDriver driverL = _findDriverByDeviceId(idA); if (driverL == null) return false; try { stopIoManager(idA); _userDataHashByDeviceId.remove(idA); driverL.setPermissionStatus(UsbSerialDriver.permissionStatusRequestRequired); driverL.close(); return true; } catch(IOException eA) { return false; } } ////////////////////////////////////////////////////////////////////////////////////////////////////// // // Write data to the device. // // Args: idA - ID number from the open command // sourceA - byte array of data to write // timeoutMsecA - amount of time in milliseconds to wait for the write to occur // // Returns: number of bytes written // ///////////////////////////////////////////////////////////////////////////////////////////////////// public static int write(int idA, byte[] sourceA, int timeoutMSecA) { UsbSerialDriver driverL = _findDriverByDeviceId(idA); if (driverL == null) return 0; try { return driverL.write(sourceA, timeoutMSecA); } catch(IOException eA) { return 0; } /* UsbIoManager managerL = m_ioManager.get(idA); if(managerL != null) { managerL.writeAsync(sourceA); return sourceA.length; } else return 0; */ } public static boolean isDeviceNameValid(String nameA) { for (UsbSerialDriver driver: _drivers) { if (driver.getDevice().getDeviceName() == nameA) return true; } return false; } public static boolean isDeviceNameOpen(String nameA) { for (UsbSerialDriver driverL: _drivers) { if (nameA.equals(driverL.getDevice().getDeviceName()) && driverL.permissionStatus() == UsbSerialDriver.permissionStatusOpen) { return true; } } return false; } ///////////////////////////////////////////////////////////////////////////////////////////////////// // // Set the Data Terminal Ready flag on the device // // Args: idA - ID number from the open command // onA - on=T, off=F // // Returns: T/F Success/Failure // //////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean setDataTerminalReady(int idA, boolean onA) { try { UsbSerialDriver driverL = _findDriverByDeviceId(idA); if (driverL == null) return false; driverL.setDTR(onA); return true; } catch(IOException eA) { return false; } } //////////////////////////////////////////////////////////////////////////////////////////// // // Set the Request to Send flag // // Args: idA - ID number from the open command // onA - on=T, off=F // // Returns: T/F Success/Failure // //////////////////////////////////////////////////////////////////////////////////////////// public static boolean setRequestToSend(int idA, boolean onA) { try { UsbSerialDriver driverL = _findDriverByDeviceId(idA); if (driverL == null) return false; driverL.setRTS(onA); return true; } catch(IOException eA) { return false; } } /////////////////////////////////////////////////////////////////////////////////////////////// // // Purge the hardware buffers based on the input and output flags // // Args: idA - ID number from the open command // inputA - input buffer purge. purge=T // outputA - output buffer purge. purge=T // // Returns: T/F Success/Failure // /////////////////////////////////////////////////////////////////////////////////////////////// public static boolean purgeBuffers(int idA, boolean inputA, boolean outputA) { try { UsbSerialDriver driverL = _findDriverByDeviceId(idA); if (driverL == null) return false; return driverL.purgeHwBuffers(inputA, outputA); } catch(IOException eA) { return false; } } ////////////////////////////////////////////////////////////////////////////////////////// // // Get the native device handle (file descriptor) // // Args: idA - ID number from the open command // // Returns: device handle // /////////////////////////////////////////////////////////////////////////////////////////// public static int getDeviceHandle(int idA) { UsbSerialDriver driverL = _findDriverByDeviceId(idA); if (driverL == null) return -1; UsbDeviceConnection connectL = driverL.getDeviceConnection(); if (connectL == null) return -1; else return connectL.getFileDescriptor(); } UsbAccessory openUsbAccessory = null; Object openAccessoryLock = new Object(); private void openAccessory(UsbAccessory usbAccessory) { Log.i(TAG, "openAccessory: " + usbAccessory.getSerial()); try { synchronized(openAccessoryLock) { if ((openUsbAccessory != null && !taiSync.isRunning()) || openUsbAccessory == null) { openUsbAccessory = usbAccessory; taiSync.open(_usbManager.openAccessory(usbAccessory)); } } } catch (IOException e) { Log.e(TAG, "openAccessory exception: " + e); taiSync.close(); closeAccessory(openUsbAccessory); } } private void closeAccessory(UsbAccessory usbAccessory) { Log.i(TAG, "closeAccessory"); synchronized(openAccessoryLock) { if (openUsbAccessory != null && usbAccessory == openUsbAccessory && taiSync.isRunning()) { taiSync.close(); openUsbAccessory = null; } } } private void probeAccessories() { final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // Log.i(TAG, "probeAccessories"); UsbAccessory[] accessories = _usbManager.getAccessoryList(); if (accessories != null) { for (UsbAccessory usbAccessory : accessories) { if (_usbManager.hasPermission(usbAccessory)) { openAccessory(usbAccessory); } else { Log.i(TAG, "requestPermission"); _usbManager.requestPermission(usbAccessory, pendingIntent); } } } } }, 0, 3000); } }
android/src/org/mavlink/qgroundcontrol/QGCActivity.java
/* Copyright 2013 Google Inc. * * 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, or (at your option) any later version. * * 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. * * Project home page: http://code.google.com/p/usb-serial-for-android/ */ /////////////////////////////////////////////////////////////////////////////////////////// // Written by: Mike Goza April 2014 // // These routines interface with the Android USB Host devices for serial port communication. // The code uses the usb-serial-for-android software library. The QGCActivity class is the // interface to the C++ routines through jni calls. Do not change the functions without also // changing the corresponding calls in the C++ routines or you will break the interface. // //////////////////////////////////////////////////////////////////////////////////////////// import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.Timer; import java.util.TimerTask; import java.io.IOException; import android.app.Activity; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.hardware.usb.UsbAccessory; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbManager; import android.widget.Toast; import android.util.Log; import android.os.PowerManager; import android.os.Bundle; import android.app.PendingIntent; import android.view.WindowManager; import com.hoho.android.usbserial.driver.*; import org.qtproject.qt5.android.bindings.QtActivity; import org.qtproject.qt5.android.bindings.QtApplication; public class QGCActivity extends QtActivity { public static int BAD_PORT = 0; private static QGCActivity m_instance; private static UsbManager m_manager; // ANDROID USB HOST CLASS private static List<UsbSerialDriver> m_devices; // LIST OF CURRENT DEVICES private static HashMap<Integer, UsbSerialDriver> m_openedDevices; // LIST OF OPENED DEVICES private static HashMap<Integer, UsbIoManager> m_ioManager; // THREADS FOR LISTENING FOR INCOMING DATA private static HashMap<Integer, Integer> m_userData; // CORRESPONDING USER DATA FOR OPENED DEVICES. USED IN DISCONNECT CALLBACK // USED TO DETECT WHEN A DEVICE HAS BEEN UNPLUGGED private BroadcastReceiver m_UsbReceiver = null; private final static ExecutorService m_Executor = Executors.newSingleThreadExecutor(); private static final String TAG = "QGC_QGCActivity"; private static PowerManager.WakeLock m_wl; public static int BAD_DEVICE_ID = 0; private static QGCActivity _instance = null; private static UsbManager _usbManager = null; private static List<UsbSerialDriver> _drivers; private static HashMap<Integer, UsbIoManager> m_ioManager; private static HashMap<Integer, Integer> _userDataHashByDeviceId; private static final String TAG = "QGC_QGCActivity"; private static PowerManager.WakeLock _wakeLock; // private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION"; private static final String ACTION_USB_PERMISSION = "org.mavlink.qgroundcontrol.action.USB_PERMISSION"; private static PendingIntent _usbPermissionIntent = null; private TaiSync taiSync = null; public static Context m_context; private final static ExecutorService m_Executor = Executors.newSingleThreadExecutor(); private final static UsbIoManager.Listener m_Listener = new UsbIoManager.Listener() { @Override public void onRunError(Exception eA, int userData) { Log.e(TAG, "onRunError Exception"); nativeDeviceException(userData, eA.getMessage()); } @Override public void onNewData(final byte[] dataA, int userData) { nativeDeviceNewData(userData, dataA); } }; // NATIVE C++ FUNCTION THAT WILL BE CALLED IF THE DEVICE IS UNPLUGGED private static native void nativeDeviceHasDisconnected(int userDataA); private static native void nativeDeviceException(int userDataA, String messageA); private static native void nativeDeviceNewData(int userDataA, byte[] dataA); private final BroadcastReceiver mOpenAccessoryReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_USB_PERMISSION.equals(action)) { UsbAccessory accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY); if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { openAccessory(accessory); } } else if( UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) { UsbAccessory accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY); if (accessory != null) { closeAccessory(accessory); } } } }; private static UsbSerialDriver _findDriverByDeviceId(int deviceId) { for (UsbSerialDriver driver: _drivers) { if (driver.getDevice().getDeviceId() == deviceId) { return driver; } } return null; } private static UsbSerialDriver _findDriverByDeviceName(String deviceName) { for (UsbSerialDriver driver: _drivers) { if (driver.getDevice().getDeviceName().equals(deviceName)) { return driver; } } return null; } private final static BroadcastReceiver _usbReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.i(TAG, "BroadcastReceiver USB action " + action); if (ACTION_USB_PERMISSION.equals(action)) { synchronized (_instance) { UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (device != null) { UsbSerialDriver driver = _findDriverByDeviceId(device.getDeviceId()); if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { qgcLogDebug("Permission granted to " + device.getDeviceName()); driver.setPermissionStatus(UsbSerialDriver.permissionStatusSuccess); } else { qgcLogDebug("Permission denied for " + device.getDeviceName()); driver.setPermissionStatus(UsbSerialDriver.permissionStatusDenied); } } } } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) { UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (device != null) { if (_userDataHashByDeviceId.containsKey(device.getDeviceId())) { nativeDeviceHasDisconnected(_userDataHashByDeviceId.get(device.getDeviceId())); } } } } }; // Native C++ functions which connect back to QSerialPort code private static native void nativeDeviceHasDisconnected(int userData); private static native void nativeDeviceException(int userData, String messageA); private static native void nativeDeviceNewData(int userData, byte[] dataA); // Native C++ functions called to log output public static native void qgcLogDebug(String message); public static native void qgcLogWarning(String message); // QGCActivity singleton public QGCActivity() { _instance = this; _drivers = new ArrayList<UsbSerialDriver>(); _userDataHashByDeviceId = new HashMap<Integer, Integer>(); m_ioManager = new HashMap<Integer, UsbIoManager>(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PowerManager pm = (PowerManager)_instance.getSystemService(Context.POWER_SERVICE); _wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "QGroundControl"); if(_wakeLock != null) { _wakeLock.acquire(); } else { Log.i(TAG, "SCREEN_BRIGHT_WAKE_LOCK not acquired!!!"); } m_instance.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); _instance.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); _usbManager = (UsbManager)_instance.getSystemService(Context.USB_SERVICE); // Register for USB Detach and USB Permission intent IntentFilter filter = new IntentFilter(); filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); filter.addAction(ACTION_USB_PERMISSION); _instance.registerReceiver(_instance._usbReceiver, filter); // Create intent for usb permission request _usbPermissionIntent = PendingIntent.getBroadcast(_instance, 0, new Intent(ACTION_USB_PERMISSION), 0); if (m_manager == null) { try { m_manager = (UsbManager)m_instance.getSystemService(Context.USB_SERVICE); taiSync = new TaiSync(); IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION); filter.addAction( UsbManager.ACTION_USB_ACCESSORY_DETACHED); registerReceiver(mOpenAccessoryReceiver, filter); probeAccessories(); } catch(Exception e) { Log.e(TAG, "Exception getCurrentDevices(): " + e); } } } @Override protected void onDestroy() { protected void onDestroy() { unregisterReceiver(mOpenAccessoryReceiver); try { if(_wakeLock != null) { _wakeLock.release(); } } catch(Exception e) { Log.e(TAG, "Exception onDestroy()"); } super.onDestroy(); } public void onInit(int status) { } /// Incrementally updates the list of drivers connected to the device private static void updateCurrentDrivers() { List<UsbSerialDriver> currentDrivers = UsbSerialProber.findAllDevices(_usbManager); if (m_manager == null) m_manager = (UsbManager)m_instance.getSystemService(Context.USB_SERVICE); if (m_devices != null) m_devices.clear(); // Remove stale drivers for (int i=_drivers.size()-1; i>=0; i--) { boolean found = false; for (UsbSerialDriver currentDriver: currentDrivers) { if (_drivers.get(i).getDevice().getDeviceId() == currentDriver.getDevice().getDeviceId()) { found = true; break; } } if (!found) { qgcLogDebug("Remove stale driver " + _drivers.get(i).getDevice().getDeviceName()); _drivers.remove(i); } } // Add new drivers for (int i=0; i<currentDrivers.size(); i++) { boolean found = false; for (int j=0; j<_drivers.size(); j++) { if (currentDrivers.get(i).getDevice().getDeviceId() == _drivers.get(j).getDevice().getDeviceId()) { found = true; break; } } if (!found) { UsbSerialDriver newDriver = currentDrivers.get(i); UsbDevice device = newDriver.getDevice(); String deviceName = device.getDeviceName(); _drivers.add(newDriver); qgcLogDebug("Adding new driver " + deviceName); // Request permission if needed if (_usbManager.hasPermission(device)) { qgcLogDebug("Already have permission to use device " + deviceName); newDriver.setPermissionStatus(UsbSerialDriver.permissionStatusSuccess); } else { qgcLogDebug("Requesting permission to use device " + deviceName); newDriver.setPermissionStatus(UsbSerialDriver.permissionStatusRequested); _usbManager.requestPermission(device, _usbPermissionIntent); } } } } /// Returns array of device info for each unopened device. /// @return Device info format DeviceName:Company:ProductId:VendorId public static String[] availableDevicesInfo() { updateCurrentDrivers(); if (_drivers.size() <= 0) { return null; } List<String> deviceInfoList = new ArrayList<String>(); for (int i=0; i<_drivers.size(); i++) { String deviceInfo; UsbSerialDriver driver = _drivers.get(i); // CHECK FOR ALREADY OPENED DEVICES AND DON"T INCLUDE THEM IN THE COUNT for (iL=0; iL<m_devices.size(); iL++) { if (m_openedDevices.get(m_devices.get(iL).getDevice().getDeviceId()) != null) { countL++; break; if (driver.permissionStatus() != UsbSerialDriver.permissionStatusSuccess) { continue; } UsbDevice device = driver.getDevice(); deviceInfo = device.getDeviceName() + ":"; if (driver instanceof FtdiSerialDriver) { deviceInfo = deviceInfo + "FTDI:"; } else if (driver instanceof CdcAcmSerialDriver) { deviceInfo = deviceInfo + "Cdc Acm:"; } else if (driver instanceof Cp2102SerialDriver) { deviceInfo = deviceInfo + "Cp2102:"; } else if (driver instanceof ProlificSerialDriver) { deviceInfo = deviceInfo + "Prolific:"; } else { deviceInfo = deviceInfo + "Unknown:"; } deviceInfo = deviceInfo + Integer.toString(device.getProductId()) + ":"; deviceInfo = deviceInfo + Integer.toString(device.getVendorId()) + ":"; deviceInfoList.add(deviceInfo); } String[] rgDeviceInfo = new String[deviceInfoList.size()]; for (int i=0; i<deviceInfoList.size(); i++) { rgDeviceInfo[i] = deviceInfoList.get(i); } return rgDeviceInfo; } /// Open the specified device /// @param userData Data to associate with device and pass back through to native calls. /// @return Device id public static int open(Context parentContext, String deviceName, int userData) { int deviceId = BAD_DEVICE_ID; m_context = parentContext; UsbSerialDriver driver = _findDriverByDeviceName(deviceName); if (driver == null) { qgcLogWarning("Attempt to open unknown device " + deviceName); return BAD_DEVICE_ID; } if (driver.permissionStatus() != UsbSerialDriver.permissionStatusSuccess) { qgcLogWarning("Attempt to open device with incorrect permission status " + deviceName + " " + driver.permissionStatus()); return BAD_DEVICE_ID; } UsbDevice device = driver.getDevice(); deviceId = device.getDeviceId(); try { driver.setConnection(_usbManager.openDevice(device)); driver.open(); driver.setPermissionStatus(UsbSerialDriver.permissionStatusOpen); _userDataHashByDeviceId.put(deviceId, userData); UsbIoManager ioManager = new UsbIoManager(driver, m_Listener, userData); m_ioManager.put(deviceId, ioManager); m_Executor.submit(ioManager); qgcLogDebug("Port open successful"); } catch(IOException exA) { driver.setPermissionStatus(UsbSerialDriver.permissionStatusRequestRequired); _userDataHashByDeviceId.remove(deviceId); if(m_ioManager.get(deviceId) != null) { m_ioManager.get(deviceId).stop(); m_ioManager.remove(deviceId); } qgcLogWarning("Port open exception: " + exA.getMessage()); return BAD_DEVICE_ID; } return deviceId; } public static void startIoManager(int idA) { if (m_ioManager.get(idA) != null) return; UsbSerialDriver driverL = _findDriverByDeviceId(idA); if (driverL == null) return; UsbIoManager managerL = new UsbIoManager(driverL, m_Listener, _userDataHashByDeviceId.get(idA)); m_ioManager.put(idA, managerL); m_Executor.submit(managerL); } public static void stopIoManager(int idA) { if(m_ioManager.get(idA) == null) return; m_ioManager.get(idA).stop(); m_ioManager.remove(idA); } /////////////////////////////////////////////////////////////////////////////////////////////////////// // // Sets the parameters on an open port. // // Args: idA - ID number from the open command // baudRateA - Decimal value of the baud rate. I.E. 9600, 57600, 115200, etc. // dataBitsA - number of data bits. Valid numbers are 5, 6, 7, 8 // stopBitsA - number of stop bits. Valid numbers are 1, 2 // parityA - No Parity=0, Odd Parity=1, Even Parity=2 // // Returns: T/F Success/Failure // //////////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean setParameters(int idA, int baudRateA, int dataBitsA, int stopBitsA, int parityA) { UsbSerialDriver driverL = _findDriverByDeviceId(idA); if (driverL == null) return false; try { driverL.setParameters(baudRateA, dataBitsA, stopBitsA, parityA); return true; } catch(IOException eA) { return false; } } //////////////////////////////////////////////////////////////////////////////////////////////////////// // // Close the device. // // Args: idA - ID number from the open command // // Returns: T/F Success/Failure // //////////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean close(int idA) { UsbSerialDriver driverL = _findDriverByDeviceId(idA); if (driverL == null) return false; try { stopIoManager(idA); _userDataHashByDeviceId.remove(idA); driverL.setPermissionStatus(UsbSerialDriver.permissionStatusRequestRequired); driverL.close(); return true; } catch(IOException eA) { return false; } } ////////////////////////////////////////////////////////////////////////////////////////////////////// // // Write data to the device. // // Args: idA - ID number from the open command // sourceA - byte array of data to write // timeoutMsecA - amount of time in milliseconds to wait for the write to occur // // Returns: number of bytes written // ///////////////////////////////////////////////////////////////////////////////////////////////////// public static int write(int idA, byte[] sourceA, int timeoutMSecA) { UsbSerialDriver driverL = _findDriverByDeviceId(idA); if (driverL == null) return 0; try { return driverL.write(sourceA, timeoutMSecA); } catch(IOException eA) { return 0; } /* UsbIoManager managerL = m_ioManager.get(idA); if(managerL != null) { managerL.writeAsync(sourceA); return sourceA.length; } else return 0; */ } public static boolean isDeviceNameValid(String nameA) { for (UsbSerialDriver driver: _drivers) { if (driver.getDevice().getDeviceName() == nameA) return true; } return false; } public static boolean isDeviceNameOpen(String nameA) { for (UsbSerialDriver driverL: _drivers) { if (nameA.equals(driverL.getDevice().getDeviceName()) && driverL.permissionStatus() == UsbSerialDriver.permissionStatusOpen) { return true; } } return false; } ///////////////////////////////////////////////////////////////////////////////////////////////////// // // Set the Data Terminal Ready flag on the device // // Args: idA - ID number from the open command // onA - on=T, off=F // // Returns: T/F Success/Failure // //////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean setDataTerminalReady(int idA, boolean onA) { try { UsbSerialDriver driverL = _findDriverByDeviceId(idA); if (driverL == null) return false; driverL.setDTR(onA); return true; } catch(IOException eA) { return false; } } //////////////////////////////////////////////////////////////////////////////////////////// // // Set the Request to Send flag // // Args: idA - ID number from the open command // onA - on=T, off=F // // Returns: T/F Success/Failure // //////////////////////////////////////////////////////////////////////////////////////////// public static boolean setRequestToSend(int idA, boolean onA) { try { UsbSerialDriver driverL = _findDriverByDeviceId(idA); if (driverL == null) return false; driverL.setRTS(onA); return true; } catch(IOException eA) { return false; } } /////////////////////////////////////////////////////////////////////////////////////////////// // // Purge the hardware buffers based on the input and output flags // // Args: idA - ID number from the open command // inputA - input buffer purge. purge=T // outputA - output buffer purge. purge=T // // Returns: T/F Success/Failure // /////////////////////////////////////////////////////////////////////////////////////////////// public static boolean purgeBuffers(int idA, boolean inputA, boolean outputA) { try { UsbSerialDriver driverL = _findDriverByDeviceId(idA); if (driverL == null) return false; return driverL.purgeHwBuffers(inputA, outputA); } catch(IOException eA) { return false; } } ////////////////////////////////////////////////////////////////////////////////////////// // // Get the native device handle (file descriptor) // // Args: idA - ID number from the open command // // Returns: device handle // /////////////////////////////////////////////////////////////////////////////////////////// public static int getDeviceHandle(int idA) { UsbSerialDriver driverL = _findDriverByDeviceId(idA); if (driverL == null) return -1; UsbDeviceConnection connectL = driverL.getDeviceConnection(); if (connectL == null) return -1; else return connectL.getFileDescriptor(); } ////////////////////////////////////////////////////////////////////////////////////////////// // // Get the open usb serial driver for the given id // // Args: idA - ID number from the open command // // Returns: usb device driver // ///////////////////////////////////////////////////////////////////////////////////////////// public static UsbSerialDriver getUsbSerialDriver(int idA) { return m_openedDevices.get(idA); } ////////////////////////////////////////////////////////////////////////////////////////////// // // Get the open usb serial driver for the given id // // Args: idA - ID number from the open command // // Returns: usb device driver // ///////////////////////////////////////////////////////////////////////////////////////////// public static UsbSerialDriver getUsbSerialDriver(int idA) { return m_openedDevices.get(idA); } UsbAccessory openUsbAccessory = null; Object openAccessoryLock = new Object(); private void openAccessory(UsbAccessory usbAccessory) { Log.i(TAG, "openAccessory: " + usbAccessory.getSerial()); try { synchronized(openAccessoryLock) { if ((openUsbAccessory != null && !taiSync.isRunning()) || openUsbAccessory == null) { openUsbAccessory = usbAccessory; taiSync.open(m_manager.openAccessory(usbAccessory)); } } } catch (IOException e) { Log.e(TAG, "openAccessory exception: " + e); taiSync.close(); closeAccessory(openUsbAccessory); } } private void closeAccessory(UsbAccessory usbAccessory) { Log.i(TAG, "closeAccessory"); synchronized(openAccessoryLock) { if (openUsbAccessory != null && usbAccessory == openUsbAccessory && taiSync.isRunning()) { taiSync.close(); openUsbAccessory = null; } } } private void probeAccessories() { final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // Log.i(TAG, "probeAccessories"); UsbAccessory[] accessories = m_manager.getAccessoryList(); if (accessories != null) { for (UsbAccessory usbAccessory : accessories) { if (m_manager.hasPermission(usbAccessory)) { openAccessory(usbAccessory); } else { Log.i(TAG, "requestPermission"); m_manager.requestPermission(usbAccessory, pendingIntent); } } } } }, 0, 3000); } }
Fixed merge
android/src/org/mavlink/qgroundcontrol/QGCActivity.java
Fixed merge
<ide><path>ndroid/src/org/mavlink/qgroundcontrol/QGCActivity.java <del> <add>package org.mavlink.qgroundcontrol; <ide> <ide> /* Copyright 2013 Google Inc. <ide> * <ide> <ide> public class QGCActivity extends QtActivity <ide> { <del> public static int BAD_PORT = 0; <del> private static QGCActivity m_instance; <del> private static UsbManager m_manager; // ANDROID USB HOST CLASS <del> private static List<UsbSerialDriver> m_devices; // LIST OF CURRENT DEVICES <del> private static HashMap<Integer, UsbSerialDriver> m_openedDevices; // LIST OF OPENED DEVICES <del> private static HashMap<Integer, UsbIoManager> m_ioManager; // THREADS FOR LISTENING FOR INCOMING DATA <del> private static HashMap<Integer, Integer> m_userData; // CORRESPONDING USER DATA FOR OPENED DEVICES. USED IN DISCONNECT CALLBACK <del> // USED TO DETECT WHEN A DEVICE HAS BEEN UNPLUGGED <del> private BroadcastReceiver m_UsbReceiver = null; <del> private final static ExecutorService m_Executor = Executors.newSingleThreadExecutor(); <del> private static final String TAG = "QGC_QGCActivity"; <del> private static PowerManager.WakeLock m_wl; <ide> public static int BAD_DEVICE_ID = 0; <ide> private static QGCActivity _instance = null; <ide> private static UsbManager _usbManager = null; <ide> } <ide> }; <ide> <del> // NATIVE C++ FUNCTION THAT WILL BE CALLED IF THE DEVICE IS UNPLUGGED <del> private static native void nativeDeviceHasDisconnected(int userDataA); <del> private static native void nativeDeviceException(int userDataA, String messageA); <del> private static native void nativeDeviceNewData(int userDataA, byte[] dataA); <ide> private final BroadcastReceiver mOpenAccessoryReceiver = <ide> new BroadcastReceiver() <ide> { <ide> } else { <ide> Log.i(TAG, "SCREEN_BRIGHT_WAKE_LOCK not acquired!!!"); <ide> } <del> m_instance.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); <ide> _instance.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); <ide> <ide> _usbManager = (UsbManager)_instance.getSystemService(Context.USB_SERVICE); <ide> <del> // Register for USB Detach and USB Permission intent <add> // Register for USB Detach and USB Permission intent <ide> IntentFilter filter = new IntentFilter(); <ide> filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); <ide> filter.addAction(ACTION_USB_PERMISSION); <ide> // Create intent for usb permission request <ide> _usbPermissionIntent = PendingIntent.getBroadcast(_instance, 0, new Intent(ACTION_USB_PERMISSION), 0); <ide> <del> if (m_manager == null) { <del> try { <del> m_manager = (UsbManager)m_instance.getSystemService(Context.USB_SERVICE); <del> taiSync = new TaiSync(); <del> <del> IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION); <del> filter.addAction( UsbManager.ACTION_USB_ACCESSORY_DETACHED); <del> registerReceiver(mOpenAccessoryReceiver, filter); <del> <del> probeAccessories(); <del> } catch(Exception e) { <del> Log.e(TAG, "Exception getCurrentDevices(): " + e); <del> } <add> try { <add> taiSync = new TaiSync(); <add> <add> IntentFilter accessoryFilter = new IntentFilter(ACTION_USB_PERMISSION); <add> filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED); <add> registerReceiver(mOpenAccessoryReceiver, accessoryFilter); <add> <add> probeAccessories(); <add> } catch(Exception e) { <add> Log.e(TAG, "Exception: " + e); <ide> } <ide> } <ide> <ide> @Override <del> protected void onDestroy() { <ide> protected void onDestroy() <ide> { <ide> unregisterReceiver(mOpenAccessoryReceiver); <ide> { <ide> List<UsbSerialDriver> currentDrivers = UsbSerialProber.findAllDevices(_usbManager); <ide> <del> if (m_manager == null) <del> m_manager = (UsbManager)m_instance.getSystemService(Context.USB_SERVICE); <del> <del> if (m_devices != null) <del> m_devices.clear(); <ide> // Remove stale drivers <ide> for (int i=_drivers.size()-1; i>=0; i--) { <ide> boolean found = false; <ide> String deviceInfo; <ide> UsbSerialDriver driver = _drivers.get(i); <ide> <del> // CHECK FOR ALREADY OPENED DEVICES AND DON"T INCLUDE THEM IN THE COUNT <del> for (iL=0; iL<m_devices.size(); iL++) <del> { <del> if (m_openedDevices.get(m_devices.get(iL).getDevice().getDeviceId()) != null) <del> { <del> countL++; <del> break; <ide> if (driver.permissionStatus() != UsbSerialDriver.permissionStatusSuccess) { <ide> continue; <ide> } <ide> return connectL.getFileDescriptor(); <ide> } <ide> <del> <del> <del> ////////////////////////////////////////////////////////////////////////////////////////////// <del> // <del> // Get the open usb serial driver for the given id <del> // <del> // Args: idA - ID number from the open command <del> // <del> // Returns: usb device driver <del> // <del> ///////////////////////////////////////////////////////////////////////////////////////////// <del> public static UsbSerialDriver getUsbSerialDriver(int idA) <del> { <del> return m_openedDevices.get(idA); <del> } <del> <del> <del> <del> ////////////////////////////////////////////////////////////////////////////////////////////// <del> // <del> // Get the open usb serial driver for the given id <del> // <del> // Args: idA - ID number from the open command <del> // <del> // Returns: usb device driver <del> // <del> ///////////////////////////////////////////////////////////////////////////////////////////// <del> public static UsbSerialDriver getUsbSerialDriver(int idA) <del> { <del> return m_openedDevices.get(idA); <del> } <del> <ide> UsbAccessory openUsbAccessory = null; <ide> Object openAccessoryLock = new Object(); <ide> <ide> synchronized(openAccessoryLock) { <ide> if ((openUsbAccessory != null && !taiSync.isRunning()) || openUsbAccessory == null) { <ide> openUsbAccessory = usbAccessory; <del> taiSync.open(m_manager.openAccessory(usbAccessory)); <add> taiSync.open(_usbManager.openAccessory(usbAccessory)); <ide> } <ide> } <ide> } catch (IOException e) { <ide> public void run() <ide> { <ide> // Log.i(TAG, "probeAccessories"); <del> UsbAccessory[] accessories = m_manager.getAccessoryList(); <add> UsbAccessory[] accessories = _usbManager.getAccessoryList(); <ide> if (accessories != null) { <ide> for (UsbAccessory usbAccessory : accessories) { <del> if (m_manager.hasPermission(usbAccessory)) { <add> if (_usbManager.hasPermission(usbAccessory)) { <ide> openAccessory(usbAccessory); <ide> } else { <ide> Log.i(TAG, "requestPermission"); <del> m_manager.requestPermission(usbAccessory, pendingIntent); <add> _usbManager.requestPermission(usbAccessory, pendingIntent); <ide> } <ide> } <ide> }
Java
apache-2.0
9c92906b09970e96c2875ef9f468f4502306b080
0
losipiuk/presto,ebyhr/presto,ebyhr/presto,hgschmie/presto,11xor6/presto,Praveen2112/presto,dain/presto,martint/presto,martint/presto,treasure-data/presto,dain/presto,smartnews/presto,electrum/presto,11xor6/presto,hgschmie/presto,smartnews/presto,losipiuk/presto,treasure-data/presto,smartnews/presto,treasure-data/presto,electrum/presto,Praveen2112/presto,treasure-data/presto,11xor6/presto,treasure-data/presto,losipiuk/presto,treasure-data/presto,erichwang/presto,Praveen2112/presto,ebyhr/presto,erichwang/presto,hgschmie/presto,electrum/presto,smartnews/presto,martint/presto,11xor6/presto,martint/presto,losipiuk/presto,electrum/presto,11xor6/presto,Praveen2112/presto,ebyhr/presto,dain/presto,Praveen2112/presto,hgschmie/presto,erichwang/presto,dain/presto,smartnews/presto,martint/presto,erichwang/presto,erichwang/presto,losipiuk/presto,electrum/presto,hgschmie/presto,ebyhr/presto,dain/presto
/* * 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 io.prestosql.sql.planner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.prestosql.Session; import io.prestosql.cost.StatsProvider; import io.prestosql.metadata.Metadata; import io.prestosql.sql.DynamicFilters; import io.prestosql.sql.analyzer.FeaturesConfig.JoinDistributionType; import io.prestosql.sql.analyzer.FeaturesConfig.JoinReorderingStrategy; import io.prestosql.sql.planner.assertions.BasePlanTest; import io.prestosql.sql.planner.assertions.MatchResult; import io.prestosql.sql.planner.assertions.Matcher; import io.prestosql.sql.planner.assertions.SymbolAliases; import io.prestosql.sql.planner.plan.EnforceSingleRowNode; import io.prestosql.sql.planner.plan.FilterNode; import io.prestosql.sql.planner.plan.JoinNode; import io.prestosql.sql.planner.plan.PlanNode; import org.testng.annotations.Test; import java.util.Optional; import static io.prestosql.SystemSessionProperties.ENABLE_DYNAMIC_FILTERING; import static io.prestosql.SystemSessionProperties.JOIN_DISTRIBUTION_TYPE; import static io.prestosql.SystemSessionProperties.JOIN_REORDERING_STRATEGY; import static io.prestosql.metadata.MetadataManager.createTestMetadataManager; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.anyNot; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.anyTree; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.equiJoinClause; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.exchange; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.expression; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.filter; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.join; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.node; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.project; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.semiJoin; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.tableScan; import static io.prestosql.sql.planner.plan.JoinNode.Type.INNER; import static io.prestosql.sql.planner.plan.JoinNode.Type.LEFT; public class TestDynamicFilter extends BasePlanTest { private final Metadata metadata = createTestMetadataManager(); public TestDynamicFilter() { super(ImmutableMap.of( ENABLE_DYNAMIC_FILTERING, "true", JOIN_REORDERING_STRATEGY, JoinReorderingStrategy.NONE.name(), JOIN_DISTRIBUTION_TYPE, JoinDistributionType.BROADCAST.name())); } @Test public void testNonInnerJoin() { assertPlan("SELECT o.orderkey FROM orders o LEFT JOIN lineitem l ON l.orderkey = o.orderkey", anyTree( join( LEFT, ImmutableList.of(equiJoinClause("ORDERS_OK", "LINEITEM_OK")), project( tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey"))), exchange( project( tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey"))))))); } @Test public void testEmptyJoinCriteria() { assertPlan("SELECT o.orderkey FROM orders o CROSS JOIN lineitem l", anyTree( join( INNER, ImmutableList.of(), tableScan("orders"), exchange( tableScan("lineitem"))))); } @Test public void testJoin() { assertPlan("SELECT o.orderkey FROM orders o, lineitem l WHERE l.orderkey = o.orderkey", anyTree( join( INNER, ImmutableList.of(equiJoinClause("ORDERS_OK", "LINEITEM_OK")), ImmutableMap.of("ORDERS_OK", "LINEITEM_OK"), Optional.empty(), tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey")), exchange( project( tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey")))), metadata))); } @Test public void testJoinOnCast() { assertPlan("SELECT o.orderkey FROM orders o, lineitem l WHERE cast(l.orderkey as int) = cast(o.orderkey as int)", anyTree( node( JoinNode.class, anyTree( node( FilterNode.class, tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey"))) .with(numberOfDynamicFilters(1))), anyTree( tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey")))))); } @Test public void testJoinMultipleEquiJoinClauses() { assertPlan("SELECT o.orderkey FROM orders o, lineitem l WHERE l.orderkey = o.orderkey AND l.partkey = o.custkey", anyTree( join( INNER, ImmutableList.of( equiJoinClause("ORDERS_OK", "LINEITEM_OK"), equiJoinClause("ORDERS_CK", "LINEITEM_PK")), ImmutableMap.of("ORDERS_OK", "LINEITEM_OK", "ORDERS_CK", "LINEITEM_PK"), Optional.empty(), tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey", "ORDERS_CK", "custkey")), exchange( project( tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey", "LINEITEM_PK", "partkey")))), metadata))); } @Test public void testJoinWithOrderBySameKey() { assertPlan("SELECT o.orderkey FROM orders o, lineitem l WHERE l.orderkey = o.orderkey ORDER BY l.orderkey ASC, o.orderkey ASC", anyTree( join( INNER, ImmutableList.of(equiJoinClause("ORDERS_OK", "LINEITEM_OK")), ImmutableMap.of("ORDERS_OK", "LINEITEM_OK"), Optional.empty(), tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey")), exchange( project( tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey")))), metadata))); } @Test public void testUncorrelatedSubqueries() { assertPlan("SELECT * FROM orders WHERE orderkey = (SELECT orderkey FROM lineitem ORDER BY orderkey LIMIT 1)", anyTree( join( INNER, ImmutableList.of(equiJoinClause("X", "Y")), ImmutableMap.of("X", "Y"), Optional.empty(), tableScan("orders", ImmutableMap.of("X", "orderkey")), project( node( EnforceSingleRowNode.class, anyTree( tableScan("lineitem", ImmutableMap.of("Y", "orderkey"))))), metadata))); assertPlan("SELECT * FROM orders WHERE orderkey IN (SELECT orderkey FROM lineitem WHERE linenumber % 4 = 0)", anyTree( filter("S", project( semiJoin("X", "Y", "S", anyTree( tableScan("orders", ImmutableMap.of("X", "orderkey"))), anyTree( tableScan("lineitem", ImmutableMap.of("Y", "orderkey")))))))); assertPlan("SELECT * FROM orders WHERE orderkey NOT IN (SELECT orderkey FROM lineitem WHERE linenumber < 0)", anyTree( filter("NOT S", project( semiJoin("X", "Y", "S", anyTree( tableScan("orders", ImmutableMap.of("X", "orderkey"))), anyTree( tableScan("lineitem", ImmutableMap.of("Y", "orderkey")))))))); } @Test public void testInnerInequalityJoinWithEquiJoinConjuncts() { assertPlan("SELECT 1 FROM orders o JOIN lineitem l ON o.shippriority = l.linenumber AND o.orderkey < l.orderkey", anyTree( anyNot( FilterNode.class, join( INNER, ImmutableList.of(equiJoinClause("O_SHIPPRIORITY", "L_LINENUMBER")), Optional.of("O_ORDERKEY < L_ORDERKEY"), anyTree(tableScan("orders", ImmutableMap.of( "O_SHIPPRIORITY", "shippriority", "O_ORDERKEY", "orderkey"))), anyTree(tableScan("lineitem", ImmutableMap.of( "L_LINENUMBER", "linenumber", "L_ORDERKEY", "orderkey"))))))); } @Test public void testSubTreeJoinDFOnProbeSide() { assertPlan( "SELECT part.partkey from part JOIN (lineitem JOIN orders ON lineitem.orderkey = orders.orderkey) ON part.partkey = lineitem.orderkey", anyTree( join( INNER, ImmutableList.of(equiJoinClause("PART_PK", "LINEITEM_OK")), ImmutableMap.of("PART_PK", "LINEITEM_OK"), Optional.empty(), tableScan("part", ImmutableMap.of("PART_PK", "partkey")), anyTree( join( INNER, ImmutableList.of(equiJoinClause("LINEITEM_OK", "ORDERS_OK")), ImmutableMap.of("LINEITEM_OK", "ORDERS_OK"), Optional.empty(), tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey")), exchange( project(tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey")))), metadata)), metadata))); } @Test public void testSubTreeJoinDFOnBuildSide() { assertPlan( "SELECT part.partkey from (lineitem JOIN orders ON lineitem.orderkey = orders.orderkey) JOIN part ON lineitem.orderkey = part.partkey", anyTree( join( INNER, ImmutableList.of(equiJoinClause("LINEITEM_OK", "PART_PK")), join( INNER, ImmutableList.of(equiJoinClause("LINEITEM_OK", "ORDERS_OK")), anyTree(node(FilterNode.class, tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey"))) .with(numberOfDynamicFilters(2))), anyTree(node(FilterNode.class, tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey"))) .with(numberOfDynamicFilters(1)))), exchange( project(tableScan("part", ImmutableMap.of("PART_PK", "partkey"))))))); } @Test public void testNestedDynamicFiltersRemoval() { assertPlan( "WITH t AS (" + " SELECT o.clerk FROM (" + " (orders o LEFT JOIN orders o1 ON o1.clerk = o.clerk) " + " LEFT JOIN orders o2 ON o2.clerk = o1.clerk)" + ") " + "SELECT t.clerk " + "FROM orders o3 JOIN t ON t.clerk = o3.clerk", anyTree( join( INNER, ImmutableList.of(equiJoinClause("ORDERS_CK", "ORDERS_CK6")), ImmutableMap.of("ORDERS_CK", "ORDERS_CK6"), Optional.empty(), tableScan("orders", ImmutableMap.of("ORDERS_CK", "clerk")), anyTree( join( LEFT, ImmutableList.of(equiJoinClause("ORDERS_CK16", "ORDERS_CK27")), anyTree( join( LEFT, ImmutableList.of(equiJoinClause("ORDERS_CK6", "ORDERS_CK16")), project( tableScan("orders", ImmutableMap.of("ORDERS_CK6", "clerk"))), exchange( project( tableScan("orders", ImmutableMap.of("ORDERS_CK16", "clerk")))))), anyTree( tableScan("orders", ImmutableMap.of("ORDERS_CK27", "clerk"))))), metadata))); } @Test public void testNonPushedDownJoinFilterRemoval() { assertPlan( "SELECT 1 FROM part t0, part t1, part t2 " + "WHERE t0.partkey = t1.partkey AND t0.partkey = t2.partkey " + "AND t0.size + t1.size = t2.size", anyTree( join( INNER, ImmutableList.of(equiJoinClause("K0", "K2"), equiJoinClause("S", "V2")), project( project( ImmutableMap.of("S", expression("V0 + V1")), join( INNER, ImmutableList.of(equiJoinClause("K0", "K1")), project( node( FilterNode.class, tableScan("part", ImmutableMap.of("K0", "partkey", "V0", "size"))) .with(numberOfDynamicFilters(2))), exchange( project( node( FilterNode.class, tableScan("part", ImmutableMap.of("K1", "partkey", "V1", "size"))) .with(numberOfDynamicFilters(1))))))), exchange( project( tableScan("part", ImmutableMap.of("K2", "partkey", "V2", "size"))))))); } private Matcher numberOfDynamicFilters(int numberOfDynamicFilters) { return new Matcher() { @Override public boolean shapeMatches(PlanNode node) { return node instanceof FilterNode; } @Override public MatchResult detailMatches(PlanNode node, StatsProvider stats, Session session, Metadata metadata, SymbolAliases symbolAliases) { FilterNode filterNode = (FilterNode) node; return new MatchResult(DynamicFilters.extractDynamicFilters(filterNode.getPredicate()).getDynamicConjuncts().size() == numberOfDynamicFilters); } }; } }
presto-main/src/test/java/io/prestosql/sql/planner/TestDynamicFilter.java
/* * 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 io.prestosql.sql.planner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.prestosql.metadata.Metadata; import io.prestosql.sql.analyzer.FeaturesConfig.JoinDistributionType; import io.prestosql.sql.analyzer.FeaturesConfig.JoinReorderingStrategy; import io.prestosql.sql.planner.assertions.BasePlanTest; import io.prestosql.sql.planner.plan.EnforceSingleRowNode; import io.prestosql.sql.planner.plan.FilterNode; import io.prestosql.sql.planner.plan.JoinNode; import org.testng.annotations.Test; import java.util.Optional; import static io.prestosql.SystemSessionProperties.ENABLE_DYNAMIC_FILTERING; import static io.prestosql.SystemSessionProperties.JOIN_DISTRIBUTION_TYPE; import static io.prestosql.SystemSessionProperties.JOIN_REORDERING_STRATEGY; import static io.prestosql.metadata.MetadataManager.createTestMetadataManager; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.anyNot; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.anyTree; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.equiJoinClause; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.exchange; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.expression; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.filter; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.join; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.node; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.project; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.semiJoin; import static io.prestosql.sql.planner.assertions.PlanMatchPattern.tableScan; import static io.prestosql.sql.planner.plan.JoinNode.Type.INNER; import static io.prestosql.sql.planner.plan.JoinNode.Type.LEFT; public class TestDynamicFilter extends BasePlanTest { private final Metadata metadata = createTestMetadataManager(); public TestDynamicFilter() { super(ImmutableMap.of( ENABLE_DYNAMIC_FILTERING, "true", JOIN_REORDERING_STRATEGY, JoinReorderingStrategy.NONE.name(), JOIN_DISTRIBUTION_TYPE, JoinDistributionType.BROADCAST.name())); } @Test public void testNonInnerJoin() { assertPlan("SELECT o.orderkey FROM orders o LEFT JOIN lineitem l ON l.orderkey = o.orderkey", anyTree( join( LEFT, ImmutableList.of(equiJoinClause("ORDERS_OK", "LINEITEM_OK")), project( tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey"))), exchange( project( tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey"))))))); } @Test public void testEmptyJoinCriteria() { assertPlan("SELECT o.orderkey FROM orders o CROSS JOIN lineitem l", anyTree( join( INNER, ImmutableList.of(), tableScan("orders"), exchange( tableScan("lineitem"))))); } @Test public void testJoin() { assertPlan("SELECT o.orderkey FROM orders o, lineitem l WHERE l.orderkey = o.orderkey", anyTree( join( INNER, ImmutableList.of(equiJoinClause("ORDERS_OK", "LINEITEM_OK")), ImmutableMap.of("ORDERS_OK", "LINEITEM_OK"), Optional.empty(), tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey")), exchange( project( tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey")))), metadata))); } @Test public void testJoinOnCast() { assertPlan("SELECT o.orderkey FROM orders o, lineitem l WHERE cast(l.orderkey as int) = cast(o.orderkey as int)", anyTree( node( JoinNode.class, anyTree( node( FilterNode.class, tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey")))), anyTree( tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey")))))); } @Test public void testJoinMultipleEquiJoinClauses() { assertPlan("SELECT o.orderkey FROM orders o, lineitem l WHERE l.orderkey = o.orderkey AND l.partkey = o.custkey", anyTree( join( INNER, ImmutableList.of( equiJoinClause("ORDERS_OK", "LINEITEM_OK"), equiJoinClause("ORDERS_CK", "LINEITEM_PK")), ImmutableMap.of("ORDERS_OK", "LINEITEM_OK", "ORDERS_CK", "LINEITEM_PK"), Optional.empty(), tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey", "ORDERS_CK", "custkey")), exchange( project( tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey", "LINEITEM_PK", "partkey")))), metadata))); } @Test public void testJoinWithOrderBySameKey() { assertPlan("SELECT o.orderkey FROM orders o, lineitem l WHERE l.orderkey = o.orderkey ORDER BY l.orderkey ASC, o.orderkey ASC", anyTree( join( INNER, ImmutableList.of(equiJoinClause("ORDERS_OK", "LINEITEM_OK")), ImmutableMap.of("ORDERS_OK", "LINEITEM_OK"), Optional.empty(), tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey")), exchange( project( tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey")))), metadata))); } @Test public void testUncorrelatedSubqueries() { assertPlan("SELECT * FROM orders WHERE orderkey = (SELECT orderkey FROM lineitem ORDER BY orderkey LIMIT 1)", anyTree( join( INNER, ImmutableList.of(equiJoinClause("X", "Y")), ImmutableMap.of("X", "Y"), Optional.empty(), tableScan("orders", ImmutableMap.of("X", "orderkey")), project( node( EnforceSingleRowNode.class, anyTree( tableScan("lineitem", ImmutableMap.of("Y", "orderkey"))))), metadata))); assertPlan("SELECT * FROM orders WHERE orderkey IN (SELECT orderkey FROM lineitem WHERE linenumber % 4 = 0)", anyTree( filter("S", project( semiJoin("X", "Y", "S", anyTree( tableScan("orders", ImmutableMap.of("X", "orderkey"))), anyTree( tableScan("lineitem", ImmutableMap.of("Y", "orderkey")))))))); assertPlan("SELECT * FROM orders WHERE orderkey NOT IN (SELECT orderkey FROM lineitem WHERE linenumber < 0)", anyTree( filter("NOT S", project( semiJoin("X", "Y", "S", anyTree( tableScan("orders", ImmutableMap.of("X", "orderkey"))), anyTree( tableScan("lineitem", ImmutableMap.of("Y", "orderkey")))))))); } @Test public void testInnerInequalityJoinWithEquiJoinConjuncts() { assertPlan("SELECT 1 FROM orders o JOIN lineitem l ON o.shippriority = l.linenumber AND o.orderkey < l.orderkey", anyTree( anyNot( FilterNode.class, join( INNER, ImmutableList.of(equiJoinClause("O_SHIPPRIORITY", "L_LINENUMBER")), Optional.of("O_ORDERKEY < L_ORDERKEY"), anyTree(tableScan("orders", ImmutableMap.of( "O_SHIPPRIORITY", "shippriority", "O_ORDERKEY", "orderkey"))), anyTree(tableScan("lineitem", ImmutableMap.of( "L_LINENUMBER", "linenumber", "L_ORDERKEY", "orderkey"))))))); } @Test public void testSubTreeJoinDFOnProbeSide() { assertPlan( "SELECT part.partkey from part JOIN (lineitem JOIN orders ON lineitem.orderkey = orders.orderkey) ON part.partkey = lineitem.orderkey", anyTree( join( INNER, ImmutableList.of(equiJoinClause("PART_PK", "LINEITEM_OK")), ImmutableMap.of("PART_PK", "LINEITEM_OK"), Optional.empty(), tableScan("part", ImmutableMap.of("PART_PK", "partkey")), anyTree( join( INNER, ImmutableList.of(equiJoinClause("LINEITEM_OK", "ORDERS_OK")), ImmutableMap.of("LINEITEM_OK", "ORDERS_OK"), Optional.empty(), tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey")), exchange( project(tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey")))), metadata)), metadata))); } @Test public void testSubTreeJoinDFOnBuildSide() { assertPlan( "SELECT part.partkey from (lineitem JOIN orders ON lineitem.orderkey = orders.orderkey) JOIN part ON lineitem.orderkey = part.partkey", anyTree( join( INNER, ImmutableList.of(equiJoinClause("LINEITEM_OK", "PART_PK")), join( INNER, ImmutableList.of(equiJoinClause("LINEITEM_OK", "ORDERS_OK")), anyTree(node(FilterNode.class, tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey")))), anyTree(node(FilterNode.class, tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey"))))), exchange( project(tableScan("part", ImmutableMap.of("PART_PK", "partkey"))))))); } @Test public void testNestedDynamicFiltersRemoval() { assertPlan( "WITH t AS (" + " SELECT o.clerk FROM (" + " (orders o LEFT JOIN orders o1 ON o1.clerk = o.clerk) " + " LEFT JOIN orders o2 ON o2.clerk = o1.clerk)" + ") " + "SELECT t.clerk " + "FROM orders o3 JOIN t ON t.clerk = o3.clerk", anyTree( join( INNER, ImmutableList.of(equiJoinClause("ORDERS_CK", "ORDERS_CK6")), ImmutableMap.of("ORDERS_CK", "ORDERS_CK6"), Optional.empty(), tableScan("orders", ImmutableMap.of("ORDERS_CK", "clerk")), anyTree( join( LEFT, ImmutableList.of(equiJoinClause("ORDERS_CK16", "ORDERS_CK27")), anyTree( join( LEFT, ImmutableList.of(equiJoinClause("ORDERS_CK6", "ORDERS_CK16")), project( tableScan("orders", ImmutableMap.of("ORDERS_CK6", "clerk"))), exchange( project( tableScan("orders", ImmutableMap.of("ORDERS_CK16", "clerk")))))), anyTree( tableScan("orders", ImmutableMap.of("ORDERS_CK27", "clerk"))))), metadata))); } @Test public void testNonPushedDownJoinFilterRemoval() { assertPlan( "SELECT 1 FROM part t0, part t1, part t2 " + "WHERE t0.partkey = t1.partkey AND t0.partkey = t2.partkey " + "AND t0.size + t1.size = t2.size", anyTree( join( INNER, ImmutableList.of(equiJoinClause("K0", "K2"), equiJoinClause("S", "V2")), project( project( ImmutableMap.of("S", expression("V0 + V1")), join( INNER, ImmutableList.of(equiJoinClause("K0", "K1")), project( node( FilterNode.class, tableScan("part", ImmutableMap.of("K0", "partkey", "V0", "size")))), exchange( project( node( FilterNode.class, tableScan("part", ImmutableMap.of("K1", "partkey", "V1", "size")))))))), exchange( project( tableScan("part", ImmutableMap.of("K2", "partkey", "V2", "size"))))))); } }
Assert number of dynamic filters
presto-main/src/test/java/io/prestosql/sql/planner/TestDynamicFilter.java
Assert number of dynamic filters
<ide><path>resto-main/src/test/java/io/prestosql/sql/planner/TestDynamicFilter.java <ide> <ide> import com.google.common.collect.ImmutableList; <ide> import com.google.common.collect.ImmutableMap; <add>import io.prestosql.Session; <add>import io.prestosql.cost.StatsProvider; <ide> import io.prestosql.metadata.Metadata; <add>import io.prestosql.sql.DynamicFilters; <ide> import io.prestosql.sql.analyzer.FeaturesConfig.JoinDistributionType; <ide> import io.prestosql.sql.analyzer.FeaturesConfig.JoinReorderingStrategy; <ide> import io.prestosql.sql.planner.assertions.BasePlanTest; <add>import io.prestosql.sql.planner.assertions.MatchResult; <add>import io.prestosql.sql.planner.assertions.Matcher; <add>import io.prestosql.sql.planner.assertions.SymbolAliases; <ide> import io.prestosql.sql.planner.plan.EnforceSingleRowNode; <ide> import io.prestosql.sql.planner.plan.FilterNode; <ide> import io.prestosql.sql.planner.plan.JoinNode; <add>import io.prestosql.sql.planner.plan.PlanNode; <ide> import org.testng.annotations.Test; <ide> <ide> import java.util.Optional; <ide> anyTree( <ide> node( <ide> FilterNode.class, <del> tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey")))), <add> tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey"))) <add> .with(numberOfDynamicFilters(1))), <ide> anyTree( <ide> tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey")))))); <ide> } <ide> INNER, <ide> ImmutableList.of(equiJoinClause("LINEITEM_OK", "ORDERS_OK")), <ide> anyTree(node(FilterNode.class, <del> tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey")))), <add> tableScan("lineitem", ImmutableMap.of("LINEITEM_OK", "orderkey"))) <add> .with(numberOfDynamicFilters(2))), <ide> anyTree(node(FilterNode.class, <del> tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey"))))), <add> tableScan("orders", ImmutableMap.of("ORDERS_OK", "orderkey"))) <add> .with(numberOfDynamicFilters(1)))), <ide> exchange( <ide> project(tableScan("part", ImmutableMap.of("PART_PK", "partkey"))))))); <ide> } <ide> project( <ide> node( <ide> FilterNode.class, <del> tableScan("part", ImmutableMap.of("K0", "partkey", "V0", "size")))), <add> tableScan("part", ImmutableMap.of("K0", "partkey", "V0", "size"))) <add> .with(numberOfDynamicFilters(2))), <ide> exchange( <ide> project( <ide> node( <ide> FilterNode.class, <del> tableScan("part", ImmutableMap.of("K1", "partkey", "V1", "size")))))))), <add> tableScan("part", ImmutableMap.of("K1", "partkey", "V1", "size"))) <add> .with(numberOfDynamicFilters(1))))))), <ide> exchange( <ide> project( <ide> tableScan("part", ImmutableMap.of("K2", "partkey", "V2", "size"))))))); <ide> } <add> <add> private Matcher numberOfDynamicFilters(int numberOfDynamicFilters) <add> { <add> return new Matcher() <add> { <add> @Override <add> public boolean shapeMatches(PlanNode node) <add> { <add> return node instanceof FilterNode; <add> } <add> <add> @Override <add> public MatchResult detailMatches(PlanNode node, StatsProvider stats, Session session, Metadata metadata, SymbolAliases symbolAliases) <add> { <add> FilterNode filterNode = (FilterNode) node; <add> return new MatchResult(DynamicFilters.extractDynamicFilters(filterNode.getPredicate()).getDynamicConjuncts().size() == numberOfDynamicFilters); <add> } <add> }; <add> } <ide> }
Java
apache-2.0
8e00c77999775e686df0a07bd3c9cd99b676c4dd
0
realityforge/arez,realityforge/arez,realityforge/arez
package org.realityforge.arez; import java.util.Objects; import java.util.concurrent.atomic.AtomicReference; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.Test; import static org.testng.Assert.*; public class ComputedValueTest extends AbstractArezTest { @Test public void initialState() throws Exception { final ArezContext context = new ArezContext(); final String name = ValueUtil.randomString(); final SafeFunction<String> function = () -> ""; final EqualityComparator<String> comparator = Objects::equals; final ComputedValue<String> computedValue = new ComputedValue<>( context, name, function, comparator ); assertEquals( computedValue.getName(), name ); assertEquals( computedValue.getContext(), context ); assertEquals( computedValue.toString(), name ); // Value starts out as null assertEquals( computedValue.getValue(), null ); // Verify the linking of all child elements assertEquals( computedValue.getObserver().getName(), name ); assertEquals( computedValue.getObserver().isDerivation(), true ); assertEquals( computedValue.getObserver().getComputedValue(), computedValue ); assertEquals( computedValue.getObservable().getName(), name ); assertEquals( computedValue.getObservable().isCalculated(), true ); assertEquals( computedValue.getObservable().getOwner(), computedValue.getObserver() ); } @Test public void computeValue() throws Exception { final ArezContext context = new ArezContext(); final String name = ValueUtil.randomString(); final AtomicReference<String> value = new AtomicReference<>(); value.set( "" ); final SafeFunction<String> function = value::get; final EqualityComparator<String> comparator = Objects::equals; final ComputedValue<String> computedValue = new ComputedValue<>( context, name, function, comparator ); assertEquals( computedValue.computeValue(), "" ); value.set( "XXX" ); assertEquals( computedValue.computeValue(), "XXX" ); } @Test public void compute() throws Exception { final ArezContext context = new ArezContext(); final String name = ValueUtil.randomString(); final AtomicReference<String> value = new AtomicReference<>(); final String value1 = ValueUtil.randomString(); final String value2 = ValueUtil.randomString(); final SafeFunction<String> function = value::get; final EqualityComparator<String> comparator = Objects::equals; final ComputedValue<String> computedValue = new ComputedValue<>( context, name, function, comparator ); setCurrentTransaction( computedValue.getObserver() ); final Observer observer = newReadOnlyObserver( context ); observer.setState( ObserverState.POSSIBLY_STALE ); computedValue.getObserver().getDerivedValue().addObserver( observer ); observer.getDependencies().add( computedValue.getObservable() ); computedValue.getObservable().setLeastStaleObserverState( ObserverState.POSSIBLY_STALE ); computedValue.setValue( value1 ); value.set( value2 ); computedValue.compute(); assertEquals( computedValue.getValue(), value2 ); assertEquals( observer.getState(), ObserverState.STALE ); } @Test public void compute_whereValueMatches() throws Exception { final ArezContext context = new ArezContext(); final String name = ValueUtil.randomString(); final AtomicReference<String> value = new AtomicReference<>(); final String value1 = ValueUtil.randomString(); final SafeFunction<String> function = value::get; final EqualityComparator<String> comparator = Objects::equals; final ComputedValue<String> computedValue = new ComputedValue<>( context, name, function, comparator ); setCurrentTransaction( computedValue.getObserver() ); final Observer observer = newReadOnlyObserver( context ); observer.setState( ObserverState.POSSIBLY_STALE ); computedValue.getObserver().getDerivedValue().addObserver( observer ); observer.getDependencies().add( computedValue.getObservable() ); computedValue.getObservable().setLeastStaleObserverState( ObserverState.POSSIBLY_STALE ); value.set( value1 ); computedValue.setValue( value1 ); computedValue.compute(); assertEquals( computedValue.getValue(), value1 ); // Verify state does not change assertEquals( observer.getState(), ObserverState.POSSIBLY_STALE ); } @Test public void dispose() throws Exception { final ArezContext context = new ArezContext(); final Observer observer = newDerivation( context ); final ComputedValue<?> computedValue = observer.getComputedValue(); setCurrentTransaction( observer ); observer.setState( ObserverState.UP_TO_DATE ); assertEquals( observer.isDisposed(), false ); context.setTransaction( null ); computedValue.dispose(); assertEquals( observer.isDisposed(), true ); assertEquals( observer.getState(), ObserverState.INACTIVE ); } @Test public void dispose_nestedInReadOnlyTransaction() throws Exception { final ArezContext context = new ArezContext(); final Observer observer = newDerivation( context ); final ComputedValue<?> computedValue = observer.getComputedValue(); setCurrentTransaction( newReadOnlyObserver( context ) ); observer.setState( ObserverState.UP_TO_DATE ); assertEquals( observer.isDisposed(), false ); final IllegalStateException exception = expectThrows( IllegalStateException.class, computedValue::dispose ); assertEquals( exception.getMessage(), "Attempting to create READ_WRITE transaction named '" + computedValue.getName() + "' but it is nested in transaction named '" + context.getTransaction().getName() + "' with mode READ_ONLY which is not equal to READ_WRITE." ); assertEquals( observer.isDisposed(), false ); } @Test public void get_upToDateComputedValue() throws Exception { final ArezContext context = new ArezContext(); final ComputedValue<String> computedValue = new ComputedValue<>( context, ValueUtil.randomString(), () -> "", Objects::equals ); final Observer observer = computedValue.getObserver(); setCurrentTransaction( context ); observer.setState( ObserverState.UP_TO_DATE ); computedValue.setValue( "XXX" ); assertEquals( computedValue.get(), "XXX" ); assertEquals( observer.getState(), ObserverState.UP_TO_DATE ); } @Test public void get_staleComputedValue() throws Exception { final ArezContext context = new ArezContext(); final ComputedValue<String> computedValue = new ComputedValue<>( context, ValueUtil.randomString(), () -> "", Objects::equals ); final Observer observer = computedValue.getObserver(); setCurrentTransaction( context ); observer.setState( ObserverState.STALE ); computedValue.setValue( "XXX" ); assertEquals( computedValue.get(), "" ); assertEquals( observer.getState(), ObserverState.UP_TO_DATE ); } @Test public void get_disposedComputedValue() throws Exception { final ArezContext context = new ArezContext(); final ComputedValue<String> computedValue = new ComputedValue<>( context, ValueUtil.randomString(), () -> "", Objects::equals ); final Observer observer = computedValue.getObserver(); setCurrentTransaction( observer ); observer.setState( ObserverState.STALE ); computedValue.setValue( "XXX" ); observer.setDisposed( true ); final IllegalStateException exception = expectThrows( IllegalStateException.class, computedValue::get ); assertEquals( exception.getMessage(), "ComputedValue named '" + computedValue.getName() + "' accessed after it " + "has been disposed." ); } @Test public void get_cycleDetected() throws Exception { final ArezContext context = new ArezContext(); final ComputedValue<String> computedValue = new ComputedValue<>( context, ValueUtil.randomString(), () -> "", Objects::equals ); final Observer observer = computedValue.getObserver(); setCurrentTransaction( context ); observer.setState( ObserverState.UP_TO_DATE ); computedValue.setValue( "XXX" ); computedValue.setComputing( true ); final IllegalStateException exception = expectThrows( IllegalStateException.class, computedValue::get ); assertEquals( exception.getMessage(), "Detected a cycle deriving ComputedValue named '" + computedValue.getName() + "'." ); computedValue.setComputing( false ); assertEquals( computedValue.get(), "XXX" ); assertEquals( observer.getState(), ObserverState.UP_TO_DATE ); } }
core/src/test/java/org/realityforge/arez/ComputedValueTest.java
package org.realityforge.arez; import java.util.Objects; import java.util.concurrent.atomic.AtomicReference; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.Test; import static org.testng.Assert.*; public class ComputedValueTest extends AbstractArezTest { @Test public void initialState() throws Exception { final ArezContext context = new ArezContext(); final String name = ValueUtil.randomString(); final SafeFunction<String> function = () -> ""; final EqualityComparator<String> comparator = Objects::equals; final ComputedValue<String> computedValue = new ComputedValue<>( context, name, function, comparator ); assertEquals( computedValue.getName(), name ); assertEquals( computedValue.getContext(), context ); assertEquals( computedValue.toString(), name ); // Value starts out as null assertEquals( computedValue.getValue(), null ); // Verify the linking of all child elements assertEquals( computedValue.getObserver().getName(), name ); assertEquals( computedValue.getObserver().isDerivation(), true ); assertEquals( computedValue.getObserver().getComputedValue(), computedValue ); assertEquals( computedValue.getObservable().getName(), name ); assertEquals( computedValue.getObservable().isCalculated(), true ); assertEquals( computedValue.getObservable().getOwner(), computedValue.getObserver() ); } @Test public void computeValue() throws Exception { final ArezContext context = new ArezContext(); final String name = ValueUtil.randomString(); final AtomicReference<String> value = new AtomicReference<>(); value.set( "" ); final SafeFunction<String> function = value::get; final EqualityComparator<String> comparator = Objects::equals; final ComputedValue<String> computedValue = new ComputedValue<>( context, name, function, comparator ); assertEquals( computedValue.computeValue(), "" ); value.set( "XXX" ); assertEquals( computedValue.computeValue(), "XXX" ); } @Test public void compute() throws Exception { final ArezContext context = new ArezContext(); final String name = ValueUtil.randomString(); final AtomicReference<String> value = new AtomicReference<>(); final String value1 = ValueUtil.randomString(); final String value2 = ValueUtil.randomString(); final SafeFunction<String> function = value::get; final EqualityComparator<String> comparator = Objects::equals; final ComputedValue<String> computedValue = new ComputedValue<>( context, name, function, comparator ); setCurrentTransaction( computedValue.getObserver() ); final Observer observer = newReadOnlyObserver( context ); observer.setState( ObserverState.POSSIBLY_STALE ); computedValue.getObserver().getDerivedValue().addObserver( observer ); observer.getDependencies().add( computedValue.getObservable() ); computedValue.getObservable().setLeastStaleObserverState( ObserverState.POSSIBLY_STALE ); computedValue.setValue( value1 ); value.set( value2 ); computedValue.compute(); assertEquals( computedValue.getValue(), value2 ); assertEquals( observer.getState(), ObserverState.STALE ); } @Test public void compute_whereValueMatches() throws Exception { final ArezContext context = new ArezContext(); final String name = ValueUtil.randomString(); final AtomicReference<String> value = new AtomicReference<>(); final String value1 = ValueUtil.randomString(); final SafeFunction<String> function = value::get; final EqualityComparator<String> comparator = Objects::equals; final ComputedValue<String> computedValue = new ComputedValue<>( context, name, function, comparator ); setCurrentTransaction( computedValue.getObserver() ); final Observer observer = newReadOnlyObserver( context ); observer.setState( ObserverState.POSSIBLY_STALE ); computedValue.getObserver().getDerivedValue().addObserver( observer ); observer.getDependencies().add( computedValue.getObservable() ); computedValue.getObservable().setLeastStaleObserverState( ObserverState.POSSIBLY_STALE ); value.set( value1 ); computedValue.setValue( value1 ); computedValue.compute(); assertEquals( computedValue.getValue(), value1 ); // Verify state does not change assertEquals( observer.getState(), ObserverState.POSSIBLY_STALE ); } @Test public void dispose() throws Exception { final ArezContext context = new ArezContext(); final Observer observer = newDerivation( context ); final ComputedValue<?> computedValue = observer.getComputedValue(); setCurrentTransaction( observer ); observer.setState( ObserverState.UP_TO_DATE ); assertEquals( observer.isDisposed(), false ); context.setTransaction( null ); computedValue.dispose(); assertEquals( observer.isDisposed(), true ); assertEquals( observer.getState(), ObserverState.INACTIVE ); } @Test public void get_upToDateComputedValue() throws Exception { final ArezContext context = new ArezContext(); final ComputedValue<String> computedValue = new ComputedValue<>( context, ValueUtil.randomString(), () -> "", Objects::equals ); final Observer observer = computedValue.getObserver(); setCurrentTransaction( context ); observer.setState( ObserverState.UP_TO_DATE ); computedValue.setValue( "XXX" ); assertEquals( computedValue.get(), "XXX" ); assertEquals( observer.getState(), ObserverState.UP_TO_DATE ); } @Test public void get_staleComputedValue() throws Exception { final ArezContext context = new ArezContext(); final ComputedValue<String> computedValue = new ComputedValue<>( context, ValueUtil.randomString(), () -> "", Objects::equals ); final Observer observer = computedValue.getObserver(); setCurrentTransaction( context ); observer.setState( ObserverState.STALE ); computedValue.setValue( "XXX" ); assertEquals( computedValue.get(), "" ); assertEquals( observer.getState(), ObserverState.UP_TO_DATE ); } @Test public void get_disposedComputedValue() throws Exception { final ArezContext context = new ArezContext(); final ComputedValue<String> computedValue = new ComputedValue<>( context, ValueUtil.randomString(), () -> "", Objects::equals ); final Observer observer = computedValue.getObserver(); setCurrentTransaction( observer ); observer.setState( ObserverState.STALE ); computedValue.setValue( "XXX" ); observer.setDisposed( true ); final IllegalStateException exception = expectThrows( IllegalStateException.class, computedValue::get ); assertEquals( exception.getMessage(), "ComputedValue named '" + computedValue.getName() + "' accessed after it " + "has been disposed." ); } @Test public void get_cycleDetected() throws Exception { final ArezContext context = new ArezContext(); final ComputedValue<String> computedValue = new ComputedValue<>( context, ValueUtil.randomString(), () -> "", Objects::equals ); final Observer observer = computedValue.getObserver(); setCurrentTransaction( context ); observer.setState( ObserverState.UP_TO_DATE ); computedValue.setValue( "XXX" ); computedValue.setComputing( true ); final IllegalStateException exception = expectThrows( IllegalStateException.class, computedValue::get ); assertEquals( exception.getMessage(), "Detected a cycle deriving ComputedValue named '" + computedValue.getName() + "'." ); computedValue.setComputing( false ); assertEquals( computedValue.get(), "XXX" ); assertEquals( observer.getState(), ObserverState.UP_TO_DATE ); } }
Verify dispose is called in read-write transaction
core/src/test/java/org/realityforge/arez/ComputedValueTest.java
Verify dispose is called in read-write transaction
<ide><path>ore/src/test/java/org/realityforge/arez/ComputedValueTest.java <ide> } <ide> <ide> @Test <add> public void dispose_nestedInReadOnlyTransaction() <add> throws Exception <add> { <add> final ArezContext context = new ArezContext(); <add> <add> final Observer observer = newDerivation( context ); <add> final ComputedValue<?> computedValue = observer.getComputedValue(); <add> <add> setCurrentTransaction( newReadOnlyObserver( context ) ); <add> observer.setState( ObserverState.UP_TO_DATE ); <add> <add> assertEquals( observer.isDisposed(), false ); <add> <add> final IllegalStateException exception = expectThrows( IllegalStateException.class, computedValue::dispose ); <add> <add> assertEquals( exception.getMessage(), <add> "Attempting to create READ_WRITE transaction named '" + computedValue.getName() + <add> "' but it is nested in transaction named '" + context.getTransaction().getName() + <add> "' with mode READ_ONLY which is not equal to READ_WRITE." ); <add> <add> assertEquals( observer.isDisposed(), false ); <add> } <add> <add> @Test <ide> public void get_upToDateComputedValue() <ide> throws Exception <ide> {
Java
apache-2.0
8cc42170995623f3bf25fa0a0e0989e9fb249796
0
mtransitapps/mtransit-for-android,mtransitapps/mtransit-for-android,mtransitapps/mtransit-for-android
package org.mtransit.android.task; import java.util.ArrayList; import java.util.HashSet; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.mtransit.android.commons.CollectionUtils; import org.mtransit.android.commons.MTLog; import org.mtransit.android.commons.RuntimeUtils; import org.mtransit.android.commons.data.News; import org.mtransit.android.commons.provider.NewsProviderContract; import org.mtransit.android.commons.provider.NewsProviderContract.Filter; import org.mtransit.android.commons.task.MTCallable; import org.mtransit.android.data.DataSourceManager; import org.mtransit.android.data.DataSourceProvider; import org.mtransit.android.data.NewsProviderProperties; import android.content.Context; public class NewsLoader extends MTAsyncTaskLoaderV4<ArrayList<News>> { private static final String TAG = NewsLoader.class.getSimpleName(); @Override public String getLogTag() { return TAG; } private ArrayList<News> news; private ArrayList<String> targetAuthorities; private ArrayList<String> filterUUIDs; private ArrayList<String> filterTargets; public NewsLoader(Context context, ArrayList<String> optTargetAuthorities, ArrayList<String> optFilterUUIDs, ArrayList<String> optFilterTargets) { super(context); this.targetAuthorities = optTargetAuthorities; this.filterUUIDs = optFilterUUIDs; this.filterTargets = optFilterTargets; } @Override public ArrayList<News> loadInBackgroundMT() { if (this.news != null) { return this.news; } this.news = new ArrayList<News>(); ArrayList<NewsProviderProperties> newsProviders; if (CollectionUtils.getSize(this.targetAuthorities) == 0) { newsProviders = DataSourceProvider.get(getContext()).getAllNewsProvider(); } else { newsProviders = new ArrayList<NewsProviderProperties>(); for (String targetAuthority : this.targetAuthorities) { newsProviders.addAll(DataSourceProvider.get(getContext()).getTargetAuthorityNewsProviders(targetAuthority)); } } if (CollectionUtils.getSize(newsProviders) == 0) { MTLog.w(this, "loadInBackground() > no News provider found"); return this.news; } ThreadPoolExecutor executor = new ThreadPoolExecutor(RuntimeUtils.NUMBER_OF_CORES, RuntimeUtils.NUMBER_OF_CORES, 1, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(newsProviders.size())); ArrayList<Future<ArrayList<News>>> taskList = new ArrayList<Future<ArrayList<News>>>(); for (NewsProviderProperties newsProvider : newsProviders) { taskList.add(executor.submit(new FindNewsTask(getContext(), newsProvider.getAuthority(), this.filterUUIDs, this.filterTargets))); } HashSet<String> newsUUIDs = new HashSet<String>(); for (Future<ArrayList<News>> future : taskList) { try { ArrayList<News> agencyNews = future.get(); if (agencyNews != null) { for (News aNews : agencyNews) { if (newsUUIDs.contains(aNews.getUUID())) { continue; } this.news.add(aNews); newsUUIDs.add(aNews.getUUID()); } } } catch (Exception e) { MTLog.w(this, e, "Error while loading in background!"); } } executor.shutdown(); CollectionUtils.sort(this.news, News.NEWS_COMPARATOR); return this.news; } @Override protected void onStartLoading() { super.onStartLoading(); if (this.news != null) { deliverResult(this.news); } if (this.news == null) { forceLoad(); } } @Override protected void onStopLoading() { super.onStopLoading(); cancelLoad(); } @Override public void deliverResult(ArrayList<News> data) { this.news = data; if (isStarted()) { super.deliverResult(data); } } private static class FindNewsTask extends MTCallable<ArrayList<News>> { private static final String TAG = NewsLoader.class.getSimpleName() + ">" + FindNewsTask.class.getSimpleName(); @Override public String getLogTag() { return TAG; } private Context context; private String authority; private ArrayList<String> filterUUIDs; private ArrayList<String> filterTargets; public FindNewsTask(Context context, String authority, ArrayList<String> optFilterUUIDs, ArrayList<String> optFilterTargets) { this.context = context; this.authority = authority; this.filterUUIDs = optFilterUUIDs; this.filterTargets = optFilterTargets; } @Override public ArrayList<News> callMT() throws Exception { Filter newsFilter; if (CollectionUtils.getSize(this.filterUUIDs) > 0) { newsFilter = NewsProviderContract.Filter.getNewUUIDsFilter(this.filterUUIDs); } else if (CollectionUtils.getSize(this.filterTargets) > 0) { newsFilter = NewsProviderContract.Filter.getNewTargetsFilter(this.filterTargets); } else { newsFilter = NewsProviderContract.Filter.getNewEmptyFilter(); } return DataSourceManager.findNews(this.context, this.authority, newsFilter); } } }
src/org/mtransit/android/task/NewsLoader.java
package org.mtransit.android.task; import java.util.ArrayList; import java.util.HashSet; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.mtransit.android.commons.CollectionUtils; import org.mtransit.android.commons.MTLog; import org.mtransit.android.commons.RuntimeUtils; import org.mtransit.android.commons.data.News; import org.mtransit.android.commons.provider.NewsProviderContract; import org.mtransit.android.commons.provider.NewsProviderContract.Filter; import org.mtransit.android.commons.task.MTCallable; import org.mtransit.android.data.DataSourceManager; import org.mtransit.android.data.DataSourceProvider; import org.mtransit.android.data.NewsProviderProperties; import android.content.Context; public class NewsLoader extends MTAsyncTaskLoaderV4<ArrayList<News>> { private static final String TAG = NewsLoader.class.getSimpleName(); @Override public String getLogTag() { return TAG; } private ArrayList<News> news; private ArrayList<String> targetAuthorities; private ArrayList<String> filterUUIDs; private ArrayList<String> filterTargets; public NewsLoader(Context context, ArrayList<String> optTargetAuthorities, ArrayList<String> optFilterUUIDs, ArrayList<String> optFilterTargets) { super(context); this.targetAuthorities = optTargetAuthorities; this.filterUUIDs = optFilterUUIDs; this.filterTargets = optFilterTargets; } @Override public ArrayList<News> loadInBackgroundMT() { if (this.news != null) { return this.news; } this.news = new ArrayList<News>(); ArrayList<NewsProviderProperties> newsProviders; if (CollectionUtils.getSize(this.targetAuthorities) == 0) { newsProviders = DataSourceProvider.get(getContext()).getAllNewsProvider(); } else { newsProviders = new ArrayList<NewsProviderProperties>(); for (String targetAuthority : this.targetAuthorities) { newsProviders.addAll(DataSourceProvider.get(getContext()).getTargetAuthorityNewsProviders(targetAuthority)); } } if (CollectionUtils.getSize(newsProviders) == 0) { MTLog.w(this, "loadInBackground() > no News provider found"); return this.news; } ThreadPoolExecutor executor = new ThreadPoolExecutor(RuntimeUtils.NUMBER_OF_CORES, RuntimeUtils.NUMBER_OF_CORES, 1, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(newsProviders.size())); ArrayList<Future<ArrayList<News>>> taskList = new ArrayList<Future<ArrayList<News>>>(); for (NewsProviderProperties newsProvider : newsProviders) { taskList.add(executor.submit(new FindNewsTask(getContext(), newsProvider.getAuthority(), this.filterUUIDs, this.filterTargets))); } HashSet<String> newsUUIDs = new HashSet<String>(); for (Future<ArrayList<News>> future : taskList) { try { ArrayList<News> agencyNews = future.get(); for (News aNews : agencyNews) { if (newsUUIDs.contains(aNews.getUUID())) { continue; } this.news.add(aNews); newsUUIDs.add(aNews.getUUID()); } } catch (Exception e) { MTLog.w(this, e, "Error while loading in background!"); } } executor.shutdown(); CollectionUtils.sort(this.news, News.NEWS_COMPARATOR); return this.news; } @Override protected void onStartLoading() { super.onStartLoading(); if (this.news != null) { deliverResult(this.news); } if (this.news == null) { forceLoad(); } } @Override protected void onStopLoading() { super.onStopLoading(); cancelLoad(); } @Override public void deliverResult(ArrayList<News> data) { this.news = data; if (isStarted()) { super.deliverResult(data); } } private static class FindNewsTask extends MTCallable<ArrayList<News>> { private static final String TAG = NewsLoader.class.getSimpleName() + ">" + FindNewsTask.class.getSimpleName(); @Override public String getLogTag() { return TAG; } private Context context; private String authority; private ArrayList<String> filterUUIDs; private ArrayList<String> filterTargets; public FindNewsTask(Context context, String authority, ArrayList<String> optFilterUUIDs, ArrayList<String> optFilterTargets) { this.context = context; this.authority = authority; this.filterUUIDs = optFilterUUIDs; this.filterTargets = optFilterTargets; } @Override public ArrayList<News> callMT() throws Exception { Filter newsFilter; if (CollectionUtils.getSize(this.filterUUIDs) > 0) { newsFilter = NewsProviderContract.Filter.getNewUUIDsFilter(this.filterUUIDs); } else if (CollectionUtils.getSize(this.filterTargets) > 0) { newsFilter = NewsProviderContract.Filter.getNewTargetsFilter(this.filterTargets); } else { newsFilter = NewsProviderContract.Filter.getNewEmptyFilter(); } return DataSourceManager.findNews(this.context, this.authority, newsFilter); } } }
Fix NPE in production.
src/org/mtransit/android/task/NewsLoader.java
Fix NPE in production.
<ide><path>rc/org/mtransit/android/task/NewsLoader.java <ide> for (Future<ArrayList<News>> future : taskList) { <ide> try { <ide> ArrayList<News> agencyNews = future.get(); <del> for (News aNews : agencyNews) { <del> if (newsUUIDs.contains(aNews.getUUID())) { <del> continue; <add> if (agencyNews != null) { <add> for (News aNews : agencyNews) { <add> if (newsUUIDs.contains(aNews.getUUID())) { <add> continue; <add> } <add> this.news.add(aNews); <add> newsUUIDs.add(aNews.getUUID()); <ide> } <del> this.news.add(aNews); <del> newsUUIDs.add(aNews.getUUID()); <ide> } <ide> } catch (Exception e) { <ide> MTLog.w(this, e, "Error while loading in background!");
Java
apache-2.0
7fc2490efa12848cf99c5d8259c1c3c8fbdb6832
0
kieker-monitoring/kieker,HaStr/kieker,leadwire-apm/leadwire-javaagent,HaStr/kieker,leadwire-apm/leadwire-javaagent,kieker-monitoring/kieker,HaStr/kieker,kieker-monitoring/kieker,kieker-monitoring/kieker,HaStr/kieker,kieker-monitoring/kieker,HaStr/kieker
/*************************************************************************** * Copyright 2012 Kieker Project (http://kieker-monitoring.net) * * 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 kieker.monitoring.core.controller; import java.util.List; /** * @author Jan Waller */ public interface IProbeController { /** * Activates a probe. * * @param pattern * pattern for the probe * @return * true on success */ public boolean activateProbe(final String pattern); /** * Deactivates a probe. * * @param pattern * pattern for the probe * @return * true on success */ public boolean deactivateProbe(final String pattern); /** * Tests if a probe is active. * * @param signature * signature of the probe * @return * true if the probe with this signature is active */ public boolean isProbeActivated(final String signature); /** * Overwrites the current list of patterns with a new pattern list. * * @param patternList * list of strings with patterns * where each string starts either with a + or - */ public void setProbePatternList(final List<String> patternList); /** * Returns the current list of patterns with a prefix indicating whether the pattern is active or not. * * @return * list of strings with patterns * where each string starts either with a + or - */ public List<String> getProbePatternList(); }
src/monitoring/kieker/monitoring/core/controller/IProbeController.java
/*************************************************************************** * Copyright 2012 Kieker Project (http://kieker-monitoring.net) * * 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 kieker.monitoring.core.controller; import java.util.List; /** * @author Jan Waller */ public interface IProbeController { /** * Activates a probe. * * @param pattern * pattern for the probe * @return * true on success */ public boolean activateProbe(final String pattern); /** * Deactivates a probe. * * @param pattern * pattern for the probe * @return * true on success */ public boolean deactivateProbe(final String pattern); /** * @param signature * signature of the probe * @return * true if the probe with this signature is active */ public boolean isProbeActivated(final String signature); /** * @param patternList * list of strings with patterns * where each string starts either with a + or - */ public void setProbePatternList(final List<String> patternList); /** * @return * list of strings with patterns * where each string starts either with a + or - */ public List<String> getProbePatternList(); }
added JavaDoc for IProbeController
src/monitoring/kieker/monitoring/core/controller/IProbeController.java
added JavaDoc for IProbeController
<ide><path>rc/monitoring/kieker/monitoring/core/controller/IProbeController.java <ide> public boolean deactivateProbe(final String pattern); <ide> <ide> /** <add> * Tests if a probe is active. <add> * <ide> * @param signature <ide> * signature of the probe <ide> * @return <ide> public boolean isProbeActivated(final String signature); <ide> <ide> /** <add> * Overwrites the current list of patterns with a new pattern list. <add> * <ide> * @param patternList <ide> * list of strings with patterns <ide> * where each string starts either with a + or - <ide> public void setProbePatternList(final List<String> patternList); <ide> <ide> /** <add> * Returns the current list of patterns with a prefix indicating whether the pattern is active or not. <add> * <ide> * @return <ide> * list of strings with patterns <ide> * where each string starts either with a + or -
Java
apache-2.0
a942dc336e8d0016f2204f57fa370e1dbaeec1c2
0
tommai78101/PokemonWalking
package common; import enums.AnsiColors; public class Debug { public static final int MinimumStringLength = 24; public static final int TabLength = 8; private static String createString(String msg) { StackTraceElement element = new Throwable().getStackTrace()[2]; String className = element.getClassName() + ":" + element.getLineNumber(); String tabs = "\t"; int length = className.length(); while (length < Debug.MinimumStringLength) { tabs = tabs.concat("\t"); length += Debug.TabLength; } return className + tabs + "- " + msg; } private static String createExceptionString(Exception e) { StackTraceElement element = e.getStackTrace()[0]; String className = element.getClassName() + ":" + element.getLineNumber(); String tabs = "\t"; int length = className.length(); while (length < Debug.MinimumStringLength) { tabs = tabs.concat("\t"); length += Debug.TabLength; } return className + tabs + "- " + e.getLocalizedMessage(); } public static void log(String msg) { System.out.println(Debug.createString(msg)); } public static void error(String msg) { System.err.println(Debug.createString(msg)); } public static void error(String msg, Exception e) { Debug.error(msg); e.printStackTrace(); } public static void exception(Exception e) { System.err.println(Debug.createExceptionString(e)); } public static void printColor(AnsiColors color, String input) { System.out.println(color.getAnsiCode() + input + AnsiColors.Clear.getAnsiCode()); } }
common/src/main/java/common/Debug.java
package common; import enums.AnsiColors; public class Debug { public static final int MinimumStringLength = 24; public static final int TabLength = 8; private static String createString(String msg) { StackTraceElement element = new Throwable().getStackTrace()[2]; String className = element.getClassName() + ":" + element.getLineNumber(); String tabs = "\t"; int length = className.length(); while (length < Debug.MinimumStringLength) { tabs = tabs.concat("\t"); length += Debug.TabLength; } return className + tabs + "- " + msg; } private static String createExceptionString(Exception e) { StackTraceElement element = e.getStackTrace()[0]; String className = element.getClassName() + ":" + element.getLineNumber(); String tabs = "\t"; int length = className.length(); while (length < Debug.MinimumStringLength) { tabs = tabs.concat("\t"); length += Debug.TabLength; } return className + tabs + "- " + e.getLocalizedMessage(); } public static void log(String msg) { System.out.println(Debug.createString(msg)); } public static void error(String msg) { System.err.println(Debug.createString(msg)); } public static void error(String msg, Exception e) { Debug.error(msg); e.printStackTrace(); } public static void exception(Exception e) { System.err.println(Debug.createExceptionString(e)); } public static void printColor(AnsiColors color, String input) { System.out.println(color.getAnsiCode() + " " + input); } }
Fixed Debug ANSI Colors support.
common/src/main/java/common/Debug.java
Fixed Debug ANSI Colors support.
<ide><path>ommon/src/main/java/common/Debug.java <ide> } <ide> <ide> public static void printColor(AnsiColors color, String input) { <del> System.out.println(color.getAnsiCode() + " " + input); <add> System.out.println(color.getAnsiCode() + input + AnsiColors.Clear.getAnsiCode()); <ide> } <ide> }
Java
apache-2.0
d5563ffd2eb949fa4ee94bc1506be007e7aad527
0
crashlytics/ios-driver,masbog/ios-driver,darraghgrace/ios-driver,seem-sky/ios-driver,seem-sky/ios-driver,adataylor/ios-driver,azaytsev/ios-driver,shutkou/ios-driver,adataylor/ios-driver,masbog/ios-driver,ios-driver/ios-driver,crashlytics/ios-driver,masbog/ios-driver,shutkou/ios-driver,ios-driver/ios-driver,shutkou/ios-driver,azaytsev/ios-driver,ios-driver/ios-driver,seem-sky/ios-driver,adataylor/ios-driver,azaytsev/ios-driver,darraghgrace/ios-driver,crashlytics/ios-driver,adataylor/ios-driver,ios-driver/ios-driver,darraghgrace/ios-driver,azaytsev/ios-driver,masbog/ios-driver,darraghgrace/ios-driver,azaytsev/ios-driver,crashlytics/ios-driver,seem-sky/ios-driver,crashlytics/ios-driver,darraghgrace/ios-driver,masbog/ios-driver,shutkou/ios-driver,shutkou/ios-driver,adataylor/ios-driver,shutkou/ios-driver,ios-driver/ios-driver
/* * Copyright 2012 ios-driver committers. * * 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.uiautomation.ios.utils; import org.apache.commons.io.IOUtils; import org.openqa.selenium.WebDriverException; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; /** * Concatenate all the small JS files into 1 file passed to instruments, and replace variables by * their value. * * @author freynaud */ public class ScriptHelper { public static final String ENCODING = "UTF-8"; private final String main = "instruments-js/main.js"; private final String json = "instruments-js/json2.js"; private final String common = "instruments-js/common.js"; private final String lib0 = "instruments-js/UIAutomation.js"; private final String lib1 = "instruments-js/UIAKeyboard.js"; private final String lib2 = "instruments-js/UIAElement.js"; private final String lib3 = "instruments-js/UIAApplication.js"; private final String lib4 = "instruments-js/UIATarget.js"; private final String lib5 = "instruments-js/UIAAlert.js"; private final String lib6 = "instruments-js/Cache.js"; private final String lib7 = "instruments-js/SafariPageNavigator.js"; private final String lib8 = "instruments-js/UIAActionSheet.js"; private static final String FILE_NAME = "uiamasterscript"; private String load(String resource) throws IOException { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, "UTF-8"); String content = writer.toString(); return content; } private String generateScriptContent(int port, String aut, String opaqueKey) throws IOException { StringBuilder scriptContent = new StringBuilder(); String c = load(lib0); c = c.replace("$PORT", String.format("%d", port)); c = c.replace("$AUT", String.format("%s", aut)); c = c.replace("$SESSION", String.format("%s", opaqueKey)); scriptContent.append(load(json)); scriptContent.append(load(common)); String t = load(lib1); System.out.println(t); System.out.println(t.contains("ç")); scriptContent.append(t); scriptContent.append(load(lib4)); scriptContent.append(load(lib3)); scriptContent.append(load(lib2)); scriptContent.append(load(lib5)); scriptContent.append(load(lib6)); scriptContent.append(load(lib7)); scriptContent.append(load(lib8)); scriptContent.append(c); scriptContent.append(load(main)); return scriptContent.toString(); } public File createTmpScript(String content) { try { File res = File.createTempFile(FILE_NAME, ".js"); res.deleteOnExit(); Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(res), "UTF-8")); writer.write(content); writer.close(); return res; } catch (Exception e) { throw new WebDriverException("Cannot generate script."); } } public File getScript(int port, String aut, String opaqueKey) { try { String content = generateScriptContent(port, aut, opaqueKey); return createTmpScript(content); } catch (Exception e) { throw new WebDriverException("cannot generate the script for instrument.", e); } } }
server/src/main/java/org/uiautomation/ios/utils/ScriptHelper.java
/* * Copyright 2012 ios-driver committers. * * 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.uiautomation.ios.utils; import org.apache.commons.io.IOUtils; import org.openqa.selenium.WebDriverException; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.io.Writer; /** * Concatenate all the small JS files into 1 file passed to instruments, and replace variables by * their value. * * @author freynaud */ public class ScriptHelper { private final String main = "instruments-js/main.js"; private final String json = "instruments-js/json2.js"; private final String common = "instruments-js/common.js"; private final String lib0 = "instruments-js/UIAutomation.js"; private final String lib1 = "instruments-js/UIAKeyboard.js"; private final String lib2 = "instruments-js/UIAElement.js"; private final String lib3 = "instruments-js/UIAApplication.js"; private final String lib4 = "instruments-js/UIATarget.js"; private final String lib5 = "instruments-js/UIAAlert.js"; private final String lib6 = "instruments-js/Cache.js"; private final String lib7 = "instruments-js/SafariPageNavigator.js"; private final String lib8 = "instruments-js/UIAActionSheet.js"; private static final String FILE_NAME = "uiamasterscript"; private String load(String resource) throws IOException { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); if (is == null) { throw new WebDriverException("cannot load : " + resource); } StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, "UTF-8"); String content = writer.toString(); return content; } private String generateScriptContent(int port, String aut, String opaqueKey) throws IOException { StringBuilder scriptContent = new StringBuilder(); String c = load(lib0); c = c.replace("$PORT", String.format("%d", port)); c = c.replace("$AUT", String.format("%s", aut)); c = c.replace("$SESSION", String.format("%s", opaqueKey)); scriptContent.append(load(json)); scriptContent.append(load(common)); scriptContent.append(load(lib1)); scriptContent.append(load(lib4)); scriptContent.append(load(lib3)); scriptContent.append(load(lib2)); scriptContent.append(load(lib5)); scriptContent.append(load(lib6)); scriptContent.append(load(lib7)); scriptContent.append(load(lib8)); scriptContent.append(c); scriptContent.append(load(main)); return scriptContent.toString(); } public File createTmpScript(String content) { try { File res = File.createTempFile(FILE_NAME, ".js"); Writer writer = new FileWriter(res); IOUtils.copy(IOUtils.toInputStream(content), writer, "UTF-8"); IOUtils.closeQuietly(writer); return res; } catch (Exception e) { throw new WebDriverException("Cannot generate script."); } } public File getScript(int port, String aut, String opaqueKey) { try { String content = generateScriptContent(port, aut, opaqueKey); return createTmpScript(content); } catch (Exception e) { throw new WebDriverException("cannot generate the script for instrument.", e); } } }
need to specify the encoding for the script.
server/src/main/java/org/uiautomation/ios/utils/ScriptHelper.java
need to specify the encoding for the script.
<ide><path>erver/src/main/java/org/uiautomation/ios/utils/ScriptHelper.java <ide> import org.apache.commons.io.IOUtils; <ide> import org.openqa.selenium.WebDriverException; <ide> <add>import java.io.BufferedWriter; <ide> import java.io.File; <del>import java.io.FileWriter; <add>import java.io.FileOutputStream; <ide> import java.io.IOException; <ide> import java.io.InputStream; <add>import java.io.OutputStreamWriter; <ide> import java.io.StringWriter; <ide> import java.io.Writer; <ide> <ide> */ <ide> public class ScriptHelper { <ide> <add> public static final String ENCODING = "UTF-8"; <ide> private final String main = "instruments-js/main.js"; <ide> private final String json = "instruments-js/json2.js"; <ide> private final String common = "instruments-js/common.js"; <ide> <ide> private String load(String resource) throws IOException { <ide> InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); <del> if (is == null) { <del> throw new WebDriverException("cannot load : " + resource); <del> } <ide> StringWriter writer = new StringWriter(); <ide> IOUtils.copy(is, writer, "UTF-8"); <ide> String content = writer.toString(); <ide> return content; <ide> } <add> <ide> <ide> private String generateScriptContent(int port, String aut, String opaqueKey) throws IOException { <ide> StringBuilder scriptContent = new StringBuilder(); <ide> <ide> scriptContent.append(load(json)); <ide> scriptContent.append(load(common)); <del> scriptContent.append(load(lib1)); <add> String t = load(lib1); <add> System.out.println(t); <add> System.out.println(t.contains("ç")); <add> scriptContent.append(t); <ide> scriptContent.append(load(lib4)); <ide> scriptContent.append(load(lib3)); <ide> scriptContent.append(load(lib2)); <ide> public File createTmpScript(String content) { <ide> try { <ide> File res = File.createTempFile(FILE_NAME, ".js"); <del> Writer writer = new FileWriter(res); <del> IOUtils.copy(IOUtils.toInputStream(content), writer, "UTF-8"); <del> IOUtils.closeQuietly(writer); <add> res.deleteOnExit(); <add> Writer <add> writer = <add> new BufferedWriter(new OutputStreamWriter(new FileOutputStream(res), "UTF-8")); <add> writer.write(content); <add> writer.close(); <ide> return res; <ide> } catch (Exception e) { <ide> throw new WebDriverException("Cannot generate script.");
Java
apache-2.0
b17dc99a5f2bd254719684dd4dbdad24cae3954c
0
GerritCodeReview/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,WANdisco/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit
// Copyright (C) 2018 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.logging; import static java.util.Objects.requireNonNull; import com.google.common.base.Stopwatch; import com.google.common.base.Strings; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import com.google.common.flogger.FluentLogger; import com.google.gerrit.common.Nullable; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; /** * TraceContext that allows to set logging tags and enforce logging. * * <p>The logging tags are attached to all log entries that are triggered while the trace context is * open. If force logging is enabled all logs that are triggered while the trace context is open are * written to the log file regardless of the configured log level. * * <pre> * try (TraceContext traceContext = TraceContext.open() * .addTag("tag-name", "tag-value") * .forceLogging()) { * // This gets logged as: A log [CONTEXT forced=true tag-name="tag-value" ] * // Since force logging is enabled this gets logged independently of the configured log * // level. * logger.atFinest().log("A log"); * * // do stuff * } * </pre> * * <p>The logging tags and the force logging flag are stored in the {@link LoggingContext}. {@link * LoggingContextAwareExecutorService}, {@link LoggingContextAwareScheduledExecutorService} and the * executor in {@link com.google.gerrit.server.git.WorkQueue} ensure that the logging context is * automatically copied to background threads. * * <p>On close of the trace context newly set tags are unset. Force logging is disabled on close if * it got enabled while the trace context was open. * * <p>Trace contexts can be nested: * * <pre> * // Initially there are no tags * logger.atSevere().log("log without tag"); * * // a tag can be set by opening a trace context * try (TraceContext ctx = TraceContext.open().addTag("tag1", "value1")) { * logger.atSevere().log("log with tag1=value1"); * * // while a trace context is open further tags can be added. * ctx.addTag("tag2", "value2") * logger.atSevere().log("log with tag1=value1 and tag2=value2"); * * // also by opening another trace context a another tag can be added * try (TraceContext ctx2 = TraceContext.open().addTag("tag3", "value3")) { * logger.atSevere().log("log with tag1=value1, tag2=value2 and tag3=value3"); * * // it's possible to have the same tag name with multiple values * ctx2.addTag("tag3", "value3a") * logger.atSevere().log("log with tag1=value1, tag2=value2, tag3=value3 and tag3=value3a"); * * // adding a tag with the same name and value as an existing tag has no effect * try (TraceContext ctx3 = TraceContext.open().addTag("tag3", "value3a")) { * logger.atSevere().log("log with tag1=value1, tag2=value2, tag3=value3 and tag3=value3a"); * } * * // closing ctx3 didn't remove tag3=value3a since it was already set before opening ctx3 * logger.atSevere().log("log with tag1=value1, tag2=value2, tag3=value3 and tag3=value3a"); * } * * // closing ctx2 removed tag3=value3 and tag3-value3a * logger.atSevere().log("with tag1=value1 and tag2=value2"); * } * * // closing ctx1 removed tag1=value1 and tag2=value2 * logger.atSevere().log("log without tag"); * </pre> */ public class TraceContext implements AutoCloseable { private static final String PLUGIN_TAG = "PLUGIN"; public static TraceContext open() { return new TraceContext(); } /** * Opens a new trace context for request tracing. * * <ul> * <li>sets a tag with a trace ID * <li>enables force logging * </ul> * * <p>if no trace ID is provided a new trace ID is only generated if request tracing was not * started yet. If request tracing was already started the given {@code traceIdConsumer} is * invoked with the existing trace ID and no new logging tag is set. * * <p>No-op if {@code trace} is {@code false}. * * @param trace whether tracing should be started * @param traceId trace ID that should be used for tracing, if {@code null} a trace ID is * generated * @param traceIdConsumer consumer for the trace ID, should be used to return the generated trace * ID to the client, not invoked if {@code trace} is {@code false} * @return the trace context */ public static TraceContext newTrace( boolean trace, @Nullable String traceId, TraceIdConsumer traceIdConsumer) { if (!trace) { // Create an empty trace context. return open(); } if (!Strings.isNullOrEmpty(traceId)) { traceIdConsumer.accept(RequestId.Type.TRACE_ID.name(), traceId); return open().addTag(RequestId.Type.TRACE_ID, traceId).forceLogging(); } Optional<String> existingTraceId = LoggingContext.getInstance().getTagsAsMap().get(RequestId.Type.TRACE_ID.name()).stream() .findAny(); if (existingTraceId.isPresent()) { // request tracing was already started, no need to generate a new trace ID traceIdConsumer.accept(RequestId.Type.TRACE_ID.name(), existingTraceId.get()); return open(); } RequestId newTraceId = new RequestId(); traceIdConsumer.accept(RequestId.Type.TRACE_ID.name(), newTraceId.toString()); return open().addTag(RequestId.Type.TRACE_ID, newTraceId).forceLogging(); } @FunctionalInterface public interface TraceIdConsumer { void accept(String tagName, String traceId); } /** * Opens a new timer that logs the time for an operation if request tracing is enabled. * * <p>If request tracing is not enabled this is a no-op. * * @param message the message * @return the trace timer */ public static TraceTimer newTimer(String message) { return new TraceTimer(message); } /** * Opens a new timer that logs the time for an operation if request tracing is enabled. * * <p>If request tracing is not enabled this is a no-op. * * @param format the message format string * @param arg argument for the message * @return the trace timer */ public static TraceTimer newTimer(String format, Object arg) { return new TraceTimer(format, arg); } /** * Opens a new timer that logs the time for an operation if request tracing is enabled. * * <p>If request tracing is not enabled this is a no-op. * * @param format the message format string * @param arg1 first argument for the message * @param arg2 second argument for the message * @return the trace timer */ public static TraceTimer newTimer(String format, Object arg1, Object arg2) { return new TraceTimer(format, arg1, arg2); } /** * Opens a new timer that logs the time for an operation if request tracing is enabled. * * <p>If request tracing is not enabled this is a no-op. * * @param format the message format string * @param arg1 first argument for the message * @param arg2 second argument for the message * @param arg3 third argument for the message * @return the trace timer */ public static TraceTimer newTimer(String format, Object arg1, Object arg2, Object arg3) { return new TraceTimer(format, arg1, arg2, arg3); } /** * Opens a new timer that logs the time for an operation if request tracing is enabled. * * <p>If request tracing is not enabled this is a no-op. * * @param format the message format string * @param arg1 first argument for the message * @param arg2 second argument for the message * @param arg3 third argument for the message * @param arg4 fourth argument for the message * @return the trace timer */ public static TraceTimer newTimer( String format, Object arg1, Object arg2, Object arg3, Object arg4) { return new TraceTimer(format, arg1, arg2, arg3, arg4); } public static class TraceTimer implements AutoCloseable { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final Consumer<Long> logFn; private final Stopwatch stopwatch; private TraceTimer(String message) { this(elapsedMs -> logger.atFine().log(message + " (%d ms)", elapsedMs)); } private TraceTimer(String format, @Nullable Object arg) { this(elapsedMs -> logger.atFine().log(format + " (%d ms)", arg, elapsedMs)); } private TraceTimer(String format, @Nullable Object arg1, @Nullable Object arg2) { this(elapsedMs -> logger.atFine().log(format + " (%d ms)", arg1, arg2, elapsedMs)); } private TraceTimer( String format, @Nullable Object arg1, @Nullable Object arg2, @Nullable Object arg3) { this(elapsedMs -> logger.atFine().log(format + " (%d ms)", arg1, arg2, arg3, elapsedMs)); } private TraceTimer( String format, @Nullable Object arg1, @Nullable Object arg2, @Nullable Object arg3, @Nullable Object arg4) { this( elapsedMs -> logger.atFine().log(format + " (%d ms)", arg1, arg2, arg3, arg4, elapsedMs)); } private TraceTimer(Consumer<Long> logFn) { this.logFn = logFn; this.stopwatch = Stopwatch.createStarted(); } @Override public void close() { stopwatch.stop(); logFn.accept(stopwatch.elapsed(TimeUnit.MILLISECONDS)); } } // Table<TAG_NAME, TAG_VALUE, REMOVE_ON_CLOSE> private final Table<String, String, Boolean> tags = HashBasedTable.create(); private boolean stopForceLoggingOnClose; private TraceContext() {} public TraceContext addTag(RequestId.Type requestId, Object tagValue) { return addTag(requireNonNull(requestId, "request ID is required").name(), tagValue); } public TraceContext addTag(String tagName, Object tagValue) { String name = requireNonNull(tagName, "tag name is required"); String value = requireNonNull(tagValue, "tag value is required").toString(); tags.put(name, value, LoggingContext.getInstance().addTag(name, value)); return this; } public TraceContext addPluginTag(String pluginName) { return addTag(PLUGIN_TAG, pluginName); } public TraceContext forceLogging() { if (stopForceLoggingOnClose) { return this; } stopForceLoggingOnClose = !LoggingContext.getInstance().forceLogging(true); return this; } @Override public void close() { for (Table.Cell<String, String, Boolean> cell : tags.cellSet()) { if (cell.getValue()) { LoggingContext.getInstance().removeTag(cell.getRowKey(), cell.getColumnKey()); } } if (stopForceLoggingOnClose) { LoggingContext.getInstance().forceLogging(false); } } }
java/com/google/gerrit/server/logging/TraceContext.java
// Copyright (C) 2018 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.logging; import static java.util.Objects.requireNonNull; import com.google.common.base.Stopwatch; import com.google.common.base.Strings; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import com.google.common.flogger.FluentLogger; import com.google.gerrit.common.Nullable; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; /** * TraceContext that allows to set logging tags and enforce logging. * * <p>The logging tags are attached to all log entries that are triggered while the trace context is * open. If force logging is enabled all logs that are triggered while the trace context is open are * written to the log file regardless of the configured log level. * * <pre> * try (TraceContext traceContext = TraceContext.open() * .addTag("tag-name", "tag-value") * .forceLogging()) { * // This gets logged as: A log [CONTEXT forced=true tag-name="tag-value" ] * // Since force logging is enabled this gets logged independently of the configured log * // level. * logger.atFinest().log("A log"); * * // do stuff * } * </pre> * * <p>The logging tags and the force logging flag are stored in the {@link LoggingContext}. {@link * LoggingContextAwareExecutorService}, {@link LoggingContextAwareScheduledExecutorService} and the * executor in {@link com.google.gerrit.server.git.WorkQueue} ensure that the logging context is * automatically copied to background threads. * * <p>On close of the trace context newly set tags are unset. Force logging is disabled on close if * it got enabled while the trace context was open. * * <p>Trace contexts can be nested: * * <pre> * // Initially there are no tags * logger.atSevere().log("log without tag"); * * // a tag can be set by opening a trace context * try (TraceContext ctx = TraceContext.open().addTag("tag1", "value1")) { * logger.atSevere().log("log with tag1=value1"); * * // while a trace context is open further tags can be added. * ctx.addTag("tag2", "value2") * logger.atSevere().log("log with tag1=value1 and tag2=value2"); * * // also by opening another trace context a another tag can be added * try (TraceContext ctx2 = TraceContext.open().addTag("tag3", "value3")) { * logger.atSevere().log("log with tag1=value1, tag2=value2 and tag3=value3"); * * // it's possible to have the same tag name with multiple values * ctx2.addTag("tag3", "value3a") * logger.atSevere().log("log with tag1=value1, tag2=value2, tag3=value3 and tag3=value3a"); * * // adding a tag with the same name and value as an existing tag has no effect * try (TraceContext ctx3 = TraceContext.open().addTag("tag3", "value3a")) { * logger.atSevere().log("log with tag1=value1, tag2=value2, tag3=value3 and tag3=value3a"); * } * * // closing ctx3 didn't remove tag3=value3a since it was already set before opening ctx3 * logger.atSevere().log("log with tag1=value1, tag2=value2, tag3=value3 and tag3=value3a"); * } * * // closing ctx2 removed tag3=value3 and tag3-value3a * logger.atSevere().log("with tag1=value1 and tag2=value2"); * } * * // closing ctx1 removed tag1=value1 and tag2=value2 * logger.atSevere().log("log without tag"); * </pre> */ public class TraceContext implements AutoCloseable { private static final String PLUGIN_TAG = "PLUGIN"; public static TraceContext open() { return new TraceContext(); } /** * Opens a new trace context for request tracing. * * <ul> * <li>sets a tag with a trace ID * <li>enables force logging * </ul> * * <p>if no trace ID is provided a new trace ID is only generated if request tracing was not * started yet. If request tracing was already started the given {@code traceIdConsumer} is * invoked with the existing trace ID and no new logging tag is set. * * <p>No-op if {@code trace} is {@code false}. * * @param trace whether tracing should be started * @param traceId trace ID that should be used for tracing, if {@code null} a trace ID is * generated * @param traceIdConsumer consumer for the trace ID, should be used to return the generated trace * ID to the client, not invoked if {@code trace} is {@code false} * @return the trace context */ public static TraceContext newTrace( boolean trace, @Nullable String traceId, TraceIdConsumer traceIdConsumer) { if (!trace) { // Create an empty trace context. return open(); } if (!Strings.isNullOrEmpty(traceId)) { traceIdConsumer.accept(RequestId.Type.TRACE_ID.name(), traceId); return open().addTag(RequestId.Type.TRACE_ID, traceId).forceLogging(); } Optional<String> existingTraceId = LoggingContext.getInstance().getTagsAsMap().get(RequestId.Type.TRACE_ID.name()).stream() .findAny(); if (existingTraceId.isPresent()) { // request tracing was already started, no need to generate a new trace ID traceIdConsumer.accept(RequestId.Type.TRACE_ID.name(), existingTraceId.get()); return open(); } RequestId newTraceId = new RequestId(); traceIdConsumer.accept(RequestId.Type.TRACE_ID.name(), newTraceId.toString()); return open().addTag(RequestId.Type.TRACE_ID, newTraceId).forceLogging(); } @FunctionalInterface public interface TraceIdConsumer { void accept(String tagName, String traceId); } /** * Opens a new timer that logs the time for an operation if request tracing is enabled. * * <p>If request tracing is not enabled this is a no-op. * * @param message the message * @return the trace timer */ public static TraceTimer newTimer(String message) { return new TraceTimer(message); } /** * Opens a new timer that logs the time for an operation if request tracing is enabled. * * <p>If request tracing is not enabled this is a no-op. * * @param format the message format string * @param arg argument for the message * @return the trace timer */ public static TraceTimer newTimer(String format, Object arg) { return new TraceTimer(format, arg); } /** * Opens a new timer that logs the time for an operation if request tracing is enabled. * * <p>If request tracing is not enabled this is a no-op. * * @param format the message format string * @param arg1 first argument for the message * @param arg2 second argument for the message * @return the trace timer */ public static TraceTimer newTimer(String format, Object arg1, Object arg2) { return new TraceTimer(format, arg1, arg2); } /** * Opens a new timer that logs the time for an operation if request tracing is enabled. * * <p>If request tracing is not enabled this is a no-op. * * @param format the message format string * @param arg1 first argument for the message * @param arg2 second argument for the message * @param arg3 third argument for the message * @return the trace timer */ public static TraceTimer newTimer(String format, Object arg1, Object arg2, Object arg3) { return new TraceTimer(format, arg1, arg2, arg3); } public static class TraceTimer implements AutoCloseable { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final Consumer<Long> logFn; private final Stopwatch stopwatch; private TraceTimer(String message) { this(elapsedMs -> logger.atFine().log(message + " (%d ms)", elapsedMs)); } private TraceTimer(String format, @Nullable Object arg) { this(elapsedMs -> logger.atFine().log(format + " (%d ms)", arg, elapsedMs)); } private TraceTimer(String format, @Nullable Object arg1, @Nullable Object arg2) { this(elapsedMs -> logger.atFine().log(format + " (%d ms)", arg1, arg2, elapsedMs)); } private TraceTimer( String format, @Nullable Object arg1, @Nullable Object arg2, @Nullable Object arg3) { this(elapsedMs -> logger.atFine().log(format + " (%d ms)", arg1, arg2, arg3, elapsedMs)); } private TraceTimer(Consumer<Long> logFn) { this.logFn = logFn; this.stopwatch = Stopwatch.createStarted(); } @Override public void close() { stopwatch.stop(); logFn.accept(stopwatch.elapsed(TimeUnit.MILLISECONDS)); } } // Table<TAG_NAME, TAG_VALUE, REMOVE_ON_CLOSE> private final Table<String, String, Boolean> tags = HashBasedTable.create(); private boolean stopForceLoggingOnClose; private TraceContext() {} public TraceContext addTag(RequestId.Type requestId, Object tagValue) { return addTag(requireNonNull(requestId, "request ID is required").name(), tagValue); } public TraceContext addTag(String tagName, Object tagValue) { String name = requireNonNull(tagName, "tag name is required"); String value = requireNonNull(tagValue, "tag value is required").toString(); tags.put(name, value, LoggingContext.getInstance().addTag(name, value)); return this; } public TraceContext addPluginTag(String pluginName) { return addTag(PLUGIN_TAG, pluginName); } public TraceContext forceLogging() { if (stopForceLoggingOnClose) { return this; } stopForceLoggingOnClose = !LoggingContext.getInstance().forceLogging(true); return this; } @Override public void close() { for (Table.Cell<String, String, Boolean> cell : tags.cellSet()) { if (cell.getValue()) { LoggingContext.getInstance().removeTag(cell.getRowKey(), cell.getColumnKey()); } } if (stopForceLoggingOnClose) { LoggingContext.getInstance().forceLogging(false); } } }
TraceContext: Support fourth format parameter Change-Id: I9bf46888455667e57f65d225450862ef660c4617
java/com/google/gerrit/server/logging/TraceContext.java
TraceContext: Support fourth format parameter
<ide><path>ava/com/google/gerrit/server/logging/TraceContext.java <ide> return new TraceTimer(format, arg1, arg2, arg3); <ide> } <ide> <add> /** <add> * Opens a new timer that logs the time for an operation if request tracing is enabled. <add> * <add> * <p>If request tracing is not enabled this is a no-op. <add> * <add> * @param format the message format string <add> * @param arg1 first argument for the message <add> * @param arg2 second argument for the message <add> * @param arg3 third argument for the message <add> * @param arg4 fourth argument for the message <add> * @return the trace timer <add> */ <add> public static TraceTimer newTimer( <add> String format, Object arg1, Object arg2, Object arg3, Object arg4) { <add> return new TraceTimer(format, arg1, arg2, arg3, arg4); <add> } <add> <ide> public static class TraceTimer implements AutoCloseable { <ide> private static final FluentLogger logger = FluentLogger.forEnclosingClass(); <ide> <ide> private TraceTimer( <ide> String format, @Nullable Object arg1, @Nullable Object arg2, @Nullable Object arg3) { <ide> this(elapsedMs -> logger.atFine().log(format + " (%d ms)", arg1, arg2, arg3, elapsedMs)); <add> } <add> <add> private TraceTimer( <add> String format, <add> @Nullable Object arg1, <add> @Nullable Object arg2, <add> @Nullable Object arg3, <add> @Nullable Object arg4) { <add> this( <add> elapsedMs -> logger.atFine().log(format + " (%d ms)", arg1, arg2, arg3, arg4, elapsedMs)); <ide> } <ide> <ide> private TraceTimer(Consumer<Long> logFn) {
Java
apache-2.0
9b6c804073dc0bcd66f48b556d2acc0ec48977c6
0
fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode
package com.fishercoder.solutions; import java.util.stream.IntStream; /** * 1055. Fixed Point * * Given an array A of distinct integers sorted in ascending order, * return the smallest index i that satisfies A[i] == i. Return -1 if no such i exists. * * Example 1: * Input: [-10,-5,0,3,7] * Output: 3 * Explanation: * For the given array, A[0] = -10, A[1] = -5, A[2] = 0, A[3] = 3, thus the output is 3. * * Example 2: * Input: [0,2,5,8,17] * Output: 0 * Explanation: * A[0] = 0, thus the output is 0. * * Example 3: * Input: [-10,-5,3,4,7,9] * Output: -1 * Explanation: * There is no such i that A[i] = i, thus the output is -1. * * Note: * * 1 <= A.length < 10^4 * -10^9 <= A[i] <= 10^9 * */ public class _1055 { public static class Solution1 { public int fixedPoint(int[] A) { return IntStream.range(0, A.length).filter(i -> A[i] == i).findFirst().orElse(-1); } } }
src/main/java/com/fishercoder/solutions/_1055.java
package com.fishercoder.solutions; /** * 1055. Fixed Point * * Given an array A of distinct integers sorted in ascending order, * return the smallest index i that satisfies A[i] == i. Return -1 if no such i exists. * * Example 1: * Input: [-10,-5,0,3,7] * Output: 3 * Explanation: * For the given array, A[0] = -10, A[1] = -5, A[2] = 0, A[3] = 3, thus the output is 3. * * Example 2: * Input: [0,2,5,8,17] * Output: 0 * Explanation: * A[0] = 0, thus the output is 0. * * Example 3: * Input: [-10,-5,3,4,7,9] * Output: -1 * Explanation: * There is no such i that A[i] = i, thus the output is -1. * * Note: * * 1 <= A.length < 10^4 * -10^9 <= A[i] <= 10^9 * */ public class _1055 { public static class Solution1 { public int fixedPoint(int[] A) { for (int i = 0; i < A.length; i++) { if (A[i] == i) { return i; } } return -1; } } }
refactor 1055
src/main/java/com/fishercoder/solutions/_1055.java
refactor 1055
<ide><path>rc/main/java/com/fishercoder/solutions/_1055.java <ide> package com.fishercoder.solutions; <add> <add>import java.util.stream.IntStream; <ide> <ide> /** <ide> * 1055. Fixed Point <ide> public class _1055 { <ide> public static class Solution1 { <ide> public int fixedPoint(int[] A) { <del> for (int i = 0; i < A.length; i++) { <del> if (A[i] == i) { <del> return i; <del> } <del> } <del> return -1; <add> return IntStream.range(0, A.length).filter(i -> A[i] == i).findFirst().orElse(-1); <ide> } <ide> } <ide> }
Java
apache-2.0
26d147afe26c6559b0ac4d0922180faaf3f6a027
0
chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.transport.discovery; import static org.junit.Assert.assertTrue; import java.net.URI; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import javax.management.ObjectInstance; import javax.management.ObjectName; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.jmx.ManagementContext; import org.apache.activemq.transport.discovery.multicast.MulticastDiscoveryAgentFactory; import org.apache.activemq.util.SocketProxy; import org.apache.activemq.util.Wait; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.Invocation; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.jmock.lib.action.CustomAction; import org.jmock.lib.legacy.ClassImposteriser; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(JMock.class) public class DiscoveryNetworkReconnectTest { private static final Log LOG = LogFactory.getLog(DiscoveryNetworkReconnectTest.class); final int maxReconnects = 5; final String groupName = "GroupID-" + "DiscoveryNetworkReconnectTest"; final String discoveryAddress = "multicast://default?group=" + groupName + "&initialReconnectDelay=1000"; final Semaphore mbeanRegistered = new Semaphore(0); final Semaphore mbeanUnregistered = new Semaphore(0); BrokerService brokerA, brokerB; Mockery context; ManagementContext managementContext; DiscoveryAgent agent; SocketProxy proxy; // ignore the hostname resolution component as this is machine dependent class NetworkBridgeObjectNameMatcher<T> extends BaseMatcher<T> { T name; NetworkBridgeObjectNameMatcher(T o) { name = o; } public boolean matches(Object arg0) { ObjectName other = (ObjectName) arg0; ObjectName mine = (ObjectName) name; return other.getKeyProperty("Type").equals(mine.getKeyProperty("Type")) && other.getKeyProperty("NetworkConnectorName").equals(mine.getKeyProperty("NetworkConnectorName")); } public void describeTo(Description arg0) { arg0.appendText(this.getClass().getName()); } } @Before public void setUp() throws Exception { context = new JUnit4Mockery() {{ setImposteriser(ClassImposteriser.INSTANCE); }}; brokerA = new BrokerService(); brokerA.setBrokerName("BrokerA"); configure(brokerA); brokerA.addConnector("tcp://localhost:0"); brokerA.start(); proxy = new SocketProxy(brokerA.getTransportConnectors().get(0).getConnectUri()); managementContext = context.mock(ManagementContext.class); context.checking(new Expectations(){{ allowing (managementContext).getJmxDomainName(); will (returnValue("Test")); allowing (managementContext).start(); allowing (managementContext).stop(); // expected MBeans allowing (managementContext).registerMBean(with(any(Object.class)), with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Broker")))); allowing (managementContext).registerMBean(with(any(Object.class)), with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=localhost")))); allowing (managementContext).registerMBean(with(any(Object.class)), with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection")))); atLeast(maxReconnects - 1).of (managementContext).registerMBean(with(any(Object.class)), with(new NetworkBridgeObjectNameMatcher<ObjectName>( new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=localhost,Name=localhost/127.0.0.1_" + proxy.getUrl().getPort())))); will(new CustomAction("signal register network mbean") { public Object invoke(Invocation invocation) throws Throwable { LOG.info("Mbean Registered: " + invocation.getParameter(0)); mbeanRegistered.release(); return new ObjectInstance((ObjectName)invocation.getParameter(0), "dscription"); } }); atLeast(maxReconnects - 1).of (managementContext).unregisterMBean(with(new NetworkBridgeObjectNameMatcher<ObjectName>( new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=localhost,Name=localhost/127.0.0.1_" + proxy.getUrl().getPort())))); will(new CustomAction("signal unregister network mbean") { public Object invoke(Invocation invocation) throws Throwable { LOG.info("Mbean Unregistered: " + invocation.getParameter(0)); mbeanUnregistered.release(); return null; } }); allowing (managementContext).unregisterMBean(with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Broker")))); allowing (managementContext).unregisterMBean(with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=localhost")))); allowing (managementContext).unregisterMBean(with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection")))); }}); brokerB = new BrokerService(); brokerB.setManagementContext(managementContext); brokerB.setBrokerName("BrokerNC"); configure(brokerB); } @After public void tearDown() throws Exception { brokerA.stop(); brokerB.stop(); proxy.close(); } private void configure(BrokerService broker) { broker.setPersistent(false); broker.setUseJmx(true); } @Test public void testMulicastReconnect() throws Exception { // control multicast advertise agent to inject proxy agent = MulticastDiscoveryAgentFactory.createDiscoveryAgent(new URI(discoveryAddress)); agent.registerService(proxy.getUrl().toString()); agent.start(); brokerB.addNetworkConnector(discoveryAddress + "&wireFormat.maxInactivityDuration=1000&wireFormat.maxInactivityDurationInitalDelay=1000"); brokerB.start(); doReconnect(); } @Test public void testSimpleReconnect() throws Exception { brokerB.addNetworkConnector("simple://(" + proxy.getUrl() + ")?useExponentialBackOff=false&initialReconnectDelay=500&wireFormat.maxInactivityDuration=1000&wireFormat.maxInactivityDurationInitalDelay=1000"); brokerB.start(); doReconnect(); } private void doReconnect() throws Exception { for (int i=0; i<maxReconnects; i++) { // Wait for connection assertTrue("we got a network connection in a timely manner", Wait.waitFor(new Wait.Condition() { public boolean isSatisified() throws Exception { return proxy.connections.size() >= 1; } })); // wait for network connector assertTrue("network connector mbean registered within 1 minute", mbeanRegistered.tryAcquire(60, TimeUnit.SECONDS)); // force an inactivity timeout via the proxy proxy.pause(); // wait for the inactivity timeout and network shutdown assertTrue("network connector mbean unregistered within 1 minute", mbeanUnregistered.tryAcquire(60, TimeUnit.SECONDS)); // let a reconnect succeed proxy.goOn(); } } }
activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.transport.discovery; import static org.junit.Assert.assertTrue; import java.net.URI; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import javax.management.ObjectInstance; import javax.management.ObjectName; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.jmx.ManagementContext; import org.apache.activemq.transport.discovery.multicast.MulticastDiscoveryAgentFactory; import org.apache.activemq.util.SocketProxy; import org.apache.activemq.util.Wait; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.Invocation; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.jmock.lib.action.CustomAction; import org.jmock.lib.legacy.ClassImposteriser; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(JMock.class) public class DiscoveryNetworkReconnectTest { private static final Log LOG = LogFactory.getLog(DiscoveryNetworkReconnectTest.class); final int maxReconnects = 5; BrokerService brokerA, brokerB; Mockery context; ManagementContext managementContext; final String groupName = "GroupID-" + "DiscoveryNetworkReconnectTest"; final String discoveryAddress = "multicast://default?group=" + groupName + "&initialReconnectDelay=1000"; final Semaphore mbeanRegistered = new Semaphore(0); final Semaphore mbeanUnregistered = new Semaphore(0); private DiscoveryAgent agent; SocketProxy proxy; @Before public void setUp() throws Exception { context = new JUnit4Mockery() {{ setImposteriser(ClassImposteriser.INSTANCE); }}; brokerA = new BrokerService(); brokerA.setBrokerName("BrokerA"); configure(brokerA); brokerA.addConnector("tcp://localhost:0"); brokerA.start(); proxy = new SocketProxy(brokerA.getTransportConnectors().get(0).getConnectUri()); managementContext = context.mock(ManagementContext.class); context.checking(new Expectations(){{ allowing (managementContext).getJmxDomainName(); will (returnValue("Test")); allowing (managementContext).start(); allowing (managementContext).stop(); // expected MBeans allowing (managementContext).registerMBean(with(any(Object.class)), with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Broker")))); allowing (managementContext).registerMBean(with(any(Object.class)), with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=localhost")))); allowing (managementContext).registerMBean(with(any(Object.class)), with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection")))); atLeast(maxReconnects - 1).of (managementContext).registerMBean(with(any(Object.class)), with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=localhost,Name=localhost/127.0.0.1_" + proxy.getUrl().getPort())))); will(new CustomAction("signal register network mbean") { public Object invoke(Invocation invocation) throws Throwable { LOG.info("Mbean Registered: " + invocation.getParameter(0)); mbeanRegistered.release(); return new ObjectInstance((ObjectName)invocation.getParameter(0), "dscription"); } }); atLeast(maxReconnects - 1).of (managementContext).unregisterMBean(with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=localhost,Name=localhost/127.0.0.1_" + proxy.getUrl().getPort())))); will(new CustomAction("signal unregister network mbean") { public Object invoke(Invocation invocation) throws Throwable { LOG.info("Mbean Unregistered: " + invocation.getParameter(0)); mbeanUnregistered.release(); return null; } }); allowing (managementContext).unregisterMBean(with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Broker")))); allowing (managementContext).unregisterMBean(with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkConnector,NetworkConnectorName=localhost")))); allowing (managementContext).unregisterMBean(with(equal( new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection")))); }}); brokerB = new BrokerService(); brokerB.setManagementContext(managementContext); brokerB.setBrokerName("BrokerNC"); configure(brokerB); } @After public void tearDown() throws Exception { brokerA.stop(); brokerB.stop(); proxy.close(); } private void configure(BrokerService broker) { broker.setPersistent(false); broker.setUseJmx(true); } @Test public void testMulicastReconnect() throws Exception { // control multicast advertise agent to inject proxy agent = MulticastDiscoveryAgentFactory.createDiscoveryAgent(new URI(discoveryAddress)); agent.registerService(proxy.getUrl().toString()); agent.start(); brokerB.addNetworkConnector(discoveryAddress + "&wireFormat.maxInactivityDuration=1000&wireFormat.maxInactivityDurationInitalDelay=1000"); brokerB.start(); doReconnect(); } @Test public void testSimpleReconnect() throws Exception { brokerB.addNetworkConnector("simple://(" + proxy.getUrl() + ")?useExponentialBackOff=false&initialReconnectDelay=500&wireFormat.maxInactivityDuration=1000&wireFormat.maxInactivityDurationInitalDelay=1000"); brokerB.start(); doReconnect(); } private void doReconnect() throws Exception { for (int i=0; i<maxReconnects; i++) { // Wait for connection assertTrue("we got a network connection in a timely manner", Wait.waitFor(new Wait.Condition() { public boolean isSatisified() throws Exception { return proxy.connections.size() >= 1; } })); // wait for network connector assertTrue("network connector mbean registered within 1 minute", mbeanRegistered.tryAcquire(60, TimeUnit.SECONDS)); // force an inactivity timeout via the proxy proxy.pause(); // wait for the inactivity timeout and network shutdown assertTrue("network connector mbean unregistered within 1 minute", mbeanUnregistered.tryAcquire(60, TimeUnit.SECONDS)); // let a reconnect succeed proxy.goOn(); } } }
remove dependence on host name resolution to resolve failure on some machines, https://issues.apache.org/activemq/browse/AMQ-1855 git-svn-id: d2a93f579bd4835921162e9a69396c846e49961c@812046 13f79535-47bb-0310-9956-ffa450edef68
activemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java
remove dependence on host name resolution to resolve failure on some machines, https://issues.apache.org/activemq/browse/AMQ-1855
<ide><path>ctivemq-core/src/test/java/org/apache/activemq/transport/discovery/DiscoveryNetworkReconnectTest.java <ide> import org.apache.activemq.util.Wait; <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <add>import org.hamcrest.BaseMatcher; <add>import org.hamcrest.Description; <ide> import org.jmock.Expectations; <ide> import org.jmock.Mockery; <ide> import org.jmock.api.Invocation; <ide> <ide> private static final Log LOG = LogFactory.getLog(DiscoveryNetworkReconnectTest.class); <ide> final int maxReconnects = 5; <del> BrokerService brokerA, brokerB; <del> Mockery context; <del> ManagementContext managementContext; <del> <ide> final String groupName = "GroupID-" + "DiscoveryNetworkReconnectTest"; <ide> final String discoveryAddress = "multicast://default?group=" + groupName + "&initialReconnectDelay=1000"; <ide> final Semaphore mbeanRegistered = new Semaphore(0); <ide> final Semaphore mbeanUnregistered = new Semaphore(0); <del> <del> <del> private DiscoveryAgent agent; <add> BrokerService brokerA, brokerB; <add> Mockery context; <add> ManagementContext managementContext; <add> DiscoveryAgent agent; <ide> SocketProxy proxy; <add> <add> // ignore the hostname resolution component as this is machine dependent <add> class NetworkBridgeObjectNameMatcher<T> extends BaseMatcher<T> { <add> T name; <add> NetworkBridgeObjectNameMatcher(T o) { <add> name = o; <add> } <add> <add> public boolean matches(Object arg0) { <add> ObjectName other = (ObjectName) arg0; <add> ObjectName mine = (ObjectName) name; <add> return other.getKeyProperty("Type").equals(mine.getKeyProperty("Type")) && <add> other.getKeyProperty("NetworkConnectorName").equals(mine.getKeyProperty("NetworkConnectorName")); <add> } <add> <add> public void describeTo(Description arg0) { <add> arg0.appendText(this.getClass().getName()); <add> } <add> } <ide> <ide> @Before <ide> public void setUp() throws Exception { <ide> context = new JUnit4Mockery() {{ <ide> setImposteriser(ClassImposteriser.INSTANCE); <ide> }}; <del> <ide> brokerA = new BrokerService(); <ide> brokerA.setBrokerName("BrokerA"); <ide> configure(brokerA); <ide> allowing (managementContext).registerMBean(with(any(Object.class)), with(equal( <ide> new ObjectName("Test:BrokerName=BrokerNC,Type=Topic,Destination=ActiveMQ.Advisory.Connection")))); <ide> <del> atLeast(maxReconnects - 1).of (managementContext).registerMBean(with(any(Object.class)), with(equal( <add> atLeast(maxReconnects - 1).of (managementContext).registerMBean(with(any(Object.class)), with(new NetworkBridgeObjectNameMatcher<ObjectName>( <ide> new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=localhost,Name=localhost/127.0.0.1_" <ide> + proxy.getUrl().getPort())))); will(new CustomAction("signal register network mbean") { <ide> public Object invoke(Invocation invocation) throws Throwable { <ide> return new ObjectInstance((ObjectName)invocation.getParameter(0), "dscription"); <ide> } <ide> }); <del> atLeast(maxReconnects - 1).of (managementContext).unregisterMBean(with(equal( <add> atLeast(maxReconnects - 1).of (managementContext).unregisterMBean(with(new NetworkBridgeObjectNameMatcher<ObjectName>( <ide> new ObjectName("Test:BrokerName=BrokerNC,Type=NetworkBridge,NetworkConnectorName=localhost,Name=localhost/127.0.0.1_" <ide> + proxy.getUrl().getPort())))); will(new CustomAction("signal unregister network mbean") { <ide> public Object invoke(Invocation invocation) throws Throwable {
Java
apache-2.0
cf00890d6093c27be5e81721ba2e55a1c4a19e2c
0
bonigarcia/webdrivermanager,bonigarcia/webdrivermanager,bonigarcia/webdrivermanager
/* * (C) Copyright 2018 Boni Garcia (http://bonigarcia.github.io/) * * 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 io.github.bonigarcia.wdm.test.server; import static java.lang.invoke.MethodHandles.lookup; import static java.util.stream.Collectors.toList; import static org.apache.commons.lang.SystemUtils.IS_OS_WINDOWS; import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.net.PortProber.findFreePort; import static org.slf4j.LoggerFactory.getLogger; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.core5.http.Header; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import io.github.bonigarcia.wdm.WebDriverManager; /** * Test using wdm server. * * @author Boni Garcia * @since 3.0.0 */ class ServerResolverTest { static final Logger log = getLogger(lookup().lookupClass()); static final String EXT = IS_OS_WINDOWS ? ".exe" : ""; static int serverPort; @BeforeAll static void startServer() throws IOException { serverPort = findFreePort(); log.debug("Test is starting WebDriverManager server at port {}", serverPort); WebDriverManager .main(new String[] { "server", String.valueOf(serverPort) }); } @ParameterizedTest @MethodSource("data") void testServerResolver(String path, String driver) throws IOException { String serverUrl = String.format("http://localhost:%s/%s", serverPort, path); try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpUriRequestBase request = new HttpGet(serverUrl); // Assert response log.debug("Request: GET {}", serverUrl); try (CloseableHttpResponse response = client.execute(request)) { int responseCode = response.getCode(); log.debug("Response: {}", responseCode); assertThat(responseCode).isEqualTo(200); // Assert attachment String attachment = String.format("attachment; filename=\"%s\"", driver); List<Header> headerList = Arrays.asList(response.getHeaders()); List<Header> collect = headerList.stream().filter( x -> x.toString().contains("Content-Disposition")) .collect(toList()); log.debug("Assessing {} ... headers should contain {}", driver, attachment); assertThat(collect.get(0)).toString().contains(attachment); } } } static Stream<Arguments> data() { return Stream.of(Arguments.of("chromedriver", "chromedriver" + EXT), Arguments.of("firefoxdriver", "geckodriver" + EXT), Arguments.of("operadriver", "operadriver" + EXT), Arguments.of("edgedriver", "msedgedriver" + EXT), Arguments.of("chromedriver?os=WIN", "chromedriver.exe"), Arguments.of( "chromedriver?os=LINUX&chromeDriverVersion=2.41&forceCache=true", "chromedriver")); } }
src/test/java/io/github/bonigarcia/wdm/test/server/ServerResolverTest.java
/* * (C) Copyright 2018 Boni Garcia (http://bonigarcia.github.io/) * * 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 io.github.bonigarcia.wdm.test.server; import static java.lang.invoke.MethodHandles.lookup; import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS; import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.net.PortProber.findFreePort; import static org.slf4j.LoggerFactory.getLogger; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.core5.http.Header; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import io.github.bonigarcia.wdm.WebDriverManager; /** * Test using wdm server. * * @author Boni Garcia * @since 3.0.0 */ class ServerResolverTest { static final Logger log = getLogger(lookup().lookupClass()); static final String EXT = IS_OS_WINDOWS ? ".exe" : ""; static int serverPort; @BeforeAll static void startServer() throws IOException { serverPort = findFreePort(); log.debug("Test is starting WebDriverManager server at port {}", serverPort); WebDriverManager .main(new String[] { "server", String.valueOf(serverPort) }); } @ParameterizedTest @MethodSource("data") void testServerResolver(String path, String driver) throws IOException { String serverUrl = String.format("http://localhost:%s/%s", serverPort, path); try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpUriRequestBase request = new HttpGet(serverUrl); // Assert response log.debug("Request: GET {}", serverUrl); try (CloseableHttpResponse response = client.execute(request)) { int responseCode = response.getCode(); log.debug("Response: {}", responseCode); assertThat(responseCode).isEqualTo(200); // Assert attachment String attachment = String.format("attachment; filename=\"%s\"", driver); List<Header> headerList = Arrays.asList(response.getHeaders()); List<Header> collect = headerList.stream().filter( x -> x.toString().contains("Content-Disposition")) .collect(toList()); log.debug("Assessing {} ... headers should contain {}", driver, attachment); assertThat(collect.get(0)).toString().contains(attachment); } } } static Stream<Arguments> data() { return Stream.of(Arguments.of("chromedriver", "chromedriver" + EXT), Arguments.of("firefoxdriver", "geckodriver" + EXT), Arguments.of("operadriver", "operadriver" + EXT), Arguments.of("edgedriver", "msedgedriver" + EXT), Arguments.of("chromedriver?os=WIN", "chromedriver.exe"), Arguments.of( "chromedriver?os=LINUX&chromeDriverVersion=2.41&forceCache=true", "chromedriver")); } }
Change commons lang import in test
src/test/java/io/github/bonigarcia/wdm/test/server/ServerResolverTest.java
Change commons lang import in test
<ide><path>rc/test/java/io/github/bonigarcia/wdm/test/server/ServerResolverTest.java <ide> <ide> import static java.lang.invoke.MethodHandles.lookup; <ide> import static java.util.stream.Collectors.toList; <del>import static org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS; <add>import static org.apache.commons.lang.SystemUtils.IS_OS_WINDOWS; <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> import static org.openqa.selenium.net.PortProber.findFreePort; <ide> import static org.slf4j.LoggerFactory.getLogger;
Java
mit
df30f12ed5c891a790a59d29510e0beb10abd2ef
0
Dezorganizacja/bridge
package com.dezorganizacja.bridge.view.text; import java.util.List; import java.util.HashMap; import java.util.Map; /** * Created by maciek on 13.04.15. */ interface Command { void runCommand(List<String> args); } public class OrdersHandler { private final Map<String, Command> menuEntries = new HashMap<>(); private final Map<String, String> menuDetails = new HashMap<>(); { menuEntries.put("h", this::help); menuEntries.put("help", this::help); menuEntries.put("credits", this::credits); menuEntries.put("menu", this::print_menu); menuDetails.put("h", "Help system"); menuDetails.put("help", "Help system"); menuDetails.put("credits", "Credits"); menuDetails.put("menu", "Displays the possible prompt commands"); } private void help(List<String> args) { print("Some help should go here"); } private void credits(List<String> args) { print("Some credits should go here"); } private void print_menu(List<String> args) { for(String menuPosition : menuDetails.keySet()) { print(menuPosition + " - " + menuDetails.get(menuPosition)); } } private void print(String toPrint) { System.out.println(toPrint); } public void dispatchOrder(String commad, List<String> args) { if(!menuEntries.containsKey(commad)) { print("No such command: " + commad); } else { menuEntries.get(commad).runCommand(args); } } }
src/main/java/com/dezorganizacja/bridge/view/text/OrdersHandler.java
package com.dezorganizacja.bridge.view.text; import java.util.List; import java.util.HashMap; import java.util.Map; /** * Created by maciek on 13.04.15. */ interface Command { void runCommand(List<String> args); } public class OrdersHandler { private Map<String, Command> menuEntries = new HashMap<>(); private Map<String, String> menuDetails = new HashMap<>(); { menuEntries.put("h", this::help); menuEntries.put("help", this::help); menuEntries.put("credits", this::credits); menuEntries.put("menu", this::print_menu); menuDetails.put("h", "Help system"); menuDetails.put("help", "Help system"); menuDetails.put("credits", "Credits"); menuDetails.put("menu", "Displays the possible prompt commands"); } private void help(List<String> args) { print("Some help should go here"); } private void credits(List<String> args) { print("Some credits should go here"); } private void print_menu(List<String> args) { for(String menuPosition : menuDetails.keySet()) { print(menuPosition + " - " + menuDetails.get(menuPosition)); } } private void print(String toPrint) { System.out.println(toPrint); } public void dispatchOrder(String commad, List<String> args) { if(!menuEntries.containsKey(commad)) { print("No such command: " + commad); } else { menuEntries.get(commad).runCommand(args); } } }
Added that miserable final where appropriate
src/main/java/com/dezorganizacja/bridge/view/text/OrdersHandler.java
Added that miserable final where appropriate
<ide><path>rc/main/java/com/dezorganizacja/bridge/view/text/OrdersHandler.java <ide> } <ide> <ide> public class OrdersHandler { <del> private Map<String, Command> menuEntries = new HashMap<>(); <del> private Map<String, String> menuDetails = new HashMap<>(); <add> private final Map<String, Command> menuEntries = new HashMap<>(); <add> private final Map<String, String> menuDetails = new HashMap<>(); <ide> { <ide> menuEntries.put("h", this::help); <ide> menuEntries.put("help", this::help);
Java
apache-2.0
97bcc93c03cbfe3715514742a25737a1987feb56
0
rkrell/izpack,dasapich/izpack,Murdock01/izpack,stenix71/izpack,Helpstone/izpack,rsharipov/izpack,codehaus/izpack,Helpstone/izpack,dasapich/izpack,yukron/izpack,kanayo/izpack,rsharipov/izpack,optotronic/izpack,izpack/izpack,akuhtz/izpack,rsharipov/izpack,optotronic/izpack,yukron/izpack,akuhtz/izpack,rsharipov/izpack,yukron/izpack,mtjandra/izpack,yukron/izpack,optotronic/izpack,akuhtz/izpack,stenix71/izpack,kanayo/izpack,maichler/izpack,izpack/izpack,bradcfisher/izpack,awilhelm/izpack-with-ips,bradcfisher/izpack,yukron/izpack,tomas-forsman/izpack,tomas-forsman/izpack,stenix71/izpack,maichler/izpack,Sage-ERP-X3/izpack,tomas-forsman/izpack,mtjandra/izpack,rkrell/izpack,Murdock01/izpack,awilhelm/izpack-with-ips,kanayo/izpack,dasapich/izpack,maichler/izpack,rkrell/izpack,bradcfisher/izpack,rkrell/izpack,Sage-ERP-X3/izpack,rkrell/izpack,Helpstone/izpack,izpack/izpack,mtjandra/izpack,Murdock01/izpack,kanayo/izpack,bradcfisher/izpack,tomas-forsman/izpack,rsharipov/izpack,awilhelm/izpack-with-ips,awilhelm/izpack-with-ips,mtjandra/izpack,bradcfisher/izpack,Murdock01/izpack,maichler/izpack,rkrell/izpack,tomas-forsman/izpack,codehaus/izpack,maichler/izpack,akuhtz/izpack,maichler/izpack,optotronic/izpack,akuhtz/izpack,optotronic/izpack,codehaus/izpack,maichler/izpack,stenix71/izpack,Murdock01/izpack,bradcfisher/izpack,kanayo/izpack,tomas-forsman/izpack,dasapich/izpack,Helpstone/izpack,izpack/izpack,izpack/izpack,mtjandra/izpack,Sage-ERP-X3/izpack,izpack/izpack,Helpstone/izpack,Sage-ERP-X3/izpack,rsharipov/izpack,codehaus/izpack,Sage-ERP-X3/izpack,codehaus/izpack,stenix71/izpack,bradcfisher/izpack,dasapich/izpack,dasapich/izpack,Sage-ERP-X3/izpack,codehaus/izpack,Murdock01/izpack,optotronic/izpack,Helpstone/izpack,codehaus/izpack,mtjandra/izpack,optotronic/izpack,yukron/izpack,Murdock01/izpack,stenix71/izpack,kanayo/izpack,izpack/izpack,akuhtz/izpack,dasapich/izpack,akuhtz/izpack,tomas-forsman/izpack,yukron/izpack,rsharipov/izpack,awilhelm/izpack-with-ips,mtjandra/izpack,rkrell/izpack,Helpstone/izpack,Sage-ERP-X3/izpack,stenix71/izpack
/* * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved. * * http://izpack.org/ * http://developer.berlios.de/projects/izpack/ * * Copyright 2008 Piotr Skowronek * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.izforge.izpack.panels; import java.util.Map; import javax.swing.JComponent; import javax.swing.JTextField; import com.izforge.izpack.util.Debug; /*---------------------------------------------------------------------------*/ /** * This class is a wrapper for JTextField to allow field validation. * Based on RuleInputField. * * @author Piotr Skowronek */ /*---------------------------------------------------------------------------*/ public class TextInputField extends JComponent implements ProcessingClient { /** * */ private static final long serialVersionUID = 8611515659787697087L; /** * Validator parameters. */ private Map validatorParams; /** * Holds an instance of the <code>Validator</code> if one was specified and available */ private Validator validationService; /** * This composite can only contain one component ie JTextField */ private JTextField field; /** * Do we have parameters for validator? */ private boolean hasParams = false; /*--------------------------------------------------------------------------*/ /** * Constructs a text input field. * * @param set A default value for field. * @param size The size of the field. * @param validator A string that specifies a class to perform validation services. The string * must completely identify the class, so that it can be instantiated. The class must implement * the <code>RuleValidator</code> interface. If an attempt to instantiate this class fails, no * validation will be performed. * @param validatorParams validator parameters. */ /*--------------------------------------------------------------------------*/ public TextInputField(String set, int size, String validator, Map validatorParams) { this(set, size, validator); this.validatorParams = validatorParams; this.hasParams = true; } /*--------------------------------------------------------------------------*/ /** * Constructs a text input field. * * @param set A default value for field. * @param suze The size of the field. * @param validator A string that specifies a class to perform validation services. The string * must completely identify the class, so that it can be instantiated. The class must implement * the <code>RuleValidator</code> interface. If an attempt to instantiate this class fails, no * validation will be performed. */ /*--------------------------------------------------------------------------*/ public TextInputField(String set, int size, String validator) { // ---------------------------------------------------- // attempt to create an instance of the Validator // ---------------------------------------------------- try { if (validator != null) { validationService = (Validator) Class.forName(validator).newInstance(); } } catch (Throwable exception) { validationService = null; Debug.trace(exception); } com.izforge.izpack.gui.FlowLayout layout = new com.izforge.izpack.gui.FlowLayout(); layout.setAlignment(com.izforge.izpack.gui.FlowLayout.LEADING); layout.setVgap(0); setLayout(layout); // ---------------------------------------------------- // construct the UI element and add it to the composite // ---------------------------------------------------- field = new JTextField(set, size); field.setCaretPosition(0); add(field); } /*--------------------------------------------------------------------------*/ /** * Returns the validator parameters, if any. The caller should check for the existence of * validator parameters via the <code>hasParams()</code> method prior to invoking this method. * * @return a java.util.Map containing the validator parameters. */ public Map getValidatorParams() { return validatorParams; } /*---------------------------------------------------------------------------*/ /** * Returns the field contents, assembled acording to the encryption and separator rules. * * @return the field contents */ /*--------------------------------------------------------------------------*/ public String getText() { return (field.getText()); } // javadoc inherited public void setText(String value) { field.setText(value); } // javadoc inherited public String getFieldContents(int index) { return field.getText(); } // javadoc inherited public int getNumFields() { // We've got only one field return 1; } /*--------------------------------------------------------------------------*/ /** * This method validates the field content. Validating is performed through a user supplied * service class that provides the validation rules. * * @return <code>true</code> if the validation passes or no implementation of a validation * rule exists. Otherwise <code>false</code> is returned. */ /*--------------------------------------------------------------------------*/ public boolean validateContents() { if (validationService != null) { return (validationService.validate(this)); } else { return (true); } } // javadoc inherited public boolean hasParams() { return hasParams; } // ---------------------------------------------------------------------------- } /*---------------------------------------------------------------------------*/
src/lib/com/izforge/izpack/panels/TextInputField.java
/* * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved. * * http://izpack.org/ * http://developer.berlios.de/projects/izpack/ * * Copyright 2008 Piotr Skowronek * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.izforge.izpack.panels; import java.util.Map; import javax.swing.JComponent; import javax.swing.JTextField; import com.izforge.izpack.util.Debug; /*---------------------------------------------------------------------------*/ /** * This class is a wrapper for JTextField to allow field validation. * Based on RuleInputField. * * @author Piotr Skowronek */ /*---------------------------------------------------------------------------*/ public class TextInputField extends JComponent implements ProcessingClient { /** * */ private static final long serialVersionUID = 8611515659787697087L; /** * Validator parameters. */ private Map validatorParams; /** * Holds an instance of the <code>Validator</code> if one was specified and available */ private Validator validationService; /** * This composite can only contain one component ie JTextField */ private JTextField field; /** * Do we have parameters for validator? */ private boolean hasParams = false; /*--------------------------------------------------------------------------*/ /** * Constructs a text input field. * * @param set A default value for field. * @param size The size of the field. * @param validator A string that specifies a class to perform validation services. The string * must completely identify the class, so that it can be instantiated. The class must implement * the <code>RuleValidator</code> interface. If an attempt to instantiate this class fails, no * validation will be performed. * @param validatorParams validator parameters. */ /*--------------------------------------------------------------------------*/ public TextInputField(String set, int size, String validator, Map validatorParams) { this(set, size, validator); this.validatorParams = validatorParams; this.hasParams = true; } /*--------------------------------------------------------------------------*/ /** * Constructs a text input field. * * @param set A default value for field. * @param suze The size of the field. * @param validator A string that specifies a class to perform validation services. The string * must completely identify the class, so that it can be instantiated. The class must implement * the <code>RuleValidator</code> interface. If an attempt to instantiate this class fails, no * validation will be performed. */ /*--------------------------------------------------------------------------*/ public TextInputField(String set, int size, String validator) { // ---------------------------------------------------- // attempt to create an instance of the Validator // ---------------------------------------------------- try { if (validator != null) { validationService = (Validator) Class.forName(validator).newInstance(); } } catch (Throwable exception) { validationService = null; Debug.trace(exception); } com.izforge.izpack.gui.FlowLayout layout = new com.izforge.izpack.gui.FlowLayout(); layout.setAlignment(com.izforge.izpack.gui.FlowLayout.LEFT); setLayout(layout); // ---------------------------------------------------- // construct the UI element and add it to the composite // ---------------------------------------------------- field = new JTextField(set, size); field.setCaretPosition(0); add(field); } /*--------------------------------------------------------------------------*/ /** * Returns the validator parameters, if any. The caller should check for the existence of * validator parameters via the <code>hasParams()</code> method prior to invoking this method. * * @return a java.util.Map containing the validator parameters. */ public Map getValidatorParams() { return validatorParams; } /*---------------------------------------------------------------------------*/ /** * Returns the field contents, assembled acording to the encryption and separator rules. * * @return the field contents */ /*--------------------------------------------------------------------------*/ public String getText() { return (field.getText()); } // javadoc inherited public void setText(String value) { field.setText(value); } // javadoc inherited public String getFieldContents(int index) { return field.getText(); } // javadoc inherited public int getNumFields() { // We've got only one field return 1; } /*--------------------------------------------------------------------------*/ /** * This method validates the field content. Validating is performed through a user supplied * service class that provides the validation rules. * * @return <code>true</code> if the validation passes or no implementation of a validation * rule exists. Otherwise <code>false</code> is returned. */ /*--------------------------------------------------------------------------*/ public boolean validateContents() { if (validationService != null) { return (validationService.validate(this)); } else { return (true); } } // javadoc inherited public boolean hasParams() { return hasParams; } // ---------------------------------------------------------------------------- } /*---------------------------------------------------------------------------*/
layout issue is fixed git-svn-id: 408af81b9e4f0a5eaad229a6d9eed76d614c4af6@2000 7d736ef5-cfd4-0310-9c9a-b52d5c14b761
src/lib/com/izforge/izpack/panels/TextInputField.java
layout issue is fixed
<ide><path>rc/lib/com/izforge/izpack/panels/TextInputField.java <ide> } <ide> <ide> com.izforge.izpack.gui.FlowLayout layout = new com.izforge.izpack.gui.FlowLayout(); <del> layout.setAlignment(com.izforge.izpack.gui.FlowLayout.LEFT); <add> layout.setAlignment(com.izforge.izpack.gui.FlowLayout.LEADING); <add> layout.setVgap(0); <ide> setLayout(layout); <ide> <ide> // ----------------------------------------------------
Java
apache-2.0
f3683e9b97cda6c7d0253bcec35a71e4ec008e5b
0
matrix-org/matrix-android-sdk,matrix-org/matrix-android-sdk,matrix-org/matrix-android-sdk
/* * Copyright 2015 OpenMarket Ltd * * 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.matrix.androidsdk.fragments; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.media.ThumbnailUtils; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.provider.Browser; import android.provider.MediaStore; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.google.gson.JsonObject; import org.matrix.androidsdk.MXSession; import org.matrix.androidsdk.R; import org.matrix.androidsdk.adapters.MessageRow; import org.matrix.androidsdk.adapters.MessagesAdapter; import org.matrix.androidsdk.data.EventTimeline; import org.matrix.androidsdk.data.IMXStore; import org.matrix.androidsdk.data.Room; import org.matrix.androidsdk.data.RoomPreviewData; import org.matrix.androidsdk.data.RoomState; import org.matrix.androidsdk.data.RoomSummary; import org.matrix.androidsdk.db.MXMediasCache; import org.matrix.androidsdk.listeners.IMXEventListener; import org.matrix.androidsdk.listeners.MXEventListener; import org.matrix.androidsdk.listeners.MXMediaUploadListener; import org.matrix.androidsdk.rest.callback.ApiCallback; import org.matrix.androidsdk.rest.callback.SimpleApiCallback; import org.matrix.androidsdk.rest.model.Event; import org.matrix.androidsdk.rest.model.FileMessage; import org.matrix.androidsdk.rest.model.ImageMessage; import org.matrix.androidsdk.rest.model.LocationMessage; import org.matrix.androidsdk.rest.model.MatrixError; import org.matrix.androidsdk.rest.model.Message; import org.matrix.androidsdk.rest.model.ReceiptData; import org.matrix.androidsdk.rest.model.Search.SearchResponse; import org.matrix.androidsdk.rest.model.Search.SearchResult; import org.matrix.androidsdk.rest.model.User; import org.matrix.androidsdk.rest.model.VideoMessage; import org.matrix.androidsdk.rest.model.bingrules.BingRule; import org.matrix.androidsdk.util.EventDisplay; import org.matrix.androidsdk.util.JsonUtils; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Timer; import java.util.TimerTask; import retrofit.RetrofitError; /** * UI Fragment containing matrix messages for a given room. * Contains {@link MatrixMessagesFragment} as a nested fragment to do the work. */ public class MatrixMessageListFragment extends Fragment implements MatrixMessagesFragment.MatrixMessagesListener, MessagesAdapter.MessagesAdapterEventsListener { // search interface public interface OnSearchResultListener { void onSearchSucceed(int nbrMessages); void onSearchFailed(); } // room preview interface public interface IRoomPreviewDataListener { RoomPreviewData getRoomPreviewData(); } // be warned when a message sending failed or succeeded public interface IEventSendingListener { /** * A message has been successfully sent. * @param event the event */ void onMessageSendingSucceeded(Event event); /** * A message sending has failed. * @param event the event */ void onMessageSendingFailed(Event event); /** * An event has been successfully redacted by the user. * @param event the event */ void onMessageRedacted(Event event); } // scroll listener public interface IOnScrollListener { /** * The events list has been scrolled. * @param firstVisibleItem the index of the first visible cell * @param visibleItemCount the number of visible cells * @param totalItemCount the number of items in the list adaptor */ void onScroll(int firstVisibleItem, int visibleItemCount, int totalItemCount); /** * Tell if the latest event is fully displayed * @param isDisplayed true if the latest event is fully displayed */ void onLatestEventDisplay(boolean isDisplayed); } protected static final String TAG_FRAGMENT_MESSAGE_OPTIONS = "org.matrix.androidsdk.RoomActivity.TAG_FRAGMENT_MESSAGE_OPTIONS"; protected static final String TAG_FRAGMENT_MESSAGE_DETAILS = "org.matrix.androidsdk.RoomActivity.TAG_FRAGMENT_MESSAGE_DETAILS"; // fragment parameters public static final String ARG_LAYOUT_ID = "MatrixMessageListFragment.ARG_LAYOUT_ID"; public static final String ARG_MATRIX_ID = "MatrixMessageListFragment.ARG_MATRIX_ID"; public static final String ARG_ROOM_ID = "MatrixMessageListFragment.ARG_ROOM_ID"; public static final String ARG_EVENT_ID = "MatrixMessageListFragment.ARG_EVENT_ID"; public static final String ARG_PREVIEW_MODE_ID = "MatrixMessageListFragment.ARG_PREVIEW_MODE_ID"; // default preview mode public static final String PREVIEW_MODE_READ_ONLY = "PREVIEW_MODE_READ_ONLY"; private static final String LOG_TAG = "MatrixMsgsListFrag"; private static final int UNDEFINED_VIEW_Y_POS = -12345678; public static MatrixMessageListFragment newInstance(String matrixId, String roomId, int layoutResId) { MatrixMessageListFragment f = new MatrixMessageListFragment(); Bundle args = new Bundle(); args.putString(ARG_ROOM_ID, roomId); args.putInt(ARG_LAYOUT_ID, layoutResId); args.putString(ARG_MATRIX_ID, matrixId); return f; } private MatrixMessagesFragment mMatrixMessagesFragment; protected MessagesAdapter mAdapter; public ListView mMessageListView; protected Handler mUiHandler; protected MXSession mSession; protected String mMatrixId; protected Room mRoom; protected String mPattern = null; protected boolean mIsMediaSearch; protected String mNextBatch = null; private boolean mDisplayAllEvents = true; public boolean mCheckSlideToHide = false; private boolean mIsScrollListenerSet; // timeline management protected boolean mIsLive = true; // by default the protected EventTimeline mEventTimeLine; protected String mEventId; // pagination statuses protected boolean mIsInitialSyncing = true; protected boolean mIsBackPaginating = false; protected boolean mIsFwdPaginating = false; // lock the pagination while refreshing the list view to avoid having twice or thrice refreshes sequence. private boolean mLockBackPagination = false; private boolean mLockFwdPagination = true; protected ArrayList<Event> mResendingEventsList; private final HashMap<String, Timer> mPendingRelaunchTimersByEventId = new HashMap<>(); private final HashMap<String, Object> mBingRulesByEventId = new HashMap<>(); // scroll to to the dedicated index when the device has been rotated private int mFirstVisibleRow = -1; // scroll to the index when loaded private int mScrollToIndex = -1; // y pos of the first visible row private int mFirstVisibleRowY = UNDEFINED_VIEW_Y_POS; // used to retrieve the preview data protected IRoomPreviewDataListener mRoomPreviewDataListener; // be warned that an event sending has failed. protected IEventSendingListener mEventSendingListener; // listen when the events list is scrolled. protected IOnScrollListener mActivityOnScrollListener; public MXMediasCache getMXMediasCache() { return null; } public MXSession getSession(String matrixId) { return null; } public MXSession getSession() { // if the session has not been set if (null == mSession) { // find it out mSession = getSession(mMatrixId); } return mSession; } /** * @return an UI handler */ private Handler getUiHandler() { if (null == mUiHandler) { mUiHandler = new Handler(Looper.getMainLooper()); } return mUiHandler; } private final IMXEventListener mEventsListener = new MXEventListener() { @Override public void onPresenceUpdate(Event event, final User user) { // Someone's presence has changed, reprocess the whole list getUiHandler().post(new Runnable() { @Override public void run() { // check first if the userID has sent some messages in the room history boolean refresh = mAdapter.isDisplayedUser(user.user_id); if (refresh) { // check, if the avatar is currently displayed // The Math.min is required because the adapter and mMessageListView could be unsynchronized. // ensure there is no IndexOfOutBound exception. int firstVisibleRow = Math.min(mMessageListView.getFirstVisiblePosition(), mAdapter.getCount()); int lastVisibleRow = Math.min(mMessageListView.getLastVisiblePosition(), mAdapter.getCount()); refresh = false; for (int i = firstVisibleRow; i <= lastVisibleRow; i++) { MessageRow row = mAdapter.getItem(i); refresh |= TextUtils.equals(user.user_id, row.getEvent().getSender()); } } if (refresh) { mAdapter.notifyDataSetChanged(); } } }); } @Override public void onBingRulesUpdate() { mBingRulesByEventId.clear(); } }; /** * Customize the scrolls behaviour. * -> scroll over the top triggers a back pagination * -> scroll over the bottom triggers a forward pagination */ protected final AbsListView.OnScrollListener mScrollListener = new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mCheckSlideToHide = (scrollState == SCROLL_STATE_TOUCH_SCROLL); //check only when the user scrolls the content if (scrollState == SCROLL_STATE_TOUCH_SCROLL) { int firstVisibleRow = mMessageListView.getFirstVisiblePosition(); int lastVisibleRow = mMessageListView.getLastVisiblePosition(); int count = mMessageListView.getCount(); if ((lastVisibleRow + 10) >= count) { Log.d(LOG_TAG, "onScrollStateChanged - forwardPaginate"); forwardPaginate(); } else if (firstVisibleRow < 2) { Log.d(LOG_TAG, "onScrollStateChanged - request history"); backPaginate(false); } } } /** * Warns that the list has been scrolled. * @param view the list view * @param firstVisibleItem the first visible indew * @param visibleItemCount the number of visible items * @param totalItemCount the total number of items */ private void manageScrollListener(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (null != mActivityOnScrollListener) { try { mActivityOnScrollListener.onScroll(firstVisibleItem, visibleItemCount, totalItemCount); } catch (Exception e) { Log.e(LOG_TAG, "## manageScrollListener : onScroll failed " + e.getMessage()); } boolean isLatestEventDisplayed; // test if the latest message is not displayed if ((firstVisibleItem + visibleItemCount) < totalItemCount) { // the latest event is not displayed isLatestEventDisplayed = false; } else { AbsListView absListView = view; View childview = absListView.getChildAt(visibleItemCount-1); // test if the bottom of the latest item is equals to the list height isLatestEventDisplayed = (null != childview) && ((childview.getTop() + childview.getHeight()) <= view.getHeight()); } try { mActivityOnScrollListener.onLatestEventDisplay(isLatestEventDisplayed); } catch (Exception e) { Log.e(LOG_TAG, "## manageScrollListener : onLatestEventDisplay failed " + e.getMessage()); } } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // store the current Y pos to jump to the right pos when backpaginating mFirstVisibleRowY = UNDEFINED_VIEW_Y_POS; View v = mMessageListView.getChildAt(firstVisibleItem); if (null != v) { mFirstVisibleRowY = v.getTop(); } if ((firstVisibleItem < 2) && (visibleItemCount != totalItemCount) && (0 != visibleItemCount)) { // Log.d(LOG_TAG, "onScroll - backPaginate"); backPaginate(false); } else if ((firstVisibleItem + visibleItemCount + 10) >= totalItemCount) { // Log.d(LOG_TAG, "onScroll - forwardPaginate"); forwardPaginate(); } manageScrollListener(view, firstVisibleItem, visibleItemCount, totalItemCount); } }; @Override public void onCreate(Bundle savedInstanceState) { Log.d(LOG_TAG, "onCreate"); super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(LOG_TAG, "onCreateView"); super.onCreateView(inflater, container, savedInstanceState); Bundle args = getArguments(); // for dispatching data to add to the adapter we need to be on the main thread mUiHandler = new Handler(Looper.getMainLooper()); mMatrixId = args.getString(ARG_MATRIX_ID); mSession = getSession(mMatrixId); if (null == mSession) { throw new RuntimeException("Must have valid default MXSession."); } if (null == getMXMediasCache()) { throw new RuntimeException("Must have valid default MediasCache."); } String roomId = args.getString(ARG_ROOM_ID); View v = inflater.inflate(args.getInt(ARG_LAYOUT_ID), container, false); mMessageListView = ((ListView)v.findViewById(R.id.listView_messages)); mIsScrollListenerSet = false; if (mAdapter == null) { // only init the adapter if it wasn't before, so we can preserve messages/position. mAdapter = createMessagesAdapter(); if (null == getMXMediasCache()) { throw new RuntimeException("Must have valid default MessagesAdapter."); } } else if(null != savedInstanceState) { mFirstVisibleRow = savedInstanceState.getInt("FIRST_VISIBLE_ROW", -1); } mAdapter.setIsPreviewMode(false); if (null == mEventTimeLine) { mEventId = args.getString(ARG_EVENT_ID); // the fragment displays the history around a message if (!TextUtils.isEmpty(mEventId)) { mEventTimeLine = new EventTimeline(mSession.getDataHandler(), roomId, mEventId); mRoom = mEventTimeLine.getRoom(); } // display a room preview else if (null != args.getString(ARG_PREVIEW_MODE_ID)) { mAdapter.setIsPreviewMode(true); mEventTimeLine = new EventTimeline(mSession.getDataHandler(), roomId); mRoom = mEventTimeLine.getRoom(); } // standard case else { if (!TextUtils.isEmpty(roomId)) { mRoom = mSession.getDataHandler().getRoom(roomId); mEventTimeLine = mRoom.getLiveTimeLine(); } } } // GA reported some weird room content // so ensure that the room fields are properly initialized mSession.getDataHandler().checkRoom(mRoom); // sanity check if (null != mRoom) { mAdapter.setTypingUsers(mRoom.getTypingUsers()); } mMessageListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { MatrixMessageListFragment.this.onRowClick(position); } }); mMessageListView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { onListTouch(event); return false; } }); mAdapter.setMessagesAdapterEventsListener(this); mDisplayAllEvents = isDisplayAllEvents(); return v; } /** * Called when a fragment is first attached to its activity. * {@link #onCreate(Bundle)} will be called after this. * * @param aHostActivity parent activity */ @Override public void onAttach(Activity aHostActivity) { super.onAttach(aHostActivity); try { mEventSendingListener = (IEventSendingListener) aHostActivity; } catch(ClassCastException e) { // if host activity does not provide the implementation, just ignore it Log.w(LOG_TAG,"## onAttach(): host activity does not implement IEventSendingListener " + aHostActivity); } try { mActivityOnScrollListener = (IOnScrollListener) aHostActivity; } catch(ClassCastException e) { // if host activity does not provide the implementation, just ignore it Log.w(LOG_TAG,"## onAttach(): host activity does not implement IOnScrollListener " + aHostActivity); } } /** * Called when the fragment is no longer attached to its activity. This * is called after {@link #onDestroy()}. */ @Override public void onDetach() { super.onDetach(); mEventSendingListener = null; mActivityOnScrollListener = null; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (null != mMessageListView) { int selected = mMessageListView.getFirstVisiblePosition(); // ListView always returns the previous index while filling from bottom if (selected > 0) { selected++; } outState.putInt("FIRST_VISIBLE_ROW", selected); } } /** * Called when the fragment is no longer in use. This is called * after {@link #onStop()} and before {@link #onDetach()}. */ @Override public void onDestroy() { super.onDestroy(); // remove listeners to prevent memory leak if(null != mMatrixMessagesFragment) { mMatrixMessagesFragment.setMatrixMessagesListener(null); } if(null != mAdapter) { mAdapter.setMessagesAdapterEventsListener(null); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Bundle args = getArguments(); FragmentManager fm = getActivity().getSupportFragmentManager(); mMatrixMessagesFragment = (MatrixMessagesFragment) fm.findFragmentByTag(getMatrixMessagesFragmentTag()); if (mMatrixMessagesFragment == null) { Log.d(LOG_TAG, "onActivityCreated create"); // this fragment controls all the logic for handling messages / API calls mMatrixMessagesFragment = createMessagesFragmentInstance(args.getString(ARG_ROOM_ID)); fm.beginTransaction().add(mMatrixMessagesFragment, getMatrixMessagesFragmentTag()).commit(); } else { Log.d(LOG_TAG, "onActivityCreated - reuse"); // Reset the listener because this is not done when the system restores the fragment (newInstance is not called) mMatrixMessagesFragment.setMatrixMessagesListener(this); } mMatrixMessagesFragment.mKeepRoomHistory = (-1 != mFirstVisibleRow); } @Override public void onPause() { super.onPause(); // mBingRulesByEventId.clear(); // check if the session has not been logged out if (mSession.isAlive() && (null != mRoom) && mIsLive) { mRoom.removeEventListener(mEventsListener); } cancelCatchingRequests(); } @Override public void onResume() { super.onResume(); // sanity check if ((null != mRoom) && mIsLive) { Room room = mSession.getDataHandler().getRoom(mRoom.getRoomId(), false); if (null != room) { room.addEventListener(mEventsListener); } else { Log.e(LOG_TAG, "the room " + mRoom.getRoomId() + " does not exist anymore"); } } } //============================================================================================================== // general methods //============================================================================================================== /** * Create the messageFragment. * Should be inherited. * @param roomId the roomID * @return the MatrixMessagesFragment */ public MatrixMessagesFragment createMessagesFragmentInstance(String roomId) { return MatrixMessagesFragment.newInstance(getSession(), roomId, this); } /** * @return the fragment tag to use to restore the matrix messages fragment */ protected String getMatrixMessagesFragmentTag() { return "org.matrix.androidsdk.RoomActivity.TAG_FRAGMENT_MATRIX_MESSAGES"; } /** * Create the messages adapter. * This method must be overriden to provide a valid creation * @return the messages adapter. */ public MessagesAdapter createMessagesAdapter() { return null; } /** * The user scrolls the list. * Apply an expected behaviour * @param event the scroll event */ public void onListTouch(MotionEvent event) { } /** * Scroll the listview to a dedicated index when the list is loaded. * @param index the index */ public void scrollToIndexWhenLoaded(int index) { mScrollToIndex = index; } /** * return true to display all the events. * else the unknown events will be hidden. */ public boolean isDisplayAllEvents() { return true; } /** * @return the max thumbnail width */ public int getMaxThumbnailWith() { return mAdapter.getMaxThumbnailWith(); } /** * @return the max thumbnail height */ public int getMaxThumbnailHeight() { return mAdapter.getMaxThumbnailHeight(); } /** * Notify the fragment that some bing rules could have been updated. */ public void onBingRulesUpdate() { mAdapter.onBingRulesUpdate(); } /** * Scroll the listView to the last item. * @param delayMs the delay before jumping to the latest event. */ public void scrollToBottom(int delayMs) { mMessageListView.postDelayed(new Runnable() { @Override public void run() { mMessageListView.setSelection(mAdapter.getCount() - 1); } }, Math.max(delayMs, 0)); } /** * Scroll the listview to the last item. */ public void scrollToBottom() { scrollToBottom(300); } /** * Provides the event for a dedicated row. * @param row the row * @return the event */ public Event getEvent(int row) { Event event = null; if (mAdapter.getCount() > row) { event = mAdapter.getItem(row).getEvent(); } return event; } // create a dummy message row for the message // It is added to the Adapter // return the created Message private MessageRow addMessageRow(Message message) { // a message row can only be added if there is a defined room if (null != mRoom) { Event event = new Event(message, mSession.getCredentials().userId, mRoom.getRoomId()); mRoom.storeOutgoingEvent(event); MessageRow messageRow = new MessageRow(event, mRoom.getState()); mAdapter.add(messageRow); scrollToBottom(); Log.d(LOG_TAG, "AddMessage Row : commit"); getSession().getDataHandler().getStore().commit(); return messageRow; } else { return null; } } /** * Redact an event from its event id. * @param eventId the event id. */ protected void redactEvent(String eventId) { // Do nothing on success, the event will be hidden when the redaction event comes down the event stream mMatrixMessagesFragment.redact(eventId, new ApiCallback<Event>() { @Override public void onSuccess(Event redactedEvent) { // create a dummy redacted event to manage the redaction. // some redated events are not removed from the history but they are pruned. Event redacterEvent = new Event(); redacterEvent.roomId = redactedEvent.roomId; redacterEvent.redacts = redactedEvent.eventId; redacterEvent.type = Event.EVENT_TYPE_REDACTION; onEvent(redacterEvent, EventTimeline.Direction.FORWARDS, mRoom.getLiveState()); if (null != mEventSendingListener) { try { mEventSendingListener.onMessageRedacted(redactedEvent); } catch (Exception e) { Log.e(LOG_TAG, "redactEvent fails : " + e.getMessage()); } } } private void onError() { if (null != getActivity()) { Toast.makeText(getActivity(), getActivity().getString(R.string.could_not_redact), Toast.LENGTH_SHORT).show(); } } @Override public void onNetworkError(Exception e) { onError(); } @Override public void onMatrixError(MatrixError e) { onError(); } @Override public void onUnexpectedError(Exception e) { onError(); } }); } /** * Tells if an event is supported by the fragment. * @param event the event to test * @return true it is supported. */ private boolean canAddEvent(Event event) { String type = event.type; return mDisplayAllEvents || Event.EVENT_TYPE_MESSAGE.equals(type) || Event.EVENT_TYPE_MESSAGE_ENCRYPTED.equals(type)|| Event.EVENT_TYPE_STATE_ROOM_NAME.equals(type) || Event.EVENT_TYPE_STATE_ROOM_TOPIC.equals(type) || Event.EVENT_TYPE_STATE_ROOM_MEMBER.equals(type) || Event.EVENT_TYPE_STATE_ROOM_THIRD_PARTY_INVITE.equals(type) || Event.EVENT_TYPE_STATE_HISTORY_VISIBILITY.equals(type) || (event.isCallEvent() && (!Event.EVENT_TYPE_CALL_CANDIDATES.equals(type))) ; } //============================================================================================================== // Messages sending method. //============================================================================================================== /** * Warns that a message sending has failed. * @param event the event */ private void onMessageSendingFailed(Event event) { if (null != mEventSendingListener) { try { mEventSendingListener.onMessageSendingFailed(event); } catch (Exception e) { Log.e(LOG_TAG, "onMessageSendingFailed failed " + e.getLocalizedMessage()); } } } /** * Warns that a message sending succeeds. * @param event the events */ private void onMessageSendingSucceeded(Event event) { if (null != mEventSendingListener) { try { mEventSendingListener.onMessageSendingSucceeded(event); } catch (Exception e) { Log.e(LOG_TAG, "onMessageSendingSucceeded failed " + e.getLocalizedMessage()); } } } /** * Send a messsage in the room. * @param message the message to send. */ private void send(final Message message) { send(addMessageRow(message)); } /** * Send a message row in the dedicated room. * @param messageRow the message row to send. */ private void send(final MessageRow messageRow) { // add sanity check if (null == messageRow) { return; } final Event event = messageRow.getEvent(); if (!event.isUndeliverable()) { final String prevEventId = event.eventId; mMatrixMessagesFragment.sendEvent(event, new ApiCallback<Void>() { @Override public void onSuccess(Void info) { onMessageSendingSucceeded(event); mAdapter.updateEventById(event, prevEventId); // pending resending ? if ((null != mResendingEventsList) && (mResendingEventsList.size() > 0)) { resend(mResendingEventsList.get(0)); mResendingEventsList.remove(0); } } private void commonFailure(final Event event) { if (null != MatrixMessageListFragment.this.getActivity()) { // display the error message only if the message cannot be resent if ((null != event.unsentException) && (event.isUndeliverable())) { if ((event.unsentException instanceof RetrofitError) && ((RetrofitError) event.unsentException).isNetworkError()) { Toast.makeText(getActivity(), getActivity().getString(R.string.unable_to_send_message) + " : " + getActivity().getString(R.string.network_error), Toast.LENGTH_LONG).show(); } else { Toast.makeText(getActivity(), getActivity().getString(R.string.unable_to_send_message) + " : " + event.unsentException.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } } else if (null != event.unsentMatrixError) { Toast.makeText(getActivity(), getActivity().getString(R.string.unable_to_send_message) + " : " + event.unsentMatrixError.getLocalizedMessage() + ".", Toast.LENGTH_LONG).show(); } mAdapter.notifyDataSetChanged(); onMessageSendingFailed(event); } } @Override public void onNetworkError(Exception e) { commonFailure(event); } @Override public void onMatrixError(MatrixError e) { commonFailure(event); } @Override public void onUnexpectedError(Exception e) { commonFailure(event); } }); } } /** * Send a text message. * @param body the text message to send. */ public void sendTextMessage(String body) { sendMessage(Message.MSGTYPE_TEXT, body, null, null); } /** * Send a formatted text message. * @param body the unformatted text message * @param formattedBody the formatted text message (optional) * @param format the format */ public void sendTextMessage(String body, String formattedBody, String format) { sendMessage(Message.MSGTYPE_TEXT, body, formattedBody, format); } /** * Send a message of type msgType with a formatted body * @param msgType the message type * @param body the unformatted text message * @param formattedBody the formatted text message (optional) * @param format the format */ private void sendMessage(String msgType, String body, String formattedBody, String format) { Message message = new Message(); message.msgtype = msgType; message.body = body; if (null != formattedBody) { // assume that the formatted body use a custom html format message.format = format; message.formatted_body = formattedBody; } send(message); } /** * Send an emote * @param emote the emote * @param formattedEmote the formatted text message (optional) * @param format the format */ public void sendEmote(String emote, String formattedEmote, String format) { sendMessage(Message.MSGTYPE_EMOTE, emote, formattedEmote, format); } /** * The media upload fails. * @param serverResponseCode the response code. * @param serverErrorMessage the error message. * @param messageRow the messageRow */ private void commonMediaUploadError(int serverResponseCode, final String serverErrorMessage, final MessageRow messageRow) { // warn the user that the media upload fails if (serverResponseCode == 500) { Timer relaunchTimer = new Timer(); mPendingRelaunchTimersByEventId.put(messageRow.getEvent().eventId, relaunchTimer); relaunchTimer.schedule(new TimerTask() { @Override public void run() { if (mPendingRelaunchTimersByEventId.containsKey(messageRow.getEvent().eventId)) { mPendingRelaunchTimersByEventId.remove(messageRow.getEvent().eventId); Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { resend(messageRow.getEvent()); } }); } } }, 1000); } else { messageRow.getEvent().mSentState = Event.SentState.UNDELIVERABLE; onMessageSendingFailed(messageRow.getEvent()); if (null != getActivity()) { Toast.makeText(getActivity(), (null != serverErrorMessage) ? serverErrorMessage : getString(R.string.message_failed_to_upload), Toast.LENGTH_LONG).show(); } } } /** * Upload a file content * @param mediaUrl the media URL * @param mimeType the media mime type * @param mediaFilename the media filename */ public void uploadFileContent(final String mediaUrl, final String mimeType, final String mediaFilename) { // create a tmp row final FileMessage tmpFileMessage = new FileMessage(); tmpFileMessage.url = mediaUrl; tmpFileMessage.body = mediaFilename; FileInputStream fileStream = null; try { Uri uri = Uri.parse(mediaUrl); Room.fillFileInfo(getActivity(), tmpFileMessage, uri, mimeType); String filename = uri.getPath(); fileStream = new FileInputStream (new File(filename)); if (null == tmpFileMessage.body) { tmpFileMessage.body = uri.getLastPathSegment(); } } catch (Exception e) { Log.e(LOG_TAG, "uploadFileContent failed with " + e.getLocalizedMessage()); } // remove any displayed MessageRow with this URL // to avoid duplicate final MessageRow messageRow = addMessageRow(tmpFileMessage); messageRow.getEvent().mSentState = Event.SentState.SENDING; getSession().getMediasCache().uploadContent(fileStream, tmpFileMessage.body, mimeType, mediaUrl, new MXMediaUploadListener() { @Override public void onUploadStart(String uploadId) { getUiHandler().post(new Runnable() { @Override public void run() { onMessageSendingSucceeded(messageRow.getEvent()); // display the pie chart. mAdapter.notifyDataSetChanged(); } }); } @Override public void onUploadCancel(String uploadId) { getUiHandler().post(new Runnable() { @Override public void run() { onMessageSendingFailed(messageRow.getEvent()); } }); } @Override public void onUploadError(final String uploadId, final int serverResponseCode, final String serverErrorMessage) { getUiHandler().post(new Runnable() { @Override public void run() { commonMediaUploadError(serverResponseCode,serverErrorMessage, messageRow); } }); } @Override public void onUploadComplete(final String uploadId, final String contentUri) { getUiHandler().post(new Runnable() { @Override public void run() { // Build the image message FileMessage message = tmpFileMessage.deepCopy(); // replace the thumbnail and the media contents by the computed ones getMXMediasCache().saveFileMediaForUrl(contentUri, mediaUrl, tmpFileMessage.getMimeType()); message.url = contentUri; // update the event content with the new message info messageRow.getEvent().content = JsonUtils.toJson(message); Log.d(LOG_TAG, "Uploaded to " + contentUri); send(messageRow); } }); } }); } /** * Compute the video thumbnail * @param videoUrl the video url * @return the video thumbnail */ public String getVideoThumbnailUrl(final String videoUrl) { String thumbUrl = null; try { Uri uri = Uri.parse(videoUrl); Bitmap thumb = ThumbnailUtils.createVideoThumbnail(uri.getPath(), MediaStore.Images.Thumbnails.MINI_KIND); thumbUrl = getMXMediasCache().saveBitmap(thumb, null); } catch (Exception e) { Log.e(LOG_TAG, "getVideoThumbailUrl failed with " + e.getLocalizedMessage()); } return thumbUrl; } /** * Upload a video message * The video thumbnail will be computed * @param videoUrl the video url * @param body the message body * @param videoMimeType the video mime type */ public void uploadVideoContent(final String videoUrl, final String body, final String videoMimeType) { uploadVideoContent(videoUrl, getVideoThumbnailUrl(videoUrl), body, videoMimeType); } /** * Upload a video message * The video thumbnail will be computed * @param videoUrl the video url * @param thumbUrl the thumbnail Url * @param body the message body * @param videoMimeType the video mime type */ public void uploadVideoContent(final String videoUrl, final String thumbUrl, final String body, final String videoMimeType) { // if the video thumbnail cannot be retrieved // send it as a file if (null == thumbUrl) { this.uploadFileContent(videoUrl, videoMimeType, body); } else { this.uploadVideoContent(null, null, thumbUrl, "image/jpeg", videoUrl, body, videoMimeType); } } /** * Upload a video message * @param thumbnailUrl the thumbnail Url * @param thumbnailMimeType the thumbnail mime type * @param videoUrl the video url * @param body the message body * @param videoMimeType the video mime type */ public void uploadVideoContent(final VideoMessage sourceVideoMessage, final MessageRow aVideoRow, final String thumbnailUrl, final String thumbnailMimeType, final String videoUrl, final String body, final String videoMimeType) { // create a tmp row VideoMessage tmpVideoMessage = sourceVideoMessage; Uri uri = null; Uri thumbUri = null; try { uri = Uri.parse(videoUrl); thumbUri = Uri.parse(thumbnailUrl); } catch (Exception e) { Log.e(LOG_TAG, "uploadVideoContent failed with " + e.getLocalizedMessage()); } // the video message is not defined if (null == tmpVideoMessage) { tmpVideoMessage = new VideoMessage(); tmpVideoMessage.url = videoUrl; tmpVideoMessage.body = body; try { Room.fillVideoInfo(getActivity(), tmpVideoMessage, uri, videoMimeType, thumbUri, thumbnailMimeType); if (null == tmpVideoMessage.body) { tmpVideoMessage.body = uri.getLastPathSegment(); } } catch (Exception e) { Log.e(LOG_TAG, "uploadVideoContent : fillVideoInfo failed " + e.getLocalizedMessage()); } } // remove any displayed MessageRow with this URL // to avoid duplicate final MessageRow videoRow = (null == aVideoRow) ? addMessageRow(tmpVideoMessage) : aVideoRow; videoRow.getEvent().mSentState = Event.SentState.SENDING; FileInputStream imageStream = null; String filename = ""; String uploadId = ""; String mimeType = ""; try { // the thumbnail has been uploaded ? if (tmpVideoMessage.isThumbnailLocalContent()) { uploadId = thumbnailUrl; imageStream = new FileInputStream(new File(thumbUri.getPath())); mimeType = thumbnailMimeType; } else { uploadId = videoUrl; imageStream = new FileInputStream(new File(uri.getPath())); filename = tmpVideoMessage.body; mimeType = videoMimeType; } } catch (Exception e) { Log.e(LOG_TAG, "uploadVideoContent : media parsing failed " + e.getLocalizedMessage()); } final boolean isContentUpload = TextUtils.equals(uploadId, videoUrl); final VideoMessage fVideoMessage = tmpVideoMessage; getSession().getMediasCache().uploadContent(imageStream, filename, mimeType, uploadId, new MXMediaUploadListener() { @Override public void onUploadStart(String uploadId) { getUiHandler().post(new Runnable() { @Override public void run() { onMessageSendingSucceeded(videoRow.getEvent()); mAdapter.notifyDataSetChanged(); } }); } @Override public void onUploadCancel(String uploadId) { getUiHandler().post(new Runnable() { @Override public void run() { onMessageSendingFailed(videoRow.getEvent()); } }); } @Override public void onUploadError(final String uploadId, final int serverResponseCode, final String serverErrorMessage) { getUiHandler().post(new Runnable() { @Override public void run() { commonMediaUploadError(serverResponseCode,serverErrorMessage, videoRow); } }); } @Override public void onUploadComplete(final String uploadId, final String contentUri) { getUiHandler().post(new Runnable() { @Override public void run() { // the video content has been uploaded if (isContentUpload) { // Build the image message VideoMessage message = fVideoMessage.deepCopy(); // replace the thumbnail and the media contents by the computed ones getMXMediasCache().saveFileMediaForUrl(contentUri, videoUrl, videoMimeType); message.url = contentUri; // update the event content with the new message info videoRow.getEvent().content = JsonUtils.toJson(message); Log.d(LOG_TAG, "Uploaded to " + contentUri); send(videoRow); } else { // ony upload the thumbnail getMXMediasCache().saveFileMediaForUrl(contentUri, thumbnailUrl, mAdapter.getMaxThumbnailWith(), mAdapter.getMaxThumbnailHeight(), thumbnailMimeType, true); fVideoMessage.info.thumbnail_url = contentUri; // upload the video uploadVideoContent(fVideoMessage, videoRow, thumbnailUrl, thumbnailMimeType, videoUrl, fVideoMessage.body, videoMimeType); } } }); } }); } /** * upload an image content. * It might be triggered from a media selection : imageUri is used to compute thumbnails. * Or, it could have been called to resend an image. * @param thumbnailUrl the thumbnail Url * @param imageUrl the image Uri * @param mediaFilename the mediaFilename * @param mimeType the image mine type */ public void uploadImageContent(final String thumbnailUrl, final String imageUrl, final String mediaFilename, final String mimeType) { // create a tmp row final ImageMessage tmpImageMessage = new ImageMessage(); tmpImageMessage.url = imageUrl; tmpImageMessage.thumbnailUrl = thumbnailUrl; tmpImageMessage.body = mediaFilename; FileInputStream imageStream = null; try { Uri uri = Uri.parse(imageUrl); Room.fillImageInfo(getActivity(), tmpImageMessage, uri, mimeType); String filename = uri.getPath(); imageStream = new FileInputStream (new File(filename)); if (null == tmpImageMessage.body) { tmpImageMessage.body = uri.getLastPathSegment(); } } catch (Exception e) { Log.e(LOG_TAG, "uploadImageContent failed with " + e.getLocalizedMessage()); } // remove any displayed MessageRow with this URL // to avoid duplicate final MessageRow imageRow = addMessageRow(tmpImageMessage); imageRow.getEvent().mSentState = Event.SentState.SENDING; getSession().getMediasCache().uploadContent(imageStream, tmpImageMessage.body, mimeType, imageUrl, new MXMediaUploadListener() { @Override public void onUploadStart(String uploadId) { getUiHandler().post(new Runnable() { @Override public void run() { onMessageSendingSucceeded(imageRow.getEvent()); mAdapter.notifyDataSetChanged(); } }); } @Override public void onUploadCancel(String uploadId) { getUiHandler().post(new Runnable() { @Override public void run() { onMessageSendingFailed(imageRow.getEvent()); } }); } @Override public void onUploadError(final String uploadId, final int serverResponseCode, final String serverErrorMessage) { getUiHandler().post(new Runnable() { @Override public void run() { commonMediaUploadError(serverResponseCode, serverErrorMessage, imageRow); } }); } @Override public void onUploadComplete(final String uploadId, final String contentUri) { getUiHandler().post(new Runnable() { @Override public void run() { // Build the image message ImageMessage message = tmpImageMessage.deepCopy(); // replace the thumbnail and the media contents by the computed ones getMXMediasCache().saveFileMediaForUrl(contentUri, thumbnailUrl, mAdapter.getMaxThumbnailWith(), mAdapter.getMaxThumbnailHeight(), "image/jpeg"); getMXMediasCache().saveFileMediaForUrl(contentUri, imageUrl, tmpImageMessage.getMimeType()); message.thumbnailUrl = null; message.url = contentUri; message.info = tmpImageMessage.info; if (TextUtils.isEmpty(message.body)) { message.body = "Image"; } // update the event content with the new message info imageRow.getEvent().content = JsonUtils.toJson(message); Log.d(LOG_TAG, "Uploaded to " + contentUri); send(imageRow); } }); } }); } /** * upload an image content. * It might be triggered from a media selection : imageUri is used to compute thumbnails. * Or, it could have been called to resend an image. * @param thumbnailUrl the thumbnail Url * @param thumbnailMimeType the thumbnail mimetype * @param geo_uri the geo_uri * @param body the message body */ public void uploadLocationContent(final String thumbnailUrl, final String thumbnailMimeType, final String geo_uri, final String body) { // create a tmp row final LocationMessage tmpLocationMessage = new LocationMessage(); tmpLocationMessage.thumbnail_url = thumbnailUrl; tmpLocationMessage.body = body; tmpLocationMessage.geo_uri = geo_uri; FileInputStream imageStream = null; try { Uri uri = Uri.parse(thumbnailUrl); Room.fillLocationInfo(getActivity(), tmpLocationMessage, uri, thumbnailMimeType); String filename = uri.getPath(); imageStream = new FileInputStream (new File(filename)); if (TextUtils.isEmpty(tmpLocationMessage.body)) { tmpLocationMessage.body = "Location"; } } catch (Exception e) { Log.e(LOG_TAG, "uploadLocationContent failed with " + e.getLocalizedMessage()); } // remove any displayed MessageRow with this URL // to avoid duplicate final MessageRow locationRow = addMessageRow(tmpLocationMessage); locationRow.getEvent().mSentState = Event.SentState.SENDING; getSession().getMediasCache().uploadContent(imageStream, tmpLocationMessage.body, thumbnailMimeType, thumbnailUrl, new MXMediaUploadListener() { @Override public void onUploadStart(String uploadId) { getUiHandler().post(new Runnable() { @Override public void run() { onMessageSendingSucceeded(locationRow.getEvent()); mAdapter.notifyDataSetChanged(); } }); } @Override public void onUploadCancel(String uploadId) { getUiHandler().post(new Runnable() { @Override public void run() { onMessageSendingFailed(locationRow.getEvent()); } }); } @Override public void onUploadError(String uploadId, final int serverResponseCode, final String serverErrorMessage) { getUiHandler().post(new Runnable() { @Override public void run() { commonMediaUploadError(serverResponseCode,serverErrorMessage, locationRow); } }); } @Override public void onUploadComplete(final String uploadId, final String contentUri) { getUiHandler().post(new Runnable() { @Override public void run() { // Build the location message LocationMessage message = tmpLocationMessage.deepCopy(); // replace the thumbnail and the media contents by the computed ones getMXMediasCache().saveFileMediaForUrl(contentUri, thumbnailUrl, mAdapter.getMaxThumbnailWith(), mAdapter.getMaxThumbnailHeight(), "image/jpeg"); message.thumbnail_url = contentUri; // update the event content with the new message info locationRow.getEvent().content = JsonUtils.toJson(message); Log.d(LOG_TAG, "Uploaded to " + contentUri); send(locationRow); } }); } }); } //============================================================================================================== // Unsent messages management //============================================================================================================== /** * Delete the unsent (undeliverable messages). */ public void deleteUnsentMessages() { Collection<Event> unsent = mSession.getDataHandler().getStore().getUndeliverableEvents(mRoom.getRoomId()); if ((null != unsent) && (unsent.size() > 0)) { IMXStore store = mSession.getDataHandler().getStore(); // reset the timestamp for (Event event : unsent) { mAdapter.removeEventById(event.eventId); store.deleteEvent(event); } // update the summary Event latestEvent = store.getLatestEvent(mRoom.getRoomId()); // if there is an oldest event, use it to set a summary if (latestEvent != null) { if (RoomSummary.isSupportedEvent(latestEvent)) { store.storeSummary(latestEvent.roomId, latestEvent, mRoom.getState(), mSession.getMyUserId()); } } store.commit(); mAdapter.notifyDataSetChanged(); } } /** * Resend the unsent messages */ public void resendUnsentMessages() { // check if the call is done in the right thread if (Looper.getMainLooper().getThread() != Thread.currentThread()) { Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { resendUnsentMessages(); } }); return; } Collection<Event> unsent = mSession.getDataHandler().getStore().getUndeliverableEvents(mRoom.getRoomId()); if ((null != unsent) && (unsent.size() > 0)) { mResendingEventsList = new ArrayList<>(unsent); // reset the timestamp for (Event event : mResendingEventsList) { event.mSentState = Event.SentState.UNSENT; } resend(mResendingEventsList.get(0)); mResendingEventsList.remove(0); } } /** * Resend an event. * @param event the event to resend. */ protected void resend(final Event event) { // sanity check // should never happen but got it in a GA issue if (null == event.eventId) { Log.e(LOG_TAG, "resend : got an event with a null eventId"); return; } // check if the call is done in the right thread if (Looper.getMainLooper().getThread() != Thread.currentThread()) { Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { resend(event); } }); return; } // update the timestamp event.originServerTs = System.currentTimeMillis(); // remove the event getSession().getDataHandler().deleteRoomEvent(event); mAdapter.removeEventById(event.eventId); mPendingRelaunchTimersByEventId.remove(event.eventId); // send it again final Message message = JsonUtils.toMessage(event.content); // resend an image ? if (message instanceof ImageMessage) { ImageMessage imageMessage = (ImageMessage)message; // media has not been uploaded if (imageMessage.isLocalContent()) { uploadImageContent(imageMessage.thumbnailUrl, imageMessage.url, imageMessage.body, imageMessage.getMimeType()); return; } } else if (message instanceof FileMessage) { FileMessage fileMessage = (FileMessage)message; // media has not been uploaded if (fileMessage.isLocalContent()) { uploadFileContent(fileMessage.url, fileMessage.getMimeType(), fileMessage.body); return; } } else if (message instanceof VideoMessage) { VideoMessage videoMessage = (VideoMessage)message; // media has not been uploaded if (videoMessage.isLocalContent() || videoMessage.isThumbnailLocalContent()) { String thumbnailUrl = null; String thumbnailMimeType = null; if (null != videoMessage.info) { thumbnailUrl = videoMessage.info.thumbnail_url; if (null != videoMessage.info.thumbnail_info) { thumbnailMimeType = videoMessage.info.thumbnail_info.mimetype; } } uploadVideoContent(videoMessage, null, thumbnailUrl, thumbnailMimeType, videoMessage.url, videoMessage.body, videoMessage.getVideoMimeType()); return; } else if (message instanceof LocationMessage) { LocationMessage locationMessage = (LocationMessage)message; // media has not been uploaded if (locationMessage.isLocalThumbnailContent()) { String thumbMimeType = null; if (null != locationMessage.thumbnail_info) { thumbMimeType = locationMessage.thumbnail_info.mimetype; } uploadLocationContent(locationMessage.thumbnail_url, thumbMimeType, locationMessage.geo_uri, locationMessage.body); return; } } } send(message); } //============================================================================================================== // UI stuff //============================================================================================================== /** * Display a spinner to warn the user that a back pagination is in progress. */ public void showLoadingBackProgress() { } /** * Dismiss the back pagination progress. */ public void hideLoadingBackProgress() { } /** * Display a spinner to warn the user that a forward pagination is in progress. */ public void showLoadingForwardProgress() { } /** * Dismiss the forward pagination progress. */ public void hideLoadingForwardProgress() { } /** * Display a spinner to warn the user that the initialization is in progress. */ public void showInitLoading() { } /** * Dismiss the initialization spinner. */ public void hideInitLoading() { } /** * Refresh the messages list. */ public void refresh() { mAdapter.notifyDataSetChanged(); } //============================================================================================================== // pagination methods //============================================================================================================== /** * Manage the request history error cases. * @param error the error object. */ private void onPaginateRequestError(final Object error) { if (null != MatrixMessageListFragment.this.getActivity()) { if (error instanceof Exception) { Log.e(LOG_TAG, "Network error: " + ((Exception) error).getMessage()); Toast.makeText(MatrixMessageListFragment.this.getActivity(), getActivity().getString(R.string.network_error), Toast.LENGTH_SHORT).show(); } else if (error instanceof MatrixError) { final MatrixError matrixError = (MatrixError) error; Log.e(LOG_TAG, "Matrix error" + " : " + matrixError.errcode + " - " + matrixError.getLocalizedMessage()); Toast.makeText(MatrixMessageListFragment.this.getActivity(), getActivity().getString(R.string.matrix_error) + " : " + matrixError.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); } hideLoadingBackProgress(); hideLoadingForwardProgress(); Log.d(LOG_TAG, "requestHistory failed " + error); mIsBackPaginating = false; } } /** * Start a forward pagination */ private void forwardPaginate() { if (mLockFwdPagination) { Log.d(LOG_TAG, "The forward pagination is locked."); return; } if ((null == mEventTimeLine) || mEventTimeLine.isLiveTimeline()) { //Log.d(LOG_TAG, "The forward pagination is not supported for the live timeline."); return; } if (mIsFwdPaginating) { Log.d(LOG_TAG, "A forward pagination is in progress, please wait."); return; } showLoadingForwardProgress(); final int countBeforeUpdate = mAdapter.getCount(); mIsFwdPaginating = mEventTimeLine.forwardPaginate(new ApiCallback<Integer>() { /** * the forward pagination is ended. */ private void onEndOfPagination(String errorMessage) { if (null != errorMessage) { Log.e(LOG_TAG, "forwardPaginate fails : " + errorMessage); } mIsFwdPaginating = false; hideLoadingForwardProgress(); } @Override public void onSuccess(Integer count) { final int firstPos = mMessageListView.getFirstVisiblePosition(); mLockBackPagination = true; // retrieve if (0 != count) { mAdapter.notifyDataSetChanged(); // trick to avoid that the list jump to the latest item. mMessageListView.setAdapter(mMessageListView.getAdapter()); // keep the first position while refreshing the list mMessageListView.setSelection(firstPos); mMessageListView.post(new Runnable() { @Override public void run() { // Scroll the list down to where it was before adding rows to the top int diff = mAdapter.getCount() - countBeforeUpdate; Log.d(LOG_TAG, "forwardPaginate ends with " + diff + " new items."); onEndOfPagination(null); mLockBackPagination = false; } }); } else { Log.d(LOG_TAG, "forwardPaginate ends : nothing to add"); onEndOfPagination(null); mLockBackPagination = false; } } @Override public void onNetworkError(Exception e) { onEndOfPagination(e.getLocalizedMessage()); } @Override public void onMatrixError(MatrixError e) { onEndOfPagination(e.getLocalizedMessage()); } @Override public void onUnexpectedError(Exception e) { onEndOfPagination(e.getLocalizedMessage()); } }); if (mIsFwdPaginating) { Log.d(LOG_TAG, "forwardPaginate starts"); showLoadingForwardProgress(); } else { hideLoadingForwardProgress(); Log.d(LOG_TAG, "forwardPaginate nothing to do"); } } /** * Set the scroll listener to mMessageListView */ private void setMessageListViewScrollListener() { // ensure that the listener is set only once // else it triggers an inifinite loop with backPaginate. if (!mIsScrollListenerSet) { mIsScrollListenerSet = true; mMessageListView.setOnScrollListener(mScrollListener); } } /** * Trigger a back pagination. * @param fillHistory true to try to fill the listview height. */ public void backPaginate(final boolean fillHistory) { if (mIsBackPaginating) { Log.d(LOG_TAG, "backPaginate is in progress : please wait"); return; } if (mIsInitialSyncing) { Log.d(LOG_TAG, "backPaginate : an initial sync is in progress"); return; } if (mLockBackPagination) { Log.d(LOG_TAG, "backPaginate : The back pagination is locked."); return; } if (!mMatrixMessagesFragment.canBackPaginate()) { Log.d(LOG_TAG, "backPaginate : cannot back paginating again"); setMessageListViewScrollListener(); return; } // in search mode, if (!TextUtils.isEmpty(mPattern)) { Log.d(LOG_TAG, "backPaginate with pattern " + mPattern); requestSearchHistory(); return; } final int countBeforeUpdate = mAdapter.getCount(); mIsBackPaginating = mMatrixMessagesFragment.backPaginate(new SimpleApiCallback<Integer>(getActivity()) { @Override public void onSuccess(final Integer count) { // Scroll the list down to where it was before adding rows to the top mMessageListView.post(new Runnable() { @Override public void run() { mLockFwdPagination = true; final int countDiff = mAdapter.getCount() - countBeforeUpdate; Log.d(LOG_TAG, "backPaginate : ends with " + countDiff + " new items (total : " + mAdapter.getCount() + ")"); // check if some messages have been added if (0 != countDiff) { mAdapter.notifyDataSetChanged(); // trick to avoid that the list jump to the latest item. mMessageListView.setAdapter(mMessageListView.getAdapter()); final int expectedPos = fillHistory ? (mAdapter.getCount() - 1) : (mMessageListView.getFirstVisiblePosition() + countDiff); Log.d(LOG_TAG, "backPaginate : jump to " + expectedPos); //private int mFirstVisibleRowY = INVALID_VIEW_Y_POS; if (fillHistory || (UNDEFINED_VIEW_Y_POS == mFirstVisibleRowY)) { // do not use count because some messages are not displayed // so we compute the new pos mMessageListView.setSelection(expectedPos); } else { mMessageListView.setSelectionFromTop(expectedPos, -mFirstVisibleRowY); } } // Test if a back pagination can be done. // countDiff == 0 is not relevant // because the server can return an empty chunk // but the start and the end tokens are not equal. // It seems often happening with the room visibility feature if (mMatrixMessagesFragment.canBackPaginate()) { Log.d(LOG_TAG, "backPaginate again"); mMessageListView.post(new Runnable() { @Override public void run() { mLockFwdPagination = false; mIsBackPaginating = false; mMessageListView.post(new Runnable() { @Override public void run() { // back paginate until getting something to display if (0 == countDiff) { Log.d(LOG_TAG, "backPaginate again because there was nothing in the current chunk"); backPaginate(fillHistory); } else if (fillHistory) { if ((mMessageListView.getVisibility() == View.VISIBLE) && mMessageListView.getFirstVisiblePosition() < 10) { Log.d(LOG_TAG, "backPaginate : fill history"); backPaginate(fillHistory); } else { Log.d(LOG_TAG, "backPaginate : history should be filled"); hideLoadingBackProgress(); mIsInitialSyncing = false; setMessageListViewScrollListener(); } } else { hideLoadingBackProgress(); } } }); } }); } else { Log.d(LOG_TAG, "no more backPaginate"); setMessageListViewScrollListener(); hideLoadingBackProgress(); mIsBackPaginating = false; mLockFwdPagination = false; } } }); } // the request will be auto restarted when a valid network will be found @Override public void onNetworkError(Exception e) { onPaginateRequestError(e); } @Override public void onMatrixError(MatrixError e) { onPaginateRequestError(e); } @Override public void onUnexpectedError(Exception e) { onPaginateRequestError(e); } }); if (mIsBackPaginating && (null != getActivity())) { Log.d(LOG_TAG, "backPaginate : starts"); showLoadingBackProgress(); } else { Log.d(LOG_TAG, "requestHistory : nothing to do"); } } /** * Cancel the catching requests. */ public void cancelCatchingRequests() { mPattern = null; if (null != mEventTimeLine) { mEventTimeLine.cancelPaginationRequest(); } mIsInitialSyncing = false; mIsBackPaginating = false; mIsFwdPaginating = false; mLockBackPagination = false; mLockFwdPagination = false; hideInitLoading(); hideLoadingBackProgress(); hideLoadingForwardProgress(); } //============================================================================================================== // MatrixMessagesFragment methods //============================================================================================================== @Override public void onEvent(final Event event, final EventTimeline.Direction direction, final RoomState roomState) { if (direction == EventTimeline.Direction.FORWARDS) { getUiHandler().post(new Runnable() { @Override public void run() { if (Event.EVENT_TYPE_REDACTION.equals(event.type)) { MessageRow messageRow = mAdapter.getMessageRow(event.getRedacts()); if (null != messageRow) { Event prunedEvent = mSession.getDataHandler().getStore().getEvent(event.getRedacts(), event.roomId); if (null == prunedEvent) { mAdapter.removeEventById(event.getRedacts()); } else { messageRow.updateEvent(prunedEvent); JsonObject content = messageRow.getEvent().getContentAsJsonObject(); boolean hasToRemoved = (null == content) || (null == content.entrySet()) || (0 == content.entrySet().size()); // test if the event is displayable // GA issue : the activity can be null if (!hasToRemoved && (null != getActivity())) { EventDisplay eventDisplay = new EventDisplay(getActivity(), prunedEvent, roomState); hasToRemoved = TextUtils.isEmpty(eventDisplay.getTextualDisplay()); } // event is removed if it has no more content. if (hasToRemoved) { mAdapter.removeEventById(prunedEvent.eventId); } } mAdapter.notifyDataSetChanged(); } } else if (Event.EVENT_TYPE_TYPING.equals(event.type)) { if (null != mRoom) { mAdapter.setTypingUsers(mRoom.getTypingUsers()); } } else { if (canAddEvent(event)) { // refresh the listView only when it is a live timeline or a search mAdapter.add(new MessageRow(event, roomState), (null == mEventTimeLine) || mEventTimeLine.isLiveTimeline()); } } } }); } else { if (canAddEvent(event)) { mAdapter.addToFront(event, roomState); } } } @Override public void onLiveEventsChunkProcessed() { // NOP } @Override public void onReceiptEvent(List<String> senderIds) { // avoid useless refresh boolean shouldRefresh = true; try { IMXStore store = mSession.getDataHandler().getStore(); int firstPos = mMessageListView.getFirstVisiblePosition(); int lastPos = mMessageListView.getLastVisiblePosition(); ArrayList<String> senders = new ArrayList<>(); ArrayList<String> eventIds = new ArrayList<>(); for (int index = firstPos; index <= lastPos; index++) { MessageRow row = mAdapter.getItem(index); senders.add(row.getEvent().getSender()); eventIds.add(row.getEvent().eventId); } shouldRefresh = false; // check if the receipt will trigger a refresh for (String sender : senderIds) { if (!TextUtils.equals(sender, mSession.getMyUserId())) { ReceiptData receipt = store.getReceipt(mRoom.getRoomId(), sender); // sanity check if (null != receipt) { // test if the event is displayed int pos = eventIds.indexOf(receipt.eventId); // if displayed if (pos >= 0) { // the sender is not displayed as a reader (makes sense...) shouldRefresh = !TextUtils.equals(senders.get(pos), sender); if (shouldRefresh) { break; } } } } } } catch (Exception e) { Log.e(LOG_TAG, "onReceiptEvent failed with " + e.getLocalizedMessage()); } if (shouldRefresh) { mAdapter.notifyDataSetChanged(); } } @Override public void onInitialMessagesLoaded() { Log.d(LOG_TAG, "onInitialMessagesLoaded"); // Jump to the bottom of the list getUiHandler().post(new Runnable() { @Override public void run() { // should never happen but reported by GA if (null == mMessageListView) { return; } hideLoadingBackProgress(); if (null == mMessageListView.getAdapter()) { mMessageListView.setAdapter(mAdapter); } if ((null == mEventTimeLine) || mEventTimeLine.isLiveTimeline()) { if (mAdapter.getCount() > 0) { // refresh the list only at the end of the sync // else the one by one message refresh gives a weird UX // The application is almost frozen during the mAdapter.notifyDataSetChanged(); if (mScrollToIndex >= 0) { mMessageListView.setSelection(mScrollToIndex); mScrollToIndex = -1; } else { mMessageListView.setSelection(mAdapter.getCount() - 1); } } // fill the page mMessageListView.post(new Runnable() { @Override public void run() { if ((mMessageListView.getVisibility() == View.VISIBLE) && mMessageListView.getFirstVisiblePosition() < 10) { Log.d(LOG_TAG, "onInitialMessagesLoaded : fill history"); backPaginate(true); } else { Log.d(LOG_TAG, "onInitialMessagesLoaded : history should be filled"); mIsInitialSyncing = false; setMessageListViewScrollListener(); } } }); } else { Log.d(LOG_TAG, "onInitialMessagesLoaded : default behaviour"); if ((0 != mAdapter.getCount()) && (mScrollToIndex > 0)) { mAdapter.notifyDataSetChanged(); mMessageListView.setSelection(mScrollToIndex); mScrollToIndex = -1; mMessageListView.post(new Runnable() { @Override public void run() { mIsInitialSyncing = false; setMessageListViewScrollListener(); } }); } else { mIsInitialSyncing = false; setMessageListViewScrollListener(); } } } }); } @Override public EventTimeline getEventTimeLine() { return mEventTimeLine; } @Override public void onTimelineInitialized() { mMessageListView.post(new Runnable() { @Override public void run() { mLockFwdPagination = false; mIsInitialSyncing = false; // search the event pos in the adapter // some events are not displayed so the added events count cannot be used. int eventPos = 0; for (; eventPos < mAdapter.getCount(); eventPos++) { if (TextUtils.equals(mAdapter.getItem(eventPos).getEvent().eventId, mEventId)) { break; } } View parentView = (View) mMessageListView.getParent(); mAdapter.notifyDataSetChanged(); mMessageListView.setAdapter(mAdapter); // center the message in the mMessageListView.setSelectionFromTop(eventPos, parentView.getHeight() / 2); } }); } @Override public RoomPreviewData getRoomPreviewData() { if (null != getActivity()) { // test if the listener has bee retrieved if (null == mRoomPreviewDataListener) { try { mRoomPreviewDataListener = (IRoomPreviewDataListener) getActivity(); } catch (ClassCastException e) { Log.e(LOG_TAG, "getRoomPreviewData failed with " + e.getLocalizedMessage()); } } if (null != mRoomPreviewDataListener) { return mRoomPreviewDataListener.getRoomPreviewData(); } } return null; } @Override public void onRoomFlush() { mAdapter.clear(); } /*** MessageAdapter listener ***/ @Override public void onRowClick(int position) { } @Override public boolean onRowLongClick(int position) { return false; } @Override public void onContentClick(int position) { } @Override public boolean onContentLongClick(int position) { return false; } @Override public void onAvatarClick(String userId) { } @Override public boolean onAvatarLongClick(String userId) { return false; } @Override public void onSenderNameClick(String userId, String displayName) { } @Override public void onMediaDownloaded(int position) { } @Override public void onReadReceiptClick(String eventId, String userId, ReceiptData receipt) { } @Override public boolean onReadReceiptLongClick(String eventId, String userId, ReceiptData receipt) { return false; } @Override public void onMoreReadReceiptClick(String eventId) { } @Override public boolean onMoreReadReceiptLongClick(String eventId) { return false; } @Override public void onURLClick(Uri uri) { if (null != uri) { Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.putExtra(Browser.EXTRA_APPLICATION_ID, getActivity().getPackageName()); getActivity().startActivity(intent); } } @Override public boolean shouldHighlightEvent(Event event) { String eventId = event.eventId; // cache the dedicated rule because it is slow to find them out Object ruleAsVoid = mBingRulesByEventId.get(eventId); if (null != ruleAsVoid) { if (ruleAsVoid instanceof BingRule) { return ((BingRule)ruleAsVoid).shouldHighlight(); } return false; } boolean res = false; BingRule rule = mSession.getDataHandler().getBingRulesManager().fulfilledBingRule(event); if (null != rule) { res = rule.shouldHighlight(); mBingRulesByEventId.put(eventId, rule); } else { mBingRulesByEventId.put(eventId, eventId); } return res; } @Override public void onMatrixUserIdClick(String userId) { } @Override public void onRoomAliasClick(String roomAlias) { } @Override public void onRoomIdClick(String roomId) { } @Override public void onMessageIdClick(String messageId) { } private int mInvalidIndexesCount = 0; @Override public void onInvalidIndexes() { mInvalidIndexesCount++; // it should happen once // else we assume that the adapter is really corrupted // It seems better to close the linked activity to avoid infinite refresh. if (1 == mInvalidIndexesCount) { mMessageListView.post(new Runnable() { @Override public void run() { mAdapter.notifyDataSetChanged(); } }); } else { mMessageListView.post(new Runnable() { @Override public void run() { if (null != getActivity()) { getActivity().finish(); } } }); } } //============================================================================================================== // search methods //============================================================================================================== /** * Cancel the current search */ protected void cancelSearch() { mPattern = null; } /** * Search the pattern on a pagination server side. */ public void requestSearchHistory() { // there is no more server message if (TextUtils.isEmpty(mNextBatch)) { mIsBackPaginating = false; return; } mIsBackPaginating = true; final int firstPos = mMessageListView.getFirstVisiblePosition(); final String fPattern = mPattern; final int countBeforeUpdate = mAdapter.getCount(); showLoadingBackProgress(); List<String> roomIds = null; if (null != mRoom) { roomIds = Arrays.asList(mRoom.getRoomId()); } ApiCallback<SearchResponse> callback = new ApiCallback<SearchResponse>() { @Override public void onSuccess(final SearchResponse searchResponse) { if (TextUtils.equals(mPattern, fPattern)) { // check that the pattern was not modified before the end of the search if (TextUtils.equals(mPattern, fPattern)) { List<SearchResult> searchResults = searchResponse.searchCategories.roomEvents.results; // is there any result to display if (0 != searchResults.size()) { mAdapter.setNotifyOnChange(false); for (SearchResult searchResult : searchResults) { MessageRow row = new MessageRow(searchResult.result, (null == mRoom) ? null : mRoom.getState()); mAdapter.insert(row, 0); } mNextBatch = searchResponse.searchCategories.roomEvents.nextBatch; // Scroll the list down to where it was before adding rows to the top getUiHandler().post(new Runnable() { @Override public void run() { final int expectedFirstPos = firstPos + (mAdapter.getCount() - countBeforeUpdate); mAdapter.notifyDataSetChanged(); // trick to avoid that the list jump to the latest item. mMessageListView.setAdapter(mMessageListView.getAdapter()); // do not use count because some messages are not displayed // so we compute the new pos mMessageListView.setSelection(expectedFirstPos); mMessageListView.post(new Runnable() { @Override public void run() { mIsBackPaginating = false; } }); } }); } else { mIsBackPaginating = false; } hideLoadingBackProgress(); } } } private void onError() { mIsBackPaginating = false; hideLoadingBackProgress(); } // the request will be auto restarted when a valid network will be found @Override public void onNetworkError(Exception e) { Log.e(LOG_TAG, "Network error: " + e.getMessage()); onError(); } @Override public void onMatrixError(MatrixError e) { Log.e(LOG_TAG, "Matrix error" + " : " + e.errcode + " - " + e.getLocalizedMessage()); onError(); } @Override public void onUnexpectedError(Exception e) { Log.e(LOG_TAG, "onUnexpectedError error" + e.getMessage()); onError(); } }; if (mIsMediaSearch) { String[] mediaTypes = {"m.image", "m.video", "m.file"}; mSession.searchMediaName(mPattern, roomIds, Arrays.asList(mediaTypes), mNextBatch, callback); } else { mSession.searchMessageText(mPattern, roomIds, mNextBatch, callback); } } /** * Manage the search response. * @param searchResponse the search response * @param onSearchResultListener the search result listener */ protected void onSearchResponse(final SearchResponse searchResponse, final OnSearchResultListener onSearchResultListener) { List<SearchResult> searchResults = searchResponse.searchCategories.roomEvents.results; ArrayList<MessageRow> messageRows = new ArrayList<>(searchResults.size()); for(SearchResult searchResult : searchResults) { RoomState roomState = null; if (null != mRoom) { roomState = mRoom.getState(); } if (null == roomState) { Room room = mSession.getDataHandler().getStore().getRoom(searchResult.result.roomId); if (null != room) { roomState = room.getState(); } } boolean isValidMessage = false; if ((null != searchResult.result) && (null != searchResult.result.content)) { JsonObject object = searchResult.result.getContentAsJsonObject(); if (null != object) { isValidMessage = (0 != object.entrySet().size()); } } if (isValidMessage) { messageRows.add(new MessageRow(searchResult.result, roomState)); } } Collections.reverse(messageRows); mAdapter.clear(); mAdapter.addAll(messageRows); mNextBatch = searchResponse.searchCategories.roomEvents.nextBatch; if (null != onSearchResultListener) { try { onSearchResultListener.onSearchSucceed(messageRows.size()); } catch (Exception e) { Log.e(LOG_TAG, "onSearchResponse failed with " + e.getLocalizedMessage()); } } } /** * Search a pattern in the messages. * @param pattern the pattern to search * @param onSearchResultListener the search callback */ public void searchPattern(final String pattern, final OnSearchResultListener onSearchResultListener) { searchPattern(pattern, false, onSearchResultListener); } /** * Search a pattern in the messages. * @param pattern the pattern to search (filename for a media message) * @param isMediaSearch true if is it is a media search. * @param onSearchResultListener the search callback */ public void searchPattern(final String pattern, boolean isMediaSearch, final OnSearchResultListener onSearchResultListener) { if (!TextUtils.equals(mPattern, pattern)) { mPattern = pattern; mIsMediaSearch = isMediaSearch; mAdapter.setSearchPattern(mPattern); // something to search if (!TextUtils.isEmpty(mPattern)) { List<String> roomIds = null; // sanity checks if (null != mRoom) { roomIds = Arrays.asList(mRoom.getRoomId()); } // ApiCallback<SearchResponse> searchCallback = new ApiCallback<SearchResponse>() { @Override public void onSuccess(final SearchResponse searchResponse) { // check that the pattern was not modified before the end of the search if (TextUtils.equals(mPattern, pattern)) { onSearchResponse(searchResponse, onSearchResultListener); } } private void onError() { if (null != onSearchResultListener) { try { onSearchResultListener.onSearchFailed(); } catch (Exception e) { Log.e(LOG_TAG, "onSearchResultListener failed with " + e.getLocalizedMessage()); } } } // the request will be auto restarted when a valid network will be found @Override public void onNetworkError(Exception e) { Log.e(LOG_TAG, "Network error: " + e.getMessage()); onError(); } @Override public void onMatrixError(MatrixError e) { Log.e(LOG_TAG, "Matrix error" + " : " + e.errcode + " - " + e.getLocalizedMessage()); onError(); } @Override public void onUnexpectedError(Exception e) { Log.e(LOG_TAG, "onUnexpectedError error" + e.getMessage()); onError(); } }; if (isMediaSearch) { String[] mediaTypes = {"m.image", "m.video", "m.file"}; mSession.searchMediaName(mPattern, roomIds, Arrays.asList(mediaTypes), null, searchCallback); } else { mSession.searchMessageText(mPattern, roomIds, null, searchCallback); } } } } }
matrix-sdk/src/main/java/org/matrix/androidsdk/fragments/MatrixMessageListFragment.java
/* * Copyright 2015 OpenMarket Ltd * * 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.matrix.androidsdk.fragments; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.media.ThumbnailUtils; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.provider.Browser; import android.provider.MediaStore; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.google.gson.JsonObject; import org.matrix.androidsdk.MXSession; import org.matrix.androidsdk.R; import org.matrix.androidsdk.adapters.MessageRow; import org.matrix.androidsdk.adapters.MessagesAdapter; import org.matrix.androidsdk.data.EventTimeline; import org.matrix.androidsdk.data.IMXStore; import org.matrix.androidsdk.data.Room; import org.matrix.androidsdk.data.RoomPreviewData; import org.matrix.androidsdk.data.RoomState; import org.matrix.androidsdk.data.RoomSummary; import org.matrix.androidsdk.db.MXMediasCache; import org.matrix.androidsdk.listeners.IMXEventListener; import org.matrix.androidsdk.listeners.MXEventListener; import org.matrix.androidsdk.listeners.MXMediaUploadListener; import org.matrix.androidsdk.rest.callback.ApiCallback; import org.matrix.androidsdk.rest.callback.SimpleApiCallback; import org.matrix.androidsdk.rest.model.Event; import org.matrix.androidsdk.rest.model.FileMessage; import org.matrix.androidsdk.rest.model.ImageMessage; import org.matrix.androidsdk.rest.model.LocationMessage; import org.matrix.androidsdk.rest.model.MatrixError; import org.matrix.androidsdk.rest.model.Message; import org.matrix.androidsdk.rest.model.ReceiptData; import org.matrix.androidsdk.rest.model.Search.SearchResponse; import org.matrix.androidsdk.rest.model.Search.SearchResult; import org.matrix.androidsdk.rest.model.User; import org.matrix.androidsdk.rest.model.VideoMessage; import org.matrix.androidsdk.rest.model.bingrules.BingRule; import org.matrix.androidsdk.util.EventDisplay; import org.matrix.androidsdk.util.JsonUtils; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Timer; import java.util.TimerTask; import retrofit.RetrofitError; /** * UI Fragment containing matrix messages for a given room. * Contains {@link MatrixMessagesFragment} as a nested fragment to do the work. */ public class MatrixMessageListFragment extends Fragment implements MatrixMessagesFragment.MatrixMessagesListener, MessagesAdapter.MessagesAdapterEventsListener { // search interface public interface OnSearchResultListener { void onSearchSucceed(int nbrMessages); void onSearchFailed(); } // room preview interface public interface IRoomPreviewDataListener { RoomPreviewData getRoomPreviewData(); } // be warned when a message sending failed or succeeded public interface IEventSendingListener { /** * A message has been successfully sent. * @param event the event */ void onMessageSendingSucceeded(Event event); /** * A message sending has failed. * @param event the event */ void onMessageSendingFailed(Event event); /** * An event has been successfully redacted by the user. * @param event the event */ void onMessageRedacted(Event event); } // scroll listener public interface IOnScrollListener { /** * The events list has been scrolled. * @param firstVisibleItem the index of the first visible cell * @param visibleItemCount the number of visible cells * @param totalItemCount the number of items in the list adaptor */ void onScroll(int firstVisibleItem, int visibleItemCount, int totalItemCount); /** * Tell if the latest event is fully displayed * @param isDisplayed true if the latest event is fully displayed */ void onLatestEventDisplay(boolean isDisplayed); } protected static final String TAG_FRAGMENT_MESSAGE_OPTIONS = "org.matrix.androidsdk.RoomActivity.TAG_FRAGMENT_MESSAGE_OPTIONS"; protected static final String TAG_FRAGMENT_MESSAGE_DETAILS = "org.matrix.androidsdk.RoomActivity.TAG_FRAGMENT_MESSAGE_DETAILS"; // fragment parameters public static final String ARG_LAYOUT_ID = "MatrixMessageListFragment.ARG_LAYOUT_ID"; public static final String ARG_MATRIX_ID = "MatrixMessageListFragment.ARG_MATRIX_ID"; public static final String ARG_ROOM_ID = "MatrixMessageListFragment.ARG_ROOM_ID"; public static final String ARG_EVENT_ID = "MatrixMessageListFragment.ARG_EVENT_ID"; public static final String ARG_PREVIEW_MODE_ID = "MatrixMessageListFragment.ARG_PREVIEW_MODE_ID"; // default preview mode public static final String PREVIEW_MODE_READ_ONLY = "PREVIEW_MODE_READ_ONLY"; private static final String LOG_TAG = "MatrixMsgsListFrag"; private static final int UNDEFINED_VIEW_Y_POS = -12345678; public static MatrixMessageListFragment newInstance(String matrixId, String roomId, int layoutResId) { MatrixMessageListFragment f = new MatrixMessageListFragment(); Bundle args = new Bundle(); args.putString(ARG_ROOM_ID, roomId); args.putInt(ARG_LAYOUT_ID, layoutResId); args.putString(ARG_MATRIX_ID, matrixId); return f; } private MatrixMessagesFragment mMatrixMessagesFragment; protected MessagesAdapter mAdapter; public ListView mMessageListView; protected Handler mUiHandler; protected MXSession mSession; protected String mMatrixId; protected Room mRoom; protected String mPattern = null; protected boolean mIsMediaSearch; protected String mNextBatch = null; private boolean mDisplayAllEvents = true; public boolean mCheckSlideToHide = false; private boolean mIsScrollListenerSet; // timeline management protected boolean mIsLive = true; // by default the protected EventTimeline mEventTimeLine; protected String mEventId; // pagination statuses protected boolean mIsInitialSyncing = true; protected boolean mIsBackPaginating = false; protected boolean mIsFwdPaginating = false; // lock the pagination while refreshing the list view to avoid having twice or thrice refreshes sequence. private boolean mLockBackPagination = false; private boolean mLockFwdPagination = true; protected ArrayList<Event> mResendingEventsList; private final HashMap<String, Timer> mPendingRelaunchTimersByEventId = new HashMap<>(); private final HashMap<String, Object> mBingRulesByEventId = new HashMap<>(); // scroll to to the dedicated index when the device has been rotated private int mFirstVisibleRow = -1; // scroll to the index when loaded private int mScrollToIndex = -1; // y pos of the first visible row private int mFirstVisibleRowY = UNDEFINED_VIEW_Y_POS; // used to retrieve the preview data protected IRoomPreviewDataListener mRoomPreviewDataListener; // be warned that an event sending has failed. protected IEventSendingListener mEventSendingListener; // listen when the events list is scrolled. protected IOnScrollListener mActivityOnScrollListener; public MXMediasCache getMXMediasCache() { return null; } public MXSession getSession(String matrixId) { return null; } public MXSession getSession() { // if the session has not been set if (null == mSession) { // find it out mSession = getSession(mMatrixId); } return mSession; } /** * @return an UI handler */ private Handler getUiHandler() { if (null == mUiHandler) { mUiHandler = new Handler(Looper.getMainLooper()); } return mUiHandler; } private final IMXEventListener mEventsListener = new MXEventListener() { @Override public void onPresenceUpdate(Event event, final User user) { // Someone's presence has changed, reprocess the whole list getUiHandler().post(new Runnable() { @Override public void run() { // check first if the userID has sent some messages in the room history boolean refresh = mAdapter.isDisplayedUser(user.user_id); if (refresh) { // check, if the avatar is currently displayed // The Math.min is required because the adapter and mMessageListView could be unsynchronized. // ensure there is no IndexOfOutBound exception. int firstVisibleRow = Math.min(mMessageListView.getFirstVisiblePosition(), mAdapter.getCount()); int lastVisibleRow = Math.min(mMessageListView.getLastVisiblePosition(), mAdapter.getCount()); refresh = false; for (int i = firstVisibleRow; i <= lastVisibleRow; i++) { MessageRow row = mAdapter.getItem(i); refresh |= TextUtils.equals(user.user_id, row.getEvent().getSender()); } } if (refresh) { mAdapter.notifyDataSetChanged(); } } }); } @Override public void onBingRulesUpdate() { mBingRulesByEventId.clear(); } }; /** * Customize the scrolls behaviour. * -> scroll over the top triggers a back pagination * -> scroll over the bottom triggers a forward pagination */ protected final AbsListView.OnScrollListener mScrollListener = new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mCheckSlideToHide = (scrollState == SCROLL_STATE_TOUCH_SCROLL); //check only when the user scrolls the content if (scrollState == SCROLL_STATE_TOUCH_SCROLL) { int firstVisibleRow = mMessageListView.getFirstVisiblePosition(); int lastVisibleRow = mMessageListView.getLastVisiblePosition(); int count = mMessageListView.getCount(); if ((lastVisibleRow + 10) >= count) { Log.d(LOG_TAG, "onScrollStateChanged - forwardPaginate"); forwardPaginate(); } else if (firstVisibleRow < 2) { Log.d(LOG_TAG, "onScrollStateChanged - request history"); backPaginate(false); } } } /** * Warns that the list has been scrolled. * @param view the list view * @param firstVisibleItem the first visible indew * @param visibleItemCount the number of visible items * @param totalItemCount the total number of items */ private void manageScrollListener(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (null != mActivityOnScrollListener) { try { mActivityOnScrollListener.onScroll(firstVisibleItem, visibleItemCount, totalItemCount); } catch (Exception e) { Log.e(LOG_TAG, "## manageScrollListener : onScroll failed " + e.getMessage()); } boolean isLatestEventDisplayed; // test if the latest message is not displayed if ((firstVisibleItem + visibleItemCount) < totalItemCount) { // the latest event is not displayed isLatestEventDisplayed = false; } else { AbsListView absListView = view; View childview = absListView.getChildAt(visibleItemCount-1); // test if the bottom of the latest item is equals to the list height isLatestEventDisplayed = (null != childview) && ((childview.getTop() + childview.getHeight()) <= view.getHeight()); } try { mActivityOnScrollListener.onLatestEventDisplay(isLatestEventDisplayed); } catch (Exception e) { Log.e(LOG_TAG, "## manageScrollListener : onLatestEventDisplay failed " + e.getMessage()); } } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // store the current Y pos to jump to the right pos when backpaginating mFirstVisibleRowY = UNDEFINED_VIEW_Y_POS; View v = mMessageListView.getChildAt(firstVisibleItem); if (null != v) { mFirstVisibleRowY = v.getTop(); } if ((firstVisibleItem < 2) && (visibleItemCount != totalItemCount) && (0 != visibleItemCount)) { // Log.d(LOG_TAG, "onScroll - backPaginate"); backPaginate(false); } else if ((firstVisibleItem + visibleItemCount + 10) >= totalItemCount) { // Log.d(LOG_TAG, "onScroll - forwardPaginate"); forwardPaginate(); } manageScrollListener(view, firstVisibleItem, visibleItemCount, totalItemCount); } }; @Override public void onCreate(Bundle savedInstanceState) { Log.d(LOG_TAG, "onCreate"); super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(LOG_TAG, "onCreateView"); super.onCreateView(inflater, container, savedInstanceState); Bundle args = getArguments(); // for dispatching data to add to the adapter we need to be on the main thread mUiHandler = new Handler(Looper.getMainLooper()); mMatrixId = args.getString(ARG_MATRIX_ID); mSession = getSession(mMatrixId); if (null == mSession) { throw new RuntimeException("Must have valid default MXSession."); } if (null == getMXMediasCache()) { throw new RuntimeException("Must have valid default MediasCache."); } String roomId = args.getString(ARG_ROOM_ID); View v = inflater.inflate(args.getInt(ARG_LAYOUT_ID), container, false); mMessageListView = ((ListView)v.findViewById(R.id.listView_messages)); mIsScrollListenerSet = false; if (mAdapter == null) { // only init the adapter if it wasn't before, so we can preserve messages/position. mAdapter = createMessagesAdapter(); if (null == getMXMediasCache()) { throw new RuntimeException("Must have valid default MessagesAdapter."); } } else if(null != savedInstanceState) { mFirstVisibleRow = savedInstanceState.getInt("FIRST_VISIBLE_ROW", -1); } mAdapter.setIsPreviewMode(false); if (null == mEventTimeLine) { mEventId = args.getString(ARG_EVENT_ID); // the fragment displays the history around a message if (!TextUtils.isEmpty(mEventId)) { mEventTimeLine = new EventTimeline(mSession.getDataHandler(), roomId, mEventId); mRoom = mEventTimeLine.getRoom(); } // display a room preview else if (null != args.getString(ARG_PREVIEW_MODE_ID)) { mAdapter.setIsPreviewMode(true); mEventTimeLine = new EventTimeline(mSession.getDataHandler(), roomId); mRoom = mEventTimeLine.getRoom(); } // standard case else { if (!TextUtils.isEmpty(roomId)) { mRoom = mSession.getDataHandler().getRoom(roomId); mEventTimeLine = mRoom.getLiveTimeLine(); } } } // GA reported some weird room content // so ensure that the room fields are properly initialized mSession.getDataHandler().checkRoom(mRoom); // sanity check if (null != mRoom) { mAdapter.setTypingUsers(mRoom.getTypingUsers()); } mMessageListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { MatrixMessageListFragment.this.onRowClick(position); } }); mMessageListView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { onListTouch(event); return false; } }); mAdapter.setMessagesAdapterEventsListener(this); mDisplayAllEvents = isDisplayAllEvents(); return v; } /** * Called when a fragment is first attached to its activity. * {@link #onCreate(Bundle)} will be called after this. * * @param aHostActivity parent activity */ @Override public void onAttach(Activity aHostActivity) { super.onAttach(aHostActivity); try { mEventSendingListener = (IEventSendingListener) aHostActivity; } catch(ClassCastException e) { // if host activity does not provide the implementation, just ignore it Log.w(LOG_TAG,"## onAttach(): host activity does not implement IEventSendingListener " + aHostActivity); } try { mActivityOnScrollListener = (IOnScrollListener) aHostActivity; } catch(ClassCastException e) { // if host activity does not provide the implementation, just ignore it Log.w(LOG_TAG,"## onAttach(): host activity does not implement IOnScrollListener " + aHostActivity); } } /** * Called when the fragment is no longer attached to its activity. This * is called after {@link #onDestroy()}. */ @Override public void onDetach() { super.onDetach(); mEventSendingListener = null; mActivityOnScrollListener = null; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (null != mMessageListView) { int selected = mMessageListView.getFirstVisiblePosition(); // ListView always returns the previous index while filling from bottom if (selected > 0) { selected++; } outState.putInt("FIRST_VISIBLE_ROW", selected); } } /** * Called when the fragment is no longer in use. This is called * after {@link #onStop()} and before {@link #onDetach()}. */ @Override public void onDestroy() { super.onDestroy(); // remove listeners to prevent memory leak if(null != mMatrixMessagesFragment) { mMatrixMessagesFragment.setMatrixMessagesListener(null); } if(null != mAdapter) { mAdapter.setMessagesAdapterEventsListener(null); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Bundle args = getArguments(); FragmentManager fm = getActivity().getSupportFragmentManager(); mMatrixMessagesFragment = (MatrixMessagesFragment) fm.findFragmentByTag(getMatrixMessagesFragmentTag()); if (mMatrixMessagesFragment == null) { Log.d(LOG_TAG, "onActivityCreated create"); // this fragment controls all the logic for handling messages / API calls mMatrixMessagesFragment = createMessagesFragmentInstance(args.getString(ARG_ROOM_ID)); fm.beginTransaction().add(mMatrixMessagesFragment, getMatrixMessagesFragmentTag()).commit(); } else { Log.d(LOG_TAG, "onActivityCreated - reuse"); // Reset the listener because this is not done when the system restores the fragment (newInstance is not called) mMatrixMessagesFragment.setMatrixMessagesListener(this); } mMatrixMessagesFragment.mKeepRoomHistory = (-1 != mFirstVisibleRow); } @Override public void onPause() { super.onPause(); // mBingRulesByEventId.clear(); // check if the session has not been logged out if (mSession.isAlive() && (null != mRoom) && mIsLive) { mRoom.removeEventListener(mEventsListener); } cancelCatchingRequests(); } @Override public void onResume() { super.onResume(); // sanity check if ((null != mRoom) && mIsLive) { Room room = mSession.getDataHandler().getRoom(mRoom.getRoomId(), false); if (null != room) { room.addEventListener(mEventsListener); } else { Log.e(LOG_TAG, "the room " + mRoom.getRoomId() + " does not exist anymore"); } } } //============================================================================================================== // general methods //============================================================================================================== /** * Create the messageFragment. * Should be inherited. * @param roomId the roomID * @return the MatrixMessagesFragment */ public MatrixMessagesFragment createMessagesFragmentInstance(String roomId) { return MatrixMessagesFragment.newInstance(getSession(), roomId, this); } /** * @return the fragment tag to use to restore the matrix messages fragment */ protected String getMatrixMessagesFragmentTag() { return "org.matrix.androidsdk.RoomActivity.TAG_FRAGMENT_MATRIX_MESSAGES"; } /** * Create the messages adapter. * This method must be overriden to provide a valid creation * @return the messages adapter. */ public MessagesAdapter createMessagesAdapter() { return null; } /** * The user scrolls the list. * Apply an expected behaviour * @param event the scroll event */ public void onListTouch(MotionEvent event) { } /** * Scroll the listview to a dedicated index when the list is loaded. * @param index the index */ public void scrollToIndexWhenLoaded(int index) { mScrollToIndex = index; } /** * return true to display all the events. * else the unknown events will be hidden. */ public boolean isDisplayAllEvents() { return true; } /** * @return the max thumbnail width */ public int getMaxThumbnailWith() { return mAdapter.getMaxThumbnailWith(); } /** * @return the max thumbnail height */ public int getMaxThumbnailHeight() { return mAdapter.getMaxThumbnailHeight(); } /** * Notify the fragment that some bing rules could have been updated. */ public void onBingRulesUpdate() { mAdapter.onBingRulesUpdate(); } /** * Scroll the listView to the last item. * @param delayMs the delay before jumping to the latest event. */ public void scrollToBottom(int delayMs) { mMessageListView.postDelayed(new Runnable() { @Override public void run() { mMessageListView.setSelection(mAdapter.getCount() - 1); } }, Math.max(delayMs, 0)); } /** * Scroll the listview to the last item. */ public void scrollToBottom() { scrollToBottom(300); } /** * Provides the event for a dedicated row. * @param row the row * @return the event */ public Event getEvent(int row) { Event event = null; if (mAdapter.getCount() > row) { event = mAdapter.getItem(row).getEvent(); } return event; } // create a dummy message row for the message // It is added to the Adapter // return the created Message private MessageRow addMessageRow(Message message) { // a message row can only be added if there is a defined room if (null != mRoom) { Event event = new Event(message, mSession.getCredentials().userId, mRoom.getRoomId()); mRoom.storeOutgoingEvent(event); MessageRow messageRow = new MessageRow(event, mRoom.getState()); mAdapter.add(messageRow); scrollToBottom(); Log.d(LOG_TAG, "AddMessage Row : commit"); getSession().getDataHandler().getStore().commit(); return messageRow; } else { return null; } } /** * Redact an event from its event id. * @param eventId the event id. */ protected void redactEvent(String eventId) { // Do nothing on success, the event will be hidden when the redaction event comes down the event stream mMatrixMessagesFragment.redact(eventId, new ApiCallback<Event>() { @Override public void onSuccess(Event redactedEvent) { // create a dummy redacted event to manage the redaction. // some redated events are not removed from the history but they are pruned. Event redacterEvent = new Event(); redacterEvent.roomId = redactedEvent.roomId; redacterEvent.redacts = redactedEvent.eventId; redacterEvent.type = Event.EVENT_TYPE_REDACTION; onEvent(redacterEvent, EventTimeline.Direction.FORWARDS, mRoom.getLiveState()); if (null != mEventSendingListener) { try { mEventSendingListener.onMessageRedacted(redactedEvent); } catch (Exception e) { Log.e(LOG_TAG, "redactEvent fails : " + e.getMessage()); } } } private void onError() { if (null != getActivity()) { Toast.makeText(getActivity(), getActivity().getString(R.string.could_not_redact), Toast.LENGTH_SHORT).show(); } } @Override public void onNetworkError(Exception e) { onError(); } @Override public void onMatrixError(MatrixError e) { onError(); } @Override public void onUnexpectedError(Exception e) { onError(); } }); } /** * Tells if an event is supported by the fragment. * @param event the event to test * @return true it is supported. */ private boolean canAddEvent(Event event) { String type = event.type; return mDisplayAllEvents || Event.EVENT_TYPE_MESSAGE.equals(type) || Event.EVENT_TYPE_MESSAGE_ENCRYPTED.equals(type)|| Event.EVENT_TYPE_STATE_ROOM_NAME.equals(type) || Event.EVENT_TYPE_STATE_ROOM_TOPIC.equals(type) || Event.EVENT_TYPE_STATE_ROOM_MEMBER.equals(type) || Event.EVENT_TYPE_STATE_ROOM_THIRD_PARTY_INVITE.equals(type) || Event.EVENT_TYPE_STATE_HISTORY_VISIBILITY.equals(type) || (event.isCallEvent() && (!Event.EVENT_TYPE_CALL_CANDIDATES.equals(type))) ; } //============================================================================================================== // Messages sending method. //============================================================================================================== /** * Warns that a message sending has failed. * @param event the event */ private void onMessageSendingFailed(Event event) { if (null != mEventSendingListener) { try { mEventSendingListener.onMessageSendingFailed(event); } catch (Exception e) { Log.e(LOG_TAG, "onMessageSendingFailed failed " + e.getLocalizedMessage()); } } } /** * Warns that a message sending succeeds. * @param event the events */ private void onMessageSendingSucceeded(Event event) { if (null != mEventSendingListener) { try { mEventSendingListener.onMessageSendingSucceeded(event); } catch (Exception e) { Log.e(LOG_TAG, "onMessageSendingSucceeded failed " + e.getLocalizedMessage()); } } } /** * Send a messsage in the room. * @param message the message to send. */ private void send(final Message message) { send(addMessageRow(message)); } /** * Send a message row in the dedicated room. * @param messageRow the message row to send. */ private void send(final MessageRow messageRow) { // add sanity check if (null == messageRow) { return; } final Event event = messageRow.getEvent(); if (!event.isUndeliverable()) { final String prevEventId = event.eventId; mMatrixMessagesFragment.sendEvent(event, new ApiCallback<Void>() { @Override public void onSuccess(Void info) { onMessageSendingSucceeded(event); mAdapter.updateEventById(event, prevEventId); // pending resending ? if ((null != mResendingEventsList) && (mResendingEventsList.size() > 0)) { resend(mResendingEventsList.get(0)); mResendingEventsList.remove(0); } } private void commonFailure(final Event event) { if (null != MatrixMessageListFragment.this.getActivity()) { // display the error message only if the message cannot be resent if ((null != event.unsentException) && (event.isUndeliverable())) { if ((event.unsentException instanceof RetrofitError) && ((RetrofitError) event.unsentException).isNetworkError()) { Toast.makeText(getActivity(), getActivity().getString(R.string.unable_to_send_message) + " : " + getActivity().getString(R.string.network_error), Toast.LENGTH_LONG).show(); } else { Toast.makeText(getActivity(), getActivity().getString(R.string.unable_to_send_message) + " : " + event.unsentException.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } } else if (null != event.unsentMatrixError) { Toast.makeText(getActivity(), getActivity().getString(R.string.unable_to_send_message) + " : " + event.unsentMatrixError.getLocalizedMessage() + ".", Toast.LENGTH_LONG).show(); } mAdapter.notifyDataSetChanged(); onMessageSendingFailed(event); } } @Override public void onNetworkError(Exception e) { commonFailure(event); } @Override public void onMatrixError(MatrixError e) { commonFailure(event); } @Override public void onUnexpectedError(Exception e) { commonFailure(event); } }); } } /** * Send a text message. * @param body the text message to send. */ public void sendTextMessage(String body) { sendMessage(Message.MSGTYPE_TEXT, body, null, null); } /** * Send a formatted text message. * @param body the unformatted text message * @param formattedBody the formatted text message (optional) * @param format the format */ public void sendTextMessage(String body, String formattedBody, String format) { sendMessage(Message.MSGTYPE_TEXT, body, formattedBody, format); } /** * Send a message of type msgType with a formatted body * @param msgType the message type * @param body the unformatted text message * @param formattedBody the formatted text message (optional) * @param format the format */ private void sendMessage(String msgType, String body, String formattedBody, String format) { Message message = new Message(); message.msgtype = msgType; message.body = body; if (null != formattedBody) { // assume that the formatted body use a custom html format message.format = format; message.formatted_body = formattedBody; } send(message); } /** * Send an emote * @param emote the emote * @param formattedEmote the formatted text message (optional) * @param format the format */ public void sendEmote(String emote, String formattedEmote, String format) { sendMessage(Message.MSGTYPE_EMOTE, emote, formattedEmote, format); } /** * The media upload fails. * @param serverResponseCode the response code. * @param serverErrorMessage the error message. * @param messageRow the messageRow */ private void commonMediaUploadError(int serverResponseCode, final String serverErrorMessage, final MessageRow messageRow) { // warn the user that the media upload fails if (serverResponseCode == 500) { Timer relaunchTimer = new Timer(); mPendingRelaunchTimersByEventId.put(messageRow.getEvent().eventId, relaunchTimer); relaunchTimer.schedule(new TimerTask() { @Override public void run() { if (mPendingRelaunchTimersByEventId.containsKey(messageRow.getEvent().eventId)) { mPendingRelaunchTimersByEventId.remove(messageRow.getEvent().eventId); Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { resend(messageRow.getEvent()); } }); } } }, 1000); } else { messageRow.getEvent().mSentState = Event.SentState.UNDELIVERABLE; onMessageSendingFailed(messageRow.getEvent()); if (null != getActivity()) { Toast.makeText(getActivity(), (null != serverErrorMessage) ? serverErrorMessage : getString(R.string.message_failed_to_upload), Toast.LENGTH_LONG).show(); } } } /** * Upload a file content * @param mediaUrl the media URL * @param mimeType the media mime type * @param mediaFilename the media filename */ public void uploadFileContent(final String mediaUrl, final String mimeType, final String mediaFilename) { // create a tmp row final FileMessage tmpFileMessage = new FileMessage(); tmpFileMessage.url = mediaUrl; tmpFileMessage.body = mediaFilename; FileInputStream fileStream = null; try { Uri uri = Uri.parse(mediaUrl); Room.fillFileInfo(getActivity(), tmpFileMessage, uri, mimeType); String filename = uri.getPath(); fileStream = new FileInputStream (new File(filename)); if (null == tmpFileMessage.body) { tmpFileMessage.body = uri.getLastPathSegment(); } } catch (Exception e) { Log.e(LOG_TAG, "uploadFileContent failed with " + e.getLocalizedMessage()); } // remove any displayed MessageRow with this URL // to avoid duplicate final MessageRow messageRow = addMessageRow(tmpFileMessage); messageRow.getEvent().mSentState = Event.SentState.SENDING; getSession().getMediasCache().uploadContent(fileStream, tmpFileMessage.body, mimeType, mediaUrl, new MXMediaUploadListener() { @Override public void onUploadStart(String uploadId) { getUiHandler().post(new Runnable() { @Override public void run() { onMessageSendingSucceeded(messageRow.getEvent()); // display the pie chart. mAdapter.notifyDataSetChanged(); } }); } @Override public void onUploadCancel(String uploadId) { getUiHandler().post(new Runnable() { @Override public void run() { onMessageSendingFailed(messageRow.getEvent()); } }); } @Override public void onUploadError(final String uploadId, final int serverResponseCode, final String serverErrorMessage) { getUiHandler().post(new Runnable() { @Override public void run() { commonMediaUploadError(serverResponseCode,serverErrorMessage, messageRow); } }); } @Override public void onUploadComplete(final String uploadId, final String contentUri) { getUiHandler().post(new Runnable() { @Override public void run() { // Build the image message FileMessage message = tmpFileMessage.deepCopy(); // replace the thumbnail and the media contents by the computed ones getMXMediasCache().saveFileMediaForUrl(contentUri, mediaUrl, tmpFileMessage.getMimeType()); message.url = contentUri; // update the event content with the new message info messageRow.getEvent().content = JsonUtils.toJson(message); Log.d(LOG_TAG, "Uploaded to " + contentUri); send(messageRow); } }); } }); } /** * Compute the video thumbnail * @param videoUrl the video url * @return the video thumbnail */ public String getVideoThumbnailUrl(final String videoUrl) { String thumbUrl = null; try { Uri uri = Uri.parse(videoUrl); Bitmap thumb = ThumbnailUtils.createVideoThumbnail(uri.getPath(), MediaStore.Images.Thumbnails.MINI_KIND); thumbUrl = getMXMediasCache().saveBitmap(thumb, null); } catch (Exception e) { Log.e(LOG_TAG, "getVideoThumbailUrl failed with " + e.getLocalizedMessage()); } return thumbUrl; } /** * Upload a video message * The video thumbnail will be computed * @param videoUrl the video url * @param body the message body * @param videoMimeType the video mime type */ public void uploadVideoContent(final String videoUrl, final String body, final String videoMimeType) { uploadVideoContent(videoUrl, getVideoThumbnailUrl(videoUrl), body, videoMimeType); } /** * Upload a video message * The video thumbnail will be computed * @param videoUrl the video url * @param thumbUrl the thumbnail Url * @param body the message body * @param videoMimeType the video mime type */ public void uploadVideoContent(final String videoUrl, final String thumbUrl, final String body, final String videoMimeType) { // if the video thumbnail cannot be retrieved // send it as a file if (null == thumbUrl) { this.uploadFileContent(videoUrl, videoMimeType, body); } else { this.uploadVideoContent(null, null, thumbUrl, "image/jpeg", videoUrl, body, videoMimeType); } } /** * Upload a video message * @param thumbnailUrl the thumbnail Url * @param thumbnailMimeType the thumbnail mime type * @param videoUrl the video url * @param body the message body * @param videoMimeType the video mime type */ public void uploadVideoContent(final VideoMessage sourceVideoMessage, final MessageRow aVideoRow, final String thumbnailUrl, final String thumbnailMimeType, final String videoUrl, final String body, final String videoMimeType) { // create a tmp row VideoMessage tmpVideoMessage = sourceVideoMessage; Uri uri = null; Uri thumbUri = null; try { uri = Uri.parse(videoUrl); thumbUri = Uri.parse(thumbnailUrl); } catch (Exception e) { Log.e(LOG_TAG, "uploadVideoContent failed with " + e.getLocalizedMessage()); } // the video message is not defined if (null == tmpVideoMessage) { tmpVideoMessage = new VideoMessage(); tmpVideoMessage.url = videoUrl; tmpVideoMessage.body = body; try { Room.fillVideoInfo(getActivity(), tmpVideoMessage, uri, videoMimeType, thumbUri, thumbnailMimeType); if (null == tmpVideoMessage.body) { tmpVideoMessage.body = uri.getLastPathSegment(); } } catch (Exception e) { Log.e(LOG_TAG, "uploadVideoContent : fillVideoInfo failed " + e.getLocalizedMessage()); } } // remove any displayed MessageRow with this URL // to avoid duplicate final MessageRow videoRow = (null == aVideoRow) ? addMessageRow(tmpVideoMessage) : aVideoRow; videoRow.getEvent().mSentState = Event.SentState.SENDING; FileInputStream imageStream = null; String filename = ""; String uploadId = ""; String mimeType = ""; try { // the thumbnail has been uploaded ? if (tmpVideoMessage.isThumbnailLocalContent()) { uploadId = thumbnailUrl; imageStream = new FileInputStream(new File(thumbUri.getPath())); mimeType = thumbnailMimeType; } else { uploadId = videoUrl; imageStream = new FileInputStream(new File(uri.getPath())); filename = tmpVideoMessage.body; mimeType = videoMimeType; } } catch (Exception e) { Log.e(LOG_TAG, "uploadVideoContent : media parsing failed " + e.getLocalizedMessage()); } final boolean isContentUpload = TextUtils.equals(uploadId, videoUrl); final VideoMessage fVideoMessage = tmpVideoMessage; getSession().getMediasCache().uploadContent(imageStream, filename, mimeType, uploadId, new MXMediaUploadListener() { @Override public void onUploadStart(String uploadId) { getUiHandler().post(new Runnable() { @Override public void run() { onMessageSendingSucceeded(videoRow.getEvent()); mAdapter.notifyDataSetChanged(); } }); } @Override public void onUploadCancel(String uploadId) { getUiHandler().post(new Runnable() { @Override public void run() { onMessageSendingFailed(videoRow.getEvent()); } }); } @Override public void onUploadError(final String uploadId, final int serverResponseCode, final String serverErrorMessage) { getUiHandler().post(new Runnable() { @Override public void run() { commonMediaUploadError(serverResponseCode,serverErrorMessage, videoRow); } }); } @Override public void onUploadComplete(final String uploadId, final String contentUri) { getUiHandler().post(new Runnable() { @Override public void run() { // the video content has been uploaded if (isContentUpload) { // Build the image message VideoMessage message = fVideoMessage.deepCopy(); // replace the thumbnail and the media contents by the computed ones getMXMediasCache().saveFileMediaForUrl(contentUri, videoUrl, videoMimeType); message.url = contentUri; // update the event content with the new message info videoRow.getEvent().content = JsonUtils.toJson(message); Log.d(LOG_TAG, "Uploaded to " + contentUri); send(videoRow); } else { // ony upload the thumbnail getMXMediasCache().saveFileMediaForUrl(contentUri, thumbnailUrl, mAdapter.getMaxThumbnailWith(), mAdapter.getMaxThumbnailHeight(), thumbnailMimeType, true); fVideoMessage.info.thumbnail_url = contentUri; // upload the video uploadVideoContent(fVideoMessage, videoRow, thumbnailUrl, thumbnailMimeType, videoUrl, fVideoMessage.body, videoMimeType); } } }); } }); } /** * upload an image content. * It might be triggered from a media selection : imageUri is used to compute thumbnails. * Or, it could have been called to resend an image. * @param thumbnailUrl the thumbnail Url * @param imageUrl the image Uri * @param mediaFilename the mediaFilename * @param mimeType the image mine type */ public void uploadImageContent(final String thumbnailUrl, final String imageUrl, final String mediaFilename, final String mimeType) { // create a tmp row final ImageMessage tmpImageMessage = new ImageMessage(); tmpImageMessage.url = imageUrl; tmpImageMessage.thumbnailUrl = thumbnailUrl; tmpImageMessage.body = mediaFilename; FileInputStream imageStream = null; try { Uri uri = Uri.parse(imageUrl); Room.fillImageInfo(getActivity(), tmpImageMessage, uri, mimeType); String filename = uri.getPath(); imageStream = new FileInputStream (new File(filename)); if (null == tmpImageMessage.body) { tmpImageMessage.body = uri.getLastPathSegment(); } } catch (Exception e) { Log.e(LOG_TAG, "uploadImageContent failed with " + e.getLocalizedMessage()); } // remove any displayed MessageRow with this URL // to avoid duplicate final MessageRow imageRow = addMessageRow(tmpImageMessage); imageRow.getEvent().mSentState = Event.SentState.SENDING; getSession().getMediasCache().uploadContent(imageStream, tmpImageMessage.body, mimeType, imageUrl, new MXMediaUploadListener() { @Override public void onUploadStart(String uploadId) { getUiHandler().post(new Runnable() { @Override public void run() { onMessageSendingSucceeded(imageRow.getEvent()); mAdapter.notifyDataSetChanged(); } }); } @Override public void onUploadCancel(String uploadId) { getUiHandler().post(new Runnable() { @Override public void run() { onMessageSendingFailed(imageRow.getEvent()); } }); } @Override public void onUploadError(final String uploadId, final int serverResponseCode, final String serverErrorMessage) { getUiHandler().post(new Runnable() { @Override public void run() { commonMediaUploadError(serverResponseCode, serverErrorMessage, imageRow); } }); } @Override public void onUploadComplete(final String uploadId, final String contentUri) { getUiHandler().post(new Runnable() { @Override public void run() { // Build the image message ImageMessage message = tmpImageMessage.deepCopy(); // replace the thumbnail and the media contents by the computed ones getMXMediasCache().saveFileMediaForUrl(contentUri, thumbnailUrl, mAdapter.getMaxThumbnailWith(), mAdapter.getMaxThumbnailHeight(), "image/jpeg"); getMXMediasCache().saveFileMediaForUrl(contentUri, imageUrl, tmpImageMessage.getMimeType()); message.thumbnailUrl = null; message.url = contentUri; message.info = tmpImageMessage.info; if (TextUtils.isEmpty(message.body)) { message.body = "Image"; } // update the event content with the new message info imageRow.getEvent().content = JsonUtils.toJson(message); Log.d(LOG_TAG, "Uploaded to " + contentUri); send(imageRow); } }); } }); } /** * upload an image content. * It might be triggered from a media selection : imageUri is used to compute thumbnails. * Or, it could have been called to resend an image. * @param thumbnailUrl the thumbnail Url * @param thumbnailMimeType the thumbnail mimetype * @param geo_uri the geo_uri * @param body the message body */ public void uploadLocationContent(final String thumbnailUrl, final String thumbnailMimeType, final String geo_uri, final String body) { // create a tmp row final LocationMessage tmpLocationMessage = new LocationMessage(); tmpLocationMessage.thumbnail_url = thumbnailUrl; tmpLocationMessage.body = body; tmpLocationMessage.geo_uri = geo_uri; FileInputStream imageStream = null; try { Uri uri = Uri.parse(thumbnailUrl); Room.fillLocationInfo(getActivity(), tmpLocationMessage, uri, thumbnailMimeType); String filename = uri.getPath(); imageStream = new FileInputStream (new File(filename)); if (TextUtils.isEmpty(tmpLocationMessage.body)) { tmpLocationMessage.body = "Location"; } } catch (Exception e) { Log.e(LOG_TAG, "uploadLocationContent failed with " + e.getLocalizedMessage()); } // remove any displayed MessageRow with this URL // to avoid duplicate final MessageRow locationRow = addMessageRow(tmpLocationMessage); locationRow.getEvent().mSentState = Event.SentState.SENDING; getSession().getMediasCache().uploadContent(imageStream, tmpLocationMessage.body, thumbnailMimeType, thumbnailUrl, new MXMediaUploadListener() { @Override public void onUploadStart(String uploadId) { getUiHandler().post(new Runnable() { @Override public void run() { onMessageSendingSucceeded(locationRow.getEvent()); mAdapter.notifyDataSetChanged(); } }); } @Override public void onUploadCancel(String uploadId) { getUiHandler().post(new Runnable() { @Override public void run() { onMessageSendingFailed(locationRow.getEvent()); } }); } @Override public void onUploadError(String uploadId, final int serverResponseCode, final String serverErrorMessage) { getUiHandler().post(new Runnable() { @Override public void run() { commonMediaUploadError(serverResponseCode,serverErrorMessage, locationRow); } }); } @Override public void onUploadComplete(final String uploadId, final String contentUri) { getUiHandler().post(new Runnable() { @Override public void run() { // Build the location message LocationMessage message = tmpLocationMessage.deepCopy(); // replace the thumbnail and the media contents by the computed ones getMXMediasCache().saveFileMediaForUrl(contentUri, thumbnailUrl, mAdapter.getMaxThumbnailWith(), mAdapter.getMaxThumbnailHeight(), "image/jpeg"); message.thumbnail_url = contentUri; // update the event content with the new message info locationRow.getEvent().content = JsonUtils.toJson(message); Log.d(LOG_TAG, "Uploaded to " + contentUri); send(locationRow); } }); } }); } //============================================================================================================== // Unsent messages management //============================================================================================================== /** * Delete the unsent (undeliverable messages). */ public void deleteUnsentMessages() { Collection<Event> unsent = mSession.getDataHandler().getStore().getUndeliverableEvents(mRoom.getRoomId()); if ((null != unsent) && (unsent.size() > 0)) { IMXStore store = mSession.getDataHandler().getStore(); // reset the timestamp for (Event event : unsent) { mAdapter.removeEventById(event.eventId); store.deleteEvent(event); } // update the summary Event latestEvent = store.getLatestEvent(mRoom.getRoomId()); // if there is an oldest event, use it to set a summary if (latestEvent != null) { if (RoomSummary.isSupportedEvent(latestEvent)) { store.storeSummary(latestEvent.roomId, latestEvent, mRoom.getState(), mSession.getMyUserId()); } } store.commit(); mAdapter.notifyDataSetChanged(); } } /** * Resend the unsent messages */ public void resendUnsentMessages() { // check if the call is done in the right thread if (Looper.getMainLooper().getThread() != Thread.currentThread()) { Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { resendUnsentMessages(); } }); return; } Collection<Event> unsent = mSession.getDataHandler().getStore().getUndeliverableEvents(mRoom.getRoomId()); if ((null != unsent) && (unsent.size() > 0)) { mResendingEventsList = new ArrayList<>(unsent); // reset the timestamp for (Event event : mResendingEventsList) { event.mSentState = Event.SentState.UNSENT; } resend(mResendingEventsList.get(0)); mResendingEventsList.remove(0); } } /** * Resend an event. * @param event the event to resend. */ protected void resend(final Event event) { // sanity check // should never happen but got it in a GA issue if (null == event.eventId) { Log.e(LOG_TAG, "resend : got an event with a null eventId"); return; } // check if the call is done in the right thread if (Looper.getMainLooper().getThread() != Thread.currentThread()) { Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { resend(event); } }); return; } // update the timestamp event.originServerTs = System.currentTimeMillis(); // remove the event getSession().getDataHandler().deleteRoomEvent(event); mAdapter.removeEventById(event.eventId); mPendingRelaunchTimersByEventId.remove(event.eventId); // send it again final Message message = JsonUtils.toMessage(event.content); // resend an image ? if (message instanceof ImageMessage) { ImageMessage imageMessage = (ImageMessage)message; // media has not been uploaded if (imageMessage.isLocalContent()) { uploadImageContent(imageMessage.thumbnailUrl, imageMessage.url, imageMessage.body, imageMessage.getMimeType()); return; } } else if (message instanceof FileMessage) { FileMessage fileMessage = (FileMessage)message; // media has not been uploaded if (fileMessage.isLocalContent()) { uploadFileContent(fileMessage.url, fileMessage.getMimeType(), fileMessage.body); return; } } else if (message instanceof VideoMessage) { VideoMessage videoMessage = (VideoMessage)message; // media has not been uploaded if (videoMessage.isLocalContent() || videoMessage.isThumbnailLocalContent()) { String thumbnailUrl = null; String thumbnailMimeType = null; if (null != videoMessage.info) { thumbnailUrl = videoMessage.info.thumbnail_url; if (null != videoMessage.info.thumbnail_info) { thumbnailMimeType = videoMessage.info.thumbnail_info.mimetype; } } uploadVideoContent(videoMessage, null, thumbnailUrl, thumbnailMimeType, videoMessage.url, videoMessage.body, videoMessage.getVideoMimeType()); return; } else if (message instanceof LocationMessage) { LocationMessage locationMessage = (LocationMessage)message; // media has not been uploaded if (locationMessage.isLocalThumbnailContent()) { String thumbMimeType = null; if (null != locationMessage.thumbnail_info) { thumbMimeType = locationMessage.thumbnail_info.mimetype; } uploadLocationContent(locationMessage.thumbnail_url, thumbMimeType, locationMessage.geo_uri, locationMessage.body); return; } } } send(message); } //============================================================================================================== // UI stuff //============================================================================================================== /** * Display a spinner to warn the user that a back pagination is in progress. */ public void showLoadingBackProgress() { } /** * Dismiss the back pagination progress. */ public void hideLoadingBackProgress() { } /** * Display a spinner to warn the user that a forward pagination is in progress. */ public void showLoadingForwardProgress() { } /** * Dismiss the forward pagination progress. */ public void hideLoadingForwardProgress() { } /** * Display a spinner to warn the user that the initialization is in progress. */ public void showInitLoading() { } /** * Dismiss the initialization spinner. */ public void hideInitLoading() { } /** * Refresh the messages list. */ public void refresh() { mAdapter.notifyDataSetChanged(); } //============================================================================================================== // pagination methods //============================================================================================================== /** * Manage the request history error cases. * @param error the error object. */ private void onPaginateRequestError(final Object error) { if (null != MatrixMessageListFragment.this.getActivity()) { if (error instanceof Exception) { Log.e(LOG_TAG, "Network error: " + ((Exception) error).getMessage()); Toast.makeText(MatrixMessageListFragment.this.getActivity(), getActivity().getString(R.string.network_error), Toast.LENGTH_SHORT).show(); } else if (error instanceof MatrixError) { final MatrixError matrixError = (MatrixError) error; Log.e(LOG_TAG, "Matrix error" + " : " + matrixError.errcode + " - " + matrixError.getLocalizedMessage()); Toast.makeText(MatrixMessageListFragment.this.getActivity(), getActivity().getString(R.string.matrix_error) + " : " + matrixError.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); } hideLoadingBackProgress(); hideLoadingForwardProgress(); Log.d(LOG_TAG, "requestHistory failed " + error); mIsBackPaginating = false; } } /** * Start a forward pagination */ private void forwardPaginate() { if (mLockFwdPagination) { Log.d(LOG_TAG, "The forward pagination is locked."); return; } if ((null == mEventTimeLine) || mEventTimeLine.isLiveTimeline()) { //Log.d(LOG_TAG, "The forward pagination is not supported for the live timeline."); return; } if (mIsFwdPaginating) { Log.d(LOG_TAG, "A forward pagination is in progress, please wait."); return; } showLoadingForwardProgress(); final int countBeforeUpdate = mAdapter.getCount(); mIsFwdPaginating = mEventTimeLine.forwardPaginate(new ApiCallback<Integer>() { /** * the forward pagination is ended. */ private void onEndOfPagination(String errorMessage) { if (null != errorMessage) { Log.e(LOG_TAG, "forwardPaginate fails : " + errorMessage); } mIsFwdPaginating = false; hideLoadingForwardProgress(); } @Override public void onSuccess(Integer count) { final int firstPos = mMessageListView.getFirstVisiblePosition(); mLockBackPagination = true; // retrieve if (0 != count) { mAdapter.notifyDataSetChanged(); // trick to avoid that the list jump to the latest item. mMessageListView.setAdapter(mMessageListView.getAdapter()); // keep the first position while refreshing the list mMessageListView.setSelection(firstPos); mMessageListView.post(new Runnable() { @Override public void run() { // Scroll the list down to where it was before adding rows to the top int diff = mAdapter.getCount() - countBeforeUpdate; Log.d(LOG_TAG, "forwardPaginate ends with " + diff + " new items."); onEndOfPagination(null); mLockBackPagination = false; } }); } else { Log.d(LOG_TAG, "forwardPaginate ends : nothing to add"); onEndOfPagination(null); mLockBackPagination = false; } } @Override public void onNetworkError(Exception e) { onEndOfPagination(e.getLocalizedMessage()); } @Override public void onMatrixError(MatrixError e) { onEndOfPagination(e.getLocalizedMessage()); } @Override public void onUnexpectedError(Exception e) { onEndOfPagination(e.getLocalizedMessage()); } }); if (mIsFwdPaginating) { Log.d(LOG_TAG, "forwardPaginate starts"); showLoadingForwardProgress(); } else { hideLoadingForwardProgress(); Log.d(LOG_TAG, "forwardPaginate nothing to do"); } } /** * Set the scroll listener to mMessageListView */ private void setMessageListViewScrollListener() { // ensure that the listener is set only once // else it triggers an inifinite loop with backPaginate. if (!mIsScrollListenerSet) { mIsScrollListenerSet = true; mMessageListView.setOnScrollListener(mScrollListener); } } /** * Trigger a back pagination. * @param fillHistory true to try to fill the listview height. */ public void backPaginate(final boolean fillHistory) { if (mIsBackPaginating) { Log.d(LOG_TAG, "backPaginate is in progress : please wait"); return; } if (mIsInitialSyncing) { Log.d(LOG_TAG, "backPaginate : an initial sync is in progress"); return; } if (mLockBackPagination) { Log.d(LOG_TAG, "backPaginate : The back pagination is locked."); return; } if (!mMatrixMessagesFragment.canBackPaginate()) { Log.d(LOG_TAG, "backPaginate : cannot back paginating again"); setMessageListViewScrollListener(); return; } // in search mode, if (!TextUtils.isEmpty(mPattern)) { Log.d(LOG_TAG, "backPaginate with pattern " + mPattern); requestSearchHistory(); return; } final int countBeforeUpdate = mAdapter.getCount(); mIsBackPaginating = mMatrixMessagesFragment.backPaginate(new SimpleApiCallback<Integer>(getActivity()) { @Override public void onSuccess(final Integer count) { // Scroll the list down to where it was before adding rows to the top mMessageListView.post(new Runnable() { @Override public void run() { mLockFwdPagination = true; final int countDiff = mAdapter.getCount() - countBeforeUpdate; Log.d(LOG_TAG, "backPaginate : ends with " + countDiff + " new items (total : " + mAdapter.getCount() + ")"); // check if some messages have been added if (0 != countDiff) { mAdapter.notifyDataSetChanged(); // trick to avoid that the list jump to the latest item. mMessageListView.setAdapter(mMessageListView.getAdapter()); final int expectedPos = fillHistory ? (mAdapter.getCount() - 1) : (mMessageListView.getFirstVisiblePosition() + countDiff); Log.d(LOG_TAG, "backPaginate : jump to " + expectedPos); //private int mFirstVisibleRowY = INVALID_VIEW_Y_POS; if (fillHistory || (UNDEFINED_VIEW_Y_POS == mFirstVisibleRowY)) { // do not use count because some messages are not displayed // so we compute the new pos mMessageListView.setSelection(expectedPos); } else { mMessageListView.setSelectionFromTop(expectedPos, -mFirstVisibleRowY); } } // Test if a back pagination can be done. // countDiff == 0 is not relevant // because the server can return an empty chunk // but the start and the end tokens are not equal. // It seems often happening with the room visibility feature if (mMatrixMessagesFragment.canBackPaginate()) { Log.d(LOG_TAG, "backPaginate again"); mMessageListView.post(new Runnable() { @Override public void run() { mLockFwdPagination = false; mIsBackPaginating = false; mMessageListView.post(new Runnable() { @Override public void run() { // back paginate until getting something to display if (0 == countDiff) { Log.d(LOG_TAG, "backPaginate again because there was nothing in the current chunk"); backPaginate(fillHistory); } else if (fillHistory) { if ((mMessageListView.getVisibility() == View.VISIBLE) && mMessageListView.getFirstVisiblePosition() < 10) { Log.d(LOG_TAG, "backPaginate : fill history"); backPaginate(fillHistory); } else { Log.d(LOG_TAG, "backPaginate : history should be filled"); hideLoadingBackProgress(); mIsInitialSyncing = false; setMessageListViewScrollListener(); } } else { hideLoadingBackProgress(); } } }); } }); } else { Log.d(LOG_TAG, "no more backPaginate"); setMessageListViewScrollListener(); hideLoadingBackProgress(); mIsBackPaginating = false; mLockFwdPagination = false; } } }); } // the request will be auto restarted when a valid network will be found @Override public void onNetworkError(Exception e) { onPaginateRequestError(e); } @Override public void onMatrixError(MatrixError e) { onPaginateRequestError(e); } @Override public void onUnexpectedError(Exception e) { onPaginateRequestError(e); } }); if (mIsBackPaginating && (null != getActivity())) { Log.d(LOG_TAG, "backPaginate : starts"); showLoadingBackProgress(); } else { Log.d(LOG_TAG, "requestHistory : nothing to do"); } } /** * Cancel the catching requests. */ public void cancelCatchingRequests() { mPattern = null; if (null != mEventTimeLine) { mEventTimeLine.cancelPaginationRequest(); } mIsInitialSyncing = false; mIsBackPaginating = false; mIsFwdPaginating = false; mLockBackPagination = false; mLockFwdPagination = false; hideInitLoading(); hideLoadingBackProgress(); hideLoadingForwardProgress(); } //============================================================================================================== // MatrixMessagesFragment methods //============================================================================================================== @Override public void onEvent(final Event event, final EventTimeline.Direction direction, final RoomState roomState) { if (direction == EventTimeline.Direction.FORWARDS) { getUiHandler().post(new Runnable() { @Override public void run() { if (Event.EVENT_TYPE_REDACTION.equals(event.type)) { MessageRow messageRow = mAdapter.getMessageRow(event.getRedacts()); if (null != messageRow) { Event prunedEvent = mSession.getDataHandler().getStore().getEvent(event.getRedacts(), event.roomId); if (null == prunedEvent) { mAdapter.removeEventById(event.getRedacts()); } else { messageRow.updateEvent(prunedEvent); JsonObject content = messageRow.getEvent().getContentAsJsonObject(); boolean hasToRemoved = (null == content) || (null == content.entrySet()) || (0 == content.entrySet().size()); // test if the event is displayable // GA issue : the activity can be null if (!hasToRemoved && (null != getActivity())) { EventDisplay eventDisplay = new EventDisplay(getActivity(), prunedEvent, roomState); hasToRemoved = TextUtils.isEmpty(eventDisplay.getTextualDisplay()); } // event is removed if it has no more content. if (hasToRemoved) { mAdapter.removeEventById(prunedEvent.eventId); } } mAdapter.notifyDataSetChanged(); } } else if (Event.EVENT_TYPE_TYPING.equals(event.type)) { if (null != mRoom) { mAdapter.setTypingUsers(mRoom.getTypingUsers()); } } else { if (canAddEvent(event)) { // refresh the listView only when it is a live timeline or a search mAdapter.add(new MessageRow(event, roomState), (null == mEventTimeLine) || mEventTimeLine.isLiveTimeline()); } } } }); } else { if (canAddEvent(event)) { mAdapter.addToFront(event, roomState); } } } @Override public void onLiveEventsChunkProcessed() { // NOP } @Override public void onReceiptEvent(List<String> senderIds) { // avoid useless refresh boolean shouldRefresh = true; try { IMXStore store = mSession.getDataHandler().getStore(); int firstPos = mMessageListView.getFirstVisiblePosition(); int lastPos = mMessageListView.getLastVisiblePosition(); ArrayList<String> senders = new ArrayList<>(); ArrayList<String> eventIds = new ArrayList<>(); for (int index = firstPos; index <= lastPos; index++) { MessageRow row = mAdapter.getItem(index); senders.add(row.getEvent().getSender()); eventIds.add(row.getEvent().eventId); } shouldRefresh = false; // check if the receipt will trigger a refresh for (String sender : senderIds) { if (!TextUtils.equals(sender, mSession.getMyUserId())) { ReceiptData receipt = store.getReceipt(mRoom.getRoomId(), sender); // sanity check if (null != receipt) { // test if the event is displayed int pos = eventIds.indexOf(receipt.eventId); // if displayed if (pos >= 0) { // the sender is not displayed as a reader (makes sense...) shouldRefresh = !TextUtils.equals(senders.get(pos), sender); if (shouldRefresh) { break; } } } } } } catch (Exception e) { Log.e(LOG_TAG, "onReceiptEvent failed with " + e.getLocalizedMessage()); } if (shouldRefresh) { mAdapter.notifyDataSetChanged(); } } @Override public void onInitialMessagesLoaded() { Log.d(LOG_TAG, "onInitialMessagesLoaded"); // Jump to the bottom of the list getUiHandler().post(new Runnable() { @Override public void run() { hideLoadingBackProgress(); if (null == mMessageListView.getAdapter()) { mMessageListView.setAdapter(mAdapter); } if ((null == mEventTimeLine) || mEventTimeLine.isLiveTimeline()) { if (mAdapter.getCount() > 0) { // refresh the list only at the end of the sync // else the one by one message refresh gives a weird UX // The application is almost frozen during the mAdapter.notifyDataSetChanged(); if (mScrollToIndex >= 0) { mMessageListView.setSelection(mScrollToIndex); mScrollToIndex = -1; } else { mMessageListView.setSelection(mAdapter.getCount() - 1); } } // fill the page mMessageListView.post(new Runnable() { @Override public void run() { if ((mMessageListView.getVisibility() == View.VISIBLE) && mMessageListView.getFirstVisiblePosition() < 10) { Log.d(LOG_TAG, "onInitialMessagesLoaded : fill history"); backPaginate(true); } else { Log.d(LOG_TAG, "onInitialMessagesLoaded : history should be filled"); mIsInitialSyncing = false; setMessageListViewScrollListener(); } } }); } else { Log.d(LOG_TAG, "onInitialMessagesLoaded : default behaviour"); if ((0 != mAdapter.getCount()) && (mScrollToIndex > 0)) { mAdapter.notifyDataSetChanged(); mMessageListView.setSelection(mScrollToIndex); mScrollToIndex = -1; mMessageListView.post(new Runnable() { @Override public void run() { mIsInitialSyncing = false; setMessageListViewScrollListener(); } }); } else { mIsInitialSyncing = false; setMessageListViewScrollListener(); } } } }); } @Override public EventTimeline getEventTimeLine() { return mEventTimeLine; } @Override public void onTimelineInitialized() { mMessageListView.post(new Runnable() { @Override public void run() { mLockFwdPagination = false; mIsInitialSyncing = false; // search the event pos in the adapter // some events are not displayed so the added events count cannot be used. int eventPos = 0; for (; eventPos < mAdapter.getCount(); eventPos++) { if (TextUtils.equals(mAdapter.getItem(eventPos).getEvent().eventId, mEventId)) { break; } } View parentView = (View) mMessageListView.getParent(); mAdapter.notifyDataSetChanged(); mMessageListView.setAdapter(mAdapter); // center the message in the mMessageListView.setSelectionFromTop(eventPos, parentView.getHeight() / 2); } }); } @Override public RoomPreviewData getRoomPreviewData() { if (null != getActivity()) { // test if the listener has bee retrieved if (null == mRoomPreviewDataListener) { try { mRoomPreviewDataListener = (IRoomPreviewDataListener) getActivity(); } catch (ClassCastException e) { Log.e(LOG_TAG, "getRoomPreviewData failed with " + e.getLocalizedMessage()); } } if (null != mRoomPreviewDataListener) { return mRoomPreviewDataListener.getRoomPreviewData(); } } return null; } @Override public void onRoomFlush() { mAdapter.clear(); } /*** MessageAdapter listener ***/ @Override public void onRowClick(int position) { } @Override public boolean onRowLongClick(int position) { return false; } @Override public void onContentClick(int position) { } @Override public boolean onContentLongClick(int position) { return false; } @Override public void onAvatarClick(String userId) { } @Override public boolean onAvatarLongClick(String userId) { return false; } @Override public void onSenderNameClick(String userId, String displayName) { } @Override public void onMediaDownloaded(int position) { } @Override public void onReadReceiptClick(String eventId, String userId, ReceiptData receipt) { } @Override public boolean onReadReceiptLongClick(String eventId, String userId, ReceiptData receipt) { return false; } @Override public void onMoreReadReceiptClick(String eventId) { } @Override public boolean onMoreReadReceiptLongClick(String eventId) { return false; } @Override public void onURLClick(Uri uri) { if (null != uri) { Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.putExtra(Browser.EXTRA_APPLICATION_ID, getActivity().getPackageName()); getActivity().startActivity(intent); } } @Override public boolean shouldHighlightEvent(Event event) { String eventId = event.eventId; // cache the dedicated rule because it is slow to find them out Object ruleAsVoid = mBingRulesByEventId.get(eventId); if (null != ruleAsVoid) { if (ruleAsVoid instanceof BingRule) { return ((BingRule)ruleAsVoid).shouldHighlight(); } return false; } boolean res = false; BingRule rule = mSession.getDataHandler().getBingRulesManager().fulfilledBingRule(event); if (null != rule) { res = rule.shouldHighlight(); mBingRulesByEventId.put(eventId, rule); } else { mBingRulesByEventId.put(eventId, eventId); } return res; } @Override public void onMatrixUserIdClick(String userId) { } @Override public void onRoomAliasClick(String roomAlias) { } @Override public void onRoomIdClick(String roomId) { } @Override public void onMessageIdClick(String messageId) { } private int mInvalidIndexesCount = 0; @Override public void onInvalidIndexes() { mInvalidIndexesCount++; // it should happen once // else we assume that the adapter is really corrupted // It seems better to close the linked activity to avoid infinite refresh. if (1 == mInvalidIndexesCount) { mMessageListView.post(new Runnable() { @Override public void run() { mAdapter.notifyDataSetChanged(); } }); } else { mMessageListView.post(new Runnable() { @Override public void run() { if (null != getActivity()) { getActivity().finish(); } } }); } } //============================================================================================================== // search methods //============================================================================================================== /** * Cancel the current search */ protected void cancelSearch() { mPattern = null; } /** * Search the pattern on a pagination server side. */ public void requestSearchHistory() { // there is no more server message if (TextUtils.isEmpty(mNextBatch)) { mIsBackPaginating = false; return; } mIsBackPaginating = true; final int firstPos = mMessageListView.getFirstVisiblePosition(); final String fPattern = mPattern; final int countBeforeUpdate = mAdapter.getCount(); showLoadingBackProgress(); List<String> roomIds = null; if (null != mRoom) { roomIds = Arrays.asList(mRoom.getRoomId()); } ApiCallback<SearchResponse> callback = new ApiCallback<SearchResponse>() { @Override public void onSuccess(final SearchResponse searchResponse) { if (TextUtils.equals(mPattern, fPattern)) { // check that the pattern was not modified before the end of the search if (TextUtils.equals(mPattern, fPattern)) { List<SearchResult> searchResults = searchResponse.searchCategories.roomEvents.results; // is there any result to display if (0 != searchResults.size()) { mAdapter.setNotifyOnChange(false); for (SearchResult searchResult : searchResults) { MessageRow row = new MessageRow(searchResult.result, (null == mRoom) ? null : mRoom.getState()); mAdapter.insert(row, 0); } mNextBatch = searchResponse.searchCategories.roomEvents.nextBatch; // Scroll the list down to where it was before adding rows to the top getUiHandler().post(new Runnable() { @Override public void run() { final int expectedFirstPos = firstPos + (mAdapter.getCount() - countBeforeUpdate); mAdapter.notifyDataSetChanged(); // trick to avoid that the list jump to the latest item. mMessageListView.setAdapter(mMessageListView.getAdapter()); // do not use count because some messages are not displayed // so we compute the new pos mMessageListView.setSelection(expectedFirstPos); mMessageListView.post(new Runnable() { @Override public void run() { mIsBackPaginating = false; } }); } }); } else { mIsBackPaginating = false; } hideLoadingBackProgress(); } } } private void onError() { mIsBackPaginating = false; hideLoadingBackProgress(); } // the request will be auto restarted when a valid network will be found @Override public void onNetworkError(Exception e) { Log.e(LOG_TAG, "Network error: " + e.getMessage()); onError(); } @Override public void onMatrixError(MatrixError e) { Log.e(LOG_TAG, "Matrix error" + " : " + e.errcode + " - " + e.getLocalizedMessage()); onError(); } @Override public void onUnexpectedError(Exception e) { Log.e(LOG_TAG, "onUnexpectedError error" + e.getMessage()); onError(); } }; if (mIsMediaSearch) { String[] mediaTypes = {"m.image", "m.video", "m.file"}; mSession.searchMediaName(mPattern, roomIds, Arrays.asList(mediaTypes), mNextBatch, callback); } else { mSession.searchMessageText(mPattern, roomIds, mNextBatch, callback); } } /** * Manage the search response. * @param searchResponse the search response * @param onSearchResultListener the search result listener */ protected void onSearchResponse(final SearchResponse searchResponse, final OnSearchResultListener onSearchResultListener) { List<SearchResult> searchResults = searchResponse.searchCategories.roomEvents.results; ArrayList<MessageRow> messageRows = new ArrayList<>(searchResults.size()); for(SearchResult searchResult : searchResults) { RoomState roomState = null; if (null != mRoom) { roomState = mRoom.getState(); } if (null == roomState) { Room room = mSession.getDataHandler().getStore().getRoom(searchResult.result.roomId); if (null != room) { roomState = room.getState(); } } boolean isValidMessage = false; if ((null != searchResult.result) && (null != searchResult.result.content)) { JsonObject object = searchResult.result.getContentAsJsonObject(); if (null != object) { isValidMessage = (0 != object.entrySet().size()); } } if (isValidMessage) { messageRows.add(new MessageRow(searchResult.result, roomState)); } } Collections.reverse(messageRows); mAdapter.clear(); mAdapter.addAll(messageRows); mNextBatch = searchResponse.searchCategories.roomEvents.nextBatch; if (null != onSearchResultListener) { try { onSearchResultListener.onSearchSucceed(messageRows.size()); } catch (Exception e) { Log.e(LOG_TAG, "onSearchResponse failed with " + e.getLocalizedMessage()); } } } /** * Search a pattern in the messages. * @param pattern the pattern to search * @param onSearchResultListener the search callback */ public void searchPattern(final String pattern, final OnSearchResultListener onSearchResultListener) { searchPattern(pattern, false, onSearchResultListener); } /** * Search a pattern in the messages. * @param pattern the pattern to search (filename for a media message) * @param isMediaSearch true if is it is a media search. * @param onSearchResultListener the search callback */ public void searchPattern(final String pattern, boolean isMediaSearch, final OnSearchResultListener onSearchResultListener) { if (!TextUtils.equals(mPattern, pattern)) { mPattern = pattern; mIsMediaSearch = isMediaSearch; mAdapter.setSearchPattern(mPattern); // something to search if (!TextUtils.isEmpty(mPattern)) { List<String> roomIds = null; // sanity checks if (null != mRoom) { roomIds = Arrays.asList(mRoom.getRoomId()); } // ApiCallback<SearchResponse> searchCallback = new ApiCallback<SearchResponse>() { @Override public void onSuccess(final SearchResponse searchResponse) { // check that the pattern was not modified before the end of the search if (TextUtils.equals(mPattern, pattern)) { onSearchResponse(searchResponse, onSearchResultListener); } } private void onError() { if (null != onSearchResultListener) { try { onSearchResultListener.onSearchFailed(); } catch (Exception e) { Log.e(LOG_TAG, "onSearchResultListener failed with " + e.getLocalizedMessage()); } } } // the request will be auto restarted when a valid network will be found @Override public void onNetworkError(Exception e) { Log.e(LOG_TAG, "Network error: " + e.getMessage()); onError(); } @Override public void onMatrixError(MatrixError e) { Log.e(LOG_TAG, "Matrix error" + " : " + e.errcode + " - " + e.getLocalizedMessage()); onError(); } @Override public void onUnexpectedError(Exception e) { Log.e(LOG_TAG, "onUnexpectedError error" + e.getMessage()); onError(); } }; if (isMediaSearch) { String[] mediaTypes = {"m.image", "m.video", "m.file"}; mSession.searchMediaName(mPattern, roomIds, Arrays.asList(mediaTypes), null, searchCallback); } else { mSession.searchMessageText(mPattern, roomIds, null, searchCallback); } } } } }
Fix a GA issue.
matrix-sdk/src/main/java/org/matrix/androidsdk/fragments/MatrixMessageListFragment.java
Fix a GA issue.
<ide><path>atrix-sdk/src/main/java/org/matrix/androidsdk/fragments/MatrixMessageListFragment.java <ide> getUiHandler().post(new Runnable() { <ide> @Override <ide> public void run() { <add> // should never happen but reported by GA <add> if (null == mMessageListView) { <add> return; <add> } <add> <ide> hideLoadingBackProgress(); <ide> <ide> if (null == mMessageListView.getAdapter()) {
Java
isc
79dd948ef27dea1151cf2ef952292e1d8fc3da70
0
sgtwilko/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion
package com.cradle.iitc_mobile.share; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import com.cradle.iitc_mobile.Log; import com.cradle.iitc_mobile.R; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class IntentGenerator { private static final String EXTRA_FLAG_IS_DEFAULT = "IITCM_IS_DEFAULT"; private static final String EXTRA_FLAG_TITLE = "IITCM_TITLE"; private static final HashSet<ComponentName> KNOWN_COPY_HANDLERS = new HashSet<ComponentName>(); static { if (KNOWN_COPY_HANDLERS.isEmpty()) { KNOWN_COPY_HANDLERS.add(new ComponentName( "com.google.android.apps.docs", "com.google.android.apps.docs.app.SendTextToClipboardActivity")); KNOWN_COPY_HANDLERS.add(new ComponentName( "com.aokp.romcontrol", "com.aokp.romcontrol.ShareToClipboard")); } } public static String getTitle(final Intent intent) throws IllegalArgumentException { if (intent.hasExtra(EXTRA_FLAG_TITLE)) return intent.getStringExtra(EXTRA_FLAG_TITLE); throw new IllegalArgumentException("Got an intent not generated by IntentGenerator!\n" + "Intent:\n" + intent.toString() + "\n" + "Extras:\n" + intent.getExtras().toString()); } public static boolean isDefault(final Intent intent) { return intent.hasExtra(EXTRA_FLAG_IS_DEFAULT) && intent.getBooleanExtra(EXTRA_FLAG_IS_DEFAULT, false); } private final Context mContext; private final PackageManager mPackageManager; public IntentGenerator(final Context context) { mContext = context; mPackageManager = mContext.getPackageManager(); } private boolean containsCopyIntent(final List<Intent> targets) { for (final Intent intent : targets) { for (final ComponentName handler : KNOWN_COPY_HANDLERS) { if (handler.equals(intent.getComponent())) return true; } } return false; } private ArrayList<Intent> resolveTargets(final Intent intent) { final String packageName = mContext.getPackageName(); final List<ResolveInfo> activityList = mPackageManager.queryIntentActivities(intent, 0); final ResolveInfo defaultTarget = mPackageManager.resolveActivity(intent, 0); final ArrayList<Intent> list = new ArrayList<Intent>(activityList.size()); for (final ResolveInfo resolveInfo : activityList) { final ActivityInfo activity = resolveInfo.activityInfo; final ComponentName component = new ComponentName(activity.packageName, activity.name); // remove IITCm from list (we only want other apps) if (activity.packageName.equals(packageName)) continue; // bug in package manager. not exported activities shouldn't even appear here // (usually you would have to compare the package name as well, but since we ignore our own activities, // this isn't necessary) if (!activity.exported) continue; final Intent targetIntent = new Intent(intent) .setComponent(component) .putExtra(EXTRA_FLAG_TITLE, activity.loadLabel(mPackageManager)); if (resolveInfo.activityInfo.name.equals(defaultTarget.activityInfo.name) && resolveInfo.activityInfo.packageName.equals(defaultTarget.activityInfo.packageName)) { targetIntent.putExtra(EXTRA_FLAG_IS_DEFAULT, true); } list.add(targetIntent); } return list; } public void cleanup(final Intent intent) { intent.removeExtra(EXTRA_FLAG_IS_DEFAULT); intent.removeExtra(EXTRA_FLAG_TITLE); } public ArrayList<Intent> getBrowserIntents(final String title, final String url) { final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); return resolveTargets(intent); } public ArrayList<Intent> getGeoIntents(final String title, final String mLl, final int mZoom) { final Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(String.format("geo:%s?z=%d", mLl, mZoom))) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); final ArrayList<Intent> targets = resolveTargets(intent); // According to https://developer.android.com/guide/components/intents-common.html, markers can be labeled. // Unfortunately, only Google Maps supports this, most other apps fail for (final Intent target : targets) { final ComponentName cn = target.getComponent(); if ("com.google.android.apps.maps".equals(cn.getPackageName())) { try { final String encodedTitle = URLEncoder.encode(title, "UTF-8"); target.setData(Uri.parse(String.format("geo:0,0?q=%s%%20(%s)&z=%d", mLl, encodedTitle, mZoom))); } catch (final UnsupportedEncodingException e) { Log.w(e); } break; } } return targets; } public ArrayList<Intent> getShareIntents(final String title, final String text) { final Intent intent = new Intent(Intent.ACTION_SEND) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) .setType("text/plain") .putExtra(Intent.EXTRA_TEXT, text) .putExtra(Intent.EXTRA_SUBJECT, title); final ArrayList<Intent> targets = resolveTargets(intent); if (!containsCopyIntent(targets)) { // add SendToClipboard intent in case Drive is not installed targets.add(new Intent(intent) .setComponent(new ComponentName(mContext, SendToClipboard.class)) .putExtra(EXTRA_FLAG_TITLE, mContext.getString(R.string.activity_share_to_clipboard))); } return targets; } }
mobile/src/com/cradle/iitc_mobile/share/IntentGenerator.java
package com.cradle.iitc_mobile.share; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import com.cradle.iitc_mobile.Log; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class IntentGenerator { private static final String EXTRA_FLAG_IS_DEFAULT = "IITCM_IS_DEFAULT"; private static final String EXTRA_FLAG_TITLE = "IITCM_TITLE"; private static final HashSet<ComponentName> KNOWN_COPY_HANDLERS = new HashSet<ComponentName>(); static { if (KNOWN_COPY_HANDLERS.isEmpty()) { KNOWN_COPY_HANDLERS.add(new ComponentName( "com.google.android.apps.docs", "com.google.android.apps.docs.app.SendTextToClipboardActivity")); KNOWN_COPY_HANDLERS.add(new ComponentName( "com.aokp.romcontrol", "com.aokp.romcontrol.ShareToClipboard")); } } public static String getTitle(final Intent intent) throws IllegalArgumentException { if (intent.hasExtra(EXTRA_FLAG_TITLE)) return intent.getStringExtra(EXTRA_FLAG_TITLE); throw new IllegalArgumentException("Got an intent not generated by IntentGenerator!\n" + "Intent:\n" + intent.toString() + "\n" + "Extras:\n" + intent.getExtras().toString()); } public static boolean isDefault(final Intent intent) { return intent.hasExtra(EXTRA_FLAG_IS_DEFAULT) && intent.getBooleanExtra(EXTRA_FLAG_IS_DEFAULT, false); } private final Context mContext; private final PackageManager mPackageManager; public IntentGenerator(final Context context) { mContext = context; mPackageManager = mContext.getPackageManager(); } private boolean containsCopyIntent(final List<Intent> targets) { for (final Intent intent : targets) { for (final ComponentName handler : KNOWN_COPY_HANDLERS) { if (handler.equals(intent.getComponent())) return true; } } return false; } private ArrayList<Intent> resolveTargets(final Intent intent) { final String packageName = mContext.getPackageName(); final List<ResolveInfo> activityList = mPackageManager.queryIntentActivities(intent, 0); final ResolveInfo defaultTarget = mPackageManager.resolveActivity(intent, 0); final ArrayList<Intent> list = new ArrayList<Intent>(activityList.size()); for (final ResolveInfo resolveInfo : activityList) { final ActivityInfo activity = resolveInfo.activityInfo; final ComponentName component = new ComponentName(activity.packageName, activity.name); // remove IITCm from list (we only want other apps) if (activity.packageName.equals(packageName)) continue; // bug in package manager. not exported activities shouldn't even appear here // (usually you would have to compare the package name as well, but since we ignore our own activities, // this isn't necessary) if (!activity.exported) continue; final Intent targetIntent = new Intent(intent) .setComponent(component) .putExtra(EXTRA_FLAG_TITLE, activity.loadLabel(mPackageManager)); if (resolveInfo.activityInfo.name.equals(defaultTarget.activityInfo.name) && resolveInfo.activityInfo.packageName.equals(defaultTarget.activityInfo.packageName)) { targetIntent.putExtra(EXTRA_FLAG_IS_DEFAULT, true); } list.add(targetIntent); } return list; } public void cleanup(final Intent intent) { intent.removeExtra(EXTRA_FLAG_IS_DEFAULT); intent.removeExtra(EXTRA_FLAG_TITLE); } public ArrayList<Intent> getBrowserIntents(final String title, final String url) { final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); return resolveTargets(intent); } public ArrayList<Intent> getGeoIntents(final String title, final String mLl, final int mZoom) { final Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(String.format("geo:%s?z=%d", mLl, mZoom))) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); final ArrayList<Intent> targets = resolveTargets(intent); // According to https://developer.android.com/guide/components/intents-common.html, markers can be labeled. // Unfortunately, only Google Maps supports this, most other apps fail for (final Intent target : targets) { final ComponentName cn = target.getComponent(); if ("com.google.android.apps.maps".equals(cn.getPackageName())) { try { final String encodedTitle = URLEncoder.encode(title, "UTF-8"); target.setData(Uri.parse(String.format("geo:0,0?q=%s%%20(%s)&z=%d", mLl, encodedTitle, mZoom))); } catch (final UnsupportedEncodingException e) { Log.w(e); } break; } } return targets; } public ArrayList<Intent> getShareIntents(final String title, final String text) { final Intent intent = new Intent(Intent.ACTION_SEND) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) .setType("text/plain") .putExtra(Intent.EXTRA_TEXT, text) .putExtra(Intent.EXTRA_SUBJECT, title); final ArrayList<Intent> targets = resolveTargets(intent); if (!containsCopyIntent(targets)) { // add SendToClipboard intent in case Drive is not installed Intent copyToClipboardIntent = new Intent(intent); copyToClipboardIntent.setComponent(new ComponentName(mContext, SendToClipboard.class)); ResolveInfo activity = mPackageManager.resolveActivity(copyToClipboardIntent, 0); copyToClipboardIntent.putExtra(EXTRA_FLAG_TITLE, activity.loadLabel(mPackageManager)); targets.add(copyToClipboardIntent); } return targets; } }
This activity belongs to us - no need to ask package manager for its label
mobile/src/com/cradle/iitc_mobile/share/IntentGenerator.java
This activity belongs to us - no need to ask package manager for its label
<ide><path>obile/src/com/cradle/iitc_mobile/share/IntentGenerator.java <ide> import android.net.Uri; <ide> <ide> import com.cradle.iitc_mobile.Log; <add>import com.cradle.iitc_mobile.R; <ide> <ide> import java.io.UnsupportedEncodingException; <ide> import java.net.URLEncoder; <ide> <ide> if (!containsCopyIntent(targets)) { <ide> // add SendToClipboard intent in case Drive is not installed <del> Intent copyToClipboardIntent = new Intent(intent); <del> copyToClipboardIntent.setComponent(new ComponentName(mContext, SendToClipboard.class)); <del> ResolveInfo activity = mPackageManager.resolveActivity(copyToClipboardIntent, 0); <del> copyToClipboardIntent.putExtra(EXTRA_FLAG_TITLE, activity.loadLabel(mPackageManager)); <del> targets.add(copyToClipboardIntent); <add> targets.add(new Intent(intent) <add> .setComponent(new ComponentName(mContext, SendToClipboard.class)) <add> .putExtra(EXTRA_FLAG_TITLE, mContext.getString(R.string.activity_share_to_clipboard))); <ide> } <ide> <ide> return targets;
Java
apache-2.0
6d7ef324cc04f1176cde02a7602e3e76105eabf4
0
ZeroMemes/ClientAPI,ImpactDevelopment/ClientAPI
package me.zero.client.integration.defaults; import me.zero.client.api.util.interfaces.Helper; import me.zero.client.api.util.interfaces.Registry; import me.zero.client.integration.Integration; import net.minecraft.client.renderer.IImageBuffer; import net.minecraft.client.renderer.ThreadDownloadImageData; import net.minecraft.util.ResourceLocation; import java.awt.image.BufferedImage; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.UUID; /** * Integration for HalfPetal's CapesAPI. * <a href="http://capesapi.com/">CapesAPI Website</a> * <a href="https://github.com/halfpetal/CapesAPI">CapesAPI GitHub</a> * * @since 1.0 * * @author Matthew Hatcher * @author Marco_MC * @author Brady * @version 2.1.0, February 2017 * * Created by Brady on 2/9/2017. */ public class CapesAPI extends Integration implements Registry<UUID, ResourceLocation>, Helper { /** * The Current Version */ public static final String VERSION = "2.1.0"; /** * The CapesAPI Base URL */ public static final String HOST = "http://capesapi.com/api/v1/"; /** * Map containing all of the Capes */ private Map<UUID, ResourceLocation> capes = new HashMap<>(); /** * Downloads and registers a user's cape to the cape map * * @since 1.0 * * @param obj The UUID getting loaded */ @Override public void load(UUID obj) { String url = HOST + obj.toString() + "/getCape"; final ResourceLocation resourceLocation = new ResourceLocation("capeapi/capes/" + obj.toString() + ".png"); IImageBuffer iImageBuffer = new IImageBuffer() { @Override public BufferedImage parseUserSkin(BufferedImage image) { return image; } @Override public void skinAvailable() { capes.put(obj, resourceLocation); } }; mc.getTextureManager().loadTexture(resourceLocation, new ThreadDownloadImageData(null, url, null, iImageBuffer)); } /** * Removes the cape of the user from the cape map * * @since 1.0 * * @param obj The User's UUID */ @Override public void unload(UUID obj) { capes.remove(obj); } /** * Get the cape of the user from the cape Map * * @since 1.0 * * @param obj The UUID * @return The cape belonging to the UUID */ @Override public ResourceLocation getEntry(UUID obj) { return capes.containsKey(obj) ? capes.get(obj) : null; } /** * @since 1.0 * * @param obj The UUID * @return Whether or not the specified UUID has a Cape associated with it */ @Override public boolean hasEntry(UUID obj) { return capes.containsKey(obj); } /** * Returns whether or not the UUID has specified the capeId. * * @since 1.0 * * @param uuid The UUID * @param capeId The Cape ID * @return Whether or not the UUID has the specified capeId * @throws IOException thrown by URL Creation and various Streams */ public boolean hasCape(UUID uuid, String capeId) throws IOException { URL url = new URL(HOST + uuid.toString() + "/hasCape" + capeId); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String response = ""; String line; while ((line = in.readLine()) != null) response += line; in.close(); return Integer.parseInt(response) == 1; } /** * Grants the user associated with the UUID * with the cape specified. * * @since 1.0 * * @param uuid The UUID * @param capeId The Cape ID * @return Whether or not the cape adding was successful * @throws IOException */ public boolean addCape(UUID uuid, String capeId) throws IOException { String data = "{\"capeId\": \"" + capeId + "\"}"; URL url = new URL(HOST + uuid.toString() + "/addCape"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); DataOutputStream out = new DataOutputStream(con.getOutputStream()); out.write(data.getBytes()); out.flush(); out.close(); InputStream stream = con.getResponseCode() == 200 ? con.getInputStream() : con.getErrorStream(); if (stream == null) throw new IOException(); BufferedReader in = new BufferedReader(new InputStreamReader(stream)); String response = ""; String line; while ((line = in.readLine()) != null) response += line; in.close(); return Integer.parseInt(response) == 1; } }
src/main/java/me/zero/client/integration/defaults/CapesAPI.java
package me.zero.client.integration.defaults; import me.zero.client.api.util.interfaces.Helper; import me.zero.client.api.util.interfaces.Registry; import me.zero.client.integration.Integration; import net.minecraft.client.renderer.IImageBuffer; import net.minecraft.client.renderer.ThreadDownloadImageData; import net.minecraft.util.ResourceLocation; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import java.util.UUID; /** * Integration for HalfPetal's CapesAPI. * <a href="http://capesapi.com/">CapesAPI Website</a> * <a href="https://github.com/halfpetal/CapesAPI">CapesAPI GitHub</a> * * @since 1.0 * * @author Matthew Hatcher * @author Marco_MC * @author Brady * @version 2.0.0, Jan 2017 * * Created by Brady on 2/9/2017. */ public class CapesAPI extends Integration implements Registry<UUID, ResourceLocation>, Helper { /** * Map containing all of the Capes */ private Map<UUID, ResourceLocation> capes = new HashMap<>(); /** * Downloads and registers a user's cape to the cape map * * @since 1.0 * * @param obj The UUID getting loaded */ @Override public void load(UUID obj) { String url = "http://capesapi.com/api/v1/" + obj.toString() + "/getCape"; final ResourceLocation resourceLocation = new ResourceLocation("capeapi/capes/" + obj.toString() + ".png"); IImageBuffer iImageBuffer = new IImageBuffer() { @Override public BufferedImage parseUserSkin(BufferedImage image) { return image; } @Override public void skinAvailable() { capes.put(obj, resourceLocation); } }; mc.getTextureManager().loadTexture(resourceLocation, new ThreadDownloadImageData(null, url, null, iImageBuffer)); } /** * Removes the cape of the user from the cape map * * @since 1.0 * * @param obj The User's UUID */ @Override public void unload(UUID obj) { capes.remove(obj); } /** * Get the cape of the user from the cape Map * * @since 1.0 * * @param obj The UUID * @return The cape belonging to the UUID */ @Override public ResourceLocation getEntry(UUID obj) { return capes.containsKey(obj) ? capes.get(obj) : null; } /** * @since 1.0 * * @param obj The UUID * @return Whether or not the specified UUID has a Cape associated with it */ @Override public boolean hasEntry(UUID obj) { return capes.containsKey(obj); } }
Added the addCape and hasCape methods that were introduced in CapesAPI 2.1.0
src/main/java/me/zero/client/integration/defaults/CapesAPI.java
Added the addCape and hasCape methods that were introduced in CapesAPI 2.1.0
<ide><path>rc/main/java/me/zero/client/integration/defaults/CapesAPI.java <ide> import net.minecraft.util.ResourceLocation; <ide> <ide> import java.awt.image.BufferedImage; <add>import java.io.*; <add>import java.net.HttpURLConnection; <add>import java.net.URL; <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> import java.util.UUID; <ide> * @author Matthew Hatcher <ide> * @author Marco_MC <ide> * @author Brady <del> * @version 2.0.0, Jan 2017 <add> * @version 2.1.0, February 2017 <ide> * <ide> * Created by Brady on 2/9/2017. <ide> */ <ide> public class CapesAPI extends Integration implements Registry<UUID, ResourceLocation>, Helper { <add> <add> /** <add> * The Current Version <add> */ <add> public static final String VERSION = "2.1.0"; <add> <add> /** <add> * The CapesAPI Base URL <add> */ <add> public static final String HOST = "http://capesapi.com/api/v1/"; <ide> <ide> /** <ide> * Map containing all of the Capes <ide> */ <ide> @Override <ide> public void load(UUID obj) { <del> String url = "http://capesapi.com/api/v1/" + obj.toString() + "/getCape"; <add> String url = HOST + obj.toString() + "/getCape"; <ide> final ResourceLocation resourceLocation = new ResourceLocation("capeapi/capes/" + obj.toString() + ".png"); <ide> IImageBuffer iImageBuffer = new IImageBuffer() { <ide> <ide> public boolean hasEntry(UUID obj) { <ide> return capes.containsKey(obj); <ide> } <add> <add> /** <add> * Returns whether or not the UUID has specified the capeId. <add> * <add> * @since 1.0 <add> * <add> * @param uuid The UUID <add> * @param capeId The Cape ID <add> * @return Whether or not the UUID has the specified capeId <add> * @throws IOException thrown by URL Creation and various Streams <add> */ <add> public boolean hasCape(UUID uuid, String capeId) throws IOException { <add> URL url = new URL(HOST + uuid.toString() + "/hasCape" + capeId); <add> HttpURLConnection connection = (HttpURLConnection) url.openConnection(); <add> connection.setRequestMethod("GET"); <add> BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); <add> <add> String response = ""; <add> String line; <add> while ((line = in.readLine()) != null) <add> response += line; <add> <add> in.close(); <add> <add> return Integer.parseInt(response) == 1; <add> } <add> <add> /** <add> * Grants the user associated with the UUID <add> * with the cape specified. <add> * <add> * @since 1.0 <add> * <add> * @param uuid The UUID <add> * @param capeId The Cape ID <add> * @return Whether or not the cape adding was successful <add> * @throws IOException <add> */ <add> public boolean addCape(UUID uuid, String capeId) throws IOException { <add> String data = "{\"capeId\": \"" + capeId + "\"}"; <add> URL url = new URL(HOST + uuid.toString() + "/addCape"); <add> HttpURLConnection con = (HttpURLConnection) url.openConnection(); <add> con.setRequestMethod("POST"); <add> con.setDoOutput(true); <add> con.setDoInput(true); <add> <add> DataOutputStream out = new DataOutputStream(con.getOutputStream()); <add> out.write(data.getBytes()); <add> out.flush(); <add> out.close(); <add> <add> InputStream stream = con.getResponseCode() == 200 ? con.getInputStream() : con.getErrorStream(); <add> <add> if (stream == null) <add> throw new IOException(); <add> <add> BufferedReader in = new BufferedReader(new InputStreamReader(stream)); <add> <add> String response = ""; <add> String line; <add> while ((line = in.readLine()) != null) <add> response += line; <add> <add> in.close(); <add> <add> return Integer.parseInt(response) == 1; <add> } <ide> }
Java
mit
68104f7af95cb8fb48102d485ba9a1cc136ed0ad
0
elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin
package com.elmakers.mine.bukkit.magic; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import com.elmakers.mine.bukkit.action.TeleportTask; import com.elmakers.mine.bukkit.api.action.GUIAction; import com.elmakers.mine.bukkit.api.batch.SpellBatch; import com.elmakers.mine.bukkit.api.block.MaterialAndData; import com.elmakers.mine.bukkit.api.data.BrushData; import com.elmakers.mine.bukkit.api.data.MageData; import com.elmakers.mine.bukkit.api.data.SpellData; import com.elmakers.mine.bukkit.api.data.UndoData; import com.elmakers.mine.bukkit.api.effect.SoundEffect; import com.elmakers.mine.bukkit.api.event.WandActivatedEvent; import com.elmakers.mine.bukkit.api.magic.CastSourceLocation; import com.elmakers.mine.bukkit.api.spell.CastingCost; import com.elmakers.mine.bukkit.api.wand.WandTemplate; import com.elmakers.mine.bukkit.api.wand.WandUpgradePath; import com.elmakers.mine.bukkit.effect.HoloUtils; import com.elmakers.mine.bukkit.effect.Hologram; import com.elmakers.mine.bukkit.entity.EntityData; import com.elmakers.mine.bukkit.heroes.HeroesManager; import com.elmakers.mine.bukkit.spell.ActionSpell; import com.elmakers.mine.bukkit.spell.BaseSpell; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.DeprecatedUtils; import com.elmakers.mine.bukkit.utility.InventoryUtils; import com.elmakers.mine.bukkit.api.wand.WandAction; import com.elmakers.mine.bukkit.wand.WandManaMode; import com.elmakers.mine.bukkit.wand.WandMode; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import de.slikey.effectlib.util.VectorUtils; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.entity.Entity; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityCombustEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.player.PlayerEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.MainHand; import org.bukkit.inventory.PlayerInventory; import org.bukkit.plugin.Plugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.util.Vector; import com.elmakers.mine.bukkit.api.batch.Batch; import com.elmakers.mine.bukkit.api.block.UndoList; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.api.spell.CostReducer; import com.elmakers.mine.bukkit.api.spell.MageSpell; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.api.spell.SpellEventType; import com.elmakers.mine.bukkit.api.spell.SpellResult; import com.elmakers.mine.bukkit.api.spell.SpellTemplate; import com.elmakers.mine.bukkit.api.wand.LostWand; import com.elmakers.mine.bukkit.block.MaterialBrush; import com.elmakers.mine.bukkit.block.UndoQueue; import com.elmakers.mine.bukkit.batch.UndoBatch; import com.elmakers.mine.bukkit.wand.Wand; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class Mage implements CostReducer, com.elmakers.mine.bukkit.api.magic.Mage { protected static int AUTOMATA_ONLINE_TIMEOUT = 5000; public static int UPDATE_FREQUENCY = 5; public static int CHANGE_WORLD_EQUIP_COOLDOWN = 1000; public static int JUMP_EFFECT_FLIGHT_EXEMPTION_DURATION = 0; public static int OFFHAND_CAST_RANGE = 32; public static int OFFHAND_CAST_COOLDOWN = 500; public static boolean DEACTIVATE_WAND_ON_WORLD_CHANGE = false; public static int DEFAULT_SP = 0; final static private Set<Material> EMPTY_MATERIAL_SET = new HashSet<>(); private static String defaultMageName = "Mage"; private static String SKILL_POINT_KEY = "sp"; public static CastSourceLocation DEFAULT_CAST_LOCATION = CastSourceLocation.MAINHAND; public static Vector DEFAULT_CAST_OFFSET = new Vector(0.5, -0.5, 0); public static double SNEAKING_CAST_OFFSET = -0.2; protected final String id; private final MageProperties properties; private final Map<String, MageClass> classes = new HashMap<>(); protected ConfigurationSection data = new MemoryConfiguration(); protected Map<String, SpellData> spellData = new HashMap<>(); protected WeakReference<Player> _player; protected WeakReference<Entity> _entity; protected WeakReference<CommandSender> _commandSender; protected boolean hasEntity; protected String playerName; protected final MagicController controller; protected CommandSender debugger; protected HashMap<String, MageSpell> spells = new HashMap<>(); private Wand activeWand = null; private Wand offhandWand = null; private MageClass activeClass = null; private boolean offhandCast = false; private Map<String, Wand> boundWands = new HashMap<>(); private final Collection<Listener> quitListeners = new HashSet<>(); private final Collection<Listener> deathListeners = new HashSet<>(); private final Collection<Listener> damageListeners = new HashSet<>(); private final Set<MageSpell> activeSpells = new HashSet<>(); private UndoQueue undoQueue = null; private LinkedList<Batch> pendingBatches = new LinkedList<>(); private boolean loading = false; private boolean unloading = false; private int debugLevel = 0; private boolean quiet = false; private EntityData entityData; private long lastTick; private int updateTicks = 0; private Location lastLocation; private Vector velocity = new Vector(); private long lastBlockTime; private long ignoreItemActivationUntil = 0; private Map<PotionEffectType, Integer> effectivePotionEffects = new HashMap<>(); protected float damageReduction = 0; protected float damageReductionPhysical = 0; protected float damageReductionProjectiles = 0; protected float damageReductionFalling = 0; protected float damageReductionFire = 0; protected float damageReductionExplosions = 0; protected boolean isVanished = false; protected long superProtectionExpiration = 0; private Map<Integer, Wand> activeArmor = new HashMap<>(); private Location location; private float costReduction = 0; private float cooldownReduction = 0; private long cooldownExpiration = 0; private float powerMultiplier = 1; private float magePowerBonus = 0; private float spMultiplier = 1; private long lastClick = 0; private long lastCast = 0; private long lastOffhandCast = 0; private long blockPlaceTimeout = 0; private Location lastDeathLocation = null; private final MaterialBrush brush; private long fallProtection = 0; private long fallProtectionCount = 1; private BaseSpell fallingSpell = null; private boolean gaveWelcomeWand = false; private GUIAction gui = null; private Hologram hologram; private boolean hologramIsVisible = false; private Map<Integer, ItemStack> respawnInventory; private Map<Integer, ItemStack> respawnArmor; private List<ItemStack> restoreInventory; private boolean restoreOpenWand; private Float restoreExperience; private Integer restoreLevel; private boolean virtualExperience = false; private float virtualExperienceProgress = 0.0f; private int virtualExperienceLevel = 0; private boolean glidingAllowed = false; private String destinationWarp; public Mage(String id, MagicController controller) { this.id = id; this.controller = controller; this.brush = new MaterialBrush(this, Material.DIRT, (byte) 0); this.properties = new MageProperties(this); _player = new WeakReference<>(null); _entity = new WeakReference<>(null); _commandSender = new WeakReference<>(null); hasEntity = false; } public void setCostReduction(float reduction) { costReduction = reduction; } @Override public boolean hasStoredInventory() { return activeWand != null && activeWand.hasStoredInventory(); } @Override public Set<Spell> getActiveSpells() { return new HashSet<Spell>(activeSpells); } public Inventory getStoredInventory() { return activeWand != null ? activeWand.getStoredInventory() : null; } @Override public void setLocation(Location location) { LivingEntity entity = getLivingEntity(); if (entity != null && location != null) { entity.teleport(location); return; } this.location = location; } public void setLocation(Location location, boolean direction) { if (!direction) { if (this.location == null) { this.location = location; } else { this.location.setX(location.getX()); this.location.setY(location.getY()); this.location.setZ(location.getZ()); } } else { this.location = location; } } public void clearCache() { if (brush != null) { brush.clearSchematic(); } } public void setCooldownReduction(float reduction) { cooldownReduction = reduction; } @Override public void setPowerMultiplier(float multiplier) { powerMultiplier = multiplier; } @Override public float getPowerMultiplier() { return powerMultiplier; } public boolean usesMana() { return activeWand == null ? false : activeWand.usesMana(); } public boolean addToStoredInventory(ItemStack item) { return (activeWand == null ? false : activeWand.addToStoredInventory(item)); } public boolean cancelSelection() { boolean result = false; if (!activeSpells.isEmpty()) { List<MageSpell> active = new ArrayList<>(activeSpells); for (MageSpell spell : active) { result = spell.cancelSelection() || result; } } return result; } public void onPlayerQuit(PlayerEvent event) { Player player = getPlayer(); if (player == null || player != event.getPlayer()) { return; } // Must allow listeners to remove themselves during the event! List<Listener> active = new ArrayList<>(quitListeners); for (Listener listener : active) { callEvent(listener, event); } } public void onPlayerDeath(EntityDeathEvent event) { Player player = getPlayer(); if (player == null || player != event.getEntity()) { return; } if (!player.hasMetadata("arena")) { lastDeathLocation = player.getLocation(); } List<Listener> active = new ArrayList<>(deathListeners); for (Listener listener : active) { callEvent(listener, event); } } public void onPlayerCombust(EntityCombustEvent event) { if (activeWand != null && activeWand.getDamageReductionFire() > 0) { event.getEntity().setFireTicks(0); event.setCancelled(true); } } protected void callEvent(Listener listener, Event event) { for (Method method : listener.getClass().getMethods()) { if (method.isAnnotationPresent(EventHandler.class)) { Class<? extends Object>[] parameters = method.getParameterTypes(); if (parameters.length == 1 && parameters[0].isAssignableFrom(event.getClass())) { try { method.invoke(listener, event); } catch (Exception ex) { ex.printStackTrace(); } } } } } public void onPlayerDamage(EntityDamageEvent event) { Player player = getPlayer(); if (player == null) { return; } // Send on to any registered spells List<Listener> active = new ArrayList<>(damageListeners); for (Listener listener : active) { callEvent(listener, event); if (event.isCancelled()) break; } EntityDamageEvent.DamageCause cause = event.getCause(); if (cause == EntityDamageEvent.DamageCause.FALL) { if (fallProtectionCount > 0 && fallProtection > 0 && fallProtection > System.currentTimeMillis()) { event.setCancelled(true); fallProtectionCount--; if (fallingSpell != null) { double scale = 1; LivingEntity li = getLivingEntity(); if (li != null) { scale = event.getDamage() / li.getMaxHealth(); } fallingSpell.playEffects("land", (float)scale, player.getLocation().getBlock().getRelative(BlockFace.DOWN)); } if (fallProtectionCount <= 0) { fallProtection = 0; fallingSpell = null; } return; } else { fallingSpell = null; } } if (isSuperProtected()) { event.setCancelled(true); if (player.getFireTicks() > 0) { player.setFireTicks(0); } return; } if (event.isCancelled()) return; // First check for damage reduction float reduction = 0; reduction = damageReduction * controller.getMaxDamageReduction(); switch (cause) { case CONTACT: case ENTITY_ATTACK: reduction += damageReductionPhysical * controller.getMaxDamageReductionPhysical(); break; case PROJECTILE: reduction += damageReductionProjectiles * controller.getMaxDamageReductionProjectiles(); break; case FALL: reduction += damageReductionFalling * controller.getMaxDamageReductionFalling(); break; case FIRE: case FIRE_TICK: case LAVA: // Also put out fire if they have fire protection of any kind. if (damageReductionFire > 0 && player.getFireTicks() > 0) { player.setFireTicks(0); } reduction += damageReductionFire * controller.getMaxDamageReductionFire(); break; case BLOCK_EXPLOSION: case ENTITY_EXPLOSION: reduction += damageReductionExplosions * controller.getMaxDamageReductionExplosions(); default: break; } if (reduction >= 1) { event.setCancelled(true); return; } double damage = event.getDamage(); if (reduction > 0) { damage = (1.0f - reduction) * damage; if (damage <= 0) damage = 0.1; event.setDamage(damage); } if (damage > 0) { for (Iterator<Batch> iterator = pendingBatches.iterator(); iterator.hasNext();) { Batch batch = iterator.next(); if (!(batch instanceof SpellBatch)) continue; SpellBatch spellBatch = (SpellBatch)batch; Spell spell = spellBatch.getSpell(); double cancelOnDamage = spell.cancelOnDamage(); if (cancelOnDamage > 0 && cancelOnDamage < damage) { spell.cancel(); batch.finish(); iterator.remove(); } } } } @Override public void unbindAll() { boundWands.clear(); } @Override public void unbind(com.elmakers.mine.bukkit.api.wand.Wand wand) { unbind(wand.getTemplateKey()); } @Override public boolean unbind(String template) { if (template != null) { return boundWands.remove(template) != null; } return false; } public void deactivateWand(Wand wand) { if (wand == activeWand) { setActiveWand(null); } if (wand == offhandWand) { setOffhandWand(null); } } public void onTeleport(PlayerTeleportEvent event) { if (DEACTIVATE_WAND_ON_WORLD_CHANGE) { Location from = event.getFrom(); Location to = event.getTo(); if (from.getWorld().equals(to.getWorld())) { return; } deactivateWand(); } } public void onChangeWorld() { sendDebugMessage("Changing worlds"); checkWandNextTick(true); if (CHANGE_WORLD_EQUIP_COOLDOWN > 0) { ignoreItemActivationUntil = System.currentTimeMillis() + CHANGE_WORLD_EQUIP_COOLDOWN; } } public void activateIcon(Wand activeWand, ItemStack icon) { if (System.currentTimeMillis() < ignoreItemActivationUntil) { return; } // Check for spell or material selection if (icon != null && icon.getType() != Material.AIR) { com.elmakers.mine.bukkit.api.spell.Spell spell = getSpell(Wand.getSpell(icon)); if (spell != null) { boolean isQuickCast = spell.isQuickCast() && !activeWand.isQuickCastDisabled(); isQuickCast = isQuickCast || (activeWand.getMode() == WandMode.CHEST && activeWand.isQuickCast()); if (isQuickCast) { activeWand.cast(spell); } else { activeWand.setActiveSpell(spell.getKey()); } } else if (Wand.isBrush(icon)){ activeWand.setActiveBrush(icon); } } else { activeWand.setActiveSpell(""); } DeprecatedUtils.updateInventory(getPlayer()); } private void setActiveWand(Wand activeWand) { // Avoid deactivating a wand by mistake, and avoid infinite recursion on null! if (this.activeWand == activeWand) return; this.activeWand = activeWand; if (activeWand != null && activeWand.isBound() && activeWand.canUse(getPlayer())) { addBound(activeWand); } blockPlaceTimeout = System.currentTimeMillis() + 200; updateEquipmentEffects(); if (activeWand != null) { WandActivatedEvent activatedEvent = new WandActivatedEvent(this, activeWand); Bukkit.getPluginManager().callEvent(activatedEvent); } } private void setOffhandWand(Wand offhandWand) { // Avoid deactivating a wand by mistake, and avoid infinite recursion on null! if (this.offhandWand == offhandWand) return; this.offhandWand = offhandWand; if (offhandWand != null && offhandWand.isBound() && offhandWand.canUse(getPlayer())) { addBound(offhandWand); } blockPlaceTimeout = System.currentTimeMillis() + 200; updateEquipmentEffects(); if (offhandWand != null) { WandActivatedEvent activatedEvent = new WandActivatedEvent(this, offhandWand); Bukkit.getPluginManager().callEvent(activatedEvent); } } @Override public boolean tryToOwn(com.elmakers.mine.bukkit.api.wand.Wand wand) { if (isPlayer() && wand instanceof Wand && ((Wand)wand).tryToOwn(getPlayer())) { addBound((Wand)wand); return true; } return false; } protected void addBound(Wand wand) { WandTemplate template = wand.getTemplate(); if (template != null && template.isRestorable()) { boundWands.put(template.getKey(), wand); } } public long getBlockPlaceTimeout() { return blockPlaceTimeout; } /** * Send a message to this Mage when a spell is cast. * * @param message The message to send */ @Override public void castMessage(String message) { if (!controller.showCastMessages()) return; sendMessage(controller.getCastMessagePrefix(), message); } /** * Send a message to this Mage. * <p/> * Use this to send messages to the player that are important. * * @param message The message to send */ @Override public void sendMessage(String message) { sendMessage(controller.getMessagePrefix(), message); } public void sendMessage(String prefix, String message) { if (message == null || message.length() == 0 || quiet || !controller.showMessages()) return; Player player = getPlayer(); boolean isTitle = false; boolean isActionBar = false; if (prefix.startsWith("a:")) { isActionBar = true; prefix = prefix.substring(2); } else if (prefix.startsWith("t:")) { isTitle = true; prefix = prefix.substring(2); } if (message.startsWith("a:")) { isActionBar = true; // message overrides prefix isTitle = false; message = message.substring(2); } else if (message.startsWith("t:")) { isTitle = true; // message overrides prefix isActionBar = false; message = message.substring(2); } String fullMessage = prefix + message; if (isTitle && player != null) { CompatibilityUtils.sendTitle(player, fullMessage, null, -1, -1, -1); return; } if (isActionBar && player != null) { CompatibilityUtils.sendActionBar(player, fullMessage); return; } CommandSender sender = getCommandSender(); if (sender != null) { sender.sendMessage(fullMessage); } } public void clearBuildingMaterial() { brush.setMaterial(controller.getDefaultMaterial(), (byte) 1); } @Override public void playSoundEffect(SoundEffect soundEffect) { if (!controller.soundsEnabled() || soundEffect == null) return; soundEffect.play(controller.getPlugin(), getEntity()); } @Override public UndoQueue getUndoQueue() { if (undoQueue == null) { undoQueue = new UndoQueue(this); undoQueue.setMaxSize(controller.getUndoQueueDepth()); } return undoQueue; } @Override public UndoList getLastUndoList() { if (undoQueue == null || undoQueue.isEmpty()) return null; return undoQueue.getLast(); } @Override public boolean prepareForUndo(com.elmakers.mine.bukkit.api.block.UndoList undoList) { if (undoList == null) return false; if (undoList.bypass()) return false; UndoQueue queue = getUndoQueue(); queue.add(undoList); return true; } @Override public boolean registerForUndo(com.elmakers.mine.bukkit.api.block.UndoList undoList) { if (!prepareForUndo(undoList)) return false; int autoUndo = controller.getAutoUndoInterval(); if (autoUndo > 0 && undoList.getScheduledUndo() == 0) { undoList.setScheduleUndo(autoUndo); } else { undoList.updateScheduledUndo(); } if (!undoList.hasBeenScheduled() && undoList.isScheduled() && undoList.hasChanges()) { controller.scheduleUndo(undoList); } return true; } @Override public void addUndoBatch(com.elmakers.mine.bukkit.api.batch.UndoBatch batch) { pendingBatches.addLast(batch); controller.addPending(this); } protected void setPlayer(Player player) { if (player != null) { playerName = player.getName(); this._player = new WeakReference<>(player); this._entity = new WeakReference<Entity>(player); this._commandSender = new WeakReference<CommandSender>(player); hasEntity = true; } else { this._player.clear(); this._entity.clear(); this._commandSender.clear(); hasEntity = false; } } protected void setEntity(Entity entity) { if (entity != null) { playerName = entity.getType().name().toLowerCase().replace("_", " "); if (entity instanceof LivingEntity) { LivingEntity li = (LivingEntity) entity; String customName = li.getCustomName(); if (customName != null && customName.length() > 0) { playerName = customName; } } this._entity = new WeakReference<>(entity); hasEntity = true; } else { this._entity.clear(); hasEntity = false; } } protected void setCommandSender(CommandSender sender) { if (sender != null) { this._commandSender = new WeakReference<>(sender); if (sender instanceof BlockCommandSender) { BlockCommandSender commandBlock = (BlockCommandSender) sender; playerName = commandBlock.getName(); Location location = getLocation(); if (location == null) { location = commandBlock.getBlock().getLocation(); } else { Location blockLocation = commandBlock.getBlock().getLocation(); location.setX(blockLocation.getX()); location.setY(blockLocation.getY()); location.setZ(blockLocation.getZ()); } setLocation(location, false); } else { setLocation(null); } } else { this._commandSender.clear(); setLocation(null); } } protected void onLoad(MageData data) { try { Collection<SpellData> spellDataList = data == null ? null : data.getSpellData(); if (spellDataList != null) { for (SpellData spellData : spellDataList) { this.spellData.put(spellData.getKey().getKey(), spellData); } } // Load player-specific data Player player = getPlayer(); if (player != null) { if (controller.isInventoryBackupEnabled()) { if (restoreInventory != null) { controller.getLogger().info("Restoring saved inventory for player " + player.getName() + " - did the server not shut down properly?"); if (activeWand != null) { activeWand.deactivate(); } Inventory inventory = player.getInventory(); for (int slot = 0; slot < restoreInventory.size(); slot++) { Object item = restoreInventory.get(slot); if (item instanceof ItemStack) { inventory.setItem(slot, (ItemStack) item); } else { inventory.setItem(slot, null); } } restoreInventory = null; } if (restoreExperience != null) { player.setExp(restoreExperience); restoreExperience = null; } if (restoreLevel != null) { player.setLevel(restoreLevel); restoreLevel = null; } } if (activeWand == null) { String welcomeWand = controller.getWelcomeWand(); if (!gaveWelcomeWand && welcomeWand.length() > 0) { gaveWelcomeWand = true; Wand wand = Wand.createWand(controller, welcomeWand); if (wand != null) { wand.takeOwnership(player); giveItem(wand.getItem()); controller.getLogger().info("Gave welcome wand " + wand.getName() + " to " + player.getName()); } else { controller.getLogger().warning("Unable to give welcome wand '" + welcomeWand + "' to " + player.getName()); } } } if (activeWand != null && restoreOpenWand && !activeWand.isInventoryOpen()) { activeWand.openInventory(); } restoreOpenWand = false; } armorUpdated(); loading = false; } catch (Exception ex) { controller.getLogger().warning("Error finalizing player data for " + playerName + ": " + ex.getMessage()); } } protected void finishLoad(MageData data) { MageLoadTask loadTask = new MageLoadTask(this, data); Bukkit.getScheduler().scheduleSyncDelayedTask(controller.getPlugin(), loadTask, 1); } @Override public boolean load(MageData data) { try { if (data == null) { finishLoad(data); return true; } boundWands.clear(); Map<String, ItemStack> boundWandItems = data.getBoundWands(); if (boundWandItems != null) { for (ItemStack boundWandItem : boundWandItems.values()) { try { Wand boundWand = controller.getWand(boundWandItem); boundWands.put(boundWand.getTemplateKey(), boundWand); } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Failed to load bound wand for " + playerName +": " + boundWandItem, ex); } } } this.data = data.getExtraData(); this.properties.load(data.getProperties()); this.properties.loadProperties(); this.classes.clear(); Map<String, ConfigurationSection> classProperties = data.getClassProperties(); for (Map.Entry<String, ConfigurationSection> entry : classProperties.entrySet()) { // ... what to do if missing templates? Don't want to lose data. Will need to think about this. String mageClassKey = entry.getKey(); MageClassTemplate classTemplate = controller.getMageClass(mageClassKey); if (classTemplate != null) { MageClass newClass = new MageClass(this, classTemplate); newClass.load(entry.getValue()); classes.put(mageClassKey, newClass); } } // Link up parents for (MageClass mageClass : classes.values()) { assignParent(mageClass); } // Load activeClass setActiveClass(data.getActiveClass()); cooldownExpiration = data.getCooldownExpiration(); fallProtectionCount = data.getFallProtectionCount(); fallProtection = data.getFallProtectionDuration(); if (fallProtectionCount > 0 && fallProtection > 0) { fallProtection = System.currentTimeMillis() + fallProtection; } gaveWelcomeWand = data.getGaveWelcomeWand(); playerName = data.getName(); lastDeathLocation = data.getLastDeathLocation(); lastCast = data.getLastCast(); destinationWarp = data.getDestinationWarp(); if (destinationWarp != null) { if (!destinationWarp.isEmpty()) { Location destination = controller.getWarp(destinationWarp); if (destination != null) { Plugin plugin = controller.getPlugin(); controller.info("Warping " + getEntity().getName() + " to " + destinationWarp + " on login"); TeleportTask task = new TeleportTask(getController(), getEntity(), destination, 4, true, true, null); Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, task, 1); } else { controller.info("Failed to warp " + getEntity().getName() + " to " + destinationWarp + " on login, warp doesn't exist"); } } destinationWarp = null; } getUndoQueue().load(data.getUndoData()); respawnInventory = data.getRespawnInventory(); respawnArmor = data.getRespawnArmor(); restoreOpenWand = data.isOpenWand(); BrushData brushData = data.getBrushData(); if (brushData != null) { brush.load(brushData); } if (controller.isInventoryBackupEnabled()) { restoreInventory = data.getStoredInventory(); restoreLevel = data.getStoredLevel(); restoreExperience = data.getStoredExperience(); } } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Failed to load player data for " + playerName, ex); return false; } finishLoad(data); return true; } @Override public @Nullable MageClass getActiveClass() { return activeClass; } @Override public boolean setActiveClass(String classKey) { if (classKey == null) { activeClass = null; return true; } MageClass targetClass = getClass(classKey); if (targetClass == null) { return false; } activeClass = targetClass; // TODO: Is this the best place to do this? activeClass.loadProperties(); return true; } @Override public boolean removeClass(String classKey) { if (!classes.containsKey(classKey)) { return false; } classes.remove(classKey); if (activeClass != null && activeClass.getTemplate().getKey().equals(classKey)) { activeClass = null; } return true; } public boolean useSkill(ItemStack skillItem) { Spell spell = getSpell(Wand.getSpell(skillItem)); if (spell == null) return false; boolean canUse = true; String skillClass = Wand.getSpellClass(skillItem); if (skillClass != null && !skillClass.isEmpty()) { if (!setActiveClass(skillClass)) { canUse = false; sendMessage(controller.getMessages().get("mage.no_class").replace("$name", spell.getName())); } } if (canUse) { // TODO: Maybe find a better way to handle this. // There is also an issue of an active wand taking over the hotbar display. Wand activeWand = this.activeWand; this.activeWand = null; spell.cast(); this.activeWand = activeWand; } return canUse; } @Override @Nullable public MageClass unlockClass(@Nonnull String key) { return getClass(key, true); } @Override public @Nullable MageClass getClass(@Nonnull String key) { return getClass(key, false); } private @Nullable MageClass getClass(@Nonnull String key, boolean forceCreate) { MageClass mageClass = classes.get(key); if (mageClass == null) { MageClassTemplate template = controller.getMageClass(key); if (template != null && (forceCreate || !template.isLocked())) { mageClass = new MageClass(this, template); assignParent(mageClass); classes.put(key, mageClass); } } return mageClass; } private void assignParent(MageClass mageClass) { MageClassTemplate template = mageClass.getTemplate(); MageClassTemplate parentTemplate = template.getParent(); if (parentTemplate != null) { // Having a sub-class means having the parent class. MageClass parentClass = getClass(parentTemplate.getKey(), true); // Should never be null, check is here to silence the compiler. if(parentClass != null) { mageClass.setParent(parentClass); } } } @Override public boolean save(MageData data) { if (loading) return false; try { data.setName(getName()); data.setId(getId()); data.setLastCast(lastCast); data.setLastDeathLocation(lastDeathLocation); data.setLocation(location); data.setDestinationWarp(destinationWarp); data.setCooldownExpiration(cooldownExpiration); long now = System.currentTimeMillis(); if (fallProtectionCount > 0 && fallProtection > now) { data.setFallProtectionCount(fallProtectionCount); data.setFallProtectionDuration(fallProtection - now); } else { data.setFallProtectionCount(0); data.setFallProtectionDuration(0); } BrushData brushData = new BrushData(); brush.save(brushData); data.setBrushData(brushData); UndoData undoData = new UndoData(); getUndoQueue().save(undoData); data.setUndoData(undoData); data.setSpellData(this.spellData.values()); if (boundWands.size() > 0) { Map<String, ItemStack> wandItems = new HashMap<>(); for (Map.Entry<String, Wand> wandEntry : boundWands.entrySet()) { wandItems.put(wandEntry.getKey(), wandEntry.getValue().getItem()); } data.setBoundWands(wandItems); } data.setRespawnArmor(respawnArmor); data.setRespawnInventory(respawnInventory); data.setOpenWand(false); if (activeWand != null) { if (activeWand.hasStoredInventory()) { data.setStoredInventory(Arrays.asList(activeWand.getStoredInventory().getContents())); } if (activeWand.isInventoryOpen()) { data.setOpenWand(true); } } data.setGaveWelcomeWand(gaveWelcomeWand); data.setExtraData(this.data); data.setProperties(properties.getConfiguration()); Map<String, ConfigurationSection> classProperties = new HashMap<>(); for (Map.Entry<String, MageClass> entry : classes.entrySet()) { classProperties.put(entry.getKey(), entry.getValue().getConfiguration()); } data.setClassProperties(classProperties); String activeClassKey = activeClass == null ? null : activeClass.getTemplate().getKey(); data.setActiveClass(activeClassKey); } catch (Exception ex) { controller.getPlugin().getLogger().log(Level.WARNING, "Failed to save player data for " + playerName, ex); return false; } return true; } public boolean checkLastClick(long maxInterval) { long now = System.currentTimeMillis(); long previous = lastClick; lastClick = now; return (previous <= 0 || previous + maxInterval < now); } protected void removeActiveEffects() { LivingEntity entity = getLivingEntity(); if (entity == null) return; Collection<PotionEffect> activeEffects = entity.getActivePotionEffects(); for (PotionEffect effect : activeEffects) { if (effect.getDuration() > Integer.MAX_VALUE / 2) { entity.removePotionEffect(effect.getType()); } } } public void sendMessageKey(String key) { sendMessage(controller.getMessages().get(key, key)); } private Wand checkWand(ItemStack itemInHand) { Player player = getPlayer(); if (isLoading() || player == null) return null; ItemStack activeWandItem = activeWand != null ? activeWand.getItem() : null; if (activeWandItem == itemInHand) return activeWand; if (!Wand.isWand(itemInHand)) itemInHand = null; if ((itemInHand != null && activeWandItem == null) || (activeWandItem != null && itemInHand == null) || (activeWandItem != null && itemInHand != null && !itemInHand.equals(activeWandItem)) ) { if (activeWand != null) { activeWand.deactivate(); } if (itemInHand != null && controller.hasWandPermission(player)) { Wand newActiveWand = controller.getWand(itemInHand); if (newActiveWand.activate(this)) { setActiveWand(newActiveWand); } else { setActiveWand(null); } } } return activeWand; } public boolean offhandCast() { long now = System.currentTimeMillis(); if (lastOffhandCast > 0 && now < lastOffhandCast + OFFHAND_CAST_COOLDOWN) { return false; } lastOffhandCast = now; Player player = getPlayer(); if (isLoading() || player == null) return false; ItemStack itemInOffhand = player.getInventory().getItemInOffHand(); if (Wand.isWand(itemInOffhand)) { if (offhandWand != null && (offhandWand.getLeftClickAction() == WandAction.CAST || offhandWand.getRightClickAction() == WandAction.CAST)) { offhandCast = true; boolean castResult = false; try { offhandWand.tickMana(); offhandWand.setActiveMage(this); castResult = offhandWand.cast(); // Don't swing arm is cast is from right-click if (offhandWand != null && offhandWand.getRightClickAction() != WandAction.CAST) { CompatibilityUtils.swingOffhand(player, OFFHAND_CAST_RANGE); } } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Error casting from offhand wand", ex); } offhandCast = false; return castResult; } } return false; } public boolean setOffhandActive(boolean active) { boolean wasActive = offhandCast; this.offhandCast = active; return wasActive; } private Wand checkOffhandWand() { Player player = getPlayer(); if (player == null) { return null; } return checkOffhandWand(player.getInventory().getItemInOffHand()); } private Wand checkOffhandWand(ItemStack itemInHand) { Player player = getPlayer(); if (isLoading() || player == null) return null; ItemStack offhandWandItem = offhandWand != null ? offhandWand.getItem() : null; if (offhandWandItem == itemInHand) return offhandWand; if (!Wand.isWand(itemInHand)) itemInHand = null; if ((itemInHand != null && offhandWandItem == null) || (offhandWandItem != null && itemInHand == null) || (itemInHand != null && offhandWandItem != null && !itemInHand.equals(offhandWandItem)) ) { if (offhandWand != null) { offhandWand.deactivate(); } if (itemInHand != null && controller.hasWandPermission(player)) { Wand newActiveWand = controller.getWand(itemInHand); if (newActiveWand.activateOffhand(this)) { setOffhandWand(newActiveWand); } else { setOffhandWand(null); } } } return offhandWand; } public void checkWandNextTick(boolean checkAll) { Bukkit.getScheduler().scheduleSyncDelayedTask(controller.getPlugin(), new CheckWandTask(this, checkAll)); } public void checkWandNextTick() { Bukkit.getScheduler().scheduleSyncDelayedTask(controller.getPlugin(), new CheckWandTask(this)); } @Override public Wand checkWand() { Player player = getPlayer(); if (isLoading() || player == null) return null; checkOffhandWand(); return checkWand(player.getInventory().getItemInMainHand()); } @Override public Vector getVelocity() { return velocity; } protected void updateVelocity() { if (lastLocation != null) { Location currentLocation = getLocation(); if (currentLocation.getWorld().equals(lastLocation.getWorld())) { long interval = System.currentTimeMillis() - lastTick; velocity.setX((currentLocation.getX() - lastLocation.getX()) * 1000 / interval); velocity.setY((currentLocation.getY() - lastLocation.getY()) * 1000 / interval); velocity.setZ((currentLocation.getZ() - lastLocation.getZ()) * 1000 / interval); } else { velocity.setX(0); velocity.setY(0); velocity.setZ(0); } } lastLocation = getLocation(); } @Override public void tick() { if (!isValid()) return; long now = System.currentTimeMillis(); if (entityData != null) { if (lastTick != 0) { long tickInterval = entityData.getTickInterval(); if (now - lastTick > tickInterval) { updateVelocity(); entityData.tick(this); lastTick = now; } } else { lastTick = now; } } else { updateVelocity(); lastTick = now; } Player player = getPlayer(); // We don't tick non-player or offline Mages, except // above where entityData is ticked if present. if (player != null && player.isOnline()) { // We only update all of this at a configurable interval, // as it could have performance concerns. if (updateTicks++ < UPDATE_FREQUENCY) return; updateTicks = 0; checkWand(); if (activeWand != null) { activeWand.tick(); } else if (virtualExperience) { resetSentExperience(); } if (offhandWand != null) { offhandWand.tick(); } if (activeClass != null) { activeClass.tick(); } properties.tick(); if (Wand.LiveHotbarSkills && (activeWand == null || !activeWand.isInventoryOpen())) { updateHotbarStatus(); } // Avoid getting kicked for large jump effects // It'd be nice to filter this by amplitude, but as // it turns out that is not easy to check efficiently. if (JUMP_EFFECT_FLIGHT_EXEMPTION_DURATION > 0 && player.hasPotionEffect(PotionEffectType.JUMP)) { controller.addFlightExemption(player, JUMP_EFFECT_FLIGHT_EXEMPTION_DURATION); } for (Wand armorWand : activeArmor.values()) { armorWand.updateEffects(this); } // Copy this set since spells may get removed while iterating! List<MageSpell> active = new ArrayList<>(activeSpells); for (MageSpell spell : active) { spell.tick(); if (!spell.isActive()) { deactivateSpell(spell); } } } } public int processPendingBatches(int maxBlockUpdates) { int updated = 0; if (pendingBatches.size() > 0) { List<Batch> processBatches = new ArrayList<>(pendingBatches); pendingBatches.clear(); for (Batch batch : processBatches) { if (updated < maxBlockUpdates) { int batchUpdated = batch.process(maxBlockUpdates - updated); updated += batchUpdated; } if (!batch.isFinished()) { pendingBatches.add(batch); } } } return updated; } public boolean hasPendingBatches() { return pendingBatches.size() > 0; } public void setLastHeldMapId(int mapId) { brush.setMapId(mapId); } @Override public int getLastHeldMapId() { return brush.getMapId(); } protected void loadSpells(Map<String, ConfigurationSection> spellConfiguration) { if (spellConfiguration == null) return; Collection<MageSpell> currentSpells = new ArrayList<>(spells.values()); for (MageSpell spell : currentSpells) { String key = spell.getKey(); if (spellConfiguration.containsKey(key)) { ConfigurationSection template = spellConfiguration.get(key); String className = template.getString("class"); if (className == null) { className = ActionSpell.class.getName(); } // Check for spells that have changed class // TODO: Still unsure if this is right. if (!spell.getClass().getName().contains(className)) { //SpellData spellData = new SpellData(key); spell.save(null); spells.remove(key); this.spellData.put(key, spell.getSpellData()); } else { spell.loadTemplate(key, template); spell.loadPrerequisites(template); } } else { spells.remove(key); } } } /* * API Implementation */ @Override public Collection<Batch> getPendingBatches() { Collection<Batch> pending = new ArrayList<>(); pending.addAll(pendingBatches); return pending; } @Override public String getName() { return playerName == null || playerName.length() == 0 ? defaultMageName : playerName; } @Override public String getDisplayName() { Entity entity = getEntity(); if (entity == null) { return getName(); } if (entity instanceof Player) { return ((Player)entity).getDisplayName(); } return controller.getEntityDisplayName(entity); } public void setName(String name) { playerName = name; } @Override public String getId() { return id; } @Override public Location getLocation() { if (location != null) return location.clone(); LivingEntity livingEntity = getLivingEntity(); if (livingEntity == null) return null; return livingEntity.getLocation(); } @Override public Location getEyeLocation() { Entity entity = getEntity(); if (entity != null) { return CompatibilityUtils.getEyeLocation(entity); } return getLocation(); } @Override public Location getCastLocation() { Location castLocation = getEyeLocation(); if (activeWand != null && !offhandCast) { castLocation = activeWand.getLocation(); } else if (offhandWand != null && offhandCast) { castLocation = offhandWand.getLocation(); } else if (DEFAULT_CAST_LOCATION == CastSourceLocation.MAINHAND) { castLocation = getOffsetLocation(castLocation, false, DEFAULT_CAST_OFFSET); } else if (DEFAULT_CAST_LOCATION == CastSourceLocation.OFFHAND) { castLocation = getOffsetLocation(castLocation, true, DEFAULT_CAST_OFFSET); } return castLocation; } @Override public Location getWandLocation() { return getCastLocation(); } public Location getOffsetLocation(Location baseLocation, boolean isInOffhand, Vector offset) { Entity entity = getEntity(); if (entity == null) return baseLocation; boolean leftHand = isInOffhand; if (entity instanceof HumanEntity) { HumanEntity human = (HumanEntity)entity; if (human.getMainHand() == MainHand.LEFT) { leftHand = !leftHand; } } double sneakOffset = 0; if (entity instanceof Player && ((Player)entity).isSneaking()) { sneakOffset = SNEAKING_CAST_OFFSET; } if (leftHand) { offset = new Vector(offset.getX(), offset.getY() + sneakOffset, -offset.getZ()); } else if (sneakOffset != 0) { offset = new Vector(offset.getX(), offset.getY() + sneakOffset, offset.getZ()); } baseLocation.add(VectorUtils.rotateVector(offset, baseLocation)); return baseLocation; } @Override public Location getOffhandWandLocation() { Location wandLocation = getEyeLocation(); if (offhandWand != null) { wandLocation = offhandWand.getLocation(); } return wandLocation; } @Override public Vector getDirection() { Location location = getLocation(); if (location != null) { return location.getDirection(); } return new Vector(0, 1, 0); } @Override public UndoList undo(Block target) { return getUndoQueue().undo(target); } @Override public Batch cancelPending() { return cancelPending(null, true); } @Override public Batch cancelPending(String spellKey) { return cancelPending(spellKey, true); } @Override public Batch cancelPending(boolean force) { return cancelPending(null, force); } @Override public int finishPendingUndo() { int finished = 0; if (pendingBatches.size() > 0) { List<Batch> batches = new ArrayList<>(); batches.addAll(pendingBatches); for (Batch batch : batches) { if (batch instanceof UndoBatch) { while (!batch.isFinished()) { batch.process(1000); } pendingBatches.remove(batch); finished++; } } } return finished; } @Override public Batch cancelPending(String spellKey, boolean force) { Batch stoppedPending = null; if (pendingBatches.size() > 0) { List<Batch> batches = new ArrayList<>(); batches.addAll(pendingBatches); for (Batch batch : batches) { if (spellKey != null || !force) { if (!(batch instanceof SpellBatch)) { continue; } SpellBatch spellBatch = (SpellBatch)batch; Spell spell = spellBatch.getSpell(); if (spell == null) { continue; } if (!force && !spell.isCancellable()) { continue; } if (spellKey != null && !spell.getSpellKey().getBaseKey().equalsIgnoreCase(spellKey)) { continue; } } if (!(batch instanceof UndoBatch)) { if (force && batch instanceof SpellBatch) { SpellBatch spellBatch = (SpellBatch)batch; Spell spell = spellBatch.getSpell(); if (spell != null) { spell.cancel(); } } batch.finish(); pendingBatches.remove(batch); stoppedPending = batch; } } } return stoppedPending; } @Override public UndoList undo() { return getUndoQueue().undo(); } @Override public boolean commit() { return getUndoQueue().commit(); } @Override public boolean hasCastPermission(Spell spell) { return spell.hasCastPermission(getCommandSender()); } @Override public boolean hasSpell(String key) { return spells.containsKey(key); } @Override public MageSpell getSpell(String key) { if (loading) return null; MageSpell playerSpell = spells.get(key); if (playerSpell == null) { playerSpell = createSpell(key); if (playerSpell != null) { SpellData spellData = this.spellData.get(key); if (spellData == null) { spellData = new SpellData(key); this.spellData.put(key, spellData); } playerSpell.load(spellData); } } else { playerSpell.setMage(this); } return playerSpell; } protected MageSpell createSpell(String key) { MageSpell playerSpell = spells.get(key); if (playerSpell != null) { playerSpell.setMage(this); return playerSpell; } SpellTemplate spellTemplate = controller.getSpellTemplate(key); if (spellTemplate == null) return null; Spell newSpell = spellTemplate.createSpell(); if (newSpell == null || !(newSpell instanceof MageSpell)) return null; playerSpell = (MageSpell)newSpell; spells.put(newSpell.getKey(), playerSpell); playerSpell.setMage(this); return playerSpell; } @Override public Collection<Spell> getSpells() { List<Spell> export = new ArrayList<Spell>(spells.values()); return export; } @Override public void activateSpell(Spell spell) { if (spell instanceof MageSpell) { MageSpell mageSpell = ((MageSpell) spell); activeSpells.add(mageSpell); mageSpell.setActive(true); } } @Override public void deactivateSpell(Spell spell) { activeSpells.remove(spell); // If this was called by the Spell itself, the following // should do nothing as the spell is already marked as inactive. if (spell instanceof MageSpell) { ((MageSpell) spell).deactivate(); } } @Override public void deactivateAllSpells() { deactivateAllSpells(false, false); } @Override public void deactivateAllSpells(boolean force, boolean quiet) { // Copy this set since spells will get removed while iterating! List<MageSpell> active = new ArrayList<>(activeSpells); for (MageSpell spell : active) { if (spell.deactivate(force, quiet)) { activeSpells.remove(spell); } } // This is mainly here to prevent multi-wand spamming and for // Disarm to be more powerful.. because Disarm needs to be more // powerful :| cancelPending(false); } @Override public boolean isCostFree() { // Special case for command blocks and Automata if (getPlayer() == null) return true; return getCostReduction() > 1; } @Override public boolean isConsumeFree() { return activeWand != null && activeWand.isConsumeFree(); } @Override public boolean isSuperProtected() { if (superProtectionExpiration != 0) { if (System.currentTimeMillis() > superProtectionExpiration) { superProtectionExpiration = 0; } else { return true; } } if (offhandCast && offhandWand != null) { return offhandWand.isSuperProtected(); } return activeWand != null && activeWand.isSuperProtected(); } @Override public boolean isSuperPowered() { if (offhandCast && offhandWand != null) { return offhandWand.isSuperPowered(); } return activeWand != null && activeWand.isSuperPowered(); } @Override public float getCostReduction() { if (offhandCast && offhandWand != null) { return offhandWand.getCostReduction() + costReduction; } return activeWand == null ? costReduction + controller.getCostReduction() : activeWand.getCostReduction() + costReduction; } @Override public float getConsumeReduction() { if (offhandCast && offhandWand != null) { return offhandWand.getConsumeReduction(); } return activeWand == null ? 0 : activeWand.getConsumeReduction(); } @Override public float getCostScale() { return 1; } @Override public float getCooldownReduction() { if (offhandCast && offhandWand != null) { return offhandWand.getCooldownReduction() + cooldownReduction; } return activeWand == null ? cooldownReduction + controller.getCooldownReduction() : activeWand.getCooldownReduction() + cooldownReduction; } @Override public boolean isCooldownFree() { return getCooldownReduction() > 1; } @Override public long getRemainingCooldown() { long remaining = 0; if (cooldownExpiration > 0) { long now = System.currentTimeMillis(); if (cooldownExpiration > now) { remaining = cooldownExpiration - now; } else { cooldownExpiration = 0; } } return remaining; } @Override public void clearCooldown() { cooldownExpiration = 0; HeroesManager heroes = controller.getHeroes(); Player player = getPlayer(); if (heroes != null && player != null) { heroes.clearCooldown(player); } } @Override public void setRemainingCooldown(long ms) { cooldownExpiration = Math.max(ms + System.currentTimeMillis(), cooldownExpiration); HeroesManager heroes = controller.getHeroes(); Player player = getPlayer(); if (heroes != null && player != null) { heroes.setCooldown(player, ms); } } @Override public Color getEffectColor() { if (offhandCast && offhandWand != null) { return offhandWand.getEffectColor(); } if (activeWand == null) return null; return activeWand.getEffectColor(); } @Override public String getEffectParticleName() { if (offhandCast && offhandWand != null) { return offhandWand.getEffectParticleName(); } if (activeWand == null) return null; return activeWand.getEffectParticleName(); } @Override public void onCast(Spell spell, SpellResult result) { lastCast = System.currentTimeMillis(); if (spell != null) { // Notify controller of successful casts, // this if for dynmap display or other global-level processing. controller.onCast(this, spell, result); } } @Override public float getPower() { if (offhandCast && offhandWand != null) { float power = Math.min(controller.getMaxPower(), offhandWand.getPower() + getMagePowerBonus()); return power * powerMultiplier; } float power = Math.min(controller.getMaxPower(), activeWand == null ? getMagePowerBonus() : activeWand.getPower() + getMagePowerBonus()); return power * powerMultiplier; } @Override public float getMagePowerBonus() { return magePowerBonus; } @Override public void setMagePowerBonus(float magePowerBonus) { this.magePowerBonus = magePowerBonus; } @Override public boolean isRestricted(Material material) { Player player = getPlayer(); if (player != null && player.hasPermission("Magic.bypass_restricted")) return false; return controller.isRestricted(material); } @Override public MageController getController() { return controller; } @Override public Set<Material> getRestrictedMaterials() { if (isSuperPowered()) { return EMPTY_MATERIAL_SET; } return controller.getRestrictedMaterials(); } @Override public boolean isPVPAllowed(Location location) { return controller.isPVPAllowed(getPlayer(), location == null ? getLocation() : location); } @Override public boolean hasBuildPermission(Block block) { return controller.hasBuildPermission(getPlayer(), block); } @Override public boolean hasBreakPermission(Block block) { return controller.hasBreakPermission(getPlayer(), block); } @Override public boolean isIndestructible(Block block) { return controller.isIndestructible(block); } @Override public boolean isDestructible(Block block) { return controller.isDestructible(block); } @Override public boolean isDead() { LivingEntity entity = getLivingEntity(); if (entity != null) { return entity.isDead(); } // Check for automata CommandSender sender = getCommandSender(); if (sender == null || !(sender instanceof BlockCommandSender)) return true; BlockCommandSender commandBlock = (BlockCommandSender) sender; Block block = commandBlock.getBlock(); if (!block.getChunk().isLoaded()) return true; return (block.getType() != Material.COMMAND); } @Override public boolean isOnline() { Player player = getPlayer(); if (player != null) { return player.isOnline(); } // Check for automata CommandSender sender = getCommandSender(); if (sender == null || !(sender instanceof BlockCommandSender)) return true; return lastCast > System.currentTimeMillis() - AUTOMATA_ONLINE_TIMEOUT; } @Override public boolean isPlayer() { Player player = getPlayer(); return player != null; } @Override public boolean hasLocation() { return getLocation() != null; } @Override public Inventory getInventory() { if (hasStoredInventory()) { return getStoredInventory(); } Player player = getPlayer(); if (player != null) { return player.getInventory(); } // TODO: Maybe wrap EntityEquipment in an Inventory... ? Could be hacky. return null; } @Override public int removeItem(ItemStack itemStack, boolean allowVariants) { if (!isPlayer()) return 0; Integer sp = Wand.getSP(itemStack); if (sp != null) { int currentSP = getSkillPoints(); int newSP = currentSP - sp; if (currentSP < sp) { sp = sp - currentSP; } else { sp = 0; } setSkillPoints(newSP); return sp; } int amount = itemStack == null ? 0 : itemStack.getAmount(); Inventory inventory = getInventory(); ItemStack[] contents = inventory.getContents(); for (int index = 0; amount > 0 && index < contents.length; index++) { ItemStack item = contents[index]; if (item == null) continue; if ((!allowVariants && itemStack.isSimilar(item)) || (allowVariants && itemStack.getType() == item.getType() && (item.getItemMeta() == null || item.getItemMeta().getDisplayName() == null))) { if (amount >= item.getAmount()) { amount -= item.getAmount(); inventory.setItem(index, null); } else { item.setAmount(item.getAmount() - amount); amount = 0; } } } return amount; } @Override public boolean hasItem(ItemStack itemStack, boolean allowVariants) { if (!isPlayer()) return false; Integer sp = Wand.getSP(itemStack); if (sp != null) { return getSkillPoints() >= sp; } int amount = itemStack == null ? 0 :itemStack.getAmount(); if (amount <= 0 ) { return true; } Inventory inventory = getInventory(); ItemStack[] contents = inventory.getContents(); for (ItemStack item : contents) { if (item != null && ((!allowVariants && itemStack.isSimilar(item)) || (allowVariants && itemStack.getType() == item.getType() && (item.getItemMeta() == null || item.getItemMeta().getDisplayName() == null))) && (amount -= item.getAmount()) <= 0) { return true; } } return false; } @Override public int removeItem(ItemStack itemStack) { return removeItem(itemStack, false); } @Override public boolean hasItem(ItemStack itemStack) { return hasItem(itemStack, false); } @Override @Deprecated public Wand getSoulWand() { return null; } @Override public Wand getActiveWand() { if (offhandCast && offhandWand != null) { return offhandWand; } return activeWand; } @Override public Wand getOffhandWand() { return offhandWand; } @Override public com.elmakers.mine.bukkit.api.block.MaterialBrush getBrush() { return brush; } @Override public float getDamageMultiplier() { float maxPowerMultiplier = controller.getMaxDamagePowerMultiplier() - 1; return 1 + (maxPowerMultiplier * getPower()); } @Override public float getRangeMultiplier() { if (activeWand == null) return 1; float maxPowerMultiplier = controller.getMaxRangePowerMultiplier() - 1; float maxPowerMultiplierMax = controller.getMaxRangePowerMultiplierMax(); float multiplier = 1 + (maxPowerMultiplier * getPower()); return Math.min(multiplier, maxPowerMultiplierMax); } @Override public float getConstructionMultiplier() { float maxPowerMultiplier = controller.getMaxConstructionPowerMultiplier() - 1; return 1 + (maxPowerMultiplier * getPower()); } @Override public float getRadiusMultiplier() { if (activeWand == null) return 1; float maxPowerMultiplier = controller.getMaxRadiusPowerMultiplier() - 1; float maxPowerMultiplierMax = controller.getMaxRadiusPowerMultiplierMax(); float multiplier = 1 + (maxPowerMultiplier * getPower()); return Math.min(multiplier, maxPowerMultiplierMax); } @Override public float getMana() { if (controller.useHeroesMana() && isPlayer()) { HeroesManager heroes = controller.getHeroes(); if (heroes != null) { return heroes.getMana(getPlayer()); } } if (offhandCast && offhandWand != null) { return offhandWand.getMana(); } if (activeWand != null) { return activeWand.getMana(); } if (activeClass != null) { return activeClass.getMana(); } return properties.getMana(); } public int getEffectiveManaMax() { if (controller.useHeroesMana() && isPlayer()) { HeroesManager heroes = controller.getHeroes(); if (heroes != null) { return heroes.getMaxMana(getPlayer()); } } if (activeWand != null) { return activeWand.getEffectiveManaMax(); } if (activeClass != null) { return activeClass.getEffectiveManaMax(); } return properties.getEffectiveManaMax(); } public int getEffectiveManaRegeneration() { if (controller.useHeroesMana() && isPlayer()) { HeroesManager heroes = controller.getHeroes(); if (heroes != null) { return heroes.getManaRegen(getPlayer()); } } if (activeWand != null) { return activeWand.getEffectiveManaRegeneration(); } if (activeClass != null) { return activeClass.getEffectiveManaRegeneration(); } return properties.getEffectiveManaRegeneration(); } @Override public void removeMana(float mana) { if (offhandCast && offhandWand != null) { offhandWand.removeMana(mana); } else if (activeWand != null) { activeWand.removeMana(mana); } else if (activeClass != null) { activeClass.removeMana(mana); } else { properties.removeMana(mana); } } @Override public void removeExperience(int xp) { Player player = getPlayer(); if (player == null) return; float expProgress = player.getExp(); int expLevel = player.getLevel(); while ((expProgress > 0 || expLevel > 0) && xp > 0) { if (expProgress > 0) { float expToLevel = Wand.getExpToLevel(expLevel); int expAtLevel = (int)(expProgress * expToLevel); if (expAtLevel > xp) { expAtLevel -= xp; xp = 0; expProgress = expAtLevel / expToLevel; } else { expProgress = 0; xp -= expAtLevel; } } else { xp -= Wand.getExpToLevel(expLevel - 1); expLevel--; if (xp < 0) { expProgress = (float) (-xp) / Wand.getExpToLevel(expLevel); xp = 0; } } } player.setExp(Math.max(0, Math.min(1.0f, expProgress))); player.setLevel(Math.max(0, expLevel)); } @Override public int getLevel() { Player player = getPlayer(); if (player != null) { return player.getLevel(); } return 0; } @Override public void setLevel(int level) { Player player = getPlayer(); if (player != null) { player.setLevel(level); } } @Override public int getExperience() { Player player = getPlayer(); if (player == null) return 0; float expProgress = player.getExp(); int expLevel = player.getLevel(); return Wand.getExperience(expLevel, expProgress); } @Override public void giveExperience(int xp) { Player player = getPlayer(); if (player != null) { player.giveExp(xp); } } public void sendExperience(float exp, int level) { if (virtualExperience && exp == virtualExperienceProgress && level == virtualExperienceLevel) return; Player player = getPlayer(); if (player != null) { CompatibilityUtils.sendExperienceUpdate(player, exp, level); virtualExperience = true; virtualExperienceProgress = exp; virtualExperienceLevel = level; } } public void resetSentExperience() { Player player = getPlayer(); if (player != null) { CompatibilityUtils.sendExperienceUpdate(player, player.getExp(), player.getLevel()); } virtualExperience = false; } public void experienceChanged() { virtualExperience = false; } @Override public boolean addBatch(Batch batch) { if (pendingBatches.size() >= controller.getPendingQueueDepth()) { controller.getLogger().info("Rejected spell cast for " + getName() + ", already has " + pendingBatches.size() + " pending, limit: " + controller.getPendingQueueDepth()); return false; } pendingBatches.addLast(batch); controller.addPending(this); return true; } @Override public void registerEvent(SpellEventType type, Listener spell) { switch (type) { case PLAYER_QUIT: if (!quitListeners.contains(spell)) quitListeners.add(spell); break; case PLAYER_DAMAGE: if (!damageListeners.contains(spell)) damageListeners.add(spell); break; case PLAYER_DEATH: if (!deathListeners.contains(spell)) deathListeners.add(spell); break; } } @Override public void unregisterEvent(SpellEventType type, Listener spell) { switch (type) { case PLAYER_DAMAGE: damageListeners.remove(spell); break; case PLAYER_QUIT: quitListeners.remove(spell); break; case PLAYER_DEATH: deathListeners.remove(spell); break; } } @Override public Player getPlayer() { Player player = _player.get(); return controller.isNPC(player) ? null : player; } @Override public Entity getEntity() { return _entity.get(); } @Override public EntityData getEntityData() { return entityData; } @Override public LivingEntity getLivingEntity() { Entity entity = _entity.get(); return (entity != null && entity instanceof LivingEntity) ? (LivingEntity) entity : null; } @Override public CommandSender getCommandSender() { return _commandSender.get(); } @Override public List<LostWand> getLostWands() { Entity entity = getEntity(); Collection<LostWand> allWands = controller.getLostWands(); List<LostWand> mageWands = new ArrayList<>(); if (entity == null) { return mageWands; } String playerId = entity.getUniqueId().toString(); for (LostWand lostWand : allWands) { String owner = lostWand.getOwnerId(); if (owner != null && owner.equals(playerId)) { mageWands.add(lostWand); } } return mageWands; } @Override public Location getLastDeathLocation() { return lastDeathLocation; } @Override public void showHoloText(Location location, String text, int duration) { // TODO: Broadcast if (!isPlayer()) return; final Player player = getPlayer(); if (hologram == null) { hologram = HoloUtils.createHoloText(location, text); } else { if (hologramIsVisible) { hologram.hide(player); } hologram.teleport(location); hologram.setLabel(text); } hologram.show(player); BukkitScheduler scheduler = Bukkit.getScheduler(); if (duration > 0) { scheduler.scheduleSyncDelayedTask(controller.getPlugin(), new Runnable() { @Override public void run() { hologram.hide(player); hologramIsVisible = false; } }, duration); } } @Override public void enableFallProtection(int ms, Spell protector) { enableFallProtection(ms, 1, protector); } @Override public void enableFallProtection(int ms, int count, Spell protector) { if (ms <= 0 || count <= 0) return; if (protector != null && protector instanceof BaseSpell) { this.fallingSpell = (BaseSpell)protector; } long nextTime = System.currentTimeMillis() + ms; if (nextTime > fallProtection) { fallProtection = nextTime; } if (count > fallProtectionCount) { fallProtectionCount = count; } } @Override public void enableFallProtection(int ms) { enableFallProtection(ms, null); } @Override public void enableSuperProtection(int ms) { if (ms <= 0) return; long nextTime = System.currentTimeMillis() + ms; if (nextTime > superProtectionExpiration) { superProtectionExpiration = nextTime; } } @Override public void clearSuperProtection() { superProtectionExpiration = 0; } public void setLoading(boolean loading) { this.loading = loading; } @Override public void disable() { // Kind of a hack, but the loading flag will prevent the Mage from doing anything further this.loading = true; } @Override public boolean isLoading() { return loading; } public void setUnloading(boolean unloading) { this.unloading = unloading; } public boolean isUnloading() { return unloading; } @Override public boolean hasPending() { if (undoQueue != null && undoQueue.hasScheduled()) return true; if (pendingBatches.size() > 0) return true; return false; } @Override public boolean isValid() { if (!hasEntity) return true; Entity entity = getEntity(); if (entity == null) return false; if (controller.isNPC(entity)) return true; if (entity instanceof Player) { Player player = (Player)entity; return player.isOnline(); } if (entity instanceof LivingEntity) { LivingEntity living = (LivingEntity)entity; return !living.isDead(); } // Automata theoretically handle themselves by sticking around for a while // And forcing themselves to be forgotten // but maybe some extra safety here would be good? return entity.isValid(); } @Override public boolean restoreWand() { if (boundWands.size() == 0) return false; Player player = getPlayer(); if (player == null) return false; Set<String> foundTemplates = new HashSet<>(); ItemStack[] inventory = getInventory().getContents(); for (ItemStack item : inventory) { if (Wand.isWand(item)) { Wand tempWand = controller.getWand(item); String template = tempWand.getTemplateKey(); if (template != null) { foundTemplates.add(template); } } } inventory = player.getEnderChest().getContents(); for (ItemStack item : inventory) { if (Wand.isWand(item)) { Wand tempWand = controller.getWand(item); String template = tempWand.getTemplateKey(); if (template != null) { foundTemplates.add(template); } } } int givenWands = 0; for (Map.Entry<String, Wand> wandEntry : boundWands.entrySet()) { if (foundTemplates.contains(wandEntry.getKey())) continue; givenWands++; ItemStack wandItem = wandEntry.getValue().duplicate().getItem(); wandItem.setAmount(1); giveItem(wandItem); } return givenWands > 0; } @Override public boolean isStealth() { if (isSneaking()) return true; if (activeWand != null && activeWand.isStealth()) return true; return false; } @Override public boolean isSneaking() { Player player = getPlayer(); return (player != null && player.isSneaking()); } @Override public boolean isJumping() { Entity entity = getEntity(); return (entity != null && !entity.isOnGround()); } @Override public ConfigurationSection getData() { if (loading) { return new MemoryConfiguration(); } return data; } public void onGUIDeactivate() { GUIAction previousGUI = gui; gui = null; Player player = getPlayer(); if (player != null) { DeprecatedUtils.updateInventory(player); } if (previousGUI != null) { previousGUI.deactivated(); } } @Override public void activateGUI(GUIAction action, Inventory inventory) { Player player = getPlayer(); if (player != null) { controller.disableItemSpawn(); try { player.closeInventory(); if (inventory != null) { gui = action; player.openInventory(inventory); } } catch (Throwable ex) { ex.printStackTrace(); } controller.enableItemSpawn(); } gui = action; } @Override public void continueGUI(GUIAction action, Inventory inventory) { Player player = getPlayer(); if (player != null) { controller.disableItemSpawn(); try { if (inventory != null) { gui = action; player.openInventory(inventory); } } catch (Throwable ex) { ex.printStackTrace(); } controller.enableItemSpawn(); } gui = action; } @Override public void deactivateGUI() { activateGUI(null, null); } @Override public GUIAction getActiveGUI() { return gui; } @Override public int getDebugLevel() { return debugLevel; } @Override public void setDebugger(CommandSender sender) { this.debugger = sender; } @Override public CommandSender getDebugger() { return debugger; } @Override public void setDebugLevel(int debugLevel) { this.debugLevel = debugLevel; } @Override public void sendDebugMessage(String message) { sendDebugMessage(message, 1); } @Override public void debugPermissions(CommandSender sender, Spell spell) { com.elmakers.mine.bukkit.api.wand.Wand wand = getActiveWand(); Location location = getLocation(); if (spell == null && wand != null) { spell = wand.getActiveSpell(); } sender.sendMessage(ChatColor.GOLD + "Permission check for " + ChatColor.AQUA + getDisplayName()); sender.sendMessage(ChatColor.GOLD + " id " + ChatColor.DARK_AQUA + getId()); sender.sendMessage(ChatColor.GOLD + " at " + ChatColor.AQUA + ChatColor.BLUE + location.getBlockX() + " " + location.getBlockY() + " " + location.getBlockZ() + " " + ChatColor.DARK_BLUE + location.getWorld().getName()); Player player = getPlayer(); boolean hasBypass = false; boolean hasPVPBypass = false; boolean hasBuildBypass = false; boolean hasBreakBypass = false; if (player != null) { hasBypass = player.hasPermission("Magic.bypass"); hasPVPBypass = player.hasPermission("Magic.bypass_pvp"); hasBuildBypass = player.hasPermission("Magic.bypass_build"); sender.sendMessage(ChatColor.AQUA + " Has bypass: " + formatBoolean(hasBypass, true, null)); sender.sendMessage(ChatColor.AQUA + " Has PVP bypass: " + formatBoolean(hasPVPBypass, true, null)); sender.sendMessage(ChatColor.AQUA + " Has Build bypass: " + formatBoolean(hasBuildBypass, true, null)); sender.sendMessage(ChatColor.AQUA + " Has Break bypass: " + formatBoolean(hasBreakBypass, true, null)); } boolean buildPermissionRequired = spell == null ? false : spell.requiresBuildPermission(); boolean breakPermissionRequired = spell == null ? false : spell.requiresBreakPermission(); boolean pvpRestricted = spell == null ? false : spell.isPvpRestricted(); sender.sendMessage(ChatColor.AQUA + " Can build: " + formatBoolean(hasBuildPermission(location.getBlock()), hasBuildBypass || !buildPermissionRequired ? null : true)); sender.sendMessage(ChatColor.AQUA + " Can break: " + formatBoolean(hasBreakPermission(location.getBlock()), hasBreakBypass || !breakPermissionRequired ? null : true)); sender.sendMessage(ChatColor.AQUA + " Can pvp: " + formatBoolean(isPVPAllowed(location), hasPVPBypass || !pvpRestricted ? null : true)); boolean isPlayer = player != null; boolean spellDisguiseRestricted = (spell == null) ? false : spell.isDisguiseRestricted(); sender.sendMessage(ChatColor.AQUA + " Is disguised: " + formatBoolean(controller.isDisguised(getEntity()), null, isPlayer && spellDisguiseRestricted ? true : null)); WorldBorder border = location.getWorld().getWorldBorder(); double borderSize = border.getSize(); // Kind of a hack, meant to prevent this from showing up when there's no border defined if (borderSize < 50000000) { borderSize = borderSize / 2 - border.getWarningDistance(); Location offset = location.subtract(border.getCenter()); boolean isOutsideBorder = (offset.getX() < -borderSize || offset.getX() > borderSize || offset.getZ() < -borderSize || offset.getZ() > borderSize); sender.sendMessage(ChatColor.AQUA + " Is in world border (" + ChatColor.GRAY + borderSize + ChatColor.AQUA + "): " + formatBoolean(!isOutsideBorder, true, false)); } if (spell != null) { sender.sendMessage(ChatColor.AQUA + " Has pnode " + ChatColor.GOLD + spell.getPermissionNode() + ChatColor.AQUA + ": " + formatBoolean(spell.hasCastPermission(player), hasBypass ? null : true)); sender.sendMessage(ChatColor.AQUA + " Region override: " + formatBoolean(controller.getRegionCastPermission(player, spell, location), hasBypass ? null : true)); sender.sendMessage(ChatColor.AQUA + " Field override: " + formatBoolean(controller.getPersonalCastPermission(player, spell, location), hasBypass ? null : true)); com.elmakers.mine.bukkit.api.block.MaterialBrush brush = spell.getBrush(); if (brush != null) { sender.sendMessage(ChatColor.GOLD + " " + spell.getName() + ChatColor.AQUA + " is erase: " + formatBoolean(brush.isErase(), null)); } sender.sendMessage(ChatColor.GOLD + " " + spell.getName() + ChatColor.AQUA + " requires build: " + formatBoolean(spell.requiresBuildPermission(), null, true, true)); sender.sendMessage(ChatColor.GOLD + " " + spell.getName() + ChatColor.AQUA + " requires break: " + formatBoolean(spell.requiresBreakPermission(), null, true, true)); sender.sendMessage(ChatColor.GOLD + " " + spell.getName() + ChatColor.AQUA + " requires pvp: " + formatBoolean(spell.isPvpRestricted(), null, true, true)); sender.sendMessage(ChatColor.GOLD + " " + spell.getName() + ChatColor.AQUA + " allowed while disguised: " + formatBoolean(!spell.isDisguiseRestricted(), null, false, true)); if (spell instanceof BaseSpell) { boolean buildPermission = ((BaseSpell)spell).hasBuildPermission(location.getBlock()); sender.sendMessage(ChatColor.GOLD + " " + spell.getName() + ChatColor.AQUA + " has build: " + formatBoolean(buildPermission, hasBuildBypass || !spell.requiresBuildPermission() ? null : true)); boolean breakPermission = ((BaseSpell)spell).hasBreakPermission(location.getBlock()); sender.sendMessage(ChatColor.GOLD + " " + spell.getName() + ChatColor.AQUA + " has break: " + formatBoolean(breakPermission, hasBreakBypass || !spell.requiresBreakPermission() ? null : true)); } sender.sendMessage(ChatColor.AQUA + " Can cast " + ChatColor.GOLD + spell.getName() + ChatColor.AQUA + ": " + formatBoolean(spell.canCast(location))); } } public static String formatBoolean(Boolean flag, Boolean greenState) { return formatBoolean(flag, greenState, greenState == null ? null : !greenState, false); } public static String formatBoolean(Boolean flag) { return formatBoolean(flag, true, false, false); } public static String formatBoolean(Boolean flag, Boolean greenState, Boolean redState) { return formatBoolean(flag, greenState, redState, false); } public static String formatBoolean(Boolean flag, Boolean greenState, Boolean redState, boolean dark) { if (flag == null) { return ChatColor.GRAY + "none"; } String text = flag ? "true" : "false"; if (greenState != null && Objects.equal(flag, greenState)) { return (dark ? ChatColor.DARK_GREEN : ChatColor.GREEN) + text; } else if (redState != null && Objects.equal(flag, redState)) { return (dark ? ChatColor.DARK_RED : ChatColor.RED) + text; } return ChatColor.GRAY + text; } @Override public void sendDebugMessage(String message, int level) { if (debugLevel >= level && message != null && !message.isEmpty()) { CommandSender sender = debugger; if (sender == null) { sender = getCommandSender(); } if (sender != null) { sender.sendMessage(controller.getMessagePrefix() + message); } } } public void clearRespawnInventories() { respawnArmor = null; respawnInventory = null; } public void restoreRespawnInventories() { Player player = getPlayer(); if (player == null) { return; } PlayerInventory inventory = player.getInventory(); if (respawnArmor != null) { ItemStack[] armor = inventory.getArmorContents(); for (Map.Entry<Integer, ItemStack> entry : respawnArmor.entrySet()) { armor[entry.getKey()] = entry.getValue(); } player.getInventory().setArmorContents(armor); } if (respawnInventory != null) { for (Map.Entry<Integer, ItemStack> entry : respawnInventory.entrySet()) { inventory.setItem(entry.getKey(), entry.getValue()); } } clearRespawnInventories(); controller.getPlugin().getServer().getScheduler().runTaskLater(controller.getPlugin(), new Runnable() { @Override public void run() { armorUpdated(); } }, 1); } public void addToRespawnInventory(int slot, ItemStack item) { if (respawnInventory == null) { respawnInventory = new HashMap<>(); } respawnInventory.put(slot, item); } public void addToRespawnArmor(int slot, ItemStack item) { if (respawnArmor == null) { respawnArmor = new HashMap<>(); } respawnArmor.put(slot, item); } @Override public void giveItem(ItemStack itemStack) { if (InventoryUtils.isEmpty(itemStack)) return; // Check for wand upgrades if appropriate Wand activeWand = getActiveWand(); if (activeWand != null) { if (activeWand.addItem(itemStack)) { return; } } if (hasStoredInventory()) { addToStoredInventory(itemStack); return; } // Place directly in hand if possible Player player = getPlayer(); if (player == null) return; PlayerInventory inventory = player.getInventory(); ItemStack inHand = inventory.getItemInMainHand(); if (inHand == null || inHand.getType() == Material.AIR) { inventory.setItemInMainHand(itemStack); // Get the new item reference - // it might change when added to an Inventory! :| itemStack = inventory.getItemInMainHand(); if (Wand.isWand(itemStack)) { checkWand(); } else { if (itemStack.getType() == Material.MAP) { setLastHeldMapId(itemStack.getDurability()); } } } else { HashMap<Integer, ItemStack> returned = player.getInventory().addItem(itemStack); if (returned.size() > 0) { player.getWorld().dropItem(player.getLocation(), itemStack); } } } public void armorUpdated() { sendDebugMessage("Checking armor"); activeArmor.clear(); Player player = getPlayer(); if (player != null) { ItemStack[] armor = player.getInventory().getArmorContents(); for (int index = 0; index < armor.length; index++) { ItemStack armorItem = armor[index]; if (Wand.isWand(armorItem)) { sendDebugMessage(" Found magic armor in slot " + index); activeArmor.put(index, controller.getWand(armorItem)); } } } if (activeWand != null) { activeWand.armorUpdated(); } updateEquipmentEffects(); } protected void updateEquipmentEffects() { damageReduction = 0; damageReductionPhysical = 0; damageReductionProjectiles = 0; damageReductionFalling = 0; damageReductionFire = 0; damageReductionExplosions = 0; spMultiplier = 1; List<PotionEffectType> currentEffects = new ArrayList<>(effectivePotionEffects.keySet()); LivingEntity entity = getLivingEntity(); effectivePotionEffects.clear(); if (activeWand != null && !activeWand.isPassive()) { damageReduction += activeWand.getDamageReduction(); damageReductionPhysical += activeWand.getDamageReductionPhysical(); damageReductionProjectiles += activeWand.getDamageReductionProjectiles(); damageReductionFalling += activeWand.getDamageReductionFalling(); damageReductionFire += activeWand.getDamageReductionFire(); damageReductionExplosions += activeWand.getDamageReductionExplosions(); effectivePotionEffects.putAll(activeWand.getPotionEffects()); spMultiplier *= activeWand.getSPMultiplier(); } // Don't add these together so things stay balanced! if (offhandWand != null && !offhandWand.isPassive()) { damageReduction = Math.max(damageReduction, offhandWand.getDamageReduction()); damageReductionPhysical += Math.max(damageReductionPhysical, offhandWand.getDamageReductionPhysical()); damageReductionProjectiles += Math.max(damageReductionProjectiles, offhandWand.getDamageReductionProjectiles()); damageReductionFalling += Math.max(damageReductionFalling, offhandWand.getDamageReductionFalling()); damageReductionFire += Math.max(damageReductionFire, offhandWand.getDamageReductionFire()); damageReductionExplosions += Math.max(damageReductionExplosions, offhandWand.getDamageReductionExplosions()); effectivePotionEffects.putAll(offhandWand.getPotionEffects()); spMultiplier *= offhandWand.getSPMultiplier(); } for (Wand armorWand : activeArmor.values()) { if (armorWand != null) { damageReduction += armorWand.getDamageReduction(); damageReductionPhysical += armorWand.getDamageReductionPhysical(); damageReductionProjectiles += armorWand.getDamageReductionProjectiles(); damageReductionFalling += armorWand.getDamageReductionFalling(); damageReductionFire += armorWand.getDamageReductionFire(); damageReductionExplosions += armorWand.getDamageReductionExplosions(); effectivePotionEffects.putAll(armorWand.getPotionEffects()); spMultiplier *= armorWand.getSPMultiplier(); } } damageReduction = Math.min(damageReduction, 1); damageReductionPhysical = Math.min(damageReductionPhysical, 1); damageReductionProjectiles = Math.min(damageReductionProjectiles, 1); damageReductionFalling = Math.min(damageReductionFalling, 1); damageReductionFire = Math.min(damageReductionFire, 1); damageReductionExplosions = Math.min(damageReductionExplosions, 1); if (entity != null) { for (PotionEffectType effectType : currentEffects) { if (!effectivePotionEffects.containsKey(effectType)) { entity.removePotionEffect(effectType); } } for (Map.Entry<PotionEffectType, Integer> effects : effectivePotionEffects.entrySet()) { PotionEffect effect = new PotionEffect(effects.getKey(), Integer.MAX_VALUE, effects.getValue(), true, false); CompatibilityUtils.applyPotionEffect(entity, effect); } } } public Collection<Wand> getActiveArmor() { return activeArmor.values(); } @Override public void deactivate() { deactivateWand(); deactivateAllSpells(true, true); removeActiveEffects(); } protected void deactivateWand() { // Close the wand inventory to make sure the player's normal inventory gets saved if (activeWand != null) { activeWand.deactivate(); } } @Override public void undoScheduled() { // Immediately rollback any auto-undo spells if (undoQueue != null) { int undid = undoQueue.undoScheduled(); if (undid != 0) { controller.info("Player " + getName() + " logging out, auto-undid " + undid + " spells"); } } int finished = finishPendingUndo(); if (finished != 0) { controller.info("Player " + getName() + " logging out, fast-forwarded undo for " + finished + " spells"); } if (undoQueue != null) { if (!undoQueue.isEmpty()) { if (controller.commitOnQuit()) { controller.info("Player logging out, committing constructions: " + getName()); undoQueue.commit(); } else { controller.info("Player " + getName() + " logging out with " + undoQueue.getSize() + " spells in their undo queue"); } } } } @Override public void removeItemsWithTag(String tag) { Player player = getPlayer(); if (player == null) return; PlayerInventory inventory = player.getInventory(); ItemStack[] contents = inventory.getContents(); for (int index = 0; index < contents.length; index++) { ItemStack item = contents[index]; if (item != null && item.getType() != Material.AIR && InventoryUtils.hasMeta(item, tag)) { inventory.setItem(index, null); } } boolean modified = false; ItemStack[] armor = inventory.getArmorContents(); for (int index = 0; index < armor.length; index++) { ItemStack item = armor[index]; if (item != null && item.getType() != Material.AIR && InventoryUtils.hasMeta(item, tag)) { modified = true; armor[index] = null; } } if (modified) { inventory.setArmorContents(armor); } } @Override public void setQuiet(boolean quiet) { this.quiet = quiet; } @Override public boolean isQuiet() { return quiet; } public void setDestinationWarp(String warp) { destinationWarp = warp; } @Override public boolean isAtMaxSkillPoints() { return getSkillPoints() >= controller.getSPMaximum(); } @Override public int getSkillPoints() { if (!data.contains(SKILL_POINT_KEY)) { data.set(SKILL_POINT_KEY, DEFAULT_SP); } // .. I thought Configuration section would auto-convert? I guess not! if (data.isString(SKILL_POINT_KEY)) { try { data.set(SKILL_POINT_KEY, Integer.parseInt(data.getString(SKILL_POINT_KEY))); } catch (Exception ex) { data.set(SKILL_POINT_KEY, 0); } } return data.getInt(SKILL_POINT_KEY); } @Override public void addSkillPoints(int delta) { int current = getSkillPoints(); String earnMessage = controller.getMessages().get("mage.earned_sp"); if (delta > 0 && earnMessage != null && !earnMessage.isEmpty()) { sendMessage(earnMessage.replace("$amount", Integer.toString(delta))); } setSkillPoints(current + delta); } @Override public void setSkillPoints(int amount) { // We don't allow negative skill points. boolean firstEarn = !data.contains(SKILL_POINT_KEY); amount = Math.max(amount, 0); int limit = controller.getSPMaximum(); if (limit > 0) { amount = Math.min(amount, limit); } data.set(SKILL_POINT_KEY, amount); if (activeWand != null && Wand.spMode != WandManaMode.NONE && activeWand.usesSP()) { if (firstEarn) { sendMessage(activeWand.getMessage("sp_instructions")); } activeWand.updateMana(); } } @Override public com.elmakers.mine.bukkit.api.wand.Wand getBoundWand(String template) { return boundWands.get(template); } @Override public WandUpgradePath getBoundWandPath(String templateKey) { com.elmakers.mine.bukkit.api.wand.Wand boundWand = boundWands.get(templateKey); if (boundWand != null) { return boundWand.getPath(); } return null; } public void setEntityData(EntityData entityData) { this.entityData = entityData; } @Override public List<Wand> getBoundWands() { return ImmutableList.copyOf(boundWands.values()); } public void updateHotbarStatus() { Player player = getPlayer(); if (player != null) { Location location = getLocation(); for (int i = 0; i < Wand.HOTBAR_SIZE; i++) { ItemStack spellItem = player.getInventory().getItem(i); String spellKey = Wand.getSpell(spellItem); if (spellKey != null) { Spell spell = getSpell(spellKey); if (spell != null) { int targetAmount = 1; long remainingCooldown = spell.getRemainingCooldown(); CastingCost requiredCost = spell.getRequiredCost(); boolean canCast = spell.canCast(location); if (canCast && remainingCooldown == 0 && requiredCost == null) { targetAmount = 1; } else if (!canCast) { targetAmount = 99; } else { canCast = remainingCooldown == 0; targetAmount = Wand.LiveHotbarCooldown ? (int)Math.min(Math.ceil((double)remainingCooldown / 1000), 99) : 99; if (Wand.LiveHotbarCooldown && requiredCost != null) { int mana = requiredCost.getMana(); if (mana > 0) { if (mana <= getEffectiveManaMax() && getEffectiveManaRegeneration() > 0) { float remainingMana = mana - getMana(); canCast = canCast && remainingMana <= 0; int targetManaTime = (int)Math.min(Math.ceil(remainingMana / getEffectiveManaRegeneration()), 99); targetAmount = Math.max(targetManaTime, targetAmount); } else { targetAmount = 99; canCast = false; } } } } if (targetAmount == 0) targetAmount = 1; boolean setAmount = false; MaterialAndData disabledIcon = spell.getDisabledIcon(); MaterialAndData spellIcon = spell.getIcon(); String urlIcon = spell.getIconURL(); String disabledUrlIcon = spell.getDisabledIconURL(); boolean usingURLIcon = (controller.isUrlIconsEnabled() || spellIcon == null || spellIcon.getMaterial() == Material.AIR) && urlIcon != null && !urlIcon.isEmpty(); if (disabledIcon != null && spellIcon != null && !usingURLIcon) { if (!canCast) { if (disabledIcon.isValid() && (disabledIcon.getMaterial() != spellItem.getType() || disabledIcon.getData() != spellItem.getDurability())) { disabledIcon.applyToItem(spellItem); } if (targetAmount == 99) { if (spellItem.getAmount() != 1) { spellItem.setAmount(1); } setAmount = true; } } else { if (spellIcon.isValid() && (spellIcon.getMaterial() != spellItem.getType() || spellIcon.getData() != spellItem.getDurability())) { spellIcon.applyToItem(spellItem); } } } else if (usingURLIcon && disabledUrlIcon != null && !disabledUrlIcon.isEmpty() && spellItem.getType() == Material.SKULL_ITEM) { String currentURL = InventoryUtils.getSkullURL(spellItem); if (!canCast) { if (!disabledUrlIcon.equals(currentURL)) { InventoryUtils.setNewSkullURL(spellItem, disabledUrlIcon); player.getInventory().setItem(i, spellItem); } if (targetAmount == 99) { if (spellItem.getAmount() != 1) { spellItem.setAmount(1); } setAmount = true; } } else { if (!urlIcon.equals(currentURL)) { InventoryUtils.setNewSkullURL(spellItem, urlIcon); player.getInventory().setItem(i, spellItem); } } } if (!setAmount && spellItem.getAmount() != targetAmount) { spellItem.setAmount(targetAmount); } } } } } } public long getLastBlockTime() { return lastBlockTime; } public void setLastBlockTime(long ms) { lastBlockTime = ms; } @Override public boolean isReflected(double angle) { if (activeWand != null && activeWand.isReflected(angle)) { return true; } if (offhandWand != null && offhandWand.isReflected(angle)) { return true; } return false; } @Override public boolean isBlocked(double angle) { if (activeWand != null && activeWand.isBlocked(angle)) { return true; } if (offhandWand != null && offhandWand.isBlocked(angle)) { return true; } return false; } @Override public float getSPMultiplier() { return spMultiplier; } @Override public @Nonnull MageProperties getProperties() { return properties; } @Override public double getVehicleMovementDirection() { LivingEntity li = getLivingEntity(); if (li == null) return 0.0f; return CompatibilityUtils.getForwardMovement(li); } @Override public double getVehicleStrafeDirection() { LivingEntity li = getLivingEntity(); if (li == null) return 0.0f; return CompatibilityUtils.getStrafeMovement(li); } @Override public boolean isVehicleJumping() { LivingEntity li = getLivingEntity(); if (li == null) return false; return CompatibilityUtils.isJumping(li); } @Override public void setVanished(boolean vanished) { Player thisPlayer = getPlayer(); if (thisPlayer != null && isVanished != vanished) { for (Player player : Bukkit.getOnlinePlayers()) { if (vanished) { player.hidePlayer(thisPlayer); } else { player.showPlayer(thisPlayer); } } } isVanished = vanished; } @Override public boolean isVanished() { return isVanished; } @Override public void setGlidingAllowed(boolean allow) { glidingAllowed = allow; } @Override public boolean isGlidingAllowed() { return glidingAllowed; } }
Magic/src/main/java/com/elmakers/mine/bukkit/magic/Mage.java
package com.elmakers.mine.bukkit.magic; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import com.elmakers.mine.bukkit.action.TeleportTask; import com.elmakers.mine.bukkit.api.action.GUIAction; import com.elmakers.mine.bukkit.api.batch.SpellBatch; import com.elmakers.mine.bukkit.api.block.MaterialAndData; import com.elmakers.mine.bukkit.api.data.BrushData; import com.elmakers.mine.bukkit.api.data.MageData; import com.elmakers.mine.bukkit.api.data.SpellData; import com.elmakers.mine.bukkit.api.data.UndoData; import com.elmakers.mine.bukkit.api.effect.SoundEffect; import com.elmakers.mine.bukkit.api.event.WandActivatedEvent; import com.elmakers.mine.bukkit.api.magic.CastSourceLocation; import com.elmakers.mine.bukkit.api.spell.CastingCost; import com.elmakers.mine.bukkit.api.wand.WandTemplate; import com.elmakers.mine.bukkit.api.wand.WandUpgradePath; import com.elmakers.mine.bukkit.effect.HoloUtils; import com.elmakers.mine.bukkit.effect.Hologram; import com.elmakers.mine.bukkit.entity.EntityData; import com.elmakers.mine.bukkit.heroes.HeroesManager; import com.elmakers.mine.bukkit.spell.ActionSpell; import com.elmakers.mine.bukkit.spell.BaseSpell; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.DeprecatedUtils; import com.elmakers.mine.bukkit.utility.InventoryUtils; import com.elmakers.mine.bukkit.api.wand.WandAction; import com.elmakers.mine.bukkit.wand.WandManaMode; import com.elmakers.mine.bukkit.wand.WandMode; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import de.slikey.effectlib.util.VectorUtils; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.entity.Entity; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityCombustEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.player.PlayerEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.MainHand; import org.bukkit.inventory.PlayerInventory; import org.bukkit.plugin.Plugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.util.Vector; import com.elmakers.mine.bukkit.api.batch.Batch; import com.elmakers.mine.bukkit.api.block.UndoList; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.api.spell.CostReducer; import com.elmakers.mine.bukkit.api.spell.MageSpell; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.api.spell.SpellEventType; import com.elmakers.mine.bukkit.api.spell.SpellResult; import com.elmakers.mine.bukkit.api.spell.SpellTemplate; import com.elmakers.mine.bukkit.api.wand.LostWand; import com.elmakers.mine.bukkit.block.MaterialBrush; import com.elmakers.mine.bukkit.block.UndoQueue; import com.elmakers.mine.bukkit.batch.UndoBatch; import com.elmakers.mine.bukkit.wand.Wand; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class Mage implements CostReducer, com.elmakers.mine.bukkit.api.magic.Mage { protected static int AUTOMATA_ONLINE_TIMEOUT = 5000; public static int UPDATE_FREQUENCY = 5; public static int CHANGE_WORLD_EQUIP_COOLDOWN = 1000; public static int JUMP_EFFECT_FLIGHT_EXEMPTION_DURATION = 0; public static int OFFHAND_CAST_RANGE = 32; public static int OFFHAND_CAST_COOLDOWN = 500; public static boolean DEACTIVATE_WAND_ON_WORLD_CHANGE = false; public static int DEFAULT_SP = 0; final static private Set<Material> EMPTY_MATERIAL_SET = new HashSet<>(); private static String defaultMageName = "Mage"; private static String SKILL_POINT_KEY = "sp"; public static CastSourceLocation DEFAULT_CAST_LOCATION = CastSourceLocation.MAINHAND; public static Vector DEFAULT_CAST_OFFSET = new Vector(0.5, -0.5, 0); public static double SNEAKING_CAST_OFFSET = -0.2; protected final String id; private final MageProperties properties; private final Map<String, MageClass> classes = new HashMap<>(); protected ConfigurationSection data = new MemoryConfiguration(); protected Map<String, SpellData> spellData = new HashMap<>(); protected WeakReference<Player> _player; protected WeakReference<Entity> _entity; protected WeakReference<CommandSender> _commandSender; protected boolean hasEntity; protected String playerName; protected final MagicController controller; protected CommandSender debugger; protected HashMap<String, MageSpell> spells = new HashMap<>(); private Wand activeWand = null; private Wand offhandWand = null; private MageClass activeClass = null; private boolean offhandCast = false; private Map<String, Wand> boundWands = new HashMap<>(); private final Collection<Listener> quitListeners = new HashSet<>(); private final Collection<Listener> deathListeners = new HashSet<>(); private final Collection<Listener> damageListeners = new HashSet<>(); private final Set<MageSpell> activeSpells = new HashSet<>(); private UndoQueue undoQueue = null; private LinkedList<Batch> pendingBatches = new LinkedList<>(); private boolean loading = false; private boolean unloading = false; private int debugLevel = 0; private boolean quiet = false; private EntityData entityData; private long lastTick; private int updateTicks = 0; private Location lastLocation; private Vector velocity = new Vector(); private long lastBlockTime; private long ignoreItemActivationUntil = 0; private Map<PotionEffectType, Integer> effectivePotionEffects = new HashMap<>(); protected float damageReduction = 0; protected float damageReductionPhysical = 0; protected float damageReductionProjectiles = 0; protected float damageReductionFalling = 0; protected float damageReductionFire = 0; protected float damageReductionExplosions = 0; protected boolean isVanished = false; protected long superProtectionExpiration = 0; private Map<Integer, Wand> activeArmor = new HashMap<>(); private Location location; private float costReduction = 0; private float cooldownReduction = 0; private long cooldownExpiration = 0; private float powerMultiplier = 1; private float magePowerBonus = 0; private float spMultiplier = 1; private long lastClick = 0; private long lastCast = 0; private long lastOffhandCast = 0; private long blockPlaceTimeout = 0; private Location lastDeathLocation = null; private final MaterialBrush brush; private long fallProtection = 0; private long fallProtectionCount = 1; private BaseSpell fallingSpell = null; private boolean gaveWelcomeWand = false; private GUIAction gui = null; private Hologram hologram; private boolean hologramIsVisible = false; private Map<Integer, ItemStack> respawnInventory; private Map<Integer, ItemStack> respawnArmor; private List<ItemStack> restoreInventory; private boolean restoreOpenWand; private Float restoreExperience; private Integer restoreLevel; private boolean virtualExperience = false; private float virtualExperienceProgress = 0.0f; private int virtualExperienceLevel = 0; private boolean glidingAllowed = false; private String destinationWarp; public Mage(String id, MagicController controller) { this.id = id; this.controller = controller; this.brush = new MaterialBrush(this, Material.DIRT, (byte) 0); this.properties = new MageProperties(this); _player = new WeakReference<>(null); _entity = new WeakReference<>(null); _commandSender = new WeakReference<>(null); hasEntity = false; } public void setCostReduction(float reduction) { costReduction = reduction; } @Override public boolean hasStoredInventory() { return activeWand != null && activeWand.hasStoredInventory(); } @Override public Set<Spell> getActiveSpells() { return new HashSet<Spell>(activeSpells); } public Inventory getStoredInventory() { return activeWand != null ? activeWand.getStoredInventory() : null; } @Override public void setLocation(Location location) { LivingEntity entity = getLivingEntity(); if (entity != null && location != null) { entity.teleport(location); return; } this.location = location; } public void setLocation(Location location, boolean direction) { if (!direction) { if (this.location == null) { this.location = location; } else { this.location.setX(location.getX()); this.location.setY(location.getY()); this.location.setZ(location.getZ()); } } else { this.location = location; } } public void clearCache() { if (brush != null) { brush.clearSchematic(); } } public void setCooldownReduction(float reduction) { cooldownReduction = reduction; } @Override public void setPowerMultiplier(float multiplier) { powerMultiplier = multiplier; } @Override public float getPowerMultiplier() { return powerMultiplier; } public boolean usesMana() { return activeWand == null ? false : activeWand.usesMana(); } public boolean addToStoredInventory(ItemStack item) { return (activeWand == null ? false : activeWand.addToStoredInventory(item)); } public boolean cancelSelection() { boolean result = false; if (!activeSpells.isEmpty()) { List<MageSpell> active = new ArrayList<>(activeSpells); for (MageSpell spell : active) { result = spell.cancelSelection() || result; } } return result; } public void onPlayerQuit(PlayerEvent event) { Player player = getPlayer(); if (player == null || player != event.getPlayer()) { return; } // Must allow listeners to remove themselves during the event! List<Listener> active = new ArrayList<>(quitListeners); for (Listener listener : active) { callEvent(listener, event); } } public void onPlayerDeath(EntityDeathEvent event) { Player player = getPlayer(); if (player == null || player != event.getEntity()) { return; } if (!player.hasMetadata("arena")) { lastDeathLocation = player.getLocation(); } List<Listener> active = new ArrayList<>(deathListeners); for (Listener listener : active) { callEvent(listener, event); } } public void onPlayerCombust(EntityCombustEvent event) { if (activeWand != null && activeWand.getDamageReductionFire() > 0) { event.getEntity().setFireTicks(0); event.setCancelled(true); } } protected void callEvent(Listener listener, Event event) { for (Method method : listener.getClass().getMethods()) { if (method.isAnnotationPresent(EventHandler.class)) { Class<? extends Object>[] parameters = method.getParameterTypes(); if (parameters.length == 1 && parameters[0].isAssignableFrom(event.getClass())) { try { method.invoke(listener, event); } catch (Exception ex) { ex.printStackTrace(); } } } } } public void onPlayerDamage(EntityDamageEvent event) { Player player = getPlayer(); if (player == null) { return; } // Send on to any registered spells List<Listener> active = new ArrayList<>(damageListeners); for (Listener listener : active) { callEvent(listener, event); if (event.isCancelled()) break; } EntityDamageEvent.DamageCause cause = event.getCause(); if (cause == EntityDamageEvent.DamageCause.FALL) { if (fallProtectionCount > 0 && fallProtection > 0 && fallProtection > System.currentTimeMillis()) { event.setCancelled(true); fallProtectionCount--; if (fallingSpell != null) { double scale = 1; LivingEntity li = getLivingEntity(); if (li != null) { scale = event.getDamage() / li.getMaxHealth(); } fallingSpell.playEffects("land", (float)scale, player.getLocation().getBlock().getRelative(BlockFace.DOWN)); } if (fallProtectionCount <= 0) { fallProtection = 0; fallingSpell = null; } return; } else { fallingSpell = null; } } if (isSuperProtected()) { event.setCancelled(true); if (player.getFireTicks() > 0) { player.setFireTicks(0); } return; } if (event.isCancelled()) return; // First check for damage reduction float reduction = 0; reduction = damageReduction * controller.getMaxDamageReduction(); switch (cause) { case CONTACT: case ENTITY_ATTACK: reduction += damageReductionPhysical * controller.getMaxDamageReductionPhysical(); break; case PROJECTILE: reduction += damageReductionProjectiles * controller.getMaxDamageReductionProjectiles(); break; case FALL: reduction += damageReductionFalling * controller.getMaxDamageReductionFalling(); break; case FIRE: case FIRE_TICK: case LAVA: // Also put out fire if they have fire protection of any kind. if (damageReductionFire > 0 && player.getFireTicks() > 0) { player.setFireTicks(0); } reduction += damageReductionFire * controller.getMaxDamageReductionFire(); break; case BLOCK_EXPLOSION: case ENTITY_EXPLOSION: reduction += damageReductionExplosions * controller.getMaxDamageReductionExplosions(); default: break; } if (reduction >= 1) { event.setCancelled(true); return; } double damage = event.getDamage(); if (reduction > 0) { damage = (1.0f - reduction) * damage; if (damage <= 0) damage = 0.1; event.setDamage(damage); } if (damage > 0) { for (Iterator<Batch> iterator = pendingBatches.iterator(); iterator.hasNext();) { Batch batch = iterator.next(); if (!(batch instanceof SpellBatch)) continue; SpellBatch spellBatch = (SpellBatch)batch; Spell spell = spellBatch.getSpell(); double cancelOnDamage = spell.cancelOnDamage(); if (cancelOnDamage > 0 && cancelOnDamage < damage) { spell.cancel(); batch.finish(); iterator.remove(); } } } } @Override public void unbindAll() { boundWands.clear(); } @Override public void unbind(com.elmakers.mine.bukkit.api.wand.Wand wand) { unbind(wand.getTemplateKey()); } @Override public boolean unbind(String template) { if (template != null) { return boundWands.remove(template) != null; } return false; } public void deactivateWand(Wand wand) { if (wand == activeWand) { setActiveWand(null); } if (wand == offhandWand) { setOffhandWand(null); } } public void onTeleport(PlayerTeleportEvent event) { if (DEACTIVATE_WAND_ON_WORLD_CHANGE) { Location from = event.getFrom(); Location to = event.getTo(); if (from.getWorld().equals(to.getWorld())) { return; } deactivateWand(); } } public void onChangeWorld() { checkWandNextTick(true); if (CHANGE_WORLD_EQUIP_COOLDOWN > 0) { ignoreItemActivationUntil = System.currentTimeMillis() + CHANGE_WORLD_EQUIP_COOLDOWN; } } public void activateIcon(Wand activeWand, ItemStack icon) { if (System.currentTimeMillis() < ignoreItemActivationUntil) { return; } // Check for spell or material selection if (icon != null && icon.getType() != Material.AIR) { com.elmakers.mine.bukkit.api.spell.Spell spell = getSpell(Wand.getSpell(icon)); if (spell != null) { boolean isQuickCast = spell.isQuickCast() && !activeWand.isQuickCastDisabled(); isQuickCast = isQuickCast || (activeWand.getMode() == WandMode.CHEST && activeWand.isQuickCast()); if (isQuickCast) { activeWand.cast(spell); } else { activeWand.setActiveSpell(spell.getKey()); } } else if (Wand.isBrush(icon)){ activeWand.setActiveBrush(icon); } } else { activeWand.setActiveSpell(""); } DeprecatedUtils.updateInventory(getPlayer()); } private void setActiveWand(Wand activeWand) { // Avoid deactivating a wand by mistake, and avoid infinite recursion on null! if (this.activeWand == activeWand) return; this.activeWand = activeWand; if (activeWand != null && activeWand.isBound() && activeWand.canUse(getPlayer())) { addBound(activeWand); } blockPlaceTimeout = System.currentTimeMillis() + 200; updateEquipmentEffects(); if (activeWand != null) { WandActivatedEvent activatedEvent = new WandActivatedEvent(this, activeWand); Bukkit.getPluginManager().callEvent(activatedEvent); } } private void setOffhandWand(Wand offhandWand) { // Avoid deactivating a wand by mistake, and avoid infinite recursion on null! if (this.offhandWand == offhandWand) return; this.offhandWand = offhandWand; if (offhandWand != null && offhandWand.isBound() && offhandWand.canUse(getPlayer())) { addBound(offhandWand); } blockPlaceTimeout = System.currentTimeMillis() + 200; updateEquipmentEffects(); if (offhandWand != null) { WandActivatedEvent activatedEvent = new WandActivatedEvent(this, offhandWand); Bukkit.getPluginManager().callEvent(activatedEvent); } } @Override public boolean tryToOwn(com.elmakers.mine.bukkit.api.wand.Wand wand) { if (isPlayer() && wand instanceof Wand && ((Wand)wand).tryToOwn(getPlayer())) { addBound((Wand)wand); return true; } return false; } protected void addBound(Wand wand) { WandTemplate template = wand.getTemplate(); if (template != null && template.isRestorable()) { boundWands.put(template.getKey(), wand); } } public long getBlockPlaceTimeout() { return blockPlaceTimeout; } /** * Send a message to this Mage when a spell is cast. * * @param message The message to send */ @Override public void castMessage(String message) { if (!controller.showCastMessages()) return; sendMessage(controller.getCastMessagePrefix(), message); } /** * Send a message to this Mage. * <p/> * Use this to send messages to the player that are important. * * @param message The message to send */ @Override public void sendMessage(String message) { sendMessage(controller.getMessagePrefix(), message); } public void sendMessage(String prefix, String message) { if (message == null || message.length() == 0 || quiet || !controller.showMessages()) return; Player player = getPlayer(); boolean isTitle = false; boolean isActionBar = false; if (prefix.startsWith("a:")) { isActionBar = true; prefix = prefix.substring(2); } else if (prefix.startsWith("t:")) { isTitle = true; prefix = prefix.substring(2); } if (message.startsWith("a:")) { isActionBar = true; // message overrides prefix isTitle = false; message = message.substring(2); } else if (message.startsWith("t:")) { isTitle = true; // message overrides prefix isActionBar = false; message = message.substring(2); } String fullMessage = prefix + message; if (isTitle && player != null) { CompatibilityUtils.sendTitle(player, fullMessage, null, -1, -1, -1); return; } if (isActionBar && player != null) { CompatibilityUtils.sendActionBar(player, fullMessage); return; } CommandSender sender = getCommandSender(); if (sender != null) { sender.sendMessage(fullMessage); } } public void clearBuildingMaterial() { brush.setMaterial(controller.getDefaultMaterial(), (byte) 1); } @Override public void playSoundEffect(SoundEffect soundEffect) { if (!controller.soundsEnabled() || soundEffect == null) return; soundEffect.play(controller.getPlugin(), getEntity()); } @Override public UndoQueue getUndoQueue() { if (undoQueue == null) { undoQueue = new UndoQueue(this); undoQueue.setMaxSize(controller.getUndoQueueDepth()); } return undoQueue; } @Override public UndoList getLastUndoList() { if (undoQueue == null || undoQueue.isEmpty()) return null; return undoQueue.getLast(); } @Override public boolean prepareForUndo(com.elmakers.mine.bukkit.api.block.UndoList undoList) { if (undoList == null) return false; if (undoList.bypass()) return false; UndoQueue queue = getUndoQueue(); queue.add(undoList); return true; } @Override public boolean registerForUndo(com.elmakers.mine.bukkit.api.block.UndoList undoList) { if (!prepareForUndo(undoList)) return false; int autoUndo = controller.getAutoUndoInterval(); if (autoUndo > 0 && undoList.getScheduledUndo() == 0) { undoList.setScheduleUndo(autoUndo); } else { undoList.updateScheduledUndo(); } if (!undoList.hasBeenScheduled() && undoList.isScheduled() && undoList.hasChanges()) { controller.scheduleUndo(undoList); } return true; } @Override public void addUndoBatch(com.elmakers.mine.bukkit.api.batch.UndoBatch batch) { pendingBatches.addLast(batch); controller.addPending(this); } protected void setPlayer(Player player) { if (player != null) { playerName = player.getName(); this._player = new WeakReference<>(player); this._entity = new WeakReference<Entity>(player); this._commandSender = new WeakReference<CommandSender>(player); hasEntity = true; } else { this._player.clear(); this._entity.clear(); this._commandSender.clear(); hasEntity = false; } } protected void setEntity(Entity entity) { if (entity != null) { playerName = entity.getType().name().toLowerCase().replace("_", " "); if (entity instanceof LivingEntity) { LivingEntity li = (LivingEntity) entity; String customName = li.getCustomName(); if (customName != null && customName.length() > 0) { playerName = customName; } } this._entity = new WeakReference<>(entity); hasEntity = true; } else { this._entity.clear(); hasEntity = false; } } protected void setCommandSender(CommandSender sender) { if (sender != null) { this._commandSender = new WeakReference<>(sender); if (sender instanceof BlockCommandSender) { BlockCommandSender commandBlock = (BlockCommandSender) sender; playerName = commandBlock.getName(); Location location = getLocation(); if (location == null) { location = commandBlock.getBlock().getLocation(); } else { Location blockLocation = commandBlock.getBlock().getLocation(); location.setX(blockLocation.getX()); location.setY(blockLocation.getY()); location.setZ(blockLocation.getZ()); } setLocation(location, false); } else { setLocation(null); } } else { this._commandSender.clear(); setLocation(null); } } protected void onLoad(MageData data) { try { Collection<SpellData> spellDataList = data == null ? null : data.getSpellData(); if (spellDataList != null) { for (SpellData spellData : spellDataList) { this.spellData.put(spellData.getKey().getKey(), spellData); } } // Load player-specific data Player player = getPlayer(); if (player != null) { if (controller.isInventoryBackupEnabled()) { if (restoreInventory != null) { controller.getLogger().info("Restoring saved inventory for player " + player.getName() + " - did the server not shut down properly?"); if (activeWand != null) { activeWand.deactivate(); } Inventory inventory = player.getInventory(); for (int slot = 0; slot < restoreInventory.size(); slot++) { Object item = restoreInventory.get(slot); if (item instanceof ItemStack) { inventory.setItem(slot, (ItemStack) item); } else { inventory.setItem(slot, null); } } restoreInventory = null; } if (restoreExperience != null) { player.setExp(restoreExperience); restoreExperience = null; } if (restoreLevel != null) { player.setLevel(restoreLevel); restoreLevel = null; } } if (activeWand == null) { String welcomeWand = controller.getWelcomeWand(); if (!gaveWelcomeWand && welcomeWand.length() > 0) { gaveWelcomeWand = true; Wand wand = Wand.createWand(controller, welcomeWand); if (wand != null) { wand.takeOwnership(player); giveItem(wand.getItem()); controller.getLogger().info("Gave welcome wand " + wand.getName() + " to " + player.getName()); } else { controller.getLogger().warning("Unable to give welcome wand '" + welcomeWand + "' to " + player.getName()); } } } if (activeWand != null && restoreOpenWand && !activeWand.isInventoryOpen()) { activeWand.openInventory(); } restoreOpenWand = false; } armorUpdated(); loading = false; } catch (Exception ex) { controller.getLogger().warning("Error finalizing player data for " + playerName + ": " + ex.getMessage()); } } protected void finishLoad(MageData data) { MageLoadTask loadTask = new MageLoadTask(this, data); Bukkit.getScheduler().scheduleSyncDelayedTask(controller.getPlugin(), loadTask, 1); } @Override public boolean load(MageData data) { try { if (data == null) { finishLoad(data); return true; } boundWands.clear(); Map<String, ItemStack> boundWandItems = data.getBoundWands(); if (boundWandItems != null) { for (ItemStack boundWandItem : boundWandItems.values()) { try { Wand boundWand = controller.getWand(boundWandItem); boundWands.put(boundWand.getTemplateKey(), boundWand); } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Failed to load bound wand for " + playerName +": " + boundWandItem, ex); } } } this.data = data.getExtraData(); this.properties.load(data.getProperties()); this.properties.loadProperties(); this.classes.clear(); Map<String, ConfigurationSection> classProperties = data.getClassProperties(); for (Map.Entry<String, ConfigurationSection> entry : classProperties.entrySet()) { // ... what to do if missing templates? Don't want to lose data. Will need to think about this. String mageClassKey = entry.getKey(); MageClassTemplate classTemplate = controller.getMageClass(mageClassKey); if (classTemplate != null) { MageClass newClass = new MageClass(this, classTemplate); newClass.load(entry.getValue()); classes.put(mageClassKey, newClass); } } // Link up parents for (MageClass mageClass : classes.values()) { assignParent(mageClass); } // Load activeClass setActiveClass(data.getActiveClass()); cooldownExpiration = data.getCooldownExpiration(); fallProtectionCount = data.getFallProtectionCount(); fallProtection = data.getFallProtectionDuration(); if (fallProtectionCount > 0 && fallProtection > 0) { fallProtection = System.currentTimeMillis() + fallProtection; } gaveWelcomeWand = data.getGaveWelcomeWand(); playerName = data.getName(); lastDeathLocation = data.getLastDeathLocation(); lastCast = data.getLastCast(); destinationWarp = data.getDestinationWarp(); if (destinationWarp != null) { if (!destinationWarp.isEmpty()) { Location destination = controller.getWarp(destinationWarp); if (destination != null) { Plugin plugin = controller.getPlugin(); controller.info("Warping " + getEntity().getName() + " to " + destinationWarp + " on login"); TeleportTask task = new TeleportTask(getController(), getEntity(), destination, 4, true, true, null); Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, task, 1); } else { controller.info("Failed to warp " + getEntity().getName() + " to " + destinationWarp + " on login, warp doesn't exist"); } } destinationWarp = null; } getUndoQueue().load(data.getUndoData()); respawnInventory = data.getRespawnInventory(); respawnArmor = data.getRespawnArmor(); restoreOpenWand = data.isOpenWand(); BrushData brushData = data.getBrushData(); if (brushData != null) { brush.load(brushData); } if (controller.isInventoryBackupEnabled()) { restoreInventory = data.getStoredInventory(); restoreLevel = data.getStoredLevel(); restoreExperience = data.getStoredExperience(); } } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Failed to load player data for " + playerName, ex); return false; } finishLoad(data); return true; } @Override public @Nullable MageClass getActiveClass() { return activeClass; } @Override public boolean setActiveClass(String classKey) { if (classKey == null) { activeClass = null; return true; } MageClass targetClass = getClass(classKey); if (targetClass == null) { return false; } activeClass = targetClass; // TODO: Is this the best place to do this? activeClass.loadProperties(); return true; } @Override public boolean removeClass(String classKey) { if (!classes.containsKey(classKey)) { return false; } classes.remove(classKey); if (activeClass != null && activeClass.getTemplate().getKey().equals(classKey)) { activeClass = null; } return true; } public boolean useSkill(ItemStack skillItem) { Spell spell = getSpell(Wand.getSpell(skillItem)); if (spell == null) return false; boolean canUse = true; String skillClass = Wand.getSpellClass(skillItem); if (skillClass != null && !skillClass.isEmpty()) { if (!setActiveClass(skillClass)) { canUse = false; sendMessage(controller.getMessages().get("mage.no_class").replace("$name", spell.getName())); } } if (canUse) { // TODO: Maybe find a better way to handle this. // There is also an issue of an active wand taking over the hotbar display. Wand activeWand = this.activeWand; this.activeWand = null; spell.cast(); this.activeWand = activeWand; } return canUse; } @Override @Nullable public MageClass unlockClass(@Nonnull String key) { return getClass(key, true); } @Override public @Nullable MageClass getClass(@Nonnull String key) { return getClass(key, false); } private @Nullable MageClass getClass(@Nonnull String key, boolean forceCreate) { MageClass mageClass = classes.get(key); if (mageClass == null) { MageClassTemplate template = controller.getMageClass(key); if (template != null && (forceCreate || !template.isLocked())) { mageClass = new MageClass(this, template); assignParent(mageClass); classes.put(key, mageClass); } } return mageClass; } private void assignParent(MageClass mageClass) { MageClassTemplate template = mageClass.getTemplate(); MageClassTemplate parentTemplate = template.getParent(); if (parentTemplate != null) { // Having a sub-class means having the parent class. MageClass parentClass = getClass(parentTemplate.getKey(), true); // Should never be null, check is here to silence the compiler. if(parentClass != null) { mageClass.setParent(parentClass); } } } @Override public boolean save(MageData data) { if (loading) return false; try { data.setName(getName()); data.setId(getId()); data.setLastCast(lastCast); data.setLastDeathLocation(lastDeathLocation); data.setLocation(location); data.setDestinationWarp(destinationWarp); data.setCooldownExpiration(cooldownExpiration); long now = System.currentTimeMillis(); if (fallProtectionCount > 0 && fallProtection > now) { data.setFallProtectionCount(fallProtectionCount); data.setFallProtectionDuration(fallProtection - now); } else { data.setFallProtectionCount(0); data.setFallProtectionDuration(0); } BrushData brushData = new BrushData(); brush.save(brushData); data.setBrushData(brushData); UndoData undoData = new UndoData(); getUndoQueue().save(undoData); data.setUndoData(undoData); data.setSpellData(this.spellData.values()); if (boundWands.size() > 0) { Map<String, ItemStack> wandItems = new HashMap<>(); for (Map.Entry<String, Wand> wandEntry : boundWands.entrySet()) { wandItems.put(wandEntry.getKey(), wandEntry.getValue().getItem()); } data.setBoundWands(wandItems); } data.setRespawnArmor(respawnArmor); data.setRespawnInventory(respawnInventory); data.setOpenWand(false); if (activeWand != null) { if (activeWand.hasStoredInventory()) { data.setStoredInventory(Arrays.asList(activeWand.getStoredInventory().getContents())); } if (activeWand.isInventoryOpen()) { data.setOpenWand(true); } } data.setGaveWelcomeWand(gaveWelcomeWand); data.setExtraData(this.data); data.setProperties(properties.getConfiguration()); Map<String, ConfigurationSection> classProperties = new HashMap<>(); for (Map.Entry<String, MageClass> entry : classes.entrySet()) { classProperties.put(entry.getKey(), entry.getValue().getConfiguration()); } data.setClassProperties(classProperties); String activeClassKey = activeClass == null ? null : activeClass.getTemplate().getKey(); data.setActiveClass(activeClassKey); } catch (Exception ex) { controller.getPlugin().getLogger().log(Level.WARNING, "Failed to save player data for " + playerName, ex); return false; } return true; } public boolean checkLastClick(long maxInterval) { long now = System.currentTimeMillis(); long previous = lastClick; lastClick = now; return (previous <= 0 || previous + maxInterval < now); } protected void removeActiveEffects() { LivingEntity entity = getLivingEntity(); if (entity == null) return; Collection<PotionEffect> activeEffects = entity.getActivePotionEffects(); for (PotionEffect effect : activeEffects) { if (effect.getDuration() > Integer.MAX_VALUE / 2) { entity.removePotionEffect(effect.getType()); } } } public void sendMessageKey(String key) { sendMessage(controller.getMessages().get(key, key)); } private Wand checkWand(ItemStack itemInHand) { Player player = getPlayer(); if (isLoading() || player == null) return null; ItemStack activeWandItem = activeWand != null ? activeWand.getItem() : null; if (activeWandItem == itemInHand) return activeWand; if (!Wand.isWand(itemInHand)) itemInHand = null; if ((itemInHand != null && activeWandItem == null) || (activeWandItem != null && itemInHand == null) || (activeWandItem != null && itemInHand != null && !itemInHand.equals(activeWandItem)) ) { if (activeWand != null) { activeWand.deactivate(); } if (itemInHand != null && controller.hasWandPermission(player)) { Wand newActiveWand = controller.getWand(itemInHand); if (newActiveWand.activate(this)) { setActiveWand(newActiveWand); } else { setActiveWand(null); } } } return activeWand; } public boolean offhandCast() { long now = System.currentTimeMillis(); if (lastOffhandCast > 0 && now < lastOffhandCast + OFFHAND_CAST_COOLDOWN) { return false; } lastOffhandCast = now; Player player = getPlayer(); if (isLoading() || player == null) return false; ItemStack itemInOffhand = player.getInventory().getItemInOffHand(); if (Wand.isWand(itemInOffhand)) { if (offhandWand != null && (offhandWand.getLeftClickAction() == WandAction.CAST || offhandWand.getRightClickAction() == WandAction.CAST)) { offhandCast = true; boolean castResult = false; try { offhandWand.tickMana(); offhandWand.setActiveMage(this); castResult = offhandWand.cast(); // Don't swing arm is cast is from right-click if (offhandWand != null && offhandWand.getRightClickAction() != WandAction.CAST) { CompatibilityUtils.swingOffhand(player, OFFHAND_CAST_RANGE); } } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Error casting from offhand wand", ex); } offhandCast = false; return castResult; } } return false; } public boolean setOffhandActive(boolean active) { boolean wasActive = offhandCast; this.offhandCast = active; return wasActive; } private Wand checkOffhandWand() { Player player = getPlayer(); if (player == null) { return null; } return checkOffhandWand(player.getInventory().getItemInOffHand()); } private Wand checkOffhandWand(ItemStack itemInHand) { Player player = getPlayer(); if (isLoading() || player == null) return null; ItemStack offhandWandItem = offhandWand != null ? offhandWand.getItem() : null; if (offhandWandItem == itemInHand) return offhandWand; if (!Wand.isWand(itemInHand)) itemInHand = null; if ((itemInHand != null && offhandWandItem == null) || (offhandWandItem != null && itemInHand == null) || (itemInHand != null && offhandWandItem != null && !itemInHand.equals(offhandWandItem)) ) { if (offhandWand != null) { offhandWand.deactivate(); } if (itemInHand != null && controller.hasWandPermission(player)) { Wand newActiveWand = controller.getWand(itemInHand); if (newActiveWand.activateOffhand(this)) { setOffhandWand(newActiveWand); } else { setOffhandWand(null); } } } return offhandWand; } public void checkWandNextTick(boolean checkAll) { Bukkit.getScheduler().scheduleSyncDelayedTask(controller.getPlugin(), new CheckWandTask(this, checkAll)); } public void checkWandNextTick() { Bukkit.getScheduler().scheduleSyncDelayedTask(controller.getPlugin(), new CheckWandTask(this)); } @Override public Wand checkWand() { Player player = getPlayer(); if (isLoading() || player == null) return null; checkOffhandWand(); return checkWand(player.getInventory().getItemInMainHand()); } @Override public Vector getVelocity() { return velocity; } protected void updateVelocity() { if (lastLocation != null) { Location currentLocation = getLocation(); if (currentLocation.getWorld().equals(lastLocation.getWorld())) { long interval = System.currentTimeMillis() - lastTick; velocity.setX((currentLocation.getX() - lastLocation.getX()) * 1000 / interval); velocity.setY((currentLocation.getY() - lastLocation.getY()) * 1000 / interval); velocity.setZ((currentLocation.getZ() - lastLocation.getZ()) * 1000 / interval); } else { velocity.setX(0); velocity.setY(0); velocity.setZ(0); } } lastLocation = getLocation(); } @Override public void tick() { if (!isValid()) return; long now = System.currentTimeMillis(); if (entityData != null) { if (lastTick != 0) { long tickInterval = entityData.getTickInterval(); if (now - lastTick > tickInterval) { updateVelocity(); entityData.tick(this); lastTick = now; } } else { lastTick = now; } } else { updateVelocity(); lastTick = now; } Player player = getPlayer(); // We don't tick non-player or offline Mages, except // above where entityData is ticked if present. if (player != null && player.isOnline()) { // We only update all of this at a configurable interval, // as it could have performance concerns. if (updateTicks++ < UPDATE_FREQUENCY) return; updateTicks = 0; checkWand(); if (activeWand != null) { activeWand.tick(); } else if (virtualExperience) { resetSentExperience(); } if (offhandWand != null) { offhandWand.tick(); } if (activeClass != null) { activeClass.tick(); } properties.tick(); if (Wand.LiveHotbarSkills && (activeWand == null || !activeWand.isInventoryOpen())) { updateHotbarStatus(); } // Avoid getting kicked for large jump effects // It'd be nice to filter this by amplitude, but as // it turns out that is not easy to check efficiently. if (JUMP_EFFECT_FLIGHT_EXEMPTION_DURATION > 0 && player.hasPotionEffect(PotionEffectType.JUMP)) { controller.addFlightExemption(player, JUMP_EFFECT_FLIGHT_EXEMPTION_DURATION); } for (Wand armorWand : activeArmor.values()) { armorWand.updateEffects(this); } // Copy this set since spells may get removed while iterating! List<MageSpell> active = new ArrayList<>(activeSpells); for (MageSpell spell : active) { spell.tick(); if (!spell.isActive()) { deactivateSpell(spell); } } } } public int processPendingBatches(int maxBlockUpdates) { int updated = 0; if (pendingBatches.size() > 0) { List<Batch> processBatches = new ArrayList<>(pendingBatches); pendingBatches.clear(); for (Batch batch : processBatches) { if (updated < maxBlockUpdates) { int batchUpdated = batch.process(maxBlockUpdates - updated); updated += batchUpdated; } if (!batch.isFinished()) { pendingBatches.add(batch); } } } return updated; } public boolean hasPendingBatches() { return pendingBatches.size() > 0; } public void setLastHeldMapId(int mapId) { brush.setMapId(mapId); } @Override public int getLastHeldMapId() { return brush.getMapId(); } protected void loadSpells(Map<String, ConfigurationSection> spellConfiguration) { if (spellConfiguration == null) return; Collection<MageSpell> currentSpells = new ArrayList<>(spells.values()); for (MageSpell spell : currentSpells) { String key = spell.getKey(); if (spellConfiguration.containsKey(key)) { ConfigurationSection template = spellConfiguration.get(key); String className = template.getString("class"); if (className == null) { className = ActionSpell.class.getName(); } // Check for spells that have changed class // TODO: Still unsure if this is right. if (!spell.getClass().getName().contains(className)) { //SpellData spellData = new SpellData(key); spell.save(null); spells.remove(key); this.spellData.put(key, spell.getSpellData()); } else { spell.loadTemplate(key, template); spell.loadPrerequisites(template); } } else { spells.remove(key); } } } /* * API Implementation */ @Override public Collection<Batch> getPendingBatches() { Collection<Batch> pending = new ArrayList<>(); pending.addAll(pendingBatches); return pending; } @Override public String getName() { return playerName == null || playerName.length() == 0 ? defaultMageName : playerName; } @Override public String getDisplayName() { Entity entity = getEntity(); if (entity == null) { return getName(); } if (entity instanceof Player) { return ((Player)entity).getDisplayName(); } return controller.getEntityDisplayName(entity); } public void setName(String name) { playerName = name; } @Override public String getId() { return id; } @Override public Location getLocation() { if (location != null) return location.clone(); LivingEntity livingEntity = getLivingEntity(); if (livingEntity == null) return null; return livingEntity.getLocation(); } @Override public Location getEyeLocation() { Entity entity = getEntity(); if (entity != null) { return CompatibilityUtils.getEyeLocation(entity); } return getLocation(); } @Override public Location getCastLocation() { Location castLocation = getEyeLocation(); if (activeWand != null && !offhandCast) { castLocation = activeWand.getLocation(); } else if (offhandWand != null && offhandCast) { castLocation = offhandWand.getLocation(); } else if (DEFAULT_CAST_LOCATION == CastSourceLocation.MAINHAND) { castLocation = getOffsetLocation(castLocation, false, DEFAULT_CAST_OFFSET); } else if (DEFAULT_CAST_LOCATION == CastSourceLocation.OFFHAND) { castLocation = getOffsetLocation(castLocation, true, DEFAULT_CAST_OFFSET); } return castLocation; } @Override public Location getWandLocation() { return getCastLocation(); } public Location getOffsetLocation(Location baseLocation, boolean isInOffhand, Vector offset) { Entity entity = getEntity(); if (entity == null) return baseLocation; boolean leftHand = isInOffhand; if (entity instanceof HumanEntity) { HumanEntity human = (HumanEntity)entity; if (human.getMainHand() == MainHand.LEFT) { leftHand = !leftHand; } } double sneakOffset = 0; if (entity instanceof Player && ((Player)entity).isSneaking()) { sneakOffset = SNEAKING_CAST_OFFSET; } if (leftHand) { offset = new Vector(offset.getX(), offset.getY() + sneakOffset, -offset.getZ()); } else if (sneakOffset != 0) { offset = new Vector(offset.getX(), offset.getY() + sneakOffset, offset.getZ()); } baseLocation.add(VectorUtils.rotateVector(offset, baseLocation)); return baseLocation; } @Override public Location getOffhandWandLocation() { Location wandLocation = getEyeLocation(); if (offhandWand != null) { wandLocation = offhandWand.getLocation(); } return wandLocation; } @Override public Vector getDirection() { Location location = getLocation(); if (location != null) { return location.getDirection(); } return new Vector(0, 1, 0); } @Override public UndoList undo(Block target) { return getUndoQueue().undo(target); } @Override public Batch cancelPending() { return cancelPending(null, true); } @Override public Batch cancelPending(String spellKey) { return cancelPending(spellKey, true); } @Override public Batch cancelPending(boolean force) { return cancelPending(null, force); } @Override public int finishPendingUndo() { int finished = 0; if (pendingBatches.size() > 0) { List<Batch> batches = new ArrayList<>(); batches.addAll(pendingBatches); for (Batch batch : batches) { if (batch instanceof UndoBatch) { while (!batch.isFinished()) { batch.process(1000); } pendingBatches.remove(batch); finished++; } } } return finished; } @Override public Batch cancelPending(String spellKey, boolean force) { Batch stoppedPending = null; if (pendingBatches.size() > 0) { List<Batch> batches = new ArrayList<>(); batches.addAll(pendingBatches); for (Batch batch : batches) { if (spellKey != null || !force) { if (!(batch instanceof SpellBatch)) { continue; } SpellBatch spellBatch = (SpellBatch)batch; Spell spell = spellBatch.getSpell(); if (spell == null) { continue; } if (!force && !spell.isCancellable()) { continue; } if (spellKey != null && !spell.getSpellKey().getBaseKey().equalsIgnoreCase(spellKey)) { continue; } } if (!(batch instanceof UndoBatch)) { if (force && batch instanceof SpellBatch) { SpellBatch spellBatch = (SpellBatch)batch; Spell spell = spellBatch.getSpell(); if (spell != null) { spell.cancel(); } } batch.finish(); pendingBatches.remove(batch); stoppedPending = batch; } } } return stoppedPending; } @Override public UndoList undo() { return getUndoQueue().undo(); } @Override public boolean commit() { return getUndoQueue().commit(); } @Override public boolean hasCastPermission(Spell spell) { return spell.hasCastPermission(getCommandSender()); } @Override public boolean hasSpell(String key) { return spells.containsKey(key); } @Override public MageSpell getSpell(String key) { if (loading) return null; MageSpell playerSpell = spells.get(key); if (playerSpell == null) { playerSpell = createSpell(key); if (playerSpell != null) { SpellData spellData = this.spellData.get(key); if (spellData == null) { spellData = new SpellData(key); this.spellData.put(key, spellData); } playerSpell.load(spellData); } } else { playerSpell.setMage(this); } return playerSpell; } protected MageSpell createSpell(String key) { MageSpell playerSpell = spells.get(key); if (playerSpell != null) { playerSpell.setMage(this); return playerSpell; } SpellTemplate spellTemplate = controller.getSpellTemplate(key); if (spellTemplate == null) return null; Spell newSpell = spellTemplate.createSpell(); if (newSpell == null || !(newSpell instanceof MageSpell)) return null; playerSpell = (MageSpell)newSpell; spells.put(newSpell.getKey(), playerSpell); playerSpell.setMage(this); return playerSpell; } @Override public Collection<Spell> getSpells() { List<Spell> export = new ArrayList<Spell>(spells.values()); return export; } @Override public void activateSpell(Spell spell) { if (spell instanceof MageSpell) { MageSpell mageSpell = ((MageSpell) spell); activeSpells.add(mageSpell); mageSpell.setActive(true); } } @Override public void deactivateSpell(Spell spell) { activeSpells.remove(spell); // If this was called by the Spell itself, the following // should do nothing as the spell is already marked as inactive. if (spell instanceof MageSpell) { ((MageSpell) spell).deactivate(); } } @Override public void deactivateAllSpells() { deactivateAllSpells(false, false); } @Override public void deactivateAllSpells(boolean force, boolean quiet) { // Copy this set since spells will get removed while iterating! List<MageSpell> active = new ArrayList<>(activeSpells); for (MageSpell spell : active) { if (spell.deactivate(force, quiet)) { activeSpells.remove(spell); } } // This is mainly here to prevent multi-wand spamming and for // Disarm to be more powerful.. because Disarm needs to be more // powerful :| cancelPending(false); } @Override public boolean isCostFree() { // Special case for command blocks and Automata if (getPlayer() == null) return true; return getCostReduction() > 1; } @Override public boolean isConsumeFree() { return activeWand != null && activeWand.isConsumeFree(); } @Override public boolean isSuperProtected() { if (superProtectionExpiration != 0) { if (System.currentTimeMillis() > superProtectionExpiration) { superProtectionExpiration = 0; } else { return true; } } if (offhandCast && offhandWand != null) { return offhandWand.isSuperProtected(); } return activeWand != null && activeWand.isSuperProtected(); } @Override public boolean isSuperPowered() { if (offhandCast && offhandWand != null) { return offhandWand.isSuperPowered(); } return activeWand != null && activeWand.isSuperPowered(); } @Override public float getCostReduction() { if (offhandCast && offhandWand != null) { return offhandWand.getCostReduction() + costReduction; } return activeWand == null ? costReduction + controller.getCostReduction() : activeWand.getCostReduction() + costReduction; } @Override public float getConsumeReduction() { if (offhandCast && offhandWand != null) { return offhandWand.getConsumeReduction(); } return activeWand == null ? 0 : activeWand.getConsumeReduction(); } @Override public float getCostScale() { return 1; } @Override public float getCooldownReduction() { if (offhandCast && offhandWand != null) { return offhandWand.getCooldownReduction() + cooldownReduction; } return activeWand == null ? cooldownReduction + controller.getCooldownReduction() : activeWand.getCooldownReduction() + cooldownReduction; } @Override public boolean isCooldownFree() { return getCooldownReduction() > 1; } @Override public long getRemainingCooldown() { long remaining = 0; if (cooldownExpiration > 0) { long now = System.currentTimeMillis(); if (cooldownExpiration > now) { remaining = cooldownExpiration - now; } else { cooldownExpiration = 0; } } return remaining; } @Override public void clearCooldown() { cooldownExpiration = 0; HeroesManager heroes = controller.getHeroes(); Player player = getPlayer(); if (heroes != null && player != null) { heroes.clearCooldown(player); } } @Override public void setRemainingCooldown(long ms) { cooldownExpiration = Math.max(ms + System.currentTimeMillis(), cooldownExpiration); HeroesManager heroes = controller.getHeroes(); Player player = getPlayer(); if (heroes != null && player != null) { heroes.setCooldown(player, ms); } } @Override public Color getEffectColor() { if (offhandCast && offhandWand != null) { return offhandWand.getEffectColor(); } if (activeWand == null) return null; return activeWand.getEffectColor(); } @Override public String getEffectParticleName() { if (offhandCast && offhandWand != null) { return offhandWand.getEffectParticleName(); } if (activeWand == null) return null; return activeWand.getEffectParticleName(); } @Override public void onCast(Spell spell, SpellResult result) { lastCast = System.currentTimeMillis(); if (spell != null) { // Notify controller of successful casts, // this if for dynmap display or other global-level processing. controller.onCast(this, spell, result); } } @Override public float getPower() { if (offhandCast && offhandWand != null) { float power = Math.min(controller.getMaxPower(), offhandWand.getPower() + getMagePowerBonus()); return power * powerMultiplier; } float power = Math.min(controller.getMaxPower(), activeWand == null ? getMagePowerBonus() : activeWand.getPower() + getMagePowerBonus()); return power * powerMultiplier; } @Override public float getMagePowerBonus() { return magePowerBonus; } @Override public void setMagePowerBonus(float magePowerBonus) { this.magePowerBonus = magePowerBonus; } @Override public boolean isRestricted(Material material) { Player player = getPlayer(); if (player != null && player.hasPermission("Magic.bypass_restricted")) return false; return controller.isRestricted(material); } @Override public MageController getController() { return controller; } @Override public Set<Material> getRestrictedMaterials() { if (isSuperPowered()) { return EMPTY_MATERIAL_SET; } return controller.getRestrictedMaterials(); } @Override public boolean isPVPAllowed(Location location) { return controller.isPVPAllowed(getPlayer(), location == null ? getLocation() : location); } @Override public boolean hasBuildPermission(Block block) { return controller.hasBuildPermission(getPlayer(), block); } @Override public boolean hasBreakPermission(Block block) { return controller.hasBreakPermission(getPlayer(), block); } @Override public boolean isIndestructible(Block block) { return controller.isIndestructible(block); } @Override public boolean isDestructible(Block block) { return controller.isDestructible(block); } @Override public boolean isDead() { LivingEntity entity = getLivingEntity(); if (entity != null) { return entity.isDead(); } // Check for automata CommandSender sender = getCommandSender(); if (sender == null || !(sender instanceof BlockCommandSender)) return true; BlockCommandSender commandBlock = (BlockCommandSender) sender; Block block = commandBlock.getBlock(); if (!block.getChunk().isLoaded()) return true; return (block.getType() != Material.COMMAND); } @Override public boolean isOnline() { Player player = getPlayer(); if (player != null) { return player.isOnline(); } // Check for automata CommandSender sender = getCommandSender(); if (sender == null || !(sender instanceof BlockCommandSender)) return true; return lastCast > System.currentTimeMillis() - AUTOMATA_ONLINE_TIMEOUT; } @Override public boolean isPlayer() { Player player = getPlayer(); return player != null; } @Override public boolean hasLocation() { return getLocation() != null; } @Override public Inventory getInventory() { if (hasStoredInventory()) { return getStoredInventory(); } Player player = getPlayer(); if (player != null) { return player.getInventory(); } // TODO: Maybe wrap EntityEquipment in an Inventory... ? Could be hacky. return null; } @Override public int removeItem(ItemStack itemStack, boolean allowVariants) { if (!isPlayer()) return 0; Integer sp = Wand.getSP(itemStack); if (sp != null) { int currentSP = getSkillPoints(); int newSP = currentSP - sp; if (currentSP < sp) { sp = sp - currentSP; } else { sp = 0; } setSkillPoints(newSP); return sp; } int amount = itemStack == null ? 0 : itemStack.getAmount(); Inventory inventory = getInventory(); ItemStack[] contents = inventory.getContents(); for (int index = 0; amount > 0 && index < contents.length; index++) { ItemStack item = contents[index]; if (item == null) continue; if ((!allowVariants && itemStack.isSimilar(item)) || (allowVariants && itemStack.getType() == item.getType() && (item.getItemMeta() == null || item.getItemMeta().getDisplayName() == null))) { if (amount >= item.getAmount()) { amount -= item.getAmount(); inventory.setItem(index, null); } else { item.setAmount(item.getAmount() - amount); amount = 0; } } } return amount; } @Override public boolean hasItem(ItemStack itemStack, boolean allowVariants) { if (!isPlayer()) return false; Integer sp = Wand.getSP(itemStack); if (sp != null) { return getSkillPoints() >= sp; } int amount = itemStack == null ? 0 :itemStack.getAmount(); if (amount <= 0 ) { return true; } Inventory inventory = getInventory(); ItemStack[] contents = inventory.getContents(); for (ItemStack item : contents) { if (item != null && ((!allowVariants && itemStack.isSimilar(item)) || (allowVariants && itemStack.getType() == item.getType() && (item.getItemMeta() == null || item.getItemMeta().getDisplayName() == null))) && (amount -= item.getAmount()) <= 0) { return true; } } return false; } @Override public int removeItem(ItemStack itemStack) { return removeItem(itemStack, false); } @Override public boolean hasItem(ItemStack itemStack) { return hasItem(itemStack, false); } @Override @Deprecated public Wand getSoulWand() { return null; } @Override public Wand getActiveWand() { if (offhandCast && offhandWand != null) { return offhandWand; } return activeWand; } @Override public Wand getOffhandWand() { return offhandWand; } @Override public com.elmakers.mine.bukkit.api.block.MaterialBrush getBrush() { return brush; } @Override public float getDamageMultiplier() { float maxPowerMultiplier = controller.getMaxDamagePowerMultiplier() - 1; return 1 + (maxPowerMultiplier * getPower()); } @Override public float getRangeMultiplier() { if (activeWand == null) return 1; float maxPowerMultiplier = controller.getMaxRangePowerMultiplier() - 1; float maxPowerMultiplierMax = controller.getMaxRangePowerMultiplierMax(); float multiplier = 1 + (maxPowerMultiplier * getPower()); return Math.min(multiplier, maxPowerMultiplierMax); } @Override public float getConstructionMultiplier() { float maxPowerMultiplier = controller.getMaxConstructionPowerMultiplier() - 1; return 1 + (maxPowerMultiplier * getPower()); } @Override public float getRadiusMultiplier() { if (activeWand == null) return 1; float maxPowerMultiplier = controller.getMaxRadiusPowerMultiplier() - 1; float maxPowerMultiplierMax = controller.getMaxRadiusPowerMultiplierMax(); float multiplier = 1 + (maxPowerMultiplier * getPower()); return Math.min(multiplier, maxPowerMultiplierMax); } @Override public float getMana() { if (controller.useHeroesMana() && isPlayer()) { HeroesManager heroes = controller.getHeroes(); if (heroes != null) { return heroes.getMana(getPlayer()); } } if (offhandCast && offhandWand != null) { return offhandWand.getMana(); } if (activeWand != null) { return activeWand.getMana(); } if (activeClass != null) { return activeClass.getMana(); } return properties.getMana(); } public int getEffectiveManaMax() { if (controller.useHeroesMana() && isPlayer()) { HeroesManager heroes = controller.getHeroes(); if (heroes != null) { return heroes.getMaxMana(getPlayer()); } } if (activeWand != null) { return activeWand.getEffectiveManaMax(); } if (activeClass != null) { return activeClass.getEffectiveManaMax(); } return properties.getEffectiveManaMax(); } public int getEffectiveManaRegeneration() { if (controller.useHeroesMana() && isPlayer()) { HeroesManager heroes = controller.getHeroes(); if (heroes != null) { return heroes.getManaRegen(getPlayer()); } } if (activeWand != null) { return activeWand.getEffectiveManaRegeneration(); } if (activeClass != null) { return activeClass.getEffectiveManaRegeneration(); } return properties.getEffectiveManaRegeneration(); } @Override public void removeMana(float mana) { if (offhandCast && offhandWand != null) { offhandWand.removeMana(mana); } else if (activeWand != null) { activeWand.removeMana(mana); } else if (activeClass != null) { activeClass.removeMana(mana); } else { properties.removeMana(mana); } } @Override public void removeExperience(int xp) { Player player = getPlayer(); if (player == null) return; float expProgress = player.getExp(); int expLevel = player.getLevel(); while ((expProgress > 0 || expLevel > 0) && xp > 0) { if (expProgress > 0) { float expToLevel = Wand.getExpToLevel(expLevel); int expAtLevel = (int)(expProgress * expToLevel); if (expAtLevel > xp) { expAtLevel -= xp; xp = 0; expProgress = expAtLevel / expToLevel; } else { expProgress = 0; xp -= expAtLevel; } } else { xp -= Wand.getExpToLevel(expLevel - 1); expLevel--; if (xp < 0) { expProgress = (float) (-xp) / Wand.getExpToLevel(expLevel); xp = 0; } } } player.setExp(Math.max(0, Math.min(1.0f, expProgress))); player.setLevel(Math.max(0, expLevel)); } @Override public int getLevel() { Player player = getPlayer(); if (player != null) { return player.getLevel(); } return 0; } @Override public void setLevel(int level) { Player player = getPlayer(); if (player != null) { player.setLevel(level); } } @Override public int getExperience() { Player player = getPlayer(); if (player == null) return 0; float expProgress = player.getExp(); int expLevel = player.getLevel(); return Wand.getExperience(expLevel, expProgress); } @Override public void giveExperience(int xp) { Player player = getPlayer(); if (player != null) { player.giveExp(xp); } } public void sendExperience(float exp, int level) { if (virtualExperience && exp == virtualExperienceProgress && level == virtualExperienceLevel) return; Player player = getPlayer(); if (player != null) { CompatibilityUtils.sendExperienceUpdate(player, exp, level); virtualExperience = true; virtualExperienceProgress = exp; virtualExperienceLevel = level; } } public void resetSentExperience() { Player player = getPlayer(); if (player != null) { CompatibilityUtils.sendExperienceUpdate(player, player.getExp(), player.getLevel()); } virtualExperience = false; } public void experienceChanged() { virtualExperience = false; } @Override public boolean addBatch(Batch batch) { if (pendingBatches.size() >= controller.getPendingQueueDepth()) { controller.getLogger().info("Rejected spell cast for " + getName() + ", already has " + pendingBatches.size() + " pending, limit: " + controller.getPendingQueueDepth()); return false; } pendingBatches.addLast(batch); controller.addPending(this); return true; } @Override public void registerEvent(SpellEventType type, Listener spell) { switch (type) { case PLAYER_QUIT: if (!quitListeners.contains(spell)) quitListeners.add(spell); break; case PLAYER_DAMAGE: if (!damageListeners.contains(spell)) damageListeners.add(spell); break; case PLAYER_DEATH: if (!deathListeners.contains(spell)) deathListeners.add(spell); break; } } @Override public void unregisterEvent(SpellEventType type, Listener spell) { switch (type) { case PLAYER_DAMAGE: damageListeners.remove(spell); break; case PLAYER_QUIT: quitListeners.remove(spell); break; case PLAYER_DEATH: deathListeners.remove(spell); break; } } @Override public Player getPlayer() { Player player = _player.get(); return controller.isNPC(player) ? null : player; } @Override public Entity getEntity() { return _entity.get(); } @Override public EntityData getEntityData() { return entityData; } @Override public LivingEntity getLivingEntity() { Entity entity = _entity.get(); return (entity != null && entity instanceof LivingEntity) ? (LivingEntity) entity : null; } @Override public CommandSender getCommandSender() { return _commandSender.get(); } @Override public List<LostWand> getLostWands() { Entity entity = getEntity(); Collection<LostWand> allWands = controller.getLostWands(); List<LostWand> mageWands = new ArrayList<>(); if (entity == null) { return mageWands; } String playerId = entity.getUniqueId().toString(); for (LostWand lostWand : allWands) { String owner = lostWand.getOwnerId(); if (owner != null && owner.equals(playerId)) { mageWands.add(lostWand); } } return mageWands; } @Override public Location getLastDeathLocation() { return lastDeathLocation; } @Override public void showHoloText(Location location, String text, int duration) { // TODO: Broadcast if (!isPlayer()) return; final Player player = getPlayer(); if (hologram == null) { hologram = HoloUtils.createHoloText(location, text); } else { if (hologramIsVisible) { hologram.hide(player); } hologram.teleport(location); hologram.setLabel(text); } hologram.show(player); BukkitScheduler scheduler = Bukkit.getScheduler(); if (duration > 0) { scheduler.scheduleSyncDelayedTask(controller.getPlugin(), new Runnable() { @Override public void run() { hologram.hide(player); hologramIsVisible = false; } }, duration); } } @Override public void enableFallProtection(int ms, Spell protector) { enableFallProtection(ms, 1, protector); } @Override public void enableFallProtection(int ms, int count, Spell protector) { if (ms <= 0 || count <= 0) return; if (protector != null && protector instanceof BaseSpell) { this.fallingSpell = (BaseSpell)protector; } long nextTime = System.currentTimeMillis() + ms; if (nextTime > fallProtection) { fallProtection = nextTime; } if (count > fallProtectionCount) { fallProtectionCount = count; } } @Override public void enableFallProtection(int ms) { enableFallProtection(ms, null); } @Override public void enableSuperProtection(int ms) { if (ms <= 0) return; long nextTime = System.currentTimeMillis() + ms; if (nextTime > superProtectionExpiration) { superProtectionExpiration = nextTime; } } @Override public void clearSuperProtection() { superProtectionExpiration = 0; } public void setLoading(boolean loading) { this.loading = loading; } @Override public void disable() { // Kind of a hack, but the loading flag will prevent the Mage from doing anything further this.loading = true; } @Override public boolean isLoading() { return loading; } public void setUnloading(boolean unloading) { this.unloading = unloading; } public boolean isUnloading() { return unloading; } @Override public boolean hasPending() { if (undoQueue != null && undoQueue.hasScheduled()) return true; if (pendingBatches.size() > 0) return true; return false; } @Override public boolean isValid() { if (!hasEntity) return true; Entity entity = getEntity(); if (entity == null) return false; if (controller.isNPC(entity)) return true; if (entity instanceof Player) { Player player = (Player)entity; return player.isOnline(); } if (entity instanceof LivingEntity) { LivingEntity living = (LivingEntity)entity; return !living.isDead(); } // Automata theoretically handle themselves by sticking around for a while // And forcing themselves to be forgotten // but maybe some extra safety here would be good? return entity.isValid(); } @Override public boolean restoreWand() { if (boundWands.size() == 0) return false; Player player = getPlayer(); if (player == null) return false; Set<String> foundTemplates = new HashSet<>(); ItemStack[] inventory = getInventory().getContents(); for (ItemStack item : inventory) { if (Wand.isWand(item)) { Wand tempWand = controller.getWand(item); String template = tempWand.getTemplateKey(); if (template != null) { foundTemplates.add(template); } } } inventory = player.getEnderChest().getContents(); for (ItemStack item : inventory) { if (Wand.isWand(item)) { Wand tempWand = controller.getWand(item); String template = tempWand.getTemplateKey(); if (template != null) { foundTemplates.add(template); } } } int givenWands = 0; for (Map.Entry<String, Wand> wandEntry : boundWands.entrySet()) { if (foundTemplates.contains(wandEntry.getKey())) continue; givenWands++; ItemStack wandItem = wandEntry.getValue().duplicate().getItem(); wandItem.setAmount(1); giveItem(wandItem); } return givenWands > 0; } @Override public boolean isStealth() { if (isSneaking()) return true; if (activeWand != null && activeWand.isStealth()) return true; return false; } @Override public boolean isSneaking() { Player player = getPlayer(); return (player != null && player.isSneaking()); } @Override public boolean isJumping() { Entity entity = getEntity(); return (entity != null && !entity.isOnGround()); } @Override public ConfigurationSection getData() { if (loading) { return new MemoryConfiguration(); } return data; } public void onGUIDeactivate() { GUIAction previousGUI = gui; gui = null; Player player = getPlayer(); if (player != null) { DeprecatedUtils.updateInventory(player); } if (previousGUI != null) { previousGUI.deactivated(); } } @Override public void activateGUI(GUIAction action, Inventory inventory) { Player player = getPlayer(); if (player != null) { controller.disableItemSpawn(); try { player.closeInventory(); if (inventory != null) { gui = action; player.openInventory(inventory); } } catch (Throwable ex) { ex.printStackTrace(); } controller.enableItemSpawn(); } gui = action; } @Override public void continueGUI(GUIAction action, Inventory inventory) { Player player = getPlayer(); if (player != null) { controller.disableItemSpawn(); try { if (inventory != null) { gui = action; player.openInventory(inventory); } } catch (Throwable ex) { ex.printStackTrace(); } controller.enableItemSpawn(); } gui = action; } @Override public void deactivateGUI() { activateGUI(null, null); } @Override public GUIAction getActiveGUI() { return gui; } @Override public int getDebugLevel() { return debugLevel; } @Override public void setDebugger(CommandSender sender) { this.debugger = sender; } @Override public CommandSender getDebugger() { return debugger; } @Override public void setDebugLevel(int debugLevel) { this.debugLevel = debugLevel; } @Override public void sendDebugMessage(String message) { sendDebugMessage(message, 1); } @Override public void debugPermissions(CommandSender sender, Spell spell) { com.elmakers.mine.bukkit.api.wand.Wand wand = getActiveWand(); Location location = getLocation(); if (spell == null && wand != null) { spell = wand.getActiveSpell(); } sender.sendMessage(ChatColor.GOLD + "Permission check for " + ChatColor.AQUA + getDisplayName()); sender.sendMessage(ChatColor.GOLD + " id " + ChatColor.DARK_AQUA + getId()); sender.sendMessage(ChatColor.GOLD + " at " + ChatColor.AQUA + ChatColor.BLUE + location.getBlockX() + " " + location.getBlockY() + " " + location.getBlockZ() + " " + ChatColor.DARK_BLUE + location.getWorld().getName()); Player player = getPlayer(); boolean hasBypass = false; boolean hasPVPBypass = false; boolean hasBuildBypass = false; boolean hasBreakBypass = false; if (player != null) { hasBypass = player.hasPermission("Magic.bypass"); hasPVPBypass = player.hasPermission("Magic.bypass_pvp"); hasBuildBypass = player.hasPermission("Magic.bypass_build"); sender.sendMessage(ChatColor.AQUA + " Has bypass: " + formatBoolean(hasBypass, true, null)); sender.sendMessage(ChatColor.AQUA + " Has PVP bypass: " + formatBoolean(hasPVPBypass, true, null)); sender.sendMessage(ChatColor.AQUA + " Has Build bypass: " + formatBoolean(hasBuildBypass, true, null)); sender.sendMessage(ChatColor.AQUA + " Has Break bypass: " + formatBoolean(hasBreakBypass, true, null)); } boolean buildPermissionRequired = spell == null ? false : spell.requiresBuildPermission(); boolean breakPermissionRequired = spell == null ? false : spell.requiresBreakPermission(); boolean pvpRestricted = spell == null ? false : spell.isPvpRestricted(); sender.sendMessage(ChatColor.AQUA + " Can build: " + formatBoolean(hasBuildPermission(location.getBlock()), hasBuildBypass || !buildPermissionRequired ? null : true)); sender.sendMessage(ChatColor.AQUA + " Can break: " + formatBoolean(hasBreakPermission(location.getBlock()), hasBreakBypass || !breakPermissionRequired ? null : true)); sender.sendMessage(ChatColor.AQUA + " Can pvp: " + formatBoolean(isPVPAllowed(location), hasPVPBypass || !pvpRestricted ? null : true)); boolean isPlayer = player != null; boolean spellDisguiseRestricted = (spell == null) ? false : spell.isDisguiseRestricted(); sender.sendMessage(ChatColor.AQUA + " Is disguised: " + formatBoolean(controller.isDisguised(getEntity()), null, isPlayer && spellDisguiseRestricted ? true : null)); WorldBorder border = location.getWorld().getWorldBorder(); double borderSize = border.getSize(); // Kind of a hack, meant to prevent this from showing up when there's no border defined if (borderSize < 50000000) { borderSize = borderSize / 2 - border.getWarningDistance(); Location offset = location.subtract(border.getCenter()); boolean isOutsideBorder = (offset.getX() < -borderSize || offset.getX() > borderSize || offset.getZ() < -borderSize || offset.getZ() > borderSize); sender.sendMessage(ChatColor.AQUA + " Is in world border (" + ChatColor.GRAY + borderSize + ChatColor.AQUA + "): " + formatBoolean(!isOutsideBorder, true, false)); } if (spell != null) { sender.sendMessage(ChatColor.AQUA + " Has pnode " + ChatColor.GOLD + spell.getPermissionNode() + ChatColor.AQUA + ": " + formatBoolean(spell.hasCastPermission(player), hasBypass ? null : true)); sender.sendMessage(ChatColor.AQUA + " Region override: " + formatBoolean(controller.getRegionCastPermission(player, spell, location), hasBypass ? null : true)); sender.sendMessage(ChatColor.AQUA + " Field override: " + formatBoolean(controller.getPersonalCastPermission(player, spell, location), hasBypass ? null : true)); com.elmakers.mine.bukkit.api.block.MaterialBrush brush = spell.getBrush(); if (brush != null) { sender.sendMessage(ChatColor.GOLD + " " + spell.getName() + ChatColor.AQUA + " is erase: " + formatBoolean(brush.isErase(), null)); } sender.sendMessage(ChatColor.GOLD + " " + spell.getName() + ChatColor.AQUA + " requires build: " + formatBoolean(spell.requiresBuildPermission(), null, true, true)); sender.sendMessage(ChatColor.GOLD + " " + spell.getName() + ChatColor.AQUA + " requires break: " + formatBoolean(spell.requiresBreakPermission(), null, true, true)); sender.sendMessage(ChatColor.GOLD + " " + spell.getName() + ChatColor.AQUA + " requires pvp: " + formatBoolean(spell.isPvpRestricted(), null, true, true)); sender.sendMessage(ChatColor.GOLD + " " + spell.getName() + ChatColor.AQUA + " allowed while disguised: " + formatBoolean(!spell.isDisguiseRestricted(), null, false, true)); if (spell instanceof BaseSpell) { boolean buildPermission = ((BaseSpell)spell).hasBuildPermission(location.getBlock()); sender.sendMessage(ChatColor.GOLD + " " + spell.getName() + ChatColor.AQUA + " has build: " + formatBoolean(buildPermission, hasBuildBypass || !spell.requiresBuildPermission() ? null : true)); boolean breakPermission = ((BaseSpell)spell).hasBreakPermission(location.getBlock()); sender.sendMessage(ChatColor.GOLD + " " + spell.getName() + ChatColor.AQUA + " has break: " + formatBoolean(breakPermission, hasBreakBypass || !spell.requiresBreakPermission() ? null : true)); } sender.sendMessage(ChatColor.AQUA + " Can cast " + ChatColor.GOLD + spell.getName() + ChatColor.AQUA + ": " + formatBoolean(spell.canCast(location))); } } public static String formatBoolean(Boolean flag, Boolean greenState) { return formatBoolean(flag, greenState, greenState == null ? null : !greenState, false); } public static String formatBoolean(Boolean flag) { return formatBoolean(flag, true, false, false); } public static String formatBoolean(Boolean flag, Boolean greenState, Boolean redState) { return formatBoolean(flag, greenState, redState, false); } public static String formatBoolean(Boolean flag, Boolean greenState, Boolean redState, boolean dark) { if (flag == null) { return ChatColor.GRAY + "none"; } String text = flag ? "true" : "false"; if (greenState != null && Objects.equal(flag, greenState)) { return (dark ? ChatColor.DARK_GREEN : ChatColor.GREEN) + text; } else if (redState != null && Objects.equal(flag, redState)) { return (dark ? ChatColor.DARK_RED : ChatColor.RED) + text; } return ChatColor.GRAY + text; } @Override public void sendDebugMessage(String message, int level) { if (debugLevel >= level && message != null && !message.isEmpty()) { CommandSender sender = debugger; if (sender == null) { sender = getCommandSender(); } if (sender != null) { sender.sendMessage(controller.getMessagePrefix() + message); } } } public void clearRespawnInventories() { respawnArmor = null; respawnInventory = null; } public void restoreRespawnInventories() { Player player = getPlayer(); if (player == null) { return; } PlayerInventory inventory = player.getInventory(); if (respawnArmor != null) { ItemStack[] armor = inventory.getArmorContents(); for (Map.Entry<Integer, ItemStack> entry : respawnArmor.entrySet()) { armor[entry.getKey()] = entry.getValue(); } player.getInventory().setArmorContents(armor); } if (respawnInventory != null) { for (Map.Entry<Integer, ItemStack> entry : respawnInventory.entrySet()) { inventory.setItem(entry.getKey(), entry.getValue()); } } clearRespawnInventories(); controller.getPlugin().getServer().getScheduler().runTaskLater(controller.getPlugin(), new Runnable() { @Override public void run() { armorUpdated(); } }, 1); } public void addToRespawnInventory(int slot, ItemStack item) { if (respawnInventory == null) { respawnInventory = new HashMap<>(); } respawnInventory.put(slot, item); } public void addToRespawnArmor(int slot, ItemStack item) { if (respawnArmor == null) { respawnArmor = new HashMap<>(); } respawnArmor.put(slot, item); } @Override public void giveItem(ItemStack itemStack) { if (InventoryUtils.isEmpty(itemStack)) return; // Check for wand upgrades if appropriate Wand activeWand = getActiveWand(); if (activeWand != null) { if (activeWand.addItem(itemStack)) { return; } } if (hasStoredInventory()) { addToStoredInventory(itemStack); return; } // Place directly in hand if possible Player player = getPlayer(); if (player == null) return; PlayerInventory inventory = player.getInventory(); ItemStack inHand = inventory.getItemInMainHand(); if (inHand == null || inHand.getType() == Material.AIR) { inventory.setItemInMainHand(itemStack); // Get the new item reference - // it might change when added to an Inventory! :| itemStack = inventory.getItemInMainHand(); if (Wand.isWand(itemStack)) { checkWand(); } else { if (itemStack.getType() == Material.MAP) { setLastHeldMapId(itemStack.getDurability()); } } } else { HashMap<Integer, ItemStack> returned = player.getInventory().addItem(itemStack); if (returned.size() > 0) { player.getWorld().dropItem(player.getLocation(), itemStack); } } } public void armorUpdated() { activeArmor.clear(); Player player = getPlayer(); if (player != null) { ItemStack[] armor = player.getInventory().getArmorContents(); for (int index = 0; index < armor.length; index++) { ItemStack armorItem = armor[index]; if (Wand.isWand(armorItem)) { activeArmor.put(index, controller.getWand(armorItem)); } } } if (activeWand != null) { activeWand.armorUpdated(); } updateEquipmentEffects(); } protected void updateEquipmentEffects() { damageReduction = 0; damageReductionPhysical = 0; damageReductionProjectiles = 0; damageReductionFalling = 0; damageReductionFire = 0; damageReductionExplosions = 0; spMultiplier = 1; List<PotionEffectType> currentEffects = new ArrayList<>(effectivePotionEffects.keySet()); LivingEntity entity = getLivingEntity(); effectivePotionEffects.clear(); if (activeWand != null && !activeWand.isPassive()) { damageReduction += activeWand.getDamageReduction(); damageReductionPhysical += activeWand.getDamageReductionPhysical(); damageReductionProjectiles += activeWand.getDamageReductionProjectiles(); damageReductionFalling += activeWand.getDamageReductionFalling(); damageReductionFire += activeWand.getDamageReductionFire(); damageReductionExplosions += activeWand.getDamageReductionExplosions(); effectivePotionEffects.putAll(activeWand.getPotionEffects()); spMultiplier *= activeWand.getSPMultiplier(); } // Don't add these together so things stay balanced! if (offhandWand != null && !offhandWand.isPassive()) { damageReduction = Math.max(damageReduction, offhandWand.getDamageReduction()); damageReductionPhysical += Math.max(damageReductionPhysical, offhandWand.getDamageReductionPhysical()); damageReductionProjectiles += Math.max(damageReductionProjectiles, offhandWand.getDamageReductionProjectiles()); damageReductionFalling += Math.max(damageReductionFalling, offhandWand.getDamageReductionFalling()); damageReductionFire += Math.max(damageReductionFire, offhandWand.getDamageReductionFire()); damageReductionExplosions += Math.max(damageReductionExplosions, offhandWand.getDamageReductionExplosions()); effectivePotionEffects.putAll(offhandWand.getPotionEffects()); spMultiplier *= offhandWand.getSPMultiplier(); } for (Wand armorWand : activeArmor.values()) { if (armorWand != null) { damageReduction += armorWand.getDamageReduction(); damageReductionPhysical += armorWand.getDamageReductionPhysical(); damageReductionProjectiles += armorWand.getDamageReductionProjectiles(); damageReductionFalling += armorWand.getDamageReductionFalling(); damageReductionFire += armorWand.getDamageReductionFire(); damageReductionExplosions += armorWand.getDamageReductionExplosions(); effectivePotionEffects.putAll(armorWand.getPotionEffects()); spMultiplier *= armorWand.getSPMultiplier(); } } damageReduction = Math.min(damageReduction, 1); damageReductionPhysical = Math.min(damageReductionPhysical, 1); damageReductionProjectiles = Math.min(damageReductionProjectiles, 1); damageReductionFalling = Math.min(damageReductionFalling, 1); damageReductionFire = Math.min(damageReductionFire, 1); damageReductionExplosions = Math.min(damageReductionExplosions, 1); if (entity != null) { for (PotionEffectType effectType : currentEffects) { if (!effectivePotionEffects.containsKey(effectType)) { entity.removePotionEffect(effectType); } } for (Map.Entry<PotionEffectType, Integer> effects : effectivePotionEffects.entrySet()) { PotionEffect effect = new PotionEffect(effects.getKey(), Integer.MAX_VALUE, effects.getValue(), true, false); CompatibilityUtils.applyPotionEffect(entity, effect); } } } public Collection<Wand> getActiveArmor() { return activeArmor.values(); } @Override public void deactivate() { deactivateWand(); deactivateAllSpells(true, true); removeActiveEffects(); } protected void deactivateWand() { // Close the wand inventory to make sure the player's normal inventory gets saved if (activeWand != null) { activeWand.deactivate(); } } @Override public void undoScheduled() { // Immediately rollback any auto-undo spells if (undoQueue != null) { int undid = undoQueue.undoScheduled(); if (undid != 0) { controller.info("Player " + getName() + " logging out, auto-undid " + undid + " spells"); } } int finished = finishPendingUndo(); if (finished != 0) { controller.info("Player " + getName() + " logging out, fast-forwarded undo for " + finished + " spells"); } if (undoQueue != null) { if (!undoQueue.isEmpty()) { if (controller.commitOnQuit()) { controller.info("Player logging out, committing constructions: " + getName()); undoQueue.commit(); } else { controller.info("Player " + getName() + " logging out with " + undoQueue.getSize() + " spells in their undo queue"); } } } } @Override public void removeItemsWithTag(String tag) { Player player = getPlayer(); if (player == null) return; PlayerInventory inventory = player.getInventory(); ItemStack[] contents = inventory.getContents(); for (int index = 0; index < contents.length; index++) { ItemStack item = contents[index]; if (item != null && item.getType() != Material.AIR && InventoryUtils.hasMeta(item, tag)) { inventory.setItem(index, null); } } boolean modified = false; ItemStack[] armor = inventory.getArmorContents(); for (int index = 0; index < armor.length; index++) { ItemStack item = armor[index]; if (item != null && item.getType() != Material.AIR && InventoryUtils.hasMeta(item, tag)) { modified = true; armor[index] = null; } } if (modified) { inventory.setArmorContents(armor); } } @Override public void setQuiet(boolean quiet) { this.quiet = quiet; } @Override public boolean isQuiet() { return quiet; } public void setDestinationWarp(String warp) { destinationWarp = warp; } @Override public boolean isAtMaxSkillPoints() { return getSkillPoints() >= controller.getSPMaximum(); } @Override public int getSkillPoints() { if (!data.contains(SKILL_POINT_KEY)) { data.set(SKILL_POINT_KEY, DEFAULT_SP); } // .. I thought Configuration section would auto-convert? I guess not! if (data.isString(SKILL_POINT_KEY)) { try { data.set(SKILL_POINT_KEY, Integer.parseInt(data.getString(SKILL_POINT_KEY))); } catch (Exception ex) { data.set(SKILL_POINT_KEY, 0); } } return data.getInt(SKILL_POINT_KEY); } @Override public void addSkillPoints(int delta) { int current = getSkillPoints(); String earnMessage = controller.getMessages().get("mage.earned_sp"); if (delta > 0 && earnMessage != null && !earnMessage.isEmpty()) { sendMessage(earnMessage.replace("$amount", Integer.toString(delta))); } setSkillPoints(current + delta); } @Override public void setSkillPoints(int amount) { // We don't allow negative skill points. boolean firstEarn = !data.contains(SKILL_POINT_KEY); amount = Math.max(amount, 0); int limit = controller.getSPMaximum(); if (limit > 0) { amount = Math.min(amount, limit); } data.set(SKILL_POINT_KEY, amount); if (activeWand != null && Wand.spMode != WandManaMode.NONE && activeWand.usesSP()) { if (firstEarn) { sendMessage(activeWand.getMessage("sp_instructions")); } activeWand.updateMana(); } } @Override public com.elmakers.mine.bukkit.api.wand.Wand getBoundWand(String template) { return boundWands.get(template); } @Override public WandUpgradePath getBoundWandPath(String templateKey) { com.elmakers.mine.bukkit.api.wand.Wand boundWand = boundWands.get(templateKey); if (boundWand != null) { return boundWand.getPath(); } return null; } public void setEntityData(EntityData entityData) { this.entityData = entityData; } @Override public List<Wand> getBoundWands() { return ImmutableList.copyOf(boundWands.values()); } public void updateHotbarStatus() { Player player = getPlayer(); if (player != null) { Location location = getLocation(); for (int i = 0; i < Wand.HOTBAR_SIZE; i++) { ItemStack spellItem = player.getInventory().getItem(i); String spellKey = Wand.getSpell(spellItem); if (spellKey != null) { Spell spell = getSpell(spellKey); if (spell != null) { int targetAmount = 1; long remainingCooldown = spell.getRemainingCooldown(); CastingCost requiredCost = spell.getRequiredCost(); boolean canCast = spell.canCast(location); if (canCast && remainingCooldown == 0 && requiredCost == null) { targetAmount = 1; } else if (!canCast) { targetAmount = 99; } else { canCast = remainingCooldown == 0; targetAmount = Wand.LiveHotbarCooldown ? (int)Math.min(Math.ceil((double)remainingCooldown / 1000), 99) : 99; if (Wand.LiveHotbarCooldown && requiredCost != null) { int mana = requiredCost.getMana(); if (mana > 0) { if (mana <= getEffectiveManaMax() && getEffectiveManaRegeneration() > 0) { float remainingMana = mana - getMana(); canCast = canCast && remainingMana <= 0; int targetManaTime = (int)Math.min(Math.ceil(remainingMana / getEffectiveManaRegeneration()), 99); targetAmount = Math.max(targetManaTime, targetAmount); } else { targetAmount = 99; canCast = false; } } } } if (targetAmount == 0) targetAmount = 1; boolean setAmount = false; MaterialAndData disabledIcon = spell.getDisabledIcon(); MaterialAndData spellIcon = spell.getIcon(); String urlIcon = spell.getIconURL(); String disabledUrlIcon = spell.getDisabledIconURL(); boolean usingURLIcon = (controller.isUrlIconsEnabled() || spellIcon == null || spellIcon.getMaterial() == Material.AIR) && urlIcon != null && !urlIcon.isEmpty(); if (disabledIcon != null && spellIcon != null && !usingURLIcon) { if (!canCast) { if (disabledIcon.isValid() && (disabledIcon.getMaterial() != spellItem.getType() || disabledIcon.getData() != spellItem.getDurability())) { disabledIcon.applyToItem(spellItem); } if (targetAmount == 99) { if (spellItem.getAmount() != 1) { spellItem.setAmount(1); } setAmount = true; } } else { if (spellIcon.isValid() && (spellIcon.getMaterial() != spellItem.getType() || spellIcon.getData() != spellItem.getDurability())) { spellIcon.applyToItem(spellItem); } } } else if (usingURLIcon && disabledUrlIcon != null && !disabledUrlIcon.isEmpty() && spellItem.getType() == Material.SKULL_ITEM) { String currentURL = InventoryUtils.getSkullURL(spellItem); if (!canCast) { if (!disabledUrlIcon.equals(currentURL)) { InventoryUtils.setNewSkullURL(spellItem, disabledUrlIcon); player.getInventory().setItem(i, spellItem); } if (targetAmount == 99) { if (spellItem.getAmount() != 1) { spellItem.setAmount(1); } setAmount = true; } } else { if (!urlIcon.equals(currentURL)) { InventoryUtils.setNewSkullURL(spellItem, urlIcon); player.getInventory().setItem(i, spellItem); } } } if (!setAmount && spellItem.getAmount() != targetAmount) { spellItem.setAmount(targetAmount); } } } } } } public long getLastBlockTime() { return lastBlockTime; } public void setLastBlockTime(long ms) { lastBlockTime = ms; } @Override public boolean isReflected(double angle) { if (activeWand != null && activeWand.isReflected(angle)) { return true; } if (offhandWand != null && offhandWand.isReflected(angle)) { return true; } return false; } @Override public boolean isBlocked(double angle) { if (activeWand != null && activeWand.isBlocked(angle)) { return true; } if (offhandWand != null && offhandWand.isBlocked(angle)) { return true; } return false; } @Override public float getSPMultiplier() { return spMultiplier; } @Override public @Nonnull MageProperties getProperties() { return properties; } @Override public double getVehicleMovementDirection() { LivingEntity li = getLivingEntity(); if (li == null) return 0.0f; return CompatibilityUtils.getForwardMovement(li); } @Override public double getVehicleStrafeDirection() { LivingEntity li = getLivingEntity(); if (li == null) return 0.0f; return CompatibilityUtils.getStrafeMovement(li); } @Override public boolean isVehicleJumping() { LivingEntity li = getLivingEntity(); if (li == null) return false; return CompatibilityUtils.isJumping(li); } @Override public void setVanished(boolean vanished) { Player thisPlayer = getPlayer(); if (thisPlayer != null && isVanished != vanished) { for (Player player : Bukkit.getOnlinePlayers()) { if (vanished) { player.hidePlayer(thisPlayer); } else { player.showPlayer(thisPlayer); } } } isVanished = vanished; } @Override public boolean isVanished() { return isVanished; } @Override public void setGlidingAllowed(boolean allow) { glidingAllowed = allow; } @Override public boolean isGlidingAllowed() { return glidingAllowed; } }
Add some debug messages for changing worlds and checking armor
Magic/src/main/java/com/elmakers/mine/bukkit/magic/Mage.java
Add some debug messages for changing worlds and checking armor
<ide><path>agic/src/main/java/com/elmakers/mine/bukkit/magic/Mage.java <ide> } <ide> <ide> public void onChangeWorld() { <add> sendDebugMessage("Changing worlds"); <ide> checkWandNextTick(true); <ide> if (CHANGE_WORLD_EQUIP_COOLDOWN > 0) { <ide> ignoreItemActivationUntil = System.currentTimeMillis() + CHANGE_WORLD_EQUIP_COOLDOWN; <ide> } <ide> <ide> public void armorUpdated() { <add> sendDebugMessage("Checking armor"); <ide> activeArmor.clear(); <ide> Player player = getPlayer(); <ide> if (player != null) <ide> for (int index = 0; index < armor.length; index++) { <ide> ItemStack armorItem = armor[index]; <ide> if (Wand.isWand(armorItem)) { <add> sendDebugMessage(" Found magic armor in slot " + index); <ide> activeArmor.put(index, controller.getWand(armorItem)); <ide> } <ide> }
Java
lgpl-2.1
910aee511077d6b7cdfc4f51d13d787b6c6ed341
0
eXist-db/exist,adamretter/exist,dizzzz/exist,adamretter/exist,wolfgangmm/exist,adamretter/exist,eXist-db/exist,ambs/exist,lcahlander/exist,wolfgangmm/exist,dizzzz/exist,windauer/exist,windauer/exist,dizzzz/exist,wolfgangmm/exist,ambs/exist,windauer/exist,ambs/exist,wolfgangmm/exist,lcahlander/exist,lcahlander/exist,ambs/exist,eXist-db/exist,dizzzz/exist,adamretter/exist,eXist-db/exist,windauer/exist,ambs/exist,dizzzz/exist,lcahlander/exist,lcahlander/exist,dizzzz/exist,wolfgangmm/exist,windauer/exist,lcahlander/exist,eXist-db/exist,wolfgangmm/exist,adamretter/exist,ambs/exist,adamretter/exist,eXist-db/exist,windauer/exist
package org.exist.xquery.functions.map; import com.evolvedbinary.j8fu.tuple.Tuple2; import com.ibm.icu.text.Collator; import io.lacuna.bifurcan.IEntry; import io.lacuna.bifurcan.IMap; import io.lacuna.bifurcan.Map; import org.exist.xquery.*; import org.exist.xquery.value.*; import javax.annotation.Nullable; import java.util.Iterator; import java.util.function.ToIntFunction; /** * Full implementation of the XDM map() type based on an * immutable hash-map. * * @author <a href="mailto:[email protected]">Adam Rettter</a> */ public class MapType extends AbstractMapType { private static final ToIntFunction<AtomicValue> KEY_HASH_FN = AtomicValue::hashCode; // TODO(AR) future potential optimisation... could the class member `map` remain `linear` ? private IMap<AtomicValue, Sequence> map; private int type = Type.ANY_TYPE; private static IMap<AtomicValue, Sequence> newMap(@Nullable final Collator collator) { return new Map<>(KEY_HASH_FN, (k1, k2) -> keysEqual(collator, k1, k2)); } public MapType(final XQueryContext context) { this(context,null); } public MapType(final XQueryContext context, @Nullable final Collator collator) { super(context); // if there's no collation, we'll use a hash map for better performance this.map = newMap(collator); } public MapType(final XQueryContext context, @Nullable final Collator collator, final AtomicValue key, final Sequence value) { super(context); this.map = newMap(collator).put(key, value); this.type = key.getType(); } public MapType(final XQueryContext context, @Nullable final Collator collator, final Iterable<Tuple2<AtomicValue, Sequence>> keyValues) { this(context, collator, keyValues.iterator()); } public MapType(final XQueryContext context, @Nullable final Collator collator, final Iterator<Tuple2<AtomicValue, Sequence>> keyValues) { super(context); // bulk put final IMap<AtomicValue, Sequence> map = newMap(collator).linear(); keyValues.forEachRemaining(kv -> map.put(kv._1, kv._2)); this.map = map.forked(); setKeyType(map); } public MapType(final XQueryContext context, final IMap<AtomicValue, Sequence> other, @Nullable final Integer type) { super(context); if (other.isLinear()) { throw new IllegalArgumentException("Map must be immutable, but linear Map was provided"); } this.map = other; if (type != null) { this.type = type; } else { setKeyType(map); } } public void add(final AbstractMapType other) { setKeyType(other.key() != null ? other.key().getType() : Type.ANY_TYPE); if(other instanceof MapType) { map = map.union(((MapType)other).map); } else { // create a transient map final IMap<AtomicValue, Sequence> newMap = map.linear(); for (final IEntry<AtomicValue, Sequence> entry : other) { newMap.put(entry.key(), entry.value()); } // return to immutable map map = newMap.forked(); } } @Override public AbstractMapType merge(final Iterable<AbstractMapType> others) { // create a transient map IMap<AtomicValue, Sequence> newMap = map.linear(); int prevType = type; for (final AbstractMapType other: others) { if (other instanceof MapType) { // MapType - optimise merge final MapType otherMap = (MapType) other; newMap = map.union(otherMap.map); if (prevType != otherMap.type) { prevType = Type.ITEM; } } else { // non MapType for (final IEntry<AtomicValue, Sequence> entry : other) { final AtomicValue key = entry.key(); newMap = newMap.put(key, entry.value()); if (prevType != key.getType()) { prevType = Type.ITEM; } } } } // return an immutable map return new MapType(context, newMap.forked(), prevType); } public void add(final AtomicValue key, final Sequence value) { setKeyType(key.getType()); map = map.put(key, value); } @Override public Sequence get(AtomicValue key) { key = convert(key); if (key == null) { return Sequence.EMPTY_SEQUENCE; } final Sequence result = map.get(key, null); return result == null ? Sequence.EMPTY_SEQUENCE : result; } @Override public AbstractMapType put(final AtomicValue key, final Sequence value) { final IMap<AtomicValue, Sequence> newMap = map.put(key, value); return new MapType(this.context, newMap, type == key.getType() ? type : Type.ITEM); } @Override public boolean contains(AtomicValue key) { key = convert(key); if (key == null) { return false; } return map.contains(key); } @Override public Sequence keys() { final ArrayListValueSequence seq = new ArrayListValueSequence((int)map.size()); for (final AtomicValue key: map.keys()) { seq.add(key); } return seq; } public AbstractMapType remove(final AtomicValue[] keysAtomicValues) { // create a transient map IMap<AtomicValue, Sequence> newMap = map.linear(); for (final AtomicValue key: keysAtomicValues) { newMap = newMap.remove(key); } // return an immutable map return new MapType(context, newMap.forked(), type); } @Override public int size() { return (int)map.size(); } @Override public Iterator<IEntry<AtomicValue, Sequence>> iterator() { return map.iterator(); } @Override public AtomicValue key() { if (map.size() > 0) { final IEntry<AtomicValue, Sequence> entry = map.nth(0); if (entry != null) { return entry.key(); } } return null; } @Override public Sequence value() { if (map.size() > 0) { final IEntry<AtomicValue, Sequence> entry = map.nth(0); if (entry != null) { return entry.value(); } } return null; } private void setKeyType(final int newType) { if (type == Type.ANY_TYPE) { type = newType; } else if (type != newType) { type = Type.ITEM; } } private void setKeyType(final IMap<AtomicValue, Sequence> newMap) { for (final AtomicValue newKey : newMap.keys()) { final int newType = newKey.getType(); if (type == Type.ANY_TYPE) { type = newType; } else if (type != newType) { type = Type.ITEM; break; // done! } } } private AtomicValue convert(final AtomicValue key) { if (type != Type.ANY_TYPE && type != Type.ITEM) { try { return key.convertTo(type); } catch (final XPathException e) { return null; } } return key; } @Override public int getKeyType() { return type; } public static <K, V> IMap<K, V> newLinearMap() { // TODO(AR) see bug in bifurcan - https://github.com/lacuna/bifurcan/issues/23 //return new LinearMap<K, V>(); return new Map<K, V>().linear(); } public static IMap<AtomicValue, Sequence> newLinearMap(@Nullable final Collator collator) { return newMap(collator).linear(); } }
exist-core/src/main/java/org/exist/xquery/functions/map/MapType.java
package org.exist.xquery.functions.map; import com.evolvedbinary.j8fu.tuple.Tuple2; import com.ibm.icu.text.Collator; import io.lacuna.bifurcan.IEntry; import io.lacuna.bifurcan.IMap; import io.lacuna.bifurcan.Map; import org.exist.xquery.*; import org.exist.xquery.value.*; import javax.annotation.Nullable; import java.util.Iterator; import java.util.function.ToIntFunction; /** * Full implementation of the XDM map() type based on an * immutable hash-map. * * @author <a href="mailto:[email protected]">Adam Rettter</a> */ public class MapType extends AbstractMapType { private static final ToIntFunction<AtomicValue> KEY_HASH_FN = AtomicValue::hashCode; // TODO(AR) future potential optimisation... could the class member `map` remain `linear` ? private IMap<AtomicValue, Sequence> map; private int type = Type.ANY_TYPE; private static IMap<AtomicValue, Sequence> newMap(@Nullable final Collator collator) { return new Map<>(KEY_HASH_FN, (k1, k2) -> keysEqual(collator, k1, k2)); } public MapType(final XQueryContext context) { this(context,null); } public MapType(final XQueryContext context, @Nullable final Collator collator) { super(context); // if there's no collation, we'll use a hash map for better performance this.map = newMap(collator); } public MapType(final XQueryContext context, @Nullable final Collator collator, final AtomicValue key, final Sequence value) { super(context); this.map = newMap(collator).put(key, value); this.type = key.getType(); } public MapType(final XQueryContext context, @Nullable final Collator collator, final Iterable<Tuple2<AtomicValue, Sequence>> keyValues) { this(context, collator, keyValues.iterator()); } public MapType(final XQueryContext context, @Nullable final Collator collator, final Iterator<Tuple2<AtomicValue, Sequence>> keyValues) { super(context); // bulk put final IMap<AtomicValue, Sequence> map = newMap(collator).linear(); keyValues.forEachRemaining(kv -> map.put(kv._1, kv._2)); this.map = map.forked(); //TODO(AR) this is incorrect all types to be checked! final long size = this.map.size(); if (size > 0) { setKeyType(this.map.nth(size - 1).key().getType()); } } public MapType(final XQueryContext context, final IMap<AtomicValue, Sequence> other, @Nullable final Integer type) { super(context); if (other.isLinear()) { throw new IllegalArgumentException("Map must be immutable, but linear Map was provided"); } this.map = other; if (type != null) { this.type = type; } else { //TODO(AR) this is incorrect all types to be checked! final long size = this.map.size(); if (size > 0) { setKeyType(this.map.nth(size - 1).key().getType()); } } } public void add(final AbstractMapType other) { setKeyType(other.key() != null ? other.key().getType() : Type.ANY_TYPE); if(other instanceof MapType) { map = map.union(((MapType)other).map); } else { // create a transient map final IMap<AtomicValue, Sequence> newMap = map.linear(); for (final IEntry<AtomicValue, Sequence> entry : other) { newMap.put(entry.key(), entry.value()); } // return to immutable map map = newMap.forked(); } } @Override public AbstractMapType merge(final Iterable<AbstractMapType> others) { // create a transient map IMap<AtomicValue, Sequence> newMap = map.linear(); int prevType = type; for (final AbstractMapType other: others) { if (other instanceof MapType) { // MapType - optimise merge final MapType otherMap = (MapType) other; newMap = map.union(otherMap.map); if (prevType != otherMap.type) { prevType = Type.ITEM; } } else { // non MapType for (final IEntry<AtomicValue, Sequence> entry : other) { final AtomicValue key = entry.key(); newMap = newMap.put(key, entry.value()); if (prevType != key.getType()) { prevType = Type.ITEM; } } } } // return an immutable map return new MapType(context, newMap.forked(), prevType); } public void add(final AtomicValue key, final Sequence value) { setKeyType(key.getType()); map = map.put(key, value); } @Override public Sequence get(AtomicValue key) { key = convert(key); if (key == null) { return Sequence.EMPTY_SEQUENCE; } final Sequence result = map.get(key, null); return result == null ? Sequence.EMPTY_SEQUENCE : result; } @Override public AbstractMapType put(final AtomicValue key, final Sequence value) { final IMap<AtomicValue, Sequence> newMap = map.put(key, value); return new MapType(this.context, newMap, type == key.getType() ? type : Type.ITEM); } @Override public boolean contains(AtomicValue key) { key = convert(key); if (key == null) { return false; } return map.contains(key); } @Override public Sequence keys() { final ArrayListValueSequence seq = new ArrayListValueSequence((int)map.size()); for (final AtomicValue key: map.keys()) { seq.add(key); } return seq; } public AbstractMapType remove(final AtomicValue[] keysAtomicValues) { // create a transient map IMap<AtomicValue, Sequence> newMap = map.linear(); for (final AtomicValue key: keysAtomicValues) { newMap = newMap.remove(key); } // return an immutable map return new MapType(context, newMap.forked(), type); } @Override public int size() { return (int)map.size(); } @Override public Iterator<IEntry<AtomicValue, Sequence>> iterator() { return map.iterator(); } @Override public AtomicValue key() { if (map.size() > 0) { final IEntry<AtomicValue, Sequence> entry = map.nth(0); if (entry != null) { return entry.key(); } } return null; } @Override public Sequence value() { if (map.size() > 0) { final IEntry<AtomicValue, Sequence> entry = map.nth(0); if (entry != null) { return entry.value(); } } return null; } private void setKeyType(final int newType) { if (type == Type.ANY_TYPE) { type = newType; } else if (type != newType) { type = Type.ITEM; } } private AtomicValue convert(final AtomicValue key) { if (type != Type.ANY_TYPE && type != Type.ITEM) { try { return key.convertTo(type); } catch (final XPathException e) { return null; } } return key; } @Override public int getKeyType() { return type; } public static <K, V> IMap<K, V> newLinearMap() { // TODO(AR) see bug in bifurcan - https://github.com/lacuna/bifurcan/issues/23 //return new LinearMap<K, V>(); return new Map<K, V>().linear(); } public static IMap<AtomicValue, Sequence> newLinearMap(@Nullable final Collator collator) { return newMap(collator).linear(); } }
[bugfix] Ensure types are set based on all keys
exist-core/src/main/java/org/exist/xquery/functions/map/MapType.java
[bugfix] Ensure types are set based on all keys
<ide><path>xist-core/src/main/java/org/exist/xquery/functions/map/MapType.java <ide> keyValues.forEachRemaining(kv -> map.put(kv._1, kv._2)); <ide> this.map = map.forked(); <ide> <del> //TODO(AR) this is incorrect all types to be checked! <del> final long size = this.map.size(); <del> if (size > 0) { <del> setKeyType(this.map.nth(size - 1).key().getType()); <del> } <add> setKeyType(map); <ide> } <ide> <ide> public MapType(final XQueryContext context, final IMap<AtomicValue, Sequence> other, @Nullable final Integer type) { <ide> if (type != null) { <ide> this.type = type; <ide> } else { <del> //TODO(AR) this is incorrect all types to be checked! <del> final long size = this.map.size(); <del> if (size > 0) { <del> setKeyType(this.map.nth(size - 1).key().getType()); <del> } <add> setKeyType(map); <ide> } <ide> } <ide> <ide> } <ide> } <ide> <add> private void setKeyType(final IMap<AtomicValue, Sequence> newMap) { <add> for (final AtomicValue newKey : newMap.keys()) { <add> final int newType = newKey.getType(); <add> <add> if (type == Type.ANY_TYPE) { <add> type = newType; <add> } <add> else if (type != newType) { <add> type = Type.ITEM; <add> break; // done! <add> } <add> } <add> } <add> <ide> private AtomicValue convert(final AtomicValue key) { <ide> if (type != Type.ANY_TYPE && type != Type.ITEM) { <ide> try {
Java
apache-2.0
48be9e2be68150a65925605565dd87c6b48b7da5
0
gbif/dwca-io
package org.gbif.dwc; import java.io.IOException; import java.nio.file.Path; /** * Collections of static methods to work with Darwin Core (archive) files. * * TODO: methods without validation, probably for use with the validator. */ public class DwcFiles { /** * Collections of static methods, no constructors. */ private DwcFiles() { } /** * Build a Darwin Core {@link Archive} from a location. The location can be an uncompressed directory or an uncompressed file. * * @param dwcLocation the location of an expanded Darwin Core Archive directory, or a single Darwin Core text file * * @return new {@link Archive}, never null. But, the {@link Archive} can be empty (e.g. no core) */ public static Archive fromLocation(Path dwcLocation) throws IOException, UnsupportedArchiveException { // delegate to InternalDwcFileFactory Archive archive = InternalDwcFileFactory.fromLocation(dwcLocation); archive.validate(); return archive; } /** * Build a Darwin Core {@link Archive} from a location. The location can be an uncompressed directory or an uncompressed file. * * This method skips basic validation, and should only be used by a tool that does its own validation. * * @param dwcLocation the location of an expanded Darwin Core Archive directory, or a single Darwin Core text file * * @return new {@link Archive}, never null. But, the {@link Archive} can be empty (e.g. no core) */ public static Archive fromLocationSkipValidation(Path dwcLocation) throws IOException, UnsupportedArchiveException { // delegate to InternalDwcFileFactory return InternalDwcFileFactory.fromLocation(dwcLocation); } /** * Build an {@link Archive} from a compressed file. The compressed file will be extracted in the provided directory. * The supported compressions are zip and gzip. * * @param dwcaLocation the location of a compressed Darwin Core Archive * @param destination the destination of the uncompressed content. * * @return new {@link Archive}, never null. But, the {@link Archive} can be empty (e.g. no core) * * @throws IOException * @throws UnsupportedArchiveException */ public static Archive fromCompressed(Path dwcaLocation, Path destination) throws IOException, UnsupportedArchiveException { // delegate to InternalDwcFileFactory Archive archive = InternalDwcFileFactory.fromCompressed(dwcaLocation, destination); archive.validate(); return archive; } }
src/main/java/org/gbif/dwc/DwcFiles.java
package org.gbif.dwc; import java.io.IOException; import java.nio.file.Path; /** * Collections of static methods to work with Darwin Core (archive) files. * * TODO: methods without validation, probably for use with the validator. */ public class DwcFiles { /** * Collections of static methods, no constructors. */ private DwcFiles() { } /** * Build a Darwin Core {@link Archive} from a location. The location can be an uncompressed directory or an uncompressed file. * * @param dwcLocation the location of an expanded Darwin Core Archive directory, or a single Darwin Core text file * * @return new {@link Archive}, never null. But, the {@link Archive} can be empty (e.g. no core) */ public static Archive fromLocation(Path dwcLocation) throws IOException, UnsupportedArchiveException { // delegate to InternalDwcFileFactory Archive archive = InternalDwcFileFactory.fromLocation(dwcLocation); archive.validate(); return archive; } /** * Build an {@link Archive} from a compressed file. The compressed file will be extracted in the provided directory. * The supported compressions are zip and gzip. * * @param dwcaLocation the location of a compressed Darwin Core Archive * @param destination the destination of the uncompressed content. * * @return new {@link Archive}, never null. But, the {@link Archive} can be empty (e.g. no core) * * @throws IOException * @throws UnsupportedArchiveException */ public static Archive fromCompressed(Path dwcaLocation, Path destination) throws IOException, UnsupportedArchiveException { // delegate to InternalDwcFileFactory Archive archive = InternalDwcFileFactory.fromCompressed(dwcaLocation, destination); archive.validate(); return archive; } }
Add method to skip validation, for use by the validator.
src/main/java/org/gbif/dwc/DwcFiles.java
Add method to skip validation, for use by the validator.
<ide><path>rc/main/java/org/gbif/dwc/DwcFiles.java <ide> } <ide> <ide> /** <add> * Build a Darwin Core {@link Archive} from a location. The location can be an uncompressed directory or an uncompressed file. <add> * <add> * This method skips basic validation, and should only be used by a tool that does its own validation. <add> * <add> * @param dwcLocation the location of an expanded Darwin Core Archive directory, or a single Darwin Core text file <add> * <add> * @return new {@link Archive}, never null. But, the {@link Archive} can be empty (e.g. no core) <add> */ <add> public static Archive fromLocationSkipValidation(Path dwcLocation) throws IOException, UnsupportedArchiveException { <add> // delegate to InternalDwcFileFactory <add> return InternalDwcFileFactory.fromLocation(dwcLocation); <add> } <add> <add> /** <ide> * Build an {@link Archive} from a compressed file. The compressed file will be extracted in the provided directory. <ide> * The supported compressions are zip and gzip. <ide> *
Java
apache-2.0
dc8cb713701f03cfbb55d55ece6f36a59b2499d5
0
Thaedrik/eventbroker
/* * Copyright (c) 2012-2015 Codestorming.org * * 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. * * Contributors * Codestorming - initial API and implementation */ package org.codestorming.broker; /** * A <em>non-mutable</em> {@link Event} implementation. * * @author Thaedrik &lt;[email protected]&gt; */ public class BasicEvent implements Event { protected final String type; protected final Object data; protected String cachedToString; /** * Creates a new {@code BasicEvent}. * * @param type The event type. * @param data The event data. */ public BasicEvent(String type, Object data) { this.type = type; this.data = data; } @Override public String getType() { return type; } @Override @SuppressWarnings("unchecked") public <T> T getData() { return (T) data; } @Override public String toString() { if (cachedToString == null) { cachedToString = "{eventType : \"" + type + "\", data : " + data + "}"; } return cachedToString; } }
src/main/java/org/codestorming/broker/BasicEvent.java
/* * Copyright (c) 2012-2015 Codestorming.org * * 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. * * Contributors * Codestorming - initial API and implementation */ package org.codestorming.broker; /** * A <em>non-mutable</em> {@link Event} implementation. * * @author Thaedrik &lt;[email protected]&gt; */ public class BasicEvent implements Event { protected final String type; protected final Object data; /** * Creates a new {@code BasicEvent}. * * @param type The event type. * @param data The event data. */ public BasicEvent(String type, Object data) { this.type = type; this.data = data; } @Override public String getType() { return type; } @Override @SuppressWarnings("unchecked") public <T> T getData() { return (T) data; } }
Added a toString() to BasicEvent
src/main/java/org/codestorming/broker/BasicEvent.java
Added a toString() to BasicEvent
<ide><path>rc/main/java/org/codestorming/broker/BasicEvent.java <ide> <ide> protected final Object data; <ide> <add> protected String cachedToString; <add> <ide> /** <ide> * Creates a new {@code BasicEvent}. <ide> * <ide> public <T> T getData() { <ide> return (T) data; <ide> } <add> <add> @Override <add> public String toString() { <add> if (cachedToString == null) { <add> cachedToString = "{eventType : \"" + type + "\", data : " + data + "}"; <add> } <add> return cachedToString; <add> } <ide> }
Java
apache-2.0
3daeca3faaf6bb7f1a8b86a770d38c8a22ef8a0f
0
BonDyka/abondarev,BonDyka/abondarev,BonDyka/abondarev
package ru.job4j.max; /** * The class created for maximum of two numbers. * * @author abondarev * @since 11.07.2017 */ public class Max { /** * The method calculate maximum of two numbers. * * @param first is the first argument. * @param second is the second argument. * @return max of two numbers. */ public int max(int first, int second) { return (first > second) ? first : second; } /** * The method calculates maximum of three numbers. * * @param first is the first argument. * @param second is the second argument. * @param third is the second argument. * @return max of three numbers. */ public int max(int first, int second, int third) { return this.max(first, this.max(second, third)); } }
chapter_001/src/main/java/ru/job4j/max/Max.java
package ru.job4j.max; /** * The class created for maximum of two numbers. * * @author abondarev * @since 11.07.2017 */ public class Max { /** * The method calculate maximum of two numbers. * * @param first is the first argument. * @param second is the second argument. * @return max of two numbers. */ public int max(int first, int second) { return (first > second) ? first : second; } /** * The method calculates maximum of three numbers. * * @param first is the first argument. * @param second is the second argument. * @param third is the second argument. * @return max of three numbers. */ public int max(int first, int second, int third) { int maxFirstSecond = this.max(first, second); int result = this.max(maxFirstSecond, third); return result; } }
3.4. Максимум из трех чисел [ #190]. Fixed
chapter_001/src/main/java/ru/job4j/max/Max.java
3.4. Максимум из трех чисел [ #190]. Fixed
<ide><path>hapter_001/src/main/java/ru/job4j/max/Max.java <ide> * @return max of three numbers. <ide> */ <ide> public int max(int first, int second, int third) { <del> int maxFirstSecond = this.max(first, second); <del> int result = this.max(maxFirstSecond, third); <del> return result; <add> return this.max(first, this.max(second, third)); <ide> } <ide> }
Java
epl-1.0
acd89405f25db81db1353a7f489846ea5386f322
0
elexis/elexis-server,elexis/elexis-server
package info.elexis.server.core.connector.elexis.jpa.model.annotated; import java.time.LocalDate; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.eclipse.persistence.annotations.Convert; import org.eclipse.persistence.annotations.Converter; import org.eclipse.persistence.annotations.ReadTransformer; import org.eclipse.persistence.annotations.WriteTransformer; import info.elexis.server.core.connector.elexis.jpa.model.annotated.converter.ElexisDBStringDateConverter; import info.elexis.server.core.connector.elexis.jpa.model.annotated.transformer.ElexisDBStringDateTimeTransformer; @Entity @Table(name = "laborwerte") public class LabResult extends AbstractDBObjectIdDeletedExtInfo { @OneToOne @JoinColumn(name = "PatientID") private Kontakt patient; @Converter(name = "ElexisDBStringDateConverter", converterClass = ElexisDBStringDateConverter.class) @Convert("ElexisDBStringDateConverter") @Column(name = "datum") private LocalDate date; @Column(length = 6) private String zeit; @OneToOne @JoinColumn(name = "ItemID") private LabItem item; @Column(length = 255, name = "resultat") private String result; @Convert(value = "IntegerStringConverter") private int flags; @Column(length = 30) private String origin; @Lob @Column(name = "Kommentar") private String comment; @Column(length = 255) private String unit; @ReadTransformer(transformerClass = ElexisDBStringDateTimeTransformer.class) @WriteTransformer(transformerClass = ElexisDBStringDateTimeTransformer.class) private LocalDateTime analysetime; @ReadTransformer(transformerClass = ElexisDBStringDateTimeTransformer.class) @WriteTransformer(transformerClass = ElexisDBStringDateTimeTransformer.class) private LocalDateTime observationtime; @ReadTransformer(transformerClass = ElexisDBStringDateTimeTransformer.class) @WriteTransformer(transformerClass = ElexisDBStringDateTimeTransformer.class) private LocalDateTime transmissiontime; @Column(length = 255) private String refMale; @Column(length = 255) private String refFemale; @Column(length = 25) private String originId; @Transient public boolean isFlagged(final int flag){ return (getFlags() & flag) != 0; } public Kontakt getPatient() { return patient; } public void setPatient(Kontakt patient) { this.patient = patient; } public String getZeit() { return zeit; } public void setZeit(String zeit) { this.zeit = zeit; } public LabItem getItem() { return item; } public void setItem(LabItem item) { this.item = item; } public String getOrigin() { return origin; } public void setOrigin(String origin) { this.origin = origin; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public String getRefMale() { return refMale; } public void setRefMale(String refMale) { this.refMale = refMale; } public String getRefFemale() { return refFemale; } public void setRefFemale(String refFemale) { this.refFemale = refFemale; } public String getOriginId() { return originId; } public void setOriginId(String originId) { this.originId = originId; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public LocalDateTime getAnalysetime() { return analysetime; } public void setAnalysetime(LocalDateTime analysetime) { this.analysetime = analysetime; } public LocalDateTime getObservationtime() { return observationtime; } public void setObservationtime(LocalDateTime observationtime) { this.observationtime = observationtime; } public LocalDateTime getTransmissiontime() { return transmissiontime; } public void setTransmissiontime(LocalDateTime transmissiontime) { this.transmissiontime = transmissiontime; } public int getFlags() { return flags; } public void setFlags(int flags) { this.flags = flags; } }
bundles/es.core.connector.elexis.jpa/src/info/elexis/server/core/connector/elexis/jpa/model/annotated/LabResult.java
package info.elexis.server.core.connector.elexis.jpa.model.annotated; import java.time.LocalDate; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.OneToOne; import javax.persistence.Table; import org.eclipse.persistence.annotations.Convert; import org.eclipse.persistence.annotations.Converter; import org.eclipse.persistence.annotations.ReadTransformer; import org.eclipse.persistence.annotations.WriteTransformer; import info.elexis.server.core.connector.elexis.jpa.model.annotated.converter.ElexisDBStringDateConverter; import info.elexis.server.core.connector.elexis.jpa.model.annotated.transformer.ElexisDBStringDateTimeTransformer; @Entity @Table(name = "laborwerte") public class LabResult extends AbstractDBObjectIdDeletedExtInfo { @OneToOne @JoinColumn(name = "PatientID") private Kontakt patient; @Converter(name = "ElexisDBStringDateConverter", converterClass = ElexisDBStringDateConverter.class) @Convert("ElexisDBStringDateConverter") @Column(name = "datum") private LocalDate date; @Column(length = 6) private String zeit; @OneToOne @JoinColumn(name = "ItemID") private LabItem item; @Column(length = 255, name = "resultat") private String result; @Convert(value = "IntegerStringConverter") private int flags; @Column(length = 30) private String origin; @Lob @Column(name = "Kommentar") private String comment; @Column(length = 255) private String unit; @ReadTransformer(transformerClass = ElexisDBStringDateTimeTransformer.class) @WriteTransformer(transformerClass = ElexisDBStringDateTimeTransformer.class) private LocalDateTime analysetime; @ReadTransformer(transformerClass = ElexisDBStringDateTimeTransformer.class) @WriteTransformer(transformerClass = ElexisDBStringDateTimeTransformer.class) private LocalDateTime observationtime; @ReadTransformer(transformerClass = ElexisDBStringDateTimeTransformer.class) @WriteTransformer(transformerClass = ElexisDBStringDateTimeTransformer.class) private LocalDateTime transmissiontime; @Column(length = 255) private String refMale; @Column(length = 255) private String refFemale; @Column(length = 25) private String originId; public Kontakt getPatient() { return patient; } public void setPatient(Kontakt patient) { this.patient = patient; } public String getZeit() { return zeit; } public void setZeit(String zeit) { this.zeit = zeit; } public LabItem getItem() { return item; } public void setItem(LabItem item) { this.item = item; } public String getOrigin() { return origin; } public void setOrigin(String origin) { this.origin = origin; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public String getRefMale() { return refMale; } public void setRefMale(String refMale) { this.refMale = refMale; } public String getRefFemale() { return refFemale; } public void setRefFemale(String refFemale) { this.refFemale = refFemale; } public String getOriginId() { return originId; } public void setOriginId(String originId) { this.originId = originId; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public LocalDateTime getAnalysetime() { return analysetime; } public void setAnalysetime(LocalDateTime analysetime) { this.analysetime = analysetime; } public LocalDateTime getObservationtime() { return observationtime; } public void setObservationtime(LocalDateTime observationtime) { this.observationtime = observationtime; } public LocalDateTime getTransmissiontime() { return transmissiontime; } public void setTransmissiontime(LocalDateTime transmissiontime) { this.transmissiontime = transmissiontime; } public int getFlags() { return flags; } public void setFlags(int flags) { this.flags = flags; } }
Provide transient LabResult#isFlagged
bundles/es.core.connector.elexis.jpa/src/info/elexis/server/core/connector/elexis/jpa/model/annotated/LabResult.java
Provide transient LabResult#isFlagged
<ide><path>undles/es.core.connector.elexis.jpa/src/info/elexis/server/core/connector/elexis/jpa/model/annotated/LabResult.java <ide> import javax.persistence.Lob; <ide> import javax.persistence.OneToOne; <ide> import javax.persistence.Table; <add>import javax.persistence.Transient; <ide> <ide> import org.eclipse.persistence.annotations.Convert; <ide> import org.eclipse.persistence.annotations.Converter; <ide> @Column(length = 25) <ide> private String originId; <ide> <add> @Transient <add> public boolean isFlagged(final int flag){ <add> return (getFlags() & flag) != 0; <add> } <add> <ide> public Kontakt getPatient() { <ide> return patient; <ide> }
JavaScript
mit
59f1146c13b598d2f0658a3f420694406ccd7eec
0
rickatech/dungeon,rickatech/dungeon
// http://www.crockford.com/javascript/private.html dungeon_display_file = 'dungeon_ajax.php'; head_display_file = 'head_ajax.php'; nav_display_file = 'nav_ajax.php'; function popUp(URL) { day = new Date(); id = day.getTime(); // args = 'toolbar = 0, scrollbars = 0, location = 0, statusbar = 0, menubar = 0'; // args = args + ', menubar = 0, resizable = 0, width = 1024 ,height = 768'; // eval("page" + id + " = window.open(URL, '" + id + "', args);"); window.open(URL); } function detectKey(event) { if (event.keyCode == 13) { document['login'].submit(); } } function detectKeyLogin(event) { if (event.keyCode == 13) { head_login(); } } function hideshow0(which) { if (!document.getElementById) return; if (which.style.display == "none") which.style.display = "block"; else if (which.style.display == "block") which.style.display = "none"; } function showtest(which) { if (!document.getElementById) return; document.getElementById(which).innerHTML = '<center><table style=\"margin: auto;\" id=\"rentab\"><tr><td>[ reset complete ]</td></tr></table></center>'; } function showactive(which) { /* the table with player view is reloaded upon action request, change color of table background to indicate a request is in progress */ if (!document.getElementById) return; document.getElementById(which).style.backgroundColor = 'yellow'; } function hideshow(which) { if (!document.getElementById) return; if (document.getElementById(which).style.display == "none") document.getElementById(which).style.display = "block"; else if (document.getElementById(which).style.display == "block") document.getElementById(which).style.display = "none"; } function head_set(which) { // FUTURE, obsolete function? headhq.url = head_display_file+'?ajax=1'; headhq.div = "head"; headhq.do_hq(); } function head_login() { un = document.getElementById("username").value; pw = document.getElementById("password").value; //alert('username: ' + un + ', ' + pw); headhq.url = head_display_file+'?ajax=1&username='+un+'&password='+pw; headhq.div = "head"; headhq.do_now(); // was .do_hq but, but this works better on slow connections //alert('login 2'); navhq.do_now(); // refresh navigation controls cal_set('calout'); // refresh dungeon view } function head_logout() { //alert('logout'); headhq.url = head_display_file+'?ajax=0&logout'; headhq.div = "head"; headhq.do_now(); // was .do_hq but, but this works better on slow connections //alert('logout 2'); navhq.do_now(); // refresh navigation controls cal_set('calout'); // refresh/clear dungeon view } function cal_set(which) { // future: supported GET parameters should be in a config file // future: ghost set/prev buttons until refresh is complete calhq.url = dungeon_display_file+'?ajax=1'; if (y = document.getElementById('year')) { if (y.value.length != 0) calhq.url = calhq.url + '&year=' + y.value; } if (m = document.getElementById('month')) { if (m.value.length != 0) calhq.url = calhq.url + '&month=' + m.value; } if (d = document.getElementById('day')) { if (d.value.length != 0) calhq.url = calhq.url + '&day=' + d.value; } if (w = document.getElementById('weeks')) { if ((w.value.length != 0) && (w.value > 0) && (w.value <= 52)) calhq.url = calhq.url + '&weeks=' + w.value; } if (b = document.getElementById('bill')) { if (b.value.length != 0) calhq.url = calhq.url + '&bill=' + b.value; } if (f = document.getElementById('filter')) { if (f.value.length != 0) calhq.url = calhq.url + '&filter=' + f.value; } calhq.div = "calout"; calhq.do_hq(); } function nav_stepforw(which) { calhq.url = dungeon_display_file+'?ajax=1&cmd=stepforw'; calhq.div = "calout"; calhq.do_hq(); } function nav_stepback(which) { calhq.url = dungeon_display_file+'?ajax=1&cmd=stepback'; calhq.div = "calout"; calhq.do_hq(); } function nav_stepleft(which) { calhq.url = dungeon_display_file+'?ajax=1&cmd=stepleft'; calhq.div = "calout"; calhq.do_hq(); } function nav_steprght(which) { calhq.url = dungeon_display_file+'?ajax=1&cmd=steprght'; calhq.div = "calout"; calhq.do_hq(); } function cal_newmap(which) { calhq.url = dungeon_display_file+'?ajax=1&newmap'; calhq.div = "calout"; calhq.do_hq(); } function nav_turnrght(which) { calhq.url = dungeon_display_file+'?ajax=1&cmd=turnrght'; calhq.div = "calout"; calhq.do_hq(); } function nav_turnleft(which) { calhq.url = dungeon_display_file+'?ajax=1&cmd=turnleft'; calhq.div = "calout"; calhq.do_hq(); } function cal_prev(which) { /* set previous week, refresh calendar */ if (p1 = document.getElementById('pprreevv')) { a = p1.innerHTML.split("-"); if (y = document.getElementById('year')) { y.value = a[0]; } if (m = document.getElementById('month')) { m.value = a[1]; } if (d = document.getElementById('day')) { d.value = a[2]; } cal_set(which); } } function list_set(which) { calhq.url = 'ajax_list.php?offset=0&range=400'; calhq.div = "calout"; calhq.do_hq(); } function to_do_set(which) { calhq.url = 'ajax_todo.php'; calhq.div = "calout"; calhq.do_hq(); } function book_set(which) { calhq.url = 'ajax_book.php'; calhq.div = "calout"; calhq.do_hq(); } function users_set(which) { //calhq.url = 'ajax_users.php'; calhq.url = 'ajax_cvleads.php'; calhq.div = "calout"; calhq.do_hq(); } function class_hq(param) { /* this is a 'class' to wrap around http_request */ /* consider adding .prototype? http://javascript.about.com/library/bltut35.htm */ /* 'constructor' logic goes here */ this.div = param; // delete(this.url); // delete(this.req); var this_ref = this; /* var here makes this a private property */ this.do_hq = function () { /* method - asynchronous content load */ // alert('do_hq() ' + this.url); // delete this.req; // if (typeof(this.req) == 'undefined') { // IE7 doesn't support this? // alert('req undefined'); this.req = new XMLHttpRequest(); // } /* http://www.mikechambers.com/blog/2006/01/31/encapsulating-ajax-xmlhttprequest-calls-within-javascript-classes/ */ this.req.onreadystatechange = function() { this_ref.do_alert()}; this.req.open('GET', this.url, true); this.req.send(null); }; this.do_alert = function () { /* method - callback for asynchronous content load */ // alert('readyState ' + this.req.readyState); if (this.req.readyState == 4) { // alert('do_alert() ' + this.url + ', status' + this.req.status); if (this.req.status == 200) { document.getElementById(this.div).innerHTML = this.req.responseText; } else { alert('There was a problem with the request.'); } // delete this.req; } }; this.do_now = function () { // alert('do_now() ' + this.url); /* method - immediate content load */ if (typeof(this.req) == 'undefined') { // alert('req undefined'); this.req = new XMLHttpRequest(); } /* using false here stalls page load until AJAX call completes */ this.req.open('GET', this.url, false); this.req.send(null); document.getElementById(this.div).innerHTML = this.req.responseText; // delete this.req; }; } function formpop(appt) { if (appt == "signup") { newWindow = window.open("signup.php", "newWin", "status=yes, width=480, height=240"); return; } appt_spl = appt+''; if (appt_spl.substring(0, 3) == "new") { // looking for new appt date encoded as: new-2010-11-12 appt_spl = appt.split("-"); newWindow = window.open("popup/appt.php?appt=new&year="+appt_spl[1]+"&month="+appt_spl[2]+"&day="+appt_spl[3], "newWin", "status=yes, width=300, height=360"); } else { newWindow = window.open("popup/appt.php?appt="+appt, "newWin", "status=yes, width=300, height=360"); } }
ajax.js
// http://www.crockford.com/javascript/private.html dungeon_display_file = 'dungeon_ajax.php'; head_display_file = 'head_ajax.php'; nav_display_file = 'nav_ajax.php'; function popUp(URL) { day = new Date(); id = day.getTime(); // args = 'toolbar = 0, scrollbars = 0, location = 0, statusbar = 0, menubar = 0'; // args = args + ', menubar = 0, resizable = 0, width = 1024 ,height = 768'; // eval("page" + id + " = window.open(URL, '" + id + "', args);"); window.open(URL); } function detectKey(event) { if (event.keyCode == 13) { document['login'].submit(); } } function detectKeyLogin(event) { if (event.keyCode == 13) { head_login(); } } function hideshow0(which) { if (!document.getElementById) return; if (which.style.display == "none") which.style.display = "block"; else if (which.style.display == "block") which.style.display = "none"; } function showtest(which) { if (!document.getElementById) return; document.getElementById(which).innerHTML = '<center><table style=\"margin: auto;\" id=\"rentab\"><tr><td>[ reset complete ]</td></tr></table></center>'; } function showactive(which) { /* the table with player view is reloaded upon action request, change color of table background to indicate a request is in progress */ if (!document.getElementById) return; document.getElementById(which).style.backgroundColor = 'yellow'; } function hideshow(which) { if (!document.getElementById) return; if (document.getElementById(which).style.display == "none") document.getElementById(which).style.display = "block"; else if (document.getElementById(which).style.display == "block") document.getElementById(which).style.display = "none"; } function head_set(which) { headhq.url = head_display_file+'?ajax=1'; headhq.div = "head"; headhq.do_hq(); } function head_login() { un = document.getElementById("username").value; pw = document.getElementById("password").value; //alert('username: ' + un + ', ' + pw); headhq.url = head_display_file+'?ajax=1&username='+un+'&password='+pw; headhq.div = "head"; headhq.do_hq(); //alert('login 2'); navhq.do_now(); // refresh navigation controls cal_set('calout'); // refresh dungeon view } function head_logout() { //alert('logout'); headhq.url = head_display_file+'?ajax=0&logout'; headhq.div = "head"; headhq.do_hq(); //alert('logout 2'); navhq.do_now(); // refresh navigation controls cal_set('calout'); // refresh/clear dungeon view } function cal_set(which) { // future: supported GET parameters should be in a config file // future: ghost set/prev buttons until refresh is complete calhq.url = dungeon_display_file+'?ajax=1'; if (y = document.getElementById('year')) { if (y.value.length != 0) calhq.url = calhq.url + '&year=' + y.value; } if (m = document.getElementById('month')) { if (m.value.length != 0) calhq.url = calhq.url + '&month=' + m.value; } if (d = document.getElementById('day')) { if (d.value.length != 0) calhq.url = calhq.url + '&day=' + d.value; } if (w = document.getElementById('weeks')) { if ((w.value.length != 0) && (w.value > 0) && (w.value <= 52)) calhq.url = calhq.url + '&weeks=' + w.value; } if (b = document.getElementById('bill')) { if (b.value.length != 0) calhq.url = calhq.url + '&bill=' + b.value; } if (f = document.getElementById('filter')) { if (f.value.length != 0) calhq.url = calhq.url + '&filter=' + f.value; } calhq.div = "calout"; calhq.do_hq(); } function nav_stepforw(which) { calhq.url = dungeon_display_file+'?ajax=1&cmd=stepforw'; calhq.div = "calout"; calhq.do_hq(); } function nav_stepback(which) { calhq.url = dungeon_display_file+'?ajax=1&cmd=stepback'; calhq.div = "calout"; calhq.do_hq(); } function nav_stepleft(which) { calhq.url = dungeon_display_file+'?ajax=1&cmd=stepleft'; calhq.div = "calout"; calhq.do_hq(); } function nav_steprght(which) { calhq.url = dungeon_display_file+'?ajax=1&cmd=steprght'; calhq.div = "calout"; calhq.do_hq(); } function cal_newmap(which) { calhq.url = dungeon_display_file+'?ajax=1&newmap'; calhq.div = "calout"; calhq.do_hq(); } function nav_turnrght(which) { calhq.url = dungeon_display_file+'?ajax=1&cmd=turnrght'; calhq.div = "calout"; calhq.do_hq(); } function nav_turnleft(which) { calhq.url = dungeon_display_file+'?ajax=1&cmd=turnleft'; calhq.div = "calout"; calhq.do_hq(); } function cal_prev(which) { /* set previous week, refresh calendar */ if (p1 = document.getElementById('pprreevv')) { a = p1.innerHTML.split("-"); if (y = document.getElementById('year')) { y.value = a[0]; } if (m = document.getElementById('month')) { m.value = a[1]; } if (d = document.getElementById('day')) { d.value = a[2]; } cal_set(which); } } function list_set(which) { calhq.url = 'ajax_list.php?offset=0&range=400'; calhq.div = "calout"; calhq.do_hq(); } function to_do_set(which) { calhq.url = 'ajax_todo.php'; calhq.div = "calout"; calhq.do_hq(); } function book_set(which) { calhq.url = 'ajax_book.php'; calhq.div = "calout"; calhq.do_hq(); } function users_set(which) { //calhq.url = 'ajax_users.php'; calhq.url = 'ajax_cvleads.php'; calhq.div = "calout"; calhq.do_hq(); } function class_hq(param) { /* this is a 'class' to wrap around http_request */ /* consider adding .prototype? http://javascript.about.com/library/bltut35.htm */ /* 'constructor' logic goes here */ this.div = param; // delete(this.url); // delete(this.req); var this_ref = this; /* var here makes this a private property */ this.do_hq = function () { /* method - asynchronous content load */ // alert('do_hq() ' + this.url); // delete this.req; // if (typeof(this.req) == 'undefined') { // IE7 doesn't support this? // alert('req undefined'); this.req = new XMLHttpRequest(); // } /* http://www.mikechambers.com/blog/2006/01/31/encapsulating-ajax-xmlhttprequest-calls-within-javascript-classes/ */ this.req.onreadystatechange = function() { this_ref.do_alert()}; this.req.open('GET', this.url, true); this.req.send(null); }; this.do_alert = function () { /* method - callback for asynchronous content load */ // alert('readyState ' + this.req.readyState); if (this.req.readyState == 4) { // alert('do_alert() ' + this.url + ', status' + this.req.status); if (this.req.status == 200) { document.getElementById(this.div).innerHTML = this.req.responseText; } else { alert('There was a problem with the request.'); } // delete this.req; } }; this.do_now = function () { // alert('do_now() ' + this.url); /* method - immediate content load */ if (typeof(this.req) == 'undefined') { // alert('req undefined'); this.req = new XMLHttpRequest(); } /* using false here stalls page load until AJAX call completes */ this.req.open('GET', this.url, false); this.req.send(null); document.getElementById(this.div).innerHTML = this.req.responseText; // delete this.req; }; } function formpop(appt) { if (appt == "signup") { newWindow = window.open("signup.php", "newWin", "status=yes, width=480, height=240"); return; } appt_spl = appt+''; if (appt_spl.substring(0, 3) == "new") { // looking for new appt date encoded as: new-2010-11-12 appt_spl = appt.split("-"); newWindow = window.open("popup/appt.php?appt=new&year="+appt_spl[1]+"&month="+appt_spl[2]+"&day="+appt_spl[3], "newWin", "status=yes, width=300, height=360"); } else { newWindow = window.open("popup/appt.php?appt="+appt, "newWin", "status=yes, width=300, height=360"); } }
seem to have fixed weird slow connection issues with nav control not displaying consistently after login or logout
ajax.js
seem to have fixed weird slow connection issues with nav control not displaying consistently after login or logout
<ide><path>jax.js <ide> } <ide> <ide> function head_set(which) { <add> // FUTURE, obsolete function? <ide> headhq.url = head_display_file+'?ajax=1'; <ide> headhq.div = "head"; <ide> headhq.do_hq(); <ide> //alert('username: ' + un + ', ' + pw); <ide> headhq.url = head_display_file+'?ajax=1&username='+un+'&password='+pw; <ide> headhq.div = "head"; <del> headhq.do_hq(); <add> headhq.do_now(); // was .do_hq but, but this works better on slow connections <ide> //alert('login 2'); <ide> navhq.do_now(); // refresh navigation controls <ide> cal_set('calout'); // refresh dungeon view <ide> //alert('logout'); <ide> headhq.url = head_display_file+'?ajax=0&logout'; <ide> headhq.div = "head"; <del> headhq.do_hq(); <add> headhq.do_now(); // was .do_hq but, but this works better on slow connections <ide> //alert('logout 2'); <ide> navhq.do_now(); // refresh navigation controls <ide> cal_set('calout'); // refresh/clear dungeon view
Java
apache-2.0
be5df8d9edad3e513e8ddb812a4968ddaa6211c0
0
GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.hypervisor.kvm.resource; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.StringReader; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.naming.ConfigurationException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import com.cloud.hypervisor.kvm.resource.rolling.maintenance.RollingMaintenanceAgentExecutor; import com.cloud.hypervisor.kvm.resource.rolling.maintenance.RollingMaintenanceExecutor; import com.cloud.hypervisor.kvm.resource.rolling.maintenance.RollingMaintenanceServiceExecutor; import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; import org.apache.cloudstack.storage.to.TemplateObjectTO; import org.apache.cloudstack.storage.to.VolumeObjectTO; import org.apache.cloudstack.utils.hypervisor.HypervisorUtils; import org.apache.cloudstack.utils.linux.CPUStat; import org.apache.cloudstack.utils.linux.KVMHostInfo; import org.apache.cloudstack.utils.linux.MemStat; import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat; import org.apache.cloudstack.utils.security.KeyStoreUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.math.NumberUtils; import org.apache.log4j.Logger; import org.joda.time.Duration; import org.libvirt.Connect; import org.libvirt.Domain; import org.libvirt.DomainBlockStats; import org.libvirt.DomainInfo; import org.libvirt.DomainInfo.DomainState; import org.libvirt.DomainInterfaceStats; import org.libvirt.DomainSnapshot; import org.libvirt.LibvirtException; import org.libvirt.MemoryStatistic; import org.libvirt.Network; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; import com.cloud.agent.api.HostVmStateReportEntry; import com.cloud.agent.api.PingCommand; import com.cloud.agent.api.PingRoutingCommand; import com.cloud.agent.api.PingRoutingWithNwGroupsCommand; import com.cloud.agent.api.SetupGuestNetworkCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; import com.cloud.agent.api.StartupStorageCommand; import com.cloud.agent.api.VmDiskStatsEntry; import com.cloud.agent.api.VmNetworkStatsEntry; import com.cloud.agent.api.VmStatsEntry; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.IpAssocVpcCommand; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.SetSourceNatCommand; import com.cloud.agent.api.to.DataStoreTO; import com.cloud.agent.api.to.DataTO; import com.cloud.agent.api.to.DiskTO; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.NfsTO; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.dao.impl.PropertiesStorage; import com.cloud.agent.resource.virtualnetwork.VRScripts; import com.cloud.agent.resource.virtualnetwork.VirtualRouterDeployer; import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource; import com.cloud.agent.api.SecurityGroupRulesCmd; import com.cloud.dc.Vlan; import com.cloud.exception.InternalErrorException; import com.cloud.host.Host.Type; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.kvm.dpdk.DpdkHelper; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.ChannelDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.ClockDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.ConsoleDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.CpuModeDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.CpuTuneDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DevicesDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef.DeviceType; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef.DiscardType; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef.DiskProtocol; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.FeaturesDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.FilesystemDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.GraphicDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.GuestDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.GuestResourceDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InputDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef.GuestNetType; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.RngDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.RngDef.RngBackendModel; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.SCSIDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.SerialDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.TermPolicy; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.VideoDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.WatchDogDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.WatchDogDef.WatchDogAction; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.WatchDogDef.WatchDogModel; import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper; import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper; import com.cloud.hypervisor.kvm.storage.IscsiStorageCleanupMonitor; import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk; import com.cloud.hypervisor.kvm.storage.KVMStoragePool; import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager; import com.cloud.hypervisor.kvm.storage.KVMStorageProcessor; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.IsolationType; import com.cloud.network.Networks.RouterPrivateIpStrategy; import com.cloud.network.Networks.TrafficType; import com.cloud.resource.RequestWrapper; import com.cloud.resource.ServerResource; import com.cloud.resource.ServerResourceBase; import com.cloud.storage.JavaStorageLayer; import com.cloud.storage.Storage; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StorageLayer; import com.cloud.storage.Volume; import com.cloud.storage.resource.StorageSubsystemCommandHandler; import com.cloud.storage.resource.StorageSubsystemCommandHandlerBase; import com.cloud.utils.ExecutionResult; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.PropertiesUtil; import com.cloud.utils.StringUtils; import com.cloud.utils.Ternary; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; import com.cloud.utils.script.OutputInterpreter; import com.cloud.utils.script.OutputInterpreter.AllLinesParser; import com.cloud.utils.script.Script; import com.cloud.utils.ssh.SshHelper; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.PowerState; import com.cloud.vm.VmDetailConstants; import com.google.common.base.Strings; /** * LibvirtComputingResource execute requests on the computing/routing host using * the libvirt API * * @config {@table || Param Name | Description | Values | Default || || * hypervisor.type | type of local hypervisor | string | kvm || || * hypervisor.uri | local hypervisor to connect to | URI | * qemu:///system || || domr.arch | instruction set for domr template | * string | i686 || || private.bridge.name | private bridge where the * domrs have their private interface | string | vmops0 || || * public.bridge.name | public bridge where the domrs have their public * interface | string | br0 || || private.network.name | name of the * network where the domrs have their private interface | string | * vmops-private || || private.ipaddr.start | start of the range of * private ip addresses for domrs | ip address | 192.168.166.128 || || * private.ipaddr.end | end of the range of private ip addresses for * domrs | ip address | start + 126 || || private.macaddr.start | start * of the range of private mac addresses for domrs | mac address | * 00:16:3e:77:e2:a0 || || private.macaddr.end | end of the range of * private mac addresses for domrs | mac address | start + 126 || || * pool | the parent of the storage pool hierarchy * } **/ public class LibvirtComputingResource extends ServerResourceBase implements ServerResource, VirtualRouterDeployer { private static final Logger s_logger = Logger.getLogger(LibvirtComputingResource.class); private String _modifyVlanPath; private String _versionstringpath; private String _patchScriptPath; private String _createvmPath; private String _manageSnapshotPath; private String _resizeVolumePath; private String _createTmplPath; private String _heartBeatPath; private String _vmActivityCheckPath; private String _securityGroupPath; private String _ovsPvlanDhcpHostPath; private String _ovsPvlanVmPath; private String _routerProxyPath; private String _ovsTunnelPath; private String _host; private String _dcId; private String _pod; private String _clusterId; private final Properties _uefiProperties = new Properties(); private long _hvVersion; private Duration _timeout; private static final int NUMMEMSTATS =2; private KVMHAMonitor _monitor; public static final String SSHKEYSPATH = "/root/.ssh"; public static final String SSHPRVKEYPATH = SSHKEYSPATH + File.separator + "id_rsa.cloud"; public static final String SSHPUBKEYPATH = SSHKEYSPATH + File.separator + "id_rsa.pub.cloud"; public static final String DEFAULTDOMRSSHPORT = "3922"; public static final String BASH_SCRIPT_PATH = "/bin/bash"; private String _mountPoint = "/mnt"; private StorageLayer _storage; private KVMStoragePoolManager _storagePoolMgr; private VifDriver _defaultVifDriver; private Map<TrafficType, VifDriver> _trafficTypeVifDrivers; protected static final String DEFAULT_OVS_VIF_DRIVER_CLASS_NAME = "com.cloud.hypervisor.kvm.resource.OvsVifDriver"; protected static final String DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME = "com.cloud.hypervisor.kvm.resource.BridgeVifDriver"; protected HypervisorType _hypervisorType; protected String _hypervisorURI; protected long _hypervisorLibvirtVersion; protected long _hypervisorQemuVersion; protected String _hypervisorPath; protected String _hostDistro; protected String _networkDirectSourceMode; protected String _networkDirectDevice; protected String _sysvmISOPath; protected String _privNwName; protected String _privBridgeName; protected String _linkLocalBridgeName; protected String _publicBridgeName; protected String _guestBridgeName; protected String _privateIp; protected String _pool; protected String _localGateway; private boolean _canBridgeFirewall; protected String _localStoragePath; protected String _localStorageUUID; protected boolean _noMemBalloon = false; protected String _guestCpuArch; protected String _guestCpuMode; protected String _guestCpuModel; protected boolean _noKvmClock; protected String _videoHw; protected int _videoRam; protected Pair<Integer,Integer> hostOsVersion; protected int _migrateSpeed; protected int _migrateDowntime; protected int _migratePauseAfter; protected boolean _diskActivityCheckEnabled; protected RollingMaintenanceExecutor rollingMaintenanceExecutor; protected long _diskActivityCheckFileSizeMin = 10485760; // 10MB protected int _diskActivityCheckTimeoutSeconds = 120; // 120s protected long _diskActivityInactiveThresholdMilliseconds = 30000; // 30s protected boolean _rngEnable = false; protected RngBackendModel _rngBackendModel = RngBackendModel.RANDOM; protected String _rngPath = "/dev/random"; protected int _rngRatePeriod = 1000; protected int _rngRateBytes = 2048; protected String _agentHooksBasedir = "/etc/cloudstack/agent/hooks"; protected String _agentHooksLibvirtXmlScript = "libvirt-vm-xml-transformer.groovy"; protected String _agentHooksLibvirtXmlMethod = "transform"; protected String _agentHooksVmOnStartScript = "libvirt-vm-state-change.groovy"; protected String _agentHooksVmOnStartMethod = "onStart"; protected String _agentHooksVmOnStopScript = "libvirt-vm-state-change.groovy"; protected String _agentHooksVmOnStopMethod = "onStop"; protected File _qemuSocketsPath; private final String _qemuGuestAgentSocketName = "org.qemu.guest_agent.0"; protected WatchDogAction _watchDogAction = WatchDogAction.NONE; protected WatchDogModel _watchDogModel = WatchDogModel.I6300ESB; private final Map <String, String> _pifs = new HashMap<String, String>(); private final Map<String, VmStats> _vmStats = new ConcurrentHashMap<String, VmStats>(); protected static final HashMap<DomainState, PowerState> s_powerStatesTable; static { s_powerStatesTable = new HashMap<DomainState, PowerState>(); s_powerStatesTable.put(DomainState.VIR_DOMAIN_SHUTOFF, PowerState.PowerOff); s_powerStatesTable.put(DomainState.VIR_DOMAIN_PAUSED, PowerState.PowerOn); s_powerStatesTable.put(DomainState.VIR_DOMAIN_RUNNING, PowerState.PowerOn); s_powerStatesTable.put(DomainState.VIR_DOMAIN_BLOCKED, PowerState.PowerOn); s_powerStatesTable.put(DomainState.VIR_DOMAIN_NOSTATE, PowerState.PowerUnknown); s_powerStatesTable.put(DomainState.VIR_DOMAIN_SHUTDOWN, PowerState.PowerOff); } private VirtualRoutingResource _virtRouterResource; private String _pingTestPath; private String _updateHostPasswdPath; private long _dom0MinMem; private long _dom0OvercommitMem; protected int _cmdsTimeout; protected int _stopTimeout; protected CPUStat _cpuStat = new CPUStat(); protected MemStat _memStat = new MemStat(_dom0MinMem, _dom0OvercommitMem); private final LibvirtUtilitiesHelper libvirtUtilitiesHelper = new LibvirtUtilitiesHelper(); @Override public ExecutionResult executeInVR(final String routerIp, final String script, final String args) { return executeInVR(routerIp, script, args, _timeout); } @Override public ExecutionResult executeInVR(final String routerIp, final String script, final String args, final Duration timeout) { final Script command = new Script(_routerProxyPath, timeout, s_logger); final AllLinesParser parser = new AllLinesParser(); command.add(script); command.add(routerIp); if (args != null) { command.add(args); } String details = command.execute(parser); if (details == null) { details = parser.getLines(); } s_logger.debug("Executing script in VR: " + script); return new ExecutionResult(command.getExitValue() == 0, details); } @Override public ExecutionResult createFileInVR(final String routerIp, final String path, final String filename, final String content) { final File permKey = new File("/root/.ssh/id_rsa.cloud"); boolean success = true; String details = "Creating file in VR, with ip: " + routerIp + ", file: " + filename; s_logger.debug(details); try { SshHelper.scpTo(routerIp, 3922, "root", permKey, null, path, content.getBytes(), filename, null); } catch (final Exception e) { s_logger.warn("Fail to create file " + path + filename + " in VR " + routerIp, e); details = e.getMessage(); success = false; } return new ExecutionResult(success, details); } @Override public ExecutionResult prepareCommand(final NetworkElementCommand cmd) { //Update IP used to access router cmd.setRouterAccessIp(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP)); assert cmd.getRouterAccessIp() != null; if (cmd instanceof IpAssocVpcCommand) { return prepareNetworkElementCommand((IpAssocVpcCommand)cmd); } else if (cmd instanceof IpAssocCommand) { return prepareNetworkElementCommand((IpAssocCommand)cmd); } else if (cmd instanceof SetupGuestNetworkCommand) { return prepareNetworkElementCommand((SetupGuestNetworkCommand)cmd); } else if (cmd instanceof SetSourceNatCommand) { return prepareNetworkElementCommand((SetSourceNatCommand)cmd); } return new ExecutionResult(true, null); } @Override public ExecutionResult cleanupCommand(final NetworkElementCommand cmd) { if (cmd instanceof IpAssocCommand && !(cmd instanceof IpAssocVpcCommand)) { return cleanupNetworkElementCommand((IpAssocCommand)cmd); } return new ExecutionResult(true, null); } public LibvirtKvmAgentHook getTransformer() throws IOException { return new LibvirtKvmAgentHook(_agentHooksBasedir, _agentHooksLibvirtXmlScript, _agentHooksLibvirtXmlMethod); } public LibvirtKvmAgentHook getStartHook() throws IOException { return new LibvirtKvmAgentHook(_agentHooksBasedir, _agentHooksVmOnStartScript, _agentHooksVmOnStartMethod); } public LibvirtKvmAgentHook getStopHook() throws IOException { return new LibvirtKvmAgentHook(_agentHooksBasedir, _agentHooksVmOnStopScript, _agentHooksVmOnStopMethod); } public LibvirtUtilitiesHelper getLibvirtUtilitiesHelper() { return libvirtUtilitiesHelper; } public CPUStat getCPUStat() { return _cpuStat; } public MemStat getMemStat() { return _memStat; } public VirtualRoutingResource getVirtRouterResource() { return _virtRouterResource; } public String getPublicBridgeName() { return _publicBridgeName; } public KVMStoragePoolManager getStoragePoolMgr() { return _storagePoolMgr; } public String getPrivateIp() { return _privateIp; } public int getMigrateDowntime() { return _migrateDowntime; } public int getMigratePauseAfter() { return _migratePauseAfter; } public int getMigrateSpeed() { return _migrateSpeed; } public RollingMaintenanceExecutor getRollingMaintenanceExecutor() { return rollingMaintenanceExecutor; } public String getPingTestPath() { return _pingTestPath; } public String getUpdateHostPasswdPath() { return _updateHostPasswdPath; } public Duration getTimeout() { return _timeout; } public String getOvsTunnelPath() { return _ovsTunnelPath; } public KVMHAMonitor getMonitor() { return _monitor; } public StorageLayer getStorage() { return _storage; } public String createTmplPath() { return _createTmplPath; } public int getCmdsTimeout() { return _cmdsTimeout; } public String manageSnapshotPath() { return _manageSnapshotPath; } public String getGuestBridgeName() { return _guestBridgeName; } public String getVmActivityCheckPath() { return _vmActivityCheckPath; } public String getOvsPvlanDhcpHostPath() { return _ovsPvlanDhcpHostPath; } public String getOvsPvlanVmPath() { return _ovsPvlanVmPath; } public String getDirectDownloadTemporaryDownloadPath() { return directDownloadTemporaryDownloadPath; } public String getResizeVolumePath() { return _resizeVolumePath; } public StorageSubsystemCommandHandler getStorageHandler() { return storageHandler; } private static final class KeyValueInterpreter extends OutputInterpreter { private final Map<String, String> map = new HashMap<String, String>(); @Override public String interpret(final BufferedReader reader) throws IOException { String line = null; int numLines = 0; while ((line = reader.readLine()) != null) { final String[] toks = line.trim().split("="); if (toks.length < 2) { s_logger.warn("Failed to parse Script output: " + line); } else { map.put(toks[0].trim(), toks[1].trim()); } numLines++; } if (numLines == 0) { s_logger.warn("KeyValueInterpreter: no output lines?"); } return null; } public Map<String, String> getKeyValues() { return map; } } @Override protected String getDefaultScriptsDir() { return null; } protected List<String> _cpuFeatures; protected enum BridgeType { NATIVE, OPENVSWITCH } protected BridgeType _bridgeType; protected StorageSubsystemCommandHandler storageHandler; protected boolean dpdkSupport = false; protected String dpdkOvsPath; protected String directDownloadTemporaryDownloadPath; private String getEndIpFromStartIp(final String startIp, final int numIps) { final String[] tokens = startIp.split("[.]"); assert tokens.length == 4; int lastbyte = Integer.parseInt(tokens[3]); lastbyte = lastbyte + numIps; tokens[3] = Integer.toString(lastbyte); final StringBuilder end = new StringBuilder(15); end.append(tokens[0]).append(".").append(tokens[1]).append(".").append(tokens[2]).append(".").append(tokens[3]); return end.toString(); } private Map<String, Object> getDeveloperProperties() throws ConfigurationException { final File file = PropertiesUtil.findConfigFile("developer.properties"); if (file == null) { throw new ConfigurationException("Unable to find developer.properties."); } s_logger.info("developer.properties found at " + file.getAbsolutePath()); try { final Properties properties = PropertiesUtil.loadFromFile(file); final String startMac = (String)properties.get("private.macaddr.start"); if (startMac == null) { throw new ConfigurationException("Developers must specify start mac for private ip range"); } final String startIp = (String)properties.get("private.ipaddr.start"); if (startIp == null) { throw new ConfigurationException("Developers must specify start ip for private ip range"); } final Map<String, Object> params = PropertiesUtil.toMap(properties); String endIp = (String)properties.get("private.ipaddr.end"); if (endIp == null) { endIp = getEndIpFromStartIp(startIp, 16); params.put("private.ipaddr.end", endIp); } return params; } catch (final FileNotFoundException ex) { throw new CloudRuntimeException("Cannot find the file: " + file.getAbsolutePath(), ex); } catch (final IOException ex) { throw new CloudRuntimeException("IOException in reading " + file.getAbsolutePath(), ex); } } private String getDefaultDirectDownloadTemporaryPath() { return "/var/lib/libvirt/images"; } protected String getDefaultNetworkScriptsDir() { return "scripts/vm/network/vnet"; } protected String getDefaultStorageScriptsDir() { return "scripts/storage/qcow2"; } protected String getDefaultHypervisorScriptsDir() { return "scripts/vm/hypervisor"; } protected String getDefaultKvmScriptsDir() { return "scripts/vm/hypervisor/kvm"; } protected String getDefaultDomrScriptsDir() { return "scripts/network/domr"; } protected String getNetworkDirectSourceMode() { return _networkDirectSourceMode; } protected String getNetworkDirectDevice() { return _networkDirectDevice; } @Override public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException { boolean success = super.configure(name, params); if (!success) { return false; } try { loadUefiProperties(); } catch (FileNotFoundException e) { s_logger.error("uefi properties file not found due to: " + e.getLocalizedMessage()); } _storage = new JavaStorageLayer(); _storage.configure("StorageLayer", params); String domrScriptsDir = (String)params.get("domr.scripts.dir"); if (domrScriptsDir == null) { domrScriptsDir = getDefaultDomrScriptsDir(); } String hypervisorScriptsDir = (String)params.get("hypervisor.scripts.dir"); if (hypervisorScriptsDir == null) { hypervisorScriptsDir = getDefaultHypervisorScriptsDir(); } String kvmScriptsDir = (String)params.get("kvm.scripts.dir"); if (kvmScriptsDir == null) { kvmScriptsDir = getDefaultKvmScriptsDir(); } String networkScriptsDir = (String)params.get("network.scripts.dir"); if (networkScriptsDir == null) { networkScriptsDir = getDefaultNetworkScriptsDir(); } String storageScriptsDir = (String)params.get("storage.scripts.dir"); if (storageScriptsDir == null) { storageScriptsDir = getDefaultStorageScriptsDir(); } final String bridgeType = (String)params.get("network.bridge.type"); if (bridgeType == null) { _bridgeType = BridgeType.NATIVE; } else { _bridgeType = BridgeType.valueOf(bridgeType.toUpperCase()); } String dpdk = (String) params.get("openvswitch.dpdk.enabled"); if (_bridgeType == BridgeType.OPENVSWITCH && Boolean.parseBoolean(dpdk)) { dpdkSupport = true; dpdkOvsPath = (String) params.get("openvswitch.dpdk.ovs.path"); if (dpdkOvsPath != null && !dpdkOvsPath.endsWith("/")) { dpdkOvsPath += "/"; } } directDownloadTemporaryDownloadPath = (String) params.get("direct.download.temporary.download.location"); if (org.apache.commons.lang.StringUtils.isBlank(directDownloadTemporaryDownloadPath)) { directDownloadTemporaryDownloadPath = getDefaultDirectDownloadTemporaryPath(); } params.put("domr.scripts.dir", domrScriptsDir); _virtRouterResource = new VirtualRoutingResource(this); success = _virtRouterResource.configure(name, params); if (!success) { return false; } _host = (String)params.get("host"); if (_host == null) { _host = "localhost"; } _dcId = (String)params.get("zone"); if (_dcId == null) { _dcId = "default"; } _pod = (String)params.get("pod"); if (_pod == null) { _pod = "default"; } _clusterId = (String)params.get("cluster"); _updateHostPasswdPath = Script.findScript(hypervisorScriptsDir, VRScripts.UPDATE_HOST_PASSWD); if (_updateHostPasswdPath == null) { throw new ConfigurationException("Unable to find update_host_passwd.sh"); } _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); if (_modifyVlanPath == null) { throw new ConfigurationException("Unable to find modifyvlan.sh"); } _versionstringpath = Script.findScript(kvmScriptsDir, "versions.sh"); if (_versionstringpath == null) { throw new ConfigurationException("Unable to find versions.sh"); } _patchScriptPath = Script.findScript(kvmScriptsDir, "patch.sh"); if (_patchScriptPath == null) { throw new ConfigurationException("Unable to find patch.sh"); } _heartBeatPath = Script.findScript(kvmScriptsDir, "kvmheartbeat.sh"); if (_heartBeatPath == null) { throw new ConfigurationException("Unable to find kvmheartbeat.sh"); } _createvmPath = Script.findScript(storageScriptsDir, "createvm.sh"); if (_createvmPath == null) { throw new ConfigurationException("Unable to find the createvm.sh"); } _manageSnapshotPath = Script.findScript(storageScriptsDir, "managesnapshot.sh"); if (_manageSnapshotPath == null) { throw new ConfigurationException("Unable to find the managesnapshot.sh"); } _resizeVolumePath = Script.findScript(storageScriptsDir, "resizevolume.sh"); if (_resizeVolumePath == null) { throw new ConfigurationException("Unable to find the resizevolume.sh"); } _vmActivityCheckPath = Script.findScript(kvmScriptsDir, "kvmvmactivity.sh"); if (_vmActivityCheckPath == null) { throw new ConfigurationException("Unable to find kvmvmactivity.sh"); } _createTmplPath = Script.findScript(storageScriptsDir, "createtmplt.sh"); if (_createTmplPath == null) { throw new ConfigurationException("Unable to find the createtmplt.sh"); } _securityGroupPath = Script.findScript(networkScriptsDir, "security_group.py"); if (_securityGroupPath == null) { throw new ConfigurationException("Unable to find the security_group.py"); } _ovsTunnelPath = Script.findScript(networkScriptsDir, "ovstunnel.py"); if (_ovsTunnelPath == null) { throw new ConfigurationException("Unable to find the ovstunnel.py"); } _routerProxyPath = Script.findScript("scripts/network/domr/", "router_proxy.sh"); if (_routerProxyPath == null) { throw new ConfigurationException("Unable to find the router_proxy.sh"); } _ovsPvlanDhcpHostPath = Script.findScript(networkScriptsDir, "ovs-pvlan-dhcp-host.sh"); if (_ovsPvlanDhcpHostPath == null) { throw new ConfigurationException("Unable to find the ovs-pvlan-dhcp-host.sh"); } _ovsPvlanVmPath = Script.findScript(networkScriptsDir, "ovs-pvlan-vm.sh"); if (_ovsPvlanVmPath == null) { throw new ConfigurationException("Unable to find the ovs-pvlan-vm.sh"); } String value = (String)params.get("developer"); final boolean isDeveloper = Boolean.parseBoolean(value); if (isDeveloper) { params.putAll(getDeveloperProperties()); } _pool = (String)params.get("pool"); if (_pool == null) { _pool = "/root"; } final String instance = (String)params.get("instance"); _hypervisorType = HypervisorType.getType((String)params.get("hypervisor.type")); if (_hypervisorType == HypervisorType.None) { _hypervisorType = HypervisorType.KVM; } String hooksDir = (String)params.get("rolling.maintenance.hooks.dir"); value = (String) params.get("rolling.maintenance.service.executor.disabled"); rollingMaintenanceExecutor = Boolean.parseBoolean(value) ? new RollingMaintenanceAgentExecutor(hooksDir) : new RollingMaintenanceServiceExecutor(hooksDir); _hypervisorURI = (String)params.get("hypervisor.uri"); if (_hypervisorURI == null) { _hypervisorURI = LibvirtConnection.getHypervisorURI(_hypervisorType.toString()); } _networkDirectSourceMode = (String)params.get("network.direct.source.mode"); _networkDirectDevice = (String)params.get("network.direct.device"); String startMac = (String)params.get("private.macaddr.start"); if (startMac == null) { startMac = "00:16:3e:77:e2:a0"; } String startIp = (String)params.get("private.ipaddr.start"); if (startIp == null) { startIp = "192.168.166.128"; } _pingTestPath = Script.findScript(kvmScriptsDir, "pingtest.sh"); if (_pingTestPath == null) { throw new ConfigurationException("Unable to find the pingtest.sh"); } _linkLocalBridgeName = (String)params.get("private.bridge.name"); if (_linkLocalBridgeName == null) { if (isDeveloper) { _linkLocalBridgeName = "cloud-" + instance + "-0"; } else { _linkLocalBridgeName = "cloud0"; } } _publicBridgeName = (String)params.get("public.network.device"); if (_publicBridgeName == null) { _publicBridgeName = "cloudbr0"; } _privBridgeName = (String)params.get("private.network.device"); if (_privBridgeName == null) { _privBridgeName = "cloudbr1"; } _guestBridgeName = (String)params.get("guest.network.device"); if (_guestBridgeName == null) { _guestBridgeName = _privBridgeName; } _privNwName = (String)params.get("private.network.name"); if (_privNwName == null) { if (isDeveloper) { _privNwName = "cloud-" + instance + "-private"; } else { _privNwName = "cloud-private"; } } _localStoragePath = (String)params.get("local.storage.path"); if (_localStoragePath == null) { _localStoragePath = "/var/lib/libvirt/images/"; } /* Directory to use for Qemu sockets like for the Qemu Guest Agent */ _qemuSocketsPath = new File("/var/lib/libvirt/qemu"); String _qemuSocketsPathVar = (String)params.get("qemu.sockets.path"); if (_qemuSocketsPathVar != null && StringUtils.isNotBlank(_qemuSocketsPathVar)) { _qemuSocketsPath = new File(_qemuSocketsPathVar); } final File storagePath = new File(_localStoragePath); _localStoragePath = storagePath.getAbsolutePath(); _localStorageUUID = (String)params.get("local.storage.uuid"); if (_localStorageUUID == null) { _localStorageUUID = UUID.randomUUID().toString(); } value = (String)params.get("scripts.timeout"); _timeout = Duration.standardSeconds(NumbersUtil.parseInt(value, 30 * 60)); value = (String)params.get("stop.script.timeout"); _stopTimeout = NumbersUtil.parseInt(value, 120) * 1000; value = (String)params.get("cmds.timeout"); _cmdsTimeout = NumbersUtil.parseInt(value, 7200) * 1000; value = (String) params.get("vm.memballoon.disable"); if (Boolean.parseBoolean(value)) { _noMemBalloon = true; } _videoHw = (String) params.get("vm.video.hardware"); value = (String) params.get("vm.video.ram"); _videoRam = NumbersUtil.parseInt(value, 0); value = (String)params.get("host.reserved.mem.mb"); // Reserve 1GB unless admin overrides _dom0MinMem = NumbersUtil.parseInt(value, 1024) * 1024* 1024L; value = (String)params.get("host.overcommit.mem.mb"); // Support overcommit memory for host if host uses ZSWAP, KSM and other memory // compressing technologies _dom0OvercommitMem = NumbersUtil.parseInt(value, 0) * 1024 * 1024L; value = (String) params.get("kvmclock.disable"); if (Boolean.parseBoolean(value)) { _noKvmClock = true; } value = (String) params.get("vm.rng.enable"); if (Boolean.parseBoolean(value)) { _rngEnable = true; value = (String) params.get("vm.rng.model"); if (!Strings.isNullOrEmpty(value)) { _rngBackendModel = RngBackendModel.valueOf(value.toUpperCase()); } value = (String) params.get("vm.rng.path"); if (!Strings.isNullOrEmpty(value)) { _rngPath = value; } value = (String) params.get("vm.rng.rate.bytes"); _rngRateBytes = NumbersUtil.parseInt(value, new Integer(_rngRateBytes)); value = (String) params.get("vm.rng.rate.period"); _rngRatePeriod = NumbersUtil.parseInt(value, new Integer(_rngRatePeriod)); } value = (String) params.get("vm.watchdog.model"); if (!Strings.isNullOrEmpty(value)) { _watchDogModel = WatchDogModel.valueOf(value.toUpperCase()); } value = (String) params.get("vm.watchdog.action"); if (!Strings.isNullOrEmpty(value)) { _watchDogAction = WatchDogAction.valueOf(value.toUpperCase()); } LibvirtConnection.initialize(_hypervisorURI); Connect conn = null; try { conn = LibvirtConnection.getConnection(); if (_bridgeType == BridgeType.OPENVSWITCH) { if (conn.getLibVirVersion() < 10 * 1000 + 0) { throw new ConfigurationException("Libvirt version 0.10.0 required for openvswitch support, but version " + conn.getLibVirVersion() + " detected"); } } } catch (final LibvirtException e) { throw new CloudRuntimeException(e.getMessage()); } // destroy default network, see https://libvirt.org/sources/java/javadoc/org/libvirt/Network.html try { Network network = conn.networkLookupByName("default"); s_logger.debug("Found libvirt default network, destroying it and setting autostart to false"); if (network.isActive() == 1) { network.destroy(); } if (network.getAutostart()) { network.setAutostart(false); } } catch (final LibvirtException e) { s_logger.warn("Ignoring libvirt error.", e); } if (HypervisorType.KVM == _hypervisorType) { /* Does node support HVM guest? If not, exit */ if (!IsHVMEnabled(conn)) { throw new ConfigurationException("NO HVM support on this machine, please make sure: " + "1. VT/SVM is supported by your CPU, or is enabled in BIOS. " + "2. kvm modules are loaded (kvm, kvm_amd|kvm_intel)"); } } _hypervisorPath = getHypervisorPath(conn); try { _hvVersion = conn.getVersion(); _hvVersion = _hvVersion % 1000000 / 1000; _hypervisorLibvirtVersion = conn.getLibVirVersion(); _hypervisorQemuVersion = conn.getVersion(); } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } final String cpuArchOverride = (String)params.get("guest.cpu.arch"); if (!Strings.isNullOrEmpty(cpuArchOverride)) { _guestCpuArch = cpuArchOverride; s_logger.info("Using guest CPU architecture: " + _guestCpuArch); } _guestCpuMode = (String)params.get("guest.cpu.mode"); if (_guestCpuMode != null) { _guestCpuModel = (String)params.get("guest.cpu.model"); if (_hypervisorLibvirtVersion < 9 * 1000 + 10) { s_logger.warn("Libvirt version 0.9.10 required for guest cpu mode, but version " + prettyVersion(_hypervisorLibvirtVersion) + " detected, so it will be disabled"); _guestCpuMode = ""; _guestCpuModel = ""; } params.put("guest.cpu.mode", _guestCpuMode); params.put("guest.cpu.model", _guestCpuModel); } final String cpuFeatures = (String)params.get("guest.cpu.features"); if (cpuFeatures != null) { _cpuFeatures = new ArrayList<String>(); for (final String feature: cpuFeatures.split(" ")) { if (!feature.isEmpty()) { _cpuFeatures.add(feature); } } } final String[] info = NetUtils.getNetworkParams(_privateNic); _monitor = new KVMHAMonitor(null, info[0], _heartBeatPath); final Thread ha = new Thread(_monitor); ha.start(); _storagePoolMgr = new KVMStoragePoolManager(_storage, _monitor); _sysvmISOPath = (String)params.get("systemvm.iso.path"); if (_sysvmISOPath == null) { final String[] isoPaths = {"/usr/share/cloudstack-common/vms/systemvm.iso"}; for (final String isoPath : isoPaths) { if (_storage.exists(isoPath)) { _sysvmISOPath = isoPath; break; } } if (_sysvmISOPath == null) { s_logger.debug("Can't find system vm ISO"); } } final Map<String, String> bridges = new HashMap<String, String>(); params.put("libvirt.host.bridges", bridges); params.put("libvirt.host.pifs", _pifs); params.put("libvirt.computing.resource", this); params.put("libvirtVersion", _hypervisorLibvirtVersion); configureVifDrivers(params); /* switch (_bridgeType) { case OPENVSWITCH: getOvsPifs(); break; case NATIVE: default: getPifs(); break; } */ if (_pifs.get("private") == null) { s_logger.error("Failed to get private nic name"); throw new ConfigurationException("Failed to get private nic name"); } if (_pifs.get("public") == null) { s_logger.error("Failed to get public nic name"); throw new ConfigurationException("Failed to get public nic name"); } s_logger.debug("Found pif: " + _pifs.get("private") + " on " + _privBridgeName + ", pif: " + _pifs.get("public") + " on " + _publicBridgeName); _canBridgeFirewall = canBridgeFirewall(_pifs.get("public")); _localGateway = Script.runSimpleBashScript("ip route show default 0.0.0.0/0|head -1|awk '{print $3}'"); if (_localGateway == null) { s_logger.warn("No default IPv4 gateway found"); } _mountPoint = (String)params.get("mount.path"); if (_mountPoint == null) { _mountPoint = "/mnt"; } value = (String) params.get("vm.migrate.downtime"); _migrateDowntime = NumbersUtil.parseInt(value, -1); value = (String) params.get("vm.migrate.pauseafter"); _migratePauseAfter = NumbersUtil.parseInt(value, -1); configureAgentHooks(params); value = (String)params.get("vm.migrate.speed"); _migrateSpeed = NumbersUtil.parseInt(value, -1); if (_migrateSpeed == -1) { //get guest network device speed _migrateSpeed = 0; final String speed = Script.runSimpleBashScript("ethtool " + _pifs.get("public") + " |grep Speed | cut -d \\ -f 2"); if (speed != null) { final String[] tokens = speed.split("M"); if (tokens.length == 2) { try { _migrateSpeed = Integer.parseInt(tokens[0]); } catch (final NumberFormatException e) { s_logger.trace("Ignoring migrateSpeed extraction error.", e); } s_logger.debug("device " + _pifs.get("public") + " has speed: " + String.valueOf(_migrateSpeed)); } } params.put("vm.migrate.speed", String.valueOf(_migrateSpeed)); } bridges.put("linklocal", _linkLocalBridgeName); bridges.put("public", _publicBridgeName); bridges.put("private", _privBridgeName); bridges.put("guest", _guestBridgeName); getVifDriver(TrafficType.Control).createControlNetwork(_linkLocalBridgeName); configureDiskActivityChecks(params); final KVMStorageProcessor storageProcessor = new KVMStorageProcessor(_storagePoolMgr, this); storageProcessor.configure(name, params); storageHandler = new StorageSubsystemCommandHandlerBase(storageProcessor); Boolean _iscsiCleanUpEnabled = Boolean.parseBoolean((String)params.get("iscsi.session.cleanup.enabled")); if (BooleanUtils.isTrue(_iscsiCleanUpEnabled)) { IscsiStorageCleanupMonitor isciCleanupMonitor = new IscsiStorageCleanupMonitor(); final Thread cleanupMonitor = new Thread(isciCleanupMonitor); cleanupMonitor.start(); } else { s_logger.info("iscsi session clean up is disabled"); } return true; } public boolean configureHostParams(final Map<String, String> params) { final File file = PropertiesUtil.findConfigFile("agent.properties"); if (file == null) { s_logger.error("Unable to find the file agent.properties"); return false; } // Save configurations in agent.properties PropertiesStorage storage = new PropertiesStorage(); storage.configure("Storage", new HashMap<String, Object>()); if (params.get("router.aggregation.command.each.timeout") != null) { String value = (String)params.get("router.aggregation.command.each.timeout"); Long longValue = NumbersUtil.parseLong(value, 600); storage.persist("router.aggregation.command.each.timeout", String.valueOf(longValue)); } return true; } private void configureAgentHooks(final Map<String, Object> params) { String value = (String) params.get("agent.hooks.basedir"); if (null != value) { _agentHooksBasedir = value; } s_logger.debug("agent.hooks.basedir is " + _agentHooksBasedir); value = (String) params.get("agent.hooks.libvirt_vm_xml_transformer.script"); if (null != value) { _agentHooksLibvirtXmlScript = value; } s_logger.debug("agent.hooks.libvirt_vm_xml_transformer.script is " + _agentHooksLibvirtXmlScript); value = (String) params.get("agent.hooks.libvirt_vm_xml_transformer.method"); if (null != value) { _agentHooksLibvirtXmlMethod = value; } s_logger.debug("agent.hooks.libvirt_vm_xml_transformer.method is " + _agentHooksLibvirtXmlMethod); value = (String) params.get("agent.hooks.libvirt_vm_on_start.script"); if (null != value) { _agentHooksVmOnStartScript = value; } s_logger.debug("agent.hooks.libvirt_vm_on_start.script is " + _agentHooksVmOnStartScript); value = (String) params.get("agent.hooks.libvirt_vm_on_start.method"); if (null != value) { _agentHooksVmOnStartMethod = value; } s_logger.debug("agent.hooks.libvirt_vm_on_start.method is " + _agentHooksVmOnStartMethod); value = (String) params.get("agent.hooks.libvirt_vm_on_stop.script"); if (null != value) { _agentHooksVmOnStopScript = value; } s_logger.debug("agent.hooks.libvirt_vm_on_stop.script is " + _agentHooksVmOnStopScript); value = (String) params.get("agent.hooks.libvirt_vm_on_stop.method"); if (null != value) { _agentHooksVmOnStopMethod = value; } s_logger.debug("agent.hooks.libvirt_vm_on_stop.method is " + _agentHooksVmOnStopMethod); } private void loadUefiProperties() throws FileNotFoundException { if (_uefiProperties != null && _uefiProperties.getProperty("guest.loader.legacy") != null) { return; } final File file = PropertiesUtil.findConfigFile("uefi.properties"); if (file == null) { throw new FileNotFoundException("Unable to find file uefi.properties."); } s_logger.info("uefi.properties file found at " + file.getAbsolutePath()); try { PropertiesUtil.loadFromFile(_uefiProperties, file); s_logger.info("guest.nvram.template.legacy = " + _uefiProperties.getProperty("guest.nvram.template.legacy")); s_logger.info("guest.loader.legacy = " + _uefiProperties.getProperty("guest.loader.legacy")); s_logger.info("guest.nvram.template.secure = " + _uefiProperties.getProperty("guest.nvram.template.secure")); s_logger.info("guest.loader.secure =" + _uefiProperties.getProperty("guest.loader.secure")); s_logger.info("guest.nvram.path = " + _uefiProperties.getProperty("guest.nvram.path")); } catch (final FileNotFoundException ex) { throw new CloudRuntimeException("Cannot find the file: " + file.getAbsolutePath(), ex); } catch (final IOException ex) { throw new CloudRuntimeException("IOException in reading " + file.getAbsolutePath(), ex); } } protected void configureDiskActivityChecks(final Map<String, Object> params) { _diskActivityCheckEnabled = Boolean.parseBoolean((String)params.get("vm.diskactivity.checkenabled")); if (_diskActivityCheckEnabled) { final int timeout = NumbersUtil.parseInt((String)params.get("vm.diskactivity.checktimeout_s"), 0); if (timeout > 0) { _diskActivityCheckTimeoutSeconds = timeout; } final long inactiveTime = NumbersUtil.parseLong((String)params.get("vm.diskactivity.inactivetime_ms"), 0L); if (inactiveTime > 0) { _diskActivityInactiveThresholdMilliseconds = inactiveTime; } } } protected void configureVifDrivers(final Map<String, Object> params) throws ConfigurationException { final String LIBVIRT_VIF_DRIVER = "libvirt.vif.driver"; _trafficTypeVifDrivers = new HashMap<TrafficType, VifDriver>(); // Load the default vif driver String defaultVifDriverName = (String)params.get(LIBVIRT_VIF_DRIVER); if (defaultVifDriverName == null) { if (_bridgeType == BridgeType.OPENVSWITCH) { s_logger.info("No libvirt.vif.driver specified. Defaults to OvsVifDriver."); defaultVifDriverName = DEFAULT_OVS_VIF_DRIVER_CLASS_NAME; } else { s_logger.info("No libvirt.vif.driver specified. Defaults to BridgeVifDriver."); defaultVifDriverName = DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME; } } _defaultVifDriver = getVifDriverClass(defaultVifDriverName, params); // Load any per-traffic-type vif drivers for (final Map.Entry<String, Object> entry : params.entrySet()) { final String k = entry.getKey(); final String vifDriverPrefix = LIBVIRT_VIF_DRIVER + "."; if (k.startsWith(vifDriverPrefix)) { // Get trafficType final String trafficTypeSuffix = k.substring(vifDriverPrefix.length()); // Does this suffix match a real traffic type? final TrafficType trafficType = TrafficType.getTrafficType(trafficTypeSuffix); if (!trafficType.equals(TrafficType.None)) { // Get vif driver class name final String vifDriverClassName = (String)entry.getValue(); // if value is null, ignore if (vifDriverClassName != null) { // add traffic type to vif driver mapping to Map _trafficTypeVifDrivers.put(trafficType, getVifDriverClass(vifDriverClassName, params)); } } } } } protected VifDriver getVifDriverClass(final String vifDriverClassName, final Map<String, Object> params) throws ConfigurationException { VifDriver vifDriver; try { final Class<?> clazz = Class.forName(vifDriverClassName); vifDriver = (VifDriver)clazz.newInstance(); vifDriver.configure(params); } catch (final ClassNotFoundException e) { throw new ConfigurationException("Unable to find class for libvirt.vif.driver " + e); } catch (final InstantiationException e) { throw new ConfigurationException("Unable to instantiate class for libvirt.vif.driver " + e); } catch (final IllegalAccessException e) { throw new ConfigurationException("Unable to instantiate class for libvirt.vif.driver " + e); } return vifDriver; } public VifDriver getVifDriver(final TrafficType trafficType) { VifDriver vifDriver = _trafficTypeVifDrivers.get(trafficType); if (vifDriver == null) { vifDriver = _defaultVifDriver; } return vifDriver; } public VifDriver getVifDriver(final TrafficType trafficType, final String bridgeName) { VifDriver vifDriver = null; for (VifDriver driver : getAllVifDrivers()) { if (driver.isExistingBridge(bridgeName)) { vifDriver = driver; break; } } if (vifDriver == null) { vifDriver = getVifDriver(trafficType); } return vifDriver; } public List<VifDriver> getAllVifDrivers() { final Set<VifDriver> vifDrivers = new HashSet<VifDriver>(); vifDrivers.add(_defaultVifDriver); vifDrivers.addAll(_trafficTypeVifDrivers.values()); final ArrayList<VifDriver> vifDriverList = new ArrayList<VifDriver>(vifDrivers); return vifDriverList; } private void getPifs() { final File dir = new File("/sys/devices/virtual/net"); final File[] netdevs = dir.listFiles(); final List<String> bridges = new ArrayList<String>(); for (int i = 0; i < netdevs.length; i++) { final File isbridge = new File(netdevs[i].getAbsolutePath() + "/bridge"); final String netdevName = netdevs[i].getName(); s_logger.debug("looking in file " + netdevs[i].getAbsolutePath() + "/bridge"); if (isbridge.exists()) { s_logger.debug("Found bridge " + netdevName); bridges.add(netdevName); } } for (final String bridge : bridges) { s_logger.debug("looking for pif for bridge " + bridge); final String pif = getPif(bridge); if (isPublicBridge(bridge)) { _pifs.put("public", pif); } if (isGuestBridge(bridge)) { _pifs.put("private", pif); } _pifs.put(bridge, pif); } // guest(private) creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("private") == null) { s_logger.debug("guest(private) traffic label '" + _guestBridgeName + "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + _guestBridgeName); if (dev.exists()) { s_logger.debug("guest(private) traffic label '" + _guestBridgeName + "' found as a physical device"); _pifs.put("private", _guestBridgeName); } } // public creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("public") == null) { s_logger.debug("public traffic label '" + _publicBridgeName+ "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + _publicBridgeName); if (dev.exists()) { s_logger.debug("public traffic label '" + _publicBridgeName + "' found as a physical device"); _pifs.put("public", _publicBridgeName); } } s_logger.debug("done looking for pifs, no more bridges"); } boolean isGuestBridge(String bridge) { return _guestBridgeName != null && bridge.equals(_guestBridgeName); } private void getOvsPifs() { final String cmdout = Script.runSimpleBashScript("ovs-vsctl list-br | sed '{:q;N;s/\\n/%/g;t q}'"); s_logger.debug("cmdout was " + cmdout); final List<String> bridges = Arrays.asList(cmdout.split("%")); for (final String bridge : bridges) { s_logger.debug("looking for pif for bridge " + bridge); // String pif = getOvsPif(bridge); // Not really interested in the pif name at this point for ovs // bridges final String pif = bridge; if (isPublicBridge(bridge)) { _pifs.put("public", pif); } if (isGuestBridge(bridge)) { _pifs.put("private", pif); } _pifs.put(bridge, pif); } s_logger.debug("done looking for pifs, no more bridges"); } public boolean isPublicBridge(String bridge) { return _publicBridgeName != null && bridge.equals(_publicBridgeName); } private String getPif(final String bridge) { String pif = matchPifFileInDirectory(bridge); final File vlanfile = new File("/proc/net/vlan/" + pif); if (vlanfile.isFile()) { pif = Script.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" + pif + " | awk {'print $2'}"); } return pif; } private String matchPifFileInDirectory(final String bridgeName) { final File brif = new File("/sys/devices/virtual/net/" + bridgeName + "/brif"); if (!brif.isDirectory()) { final File pif = new File("/sys/class/net/" + bridgeName); if (pif.isDirectory()) { // if bridgeName already refers to a pif, return it as-is return bridgeName; } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", does " + brif.getAbsolutePath() + "exist?"); return ""; } final File[] interfaces = brif.listFiles(); for (int i = 0; i < interfaces.length; i++) { final String fname = interfaces[i].getName(); s_logger.debug("matchPifFileInDirectory: file name '" + fname + "'"); if (isInterface(fname)) { return fname; } } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", did not find an eth*, bond*, team*, vlan*, em*, p*p*, ens*, eno*, enp*, or enx* in " + brif.getAbsolutePath()); return ""; } static String [] ifNamePatterns = { "^eth", "^bond", "^vlan", "^vx", "^em", "^ens", "^eno", "^enp", "^team", "^enx", "^dummy", "^lo", "^p\\d+p\\d+" }; /** * @param fname * @return */ protected static boolean isInterface(final String fname) { StringBuffer commonPattern = new StringBuffer(); for (final String ifNamePattern : ifNamePatterns) { commonPattern.append("|(").append(ifNamePattern).append(".*)"); } if(fname.matches(commonPattern.toString())) { return true; } return false; } public boolean checkNetwork(final TrafficType trafficType, final String networkName) { if (networkName == null) { return true; } if (getVifDriver(trafficType, networkName) instanceof OvsVifDriver) { return checkOvsNetwork(networkName); } else { return checkBridgeNetwork(networkName); } } private boolean checkBridgeNetwork(final String networkName) { if (networkName == null) { return true; } final String name = matchPifFileInDirectory(networkName); if (name == null || name.isEmpty()) { return false; } else { return true; } } private boolean checkOvsNetwork(final String networkName) { s_logger.debug("Checking if network " + networkName + " exists as openvswitch bridge"); if (networkName == null) { return true; } final Script command = new Script("/bin/sh", _timeout); command.add("-c"); command.add("ovs-vsctl br-exists " + networkName); return "0".equals(command.execute(null)); } public boolean passCmdLine(final String vmName, final String cmdLine) throws InternalErrorException { final Script command = new Script(_patchScriptPath, 300 * 1000, s_logger); String result; command.add("-n", vmName); command.add("-c", cmdLine); result = command.execute(); if (result != null) { s_logger.error("Passing cmdline failed:" + result); return false; } return true; } boolean isDirectAttachedNetwork(final String type) { if ("untagged".equalsIgnoreCase(type)) { return true; } else { try { Long.valueOf(type); } catch (final NumberFormatException e) { return true; } return false; } } public String startVM(final Connect conn, final String vmName, final String domainXML) throws LibvirtException, InternalErrorException { try { /* We create a transient domain here. When this method gets called we receive a full XML specification of the guest, so no need to define it persistent. This also makes sure we never have any old "garbage" defined in libvirt which might haunt us. */ // check for existing inactive vm definition and remove it // this can sometimes happen during crashes, etc Domain dm = null; try { dm = conn.domainLookupByName(vmName); if (dm != null && dm.isPersistent() == 1) { // this is safe because it doesn't stop running VMs dm.undefine(); } } catch (final LibvirtException e) { // this is what we want, no domain found } finally { if (dm != null) { dm.free(); } } conn.domainCreateXML(domainXML, 0); } catch (final LibvirtException e) { throw e; } return null; } @Override public boolean stop() { try { final Connect conn = LibvirtConnection.getConnection(); conn.close(); } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } return true; } /** * This finds a command wrapper to handle the command and executes it. * If no wrapper is found an {@see UnsupportedAnswer} is sent back. * Any other exceptions are to be caught and wrapped in an generic {@see Answer}, marked as failed. * * @param cmd the instance of a {@see Command} to execute. * @return the for the {@see Command} appropriate {@see Answer} or {@see UnsupportedAnswer} */ @Override public Answer executeRequest(final Command cmd) { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); try { return wrapper.execute(cmd, this); } catch (final RequestWrapper.CommandNotSupported cmde) { return Answer.createUnsupportedCommandAnswer(cmd); } } public synchronized boolean destroyTunnelNetwork(final String bridge) { findOrCreateTunnelNetwork(bridge); final Script cmd = new Script(_ovsTunnelPath, _timeout, s_logger); cmd.add("destroy_ovs_bridge"); cmd.add("--bridge", bridge); final String result = cmd.execute(); if (result != null) { s_logger.debug("OVS Bridge could not be destroyed due to error ==> " + result); return false; } return true; } public synchronized boolean findOrCreateTunnelNetwork(final String nwName) { try { if (checkNetwork(TrafficType.Guest, nwName)) { return true; } // if not found, create a new one final Map<String, String> otherConfig = new HashMap<String, String>(); otherConfig.put("ovs-host-setup", ""); Script.runSimpleBashScript("ovs-vsctl -- --may-exist add-br " + nwName + " -- set bridge " + nwName + " other_config:ovs-host-setup='-1'"); s_logger.debug("### KVM network for tunnels created:" + nwName); } catch (final Exception e) { s_logger.warn("createTunnelNetwork failed", e); return false; } return true; } public synchronized boolean configureTunnelNetwork(final long networkId, final long hostId, final String nwName) { try { final boolean findResult = findOrCreateTunnelNetwork(nwName); if (!findResult) { s_logger.warn("LibvirtComputingResource.findOrCreateTunnelNetwork() failed! Cannot proceed creating the tunnel."); return false; } final String configuredHosts = Script .runSimpleBashScript("ovs-vsctl get bridge " + nwName + " other_config:ovs-host-setup"); boolean configured = false; if (configuredHosts != null) { final String hostIdsStr[] = configuredHosts.split(","); for (final String hostIdStr : hostIdsStr) { if (hostIdStr.equals(((Long)hostId).toString())) { configured = true; break; } } } if (!configured) { final Script cmd = new Script(_ovsTunnelPath, _timeout, s_logger); cmd.add("setup_ovs_bridge"); cmd.add("--key", nwName); cmd.add("--cs_host_id", ((Long)hostId).toString()); cmd.add("--bridge", nwName); final String result = cmd.execute(); if (result != null) { throw new CloudRuntimeException( "Unable to pre-configure OVS bridge " + nwName + " for network ID:" + networkId); } } } catch (final Exception e) { s_logger.warn("createandConfigureTunnelNetwork failed", e); return false; } return true; } protected Storage.StorageResourceType getStorageResourceType() { return Storage.StorageResourceType.STORAGE_POOL; } // this is much like PrimaryStorageDownloadCommand, but keeping it separate public KVMPhysicalDisk templateToPrimaryDownload(final String templateUrl, final KVMStoragePool primaryPool, final String volUuid) { final int index = templateUrl.lastIndexOf("/"); final String mountpoint = templateUrl.substring(0, index); String templateName = null; if (index < templateUrl.length() - 1) { templateName = templateUrl.substring(index + 1); } KVMPhysicalDisk templateVol = null; KVMStoragePool secondaryPool = null; try { secondaryPool = _storagePoolMgr.getStoragePoolByURI(mountpoint); /* Get template vol */ if (templateName == null) { secondaryPool.refresh(); final List<KVMPhysicalDisk> disks = secondaryPool.listPhysicalDisks(); if (disks == null || disks.isEmpty()) { s_logger.error("Failed to get volumes from pool: " + secondaryPool.getUuid()); return null; } for (final KVMPhysicalDisk disk : disks) { if (disk.getName().endsWith("qcow2")) { templateVol = disk; break; } } if (templateVol == null) { s_logger.error("Failed to get template from pool: " + secondaryPool.getUuid()); return null; } } else { templateVol = secondaryPool.getPhysicalDisk(templateName); } /* Copy volume to primary storage */ final KVMPhysicalDisk primaryVol = _storagePoolMgr.copyPhysicalDisk(templateVol, volUuid, primaryPool, 0); return primaryVol; } catch (final CloudRuntimeException e) { s_logger.error("Failed to download template to primary storage", e); return null; } finally { if (secondaryPool != null) { _storagePoolMgr.deleteStoragePool(secondaryPool.getType(), secondaryPool.getUuid()); } } } public String getResizeScriptType(final KVMStoragePool pool, final KVMPhysicalDisk vol) { final StoragePoolType poolType = pool.getType(); final PhysicalDiskFormat volFormat = vol.getFormat(); if (pool.getType() == StoragePoolType.CLVM && volFormat == PhysicalDiskFormat.RAW) { return "CLVM"; } else if ((poolType == StoragePoolType.NetworkFilesystem || poolType == StoragePoolType.SharedMountPoint || poolType == StoragePoolType.Filesystem || poolType == StoragePoolType.Gluster) && volFormat == PhysicalDiskFormat.QCOW2 ) { return "QCOW2"; } throw new CloudRuntimeException("Cannot determine resize type from pool type " + pool.getType()); } private String getBroadcastUriFromBridge(final String brName) { final String pif = matchPifFileInDirectory(brName); final Pattern pattern = Pattern.compile("(\\D+)(\\d+)(\\D*)(\\d*)(\\D*)(\\d*)"); final Matcher matcher = pattern.matcher(pif); s_logger.debug("getting broadcast uri for pif " + pif + " and bridge " + brName); if(matcher.find()) { if (brName.startsWith("brvx")){ return BroadcastDomainType.Vxlan.toUri(matcher.group(2)).toString(); } else{ if (!matcher.group(6).isEmpty()) { return BroadcastDomainType.Vlan.toUri(matcher.group(6)).toString(); } else if (!matcher.group(4).isEmpty()) { return BroadcastDomainType.Vlan.toUri(matcher.group(4)).toString(); } else { //untagged or not matching (eth|bond|team)#.# s_logger.debug("failed to get vNet id from bridge " + brName + "attached to physical interface" + pif + ", perhaps untagged interface"); return ""; } } } else { s_logger.debug("failed to get vNet id from bridge " + brName + "attached to physical interface" + pif); return ""; } } private void VifHotPlug(final Connect conn, final String vmName, final String broadcastUri, final String macAddr) throws InternalErrorException, LibvirtException { final NicTO nicTO = new NicTO(); nicTO.setMac(macAddr); nicTO.setType(TrafficType.Public); if (broadcastUri == null) { nicTO.setBroadcastType(BroadcastDomainType.Native); } else { final URI uri = BroadcastDomainType.fromString(broadcastUri); nicTO.setBroadcastType(BroadcastDomainType.getSchemeValue(uri)); nicTO.setBroadcastUri(uri); } final Domain vm = getDomain(conn, vmName); vm.attachDevice(getVifDriver(nicTO.getType()).plug(nicTO, "Other PV", "", null).toString()); } private void vifHotUnPlug (final Connect conn, final String vmName, final String macAddr) throws InternalErrorException, LibvirtException { Domain vm = null; vm = getDomain(conn, vmName); final List<InterfaceDef> pluggedNics = getInterfaces(conn, vmName); for (final InterfaceDef pluggedNic : pluggedNics) { if (pluggedNic.getMacAddress().equalsIgnoreCase(macAddr)) { vm.detachDevice(pluggedNic.toString()); // We don't know which "traffic type" is associated with // each interface at this point, so inform all vif drivers for (final VifDriver vifDriver : getAllVifDrivers()) { vifDriver.unplug(pluggedNic); } } } } private ExecutionResult prepareNetworkElementCommand(final SetupGuestNetworkCommand cmd) { Connect conn; final NicTO nic = cmd.getNic(); final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); try { conn = LibvirtConnection.getConnectionByVmName(routerName); final List<InterfaceDef> pluggedNics = getInterfaces(conn, routerName); InterfaceDef routerNic = null; for (final InterfaceDef pluggedNic : pluggedNics) { if (pluggedNic.getMacAddress().equalsIgnoreCase(nic.getMac())) { routerNic = pluggedNic; break; } } if (routerNic == null) { return new ExecutionResult(false, "Can not find nic with mac " + nic.getMac() + " for VM " + routerName); } return new ExecutionResult(true, null); } catch (final LibvirtException e) { final String msg = "Creating guest network failed due to " + e.toString(); s_logger.warn(msg, e); return new ExecutionResult(false, msg); } } protected ExecutionResult prepareNetworkElementCommand(final SetSourceNatCommand cmd) { Connect conn; final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); final IpAddressTO pubIP = cmd.getIpAddress(); try { conn = LibvirtConnection.getConnectionByVmName(routerName); Integer devNum = 0; final String pubVlan = pubIP.getBroadcastUri(); final List<InterfaceDef> pluggedNics = getInterfaces(conn, routerName); for (final InterfaceDef pluggedNic : pluggedNics) { final String pluggedVlanBr = pluggedNic.getBrName(); final String pluggedVlanId = getBroadcastUriFromBridge(pluggedVlanBr); if (pubVlan.equalsIgnoreCase(Vlan.UNTAGGED) && pluggedVlanBr.equalsIgnoreCase(_publicBridgeName)) { break; } else if (pluggedVlanBr.equalsIgnoreCase(_linkLocalBridgeName)) { /*skip over, no physical bridge device exists*/ } else if (pluggedVlanId == null) { /*this should only be true in the case of link local bridge*/ return new ExecutionResult(false, "unable to find the vlan id for bridge " + pluggedVlanBr + " when attempting to set up" + pubVlan + " on router " + routerName); } else if (pluggedVlanId.equals(pubVlan)) { break; } devNum++; } pubIP.setNicDevId(devNum); return new ExecutionResult(true, "success"); } catch (final LibvirtException e) { final String msg = "Ip SNAT failure due to " + e.toString(); s_logger.error(msg, e); return new ExecutionResult(false, msg); } } protected ExecutionResult prepareNetworkElementCommand(final IpAssocVpcCommand cmd) { Connect conn; final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); try { conn = getLibvirtUtilitiesHelper().getConnectionByVmName(routerName); Pair<Map<String, Integer>, Integer> macAddressToNicNumPair = getMacAddressToNicNumPair(conn, routerName); final Map<String, Integer> macAddressToNicNum = macAddressToNicNumPair.first(); Integer devNum = macAddressToNicNumPair.second(); final IpAddressTO[] ips = cmd.getIpAddresses(); for (final IpAddressTO ip : ips) { ip.setNicDevId(macAddressToNicNum.get(ip.getVifMacAddress())); } return new ExecutionResult(true, null); } catch (final LibvirtException e) { s_logger.error("Ip Assoc failure on applying one ip due to exception: ", e); return new ExecutionResult(false, e.getMessage()); } } public ExecutionResult prepareNetworkElementCommand(final IpAssocCommand cmd) { final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); final String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); Connect conn; try { conn = getLibvirtUtilitiesHelper().getConnectionByVmName(routerName); Pair<Map<String, Integer>, Integer> macAddressToNicNumPair = getMacAddressToNicNumPair(conn, routerName); final Map<String, Integer> macAddressToNicNum = macAddressToNicNumPair.first(); Integer devNum = macAddressToNicNumPair.second(); final IpAddressTO[] ips = cmd.getIpAddresses(); int nicNum = 0; for (final IpAddressTO ip : ips) { boolean newNic = false; if (!macAddressToNicNum.containsKey(ip.getVifMacAddress())) { /* plug a vif into router */ VifHotPlug(conn, routerName, ip.getBroadcastUri(), ip.getVifMacAddress()); macAddressToNicNum.put(ip.getVifMacAddress(), devNum++); newNic = true; } nicNum = macAddressToNicNum.get(ip.getVifMacAddress()); networkUsage(routerIp, "addVif", "eth" + nicNum); ip.setNicDevId(nicNum); ip.setNewNic(newNic); } return new ExecutionResult(true, null); } catch (final LibvirtException e) { s_logger.error("ipassoccmd failed", e); return new ExecutionResult(false, e.getMessage()); } catch (final InternalErrorException e) { s_logger.error("ipassoccmd failed", e); return new ExecutionResult(false, e.getMessage()); } } protected ExecutionResult cleanupNetworkElementCommand(final IpAssocCommand cmd) { final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); final String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); final String lastIp = cmd.getAccessDetail(NetworkElementCommand.NETWORK_PUB_LAST_IP); Connect conn; try { conn = getLibvirtUtilitiesHelper().getConnectionByVmName(routerName); Pair<Map<String, Integer>, Integer> macAddressToNicNumPair = getMacAddressToNicNumPair(conn, routerName); final Map<String, Integer> macAddressToNicNum = macAddressToNicNumPair.first(); Integer devNum = macAddressToNicNumPair.second(); final IpAddressTO[] ips = cmd.getIpAddresses(); int nicNum = 0; for (final IpAddressTO ip : ips) { if (!macAddressToNicNum.containsKey(ip.getVifMacAddress())) { /* plug a vif into router */ VifHotPlug(conn, routerName, ip.getBroadcastUri(), ip.getVifMacAddress()); macAddressToNicNum.put(ip.getVifMacAddress(), devNum++); } nicNum = macAddressToNicNum.get(ip.getVifMacAddress()); if (org.apache.commons.lang.StringUtils.equalsIgnoreCase(lastIp, "true") && !ip.isAdd()) { // in isolated network eth2 is the default public interface. We don't want to delete it. if (nicNum != 2) { vifHotUnPlug(conn, routerName, ip.getVifMacAddress()); networkUsage(routerIp, "deleteVif", "eth" + nicNum); } } } } catch (final LibvirtException e) { s_logger.error("ipassoccmd failed", e); return new ExecutionResult(false, e.getMessage()); } catch (final InternalErrorException e) { s_logger.error("ipassoccmd failed", e); return new ExecutionResult(false, e.getMessage()); } return new ExecutionResult(true, null); } private Pair<Map<String, Integer>, Integer> getMacAddressToNicNumPair(Connect conn, String routerName) { Integer devNum = 0; final List<InterfaceDef> pluggedNics = getInterfaces(conn, routerName); final Map<String, Integer> macAddressToNicNum = new HashMap<>(pluggedNics.size()); for (final InterfaceDef pluggedNic : pluggedNics) { final String pluggedVlan = pluggedNic.getBrName(); macAddressToNicNum.put(pluggedNic.getMacAddress(), devNum); devNum++; } return new Pair<Map<String, Integer>, Integer>(macAddressToNicNum, devNum); } protected PowerState convertToPowerState(final DomainState ps) { final PowerState state = s_powerStatesTable.get(ps); return state == null ? PowerState.PowerUnknown : state; } public PowerState getVmState(final Connect conn, final String vmName) { int retry = 3; Domain vms = null; while (retry-- > 0) { try { vms = conn.domainLookupByName(vmName); final PowerState s = convertToPowerState(vms.getInfo().state); return s; } catch (final LibvirtException e) { s_logger.warn("Can't get vm state " + vmName + e.getMessage() + "retry:" + retry); } finally { try { if (vms != null) { vms.free(); } } catch (final LibvirtException l) { s_logger.trace("Ignoring libvirt error.", l); } } } return PowerState.PowerOff; } public String networkUsage(final String privateIpAddress, final String option, final String vif) { final Script getUsage = new Script(_routerProxyPath, s_logger); getUsage.add("netusage.sh"); getUsage.add(privateIpAddress); if (option.equals("get")) { getUsage.add("-g"); } else if (option.equals("create")) { getUsage.add("-c"); } else if (option.equals("reset")) { getUsage.add("-r"); } else if (option.equals("addVif")) { getUsage.add("-a", vif); } else if (option.equals("deleteVif")) { getUsage.add("-d", vif); } final OutputInterpreter.OneLineParser usageParser = new OutputInterpreter.OneLineParser(); final String result = getUsage.execute(usageParser); if (result != null) { s_logger.debug("Failed to execute networkUsage:" + result); return null; } return usageParser.getLine(); } public long[] getNetworkStats(final String privateIP) { final String result = networkUsage(privateIP, "get", null); final long[] stats = new long[2]; if (result != null) { final String[] splitResult = result.split(":"); int i = 0; while (i < splitResult.length - 1) { stats[0] += Long.parseLong(splitResult[i++]); stats[1] += Long.parseLong(splitResult[i++]); } } return stats; } public String configureVPCNetworkUsage(final String privateIpAddress, final String publicIp, final String option, final String vpcCIDR) { final Script getUsage = new Script(_routerProxyPath, s_logger); getUsage.add("vpc_netusage.sh"); getUsage.add(privateIpAddress); getUsage.add("-l", publicIp); if (option.equals("get")) { getUsage.add("-g"); } else if (option.equals("create")) { getUsage.add("-c"); getUsage.add("-v", vpcCIDR); } else if (option.equals("reset")) { getUsage.add("-r"); } else if (option.equals("vpn")) { getUsage.add("-n"); } else if (option.equals("remove")) { getUsage.add("-d"); } final OutputInterpreter.OneLineParser usageParser = new OutputInterpreter.OneLineParser(); final String result = getUsage.execute(usageParser); if (result != null) { s_logger.debug("Failed to execute VPCNetworkUsage:" + result); return null; } return usageParser.getLine(); } public long[] getVPCNetworkStats(final String privateIP, final String publicIp, final String option) { final String result = configureVPCNetworkUsage(privateIP, publicIp, option, null); final long[] stats = new long[2]; if (result != null) { final String[] splitResult = result.split(":"); int i = 0; while (i < splitResult.length - 1) { stats[0] += Long.parseLong(splitResult[i++]); stats[1] += Long.parseLong(splitResult[i++]); } } return stats; } public void handleVmStartFailure(final Connect conn, final String vmName, final LibvirtVMDef vm) { if (vm != null && vm.getDevices() != null) { cleanupVMNetworks(conn, vm.getDevices().getInterfaces()); } } protected String getUuid(String uuid) { if (uuid == null) { uuid = UUID.randomUUID().toString(); } else { try { final UUID uuid2 = UUID.fromString(uuid); final String uuid3 = uuid2.toString(); if (!uuid3.equals(uuid)) { uuid = UUID.randomUUID().toString(); } } catch (final IllegalArgumentException e) { uuid = UUID.randomUUID().toString(); } } return uuid; } /** * Set quota and period tags on 'ctd' when CPU limit use is set */ protected void setQuotaAndPeriod(VirtualMachineTO vmTO, CpuTuneDef ctd) { if (vmTO.getLimitCpuUse() && vmTO.getCpuQuotaPercentage() != null) { Double cpuQuotaPercentage = vmTO.getCpuQuotaPercentage(); int period = CpuTuneDef.DEFAULT_PERIOD; int quota = (int) (period * cpuQuotaPercentage); if (quota < CpuTuneDef.MIN_QUOTA) { s_logger.info("Calculated quota (" + quota + ") below the minimum (" + CpuTuneDef.MIN_QUOTA + ") for VM domain " + vmTO.getUuid() + ", setting it to minimum " + "and calculating period instead of using the default"); quota = CpuTuneDef.MIN_QUOTA; period = (int) ((double) quota / cpuQuotaPercentage); if (period > CpuTuneDef.MAX_PERIOD) { s_logger.info("Calculated period (" + period + ") exceeds the maximum (" + CpuTuneDef.MAX_PERIOD + "), setting it to the maximum"); period = CpuTuneDef.MAX_PERIOD; } } ctd.setQuota(quota); ctd.setPeriod(period); s_logger.info("Setting quota=" + quota + ", period=" + period + " to VM domain " + vmTO.getUuid()); } } protected void enlightenWindowsVm(VirtualMachineTO vmTO, FeaturesDef features) { if (vmTO.getOs().contains("Windows PV")) { // If OS is Windows PV, then enable the features. Features supported on Windows 2008 and later LibvirtVMDef.HyperVEnlightenmentFeatureDef hyv = new LibvirtVMDef.HyperVEnlightenmentFeatureDef(); hyv.setFeature("relaxed", true); hyv.setFeature("vapic", true); hyv.setFeature("spinlocks", true); hyv.setRetries(8096); features.addHyperVFeature(hyv); s_logger.info("Enabling KVM Enlightment Features to VM domain " + vmTO.getUuid()); } } public LibvirtVMDef createVMFromSpec(final VirtualMachineTO vmTO) { final LibvirtVMDef vm = new LibvirtVMDef(); vm.setDomainName(vmTO.getName()); String uuid = vmTO.getUuid(); uuid = getUuid(uuid); vm.setDomUUID(uuid); vm.setDomDescription(vmTO.getOs()); vm.setPlatformEmulator(vmTO.getPlatformEmulator()); Map<String, String> customParams = vmTO.getDetails(); boolean isUefiEnabled = false; boolean isSecureBoot = false; String bootMode =null; if (MapUtils.isNotEmpty(customParams) && customParams.containsKey(GuestDef.BootType.UEFI.toString())) { isUefiEnabled = true; bootMode = customParams.get(GuestDef.BootType.UEFI.toString()); if (StringUtils.isNotBlank(bootMode) && "secure".equalsIgnoreCase(bootMode)) { isSecureBoot = true; } } Map<String, String> extraConfig = vmTO.getExtraConfig(); if (dpdkSupport && (!extraConfig.containsKey(DpdkHelper.DPDK_NUMA) || !extraConfig.containsKey(DpdkHelper.DPDK_HUGE_PAGES))) { s_logger.info("DPDK is enabled but it needs extra configurations for CPU NUMA and Huge Pages for VM deployment"); } final GuestDef guest = new GuestDef(); if (HypervisorType.LXC == _hypervisorType && VirtualMachine.Type.User == vmTO.getType()) { // LXC domain is only valid for user VMs. Use KVM for system VMs. guest.setGuestType(GuestDef.GuestType.LXC); vm.setHvsType(HypervisorType.LXC.toString().toLowerCase()); } else { guest.setGuestType(GuestDef.GuestType.KVM); vm.setHvsType(HypervisorType.KVM.toString().toLowerCase()); vm.setLibvirtVersion(_hypervisorLibvirtVersion); vm.setQemuVersion(_hypervisorQemuVersion); } guest.setGuestArch(_guestCpuArch != null ? _guestCpuArch : vmTO.getArch()); guest.setMachineType(_guestCpuArch != null && _guestCpuArch.equals("aarch64") ? "virt" : "pc"); guest.setBootType(GuestDef.BootType.BIOS); if (MapUtils.isNotEmpty(customParams) && customParams.containsKey(GuestDef.BootType.UEFI.toString())) { guest.setBootType(GuestDef.BootType.UEFI); guest.setBootMode(GuestDef.BootMode.LEGACY); if (StringUtils.isNotBlank(customParams.get(GuestDef.BootType.UEFI.toString())) && "secure".equalsIgnoreCase(customParams.get(GuestDef.BootType.UEFI.toString()))) { guest.setMachineType("q35"); guest.setBootMode(GuestDef.BootMode.SECURE); // setting to secure mode } } guest.setUuid(uuid); guest.setBootOrder(GuestDef.BootOrder.CDROM); guest.setBootOrder(GuestDef.BootOrder.HARDISK); if (isUefiEnabled) { if (_uefiProperties.getProperty(GuestDef.GUEST_LOADER_SECURE) != null && "secure".equalsIgnoreCase(bootMode)) { guest.setLoader(_uefiProperties.getProperty(GuestDef.GUEST_LOADER_SECURE)); } if (_uefiProperties.getProperty(GuestDef.GUEST_LOADER_LEGACY) != null && "legacy".equalsIgnoreCase(bootMode)) { guest.setLoader(_uefiProperties.getProperty(GuestDef.GUEST_LOADER_LEGACY)); } if (_uefiProperties.getProperty(GuestDef.GUEST_NVRAM_PATH) != null) { guest.setNvram(_uefiProperties.getProperty(GuestDef.GUEST_NVRAM_PATH)); } if (isSecureBoot) { if (_uefiProperties.getProperty(GuestDef.GUEST_NVRAM_TEMPLATE_SECURE) != null && "secure".equalsIgnoreCase(bootMode)) { guest.setNvramTemplate(_uefiProperties.getProperty(GuestDef.GUEST_NVRAM_TEMPLATE_SECURE)); } } else { if (_uefiProperties.getProperty(GuestDef.GUEST_NVRAM_TEMPLATE_LEGACY) != null) { guest.setNvramTemplate(_uefiProperties.getProperty(GuestDef.GUEST_NVRAM_TEMPLATE_LEGACY)); } } } vm.addComp(guest); final GuestResourceDef grd = new GuestResourceDef(); if (vmTO.getMinRam() != vmTO.getMaxRam() && !_noMemBalloon) { grd.setMemBalloning(true); grd.setCurrentMem(vmTO.getMinRam() / 1024); grd.setMemorySize(vmTO.getMaxRam() / 1024); } else { grd.setMemorySize(vmTO.getMaxRam() / 1024); } final int vcpus = vmTO.getCpus(); grd.setVcpuNum(vcpus); vm.addComp(grd); if (!extraConfig.containsKey(DpdkHelper.DPDK_NUMA)) { final CpuModeDef cmd = new CpuModeDef(); cmd.setMode(_guestCpuMode); cmd.setModel(_guestCpuModel); if (vmTO.getType() == VirtualMachine.Type.User) { cmd.setFeatures(_cpuFeatures); } // multi cores per socket, for larger core configs if (vcpus % 6 == 0) { final int sockets = vcpus / 6; cmd.setTopology(6, sockets); } else if (vcpus % 4 == 0) { final int sockets = vcpus / 4; cmd.setTopology(4, sockets); } vm.addComp(cmd); } if (_hypervisorLibvirtVersion >= 9000) { final CpuTuneDef ctd = new CpuTuneDef(); /** A 4.0.X/4.1.X management server doesn't send the correct JSON command for getMinSpeed, it only sends a 'speed' field. So if getMinSpeed() returns null we fall back to getSpeed(). This way a >4.1 agent can work communicate a <=4.1 management server This change is due to the overcommit feature in 4.2 */ if (vmTO.getMinSpeed() != null) { ctd.setShares(vmTO.getCpus() * vmTO.getMinSpeed()); } else { ctd.setShares(vmTO.getCpus() * vmTO.getSpeed()); } setQuotaAndPeriod(vmTO, ctd); vm.addComp(ctd); } final FeaturesDef features = new FeaturesDef(); features.addFeatures("pae"); features.addFeatures("apic"); features.addFeatures("acpi"); if (isUefiEnabled && isSecureMode(customParams.get(GuestDef.BootType.UEFI.toString()))) { features.addFeatures("smm"); } //KVM hyperv enlightenment features based on OS Type enlightenWindowsVm(vmTO, features); vm.addComp(features); final TermPolicy term = new TermPolicy(); term.setCrashPolicy("destroy"); term.setPowerOffPolicy("destroy"); term.setRebootPolicy("restart"); vm.addComp(term); final ClockDef clock = new ClockDef(); if (vmTO.getOs().startsWith("Windows")) { clock.setClockOffset(ClockDef.ClockOffset.LOCALTIME); clock.setTimer("hypervclock", null, null); } else if (vmTO.getType() != VirtualMachine.Type.User || isGuestPVEnabled(vmTO.getOs())) { if (_hypervisorLibvirtVersion >= 9 * 1000 + 10) { clock.setTimer("kvmclock", null, null, _noKvmClock); } } vm.addComp(clock); final DevicesDef devices = new DevicesDef(); devices.setEmulatorPath(_hypervisorPath); devices.setGuestType(guest.getGuestType()); final SerialDef serial = new SerialDef("pty", null, (short)0); devices.addDevice(serial); if (_rngEnable) { final RngDef rngDevice = new RngDef(_rngPath, _rngBackendModel, _rngRateBytes, _rngRatePeriod); devices.addDevice(rngDevice); } /* Add a VirtIO channel for the Qemu Guest Agent tools */ File virtIoChannel = Paths.get(_qemuSocketsPath.getPath(), vmTO.getName() + "." + _qemuGuestAgentSocketName).toFile(); devices.addDevice(new ChannelDef(_qemuGuestAgentSocketName, ChannelDef.ChannelType.UNIX, virtIoChannel)); devices.addDevice(new WatchDogDef(_watchDogAction, _watchDogModel)); final VideoDef videoCard = new VideoDef(_videoHw, _videoRam); devices.addDevice(videoCard); final ConsoleDef console = new ConsoleDef("pty", null, null, (short)0); devices.addDevice(console); //add the VNC port passwd here, get the passwd from the vmInstance. final String passwd = vmTO.getVncPassword(); final GraphicDef grap = new GraphicDef("vnc", (short)0, true, vmTO.getVncAddr(), passwd, null); devices.addDevice(grap); final InputDef input = new InputDef("tablet", "usb"); devices.addDevice(input); // Add an explicit USB devices for ARM64 if (_guestCpuArch != null && _guestCpuArch.equals("aarch64")) { devices.addDevice(new InputDef("keyboard", "usb")); devices.addDevice(new InputDef("mouse", "usb")); devices.addDevice(new LibvirtVMDef.USBDef((short)0, 0, 5, 0, 0)); } DiskDef.DiskBus busT = getDiskModelFromVMDetail(vmTO); if (busT == null) { busT = getGuestDiskModel(vmTO.getPlatformEmulator()); } // If we're using virtio scsi, then we need to add a virtual scsi controller if (busT == DiskDef.DiskBus.SCSI) { final SCSIDef sd = new SCSIDef((short)0, 0, 0, 9, 0, vcpus); devices.addDevice(sd); } vm.addComp(devices); // Add extra configuration to User VM Domain XML before starting if (vmTO.getType().equals(VirtualMachine.Type.User) && MapUtils.isNotEmpty(extraConfig)) { s_logger.info("Appending extra configuration data to guest VM domain XML"); addExtraConfigComponent(extraConfig, vm); } return vm; } /** * Add extra configurations (if any) as a String component to the domain XML */ protected void addExtraConfigComponent(Map<String, String> extraConfig, LibvirtVMDef vm) { if (MapUtils.isNotEmpty(extraConfig)) { StringBuilder extraConfigBuilder = new StringBuilder(); for (String key : extraConfig.keySet()) { if (!key.startsWith(DpdkHelper.DPDK_INTERFACE_PREFIX) && !key.equals(DpdkHelper.DPDK_VHOST_USER_MODE)) { extraConfigBuilder.append(extraConfig.get(key)); } } String comp = extraConfigBuilder.toString(); if (org.apache.commons.lang.StringUtils.isNotBlank(comp)) { vm.addComp(comp); } } } public void createVifs(final VirtualMachineTO vmSpec, final LibvirtVMDef vm) throws InternalErrorException, LibvirtException { final NicTO[] nics = vmSpec.getNics(); final Map <String, String> params = vmSpec.getDetails(); String nicAdapter = ""; if (params != null && params.get("nicAdapter") != null && !params.get("nicAdapter").isEmpty()) { nicAdapter = params.get("nicAdapter"); } Map<String, String> extraConfig = vmSpec.getExtraConfig(); for (int i = 0; i < nics.length; i++) { for (final NicTO nic : vmSpec.getNics()) { if (nic.getDeviceId() == i) { createVif(vm, nic, nicAdapter, extraConfig); } } } } public String getVolumePath(final Connect conn, final DiskTO volume) throws LibvirtException, URISyntaxException { final DataTO data = volume.getData(); final DataStoreTO store = data.getDataStore(); if (volume.getType() == Volume.Type.ISO && data.getPath() != null && (store instanceof NfsTO || store instanceof PrimaryDataStoreTO && data instanceof TemplateObjectTO && !((TemplateObjectTO) data).isDirectDownload())) { final String isoPath = store.getUrl().split("\\?")[0] + File.separator + data.getPath(); final int index = isoPath.lastIndexOf("/"); final String path = isoPath.substring(0, index); final String name = isoPath.substring(index + 1); final KVMStoragePool secondaryPool = _storagePoolMgr.getStoragePoolByURI(path); final KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name); return isoVol.getPath(); } else { return data.getPath(); } } public void createVbd(final Connect conn, final VirtualMachineTO vmSpec, final String vmName, final LibvirtVMDef vm) throws InternalErrorException, LibvirtException, URISyntaxException { final Map<String, String> details = vmSpec.getDetails(); final List<DiskTO> disks = Arrays.asList(vmSpec.getDisks()); boolean isSecureBoot = false; boolean isWindowsTemplate = false; Collections.sort(disks, new Comparator<DiskTO>() { @Override public int compare(final DiskTO arg0, final DiskTO arg1) { return arg0.getDiskSeq() > arg1.getDiskSeq() ? 1 : -1; } }); if (MapUtils.isNotEmpty(details) && details.containsKey(GuestDef.BootType.UEFI.toString())) { isSecureBoot = isSecureMode(details.get(GuestDef.BootType.UEFI.toString())); } if (vmSpec.getOs().toLowerCase().contains("window")) { isWindowsTemplate =true; } for (final DiskTO volume : disks) { KVMPhysicalDisk physicalDisk = null; KVMStoragePool pool = null; final DataTO data = volume.getData(); if (volume.getType() == Volume.Type.ISO && data.getPath() != null) { DataStoreTO dataStore = data.getDataStore(); String dataStoreUrl = null; if (dataStore instanceof NfsTO) { NfsTO nfsStore = (NfsTO)data.getDataStore(); dataStoreUrl = nfsStore.getUrl(); physicalDisk = getPhysicalDiskFromNfsStore(dataStoreUrl, data); } else if (dataStore instanceof PrimaryDataStoreTO) { //In order to support directly downloaded ISOs PrimaryDataStoreTO primaryDataStoreTO = (PrimaryDataStoreTO) dataStore; if (primaryDataStoreTO.getPoolType().equals(StoragePoolType.NetworkFilesystem)) { String psHost = primaryDataStoreTO.getHost(); String psPath = primaryDataStoreTO.getPath(); dataStoreUrl = "nfs://" + psHost + File.separator + psPath; physicalDisk = getPhysicalDiskFromNfsStore(dataStoreUrl, data); } else if (primaryDataStoreTO.getPoolType().equals(StoragePoolType.SharedMountPoint) || primaryDataStoreTO.getPoolType().equals(StoragePoolType.Filesystem)) { physicalDisk = getPhysicalDiskPrimaryStore(primaryDataStoreTO, data); } } } else if (volume.getType() != Volume.Type.ISO) { final PrimaryDataStoreTO store = (PrimaryDataStoreTO)data.getDataStore(); physicalDisk = _storagePoolMgr.getPhysicalDisk(store.getPoolType(), store.getUuid(), data.getPath()); pool = physicalDisk.getPool(); } String volPath = null; if (physicalDisk != null) { volPath = physicalDisk.getPath(); } // check for disk activity, if detected we should exit because vm is running elsewhere if (_diskActivityCheckEnabled && physicalDisk != null && physicalDisk.getFormat() == PhysicalDiskFormat.QCOW2) { s_logger.debug("Checking physical disk file at path " + volPath + " for disk activity to ensure vm is not running elsewhere"); try { HypervisorUtils.checkVolumeFileForActivity(volPath, _diskActivityCheckTimeoutSeconds, _diskActivityInactiveThresholdMilliseconds, _diskActivityCheckFileSizeMin); } catch (final IOException ex) { throw new CloudRuntimeException("Unable to check physical disk file for activity", ex); } s_logger.debug("Disk activity check cleared"); } // if params contains a rootDiskController key, use its value (this is what other HVs are doing) DiskDef.DiskBus diskBusType = getDiskModelFromVMDetail(vmSpec); if (diskBusType == null) { diskBusType = getGuestDiskModel(vmSpec.getPlatformEmulator()); } // I'm not sure why previously certain DATADISKs were hard-coded VIRTIO and others not, however this // maintains existing functionality with the exception that SCSI will override VIRTIO. DiskDef.DiskBus diskBusTypeData = (diskBusType == DiskDef.DiskBus.SCSI) ? diskBusType : DiskDef.DiskBus.VIRTIO; final DiskDef disk = new DiskDef(); int devId = volume.getDiskSeq().intValue(); if (volume.getType() == Volume.Type.ISO) { if (volPath == null) { if (isSecureBoot) { disk.defISODisk(null, devId,isSecureBoot,isWindowsTemplate); } else { /* Add iso as placeholder */ disk.defISODisk(null, devId); } } else { disk.defISODisk(volPath, devId); } if (_guestCpuArch != null && _guestCpuArch.equals("aarch64")) { disk.setBusType(DiskDef.DiskBus.SCSI); } } else { if (diskBusType == DiskDef.DiskBus.SCSI ) { disk.setQemuDriver(true); disk.setDiscard(DiscardType.UNMAP); } if (pool.getType() == StoragePoolType.RBD) { /* For RBD pools we use the secret mechanism in libvirt. We store the secret under the UUID of the pool, that's why we pass the pool's UUID as the authSecret */ disk.defNetworkBasedDisk(physicalDisk.getPath().replace("rbd:", ""), pool.getSourceHost(), pool.getSourcePort(), pool.getAuthUserName(), pool.getUuid(), devId, diskBusType, DiskProtocol.RBD, DiskDef.DiskFmtType.RAW); } else if (pool.getType() == StoragePoolType.Gluster) { final String mountpoint = pool.getLocalPath(); final String path = physicalDisk.getPath(); final String glusterVolume = pool.getSourceDir().replace("/", ""); disk.defNetworkBasedDisk(glusterVolume + path.replace(mountpoint, ""), pool.getSourceHost(), pool.getSourcePort(), null, null, devId, diskBusType, DiskProtocol.GLUSTER, DiskDef.DiskFmtType.QCOW2); } else if (pool.getType() == StoragePoolType.CLVM || physicalDisk.getFormat() == PhysicalDiskFormat.RAW) { if (volume.getType() == Volume.Type.DATADISK) { disk.defBlockBasedDisk(physicalDisk.getPath(), devId, diskBusTypeData); } else { disk.defBlockBasedDisk(physicalDisk.getPath(), devId, diskBusType); } } else { if (volume.getType() == Volume.Type.DATADISK) { disk.defFileBasedDisk(physicalDisk.getPath(), devId, diskBusTypeData, DiskDef.DiskFmtType.QCOW2); } else { if (isSecureBoot) { disk.defFileBasedDisk(physicalDisk.getPath(), devId, DiskDef.DiskFmtType.QCOW2, isWindowsTemplate); } else { disk.defFileBasedDisk(physicalDisk.getPath(), devId, diskBusType, DiskDef.DiskFmtType.QCOW2); } } } } if (data instanceof VolumeObjectTO) { final VolumeObjectTO volumeObjectTO = (VolumeObjectTO)data; disk.setSerial(diskUuidToSerial(volumeObjectTO.getUuid())); setBurstProperties(volumeObjectTO, disk); if (volumeObjectTO.getCacheMode() != null) { disk.setCacheMode(DiskDef.DiskCacheMode.valueOf(volumeObjectTO.getCacheMode().toString().toUpperCase())); } } if (vm.getDevices() == null) { s_logger.error("There is no devices for" + vm); throw new RuntimeException("There is no devices for" + vm); } vm.getDevices().addDevice(disk); } if (vmSpec.getType() != VirtualMachine.Type.User) { if (_sysvmISOPath != null) { final DiskDef iso = new DiskDef(); iso.defISODisk(_sysvmISOPath); if (_guestCpuArch != null && _guestCpuArch.equals("aarch64")) { iso.setBusType(DiskDef.DiskBus.SCSI); } vm.getDevices().addDevice(iso); } } // For LXC, find and add the root filesystem, rbd data disks if (HypervisorType.LXC.toString().toLowerCase().equals(vm.getHvsType())) { for (final DiskTO volume : disks) { final DataTO data = volume.getData(); final PrimaryDataStoreTO store = (PrimaryDataStoreTO)data.getDataStore(); if (volume.getType() == Volume.Type.ROOT) { final KVMPhysicalDisk physicalDisk = _storagePoolMgr.getPhysicalDisk(store.getPoolType(), store.getUuid(), data.getPath()); final FilesystemDef rootFs = new FilesystemDef(physicalDisk.getPath(), "/"); vm.getDevices().addDevice(rootFs); } else if (volume.getType() == Volume.Type.DATADISK) { final KVMPhysicalDisk physicalDisk = _storagePoolMgr.getPhysicalDisk(store.getPoolType(), store.getUuid(), data.getPath()); final KVMStoragePool pool = physicalDisk.getPool(); if(StoragePoolType.RBD.equals(pool.getType())) { final int devId = volume.getDiskSeq().intValue(); final String device = mapRbdDevice(physicalDisk); if (device != null) { s_logger.debug("RBD device on host is: " + device); final DiskDef diskdef = new DiskDef(); diskdef.defBlockBasedDisk(device, devId, DiskDef.DiskBus.VIRTIO); diskdef.setQemuDriver(false); vm.getDevices().addDevice(diskdef); } else { throw new InternalErrorException("Error while mapping RBD device on host"); } } } } } } private KVMPhysicalDisk getPhysicalDiskPrimaryStore(PrimaryDataStoreTO primaryDataStoreTO, DataTO data) { KVMStoragePool storagePool = _storagePoolMgr.getStoragePool(primaryDataStoreTO.getPoolType(), primaryDataStoreTO.getUuid()); return storagePool.getPhysicalDisk(data.getPath()); } private KVMPhysicalDisk getPhysicalDiskFromNfsStore(String dataStoreUrl, DataTO data) { final String volPath = dataStoreUrl + File.separator + data.getPath(); final int index = volPath.lastIndexOf("/"); final String volDir = volPath.substring(0, index); final String volName = volPath.substring(index + 1); final KVMStoragePool storage = _storagePoolMgr.getStoragePoolByURI(volDir); return storage.getPhysicalDisk(volName); } private void setBurstProperties(final VolumeObjectTO volumeObjectTO, final DiskDef disk ) { if (volumeObjectTO.getBytesReadRate() != null && volumeObjectTO.getBytesReadRate() > 0) { disk.setBytesReadRate(volumeObjectTO.getBytesReadRate()); } if (volumeObjectTO.getBytesReadRateMax() != null && volumeObjectTO.getBytesReadRateMax() > 0) { disk.setBytesReadRateMax(volumeObjectTO.getBytesReadRateMax()); } if (volumeObjectTO.getBytesReadRateMaxLength() != null && volumeObjectTO.getBytesReadRateMaxLength() > 0) { disk.setBytesReadRateMaxLength(volumeObjectTO.getBytesReadRateMaxLength()); } if (volumeObjectTO.getBytesWriteRate() != null && volumeObjectTO.getBytesWriteRate() > 0) { disk.setBytesWriteRate(volumeObjectTO.getBytesWriteRate()); } if (volumeObjectTO.getBytesWriteRateMax() != null && volumeObjectTO.getBytesWriteRateMax() > 0) { disk.setBytesWriteRateMax(volumeObjectTO.getBytesWriteRateMax()); } if (volumeObjectTO.getBytesWriteRateMaxLength() != null && volumeObjectTO.getBytesWriteRateMaxLength() > 0) { disk.setBytesWriteRateMaxLength(volumeObjectTO.getBytesWriteRateMaxLength()); } if (volumeObjectTO.getIopsReadRate() != null && volumeObjectTO.getIopsReadRate() > 0) { disk.setIopsReadRate(volumeObjectTO.getIopsReadRate()); } if (volumeObjectTO.getIopsReadRateMax() != null && volumeObjectTO.getIopsReadRateMax() > 0) { disk.setIopsReadRateMax(volumeObjectTO.getIopsReadRateMax()); } if (volumeObjectTO.getIopsReadRateMaxLength() != null && volumeObjectTO.getIopsReadRateMaxLength() > 0) { disk.setIopsReadRateMaxLength(volumeObjectTO.getIopsReadRateMaxLength()); } if (volumeObjectTO.getIopsWriteRate() != null && volumeObjectTO.getIopsWriteRate() > 0) { disk.setIopsWriteRate(volumeObjectTO.getIopsWriteRate()); } if (volumeObjectTO.getIopsWriteRateMax() != null && volumeObjectTO.getIopsWriteRateMax() > 0) { disk.setIopsWriteRateMax(volumeObjectTO.getIopsWriteRateMax()); } if (volumeObjectTO.getIopsWriteRateMaxLength() != null && volumeObjectTO.getIopsWriteRateMaxLength() > 0) { disk.setIopsWriteRateMaxLength(volumeObjectTO.getIopsWriteRateMaxLength()); } } private void createVif(final LibvirtVMDef vm, final NicTO nic, final String nicAdapter, Map<String, String> extraConfig) throws InternalErrorException, LibvirtException { if (vm.getDevices() == null) { s_logger.error("LibvirtVMDef object get devices with null result"); throw new InternalErrorException("LibvirtVMDef object get devices with null result"); } vm.getDevices().addDevice(getVifDriver(nic.getType(), nic.getName()).plug(nic, vm.getPlatformEmulator(), nicAdapter, extraConfig)); } public boolean cleanupDisk(Map<String, String> volumeToDisconnect) { return _storagePoolMgr.disconnectPhysicalDisk(volumeToDisconnect); } public boolean cleanupDisk(final DiskDef disk) { final String path = disk.getDiskPath(); if (path == null) { s_logger.debug("Unable to clean up disk with null path (perhaps empty cdrom drive):" + disk); return false; } if (path.endsWith("systemvm.iso")) { // don't need to clean up system vm ISO as it's stored in local return true; } return _storagePoolMgr.disconnectPhysicalDiskByPath(path); } protected KVMStoragePoolManager getPoolManager() { return _storagePoolMgr; } public synchronized String attachOrDetachISO(final Connect conn, final String vmName, String isoPath, final boolean isAttach, final Integer diskSeq) throws LibvirtException, URISyntaxException, InternalErrorException { final DiskDef iso = new DiskDef(); if (isoPath != null && isAttach) { final int index = isoPath.lastIndexOf("/"); final String path = isoPath.substring(0, index); final String name = isoPath.substring(index + 1); final KVMStoragePool secondaryPool = _storagePoolMgr.getStoragePoolByURI(path); final KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name); isoPath = isoVol.getPath(); iso.defISODisk(isoPath, diskSeq); } else { iso.defISODisk(null, diskSeq); } final String result = attachOrDetachDevice(conn, true, vmName, iso.toString()); if (result == null && !isAttach) { final List<DiskDef> disks = getDisks(conn, vmName); for (final DiskDef disk : disks) { if (disk.getDeviceType() == DiskDef.DeviceType.CDROM && (diskSeq == null || disk.getDiskLabel() == iso.getDiskLabel())) { cleanupDisk(disk); } } } return result; } public synchronized String attachOrDetachDisk(final Connect conn, final boolean attach, final String vmName, final KVMPhysicalDisk attachingDisk, final int devId, final Long bytesReadRate, final Long bytesReadRateMax, final Long bytesReadRateMaxLength, final Long bytesWriteRate, final Long bytesWriteRateMax, final Long bytesWriteRateMaxLength, final Long iopsReadRate, final Long iopsReadRateMax, final Long iopsReadRateMaxLength, final Long iopsWriteRate, final Long iopsWriteRateMax, final Long iopsWriteRateMaxLength, final String cacheMode) throws LibvirtException, InternalErrorException { List<DiskDef> disks = null; Domain dm = null; DiskDef diskdef = null; final KVMStoragePool attachingPool = attachingDisk.getPool(); try { dm = conn.domainLookupByName(vmName); final LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); final String domXml = dm.getXMLDesc(0); parser.parseDomainXML(domXml); disks = parser.getDisks(); if (!attach) { for (final DiskDef disk : disks) { final String file = disk.getDiskPath(); if (file != null && file.equalsIgnoreCase(attachingDisk.getPath())) { diskdef = disk; break; } } if (diskdef == null) { throw new InternalErrorException("disk: " + attachingDisk.getPath() + " is not attached before"); } } else { DiskDef.DiskBus busT = DiskDef.DiskBus.VIRTIO; for (final DiskDef disk : disks) { if (disk.getDeviceType() == DeviceType.DISK) { if (disk.getBusType() == DiskDef.DiskBus.SCSI) { busT = DiskDef.DiskBus.SCSI; } break; } } diskdef = new DiskDef(); if (busT == DiskDef.DiskBus.SCSI) { diskdef.setQemuDriver(true); diskdef.setDiscard(DiscardType.UNMAP); } if (attachingPool.getType() == StoragePoolType.RBD) { diskdef.defNetworkBasedDisk(attachingDisk.getPath(), attachingPool.getSourceHost(), attachingPool.getSourcePort(), attachingPool.getAuthUserName(), attachingPool.getUuid(), devId, busT, DiskProtocol.RBD, DiskDef.DiskFmtType.RAW); } else if (attachingPool.getType() == StoragePoolType.Gluster) { diskdef.defNetworkBasedDisk(attachingDisk.getPath(), attachingPool.getSourceHost(), attachingPool.getSourcePort(), null, null, devId, busT, DiskProtocol.GLUSTER, DiskDef.DiskFmtType.QCOW2); } else if (attachingDisk.getFormat() == PhysicalDiskFormat.QCOW2) { diskdef.defFileBasedDisk(attachingDisk.getPath(), devId, busT, DiskDef.DiskFmtType.QCOW2); } else if (attachingDisk.getFormat() == PhysicalDiskFormat.RAW) { diskdef.defBlockBasedDisk(attachingDisk.getPath(), devId, busT); } if (bytesReadRate != null && bytesReadRate > 0) { diskdef.setBytesReadRate(bytesReadRate); } if (bytesReadRateMax != null && bytesReadRateMax > 0) { diskdef.setBytesReadRateMax(bytesReadRateMax); } if (bytesReadRateMaxLength != null && bytesReadRateMaxLength > 0) { diskdef.setBytesReadRateMaxLength(bytesReadRateMaxLength); } if (bytesWriteRate != null && bytesWriteRate > 0) { diskdef.setBytesWriteRate(bytesWriteRate); } if (bytesWriteRateMax != null && bytesWriteRateMax > 0) { diskdef.setBytesWriteRateMax(bytesWriteRateMax); } if (bytesWriteRateMaxLength != null && bytesWriteRateMaxLength > 0) { diskdef.setBytesWriteRateMaxLength(bytesWriteRateMaxLength); } if (iopsReadRate != null && iopsReadRate > 0) { diskdef.setIopsReadRate(iopsReadRate); } if (iopsReadRateMax != null && iopsReadRateMax > 0) { diskdef.setIopsReadRateMax(iopsReadRateMax); } if (iopsReadRateMaxLength != null && iopsReadRateMaxLength > 0) { diskdef.setIopsReadRateMaxLength(iopsReadRateMaxLength); } if (iopsWriteRate != null && iopsWriteRate > 0) { diskdef.setIopsWriteRate(iopsWriteRate); } if (iopsWriteRateMax != null && iopsWriteRateMax > 0) { diskdef.setIopsWriteRateMax(iopsWriteRateMax); } if (cacheMode != null) { diskdef.setCacheMode(DiskDef.DiskCacheMode.valueOf(cacheMode.toUpperCase())); } } final String xml = diskdef.toString(); return attachOrDetachDevice(conn, attach, vmName, xml); } finally { if (dm != null) { dm.free(); } } } protected synchronized String attachOrDetachDevice(final Connect conn, final boolean attach, final String vmName, final String xml) throws LibvirtException, InternalErrorException { Domain dm = null; try { dm = conn.domainLookupByName(vmName); if (attach) { s_logger.debug("Attaching device: " + xml); dm.attachDevice(xml); } else { s_logger.debug("Detaching device: " + xml); dm.detachDevice(xml); } } catch (final LibvirtException e) { if (attach) { s_logger.warn("Failed to attach device to " + vmName + ": " + e.getMessage()); } else { s_logger.warn("Failed to detach device from " + vmName + ": " + e.getMessage()); } throw e; } finally { if (dm != null) { try { dm.free(); } catch (final LibvirtException l) { s_logger.trace("Ignoring libvirt error.", l); } } } return null; } @Override public PingCommand getCurrentStatus(final long id) { if (!_canBridgeFirewall) { return new PingRoutingCommand(com.cloud.host.Host.Type.Routing, id, this.getHostVmStateReport()); } else { final HashMap<String, Pair<Long, Long>> nwGrpStates = syncNetworkGroups(id); return new PingRoutingWithNwGroupsCommand(getType(), id, this.getHostVmStateReport(), nwGrpStates); } } @Override public Type getType() { return Type.Routing; } private Map<String, String> getVersionStrings() { final Script command = new Script(_versionstringpath, _timeout, s_logger); final KeyValueInterpreter kvi = new KeyValueInterpreter(); final String result = command.execute(kvi); if (result == null) { return kvi.getKeyValues(); } else { return new HashMap<String, String>(1); } } @Override public StartupCommand[] initialize() { final KVMHostInfo info = new KVMHostInfo(_dom0MinMem, _dom0OvercommitMem); String capabilities = String.join(",", info.getCapabilities()); if (dpdkSupport) { capabilities += ",dpdk"; } final StartupRoutingCommand cmd = new StartupRoutingCommand(info.getCpus(), info.getCpuSpeed(), info.getTotalMemory(), info.getReservedMemory(), capabilities, _hypervisorType, RouterPrivateIpStrategy.HostLocal); cmd.setCpuSockets(info.getCpuSockets()); fillNetworkInformation(cmd); _privateIp = cmd.getPrivateIpAddress(); cmd.getHostDetails().putAll(getVersionStrings()); cmd.getHostDetails().put(KeyStoreUtils.SECURED, String.valueOf(isHostSecured()).toLowerCase()); cmd.setPool(_pool); cmd.setCluster(_clusterId); cmd.setGatewayIpAddress(_localGateway); cmd.setIqn(getIqn()); if (cmd.getHostDetails().containsKey("Host.OS")) { _hostDistro = cmd.getHostDetails().get("Host.OS"); } StartupStorageCommand sscmd = null; try { final KVMStoragePool localStoragePool = _storagePoolMgr.createStoragePool(_localStorageUUID, "localhost", -1, _localStoragePath, "", StoragePoolType.Filesystem); final com.cloud.agent.api.StoragePoolInfo pi = new com.cloud.agent.api.StoragePoolInfo(localStoragePool.getUuid(), cmd.getPrivateIpAddress(), _localStoragePath, _localStoragePath, StoragePoolType.Filesystem, localStoragePool.getCapacity(), localStoragePool.getAvailable()); sscmd = new StartupStorageCommand(); sscmd.setPoolInfo(pi); sscmd.setGuid(pi.getUuid()); sscmd.setDataCenter(_dcId); sscmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL); } catch (final CloudRuntimeException e) { s_logger.debug("Unable to initialize local storage pool: " + e); } if (sscmd != null) { return new StartupCommand[] {cmd, sscmd}; } else { return new StartupCommand[] {cmd}; } } public String diskUuidToSerial(String uuid) { String uuidWithoutHyphen = uuid.replace("-",""); return uuidWithoutHyphen.substring(0, Math.min(uuidWithoutHyphen.length(), 20)); } private String getIqn() { try { final String textToFind = "InitiatorName="; final Script iScsiAdmCmd = new Script(true, "grep", 0, s_logger); iScsiAdmCmd.add(textToFind); iScsiAdmCmd.add("/etc/iscsi/initiatorname.iscsi"); final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); final String result = iScsiAdmCmd.execute(parser); if (result != null) { return null; } final String textFound = parser.getLine().trim(); return textFound.substring(textToFind.length()); } catch (final Exception ex) { return null; } } protected List<String> getAllVmNames(final Connect conn) { final ArrayList<String> la = new ArrayList<String>(); try { final String names[] = conn.listDefinedDomains(); for (int i = 0; i < names.length; i++) { la.add(names[i]); } } catch (final LibvirtException e) { s_logger.warn("Failed to list Defined domains", e); } int[] ids = null; try { ids = conn.listDomains(); } catch (final LibvirtException e) { s_logger.warn("Failed to list domains", e); return la; } Domain dm = null; for (int i = 0; i < ids.length; i++) { try { dm = conn.domainLookupByID(ids[i]); la.add(dm.getName()); } catch (final LibvirtException e) { s_logger.warn("Unable to get vms", e); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } } } return la; } private HashMap<String, HostVmStateReportEntry> getHostVmStateReport() { final HashMap<String, HostVmStateReportEntry> vmStates = new HashMap<String, HostVmStateReportEntry>(); Connect conn = null; if (_hypervisorType == HypervisorType.LXC) { try { conn = LibvirtConnection.getConnectionByType(HypervisorType.LXC.toString()); vmStates.putAll(getHostVmStateReport(conn)); conn = LibvirtConnection.getConnectionByType(HypervisorType.KVM.toString()); vmStates.putAll(getHostVmStateReport(conn)); } catch (final LibvirtException e) { s_logger.debug("Failed to get connection: " + e.getMessage()); } } if (_hypervisorType == HypervisorType.KVM) { try { conn = LibvirtConnection.getConnectionByType(HypervisorType.KVM.toString()); vmStates.putAll(getHostVmStateReport(conn)); } catch (final LibvirtException e) { s_logger.debug("Failed to get connection: " + e.getMessage()); } } return vmStates; } private HashMap<String, HostVmStateReportEntry> getHostVmStateReport(final Connect conn) { final HashMap<String, HostVmStateReportEntry> vmStates = new HashMap<String, HostVmStateReportEntry>(); String[] vms = null; int[] ids = null; try { ids = conn.listDomains(); } catch (final LibvirtException e) { s_logger.warn("Unable to listDomains", e); return null; } try { vms = conn.listDefinedDomains(); } catch (final LibvirtException e) { s_logger.warn("Unable to listDomains", e); return null; } Domain dm = null; for (int i = 0; i < ids.length; i++) { try { dm = conn.domainLookupByID(ids[i]); final DomainState ps = dm.getInfo().state; final PowerState state = convertToPowerState(ps); s_logger.trace("VM " + dm.getName() + ": powerstate = " + ps + "; vm state=" + state.toString()); final String vmName = dm.getName(); // TODO : for XS/KVM (host-based resource), we require to remove // VM completely from host, for some reason, KVM seems to still keep // Stopped VM around, to work-around that, reporting only powered-on VM // if (state == PowerState.PowerOn) { vmStates.put(vmName, new HostVmStateReportEntry(state, conn.getHostName())); } } catch (final LibvirtException e) { s_logger.warn("Unable to get vms", e); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } } } for (int i = 0; i < vms.length; i++) { try { dm = conn.domainLookupByName(vms[i]); final DomainState ps = dm.getInfo().state; final PowerState state = convertToPowerState(ps); final String vmName = dm.getName(); s_logger.trace("VM " + vmName + ": powerstate = " + ps + "; vm state=" + state.toString()); // TODO : for XS/KVM (host-based resource), we require to remove // VM completely from host, for some reason, KVM seems to still keep // Stopped VM around, to work-around that, reporting only powered-on VM // if (state == PowerState.PowerOn) { vmStates.put(vmName, new HostVmStateReportEntry(state, conn.getHostName())); } } catch (final LibvirtException e) { s_logger.warn("Unable to get vms", e); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } } } return vmStates; } public String rebootVM(final Connect conn, final String vmName) throws LibvirtException{ Domain dm = null; String msg = null; try { dm = conn.domainLookupByName(vmName); // Get XML Dump including the secure information such as VNC password // By passing 1, or VIR_DOMAIN_XML_SECURE flag // https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainXMLFlags String vmDef = dm.getXMLDesc(1); final LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); parser.parseDomainXML(vmDef); for (final InterfaceDef nic : parser.getInterfaces()) { if (nic.getNetType() == GuestNetType.BRIDGE && nic.getBrName().startsWith("cloudVirBr")) { try { final int vnetId = Integer.parseInt(nic.getBrName().replaceFirst("cloudVirBr", "")); final String pifName = getPif(_guestBridgeName); final String newBrName = "br" + pifName + "-" + vnetId; vmDef = vmDef.replace("'" + nic.getBrName() + "'", "'" + newBrName + "'"); s_logger.debug("VM bridge name is changed from " + nic.getBrName() + " to " + newBrName); } catch (final NumberFormatException e) { continue; } } } s_logger.debug(vmDef); msg = stopVM(conn, vmName, false); msg = startVM(conn, vmName, vmDef); return null; } catch (final LibvirtException e) { s_logger.warn("Failed to create vm", e); msg = e.getMessage(); } catch (final InternalErrorException e) { s_logger.warn("Failed to create vm", e); msg = e.getMessage(); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } } return msg; } public String stopVM(final Connect conn, final String vmName, final boolean forceStop) { DomainState state = null; Domain dm = null; // delete the metadata of vm snapshots before stopping try { dm = conn.domainLookupByName(vmName); cleanVMSnapshotMetadata(dm); } catch (LibvirtException e) { s_logger.debug("Failed to get vm :" + e.getMessage()); } finally { try { if (dm != null) { dm.free(); } } catch (LibvirtException l) { s_logger.trace("Ignoring libvirt error.", l); } } s_logger.debug("Try to stop the vm at first"); if (forceStop) { return stopVMInternal(conn, vmName, true); } String ret = stopVMInternal(conn, vmName, false); if (ret == Script.ERR_TIMEOUT) { ret = stopVMInternal(conn, vmName, true); } else if (ret != null) { /* * There is a race condition between libvirt and qemu: libvirt * listens on qemu's monitor fd. If qemu is shutdown, while libvirt * is reading on the fd, then libvirt will report an error. */ /* Retry 3 times, to make sure we can get the vm's status */ for (int i = 0; i < 3; i++) { try { dm = conn.domainLookupByName(vmName); state = dm.getInfo().state; break; } catch (final LibvirtException e) { s_logger.debug("Failed to get vm status:" + e.getMessage()); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException l) { s_logger.trace("Ignoring libvirt error.", l); } } } if (state == null) { s_logger.debug("Can't get vm's status, assume it's dead already"); return null; } if (state != DomainState.VIR_DOMAIN_SHUTOFF) { s_logger.debug("Try to destroy the vm"); ret = stopVMInternal(conn, vmName, true); if (ret != null) { return ret; } } } return null; } protected String stopVMInternal(final Connect conn, final String vmName, final boolean force) { Domain dm = null; try { dm = conn.domainLookupByName(vmName); final int persist = dm.isPersistent(); if (force) { if (dm.isActive() == 1) { dm.destroy(); if (persist == 1) { dm.undefine(); } } } else { if (dm.isActive() == 0) { return null; } dm.shutdown(); int retry = _stopTimeout / 2000; /* Wait for the domain gets into shutoff state. When it does the dm object will no longer work, so we need to catch it. */ try { while (dm.isActive() == 1 && retry >= 0) { Thread.sleep(2000); retry--; } } catch (final LibvirtException e) { final String error = e.toString(); if (error.contains("Domain not found")) { s_logger.debug("successfully shut down vm " + vmName); } else { s_logger.debug("Error in waiting for vm shutdown:" + error); } } if (retry < 0) { s_logger.warn("Timed out waiting for domain " + vmName + " to shutdown gracefully"); return Script.ERR_TIMEOUT; } else { if (persist == 1) { dm.undefine(); } } } } catch (final LibvirtException e) { if (e.getMessage().contains("Domain not found")) { s_logger.debug("VM " + vmName + " doesn't exist, no need to stop it"); return null; } s_logger.debug("Failed to stop VM :" + vmName + " :", e); return e.getMessage(); } catch (final InterruptedException ie) { s_logger.debug("Interrupted sleep"); return ie.getMessage(); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } } return null; } public Integer getVncPort(final Connect conn, final String vmName) throws LibvirtException { final LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); Domain dm = null; try { dm = conn.domainLookupByName(vmName); final String xmlDesc = dm.getXMLDesc(0); parser.parseDomainXML(xmlDesc); return parser.getVncPort(); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException l) { s_logger.trace("Ignoring libvirt error.", l); } } } private boolean IsHVMEnabled(final Connect conn) { final LibvirtCapXMLParser parser = new LibvirtCapXMLParser(); try { parser.parseCapabilitiesXML(conn.getCapabilities()); final ArrayList<String> osTypes = parser.getGuestOsType(); for (final String o : osTypes) { if (o.equalsIgnoreCase("hvm")) { return true; } } } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } return false; } private String getHypervisorPath(final Connect conn) { final LibvirtCapXMLParser parser = new LibvirtCapXMLParser(); try { parser.parseCapabilitiesXML(conn.getCapabilities()); } catch (final LibvirtException e) { s_logger.debug(e.getMessage()); } return parser.getEmulator(); } boolean isGuestPVEnabled(final String guestOSName) { DiskDef.DiskBus db = getGuestDiskModel(guestOSName); return db != DiskDef.DiskBus.IDE; } public boolean isCentosHost() { if (_hvVersion <= 9) { return true; } else { return false; } } public DiskDef.DiskBus getDiskModelFromVMDetail(final VirtualMachineTO vmTO) { Map<String, String> details = vmTO.getDetails(); if (details == null) { return null; } if (_guestCpuArch != null && _guestCpuArch.equals("aarch64")) { return DiskDef.DiskBus.SCSI; } final String rootDiskController = details.get(VmDetailConstants.ROOT_DISK_CONTROLLER); if (StringUtils.isNotBlank(rootDiskController)) { s_logger.debug("Passed custom disk bus " + rootDiskController); for (final DiskDef.DiskBus bus : DiskDef.DiskBus.values()) { if (bus.toString().equalsIgnoreCase(rootDiskController)) { s_logger.debug("Found matching enum for disk bus " + rootDiskController); return bus; } } } return null; } private DiskDef.DiskBus getGuestDiskModel(final String platformEmulator) { if (_guestCpuArch != null && _guestCpuArch.equals("aarch64")) { return DiskDef.DiskBus.SCSI; } if (platformEmulator == null) { return DiskDef.DiskBus.IDE; } else if (platformEmulator.startsWith("Other PV Virtio-SCSI")) { return DiskDef.DiskBus.SCSI; } else if (platformEmulator.contains("Ubuntu") || platformEmulator.startsWith("Fedora") || platformEmulator.startsWith("CentOS") || platformEmulator.startsWith("Red Hat Enterprise Linux") || platformEmulator.startsWith("Debian GNU/Linux") || platformEmulator.startsWith("FreeBSD") || platformEmulator.startsWith("Oracle") || platformEmulator.startsWith("Other PV")) { return DiskDef.DiskBus.VIRTIO; } else { return DiskDef.DiskBus.IDE; } } private void cleanupVMNetworks(final Connect conn, final List<InterfaceDef> nics) { if (nics != null) { for (final InterfaceDef nic : nics) { for (final VifDriver vifDriver : getAllVifDrivers()) { vifDriver.unplug(nic); } } } } public Domain getDomain(final Connect conn, final String vmName) throws LibvirtException { return conn.domainLookupByName(vmName); } public List<InterfaceDef> getInterfaces(final Connect conn, final String vmName) { final LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); Domain dm = null; try { dm = conn.domainLookupByName(vmName); parser.parseDomainXML(dm.getXMLDesc(0)); return parser.getInterfaces(); } catch (final LibvirtException e) { s_logger.debug("Failed to get dom xml: " + e.toString()); return new ArrayList<InterfaceDef>(); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } } } public List<DiskDef> getDisks(final Connect conn, final String vmName) { final LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); Domain dm = null; try { dm = conn.domainLookupByName(vmName); parser.parseDomainXML(dm.getXMLDesc(0)); return parser.getDisks(); } catch (final LibvirtException e) { s_logger.debug("Failed to get dom xml: " + e.toString()); return new ArrayList<DiskDef>(); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } } } private String executeBashScript(final String script) { final Script command = new Script("/bin/bash", _timeout, s_logger); command.add("-c"); command.add(script); return command.execute(); } public List<VmNetworkStatsEntry> getVmNetworkStat(Connect conn, String vmName) throws LibvirtException { Domain dm = null; try { dm = getDomain(conn, vmName); List<VmNetworkStatsEntry> stats = new ArrayList<VmNetworkStatsEntry>(); List<InterfaceDef> nics = getInterfaces(conn, vmName); for (InterfaceDef nic : nics) { DomainInterfaceStats nicStats = dm.interfaceStats(nic.getDevName()); String macAddress = nic.getMacAddress(); VmNetworkStatsEntry stat = new VmNetworkStatsEntry(vmName, macAddress, nicStats.tx_bytes, nicStats.rx_bytes); stats.add(stat); } return stats; } finally { if (dm != null) { dm.free(); } } } public List<VmDiskStatsEntry> getVmDiskStat(final Connect conn, final String vmName) throws LibvirtException { Domain dm = null; try { dm = getDomain(conn, vmName); final List<VmDiskStatsEntry> stats = new ArrayList<VmDiskStatsEntry>(); final List<DiskDef> disks = getDisks(conn, vmName); for (final DiskDef disk : disks) { if (disk.getDeviceType() != DeviceType.DISK) { break; } final DomainBlockStats blockStats = dm.blockStats(disk.getDiskLabel()); final String path = disk.getDiskPath(); // for example, path = /mnt/pool_uuid/disk_path/ String diskPath = null; if (path != null) { final String[] token = path.split("/"); if (token.length > 3) { diskPath = token[3]; final VmDiskStatsEntry stat = new VmDiskStatsEntry(vmName, diskPath, blockStats.wr_req, blockStats.rd_req, blockStats.wr_bytes, blockStats.rd_bytes); stats.add(stat); } } } return stats; } finally { if (dm != null) { dm.free(); } } } private class VmStats { long _usedTime; long _tx; long _rx; long _ioRead; long _ioWrote; long _bytesRead; long _bytesWrote; Calendar _timestamp; } public VmStatsEntry getVmStat(final Connect conn, final String vmName) throws LibvirtException { Domain dm = null; try { dm = getDomain(conn, vmName); if (dm == null) { return null; } DomainInfo info = dm.getInfo(); final VmStatsEntry stats = new VmStatsEntry(); stats.setNumCPUs(info.nrVirtCpu); stats.setEntityType("vm"); stats.setMemoryKBs(info.maxMem); stats.setTargetMemoryKBs(info.memory); stats.setIntFreeMemoryKBs(getMemoryFreeInKBs(dm)); /* get cpu utilization */ VmStats oldStats = null; final Calendar now = Calendar.getInstance(); oldStats = _vmStats.get(vmName); long elapsedTime = 0; if (oldStats != null) { elapsedTime = now.getTimeInMillis() - oldStats._timestamp.getTimeInMillis(); double utilization = (info.cpuTime - oldStats._usedTime) / ((double)elapsedTime * 1000000); utilization = utilization / info.nrVirtCpu; if (utilization > 0) { stats.setCPUUtilization(utilization * 100); } } /* get network stats */ final List<InterfaceDef> vifs = getInterfaces(conn, vmName); long rx = 0; long tx = 0; for (final InterfaceDef vif : vifs) { final DomainInterfaceStats ifStats = dm.interfaceStats(vif.getDevName()); rx += ifStats.rx_bytes; tx += ifStats.tx_bytes; } if (oldStats != null) { final double deltarx = rx - oldStats._rx; if (deltarx > 0) { stats.setNetworkReadKBs(deltarx / 1024); } final double deltatx = tx - oldStats._tx; if (deltatx > 0) { stats.setNetworkWriteKBs(deltatx / 1024); } } /* get disk stats */ final List<DiskDef> disks = getDisks(conn, vmName); long io_rd = 0; long io_wr = 0; long bytes_rd = 0; long bytes_wr = 0; for (final DiskDef disk : disks) { if (disk.getDeviceType() == DeviceType.CDROM || disk.getDeviceType() == DeviceType.FLOPPY) { continue; } final DomainBlockStats blockStats = dm.blockStats(disk.getDiskLabel()); io_rd += blockStats.rd_req; io_wr += blockStats.wr_req; bytes_rd += blockStats.rd_bytes; bytes_wr += blockStats.wr_bytes; } if (oldStats != null) { final long deltaiord = io_rd - oldStats._ioRead; if (deltaiord > 0) { stats.setDiskReadIOs(deltaiord); } final long deltaiowr = io_wr - oldStats._ioWrote; if (deltaiowr > 0) { stats.setDiskWriteIOs(deltaiowr); } final double deltabytesrd = bytes_rd - oldStats._bytesRead; if (deltabytesrd > 0) { stats.setDiskReadKBs(deltabytesrd / 1024); } final double deltabyteswr = bytes_wr - oldStats._bytesWrote; if (deltabyteswr > 0) { stats.setDiskWriteKBs(deltabyteswr / 1024); } } /* save to Hashmap */ final VmStats newStat = new VmStats(); newStat._usedTime = info.cpuTime; newStat._rx = rx; newStat._tx = tx; newStat._ioRead = io_rd; newStat._ioWrote = io_wr; newStat._bytesRead = bytes_rd; newStat._bytesWrote = bytes_wr; newStat._timestamp = now; _vmStats.put(vmName, newStat); return stats; } finally { if (dm != null) { dm.free(); } } } /** * This method retrieves the memory statistics from the domain given as parameters. * If no memory statistic is found, it will return {@link NumberUtils#LONG_ZERO} as the value of free memory in the domain. * If it can retrieve the domain memory statistics, it will return the free memory statistic; that means, it returns the value at the first position of the array returned by {@link Domain#memoryStats(int)}. * * @return the amount of free memory in KBs */ protected long getMemoryFreeInKBs(Domain dm) throws LibvirtException { MemoryStatistic[] mems = dm.memoryStats(NUMMEMSTATS); if (ArrayUtils.isEmpty(mems)) { return NumberUtils.LONG_ZERO; } return mems[0].getValue(); } private boolean canBridgeFirewall(final String prvNic) { final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("can_bridge_firewall"); cmd.add("--privnic", prvNic); final String result = cmd.execute(); if (result != null) { return false; } return true; } public boolean destroyNetworkRulesForVM(final Connect conn, final String vmName) { if (!_canBridgeFirewall) { return false; } String vif = null; final List<InterfaceDef> intfs = getInterfaces(conn, vmName); if (intfs.size() > 0) { final InterfaceDef intf = intfs.get(0); vif = intf.getDevName(); } final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("destroy_network_rules_for_vm"); cmd.add("--vmname", vmName); if (vif != null) { cmd.add("--vif", vif); } final String result = cmd.execute(); if (result != null) { return false; } return true; } /** * Function to destroy the security group rules applied to the nic's * @param conn * @param vmName * @param nic * @return * true : If success * false : If failure */ public boolean destroyNetworkRulesForNic(final Connect conn, final String vmName, final NicTO nic) { if (!_canBridgeFirewall) { return false; } final List<String> nicSecIps = nic.getNicSecIps(); String secIpsStr; final StringBuilder sb = new StringBuilder(); if (nicSecIps != null) { for (final String ip : nicSecIps) { sb.append(ip).append(SecurityGroupRulesCmd.RULE_COMMAND_SEPARATOR); } secIpsStr = sb.toString(); } else { secIpsStr = "0" + SecurityGroupRulesCmd.RULE_COMMAND_SEPARATOR; } final List<InterfaceDef> intfs = getInterfaces(conn, vmName); if (intfs.size() == 0 || intfs.size() < nic.getDeviceId()) { return false; } final InterfaceDef intf = intfs.get(nic.getDeviceId()); final String brname = intf.getBrName(); final String vif = intf.getDevName(); final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("destroy_network_rules_for_vm"); cmd.add("--vmname", vmName); if (nic.getIp() != null) { cmd.add("--vmip", nic.getIp()); } cmd.add("--vmmac", nic.getMac()); cmd.add("--vif", vif); cmd.add("--nicsecips", secIpsStr); final String result = cmd.execute(); if (result != null) { return false; } return true; } /** * Function to apply default network rules for a VM * @param conn * @param vm * @param checkBeforeApply * @return */ public boolean applyDefaultNetworkRules(final Connect conn, final VirtualMachineTO vm, final boolean checkBeforeApply) { NicTO[] nicTOs = new NicTO[] {}; if (vm != null && vm.getNics() != null) { s_logger.debug("Checking default network rules for vm " + vm.getName()); nicTOs = vm.getNics(); } for (NicTO nic : nicTOs) { if (vm.getType() != VirtualMachine.Type.User) { nic.setPxeDisable(true); } } boolean isFirstNic = true; for (final NicTO nic : nicTOs) { if (nic.isSecurityGroupEnabled() || nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) { if (vm.getType() != VirtualMachine.Type.User) { configureDefaultNetworkRulesForSystemVm(conn, vm.getName()); break; } if (!applyDefaultNetworkRulesOnNic(conn, vm.getName(), vm.getId(), nic, isFirstNic, checkBeforeApply)) { s_logger.error("Unable to apply default network rule for nic " + nic.getName() + " for VM " + vm.getName()); return false; } isFirstNic = false; } } return true; } /** * Function to apply default network rules for a NIC * @param conn * @param vmName * @param vmId * @param nic * @param isFirstNic * @param checkBeforeApply * @return */ public boolean applyDefaultNetworkRulesOnNic(final Connect conn, final String vmName, final Long vmId, final NicTO nic, boolean isFirstNic, boolean checkBeforeApply) { final List<String> nicSecIps = nic.getNicSecIps(); String secIpsStr; final StringBuilder sb = new StringBuilder(); if (nicSecIps != null) { for (final String ip : nicSecIps) { sb.append(ip).append(SecurityGroupRulesCmd.RULE_COMMAND_SEPARATOR); } secIpsStr = sb.toString(); } else { secIpsStr = "0" + SecurityGroupRulesCmd.RULE_COMMAND_SEPARATOR; } return defaultNetworkRules(conn, vmName, nic, vmId, secIpsStr, isFirstNic, checkBeforeApply); } public boolean defaultNetworkRules(final Connect conn, final String vmName, final NicTO nic, final Long vmId, final String secIpStr, final boolean isFirstNic, final boolean checkBeforeApply) { if (!_canBridgeFirewall) { return false; } final List<InterfaceDef> intfs = getInterfaces(conn, vmName); if (intfs.size() == 0 || intfs.size() < nic.getDeviceId()) { return false; } final InterfaceDef intf = intfs.get(nic.getDeviceId()); final String brname = intf.getBrName(); final String vif = intf.getDevName(); final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("default_network_rules"); cmd.add("--vmname", vmName); cmd.add("--vmid", vmId.toString()); if (nic.getIp() != null) { cmd.add("--vmip", nic.getIp()); } if (nic.getIp6Address() != null) { cmd.add("--vmip6", nic.getIp6Address()); } cmd.add("--vmmac", nic.getMac()); cmd.add("--vif", vif); cmd.add("--brname", brname); cmd.add("--nicsecips", secIpStr); if (isFirstNic) { cmd.add("--isFirstNic"); } if (checkBeforeApply) { cmd.add("--check"); } final String result = cmd.execute(); if (result != null) { return false; } return true; } protected boolean post_default_network_rules(final Connect conn, final String vmName, final NicTO nic, final Long vmId, final InetAddress dhcpServerIp, final String hostIp, final String hostMacAddr) { if (!_canBridgeFirewall) { return false; } final List<InterfaceDef> intfs = getInterfaces(conn, vmName); if (intfs.size() < nic.getDeviceId()) { return false; } final InterfaceDef intf = intfs.get(nic.getDeviceId()); final String brname = intf.getBrName(); final String vif = intf.getDevName(); final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("post_default_network_rules"); cmd.add("--vmname", vmName); cmd.add("--vmid", vmId.toString()); cmd.add("--vmip", nic.getIp()); cmd.add("--vmmac", nic.getMac()); cmd.add("--vif", vif); cmd.add("--brname", brname); if (dhcpServerIp != null) { cmd.add("--dhcpSvr", dhcpServerIp.getHostAddress()); } cmd.add("--hostIp", hostIp); cmd.add("--hostMacAddr", hostMacAddr); final String result = cmd.execute(); if (result != null) { return false; } return true; } public boolean configureDefaultNetworkRulesForSystemVm(final Connect conn, final String vmName) { if (!_canBridgeFirewall) { return false; } final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("default_network_rules_systemvm"); cmd.add("--vmname", vmName); cmd.add("--localbrname", _linkLocalBridgeName); final String result = cmd.execute(); if (result != null) { return false; } return true; } public boolean addNetworkRules(final String vmName, final String vmId, final String guestIP, final String guestIP6, final String sig, final String seq, final String mac, final String rules, final String vif, final String brname, final String secIps) { if (!_canBridgeFirewall) { return false; } final String newRules = rules.replace(" ", ";"); final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("add_network_rules"); cmd.add("--vmname", vmName); cmd.add("--vmid", vmId); cmd.add("--vmip", guestIP); if (StringUtils.isNotBlank(guestIP6)) { cmd.add("--vmip6", guestIP6); } cmd.add("--sig", sig); cmd.add("--seq", seq); cmd.add("--vmmac", mac); cmd.add("--vif", vif); cmd.add("--brname", brname); cmd.add("--nicsecips", secIps); if (newRules != null && !newRules.isEmpty()) { cmd.add("--rules", newRules); } final String result = cmd.execute(); if (result != null) { return false; } return true; } public boolean configureNetworkRulesVMSecondaryIP(final Connect conn, final String vmName, final String vmMac, final String secIp, final String action) { if (!_canBridgeFirewall) { return false; } final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("network_rules_vmSecondaryIp"); cmd.add("--vmname", vmName); cmd.add("--vmmac", vmMac); cmd.add("--nicsecips", secIp); cmd.add("--action=" + action); final String result = cmd.execute(); if (result != null) { return false; } return true; } public boolean cleanupRules() { if (!_canBridgeFirewall) { return false; } final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("cleanup_rules"); final String result = cmd.execute(); if (result != null) { return false; } return true; } public String getRuleLogsForVms() { final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("get_rule_logs_for_vms"); final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); final String result = cmd.execute(parser); if (result == null) { return parser.getLine(); } return null; } private HashMap<String, Pair<Long, Long>> syncNetworkGroups(final long id) { final HashMap<String, Pair<Long, Long>> states = new HashMap<String, Pair<Long, Long>>(); final String result = getRuleLogsForVms(); s_logger.trace("syncNetworkGroups: id=" + id + " got: " + result); final String[] rulelogs = result != null ? result.split(";") : new String[0]; for (final String rulesforvm : rulelogs) { final String[] log = rulesforvm.split(","); if (log.length != 6) { continue; } try { states.put(log[0], new Pair<Long, Long>(Long.parseLong(log[1]), Long.parseLong(log[5]))); } catch (final NumberFormatException nfe) { states.put(log[0], new Pair<Long, Long>(-1L, -1L)); } } return states; } /* online snapshot supported by enhanced qemu-kvm */ private boolean isSnapshotSupported() { final String result = executeBashScript("qemu-img --help|grep convert"); if (result != null) { return false; } else { return true; } } public Pair<Double, Double> getNicStats(final String nicName) { return new Pair<Double, Double>(readDouble(nicName, "rx_bytes"), readDouble(nicName, "tx_bytes")); } static double readDouble(final String nicName, final String fileName) { final String path = "/sys/class/net/" + nicName + "/statistics/" + fileName; try { return Double.parseDouble(FileUtils.readFileToString(new File(path))); } catch (final IOException ioe) { s_logger.warn("Failed to read the " + fileName + " for " + nicName + " from " + path, ioe); return 0.0; } } private String prettyVersion(final long version) { final long major = version / 1000000; final long minor = version % 1000000 / 1000; final long release = version % 1000000 % 1000; return major + "." + minor + "." + release; } @Override public void setName(final String name) { // TODO Auto-generated method stub } @Override public void setConfigParams(final Map<String, Object> params) { // TODO Auto-generated method stub } @Override public Map<String, Object> getConfigParams() { // TODO Auto-generated method stub return null; } @Override public int getRunLevel() { // TODO Auto-generated method stub return 0; } @Override public void setRunLevel(final int level) { // TODO Auto-generated method stub } public HypervisorType getHypervisorType(){ return _hypervisorType; } public String mapRbdDevice(final KVMPhysicalDisk disk){ final KVMStoragePool pool = disk.getPool(); //Check if rbd image is already mapped final String[] splitPoolImage = disk.getPath().split("/"); String device = Script.runSimpleBashScript("rbd showmapped | grep \""+splitPoolImage[0]+"[ ]*"+splitPoolImage[1]+"\" | grep -o \"[^ ]*[ ]*$\""); if(device == null) { //If not mapped, map and return mapped device Script.runSimpleBashScript("rbd map " + disk.getPath() + " --id " + pool.getAuthUserName()); device = Script.runSimpleBashScript("rbd showmapped | grep \""+splitPoolImage[0]+"[ ]*"+splitPoolImage[1]+"\" | grep -o \"[^ ]*[ ]*$\""); } return device; } public List<Ternary<String, Boolean, String>> cleanVMSnapshotMetadata(Domain dm) throws LibvirtException { s_logger.debug("Cleaning the metadata of vm snapshots of vm " + dm.getName()); List<Ternary<String, Boolean, String>> vmsnapshots = new ArrayList<Ternary<String, Boolean, String>>(); if (dm.snapshotNum() == 0) { return vmsnapshots; } String currentSnapshotName = null; try { DomainSnapshot snapshotCurrent = dm.snapshotCurrent(); String snapshotXML = snapshotCurrent.getXMLDesc(); snapshotCurrent.free(); DocumentBuilder builder; try { builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(snapshotXML)); Document doc = builder.parse(is); Element rootElement = doc.getDocumentElement(); currentSnapshotName = getTagValue("name", rootElement); } catch (ParserConfigurationException e) { s_logger.debug(e.toString()); } catch (SAXException e) { s_logger.debug(e.toString()); } catch (IOException e) { s_logger.debug(e.toString()); } } catch (LibvirtException e) { s_logger.debug("Fail to get the current vm snapshot for vm: " + dm.getName() + ", continue"); } int flags = 2; // VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY = 2 String[] snapshotNames = dm.snapshotListNames(); Arrays.sort(snapshotNames); for (String snapshotName: snapshotNames) { DomainSnapshot snapshot = dm.snapshotLookupByName(snapshotName); Boolean isCurrent = (currentSnapshotName != null && currentSnapshotName.equals(snapshotName)) ? true: false; vmsnapshots.add(new Ternary<String, Boolean, String>(snapshotName, isCurrent, snapshot.getXMLDesc())); } for (String snapshotName: snapshotNames) { DomainSnapshot snapshot = dm.snapshotLookupByName(snapshotName); snapshot.delete(flags); // clean metadata of vm snapshot } return vmsnapshots; } private static String getTagValue(String tag, Element eElement) { NodeList nlList = eElement.getElementsByTagName(tag).item(0).getChildNodes(); Node nValue = nlList.item(0); return nValue.getNodeValue(); } public void restoreVMSnapshotMetadata(Domain dm, String vmName, List<Ternary<String, Boolean, String>> vmsnapshots) { s_logger.debug("Restoring the metadata of vm snapshots of vm " + vmName); for (Ternary<String, Boolean, String> vmsnapshot: vmsnapshots) { String snapshotName = vmsnapshot.first(); Boolean isCurrent = vmsnapshot.second(); String snapshotXML = vmsnapshot.third(); s_logger.debug("Restoring vm snapshot " + snapshotName + " on " + vmName + " with XML:\n " + snapshotXML); try { int flags = 1; // VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE = 1 if (isCurrent) { flags += 2; // VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT = 2 } dm.snapshotCreateXML(snapshotXML, flags); } catch (LibvirtException e) { s_logger.debug("Failed to restore vm snapshot " + snapshotName + ", continue"); continue; } } } public String getHostDistro() { return _hostDistro; } public boolean isHostSecured() { // Test for host certificates final File confFile = PropertiesUtil.findConfigFile(KeyStoreUtils.AGENT_PROPSFILE); if (confFile == null || !confFile.exists() || !Paths.get(confFile.getParent(), KeyStoreUtils.CERT_FILENAME).toFile().exists()) { return false; } // Test for libvirt TLS configuration try { new Connect(String.format("qemu+tls://%s/system", _privateIp)); } catch (final LibvirtException ignored) { return false; } return true; } public boolean isSecureMode(String bootMode) { if (StringUtils.isNotBlank(bootMode) && "secure".equalsIgnoreCase(bootMode)) { return true; } return false; } }
plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.hypervisor.kvm.resource; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.StringReader; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.naming.ConfigurationException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import com.cloud.hypervisor.kvm.resource.rolling.maintenance.RollingMaintenanceAgentExecutor; import com.cloud.hypervisor.kvm.resource.rolling.maintenance.RollingMaintenanceExecutor; import com.cloud.hypervisor.kvm.resource.rolling.maintenance.RollingMaintenanceServiceExecutor; import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; import org.apache.cloudstack.storage.to.TemplateObjectTO; import org.apache.cloudstack.storage.to.VolumeObjectTO; import org.apache.cloudstack.utils.hypervisor.HypervisorUtils; import org.apache.cloudstack.utils.linux.CPUStat; import org.apache.cloudstack.utils.linux.KVMHostInfo; import org.apache.cloudstack.utils.linux.MemStat; import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat; import org.apache.cloudstack.utils.security.KeyStoreUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.math.NumberUtils; import org.apache.log4j.Logger; import org.joda.time.Duration; import org.libvirt.Connect; import org.libvirt.Domain; import org.libvirt.DomainBlockStats; import org.libvirt.DomainInfo; import org.libvirt.DomainInfo.DomainState; import org.libvirt.DomainInterfaceStats; import org.libvirt.DomainSnapshot; import org.libvirt.LibvirtException; import org.libvirt.MemoryStatistic; import org.libvirt.Network; import org.libvirt.NodeInfo; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; import com.cloud.agent.api.HostVmStateReportEntry; import com.cloud.agent.api.PingCommand; import com.cloud.agent.api.PingRoutingCommand; import com.cloud.agent.api.PingRoutingWithNwGroupsCommand; import com.cloud.agent.api.SetupGuestNetworkCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; import com.cloud.agent.api.StartupStorageCommand; import com.cloud.agent.api.VmDiskStatsEntry; import com.cloud.agent.api.VmNetworkStatsEntry; import com.cloud.agent.api.VmStatsEntry; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.IpAssocVpcCommand; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.SetSourceNatCommand; import com.cloud.agent.api.to.DataStoreTO; import com.cloud.agent.api.to.DataTO; import com.cloud.agent.api.to.DiskTO; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.NfsTO; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.dao.impl.PropertiesStorage; import com.cloud.agent.resource.virtualnetwork.VRScripts; import com.cloud.agent.resource.virtualnetwork.VirtualRouterDeployer; import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource; import com.cloud.agent.api.SecurityGroupRulesCmd; import com.cloud.dc.Vlan; import com.cloud.exception.InternalErrorException; import com.cloud.host.Host.Type; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.kvm.dpdk.DpdkHelper; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.ChannelDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.ClockDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.ConsoleDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.CpuModeDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.CpuTuneDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DevicesDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef.DeviceType; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef.DiscardType; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef.DiskProtocol; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.FeaturesDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.FilesystemDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.GraphicDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.GuestDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.GuestResourceDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InputDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef.GuestNetType; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.RngDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.RngDef.RngBackendModel; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.SCSIDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.SerialDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.TermPolicy; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.VideoDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.WatchDogDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.WatchDogDef.WatchDogAction; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.WatchDogDef.WatchDogModel; import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper; import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper; import com.cloud.hypervisor.kvm.storage.IscsiStorageCleanupMonitor; import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk; import com.cloud.hypervisor.kvm.storage.KVMStoragePool; import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager; import com.cloud.hypervisor.kvm.storage.KVMStorageProcessor; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.IsolationType; import com.cloud.network.Networks.RouterPrivateIpStrategy; import com.cloud.network.Networks.TrafficType; import com.cloud.resource.RequestWrapper; import com.cloud.resource.ServerResource; import com.cloud.resource.ServerResourceBase; import com.cloud.storage.JavaStorageLayer; import com.cloud.storage.Storage; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StorageLayer; import com.cloud.storage.Volume; import com.cloud.storage.resource.StorageSubsystemCommandHandler; import com.cloud.storage.resource.StorageSubsystemCommandHandlerBase; import com.cloud.utils.ExecutionResult; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.PropertiesUtil; import com.cloud.utils.StringUtils; import com.cloud.utils.Ternary; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; import com.cloud.utils.script.OutputInterpreter; import com.cloud.utils.script.OutputInterpreter.AllLinesParser; import com.cloud.utils.script.Script; import com.cloud.utils.ssh.SshHelper; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.PowerState; import com.cloud.vm.VmDetailConstants; import com.google.common.base.Strings; /** * LibvirtComputingResource execute requests on the computing/routing host using * the libvirt API * * @config {@table || Param Name | Description | Values | Default || || * hypervisor.type | type of local hypervisor | string | kvm || || * hypervisor.uri | local hypervisor to connect to | URI | * qemu:///system || || domr.arch | instruction set for domr template | * string | i686 || || private.bridge.name | private bridge where the * domrs have their private interface | string | vmops0 || || * public.bridge.name | public bridge where the domrs have their public * interface | string | br0 || || private.network.name | name of the * network where the domrs have their private interface | string | * vmops-private || || private.ipaddr.start | start of the range of * private ip addresses for domrs | ip address | 192.168.166.128 || || * private.ipaddr.end | end of the range of private ip addresses for * domrs | ip address | start + 126 || || private.macaddr.start | start * of the range of private mac addresses for domrs | mac address | * 00:16:3e:77:e2:a0 || || private.macaddr.end | end of the range of * private mac addresses for domrs | mac address | start + 126 || || * pool | the parent of the storage pool hierarchy * } **/ public class LibvirtComputingResource extends ServerResourceBase implements ServerResource, VirtualRouterDeployer { private static final Logger s_logger = Logger.getLogger(LibvirtComputingResource.class); private String _modifyVlanPath; private String _versionstringpath; private String _patchScriptPath; private String _createvmPath; private String _manageSnapshotPath; private String _resizeVolumePath; private String _createTmplPath; private String _heartBeatPath; private String _vmActivityCheckPath; private String _securityGroupPath; private String _ovsPvlanDhcpHostPath; private String _ovsPvlanVmPath; private String _routerProxyPath; private String _ovsTunnelPath; private String _host; private String _dcId; private String _pod; private String _clusterId; private final Properties _uefiProperties = new Properties(); private long _hvVersion; private Duration _timeout; private static final int NUMMEMSTATS =2; private KVMHAMonitor _monitor; public static final String SSHKEYSPATH = "/root/.ssh"; public static final String SSHPRVKEYPATH = SSHKEYSPATH + File.separator + "id_rsa.cloud"; public static final String SSHPUBKEYPATH = SSHKEYSPATH + File.separator + "id_rsa.pub.cloud"; public static final String DEFAULTDOMRSSHPORT = "3922"; public static final String BASH_SCRIPT_PATH = "/bin/bash"; private String _mountPoint = "/mnt"; private StorageLayer _storage; private KVMStoragePoolManager _storagePoolMgr; private VifDriver _defaultVifDriver; private Map<TrafficType, VifDriver> _trafficTypeVifDrivers; protected static final String DEFAULT_OVS_VIF_DRIVER_CLASS_NAME = "com.cloud.hypervisor.kvm.resource.OvsVifDriver"; protected static final String DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME = "com.cloud.hypervisor.kvm.resource.BridgeVifDriver"; protected HypervisorType _hypervisorType; protected String _hypervisorURI; protected long _hypervisorLibvirtVersion; protected long _hypervisorQemuVersion; protected String _hypervisorPath; protected String _hostDistro; protected String _networkDirectSourceMode; protected String _networkDirectDevice; protected String _sysvmISOPath; protected String _privNwName; protected String _privBridgeName; protected String _linkLocalBridgeName; protected String _publicBridgeName; protected String _guestBridgeName; protected String _privateIp; protected String _pool; protected String _localGateway; private boolean _canBridgeFirewall; protected String _localStoragePath; protected String _localStorageUUID; protected boolean _noMemBalloon = false; protected String _guestCpuArch; protected String _guestCpuMode; protected String _guestCpuModel; protected boolean _noKvmClock; protected String _videoHw; protected int _videoRam; protected Pair<Integer,Integer> hostOsVersion; protected int _migrateSpeed; protected int _migrateDowntime; protected int _migratePauseAfter; protected boolean _diskActivityCheckEnabled; protected RollingMaintenanceExecutor rollingMaintenanceExecutor; protected long _diskActivityCheckFileSizeMin = 10485760; // 10MB protected int _diskActivityCheckTimeoutSeconds = 120; // 120s protected long _diskActivityInactiveThresholdMilliseconds = 30000; // 30s protected boolean _rngEnable = false; protected RngBackendModel _rngBackendModel = RngBackendModel.RANDOM; protected String _rngPath = "/dev/random"; protected int _rngRatePeriod = 1000; protected int _rngRateBytes = 2048; protected String _agentHooksBasedir = "/etc/cloudstack/agent/hooks"; protected String _agentHooksLibvirtXmlScript = "libvirt-vm-xml-transformer.groovy"; protected String _agentHooksLibvirtXmlMethod = "transform"; protected String _agentHooksVmOnStartScript = "libvirt-vm-state-change.groovy"; protected String _agentHooksVmOnStartMethod = "onStart"; protected String _agentHooksVmOnStopScript = "libvirt-vm-state-change.groovy"; protected String _agentHooksVmOnStopMethod = "onStop"; protected File _qemuSocketsPath; private final String _qemuGuestAgentSocketName = "org.qemu.guest_agent.0"; protected WatchDogAction _watchDogAction = WatchDogAction.NONE; protected WatchDogModel _watchDogModel = WatchDogModel.I6300ESB; private final Map <String, String> _pifs = new HashMap<String, String>(); private final Map<String, VmStats> _vmStats = new ConcurrentHashMap<String, VmStats>(); protected static final HashMap<DomainState, PowerState> s_powerStatesTable; static { s_powerStatesTable = new HashMap<DomainState, PowerState>(); s_powerStatesTable.put(DomainState.VIR_DOMAIN_SHUTOFF, PowerState.PowerOff); s_powerStatesTable.put(DomainState.VIR_DOMAIN_PAUSED, PowerState.PowerOn); s_powerStatesTable.put(DomainState.VIR_DOMAIN_RUNNING, PowerState.PowerOn); s_powerStatesTable.put(DomainState.VIR_DOMAIN_BLOCKED, PowerState.PowerOn); s_powerStatesTable.put(DomainState.VIR_DOMAIN_NOSTATE, PowerState.PowerUnknown); s_powerStatesTable.put(DomainState.VIR_DOMAIN_SHUTDOWN, PowerState.PowerOff); } private VirtualRoutingResource _virtRouterResource; private String _pingTestPath; private String _updateHostPasswdPath; private long _dom0MinMem; private long _dom0OvercommitMem; protected int _cmdsTimeout; protected int _stopTimeout; protected CPUStat _cpuStat = new CPUStat(); protected MemStat _memStat = new MemStat(_dom0MinMem, _dom0OvercommitMem); private final LibvirtUtilitiesHelper libvirtUtilitiesHelper = new LibvirtUtilitiesHelper(); @Override public ExecutionResult executeInVR(final String routerIp, final String script, final String args) { return executeInVR(routerIp, script, args, _timeout); } @Override public ExecutionResult executeInVR(final String routerIp, final String script, final String args, final Duration timeout) { final Script command = new Script(_routerProxyPath, timeout, s_logger); final AllLinesParser parser = new AllLinesParser(); command.add(script); command.add(routerIp); if (args != null) { command.add(args); } String details = command.execute(parser); if (details == null) { details = parser.getLines(); } s_logger.debug("Executing script in VR: " + script); return new ExecutionResult(command.getExitValue() == 0, details); } @Override public ExecutionResult createFileInVR(final String routerIp, final String path, final String filename, final String content) { final File permKey = new File("/root/.ssh/id_rsa.cloud"); boolean success = true; String details = "Creating file in VR, with ip: " + routerIp + ", file: " + filename; s_logger.debug(details); try { SshHelper.scpTo(routerIp, 3922, "root", permKey, null, path, content.getBytes(), filename, null); } catch (final Exception e) { s_logger.warn("Fail to create file " + path + filename + " in VR " + routerIp, e); details = e.getMessage(); success = false; } return new ExecutionResult(success, details); } @Override public ExecutionResult prepareCommand(final NetworkElementCommand cmd) { //Update IP used to access router cmd.setRouterAccessIp(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP)); assert cmd.getRouterAccessIp() != null; if (cmd instanceof IpAssocVpcCommand) { return prepareNetworkElementCommand((IpAssocVpcCommand)cmd); } else if (cmd instanceof IpAssocCommand) { return prepareNetworkElementCommand((IpAssocCommand)cmd); } else if (cmd instanceof SetupGuestNetworkCommand) { return prepareNetworkElementCommand((SetupGuestNetworkCommand)cmd); } else if (cmd instanceof SetSourceNatCommand) { return prepareNetworkElementCommand((SetSourceNatCommand)cmd); } return new ExecutionResult(true, null); } @Override public ExecutionResult cleanupCommand(final NetworkElementCommand cmd) { if (cmd instanceof IpAssocCommand && !(cmd instanceof IpAssocVpcCommand)) { return cleanupNetworkElementCommand((IpAssocCommand)cmd); } return new ExecutionResult(true, null); } public LibvirtKvmAgentHook getTransformer() throws IOException { return new LibvirtKvmAgentHook(_agentHooksBasedir, _agentHooksLibvirtXmlScript, _agentHooksLibvirtXmlMethod); } public LibvirtKvmAgentHook getStartHook() throws IOException { return new LibvirtKvmAgentHook(_agentHooksBasedir, _agentHooksVmOnStartScript, _agentHooksVmOnStartMethod); } public LibvirtKvmAgentHook getStopHook() throws IOException { return new LibvirtKvmAgentHook(_agentHooksBasedir, _agentHooksVmOnStopScript, _agentHooksVmOnStopMethod); } public LibvirtUtilitiesHelper getLibvirtUtilitiesHelper() { return libvirtUtilitiesHelper; } public CPUStat getCPUStat() { return _cpuStat; } public MemStat getMemStat() { return _memStat; } public VirtualRoutingResource getVirtRouterResource() { return _virtRouterResource; } public String getPublicBridgeName() { return _publicBridgeName; } public KVMStoragePoolManager getStoragePoolMgr() { return _storagePoolMgr; } public String getPrivateIp() { return _privateIp; } public int getMigrateDowntime() { return _migrateDowntime; } public int getMigratePauseAfter() { return _migratePauseAfter; } public int getMigrateSpeed() { return _migrateSpeed; } public RollingMaintenanceExecutor getRollingMaintenanceExecutor() { return rollingMaintenanceExecutor; } public String getPingTestPath() { return _pingTestPath; } public String getUpdateHostPasswdPath() { return _updateHostPasswdPath; } public Duration getTimeout() { return _timeout; } public String getOvsTunnelPath() { return _ovsTunnelPath; } public KVMHAMonitor getMonitor() { return _monitor; } public StorageLayer getStorage() { return _storage; } public String createTmplPath() { return _createTmplPath; } public int getCmdsTimeout() { return _cmdsTimeout; } public String manageSnapshotPath() { return _manageSnapshotPath; } public String getGuestBridgeName() { return _guestBridgeName; } public String getVmActivityCheckPath() { return _vmActivityCheckPath; } public String getOvsPvlanDhcpHostPath() { return _ovsPvlanDhcpHostPath; } public String getOvsPvlanVmPath() { return _ovsPvlanVmPath; } public String getDirectDownloadTemporaryDownloadPath() { return directDownloadTemporaryDownloadPath; } public String getResizeVolumePath() { return _resizeVolumePath; } public StorageSubsystemCommandHandler getStorageHandler() { return storageHandler; } private static final class KeyValueInterpreter extends OutputInterpreter { private final Map<String, String> map = new HashMap<String, String>(); @Override public String interpret(final BufferedReader reader) throws IOException { String line = null; int numLines = 0; while ((line = reader.readLine()) != null) { final String[] toks = line.trim().split("="); if (toks.length < 2) { s_logger.warn("Failed to parse Script output: " + line); } else { map.put(toks[0].trim(), toks[1].trim()); } numLines++; } if (numLines == 0) { s_logger.warn("KeyValueInterpreter: no output lines?"); } return null; } public Map<String, String> getKeyValues() { return map; } } @Override protected String getDefaultScriptsDir() { return null; } protected List<String> _cpuFeatures; protected enum BridgeType { NATIVE, OPENVSWITCH } protected BridgeType _bridgeType; protected StorageSubsystemCommandHandler storageHandler; protected boolean dpdkSupport = false; protected String dpdkOvsPath; protected String directDownloadTemporaryDownloadPath; private String getEndIpFromStartIp(final String startIp, final int numIps) { final String[] tokens = startIp.split("[.]"); assert tokens.length == 4; int lastbyte = Integer.parseInt(tokens[3]); lastbyte = lastbyte + numIps; tokens[3] = Integer.toString(lastbyte); final StringBuilder end = new StringBuilder(15); end.append(tokens[0]).append(".").append(tokens[1]).append(".").append(tokens[2]).append(".").append(tokens[3]); return end.toString(); } private Map<String, Object> getDeveloperProperties() throws ConfigurationException { final File file = PropertiesUtil.findConfigFile("developer.properties"); if (file == null) { throw new ConfigurationException("Unable to find developer.properties."); } s_logger.info("developer.properties found at " + file.getAbsolutePath()); try { final Properties properties = PropertiesUtil.loadFromFile(file); final String startMac = (String)properties.get("private.macaddr.start"); if (startMac == null) { throw new ConfigurationException("Developers must specify start mac for private ip range"); } final String startIp = (String)properties.get("private.ipaddr.start"); if (startIp == null) { throw new ConfigurationException("Developers must specify start ip for private ip range"); } final Map<String, Object> params = PropertiesUtil.toMap(properties); String endIp = (String)properties.get("private.ipaddr.end"); if (endIp == null) { endIp = getEndIpFromStartIp(startIp, 16); params.put("private.ipaddr.end", endIp); } return params; } catch (final FileNotFoundException ex) { throw new CloudRuntimeException("Cannot find the file: " + file.getAbsolutePath(), ex); } catch (final IOException ex) { throw new CloudRuntimeException("IOException in reading " + file.getAbsolutePath(), ex); } } private String getDefaultDirectDownloadTemporaryPath() { return "/var/lib/libvirt/images"; } protected String getDefaultNetworkScriptsDir() { return "scripts/vm/network/vnet"; } protected String getDefaultStorageScriptsDir() { return "scripts/storage/qcow2"; } protected String getDefaultHypervisorScriptsDir() { return "scripts/vm/hypervisor"; } protected String getDefaultKvmScriptsDir() { return "scripts/vm/hypervisor/kvm"; } protected String getDefaultDomrScriptsDir() { return "scripts/network/domr"; } protected String getNetworkDirectSourceMode() { return _networkDirectSourceMode; } protected String getNetworkDirectDevice() { return _networkDirectDevice; } @Override public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException { boolean success = super.configure(name, params); if (!success) { return false; } try { loadUefiProperties(); } catch (FileNotFoundException e) { s_logger.error("uefi properties file not found due to: " + e.getLocalizedMessage()); } _storage = new JavaStorageLayer(); _storage.configure("StorageLayer", params); String domrScriptsDir = (String)params.get("domr.scripts.dir"); if (domrScriptsDir == null) { domrScriptsDir = getDefaultDomrScriptsDir(); } String hypervisorScriptsDir = (String)params.get("hypervisor.scripts.dir"); if (hypervisorScriptsDir == null) { hypervisorScriptsDir = getDefaultHypervisorScriptsDir(); } String kvmScriptsDir = (String)params.get("kvm.scripts.dir"); if (kvmScriptsDir == null) { kvmScriptsDir = getDefaultKvmScriptsDir(); } String networkScriptsDir = (String)params.get("network.scripts.dir"); if (networkScriptsDir == null) { networkScriptsDir = getDefaultNetworkScriptsDir(); } String storageScriptsDir = (String)params.get("storage.scripts.dir"); if (storageScriptsDir == null) { storageScriptsDir = getDefaultStorageScriptsDir(); } final String bridgeType = (String)params.get("network.bridge.type"); if (bridgeType == null) { _bridgeType = BridgeType.NATIVE; } else { _bridgeType = BridgeType.valueOf(bridgeType.toUpperCase()); } String dpdk = (String) params.get("openvswitch.dpdk.enabled"); if (_bridgeType == BridgeType.OPENVSWITCH && Boolean.parseBoolean(dpdk)) { dpdkSupport = true; dpdkOvsPath = (String) params.get("openvswitch.dpdk.ovs.path"); if (dpdkOvsPath != null && !dpdkOvsPath.endsWith("/")) { dpdkOvsPath += "/"; } } directDownloadTemporaryDownloadPath = (String) params.get("direct.download.temporary.download.location"); if (org.apache.commons.lang.StringUtils.isBlank(directDownloadTemporaryDownloadPath)) { directDownloadTemporaryDownloadPath = getDefaultDirectDownloadTemporaryPath(); } params.put("domr.scripts.dir", domrScriptsDir); _virtRouterResource = new VirtualRoutingResource(this); success = _virtRouterResource.configure(name, params); if (!success) { return false; } _host = (String)params.get("host"); if (_host == null) { _host = "localhost"; } _dcId = (String)params.get("zone"); if (_dcId == null) { _dcId = "default"; } _pod = (String)params.get("pod"); if (_pod == null) { _pod = "default"; } _clusterId = (String)params.get("cluster"); _updateHostPasswdPath = Script.findScript(hypervisorScriptsDir, VRScripts.UPDATE_HOST_PASSWD); if (_updateHostPasswdPath == null) { throw new ConfigurationException("Unable to find update_host_passwd.sh"); } _modifyVlanPath = Script.findScript(networkScriptsDir, "modifyvlan.sh"); if (_modifyVlanPath == null) { throw new ConfigurationException("Unable to find modifyvlan.sh"); } _versionstringpath = Script.findScript(kvmScriptsDir, "versions.sh"); if (_versionstringpath == null) { throw new ConfigurationException("Unable to find versions.sh"); } _patchScriptPath = Script.findScript(kvmScriptsDir, "patch.sh"); if (_patchScriptPath == null) { throw new ConfigurationException("Unable to find patch.sh"); } _heartBeatPath = Script.findScript(kvmScriptsDir, "kvmheartbeat.sh"); if (_heartBeatPath == null) { throw new ConfigurationException("Unable to find kvmheartbeat.sh"); } _createvmPath = Script.findScript(storageScriptsDir, "createvm.sh"); if (_createvmPath == null) { throw new ConfigurationException("Unable to find the createvm.sh"); } _manageSnapshotPath = Script.findScript(storageScriptsDir, "managesnapshot.sh"); if (_manageSnapshotPath == null) { throw new ConfigurationException("Unable to find the managesnapshot.sh"); } _resizeVolumePath = Script.findScript(storageScriptsDir, "resizevolume.sh"); if (_resizeVolumePath == null) { throw new ConfigurationException("Unable to find the resizevolume.sh"); } _vmActivityCheckPath = Script.findScript(kvmScriptsDir, "kvmvmactivity.sh"); if (_vmActivityCheckPath == null) { throw new ConfigurationException("Unable to find kvmvmactivity.sh"); } _createTmplPath = Script.findScript(storageScriptsDir, "createtmplt.sh"); if (_createTmplPath == null) { throw new ConfigurationException("Unable to find the createtmplt.sh"); } _securityGroupPath = Script.findScript(networkScriptsDir, "security_group.py"); if (_securityGroupPath == null) { throw new ConfigurationException("Unable to find the security_group.py"); } _ovsTunnelPath = Script.findScript(networkScriptsDir, "ovstunnel.py"); if (_ovsTunnelPath == null) { throw new ConfigurationException("Unable to find the ovstunnel.py"); } _routerProxyPath = Script.findScript("scripts/network/domr/", "router_proxy.sh"); if (_routerProxyPath == null) { throw new ConfigurationException("Unable to find the router_proxy.sh"); } _ovsPvlanDhcpHostPath = Script.findScript(networkScriptsDir, "ovs-pvlan-dhcp-host.sh"); if (_ovsPvlanDhcpHostPath == null) { throw new ConfigurationException("Unable to find the ovs-pvlan-dhcp-host.sh"); } _ovsPvlanVmPath = Script.findScript(networkScriptsDir, "ovs-pvlan-vm.sh"); if (_ovsPvlanVmPath == null) { throw new ConfigurationException("Unable to find the ovs-pvlan-vm.sh"); } String value = (String)params.get("developer"); final boolean isDeveloper = Boolean.parseBoolean(value); if (isDeveloper) { params.putAll(getDeveloperProperties()); } _pool = (String)params.get("pool"); if (_pool == null) { _pool = "/root"; } final String instance = (String)params.get("instance"); _hypervisorType = HypervisorType.getType((String)params.get("hypervisor.type")); if (_hypervisorType == HypervisorType.None) { _hypervisorType = HypervisorType.KVM; } String hooksDir = (String)params.get("rolling.maintenance.hooks.dir"); value = (String) params.get("rolling.maintenance.service.executor.disabled"); rollingMaintenanceExecutor = Boolean.parseBoolean(value) ? new RollingMaintenanceAgentExecutor(hooksDir) : new RollingMaintenanceServiceExecutor(hooksDir); _hypervisorURI = (String)params.get("hypervisor.uri"); if (_hypervisorURI == null) { _hypervisorURI = LibvirtConnection.getHypervisorURI(_hypervisorType.toString()); } _networkDirectSourceMode = (String)params.get("network.direct.source.mode"); _networkDirectDevice = (String)params.get("network.direct.device"); String startMac = (String)params.get("private.macaddr.start"); if (startMac == null) { startMac = "00:16:3e:77:e2:a0"; } String startIp = (String)params.get("private.ipaddr.start"); if (startIp == null) { startIp = "192.168.166.128"; } _pingTestPath = Script.findScript(kvmScriptsDir, "pingtest.sh"); if (_pingTestPath == null) { throw new ConfigurationException("Unable to find the pingtest.sh"); } _linkLocalBridgeName = (String)params.get("private.bridge.name"); if (_linkLocalBridgeName == null) { if (isDeveloper) { _linkLocalBridgeName = "cloud-" + instance + "-0"; } else { _linkLocalBridgeName = "cloud0"; } } _publicBridgeName = (String)params.get("public.network.device"); if (_publicBridgeName == null) { _publicBridgeName = "cloudbr0"; } _privBridgeName = (String)params.get("private.network.device"); if (_privBridgeName == null) { _privBridgeName = "cloudbr1"; } _guestBridgeName = (String)params.get("guest.network.device"); if (_guestBridgeName == null) { _guestBridgeName = _privBridgeName; } _privNwName = (String)params.get("private.network.name"); if (_privNwName == null) { if (isDeveloper) { _privNwName = "cloud-" + instance + "-private"; } else { _privNwName = "cloud-private"; } } _localStoragePath = (String)params.get("local.storage.path"); if (_localStoragePath == null) { _localStoragePath = "/var/lib/libvirt/images/"; } /* Directory to use for Qemu sockets like for the Qemu Guest Agent */ _qemuSocketsPath = new File("/var/lib/libvirt/qemu"); String _qemuSocketsPathVar = (String)params.get("qemu.sockets.path"); if (_qemuSocketsPathVar != null && StringUtils.isNotBlank(_qemuSocketsPathVar)) { _qemuSocketsPath = new File(_qemuSocketsPathVar); } final File storagePath = new File(_localStoragePath); _localStoragePath = storagePath.getAbsolutePath(); _localStorageUUID = (String)params.get("local.storage.uuid"); if (_localStorageUUID == null) { _localStorageUUID = UUID.randomUUID().toString(); } value = (String)params.get("scripts.timeout"); _timeout = Duration.standardSeconds(NumbersUtil.parseInt(value, 30 * 60)); value = (String)params.get("stop.script.timeout"); _stopTimeout = NumbersUtil.parseInt(value, 120) * 1000; value = (String)params.get("cmds.timeout"); _cmdsTimeout = NumbersUtil.parseInt(value, 7200) * 1000; value = (String) params.get("vm.memballoon.disable"); if (Boolean.parseBoolean(value)) { _noMemBalloon = true; } _videoHw = (String) params.get("vm.video.hardware"); value = (String) params.get("vm.video.ram"); _videoRam = NumbersUtil.parseInt(value, 0); value = (String)params.get("host.reserved.mem.mb"); // Reserve 1GB unless admin overrides _dom0MinMem = NumbersUtil.parseInt(value, 1024) * 1024* 1024L; value = (String)params.get("host.overcommit.mem.mb"); // Support overcommit memory for host if host uses ZSWAP, KSM and other memory // compressing technologies _dom0OvercommitMem = NumbersUtil.parseInt(value, 0) * 1024 * 1024L; value = (String) params.get("kvmclock.disable"); if (Boolean.parseBoolean(value)) { _noKvmClock = true; } value = (String) params.get("vm.rng.enable"); if (Boolean.parseBoolean(value)) { _rngEnable = true; value = (String) params.get("vm.rng.model"); if (!Strings.isNullOrEmpty(value)) { _rngBackendModel = RngBackendModel.valueOf(value.toUpperCase()); } value = (String) params.get("vm.rng.path"); if (!Strings.isNullOrEmpty(value)) { _rngPath = value; } value = (String) params.get("vm.rng.rate.bytes"); _rngRateBytes = NumbersUtil.parseInt(value, new Integer(_rngRateBytes)); value = (String) params.get("vm.rng.rate.period"); _rngRatePeriod = NumbersUtil.parseInt(value, new Integer(_rngRatePeriod)); } value = (String) params.get("vm.watchdog.model"); if (!Strings.isNullOrEmpty(value)) { _watchDogModel = WatchDogModel.valueOf(value.toUpperCase()); } value = (String) params.get("vm.watchdog.action"); if (!Strings.isNullOrEmpty(value)) { _watchDogAction = WatchDogAction.valueOf(value.toUpperCase()); } LibvirtConnection.initialize(_hypervisorURI); Connect conn = null; try { conn = LibvirtConnection.getConnection(); if (_bridgeType == BridgeType.OPENVSWITCH) { if (conn.getLibVirVersion() < 10 * 1000 + 0) { throw new ConfigurationException("Libvirt version 0.10.0 required for openvswitch support, but version " + conn.getLibVirVersion() + " detected"); } } } catch (final LibvirtException e) { throw new CloudRuntimeException(e.getMessage()); } // destroy default network, see https://libvirt.org/sources/java/javadoc/org/libvirt/Network.html try { Network network = conn.networkLookupByName("default"); s_logger.debug("Found libvirt default network, destroying it and setting autostart to false"); if (network.isActive() == 1) { network.destroy(); } if (network.getAutostart()) { network.setAutostart(false); } } catch (final LibvirtException e) { s_logger.warn("Ignoring libvirt error.", e); } if (HypervisorType.KVM == _hypervisorType) { /* Does node support HVM guest? If not, exit */ if (!IsHVMEnabled(conn)) { throw new ConfigurationException("NO HVM support on this machine, please make sure: " + "1. VT/SVM is supported by your CPU, or is enabled in BIOS. " + "2. kvm modules are loaded (kvm, kvm_amd|kvm_intel)"); } } _hypervisorPath = getHypervisorPath(conn); try { _hvVersion = conn.getVersion(); _hvVersion = _hvVersion % 1000000 / 1000; _hypervisorLibvirtVersion = conn.getLibVirVersion(); _hypervisorQemuVersion = conn.getVersion(); } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } final String cpuArchOverride = (String)params.get("guest.cpu.arch"); if (!Strings.isNullOrEmpty(cpuArchOverride)) { _guestCpuArch = cpuArchOverride; s_logger.info("Using guest CPU architecture: " + _guestCpuArch); } _guestCpuMode = (String)params.get("guest.cpu.mode"); if (_guestCpuMode != null) { _guestCpuModel = (String)params.get("guest.cpu.model"); if (_hypervisorLibvirtVersion < 9 * 1000 + 10) { s_logger.warn("Libvirt version 0.9.10 required for guest cpu mode, but version " + prettyVersion(_hypervisorLibvirtVersion) + " detected, so it will be disabled"); _guestCpuMode = ""; _guestCpuModel = ""; } params.put("guest.cpu.mode", _guestCpuMode); params.put("guest.cpu.model", _guestCpuModel); } final String cpuFeatures = (String)params.get("guest.cpu.features"); if (cpuFeatures != null) { _cpuFeatures = new ArrayList<String>(); for (final String feature: cpuFeatures.split(" ")) { if (!feature.isEmpty()) { _cpuFeatures.add(feature); } } } final String[] info = NetUtils.getNetworkParams(_privateNic); _monitor = new KVMHAMonitor(null, info[0], _heartBeatPath); final Thread ha = new Thread(_monitor); ha.start(); _storagePoolMgr = new KVMStoragePoolManager(_storage, _monitor); _sysvmISOPath = (String)params.get("systemvm.iso.path"); if (_sysvmISOPath == null) { final String[] isoPaths = {"/usr/share/cloudstack-common/vms/systemvm.iso"}; for (final String isoPath : isoPaths) { if (_storage.exists(isoPath)) { _sysvmISOPath = isoPath; break; } } if (_sysvmISOPath == null) { s_logger.debug("Can't find system vm ISO"); } } final Map<String, String> bridges = new HashMap<String, String>(); params.put("libvirt.host.bridges", bridges); params.put("libvirt.host.pifs", _pifs); params.put("libvirt.computing.resource", this); params.put("libvirtVersion", _hypervisorLibvirtVersion); configureVifDrivers(params); /* switch (_bridgeType) { case OPENVSWITCH: getOvsPifs(); break; case NATIVE: default: getPifs(); break; } */ if (_pifs.get("private") == null) { s_logger.error("Failed to get private nic name"); throw new ConfigurationException("Failed to get private nic name"); } if (_pifs.get("public") == null) { s_logger.error("Failed to get public nic name"); throw new ConfigurationException("Failed to get public nic name"); } s_logger.debug("Found pif: " + _pifs.get("private") + " on " + _privBridgeName + ", pif: " + _pifs.get("public") + " on " + _publicBridgeName); _canBridgeFirewall = canBridgeFirewall(_pifs.get("public")); _localGateway = Script.runSimpleBashScript("ip route show default 0.0.0.0/0|head -1|awk '{print $3}'"); if (_localGateway == null) { s_logger.warn("No default IPv4 gateway found"); } _mountPoint = (String)params.get("mount.path"); if (_mountPoint == null) { _mountPoint = "/mnt"; } value = (String) params.get("vm.migrate.downtime"); _migrateDowntime = NumbersUtil.parseInt(value, -1); value = (String) params.get("vm.migrate.pauseafter"); _migratePauseAfter = NumbersUtil.parseInt(value, -1); configureAgentHooks(params); value = (String)params.get("vm.migrate.speed"); _migrateSpeed = NumbersUtil.parseInt(value, -1); if (_migrateSpeed == -1) { //get guest network device speed _migrateSpeed = 0; final String speed = Script.runSimpleBashScript("ethtool " + _pifs.get("public") + " |grep Speed | cut -d \\ -f 2"); if (speed != null) { final String[] tokens = speed.split("M"); if (tokens.length == 2) { try { _migrateSpeed = Integer.parseInt(tokens[0]); } catch (final NumberFormatException e) { s_logger.trace("Ignoring migrateSpeed extraction error.", e); } s_logger.debug("device " + _pifs.get("public") + " has speed: " + String.valueOf(_migrateSpeed)); } } params.put("vm.migrate.speed", String.valueOf(_migrateSpeed)); } bridges.put("linklocal", _linkLocalBridgeName); bridges.put("public", _publicBridgeName); bridges.put("private", _privBridgeName); bridges.put("guest", _guestBridgeName); getVifDriver(TrafficType.Control).createControlNetwork(_linkLocalBridgeName); configureDiskActivityChecks(params); final KVMStorageProcessor storageProcessor = new KVMStorageProcessor(_storagePoolMgr, this); storageProcessor.configure(name, params); storageHandler = new StorageSubsystemCommandHandlerBase(storageProcessor); Boolean _iscsiCleanUpEnabled = Boolean.parseBoolean((String)params.get("iscsi.session.cleanup.enabled")); if (BooleanUtils.isTrue(_iscsiCleanUpEnabled)) { IscsiStorageCleanupMonitor isciCleanupMonitor = new IscsiStorageCleanupMonitor(); final Thread cleanupMonitor = new Thread(isciCleanupMonitor); cleanupMonitor.start(); } else { s_logger.info("iscsi session clean up is disabled"); } return true; } public boolean configureHostParams(final Map<String, String> params) { final File file = PropertiesUtil.findConfigFile("agent.properties"); if (file == null) { s_logger.error("Unable to find the file agent.properties"); return false; } // Save configurations in agent.properties PropertiesStorage storage = new PropertiesStorage(); storage.configure("Storage", new HashMap<String, Object>()); if (params.get("router.aggregation.command.each.timeout") != null) { String value = (String)params.get("router.aggregation.command.each.timeout"); Long longValue = NumbersUtil.parseLong(value, 600); storage.persist("router.aggregation.command.each.timeout", String.valueOf(longValue)); } return true; } private void configureAgentHooks(final Map<String, Object> params) { String value = (String) params.get("agent.hooks.basedir"); if (null != value) { _agentHooksBasedir = value; } s_logger.debug("agent.hooks.basedir is " + _agentHooksBasedir); value = (String) params.get("agent.hooks.libvirt_vm_xml_transformer.script"); if (null != value) { _agentHooksLibvirtXmlScript = value; } s_logger.debug("agent.hooks.libvirt_vm_xml_transformer.script is " + _agentHooksLibvirtXmlScript); value = (String) params.get("agent.hooks.libvirt_vm_xml_transformer.method"); if (null != value) { _agentHooksLibvirtXmlMethod = value; } s_logger.debug("agent.hooks.libvirt_vm_xml_transformer.method is " + _agentHooksLibvirtXmlMethod); value = (String) params.get("agent.hooks.libvirt_vm_on_start.script"); if (null != value) { _agentHooksVmOnStartScript = value; } s_logger.debug("agent.hooks.libvirt_vm_on_start.script is " + _agentHooksVmOnStartScript); value = (String) params.get("agent.hooks.libvirt_vm_on_start.method"); if (null != value) { _agentHooksVmOnStartMethod = value; } s_logger.debug("agent.hooks.libvirt_vm_on_start.method is " + _agentHooksVmOnStartMethod); value = (String) params.get("agent.hooks.libvirt_vm_on_stop.script"); if (null != value) { _agentHooksVmOnStopScript = value; } s_logger.debug("agent.hooks.libvirt_vm_on_stop.script is " + _agentHooksVmOnStopScript); value = (String) params.get("agent.hooks.libvirt_vm_on_stop.method"); if (null != value) { _agentHooksVmOnStopMethod = value; } s_logger.debug("agent.hooks.libvirt_vm_on_stop.method is " + _agentHooksVmOnStopMethod); } private void loadUefiProperties() throws FileNotFoundException { if (_uefiProperties != null && _uefiProperties.getProperty("guest.loader.legacy") != null) { return; } final File file = PropertiesUtil.findConfigFile("uefi.properties"); if (file == null) { throw new FileNotFoundException("Unable to find file uefi.properties."); } s_logger.info("uefi.properties file found at " + file.getAbsolutePath()); try { PropertiesUtil.loadFromFile(_uefiProperties, file); s_logger.info("guest.nvram.template.legacy = " + _uefiProperties.getProperty("guest.nvram.template.legacy")); s_logger.info("guest.loader.legacy = " + _uefiProperties.getProperty("guest.loader.legacy")); s_logger.info("guest.nvram.template.secure = " + _uefiProperties.getProperty("guest.nvram.template.secure")); s_logger.info("guest.loader.secure =" + _uefiProperties.getProperty("guest.loader.secure")); s_logger.info("guest.nvram.path = " + _uefiProperties.getProperty("guest.nvram.path")); } catch (final FileNotFoundException ex) { throw new CloudRuntimeException("Cannot find the file: " + file.getAbsolutePath(), ex); } catch (final IOException ex) { throw new CloudRuntimeException("IOException in reading " + file.getAbsolutePath(), ex); } } protected void configureDiskActivityChecks(final Map<String, Object> params) { _diskActivityCheckEnabled = Boolean.parseBoolean((String)params.get("vm.diskactivity.checkenabled")); if (_diskActivityCheckEnabled) { final int timeout = NumbersUtil.parseInt((String)params.get("vm.diskactivity.checktimeout_s"), 0); if (timeout > 0) { _diskActivityCheckTimeoutSeconds = timeout; } final long inactiveTime = NumbersUtil.parseLong((String)params.get("vm.diskactivity.inactivetime_ms"), 0L); if (inactiveTime > 0) { _diskActivityInactiveThresholdMilliseconds = inactiveTime; } } } protected void configureVifDrivers(final Map<String, Object> params) throws ConfigurationException { final String LIBVIRT_VIF_DRIVER = "libvirt.vif.driver"; _trafficTypeVifDrivers = new HashMap<TrafficType, VifDriver>(); // Load the default vif driver String defaultVifDriverName = (String)params.get(LIBVIRT_VIF_DRIVER); if (defaultVifDriverName == null) { if (_bridgeType == BridgeType.OPENVSWITCH) { s_logger.info("No libvirt.vif.driver specified. Defaults to OvsVifDriver."); defaultVifDriverName = DEFAULT_OVS_VIF_DRIVER_CLASS_NAME; } else { s_logger.info("No libvirt.vif.driver specified. Defaults to BridgeVifDriver."); defaultVifDriverName = DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME; } } _defaultVifDriver = getVifDriverClass(defaultVifDriverName, params); // Load any per-traffic-type vif drivers for (final Map.Entry<String, Object> entry : params.entrySet()) { final String k = entry.getKey(); final String vifDriverPrefix = LIBVIRT_VIF_DRIVER + "."; if (k.startsWith(vifDriverPrefix)) { // Get trafficType final String trafficTypeSuffix = k.substring(vifDriverPrefix.length()); // Does this suffix match a real traffic type? final TrafficType trafficType = TrafficType.getTrafficType(trafficTypeSuffix); if (!trafficType.equals(TrafficType.None)) { // Get vif driver class name final String vifDriverClassName = (String)entry.getValue(); // if value is null, ignore if (vifDriverClassName != null) { // add traffic type to vif driver mapping to Map _trafficTypeVifDrivers.put(trafficType, getVifDriverClass(vifDriverClassName, params)); } } } } } protected VifDriver getVifDriverClass(final String vifDriverClassName, final Map<String, Object> params) throws ConfigurationException { VifDriver vifDriver; try { final Class<?> clazz = Class.forName(vifDriverClassName); vifDriver = (VifDriver)clazz.newInstance(); vifDriver.configure(params); } catch (final ClassNotFoundException e) { throw new ConfigurationException("Unable to find class for libvirt.vif.driver " + e); } catch (final InstantiationException e) { throw new ConfigurationException("Unable to instantiate class for libvirt.vif.driver " + e); } catch (final IllegalAccessException e) { throw new ConfigurationException("Unable to instantiate class for libvirt.vif.driver " + e); } return vifDriver; } public VifDriver getVifDriver(final TrafficType trafficType) { VifDriver vifDriver = _trafficTypeVifDrivers.get(trafficType); if (vifDriver == null) { vifDriver = _defaultVifDriver; } return vifDriver; } public VifDriver getVifDriver(final TrafficType trafficType, final String bridgeName) { VifDriver vifDriver = null; for (VifDriver driver : getAllVifDrivers()) { if (driver.isExistingBridge(bridgeName)) { vifDriver = driver; break; } } if (vifDriver == null) { vifDriver = getVifDriver(trafficType); } return vifDriver; } public List<VifDriver> getAllVifDrivers() { final Set<VifDriver> vifDrivers = new HashSet<VifDriver>(); vifDrivers.add(_defaultVifDriver); vifDrivers.addAll(_trafficTypeVifDrivers.values()); final ArrayList<VifDriver> vifDriverList = new ArrayList<VifDriver>(vifDrivers); return vifDriverList; } private void getPifs() { final File dir = new File("/sys/devices/virtual/net"); final File[] netdevs = dir.listFiles(); final List<String> bridges = new ArrayList<String>(); for (int i = 0; i < netdevs.length; i++) { final File isbridge = new File(netdevs[i].getAbsolutePath() + "/bridge"); final String netdevName = netdevs[i].getName(); s_logger.debug("looking in file " + netdevs[i].getAbsolutePath() + "/bridge"); if (isbridge.exists()) { s_logger.debug("Found bridge " + netdevName); bridges.add(netdevName); } } for (final String bridge : bridges) { s_logger.debug("looking for pif for bridge " + bridge); final String pif = getPif(bridge); if (isPublicBridge(bridge)) { _pifs.put("public", pif); } if (isGuestBridge(bridge)) { _pifs.put("private", pif); } _pifs.put(bridge, pif); } // guest(private) creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("private") == null) { s_logger.debug("guest(private) traffic label '" + _guestBridgeName + "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + _guestBridgeName); if (dev.exists()) { s_logger.debug("guest(private) traffic label '" + _guestBridgeName + "' found as a physical device"); _pifs.put("private", _guestBridgeName); } } // public creates bridges on a pif, if private bridge not found try pif direct // This addresses the unnecessary requirement of someone to create an unused bridge just for traffic label if (_pifs.get("public") == null) { s_logger.debug("public traffic label '" + _publicBridgeName+ "' not found as bridge, looking for physical interface"); final File dev = new File("/sys/class/net/" + _publicBridgeName); if (dev.exists()) { s_logger.debug("public traffic label '" + _publicBridgeName + "' found as a physical device"); _pifs.put("public", _publicBridgeName); } } s_logger.debug("done looking for pifs, no more bridges"); } boolean isGuestBridge(String bridge) { return _guestBridgeName != null && bridge.equals(_guestBridgeName); } private void getOvsPifs() { final String cmdout = Script.runSimpleBashScript("ovs-vsctl list-br | sed '{:q;N;s/\\n/%/g;t q}'"); s_logger.debug("cmdout was " + cmdout); final List<String> bridges = Arrays.asList(cmdout.split("%")); for (final String bridge : bridges) { s_logger.debug("looking for pif for bridge " + bridge); // String pif = getOvsPif(bridge); // Not really interested in the pif name at this point for ovs // bridges final String pif = bridge; if (isPublicBridge(bridge)) { _pifs.put("public", pif); } if (isGuestBridge(bridge)) { _pifs.put("private", pif); } _pifs.put(bridge, pif); } s_logger.debug("done looking for pifs, no more bridges"); } public boolean isPublicBridge(String bridge) { return _publicBridgeName != null && bridge.equals(_publicBridgeName); } private String getPif(final String bridge) { String pif = matchPifFileInDirectory(bridge); final File vlanfile = new File("/proc/net/vlan/" + pif); if (vlanfile.isFile()) { pif = Script.runSimpleBashScript("grep ^Device\\: /proc/net/vlan/" + pif + " | awk {'print $2'}"); } return pif; } private String matchPifFileInDirectory(final String bridgeName) { final File brif = new File("/sys/devices/virtual/net/" + bridgeName + "/brif"); if (!brif.isDirectory()) { final File pif = new File("/sys/class/net/" + bridgeName); if (pif.isDirectory()) { // if bridgeName already refers to a pif, return it as-is return bridgeName; } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", does " + brif.getAbsolutePath() + "exist?"); return ""; } final File[] interfaces = brif.listFiles(); for (int i = 0; i < interfaces.length; i++) { final String fname = interfaces[i].getName(); s_logger.debug("matchPifFileInDirectory: file name '" + fname + "'"); if (isInterface(fname)) { return fname; } } s_logger.debug("failing to get physical interface from bridge " + bridgeName + ", did not find an eth*, bond*, team*, vlan*, em*, p*p*, ens*, eno*, enp*, or enx* in " + brif.getAbsolutePath()); return ""; } static String [] ifNamePatterns = { "^eth", "^bond", "^vlan", "^vx", "^em", "^ens", "^eno", "^enp", "^team", "^enx", "^dummy", "^lo", "^p\\d+p\\d+" }; /** * @param fname * @return */ protected static boolean isInterface(final String fname) { StringBuffer commonPattern = new StringBuffer(); for (final String ifNamePattern : ifNamePatterns) { commonPattern.append("|(").append(ifNamePattern).append(".*)"); } if(fname.matches(commonPattern.toString())) { return true; } return false; } public boolean checkNetwork(final TrafficType trafficType, final String networkName) { if (networkName == null) { return true; } if (getVifDriver(trafficType, networkName) instanceof OvsVifDriver) { return checkOvsNetwork(networkName); } else { return checkBridgeNetwork(networkName); } } private boolean checkBridgeNetwork(final String networkName) { if (networkName == null) { return true; } final String name = matchPifFileInDirectory(networkName); if (name == null || name.isEmpty()) { return false; } else { return true; } } private boolean checkOvsNetwork(final String networkName) { s_logger.debug("Checking if network " + networkName + " exists as openvswitch bridge"); if (networkName == null) { return true; } final Script command = new Script("/bin/sh", _timeout); command.add("-c"); command.add("ovs-vsctl br-exists " + networkName); return "0".equals(command.execute(null)); } public boolean passCmdLine(final String vmName, final String cmdLine) throws InternalErrorException { final Script command = new Script(_patchScriptPath, 300 * 1000, s_logger); String result; command.add("-n", vmName); command.add("-c", cmdLine); result = command.execute(); if (result != null) { s_logger.error("Passing cmdline failed:" + result); return false; } return true; } boolean isDirectAttachedNetwork(final String type) { if ("untagged".equalsIgnoreCase(type)) { return true; } else { try { Long.valueOf(type); } catch (final NumberFormatException e) { return true; } return false; } } public String startVM(final Connect conn, final String vmName, final String domainXML) throws LibvirtException, InternalErrorException { try { /* We create a transient domain here. When this method gets called we receive a full XML specification of the guest, so no need to define it persistent. This also makes sure we never have any old "garbage" defined in libvirt which might haunt us. */ // check for existing inactive vm definition and remove it // this can sometimes happen during crashes, etc Domain dm = null; try { dm = conn.domainLookupByName(vmName); if (dm != null && dm.isPersistent() == 1) { // this is safe because it doesn't stop running VMs dm.undefine(); } } catch (final LibvirtException e) { // this is what we want, no domain found } finally { if (dm != null) { dm.free(); } } conn.domainCreateXML(domainXML, 0); } catch (final LibvirtException e) { throw e; } return null; } @Override public boolean stop() { try { final Connect conn = LibvirtConnection.getConnection(); conn.close(); } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } return true; } /** * This finds a command wrapper to handle the command and executes it. * If no wrapper is found an {@see UnsupportedAnswer} is sent back. * Any other exceptions are to be caught and wrapped in an generic {@see Answer}, marked as failed. * * @param cmd the instance of a {@see Command} to execute. * @return the for the {@see Command} appropriate {@see Answer} or {@see UnsupportedAnswer} */ @Override public Answer executeRequest(final Command cmd) { final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance(); try { return wrapper.execute(cmd, this); } catch (final RequestWrapper.CommandNotSupported cmde) { return Answer.createUnsupportedCommandAnswer(cmd); } } public synchronized boolean destroyTunnelNetwork(final String bridge) { findOrCreateTunnelNetwork(bridge); final Script cmd = new Script(_ovsTunnelPath, _timeout, s_logger); cmd.add("destroy_ovs_bridge"); cmd.add("--bridge", bridge); final String result = cmd.execute(); if (result != null) { s_logger.debug("OVS Bridge could not be destroyed due to error ==> " + result); return false; } return true; } public synchronized boolean findOrCreateTunnelNetwork(final String nwName) { try { if (checkNetwork(TrafficType.Guest, nwName)) { return true; } // if not found, create a new one final Map<String, String> otherConfig = new HashMap<String, String>(); otherConfig.put("ovs-host-setup", ""); Script.runSimpleBashScript("ovs-vsctl -- --may-exist add-br " + nwName + " -- set bridge " + nwName + " other_config:ovs-host-setup='-1'"); s_logger.debug("### KVM network for tunnels created:" + nwName); } catch (final Exception e) { s_logger.warn("createTunnelNetwork failed", e); return false; } return true; } public synchronized boolean configureTunnelNetwork(final long networkId, final long hostId, final String nwName) { try { final boolean findResult = findOrCreateTunnelNetwork(nwName); if (!findResult) { s_logger.warn("LibvirtComputingResource.findOrCreateTunnelNetwork() failed! Cannot proceed creating the tunnel."); return false; } final String configuredHosts = Script .runSimpleBashScript("ovs-vsctl get bridge " + nwName + " other_config:ovs-host-setup"); boolean configured = false; if (configuredHosts != null) { final String hostIdsStr[] = configuredHosts.split(","); for (final String hostIdStr : hostIdsStr) { if (hostIdStr.equals(((Long)hostId).toString())) { configured = true; break; } } } if (!configured) { final Script cmd = new Script(_ovsTunnelPath, _timeout, s_logger); cmd.add("setup_ovs_bridge"); cmd.add("--key", nwName); cmd.add("--cs_host_id", ((Long)hostId).toString()); cmd.add("--bridge", nwName); final String result = cmd.execute(); if (result != null) { throw new CloudRuntimeException( "Unable to pre-configure OVS bridge " + nwName + " for network ID:" + networkId); } } } catch (final Exception e) { s_logger.warn("createandConfigureTunnelNetwork failed", e); return false; } return true; } protected Storage.StorageResourceType getStorageResourceType() { return Storage.StorageResourceType.STORAGE_POOL; } // this is much like PrimaryStorageDownloadCommand, but keeping it separate public KVMPhysicalDisk templateToPrimaryDownload(final String templateUrl, final KVMStoragePool primaryPool, final String volUuid) { final int index = templateUrl.lastIndexOf("/"); final String mountpoint = templateUrl.substring(0, index); String templateName = null; if (index < templateUrl.length() - 1) { templateName = templateUrl.substring(index + 1); } KVMPhysicalDisk templateVol = null; KVMStoragePool secondaryPool = null; try { secondaryPool = _storagePoolMgr.getStoragePoolByURI(mountpoint); /* Get template vol */ if (templateName == null) { secondaryPool.refresh(); final List<KVMPhysicalDisk> disks = secondaryPool.listPhysicalDisks(); if (disks == null || disks.isEmpty()) { s_logger.error("Failed to get volumes from pool: " + secondaryPool.getUuid()); return null; } for (final KVMPhysicalDisk disk : disks) { if (disk.getName().endsWith("qcow2")) { templateVol = disk; break; } } if (templateVol == null) { s_logger.error("Failed to get template from pool: " + secondaryPool.getUuid()); return null; } } else { templateVol = secondaryPool.getPhysicalDisk(templateName); } /* Copy volume to primary storage */ final KVMPhysicalDisk primaryVol = _storagePoolMgr.copyPhysicalDisk(templateVol, volUuid, primaryPool, 0); return primaryVol; } catch (final CloudRuntimeException e) { s_logger.error("Failed to download template to primary storage", e); return null; } finally { if (secondaryPool != null) { _storagePoolMgr.deleteStoragePool(secondaryPool.getType(), secondaryPool.getUuid()); } } } public String getResizeScriptType(final KVMStoragePool pool, final KVMPhysicalDisk vol) { final StoragePoolType poolType = pool.getType(); final PhysicalDiskFormat volFormat = vol.getFormat(); if (pool.getType() == StoragePoolType.CLVM && volFormat == PhysicalDiskFormat.RAW) { return "CLVM"; } else if ((poolType == StoragePoolType.NetworkFilesystem || poolType == StoragePoolType.SharedMountPoint || poolType == StoragePoolType.Filesystem || poolType == StoragePoolType.Gluster) && volFormat == PhysicalDiskFormat.QCOW2 ) { return "QCOW2"; } throw new CloudRuntimeException("Cannot determine resize type from pool type " + pool.getType()); } private String getBroadcastUriFromBridge(final String brName) { final String pif = matchPifFileInDirectory(brName); final Pattern pattern = Pattern.compile("(\\D+)(\\d+)(\\D*)(\\d*)(\\D*)(\\d*)"); final Matcher matcher = pattern.matcher(pif); s_logger.debug("getting broadcast uri for pif " + pif + " and bridge " + brName); if(matcher.find()) { if (brName.startsWith("brvx")){ return BroadcastDomainType.Vxlan.toUri(matcher.group(2)).toString(); } else{ if (!matcher.group(6).isEmpty()) { return BroadcastDomainType.Vlan.toUri(matcher.group(6)).toString(); } else if (!matcher.group(4).isEmpty()) { return BroadcastDomainType.Vlan.toUri(matcher.group(4)).toString(); } else { //untagged or not matching (eth|bond|team)#.# s_logger.debug("failed to get vNet id from bridge " + brName + "attached to physical interface" + pif + ", perhaps untagged interface"); return ""; } } } else { s_logger.debug("failed to get vNet id from bridge " + brName + "attached to physical interface" + pif); return ""; } } private void VifHotPlug(final Connect conn, final String vmName, final String broadcastUri, final String macAddr) throws InternalErrorException, LibvirtException { final NicTO nicTO = new NicTO(); nicTO.setMac(macAddr); nicTO.setType(TrafficType.Public); if (broadcastUri == null) { nicTO.setBroadcastType(BroadcastDomainType.Native); } else { final URI uri = BroadcastDomainType.fromString(broadcastUri); nicTO.setBroadcastType(BroadcastDomainType.getSchemeValue(uri)); nicTO.setBroadcastUri(uri); } final Domain vm = getDomain(conn, vmName); vm.attachDevice(getVifDriver(nicTO.getType()).plug(nicTO, "Other PV", "", null).toString()); } private void vifHotUnPlug (final Connect conn, final String vmName, final String macAddr) throws InternalErrorException, LibvirtException { Domain vm = null; vm = getDomain(conn, vmName); final List<InterfaceDef> pluggedNics = getInterfaces(conn, vmName); for (final InterfaceDef pluggedNic : pluggedNics) { if (pluggedNic.getMacAddress().equalsIgnoreCase(macAddr)) { vm.detachDevice(pluggedNic.toString()); // We don't know which "traffic type" is associated with // each interface at this point, so inform all vif drivers for (final VifDriver vifDriver : getAllVifDrivers()) { vifDriver.unplug(pluggedNic); } } } } private ExecutionResult prepareNetworkElementCommand(final SetupGuestNetworkCommand cmd) { Connect conn; final NicTO nic = cmd.getNic(); final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); try { conn = LibvirtConnection.getConnectionByVmName(routerName); final List<InterfaceDef> pluggedNics = getInterfaces(conn, routerName); InterfaceDef routerNic = null; for (final InterfaceDef pluggedNic : pluggedNics) { if (pluggedNic.getMacAddress().equalsIgnoreCase(nic.getMac())) { routerNic = pluggedNic; break; } } if (routerNic == null) { return new ExecutionResult(false, "Can not find nic with mac " + nic.getMac() + " for VM " + routerName); } return new ExecutionResult(true, null); } catch (final LibvirtException e) { final String msg = "Creating guest network failed due to " + e.toString(); s_logger.warn(msg, e); return new ExecutionResult(false, msg); } } protected ExecutionResult prepareNetworkElementCommand(final SetSourceNatCommand cmd) { Connect conn; final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); final IpAddressTO pubIP = cmd.getIpAddress(); try { conn = LibvirtConnection.getConnectionByVmName(routerName); Integer devNum = 0; final String pubVlan = pubIP.getBroadcastUri(); final List<InterfaceDef> pluggedNics = getInterfaces(conn, routerName); for (final InterfaceDef pluggedNic : pluggedNics) { final String pluggedVlanBr = pluggedNic.getBrName(); final String pluggedVlanId = getBroadcastUriFromBridge(pluggedVlanBr); if (pubVlan.equalsIgnoreCase(Vlan.UNTAGGED) && pluggedVlanBr.equalsIgnoreCase(_publicBridgeName)) { break; } else if (pluggedVlanBr.equalsIgnoreCase(_linkLocalBridgeName)) { /*skip over, no physical bridge device exists*/ } else if (pluggedVlanId == null) { /*this should only be true in the case of link local bridge*/ return new ExecutionResult(false, "unable to find the vlan id for bridge " + pluggedVlanBr + " when attempting to set up" + pubVlan + " on router " + routerName); } else if (pluggedVlanId.equals(pubVlan)) { break; } devNum++; } pubIP.setNicDevId(devNum); return new ExecutionResult(true, "success"); } catch (final LibvirtException e) { final String msg = "Ip SNAT failure due to " + e.toString(); s_logger.error(msg, e); return new ExecutionResult(false, msg); } } protected ExecutionResult prepareNetworkElementCommand(final IpAssocVpcCommand cmd) { Connect conn; final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); try { conn = getLibvirtUtilitiesHelper().getConnectionByVmName(routerName); Pair<Map<String, Integer>, Integer> macAddressToNicNumPair = getMacAddressToNicNumPair(conn, routerName); final Map<String, Integer> macAddressToNicNum = macAddressToNicNumPair.first(); Integer devNum = macAddressToNicNumPair.second(); final IpAddressTO[] ips = cmd.getIpAddresses(); for (final IpAddressTO ip : ips) { ip.setNicDevId(macAddressToNicNum.get(ip.getVifMacAddress())); } return new ExecutionResult(true, null); } catch (final LibvirtException e) { s_logger.error("Ip Assoc failure on applying one ip due to exception: ", e); return new ExecutionResult(false, e.getMessage()); } } public ExecutionResult prepareNetworkElementCommand(final IpAssocCommand cmd) { final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); final String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); Connect conn; try { conn = getLibvirtUtilitiesHelper().getConnectionByVmName(routerName); Pair<Map<String, Integer>, Integer> macAddressToNicNumPair = getMacAddressToNicNumPair(conn, routerName); final Map<String, Integer> macAddressToNicNum = macAddressToNicNumPair.first(); Integer devNum = macAddressToNicNumPair.second(); final IpAddressTO[] ips = cmd.getIpAddresses(); int nicNum = 0; for (final IpAddressTO ip : ips) { boolean newNic = false; if (!macAddressToNicNum.containsKey(ip.getVifMacAddress())) { /* plug a vif into router */ VifHotPlug(conn, routerName, ip.getBroadcastUri(), ip.getVifMacAddress()); macAddressToNicNum.put(ip.getVifMacAddress(), devNum++); newNic = true; } nicNum = macAddressToNicNum.get(ip.getVifMacAddress()); networkUsage(routerIp, "addVif", "eth" + nicNum); ip.setNicDevId(nicNum); ip.setNewNic(newNic); } return new ExecutionResult(true, null); } catch (final LibvirtException e) { s_logger.error("ipassoccmd failed", e); return new ExecutionResult(false, e.getMessage()); } catch (final InternalErrorException e) { s_logger.error("ipassoccmd failed", e); return new ExecutionResult(false, e.getMessage()); } } protected ExecutionResult cleanupNetworkElementCommand(final IpAssocCommand cmd) { final String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); final String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); final String lastIp = cmd.getAccessDetail(NetworkElementCommand.NETWORK_PUB_LAST_IP); Connect conn; try { conn = getLibvirtUtilitiesHelper().getConnectionByVmName(routerName); Pair<Map<String, Integer>, Integer> macAddressToNicNumPair = getMacAddressToNicNumPair(conn, routerName); final Map<String, Integer> macAddressToNicNum = macAddressToNicNumPair.first(); Integer devNum = macAddressToNicNumPair.second(); final IpAddressTO[] ips = cmd.getIpAddresses(); int nicNum = 0; for (final IpAddressTO ip : ips) { if (!macAddressToNicNum.containsKey(ip.getVifMacAddress())) { /* plug a vif into router */ VifHotPlug(conn, routerName, ip.getBroadcastUri(), ip.getVifMacAddress()); macAddressToNicNum.put(ip.getVifMacAddress(), devNum++); } nicNum = macAddressToNicNum.get(ip.getVifMacAddress()); if (org.apache.commons.lang.StringUtils.equalsIgnoreCase(lastIp, "true") && !ip.isAdd()) { // in isolated network eth2 is the default public interface. We don't want to delete it. if (nicNum != 2) { vifHotUnPlug(conn, routerName, ip.getVifMacAddress()); networkUsage(routerIp, "deleteVif", "eth" + nicNum); } } } } catch (final LibvirtException e) { s_logger.error("ipassoccmd failed", e); return new ExecutionResult(false, e.getMessage()); } catch (final InternalErrorException e) { s_logger.error("ipassoccmd failed", e); return new ExecutionResult(false, e.getMessage()); } return new ExecutionResult(true, null); } private Pair<Map<String, Integer>, Integer> getMacAddressToNicNumPair(Connect conn, String routerName) { Integer devNum = 0; final List<InterfaceDef> pluggedNics = getInterfaces(conn, routerName); final Map<String, Integer> macAddressToNicNum = new HashMap<>(pluggedNics.size()); for (final InterfaceDef pluggedNic : pluggedNics) { final String pluggedVlan = pluggedNic.getBrName(); macAddressToNicNum.put(pluggedNic.getMacAddress(), devNum); devNum++; } return new Pair<Map<String, Integer>, Integer>(macAddressToNicNum, devNum); } protected PowerState convertToPowerState(final DomainState ps) { final PowerState state = s_powerStatesTable.get(ps); return state == null ? PowerState.PowerUnknown : state; } public PowerState getVmState(final Connect conn, final String vmName) { int retry = 3; Domain vms = null; while (retry-- > 0) { try { vms = conn.domainLookupByName(vmName); final PowerState s = convertToPowerState(vms.getInfo().state); return s; } catch (final LibvirtException e) { s_logger.warn("Can't get vm state " + vmName + e.getMessage() + "retry:" + retry); } finally { try { if (vms != null) { vms.free(); } } catch (final LibvirtException l) { s_logger.trace("Ignoring libvirt error.", l); } } } return PowerState.PowerOff; } public String networkUsage(final String privateIpAddress, final String option, final String vif) { final Script getUsage = new Script(_routerProxyPath, s_logger); getUsage.add("netusage.sh"); getUsage.add(privateIpAddress); if (option.equals("get")) { getUsage.add("-g"); } else if (option.equals("create")) { getUsage.add("-c"); } else if (option.equals("reset")) { getUsage.add("-r"); } else if (option.equals("addVif")) { getUsage.add("-a", vif); } else if (option.equals("deleteVif")) { getUsage.add("-d", vif); } final OutputInterpreter.OneLineParser usageParser = new OutputInterpreter.OneLineParser(); final String result = getUsage.execute(usageParser); if (result != null) { s_logger.debug("Failed to execute networkUsage:" + result); return null; } return usageParser.getLine(); } public long[] getNetworkStats(final String privateIP) { final String result = networkUsage(privateIP, "get", null); final long[] stats = new long[2]; if (result != null) { final String[] splitResult = result.split(":"); int i = 0; while (i < splitResult.length - 1) { stats[0] += Long.parseLong(splitResult[i++]); stats[1] += Long.parseLong(splitResult[i++]); } } return stats; } public String configureVPCNetworkUsage(final String privateIpAddress, final String publicIp, final String option, final String vpcCIDR) { final Script getUsage = new Script(_routerProxyPath, s_logger); getUsage.add("vpc_netusage.sh"); getUsage.add(privateIpAddress); getUsage.add("-l", publicIp); if (option.equals("get")) { getUsage.add("-g"); } else if (option.equals("create")) { getUsage.add("-c"); getUsage.add("-v", vpcCIDR); } else if (option.equals("reset")) { getUsage.add("-r"); } else if (option.equals("vpn")) { getUsage.add("-n"); } else if (option.equals("remove")) { getUsage.add("-d"); } final OutputInterpreter.OneLineParser usageParser = new OutputInterpreter.OneLineParser(); final String result = getUsage.execute(usageParser); if (result != null) { s_logger.debug("Failed to execute VPCNetworkUsage:" + result); return null; } return usageParser.getLine(); } public long[] getVPCNetworkStats(final String privateIP, final String publicIp, final String option) { final String result = configureVPCNetworkUsage(privateIP, publicIp, option, null); final long[] stats = new long[2]; if (result != null) { final String[] splitResult = result.split(":"); int i = 0; while (i < splitResult.length - 1) { stats[0] += Long.parseLong(splitResult[i++]); stats[1] += Long.parseLong(splitResult[i++]); } } return stats; } public void handleVmStartFailure(final Connect conn, final String vmName, final LibvirtVMDef vm) { if (vm != null && vm.getDevices() != null) { cleanupVMNetworks(conn, vm.getDevices().getInterfaces()); } } protected String getUuid(String uuid) { if (uuid == null) { uuid = UUID.randomUUID().toString(); } else { try { final UUID uuid2 = UUID.fromString(uuid); final String uuid3 = uuid2.toString(); if (!uuid3.equals(uuid)) { uuid = UUID.randomUUID().toString(); } } catch (final IllegalArgumentException e) { uuid = UUID.randomUUID().toString(); } } return uuid; } /** * Set quota and period tags on 'ctd' when CPU limit use is set */ protected void setQuotaAndPeriod(VirtualMachineTO vmTO, CpuTuneDef ctd) { if (vmTO.getLimitCpuUse() && vmTO.getCpuQuotaPercentage() != null) { Double cpuQuotaPercentage = vmTO.getCpuQuotaPercentage(); int period = CpuTuneDef.DEFAULT_PERIOD; int quota = (int) (period * cpuQuotaPercentage); if (quota < CpuTuneDef.MIN_QUOTA) { s_logger.info("Calculated quota (" + quota + ") below the minimum (" + CpuTuneDef.MIN_QUOTA + ") for VM domain " + vmTO.getUuid() + ", setting it to minimum " + "and calculating period instead of using the default"); quota = CpuTuneDef.MIN_QUOTA; period = (int) ((double) quota / cpuQuotaPercentage); if (period > CpuTuneDef.MAX_PERIOD) { s_logger.info("Calculated period (" + period + ") exceeds the maximum (" + CpuTuneDef.MAX_PERIOD + "), setting it to the maximum"); period = CpuTuneDef.MAX_PERIOD; } } ctd.setQuota(quota); ctd.setPeriod(period); s_logger.info("Setting quota=" + quota + ", period=" + period + " to VM domain " + vmTO.getUuid()); } } protected void enlightenWindowsVm(VirtualMachineTO vmTO, FeaturesDef features) { if (vmTO.getOs().contains("Windows PV")) { // If OS is Windows PV, then enable the features. Features supported on Windows 2008 and later LibvirtVMDef.HyperVEnlightenmentFeatureDef hyv = new LibvirtVMDef.HyperVEnlightenmentFeatureDef(); hyv.setFeature("relaxed", true); hyv.setFeature("vapic", true); hyv.setFeature("spinlocks", true); hyv.setRetries(8096); features.addHyperVFeature(hyv); s_logger.info("Enabling KVM Enlightment Features to VM domain " + vmTO.getUuid()); } } public LibvirtVMDef createVMFromSpec(final VirtualMachineTO vmTO) { final LibvirtVMDef vm = new LibvirtVMDef(); vm.setDomainName(vmTO.getName()); String uuid = vmTO.getUuid(); uuid = getUuid(uuid); vm.setDomUUID(uuid); vm.setDomDescription(vmTO.getOs()); vm.setPlatformEmulator(vmTO.getPlatformEmulator()); Map<String, String> customParams = vmTO.getDetails(); boolean isUefiEnabled = false; boolean isSecureBoot = false; String bootMode =null; if (MapUtils.isNotEmpty(customParams) && customParams.containsKey(GuestDef.BootType.UEFI.toString())) { isUefiEnabled = true; bootMode = customParams.get(GuestDef.BootType.UEFI.toString()); if (StringUtils.isNotBlank(bootMode) && "secure".equalsIgnoreCase(bootMode)) { isSecureBoot = true; } } Map<String, String> extraConfig = vmTO.getExtraConfig(); if (dpdkSupport && (!extraConfig.containsKey(DpdkHelper.DPDK_NUMA) || !extraConfig.containsKey(DpdkHelper.DPDK_HUGE_PAGES))) { s_logger.info("DPDK is enabled but it needs extra configurations for CPU NUMA and Huge Pages for VM deployment"); } final GuestDef guest = new GuestDef(); if (HypervisorType.LXC == _hypervisorType && VirtualMachine.Type.User == vmTO.getType()) { // LXC domain is only valid for user VMs. Use KVM for system VMs. guest.setGuestType(GuestDef.GuestType.LXC); vm.setHvsType(HypervisorType.LXC.toString().toLowerCase()); } else { guest.setGuestType(GuestDef.GuestType.KVM); vm.setHvsType(HypervisorType.KVM.toString().toLowerCase()); vm.setLibvirtVersion(_hypervisorLibvirtVersion); vm.setQemuVersion(_hypervisorQemuVersion); } guest.setGuestArch(_guestCpuArch != null ? _guestCpuArch : vmTO.getArch()); guest.setMachineType(_guestCpuArch != null && _guestCpuArch.equals("aarch64") ? "virt" : "pc"); guest.setBootType(GuestDef.BootType.BIOS); if (MapUtils.isNotEmpty(customParams) && customParams.containsKey(GuestDef.BootType.UEFI.toString())) { guest.setBootType(GuestDef.BootType.UEFI); guest.setBootMode(GuestDef.BootMode.LEGACY); if (StringUtils.isNotBlank(customParams.get(GuestDef.BootType.UEFI.toString())) && "secure".equalsIgnoreCase(customParams.get(GuestDef.BootType.UEFI.toString()))) { guest.setMachineType("q35"); guest.setBootMode(GuestDef.BootMode.SECURE); // setting to secure mode } } guest.setUuid(uuid); guest.setBootOrder(GuestDef.BootOrder.CDROM); guest.setBootOrder(GuestDef.BootOrder.HARDISK); if (isUefiEnabled) { if (_uefiProperties.getProperty(GuestDef.GUEST_LOADER_SECURE) != null && "secure".equalsIgnoreCase(bootMode)) { guest.setLoader(_uefiProperties.getProperty(GuestDef.GUEST_LOADER_SECURE)); } if (_uefiProperties.getProperty(GuestDef.GUEST_LOADER_LEGACY) != null && "legacy".equalsIgnoreCase(bootMode)) { guest.setLoader(_uefiProperties.getProperty(GuestDef.GUEST_LOADER_LEGACY)); } if (_uefiProperties.getProperty(GuestDef.GUEST_NVRAM_PATH) != null) { guest.setNvram(_uefiProperties.getProperty(GuestDef.GUEST_NVRAM_PATH)); } if (isSecureBoot) { if (_uefiProperties.getProperty(GuestDef.GUEST_NVRAM_TEMPLATE_SECURE) != null && "secure".equalsIgnoreCase(bootMode)) { guest.setNvramTemplate(_uefiProperties.getProperty(GuestDef.GUEST_NVRAM_TEMPLATE_SECURE)); } } else { if (_uefiProperties.getProperty(GuestDef.GUEST_NVRAM_TEMPLATE_LEGACY) != null) { guest.setNvramTemplate(_uefiProperties.getProperty(GuestDef.GUEST_NVRAM_TEMPLATE_LEGACY)); } } } vm.addComp(guest); final GuestResourceDef grd = new GuestResourceDef(); if (vmTO.getMinRam() != vmTO.getMaxRam() && !_noMemBalloon) { grd.setMemBalloning(true); grd.setCurrentMem(vmTO.getMinRam() / 1024); grd.setMemorySize(vmTO.getMaxRam() / 1024); } else { grd.setMemorySize(vmTO.getMaxRam() / 1024); } final int vcpus = vmTO.getCpus(); grd.setVcpuNum(vcpus); vm.addComp(grd); if (!extraConfig.containsKey(DpdkHelper.DPDK_NUMA)) { final CpuModeDef cmd = new CpuModeDef(); cmd.setMode(_guestCpuMode); cmd.setModel(_guestCpuModel); if (vmTO.getType() == VirtualMachine.Type.User) { cmd.setFeatures(_cpuFeatures); } // multi cores per socket, for larger core configs if (vcpus % 6 == 0) { final int sockets = vcpus / 6; cmd.setTopology(6, sockets); } else if (vcpus % 4 == 0) { final int sockets = vcpus / 4; cmd.setTopology(4, sockets); } vm.addComp(cmd); } if (_hypervisorLibvirtVersion >= 9000) { final CpuTuneDef ctd = new CpuTuneDef(); /** A 4.0.X/4.1.X management server doesn't send the correct JSON command for getMinSpeed, it only sends a 'speed' field. So if getMinSpeed() returns null we fall back to getSpeed(). This way a >4.1 agent can work communicate a <=4.1 management server This change is due to the overcommit feature in 4.2 */ if (vmTO.getMinSpeed() != null) { ctd.setShares(vmTO.getCpus() * vmTO.getMinSpeed()); } else { ctd.setShares(vmTO.getCpus() * vmTO.getSpeed()); } setQuotaAndPeriod(vmTO, ctd); vm.addComp(ctd); } final FeaturesDef features = new FeaturesDef(); features.addFeatures("pae"); features.addFeatures("apic"); features.addFeatures("acpi"); if (isUefiEnabled && isSecureMode(customParams.get(GuestDef.BootType.UEFI.toString()))) { features.addFeatures("smm"); } //KVM hyperv enlightenment features based on OS Type enlightenWindowsVm(vmTO, features); vm.addComp(features); final TermPolicy term = new TermPolicy(); term.setCrashPolicy("destroy"); term.setPowerOffPolicy("destroy"); term.setRebootPolicy("restart"); vm.addComp(term); final ClockDef clock = new ClockDef(); if (vmTO.getOs().startsWith("Windows")) { clock.setClockOffset(ClockDef.ClockOffset.LOCALTIME); clock.setTimer("hypervclock", null, null); } else if (vmTO.getType() != VirtualMachine.Type.User || isGuestPVEnabled(vmTO.getOs())) { if (_hypervisorLibvirtVersion >= 9 * 1000 + 10) { clock.setTimer("kvmclock", null, null, _noKvmClock); } } vm.addComp(clock); final DevicesDef devices = new DevicesDef(); devices.setEmulatorPath(_hypervisorPath); devices.setGuestType(guest.getGuestType()); final SerialDef serial = new SerialDef("pty", null, (short)0); devices.addDevice(serial); if (_rngEnable) { final RngDef rngDevice = new RngDef(_rngPath, _rngBackendModel, _rngRateBytes, _rngRatePeriod); devices.addDevice(rngDevice); } /* Add a VirtIO channel for the Qemu Guest Agent tools */ File virtIoChannel = Paths.get(_qemuSocketsPath.getPath(), vmTO.getName() + "." + _qemuGuestAgentSocketName).toFile(); devices.addDevice(new ChannelDef(_qemuGuestAgentSocketName, ChannelDef.ChannelType.UNIX, virtIoChannel)); devices.addDevice(new WatchDogDef(_watchDogAction, _watchDogModel)); final VideoDef videoCard = new VideoDef(_videoHw, _videoRam); devices.addDevice(videoCard); final ConsoleDef console = new ConsoleDef("pty", null, null, (short)0); devices.addDevice(console); //add the VNC port passwd here, get the passwd from the vmInstance. final String passwd = vmTO.getVncPassword(); final GraphicDef grap = new GraphicDef("vnc", (short)0, true, vmTO.getVncAddr(), passwd, null); devices.addDevice(grap); final InputDef input = new InputDef("tablet", "usb"); devices.addDevice(input); // Add an explicit USB devices for ARM64 if (_guestCpuArch != null && _guestCpuArch.equals("aarch64")) { devices.addDevice(new InputDef("keyboard", "usb")); devices.addDevice(new InputDef("mouse", "usb")); devices.addDevice(new LibvirtVMDef.USBDef((short)0, 0, 5, 0, 0)); } DiskDef.DiskBus busT = getDiskModelFromVMDetail(vmTO); if (busT == null) { busT = getGuestDiskModel(vmTO.getPlatformEmulator()); } // If we're using virtio scsi, then we need to add a virtual scsi controller if (busT == DiskDef.DiskBus.SCSI) { final SCSIDef sd = new SCSIDef((short)0, 0, 0, 9, 0, vcpus); devices.addDevice(sd); } vm.addComp(devices); // Add extra configuration to User VM Domain XML before starting if (vmTO.getType().equals(VirtualMachine.Type.User) && MapUtils.isNotEmpty(extraConfig)) { s_logger.info("Appending extra configuration data to guest VM domain XML"); addExtraConfigComponent(extraConfig, vm); } return vm; } /** * Add extra configurations (if any) as a String component to the domain XML */ protected void addExtraConfigComponent(Map<String, String> extraConfig, LibvirtVMDef vm) { if (MapUtils.isNotEmpty(extraConfig)) { StringBuilder extraConfigBuilder = new StringBuilder(); for (String key : extraConfig.keySet()) { if (!key.startsWith(DpdkHelper.DPDK_INTERFACE_PREFIX) && !key.equals(DpdkHelper.DPDK_VHOST_USER_MODE)) { extraConfigBuilder.append(extraConfig.get(key)); } } String comp = extraConfigBuilder.toString(); if (org.apache.commons.lang.StringUtils.isNotBlank(comp)) { vm.addComp(comp); } } } public void createVifs(final VirtualMachineTO vmSpec, final LibvirtVMDef vm) throws InternalErrorException, LibvirtException { final NicTO[] nics = vmSpec.getNics(); final Map <String, String> params = vmSpec.getDetails(); String nicAdapter = ""; if (params != null && params.get("nicAdapter") != null && !params.get("nicAdapter").isEmpty()) { nicAdapter = params.get("nicAdapter"); } Map<String, String> extraConfig = vmSpec.getExtraConfig(); for (int i = 0; i < nics.length; i++) { for (final NicTO nic : vmSpec.getNics()) { if (nic.getDeviceId() == i) { createVif(vm, nic, nicAdapter, extraConfig); } } } } public String getVolumePath(final Connect conn, final DiskTO volume) throws LibvirtException, URISyntaxException { final DataTO data = volume.getData(); final DataStoreTO store = data.getDataStore(); if (volume.getType() == Volume.Type.ISO && data.getPath() != null && (store instanceof NfsTO || store instanceof PrimaryDataStoreTO && data instanceof TemplateObjectTO && !((TemplateObjectTO) data).isDirectDownload())) { final String isoPath = store.getUrl().split("\\?")[0] + File.separator + data.getPath(); final int index = isoPath.lastIndexOf("/"); final String path = isoPath.substring(0, index); final String name = isoPath.substring(index + 1); final KVMStoragePool secondaryPool = _storagePoolMgr.getStoragePoolByURI(path); final KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name); return isoVol.getPath(); } else { return data.getPath(); } } public void createVbd(final Connect conn, final VirtualMachineTO vmSpec, final String vmName, final LibvirtVMDef vm) throws InternalErrorException, LibvirtException, URISyntaxException { final Map<String, String> details = vmSpec.getDetails(); final List<DiskTO> disks = Arrays.asList(vmSpec.getDisks()); boolean isSecureBoot = false; boolean isWindowsTemplate = false; Collections.sort(disks, new Comparator<DiskTO>() { @Override public int compare(final DiskTO arg0, final DiskTO arg1) { return arg0.getDiskSeq() > arg1.getDiskSeq() ? 1 : -1; } }); if (MapUtils.isNotEmpty(details) && details.containsKey(GuestDef.BootType.UEFI.toString())) { isSecureBoot = isSecureMode(details.get(GuestDef.BootType.UEFI.toString())); } if (vmSpec.getOs().toLowerCase().contains("window")) { isWindowsTemplate =true; } for (final DiskTO volume : disks) { KVMPhysicalDisk physicalDisk = null; KVMStoragePool pool = null; final DataTO data = volume.getData(); if (volume.getType() == Volume.Type.ISO && data.getPath() != null) { DataStoreTO dataStore = data.getDataStore(); String dataStoreUrl = null; if (dataStore instanceof NfsTO) { NfsTO nfsStore = (NfsTO)data.getDataStore(); dataStoreUrl = nfsStore.getUrl(); physicalDisk = getPhysicalDiskFromNfsStore(dataStoreUrl, data); } else if (dataStore instanceof PrimaryDataStoreTO) { //In order to support directly downloaded ISOs PrimaryDataStoreTO primaryDataStoreTO = (PrimaryDataStoreTO) dataStore; if (primaryDataStoreTO.getPoolType().equals(StoragePoolType.NetworkFilesystem)) { String psHost = primaryDataStoreTO.getHost(); String psPath = primaryDataStoreTO.getPath(); dataStoreUrl = "nfs://" + psHost + File.separator + psPath; physicalDisk = getPhysicalDiskFromNfsStore(dataStoreUrl, data); } else if (primaryDataStoreTO.getPoolType().equals(StoragePoolType.SharedMountPoint) || primaryDataStoreTO.getPoolType().equals(StoragePoolType.Filesystem)) { physicalDisk = getPhysicalDiskPrimaryStore(primaryDataStoreTO, data); } } } else if (volume.getType() != Volume.Type.ISO) { final PrimaryDataStoreTO store = (PrimaryDataStoreTO)data.getDataStore(); physicalDisk = _storagePoolMgr.getPhysicalDisk(store.getPoolType(), store.getUuid(), data.getPath()); pool = physicalDisk.getPool(); } String volPath = null; if (physicalDisk != null) { volPath = physicalDisk.getPath(); } // check for disk activity, if detected we should exit because vm is running elsewhere if (_diskActivityCheckEnabled && physicalDisk != null && physicalDisk.getFormat() == PhysicalDiskFormat.QCOW2) { s_logger.debug("Checking physical disk file at path " + volPath + " for disk activity to ensure vm is not running elsewhere"); try { HypervisorUtils.checkVolumeFileForActivity(volPath, _diskActivityCheckTimeoutSeconds, _diskActivityInactiveThresholdMilliseconds, _diskActivityCheckFileSizeMin); } catch (final IOException ex) { throw new CloudRuntimeException("Unable to check physical disk file for activity", ex); } s_logger.debug("Disk activity check cleared"); } // if params contains a rootDiskController key, use its value (this is what other HVs are doing) DiskDef.DiskBus diskBusType = getDiskModelFromVMDetail(vmSpec); if (diskBusType == null) { diskBusType = getGuestDiskModel(vmSpec.getPlatformEmulator()); } // I'm not sure why previously certain DATADISKs were hard-coded VIRTIO and others not, however this // maintains existing functionality with the exception that SCSI will override VIRTIO. DiskDef.DiskBus diskBusTypeData = (diskBusType == DiskDef.DiskBus.SCSI) ? diskBusType : DiskDef.DiskBus.VIRTIO; final DiskDef disk = new DiskDef(); int devId = volume.getDiskSeq().intValue(); if (volume.getType() == Volume.Type.ISO) { if (volPath == null) { if (isSecureBoot) { disk.defISODisk(null, devId,isSecureBoot,isWindowsTemplate); } else { /* Add iso as placeholder */ disk.defISODisk(null, devId); } } else { disk.defISODisk(volPath, devId); } if (_guestCpuArch != null && _guestCpuArch.equals("aarch64")) { disk.setBusType(DiskDef.DiskBus.SCSI); } } else { if (diskBusType == DiskDef.DiskBus.SCSI ) { disk.setQemuDriver(true); disk.setDiscard(DiscardType.UNMAP); } if (pool.getType() == StoragePoolType.RBD) { /* For RBD pools we use the secret mechanism in libvirt. We store the secret under the UUID of the pool, that's why we pass the pool's UUID as the authSecret */ disk.defNetworkBasedDisk(physicalDisk.getPath().replace("rbd:", ""), pool.getSourceHost(), pool.getSourcePort(), pool.getAuthUserName(), pool.getUuid(), devId, diskBusType, DiskProtocol.RBD, DiskDef.DiskFmtType.RAW); } else if (pool.getType() == StoragePoolType.Gluster) { final String mountpoint = pool.getLocalPath(); final String path = physicalDisk.getPath(); final String glusterVolume = pool.getSourceDir().replace("/", ""); disk.defNetworkBasedDisk(glusterVolume + path.replace(mountpoint, ""), pool.getSourceHost(), pool.getSourcePort(), null, null, devId, diskBusType, DiskProtocol.GLUSTER, DiskDef.DiskFmtType.QCOW2); } else if (pool.getType() == StoragePoolType.CLVM || physicalDisk.getFormat() == PhysicalDiskFormat.RAW) { if (volume.getType() == Volume.Type.DATADISK) { disk.defBlockBasedDisk(physicalDisk.getPath(), devId, diskBusTypeData); } else { disk.defBlockBasedDisk(physicalDisk.getPath(), devId, diskBusType); } } else { if (volume.getType() == Volume.Type.DATADISK) { disk.defFileBasedDisk(physicalDisk.getPath(), devId, diskBusTypeData, DiskDef.DiskFmtType.QCOW2); } else { if (isSecureBoot) { disk.defFileBasedDisk(physicalDisk.getPath(), devId, DiskDef.DiskFmtType.QCOW2, isWindowsTemplate); } else { disk.defFileBasedDisk(physicalDisk.getPath(), devId, diskBusType, DiskDef.DiskFmtType.QCOW2); } } } } if (data instanceof VolumeObjectTO) { final VolumeObjectTO volumeObjectTO = (VolumeObjectTO)data; disk.setSerial(diskUuidToSerial(volumeObjectTO.getUuid())); setBurstProperties(volumeObjectTO, disk); if (volumeObjectTO.getCacheMode() != null) { disk.setCacheMode(DiskDef.DiskCacheMode.valueOf(volumeObjectTO.getCacheMode().toString().toUpperCase())); } } if (vm.getDevices() == null) { s_logger.error("There is no devices for" + vm); throw new RuntimeException("There is no devices for" + vm); } vm.getDevices().addDevice(disk); } if (vmSpec.getType() != VirtualMachine.Type.User) { if (_sysvmISOPath != null) { final DiskDef iso = new DiskDef(); iso.defISODisk(_sysvmISOPath); if (_guestCpuArch != null && _guestCpuArch.equals("aarch64")) { iso.setBusType(DiskDef.DiskBus.SCSI); } vm.getDevices().addDevice(iso); } } // For LXC, find and add the root filesystem, rbd data disks if (HypervisorType.LXC.toString().toLowerCase().equals(vm.getHvsType())) { for (final DiskTO volume : disks) { final DataTO data = volume.getData(); final PrimaryDataStoreTO store = (PrimaryDataStoreTO)data.getDataStore(); if (volume.getType() == Volume.Type.ROOT) { final KVMPhysicalDisk physicalDisk = _storagePoolMgr.getPhysicalDisk(store.getPoolType(), store.getUuid(), data.getPath()); final FilesystemDef rootFs = new FilesystemDef(physicalDisk.getPath(), "/"); vm.getDevices().addDevice(rootFs); } else if (volume.getType() == Volume.Type.DATADISK) { final KVMPhysicalDisk physicalDisk = _storagePoolMgr.getPhysicalDisk(store.getPoolType(), store.getUuid(), data.getPath()); final KVMStoragePool pool = physicalDisk.getPool(); if(StoragePoolType.RBD.equals(pool.getType())) { final int devId = volume.getDiskSeq().intValue(); final String device = mapRbdDevice(physicalDisk); if (device != null) { s_logger.debug("RBD device on host is: " + device); final DiskDef diskdef = new DiskDef(); diskdef.defBlockBasedDisk(device, devId, DiskDef.DiskBus.VIRTIO); diskdef.setQemuDriver(false); vm.getDevices().addDevice(diskdef); } else { throw new InternalErrorException("Error while mapping RBD device on host"); } } } } } } private KVMPhysicalDisk getPhysicalDiskPrimaryStore(PrimaryDataStoreTO primaryDataStoreTO, DataTO data) { KVMStoragePool storagePool = _storagePoolMgr.getStoragePool(primaryDataStoreTO.getPoolType(), primaryDataStoreTO.getUuid()); return storagePool.getPhysicalDisk(data.getPath()); } private KVMPhysicalDisk getPhysicalDiskFromNfsStore(String dataStoreUrl, DataTO data) { final String volPath = dataStoreUrl + File.separator + data.getPath(); final int index = volPath.lastIndexOf("/"); final String volDir = volPath.substring(0, index); final String volName = volPath.substring(index + 1); final KVMStoragePool storage = _storagePoolMgr.getStoragePoolByURI(volDir); return storage.getPhysicalDisk(volName); } private void setBurstProperties(final VolumeObjectTO volumeObjectTO, final DiskDef disk ) { if (volumeObjectTO.getBytesReadRate() != null && volumeObjectTO.getBytesReadRate() > 0) { disk.setBytesReadRate(volumeObjectTO.getBytesReadRate()); } if (volumeObjectTO.getBytesReadRateMax() != null && volumeObjectTO.getBytesReadRateMax() > 0) { disk.setBytesReadRateMax(volumeObjectTO.getBytesReadRateMax()); } if (volumeObjectTO.getBytesReadRateMaxLength() != null && volumeObjectTO.getBytesReadRateMaxLength() > 0) { disk.setBytesReadRateMaxLength(volumeObjectTO.getBytesReadRateMaxLength()); } if (volumeObjectTO.getBytesWriteRate() != null && volumeObjectTO.getBytesWriteRate() > 0) { disk.setBytesWriteRate(volumeObjectTO.getBytesWriteRate()); } if (volumeObjectTO.getBytesWriteRateMax() != null && volumeObjectTO.getBytesWriteRateMax() > 0) { disk.setBytesWriteRateMax(volumeObjectTO.getBytesWriteRateMax()); } if (volumeObjectTO.getBytesWriteRateMaxLength() != null && volumeObjectTO.getBytesWriteRateMaxLength() > 0) { disk.setBytesWriteRateMaxLength(volumeObjectTO.getBytesWriteRateMaxLength()); } if (volumeObjectTO.getIopsReadRate() != null && volumeObjectTO.getIopsReadRate() > 0) { disk.setIopsReadRate(volumeObjectTO.getIopsReadRate()); } if (volumeObjectTO.getIopsReadRateMax() != null && volumeObjectTO.getIopsReadRateMax() > 0) { disk.setIopsReadRateMax(volumeObjectTO.getIopsReadRateMax()); } if (volumeObjectTO.getIopsReadRateMaxLength() != null && volumeObjectTO.getIopsReadRateMaxLength() > 0) { disk.setIopsReadRateMaxLength(volumeObjectTO.getIopsReadRateMaxLength()); } if (volumeObjectTO.getIopsWriteRate() != null && volumeObjectTO.getIopsWriteRate() > 0) { disk.setIopsWriteRate(volumeObjectTO.getIopsWriteRate()); } if (volumeObjectTO.getIopsWriteRateMax() != null && volumeObjectTO.getIopsWriteRateMax() > 0) { disk.setIopsWriteRateMax(volumeObjectTO.getIopsWriteRateMax()); } if (volumeObjectTO.getIopsWriteRateMaxLength() != null && volumeObjectTO.getIopsWriteRateMaxLength() > 0) { disk.setIopsWriteRateMaxLength(volumeObjectTO.getIopsWriteRateMaxLength()); } } private void createVif(final LibvirtVMDef vm, final NicTO nic, final String nicAdapter, Map<String, String> extraConfig) throws InternalErrorException, LibvirtException { if (vm.getDevices() == null) { s_logger.error("LibvirtVMDef object get devices with null result"); throw new InternalErrorException("LibvirtVMDef object get devices with null result"); } vm.getDevices().addDevice(getVifDriver(nic.getType(), nic.getName()).plug(nic, vm.getPlatformEmulator(), nicAdapter, extraConfig)); } public boolean cleanupDisk(Map<String, String> volumeToDisconnect) { return _storagePoolMgr.disconnectPhysicalDisk(volumeToDisconnect); } public boolean cleanupDisk(final DiskDef disk) { final String path = disk.getDiskPath(); if (path == null) { s_logger.debug("Unable to clean up disk with null path (perhaps empty cdrom drive):" + disk); return false; } if (path.endsWith("systemvm.iso")) { // don't need to clean up system vm ISO as it's stored in local return true; } return _storagePoolMgr.disconnectPhysicalDiskByPath(path); } protected KVMStoragePoolManager getPoolManager() { return _storagePoolMgr; } public synchronized String attachOrDetachISO(final Connect conn, final String vmName, String isoPath, final boolean isAttach, final Integer diskSeq) throws LibvirtException, URISyntaxException, InternalErrorException { final DiskDef iso = new DiskDef(); if (isoPath != null && isAttach) { final int index = isoPath.lastIndexOf("/"); final String path = isoPath.substring(0, index); final String name = isoPath.substring(index + 1); final KVMStoragePool secondaryPool = _storagePoolMgr.getStoragePoolByURI(path); final KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name); isoPath = isoVol.getPath(); iso.defISODisk(isoPath, diskSeq); } else { iso.defISODisk(null, diskSeq); } final String result = attachOrDetachDevice(conn, true, vmName, iso.toString()); if (result == null && !isAttach) { final List<DiskDef> disks = getDisks(conn, vmName); for (final DiskDef disk : disks) { if (disk.getDeviceType() == DiskDef.DeviceType.CDROM && (diskSeq == null || disk.getDiskLabel() == iso.getDiskLabel())) { cleanupDisk(disk); } } } return result; } public synchronized String attachOrDetachDisk(final Connect conn, final boolean attach, final String vmName, final KVMPhysicalDisk attachingDisk, final int devId, final Long bytesReadRate, final Long bytesReadRateMax, final Long bytesReadRateMaxLength, final Long bytesWriteRate, final Long bytesWriteRateMax, final Long bytesWriteRateMaxLength, final Long iopsReadRate, final Long iopsReadRateMax, final Long iopsReadRateMaxLength, final Long iopsWriteRate, final Long iopsWriteRateMax, final Long iopsWriteRateMaxLength, final String cacheMode) throws LibvirtException, InternalErrorException { List<DiskDef> disks = null; Domain dm = null; DiskDef diskdef = null; final KVMStoragePool attachingPool = attachingDisk.getPool(); try { dm = conn.domainLookupByName(vmName); final LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); final String domXml = dm.getXMLDesc(0); parser.parseDomainXML(domXml); disks = parser.getDisks(); if (!attach) { for (final DiskDef disk : disks) { final String file = disk.getDiskPath(); if (file != null && file.equalsIgnoreCase(attachingDisk.getPath())) { diskdef = disk; break; } } if (diskdef == null) { throw new InternalErrorException("disk: " + attachingDisk.getPath() + " is not attached before"); } } else { DiskDef.DiskBus busT = DiskDef.DiskBus.VIRTIO; for (final DiskDef disk : disks) { if (disk.getDeviceType() == DeviceType.DISK) { if (disk.getBusType() == DiskDef.DiskBus.SCSI) { busT = DiskDef.DiskBus.SCSI; } break; } } diskdef = new DiskDef(); if (busT == DiskDef.DiskBus.SCSI) { diskdef.setQemuDriver(true); diskdef.setDiscard(DiscardType.UNMAP); } if (attachingPool.getType() == StoragePoolType.RBD) { diskdef.defNetworkBasedDisk(attachingDisk.getPath(), attachingPool.getSourceHost(), attachingPool.getSourcePort(), attachingPool.getAuthUserName(), attachingPool.getUuid(), devId, busT, DiskProtocol.RBD, DiskDef.DiskFmtType.RAW); } else if (attachingPool.getType() == StoragePoolType.Gluster) { diskdef.defNetworkBasedDisk(attachingDisk.getPath(), attachingPool.getSourceHost(), attachingPool.getSourcePort(), null, null, devId, busT, DiskProtocol.GLUSTER, DiskDef.DiskFmtType.QCOW2); } else if (attachingDisk.getFormat() == PhysicalDiskFormat.QCOW2) { diskdef.defFileBasedDisk(attachingDisk.getPath(), devId, busT, DiskDef.DiskFmtType.QCOW2); } else if (attachingDisk.getFormat() == PhysicalDiskFormat.RAW) { diskdef.defBlockBasedDisk(attachingDisk.getPath(), devId, busT); } if (bytesReadRate != null && bytesReadRate > 0) { diskdef.setBytesReadRate(bytesReadRate); } if (bytesReadRateMax != null && bytesReadRateMax > 0) { diskdef.setBytesReadRateMax(bytesReadRateMax); } if (bytesReadRateMaxLength != null && bytesReadRateMaxLength > 0) { diskdef.setBytesReadRateMaxLength(bytesReadRateMaxLength); } if (bytesWriteRate != null && bytesWriteRate > 0) { diskdef.setBytesWriteRate(bytesWriteRate); } if (bytesWriteRateMax != null && bytesWriteRateMax > 0) { diskdef.setBytesWriteRateMax(bytesWriteRateMax); } if (bytesWriteRateMaxLength != null && bytesWriteRateMaxLength > 0) { diskdef.setBytesWriteRateMaxLength(bytesWriteRateMaxLength); } if (iopsReadRate != null && iopsReadRate > 0) { diskdef.setIopsReadRate(iopsReadRate); } if (iopsReadRateMax != null && iopsReadRateMax > 0) { diskdef.setIopsReadRateMax(iopsReadRateMax); } if (iopsReadRateMaxLength != null && iopsReadRateMaxLength > 0) { diskdef.setIopsReadRateMaxLength(iopsReadRateMaxLength); } if (iopsWriteRate != null && iopsWriteRate > 0) { diskdef.setIopsWriteRate(iopsWriteRate); } if (iopsWriteRateMax != null && iopsWriteRateMax > 0) { diskdef.setIopsWriteRateMax(iopsWriteRateMax); } if (cacheMode != null) { diskdef.setCacheMode(DiskDef.DiskCacheMode.valueOf(cacheMode.toUpperCase())); } } final String xml = diskdef.toString(); return attachOrDetachDevice(conn, attach, vmName, xml); } finally { if (dm != null) { dm.free(); } } } protected synchronized String attachOrDetachDevice(final Connect conn, final boolean attach, final String vmName, final String xml) throws LibvirtException, InternalErrorException { Domain dm = null; try { dm = conn.domainLookupByName(vmName); if (attach) { s_logger.debug("Attaching device: " + xml); dm.attachDevice(xml); } else { s_logger.debug("Detaching device: " + xml); dm.detachDevice(xml); } } catch (final LibvirtException e) { if (attach) { s_logger.warn("Failed to attach device to " + vmName + ": " + e.getMessage()); } else { s_logger.warn("Failed to detach device from " + vmName + ": " + e.getMessage()); } throw e; } finally { if (dm != null) { try { dm.free(); } catch (final LibvirtException l) { s_logger.trace("Ignoring libvirt error.", l); } } } return null; } @Override public PingCommand getCurrentStatus(final long id) { if (!_canBridgeFirewall) { return new PingRoutingCommand(com.cloud.host.Host.Type.Routing, id, this.getHostVmStateReport()); } else { final HashMap<String, Pair<Long, Long>> nwGrpStates = syncNetworkGroups(id); return new PingRoutingWithNwGroupsCommand(getType(), id, this.getHostVmStateReport(), nwGrpStates); } } @Override public Type getType() { return Type.Routing; } private Map<String, String> getVersionStrings() { final Script command = new Script(_versionstringpath, _timeout, s_logger); final KeyValueInterpreter kvi = new KeyValueInterpreter(); final String result = command.execute(kvi); if (result == null) { return kvi.getKeyValues(); } else { return new HashMap<String, String>(1); } } @Override public StartupCommand[] initialize() { final KVMHostInfo info = new KVMHostInfo(_dom0MinMem, _dom0OvercommitMem); String capabilities = String.join(",", info.getCapabilities()); if (dpdkSupport) { capabilities += ",dpdk"; } final StartupRoutingCommand cmd = new StartupRoutingCommand(info.getCpus(), info.getCpuSpeed(), info.getTotalMemory(), info.getReservedMemory(), capabilities, _hypervisorType, RouterPrivateIpStrategy.HostLocal); cmd.setCpuSockets(info.getCpuSockets()); fillNetworkInformation(cmd); _privateIp = cmd.getPrivateIpAddress(); cmd.getHostDetails().putAll(getVersionStrings()); cmd.getHostDetails().put(KeyStoreUtils.SECURED, String.valueOf(isHostSecured()).toLowerCase()); cmd.setPool(_pool); cmd.setCluster(_clusterId); cmd.setGatewayIpAddress(_localGateway); cmd.setIqn(getIqn()); if (cmd.getHostDetails().containsKey("Host.OS")) { _hostDistro = cmd.getHostDetails().get("Host.OS"); } StartupStorageCommand sscmd = null; try { final KVMStoragePool localStoragePool = _storagePoolMgr.createStoragePool(_localStorageUUID, "localhost", -1, _localStoragePath, "", StoragePoolType.Filesystem); final com.cloud.agent.api.StoragePoolInfo pi = new com.cloud.agent.api.StoragePoolInfo(localStoragePool.getUuid(), cmd.getPrivateIpAddress(), _localStoragePath, _localStoragePath, StoragePoolType.Filesystem, localStoragePool.getCapacity(), localStoragePool.getAvailable()); sscmd = new StartupStorageCommand(); sscmd.setPoolInfo(pi); sscmd.setGuid(pi.getUuid()); sscmd.setDataCenter(_dcId); sscmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL); } catch (final CloudRuntimeException e) { s_logger.debug("Unable to initialize local storage pool: " + e); } if (sscmd != null) { return new StartupCommand[] {cmd, sscmd}; } else { return new StartupCommand[] {cmd}; } } public String diskUuidToSerial(String uuid) { String uuidWithoutHyphen = uuid.replace("-",""); return uuidWithoutHyphen.substring(0, Math.min(uuidWithoutHyphen.length(), 20)); } private String getIqn() { try { final String textToFind = "InitiatorName="; final Script iScsiAdmCmd = new Script(true, "grep", 0, s_logger); iScsiAdmCmd.add(textToFind); iScsiAdmCmd.add("/etc/iscsi/initiatorname.iscsi"); final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); final String result = iScsiAdmCmd.execute(parser); if (result != null) { return null; } final String textFound = parser.getLine().trim(); return textFound.substring(textToFind.length()); } catch (final Exception ex) { return null; } } protected List<String> getAllVmNames(final Connect conn) { final ArrayList<String> la = new ArrayList<String>(); try { final String names[] = conn.listDefinedDomains(); for (int i = 0; i < names.length; i++) { la.add(names[i]); } } catch (final LibvirtException e) { s_logger.warn("Failed to list Defined domains", e); } int[] ids = null; try { ids = conn.listDomains(); } catch (final LibvirtException e) { s_logger.warn("Failed to list domains", e); return la; } Domain dm = null; for (int i = 0; i < ids.length; i++) { try { dm = conn.domainLookupByID(ids[i]); la.add(dm.getName()); } catch (final LibvirtException e) { s_logger.warn("Unable to get vms", e); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } } } return la; } private HashMap<String, HostVmStateReportEntry> getHostVmStateReport() { final HashMap<String, HostVmStateReportEntry> vmStates = new HashMap<String, HostVmStateReportEntry>(); Connect conn = null; if (_hypervisorType == HypervisorType.LXC) { try { conn = LibvirtConnection.getConnectionByType(HypervisorType.LXC.toString()); vmStates.putAll(getHostVmStateReport(conn)); conn = LibvirtConnection.getConnectionByType(HypervisorType.KVM.toString()); vmStates.putAll(getHostVmStateReport(conn)); } catch (final LibvirtException e) { s_logger.debug("Failed to get connection: " + e.getMessage()); } } if (_hypervisorType == HypervisorType.KVM) { try { conn = LibvirtConnection.getConnectionByType(HypervisorType.KVM.toString()); vmStates.putAll(getHostVmStateReport(conn)); } catch (final LibvirtException e) { s_logger.debug("Failed to get connection: " + e.getMessage()); } } return vmStates; } private HashMap<String, HostVmStateReportEntry> getHostVmStateReport(final Connect conn) { final HashMap<String, HostVmStateReportEntry> vmStates = new HashMap<String, HostVmStateReportEntry>(); String[] vms = null; int[] ids = null; try { ids = conn.listDomains(); } catch (final LibvirtException e) { s_logger.warn("Unable to listDomains", e); return null; } try { vms = conn.listDefinedDomains(); } catch (final LibvirtException e) { s_logger.warn("Unable to listDomains", e); return null; } Domain dm = null; for (int i = 0; i < ids.length; i++) { try { dm = conn.domainLookupByID(ids[i]); final DomainState ps = dm.getInfo().state; final PowerState state = convertToPowerState(ps); s_logger.trace("VM " + dm.getName() + ": powerstate = " + ps + "; vm state=" + state.toString()); final String vmName = dm.getName(); // TODO : for XS/KVM (host-based resource), we require to remove // VM completely from host, for some reason, KVM seems to still keep // Stopped VM around, to work-around that, reporting only powered-on VM // if (state == PowerState.PowerOn) { vmStates.put(vmName, new HostVmStateReportEntry(state, conn.getHostName())); } } catch (final LibvirtException e) { s_logger.warn("Unable to get vms", e); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } } } for (int i = 0; i < vms.length; i++) { try { dm = conn.domainLookupByName(vms[i]); final DomainState ps = dm.getInfo().state; final PowerState state = convertToPowerState(ps); final String vmName = dm.getName(); s_logger.trace("VM " + vmName + ": powerstate = " + ps + "; vm state=" + state.toString()); // TODO : for XS/KVM (host-based resource), we require to remove // VM completely from host, for some reason, KVM seems to still keep // Stopped VM around, to work-around that, reporting only powered-on VM // if (state == PowerState.PowerOn) { vmStates.put(vmName, new HostVmStateReportEntry(state, conn.getHostName())); } } catch (final LibvirtException e) { s_logger.warn("Unable to get vms", e); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } } } return vmStates; } public String rebootVM(final Connect conn, final String vmName) throws LibvirtException{ Domain dm = null; String msg = null; try { dm = conn.domainLookupByName(vmName); // Get XML Dump including the secure information such as VNC password // By passing 1, or VIR_DOMAIN_XML_SECURE flag // https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainXMLFlags String vmDef = dm.getXMLDesc(1); final LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); parser.parseDomainXML(vmDef); for (final InterfaceDef nic : parser.getInterfaces()) { if (nic.getNetType() == GuestNetType.BRIDGE && nic.getBrName().startsWith("cloudVirBr")) { try { final int vnetId = Integer.parseInt(nic.getBrName().replaceFirst("cloudVirBr", "")); final String pifName = getPif(_guestBridgeName); final String newBrName = "br" + pifName + "-" + vnetId; vmDef = vmDef.replace("'" + nic.getBrName() + "'", "'" + newBrName + "'"); s_logger.debug("VM bridge name is changed from " + nic.getBrName() + " to " + newBrName); } catch (final NumberFormatException e) { continue; } } } s_logger.debug(vmDef); msg = stopVM(conn, vmName, false); msg = startVM(conn, vmName, vmDef); return null; } catch (final LibvirtException e) { s_logger.warn("Failed to create vm", e); msg = e.getMessage(); } catch (final InternalErrorException e) { s_logger.warn("Failed to create vm", e); msg = e.getMessage(); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } } return msg; } public String stopVM(final Connect conn, final String vmName, final boolean forceStop) { DomainState state = null; Domain dm = null; // delete the metadata of vm snapshots before stopping try { dm = conn.domainLookupByName(vmName); cleanVMSnapshotMetadata(dm); } catch (LibvirtException e) { s_logger.debug("Failed to get vm :" + e.getMessage()); } finally { try { if (dm != null) { dm.free(); } } catch (LibvirtException l) { s_logger.trace("Ignoring libvirt error.", l); } } s_logger.debug("Try to stop the vm at first"); if (forceStop) { return stopVMInternal(conn, vmName, true); } String ret = stopVMInternal(conn, vmName, false); if (ret == Script.ERR_TIMEOUT) { ret = stopVMInternal(conn, vmName, true); } else if (ret != null) { /* * There is a race condition between libvirt and qemu: libvirt * listens on qemu's monitor fd. If qemu is shutdown, while libvirt * is reading on the fd, then libvirt will report an error. */ /* Retry 3 times, to make sure we can get the vm's status */ for (int i = 0; i < 3; i++) { try { dm = conn.domainLookupByName(vmName); state = dm.getInfo().state; break; } catch (final LibvirtException e) { s_logger.debug("Failed to get vm status:" + e.getMessage()); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException l) { s_logger.trace("Ignoring libvirt error.", l); } } } if (state == null) { s_logger.debug("Can't get vm's status, assume it's dead already"); return null; } if (state != DomainState.VIR_DOMAIN_SHUTOFF) { s_logger.debug("Try to destroy the vm"); ret = stopVMInternal(conn, vmName, true); if (ret != null) { return ret; } } } return null; } protected String stopVMInternal(final Connect conn, final String vmName, final boolean force) { Domain dm = null; try { dm = conn.domainLookupByName(vmName); final int persist = dm.isPersistent(); if (force) { if (dm.isActive() == 1) { dm.destroy(); if (persist == 1) { dm.undefine(); } } } else { if (dm.isActive() == 0) { return null; } dm.shutdown(); int retry = _stopTimeout / 2000; /* Wait for the domain gets into shutoff state. When it does the dm object will no longer work, so we need to catch it. */ try { while (dm.isActive() == 1 && retry >= 0) { Thread.sleep(2000); retry--; } } catch (final LibvirtException e) { final String error = e.toString(); if (error.contains("Domain not found")) { s_logger.debug("successfully shut down vm " + vmName); } else { s_logger.debug("Error in waiting for vm shutdown:" + error); } } if (retry < 0) { s_logger.warn("Timed out waiting for domain " + vmName + " to shutdown gracefully"); return Script.ERR_TIMEOUT; } else { if (persist == 1) { dm.undefine(); } } } } catch (final LibvirtException e) { if (e.getMessage().contains("Domain not found")) { s_logger.debug("VM " + vmName + " doesn't exist, no need to stop it"); return null; } s_logger.debug("Failed to stop VM :" + vmName + " :", e); return e.getMessage(); } catch (final InterruptedException ie) { s_logger.debug("Interrupted sleep"); return ie.getMessage(); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } } return null; } public Integer getVncPort(final Connect conn, final String vmName) throws LibvirtException { final LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); Domain dm = null; try { dm = conn.domainLookupByName(vmName); final String xmlDesc = dm.getXMLDesc(0); parser.parseDomainXML(xmlDesc); return parser.getVncPort(); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException l) { s_logger.trace("Ignoring libvirt error.", l); } } } private boolean IsHVMEnabled(final Connect conn) { final LibvirtCapXMLParser parser = new LibvirtCapXMLParser(); try { parser.parseCapabilitiesXML(conn.getCapabilities()); final ArrayList<String> osTypes = parser.getGuestOsType(); for (final String o : osTypes) { if (o.equalsIgnoreCase("hvm")) { return true; } } } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } return false; } private String getHypervisorPath(final Connect conn) { final LibvirtCapXMLParser parser = new LibvirtCapXMLParser(); try { parser.parseCapabilitiesXML(conn.getCapabilities()); } catch (final LibvirtException e) { s_logger.debug(e.getMessage()); } return parser.getEmulator(); } boolean isGuestPVEnabled(final String guestOSName) { DiskDef.DiskBus db = getGuestDiskModel(guestOSName); return db != DiskDef.DiskBus.IDE; } public boolean isCentosHost() { if (_hvVersion <= 9) { return true; } else { return false; } } public DiskDef.DiskBus getDiskModelFromVMDetail(final VirtualMachineTO vmTO) { Map<String, String> details = vmTO.getDetails(); if (details == null) { return null; } if (_guestCpuArch != null && _guestCpuArch.equals("aarch64")) { return DiskDef.DiskBus.SCSI; } final String rootDiskController = details.get(VmDetailConstants.ROOT_DISK_CONTROLLER); if (StringUtils.isNotBlank(rootDiskController)) { s_logger.debug("Passed custom disk bus " + rootDiskController); for (final DiskDef.DiskBus bus : DiskDef.DiskBus.values()) { if (bus.toString().equalsIgnoreCase(rootDiskController)) { s_logger.debug("Found matching enum for disk bus " + rootDiskController); return bus; } } } return null; } private DiskDef.DiskBus getGuestDiskModel(final String platformEmulator) { if (_guestCpuArch != null && _guestCpuArch.equals("aarch64")) { return DiskDef.DiskBus.SCSI; } if (platformEmulator == null) { return DiskDef.DiskBus.IDE; } else if (platformEmulator.startsWith("Other PV Virtio-SCSI")) { return DiskDef.DiskBus.SCSI; } else if (platformEmulator.contains("Ubuntu") || platformEmulator.startsWith("Fedora") || platformEmulator.startsWith("CentOS") || platformEmulator.startsWith("Red Hat Enterprise Linux") || platformEmulator.startsWith("Debian GNU/Linux") || platformEmulator.startsWith("FreeBSD") || platformEmulator.startsWith("Oracle") || platformEmulator.startsWith("Other PV")) { return DiskDef.DiskBus.VIRTIO; } else { return DiskDef.DiskBus.IDE; } } private void cleanupVMNetworks(final Connect conn, final List<InterfaceDef> nics) { if (nics != null) { for (final InterfaceDef nic : nics) { for (final VifDriver vifDriver : getAllVifDrivers()) { vifDriver.unplug(nic); } } } } public Domain getDomain(final Connect conn, final String vmName) throws LibvirtException { return conn.domainLookupByName(vmName); } public List<InterfaceDef> getInterfaces(final Connect conn, final String vmName) { final LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); Domain dm = null; try { dm = conn.domainLookupByName(vmName); parser.parseDomainXML(dm.getXMLDesc(0)); return parser.getInterfaces(); } catch (final LibvirtException e) { s_logger.debug("Failed to get dom xml: " + e.toString()); return new ArrayList<InterfaceDef>(); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } } } public List<DiskDef> getDisks(final Connect conn, final String vmName) { final LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser(); Domain dm = null; try { dm = conn.domainLookupByName(vmName); parser.parseDomainXML(dm.getXMLDesc(0)); return parser.getDisks(); } catch (final LibvirtException e) { s_logger.debug("Failed to get dom xml: " + e.toString()); return new ArrayList<DiskDef>(); } finally { try { if (dm != null) { dm.free(); } } catch (final LibvirtException e) { s_logger.trace("Ignoring libvirt error.", e); } } } private String executeBashScript(final String script) { final Script command = new Script("/bin/bash", _timeout, s_logger); command.add("-c"); command.add(script); return command.execute(); } public List<VmNetworkStatsEntry> getVmNetworkStat(Connect conn, String vmName) throws LibvirtException { Domain dm = null; try { dm = getDomain(conn, vmName); List<VmNetworkStatsEntry> stats = new ArrayList<VmNetworkStatsEntry>(); List<InterfaceDef> nics = getInterfaces(conn, vmName); for (InterfaceDef nic : nics) { DomainInterfaceStats nicStats = dm.interfaceStats(nic.getDevName()); String macAddress = nic.getMacAddress(); VmNetworkStatsEntry stat = new VmNetworkStatsEntry(vmName, macAddress, nicStats.tx_bytes, nicStats.rx_bytes); stats.add(stat); } return stats; } finally { if (dm != null) { dm.free(); } } } public List<VmDiskStatsEntry> getVmDiskStat(final Connect conn, final String vmName) throws LibvirtException { Domain dm = null; try { dm = getDomain(conn, vmName); final List<VmDiskStatsEntry> stats = new ArrayList<VmDiskStatsEntry>(); final List<DiskDef> disks = getDisks(conn, vmName); for (final DiskDef disk : disks) { if (disk.getDeviceType() != DeviceType.DISK) { break; } final DomainBlockStats blockStats = dm.blockStats(disk.getDiskLabel()); final String path = disk.getDiskPath(); // for example, path = /mnt/pool_uuid/disk_path/ String diskPath = null; if (path != null) { final String[] token = path.split("/"); if (token.length > 3) { diskPath = token[3]; final VmDiskStatsEntry stat = new VmDiskStatsEntry(vmName, diskPath, blockStats.wr_req, blockStats.rd_req, blockStats.wr_bytes, blockStats.rd_bytes); stats.add(stat); } } } return stats; } finally { if (dm != null) { dm.free(); } } } private class VmStats { long _usedTime; long _tx; long _rx; long _ioRead; long _ioWrote; long _bytesRead; long _bytesWrote; Calendar _timestamp; } public VmStatsEntry getVmStat(final Connect conn, final String vmName) throws LibvirtException { Domain dm = null; try { dm = getDomain(conn, vmName); if (dm == null) { return null; } DomainInfo info = dm.getInfo(); final VmStatsEntry stats = new VmStatsEntry(); stats.setNumCPUs(info.nrVirtCpu); stats.setEntityType("vm"); stats.setMemoryKBs(info.maxMem); stats.setTargetMemoryKBs(info.memory); stats.setIntFreeMemoryKBs(getMemoryFreeInKBs(dm)); /* get cpu utilization */ VmStats oldStats = null; final Calendar now = Calendar.getInstance(); oldStats = _vmStats.get(vmName); long elapsedTime = 0; if (oldStats != null) { elapsedTime = now.getTimeInMillis() - oldStats._timestamp.getTimeInMillis(); double utilization = (info.cpuTime - oldStats._usedTime) / ((double)elapsedTime * 1000000); final NodeInfo node = conn.nodeInfo(); utilization = utilization / node.cpus; if (utilization > 0) { stats.setCPUUtilization(utilization * 100); } } /* get network stats */ final List<InterfaceDef> vifs = getInterfaces(conn, vmName); long rx = 0; long tx = 0; for (final InterfaceDef vif : vifs) { final DomainInterfaceStats ifStats = dm.interfaceStats(vif.getDevName()); rx += ifStats.rx_bytes; tx += ifStats.tx_bytes; } if (oldStats != null) { final double deltarx = rx - oldStats._rx; if (deltarx > 0) { stats.setNetworkReadKBs(deltarx / 1024); } final double deltatx = tx - oldStats._tx; if (deltatx > 0) { stats.setNetworkWriteKBs(deltatx / 1024); } } /* get disk stats */ final List<DiskDef> disks = getDisks(conn, vmName); long io_rd = 0; long io_wr = 0; long bytes_rd = 0; long bytes_wr = 0; for (final DiskDef disk : disks) { if (disk.getDeviceType() == DeviceType.CDROM || disk.getDeviceType() == DeviceType.FLOPPY) { continue; } final DomainBlockStats blockStats = dm.blockStats(disk.getDiskLabel()); io_rd += blockStats.rd_req; io_wr += blockStats.wr_req; bytes_rd += blockStats.rd_bytes; bytes_wr += blockStats.wr_bytes; } if (oldStats != null) { final long deltaiord = io_rd - oldStats._ioRead; if (deltaiord > 0) { stats.setDiskReadIOs(deltaiord); } final long deltaiowr = io_wr - oldStats._ioWrote; if (deltaiowr > 0) { stats.setDiskWriteIOs(deltaiowr); } final double deltabytesrd = bytes_rd - oldStats._bytesRead; if (deltabytesrd > 0) { stats.setDiskReadKBs(deltabytesrd / 1024); } final double deltabyteswr = bytes_wr - oldStats._bytesWrote; if (deltabyteswr > 0) { stats.setDiskWriteKBs(deltabyteswr / 1024); } } /* save to Hashmap */ final VmStats newStat = new VmStats(); newStat._usedTime = info.cpuTime; newStat._rx = rx; newStat._tx = tx; newStat._ioRead = io_rd; newStat._ioWrote = io_wr; newStat._bytesRead = bytes_rd; newStat._bytesWrote = bytes_wr; newStat._timestamp = now; _vmStats.put(vmName, newStat); return stats; } finally { if (dm != null) { dm.free(); } } } /** * This method retrieves the memory statistics from the domain given as parameters. * If no memory statistic is found, it will return {@link NumberUtils#LONG_ZERO} as the value of free memory in the domain. * If it can retrieve the domain memory statistics, it will return the free memory statistic; that means, it returns the value at the first position of the array returned by {@link Domain#memoryStats(int)}. * * @return the amount of free memory in KBs */ protected long getMemoryFreeInKBs(Domain dm) throws LibvirtException { MemoryStatistic[] mems = dm.memoryStats(NUMMEMSTATS); if (ArrayUtils.isEmpty(mems)) { return NumberUtils.LONG_ZERO; } return mems[0].getValue(); } private boolean canBridgeFirewall(final String prvNic) { final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("can_bridge_firewall"); cmd.add("--privnic", prvNic); final String result = cmd.execute(); if (result != null) { return false; } return true; } public boolean destroyNetworkRulesForVM(final Connect conn, final String vmName) { if (!_canBridgeFirewall) { return false; } String vif = null; final List<InterfaceDef> intfs = getInterfaces(conn, vmName); if (intfs.size() > 0) { final InterfaceDef intf = intfs.get(0); vif = intf.getDevName(); } final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("destroy_network_rules_for_vm"); cmd.add("--vmname", vmName); if (vif != null) { cmd.add("--vif", vif); } final String result = cmd.execute(); if (result != null) { return false; } return true; } /** * Function to destroy the security group rules applied to the nic's * @param conn * @param vmName * @param nic * @return * true : If success * false : If failure */ public boolean destroyNetworkRulesForNic(final Connect conn, final String vmName, final NicTO nic) { if (!_canBridgeFirewall) { return false; } final List<String> nicSecIps = nic.getNicSecIps(); String secIpsStr; final StringBuilder sb = new StringBuilder(); if (nicSecIps != null) { for (final String ip : nicSecIps) { sb.append(ip).append(SecurityGroupRulesCmd.RULE_COMMAND_SEPARATOR); } secIpsStr = sb.toString(); } else { secIpsStr = "0" + SecurityGroupRulesCmd.RULE_COMMAND_SEPARATOR; } final List<InterfaceDef> intfs = getInterfaces(conn, vmName); if (intfs.size() == 0 || intfs.size() < nic.getDeviceId()) { return false; } final InterfaceDef intf = intfs.get(nic.getDeviceId()); final String brname = intf.getBrName(); final String vif = intf.getDevName(); final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("destroy_network_rules_for_vm"); cmd.add("--vmname", vmName); if (nic.getIp() != null) { cmd.add("--vmip", nic.getIp()); } cmd.add("--vmmac", nic.getMac()); cmd.add("--vif", vif); cmd.add("--nicsecips", secIpsStr); final String result = cmd.execute(); if (result != null) { return false; } return true; } /** * Function to apply default network rules for a VM * @param conn * @param vm * @param checkBeforeApply * @return */ public boolean applyDefaultNetworkRules(final Connect conn, final VirtualMachineTO vm, final boolean checkBeforeApply) { NicTO[] nicTOs = new NicTO[] {}; if (vm != null && vm.getNics() != null) { s_logger.debug("Checking default network rules for vm " + vm.getName()); nicTOs = vm.getNics(); } for (NicTO nic : nicTOs) { if (vm.getType() != VirtualMachine.Type.User) { nic.setPxeDisable(true); } } boolean isFirstNic = true; for (final NicTO nic : nicTOs) { if (nic.isSecurityGroupEnabled() || nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) { if (vm.getType() != VirtualMachine.Type.User) { configureDefaultNetworkRulesForSystemVm(conn, vm.getName()); break; } if (!applyDefaultNetworkRulesOnNic(conn, vm.getName(), vm.getId(), nic, isFirstNic, checkBeforeApply)) { s_logger.error("Unable to apply default network rule for nic " + nic.getName() + " for VM " + vm.getName()); return false; } isFirstNic = false; } } return true; } /** * Function to apply default network rules for a NIC * @param conn * @param vmName * @param vmId * @param nic * @param isFirstNic * @param checkBeforeApply * @return */ public boolean applyDefaultNetworkRulesOnNic(final Connect conn, final String vmName, final Long vmId, final NicTO nic, boolean isFirstNic, boolean checkBeforeApply) { final List<String> nicSecIps = nic.getNicSecIps(); String secIpsStr; final StringBuilder sb = new StringBuilder(); if (nicSecIps != null) { for (final String ip : nicSecIps) { sb.append(ip).append(SecurityGroupRulesCmd.RULE_COMMAND_SEPARATOR); } secIpsStr = sb.toString(); } else { secIpsStr = "0" + SecurityGroupRulesCmd.RULE_COMMAND_SEPARATOR; } return defaultNetworkRules(conn, vmName, nic, vmId, secIpsStr, isFirstNic, checkBeforeApply); } public boolean defaultNetworkRules(final Connect conn, final String vmName, final NicTO nic, final Long vmId, final String secIpStr, final boolean isFirstNic, final boolean checkBeforeApply) { if (!_canBridgeFirewall) { return false; } final List<InterfaceDef> intfs = getInterfaces(conn, vmName); if (intfs.size() == 0 || intfs.size() < nic.getDeviceId()) { return false; } final InterfaceDef intf = intfs.get(nic.getDeviceId()); final String brname = intf.getBrName(); final String vif = intf.getDevName(); final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("default_network_rules"); cmd.add("--vmname", vmName); cmd.add("--vmid", vmId.toString()); if (nic.getIp() != null) { cmd.add("--vmip", nic.getIp()); } if (nic.getIp6Address() != null) { cmd.add("--vmip6", nic.getIp6Address()); } cmd.add("--vmmac", nic.getMac()); cmd.add("--vif", vif); cmd.add("--brname", brname); cmd.add("--nicsecips", secIpStr); if (isFirstNic) { cmd.add("--isFirstNic"); } if (checkBeforeApply) { cmd.add("--check"); } final String result = cmd.execute(); if (result != null) { return false; } return true; } protected boolean post_default_network_rules(final Connect conn, final String vmName, final NicTO nic, final Long vmId, final InetAddress dhcpServerIp, final String hostIp, final String hostMacAddr) { if (!_canBridgeFirewall) { return false; } final List<InterfaceDef> intfs = getInterfaces(conn, vmName); if (intfs.size() < nic.getDeviceId()) { return false; } final InterfaceDef intf = intfs.get(nic.getDeviceId()); final String brname = intf.getBrName(); final String vif = intf.getDevName(); final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("post_default_network_rules"); cmd.add("--vmname", vmName); cmd.add("--vmid", vmId.toString()); cmd.add("--vmip", nic.getIp()); cmd.add("--vmmac", nic.getMac()); cmd.add("--vif", vif); cmd.add("--brname", brname); if (dhcpServerIp != null) { cmd.add("--dhcpSvr", dhcpServerIp.getHostAddress()); } cmd.add("--hostIp", hostIp); cmd.add("--hostMacAddr", hostMacAddr); final String result = cmd.execute(); if (result != null) { return false; } return true; } public boolean configureDefaultNetworkRulesForSystemVm(final Connect conn, final String vmName) { if (!_canBridgeFirewall) { return false; } final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("default_network_rules_systemvm"); cmd.add("--vmname", vmName); cmd.add("--localbrname", _linkLocalBridgeName); final String result = cmd.execute(); if (result != null) { return false; } return true; } public boolean addNetworkRules(final String vmName, final String vmId, final String guestIP, final String guestIP6, final String sig, final String seq, final String mac, final String rules, final String vif, final String brname, final String secIps) { if (!_canBridgeFirewall) { return false; } final String newRules = rules.replace(" ", ";"); final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("add_network_rules"); cmd.add("--vmname", vmName); cmd.add("--vmid", vmId); cmd.add("--vmip", guestIP); if (StringUtils.isNotBlank(guestIP6)) { cmd.add("--vmip6", guestIP6); } cmd.add("--sig", sig); cmd.add("--seq", seq); cmd.add("--vmmac", mac); cmd.add("--vif", vif); cmd.add("--brname", brname); cmd.add("--nicsecips", secIps); if (newRules != null && !newRules.isEmpty()) { cmd.add("--rules", newRules); } final String result = cmd.execute(); if (result != null) { return false; } return true; } public boolean configureNetworkRulesVMSecondaryIP(final Connect conn, final String vmName, final String vmMac, final String secIp, final String action) { if (!_canBridgeFirewall) { return false; } final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("network_rules_vmSecondaryIp"); cmd.add("--vmname", vmName); cmd.add("--vmmac", vmMac); cmd.add("--nicsecips", secIp); cmd.add("--action=" + action); final String result = cmd.execute(); if (result != null) { return false; } return true; } public boolean cleanupRules() { if (!_canBridgeFirewall) { return false; } final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("cleanup_rules"); final String result = cmd.execute(); if (result != null) { return false; } return true; } public String getRuleLogsForVms() { final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("get_rule_logs_for_vms"); final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser(); final String result = cmd.execute(parser); if (result == null) { return parser.getLine(); } return null; } private HashMap<String, Pair<Long, Long>> syncNetworkGroups(final long id) { final HashMap<String, Pair<Long, Long>> states = new HashMap<String, Pair<Long, Long>>(); final String result = getRuleLogsForVms(); s_logger.trace("syncNetworkGroups: id=" + id + " got: " + result); final String[] rulelogs = result != null ? result.split(";") : new String[0]; for (final String rulesforvm : rulelogs) { final String[] log = rulesforvm.split(","); if (log.length != 6) { continue; } try { states.put(log[0], new Pair<Long, Long>(Long.parseLong(log[1]), Long.parseLong(log[5]))); } catch (final NumberFormatException nfe) { states.put(log[0], new Pair<Long, Long>(-1L, -1L)); } } return states; } /* online snapshot supported by enhanced qemu-kvm */ private boolean isSnapshotSupported() { final String result = executeBashScript("qemu-img --help|grep convert"); if (result != null) { return false; } else { return true; } } public Pair<Double, Double> getNicStats(final String nicName) { return new Pair<Double, Double>(readDouble(nicName, "rx_bytes"), readDouble(nicName, "tx_bytes")); } static double readDouble(final String nicName, final String fileName) { final String path = "/sys/class/net/" + nicName + "/statistics/" + fileName; try { return Double.parseDouble(FileUtils.readFileToString(new File(path))); } catch (final IOException ioe) { s_logger.warn("Failed to read the " + fileName + " for " + nicName + " from " + path, ioe); return 0.0; } } private String prettyVersion(final long version) { final long major = version / 1000000; final long minor = version % 1000000 / 1000; final long release = version % 1000000 % 1000; return major + "." + minor + "." + release; } @Override public void setName(final String name) { // TODO Auto-generated method stub } @Override public void setConfigParams(final Map<String, Object> params) { // TODO Auto-generated method stub } @Override public Map<String, Object> getConfigParams() { // TODO Auto-generated method stub return null; } @Override public int getRunLevel() { // TODO Auto-generated method stub return 0; } @Override public void setRunLevel(final int level) { // TODO Auto-generated method stub } public HypervisorType getHypervisorType(){ return _hypervisorType; } public String mapRbdDevice(final KVMPhysicalDisk disk){ final KVMStoragePool pool = disk.getPool(); //Check if rbd image is already mapped final String[] splitPoolImage = disk.getPath().split("/"); String device = Script.runSimpleBashScript("rbd showmapped | grep \""+splitPoolImage[0]+"[ ]*"+splitPoolImage[1]+"\" | grep -o \"[^ ]*[ ]*$\""); if(device == null) { //If not mapped, map and return mapped device Script.runSimpleBashScript("rbd map " + disk.getPath() + " --id " + pool.getAuthUserName()); device = Script.runSimpleBashScript("rbd showmapped | grep \""+splitPoolImage[0]+"[ ]*"+splitPoolImage[1]+"\" | grep -o \"[^ ]*[ ]*$\""); } return device; } public List<Ternary<String, Boolean, String>> cleanVMSnapshotMetadata(Domain dm) throws LibvirtException { s_logger.debug("Cleaning the metadata of vm snapshots of vm " + dm.getName()); List<Ternary<String, Boolean, String>> vmsnapshots = new ArrayList<Ternary<String, Boolean, String>>(); if (dm.snapshotNum() == 0) { return vmsnapshots; } String currentSnapshotName = null; try { DomainSnapshot snapshotCurrent = dm.snapshotCurrent(); String snapshotXML = snapshotCurrent.getXMLDesc(); snapshotCurrent.free(); DocumentBuilder builder; try { builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(snapshotXML)); Document doc = builder.parse(is); Element rootElement = doc.getDocumentElement(); currentSnapshotName = getTagValue("name", rootElement); } catch (ParserConfigurationException e) { s_logger.debug(e.toString()); } catch (SAXException e) { s_logger.debug(e.toString()); } catch (IOException e) { s_logger.debug(e.toString()); } } catch (LibvirtException e) { s_logger.debug("Fail to get the current vm snapshot for vm: " + dm.getName() + ", continue"); } int flags = 2; // VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY = 2 String[] snapshotNames = dm.snapshotListNames(); Arrays.sort(snapshotNames); for (String snapshotName: snapshotNames) { DomainSnapshot snapshot = dm.snapshotLookupByName(snapshotName); Boolean isCurrent = (currentSnapshotName != null && currentSnapshotName.equals(snapshotName)) ? true: false; vmsnapshots.add(new Ternary<String, Boolean, String>(snapshotName, isCurrent, snapshot.getXMLDesc())); } for (String snapshotName: snapshotNames) { DomainSnapshot snapshot = dm.snapshotLookupByName(snapshotName); snapshot.delete(flags); // clean metadata of vm snapshot } return vmsnapshots; } private static String getTagValue(String tag, Element eElement) { NodeList nlList = eElement.getElementsByTagName(tag).item(0).getChildNodes(); Node nValue = nlList.item(0); return nValue.getNodeValue(); } public void restoreVMSnapshotMetadata(Domain dm, String vmName, List<Ternary<String, Boolean, String>> vmsnapshots) { s_logger.debug("Restoring the metadata of vm snapshots of vm " + vmName); for (Ternary<String, Boolean, String> vmsnapshot: vmsnapshots) { String snapshotName = vmsnapshot.first(); Boolean isCurrent = vmsnapshot.second(); String snapshotXML = vmsnapshot.third(); s_logger.debug("Restoring vm snapshot " + snapshotName + " on " + vmName + " with XML:\n " + snapshotXML); try { int flags = 1; // VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE = 1 if (isCurrent) { flags += 2; // VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT = 2 } dm.snapshotCreateXML(snapshotXML, flags); } catch (LibvirtException e) { s_logger.debug("Failed to restore vm snapshot " + snapshotName + ", continue"); continue; } } } public String getHostDistro() { return _hostDistro; } public boolean isHostSecured() { // Test for host certificates final File confFile = PropertiesUtil.findConfigFile(KeyStoreUtils.AGENT_PROPSFILE); if (confFile == null || !confFile.exists() || !Paths.get(confFile.getParent(), KeyStoreUtils.CERT_FILENAME).toFile().exists()) { return false; } // Test for libvirt TLS configuration try { new Connect(String.format("qemu+tls://%s/system", _privateIp)); } catch (final LibvirtException ignored) { return false; } return true; } public boolean isSecureMode(String bootMode) { if (StringUtils.isNotBlank(bootMode) && "secure".equalsIgnoreCase(bootMode)) { return true; } return false; } }
kvm: fix wrong VM CPU usage (#4381)
plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
kvm: fix wrong VM CPU usage (#4381)
<ide><path>lugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java <ide> import org.libvirt.LibvirtException; <ide> import org.libvirt.MemoryStatistic; <ide> import org.libvirt.Network; <del>import org.libvirt.NodeInfo; <ide> import org.w3c.dom.Document; <ide> import org.w3c.dom.Element; <ide> import org.w3c.dom.Node; <ide> elapsedTime = now.getTimeInMillis() - oldStats._timestamp.getTimeInMillis(); <ide> double utilization = (info.cpuTime - oldStats._usedTime) / ((double)elapsedTime * 1000000); <ide> <del> final NodeInfo node = conn.nodeInfo(); <del> utilization = utilization / node.cpus; <add> utilization = utilization / info.nrVirtCpu; <ide> if (utilization > 0) { <ide> stats.setCPUUtilization(utilization * 100); <ide> }
JavaScript
mit
7fcfd9b4f8192b112f81d00872e40cfc59bde185
0
aurbano/resource-path
import test from 'ava'; import resource from '../index'; test('Returns a valid simple URL', t => { const input = '/path/to/resource'; const output = '/path/to/resource'; t.is(resource(input), output); }); test('Returns a URL with all params', t => { const input = '/path/:param1/resource/:param2'; const inputParams = { param1: 'one', param2: '123', }; const output = '/path/one/resource/123'; t.is(resource(input, inputParams), output); }); test('Returns a URL with some params', t => { const input = '/path/:param1/resource/:param2'; const inputParams = { param1: 'one', }; const output = '/path/one/resource'; t.is(resource(input, inputParams), output); }); test('Returns a URL with no params', t => { const input = '/path'; const inputParams = { }; const output = '/path'; t.is(resource(input, inputParams), output); }); test('Not allow "hasOwnProperty" as param', t => { const input = '/path/:hasOwnProperty'; try { resource(input); t.fail('Should have thrown an exception'); } catch (e) { t.is(e.message, 'badname'); t.pass(); } }); test('Returns full URL', t => { const input = 'https://example.com/path/:id/end'; const inputParams = { id: 123, }; const output = 'https://example.com/path/123/end'; t.is(resource(input, inputParams), output); }); test('Returns full IPv6 URL', t => { const input = 'http://[2001:db8:1f70::999:de8:7648:6e8]:100/path/:id/end'; const inputParams = { id: 123, }; const output = 'http://[2001:db8:1f70::999:de8:7648:6e8]:100/path/123/end'; t.is(resource(input, inputParams), output); }); test('Returns query parameters', t => { const input = '/path?id=:id&another=:two&third=hello'; const inputParams = { id: 123, two: 'something', }; const output = '/path?id=123&another=something&third=hello'; t.is(resource(input, inputParams), output); }); test('Remove trailing slash', t => { const input = '/path/to/:resource/something'; const output = '/path/to/something'; t.is(resource(input), output); });
tests/index.test.js
import test from 'ava'; import resource from '../index'; test('Returns a valid simple URL', t => { const input = '/path/to/resource'; const output = '/path/to/resource'; t.is(resource(input), output); }); test('Returns a URL with all params', t => { const input = '/path/:param1/resource/:param2'; const inputParams = { param1: 'one', param2: '123', }; const output = '/path/one/resource/123'; t.is(resource(input, inputParams), output); }); test('Returns a URL with some params', t => { const input = '/path/:param1/resource/:param2'; const inputParams = { param1: 'one', }; const output = '/path/one/resource'; t.is(resource(input, inputParams), output); }); test('Returns a URL with no params', t => { const input = '/path'; const inputParams = { }; const output = '/path'; t.is(resource(input, inputParams), output); });
improve testing coverage
tests/index.test.js
improve testing coverage
<ide><path>ests/index.test.js <ide> <ide> t.is(resource(input, inputParams), output); <ide> }); <add> <add>test('Not allow "hasOwnProperty" as param', t => { <add> const input = '/path/:hasOwnProperty'; <add> <add> try { <add> resource(input); <add> t.fail('Should have thrown an exception'); <add> } catch (e) { <add> t.is(e.message, 'badname'); <add> t.pass(); <add> } <add>}); <add> <add>test('Returns full URL', t => { <add> const input = 'https://example.com/path/:id/end'; <add> const inputParams = { <add> id: 123, <add> }; <add> const output = 'https://example.com/path/123/end'; <add> <add> t.is(resource(input, inputParams), output); <add>}); <add> <add>test('Returns full IPv6 URL', t => { <add> const input = 'http://[2001:db8:1f70::999:de8:7648:6e8]:100/path/:id/end'; <add> const inputParams = { <add> id: 123, <add> }; <add> const output = 'http://[2001:db8:1f70::999:de8:7648:6e8]:100/path/123/end'; <add> <add> t.is(resource(input, inputParams), output); <add>}); <add> <add>test('Returns query parameters', t => { <add> const input = '/path?id=:id&another=:two&third=hello'; <add> const inputParams = { <add> id: 123, <add> two: 'something', <add> }; <add> const output = '/path?id=123&another=something&third=hello'; <add> <add> t.is(resource(input, inputParams), output); <add>}); <add> <add>test('Remove trailing slash', t => { <add> const input = '/path/to/:resource/something'; <add> const output = '/path/to/something'; <add> <add> t.is(resource(input), output); <add>});
Java
mit
error: pathspec 'src/com/codingbat/array2/package-info.java' did not match any file(s) known to git
374ade9f82382e0b8eff5e2fd6be2e8254fa73c6
1
antalpeti/CodingBat
/** * Contains solutions to the Array-2 section. */ package com.codingbat.array2;
src/com/codingbat/array2/package-info.java
Add package documentation.
src/com/codingbat/array2/package-info.java
Add package documentation.
<ide><path>rc/com/codingbat/array2/package-info.java <add>/** <add> * Contains solutions to the Array-2 section. <add> */ <add>package com.codingbat.array2;
Java
mit
f1b1665e9f7ccff5a7f284f945887a26811346dc
0
navinpai/OSMT2013
package org.iiitb.os.os_proj; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); System.out.println("Merge Conflict"); } }
src/main/java/org/iiitb/os/os_proj/App.java
package org.iiitb.os.os_proj; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); System.out.println("Testing egit out"); } }
resolving merge conflict
src/main/java/org/iiitb/os/os_proj/App.java
resolving merge conflict
<ide><path>rc/main/java/org/iiitb/os/os_proj/App.java <ide> public static void main( String[] args ) <ide> { <ide> System.out.println( "Hello World!" ); <del> System.out.println("Testing egit out"); <add> System.out.println("Merge Conflict"); <ide> } <ide> }
Java
apache-2.0
186072502815a2bf6008a300881136826fedc1b1
0
ceylon/ceylon,ceylon/ceylon,ceylon/ceylon,ceylon/ceylon,ceylon/ceylon
/* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * 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 General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * 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 distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.eclipse.ceylon.compiler.java.test; import org.eclipse.ceylon.ant.AntToolTests; import org.eclipse.ceylon.ceylondoc.test.CeylonDocToolTests; import org.eclipse.ceylon.compiler.java.codegen.NamingTests; import org.eclipse.ceylon.compiler.java.test.annotations.AnnotationsTests; import org.eclipse.ceylon.compiler.java.test.bc.BcTests; import org.eclipse.ceylon.compiler.java.test.cargeneration.CarGenerationTests; import org.eclipse.ceylon.compiler.java.test.cmr.CMRHTTPTests; import org.eclipse.ceylon.compiler.java.test.cmr.CMRTests; import org.eclipse.ceylon.compiler.java.test.compat.CompatTests; import org.eclipse.ceylon.compiler.java.test.expression.ExpressionTests; import org.eclipse.ceylon.compiler.java.test.expression.ExpressionTests2; import org.eclipse.ceylon.compiler.java.test.expression.comprehensions.ComprehensionTests; import org.eclipse.ceylon.compiler.java.test.expression.ref.StaticRefTests; import org.eclipse.ceylon.compiler.java.test.fordebug.SourcePositionsTests; import org.eclipse.ceylon.compiler.java.test.fordebug.TraceTests; import org.eclipse.ceylon.compiler.java.test.interop.InteropTests; import org.eclipse.ceylon.compiler.java.test.issues.IssuesTests_0000_0499; import org.eclipse.ceylon.compiler.java.test.issues.IssuesTests_0500_0999; import org.eclipse.ceylon.compiler.java.test.issues.IssuesTests_1000_1499; import org.eclipse.ceylon.compiler.java.test.issues.IssuesTests_1500_1999; import org.eclipse.ceylon.compiler.java.test.issues.IssuesTests_2000_2499; import org.eclipse.ceylon.compiler.java.test.issues.IssuesTests_5500_5999; import org.eclipse.ceylon.compiler.java.test.issues.IssuesTests_6000_6499; import org.eclipse.ceylon.compiler.java.test.issues.PackageIssuesTests; import org.eclipse.ceylon.compiler.java.test.language.LanguageSuite; import org.eclipse.ceylon.compiler.java.test.languagesatisfaction.LanguageSatisfactionSuite; import org.eclipse.ceylon.compiler.java.test.metamodel.MetamodelTests; import org.eclipse.ceylon.compiler.java.test.misc.MiscTests; import org.eclipse.ceylon.compiler.java.test.model.ModelLoaderTests; import org.eclipse.ceylon.compiler.java.test.model.TypeParserTests; import org.eclipse.ceylon.compiler.java.test.model.ValueTypeTests; import org.eclipse.ceylon.compiler.java.test.nativecode.NativeTests; import org.eclipse.ceylon.compiler.java.test.quoting.QuotingTests; import org.eclipse.ceylon.compiler.java.test.recovery.RecoveryTests; import org.eclipse.ceylon.compiler.java.test.reporting.ReportingTests; import org.eclipse.ceylon.compiler.java.test.runtime.RuntimeSuite; import org.eclipse.ceylon.compiler.java.test.statement.OptimizationTests; import org.eclipse.ceylon.compiler.java.test.statement.StatementTests; import org.eclipse.ceylon.compiler.java.test.statement.TryCatchTests; import org.eclipse.ceylon.compiler.java.test.structure.ConstructorTests; import org.eclipse.ceylon.compiler.java.test.structure.SerializableTests; import org.eclipse.ceylon.compiler.java.test.structure.StaticTests; import org.eclipse.ceylon.compiler.java.test.structure.StructureTests; import org.eclipse.ceylon.compiler.java.test.structure.StructureTests2; import org.eclipse.ceylon.compiler.java.test.structure.StructureTests3; import org.eclipse.ceylon.compiler.java.test.structure.ee.EeTests; import org.eclipse.ceylon.launcher.test.BootstrapTests; import org.eclipse.ceylon.tools.TopLevelToolTests; import org.eclipse.ceylon.tools.test.CompilerToolsTests; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ ExpressionTests.class, ExpressionTests2.class, StructureTests.class, StructureTests2.class, StructureTests3.class, SerializableTests.class, CMRHTTPTests.class, IssuesTests_0000_0499.class, IssuesTests_0500_0999.class, IssuesTests_1000_1499.class, IssuesTests_1500_1999.class, IssuesTests_2000_2499.class, IssuesTests_5500_5999.class, IssuesTests_6000_6499.class, NamingTests.class, StaticTests.class, ConstructorTests.class, AnnotationsTests.class, InteropTests.class, ModelLoaderTests.class, ValueTypeTests.class, PackageIssuesTests.class, RecoveryTests.class, StatementTests.class, OptimizationTests.class, TryCatchTests.class, TypeParserTests.class, QuotingTests.class, ComprehensionTests.class, StaticRefTests.class, NativeTests.class, EeTests.class, MiscTests.class, CeylonDocToolTests.class, CompilerToolsTests.class, CMRTests.class, RuntimeSuite.class, MetamodelTests.class, LanguageSatisfactionSuite.class, LanguageSuite.class, BcTests.class, CompatTests.class, AntToolTests.class, TraceTests.class, CarGenerationTests.class, ReportingTests.class, SourcePositionsTests.class, BootstrapTests.class, TopLevelToolTests.class, // Unable to run due to OOMs // IntegrationTests.class, }) public class AllCompilerTests { }
compiler-java/test/src/org/eclipse/ceylon/compiler/java/test/AllCompilerTests.java
/* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * 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 General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * 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 distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.eclipse.ceylon.compiler.java.test; import org.eclipse.ceylon.ant.AntToolTests; import org.eclipse.ceylon.ceylondoc.test.CeylonDocToolTests; import org.eclipse.ceylon.compiler.java.codegen.NamingTests; import org.eclipse.ceylon.compiler.java.test.annotations.AnnotationsTests; import org.eclipse.ceylon.compiler.java.test.bc.BcTests; import org.eclipse.ceylon.compiler.java.test.cargeneration.CarGenerationTests; import org.eclipse.ceylon.compiler.java.test.cmr.CMRHTTPTests; import org.eclipse.ceylon.compiler.java.test.cmr.CMRTests; import org.eclipse.ceylon.compiler.java.test.compat.CompatTests; import org.eclipse.ceylon.compiler.java.test.expression.ExpressionTests; import org.eclipse.ceylon.compiler.java.test.expression.ExpressionTests2; import org.eclipse.ceylon.compiler.java.test.expression.comprehensions.ComprehensionTests; import org.eclipse.ceylon.compiler.java.test.expression.ref.StaticRefTests; import org.eclipse.ceylon.compiler.java.test.fordebug.SourcePositionsTests; import org.eclipse.ceylon.compiler.java.test.fordebug.TraceTests; import org.eclipse.ceylon.compiler.java.test.interop.InteropTests; import org.eclipse.ceylon.compiler.java.test.issues.IssuesTests_0000_0499; import org.eclipse.ceylon.compiler.java.test.issues.IssuesTests_0500_0999; import org.eclipse.ceylon.compiler.java.test.issues.IssuesTests_1000_1499; import org.eclipse.ceylon.compiler.java.test.issues.IssuesTests_1500_1999; import org.eclipse.ceylon.compiler.java.test.issues.IssuesTests_2000_2499; import org.eclipse.ceylon.compiler.java.test.issues.IssuesTests_5500_5999; import org.eclipse.ceylon.compiler.java.test.issues.IssuesTests_6000_6499; import org.eclipse.ceylon.compiler.java.test.issues.PackageIssuesTests; import org.eclipse.ceylon.compiler.java.test.language.LanguageSuite; import org.eclipse.ceylon.compiler.java.test.languagesatisfaction.LanguageSatisfactionSuite; import org.eclipse.ceylon.compiler.java.test.metamodel.MetamodelTests; import org.eclipse.ceylon.compiler.java.test.misc.MiscTests; import org.eclipse.ceylon.compiler.java.test.model.ModelLoaderTests; import org.eclipse.ceylon.compiler.java.test.model.TypeParserTests; import org.eclipse.ceylon.compiler.java.test.model.ValueTypeTests; import org.eclipse.ceylon.compiler.java.test.nativecode.NativeTests; import org.eclipse.ceylon.compiler.java.test.quoting.QuotingTests; import org.eclipse.ceylon.compiler.java.test.recovery.RecoveryTests; import org.eclipse.ceylon.compiler.java.test.reporting.ReportingTests; import org.eclipse.ceylon.compiler.java.test.runtime.RuntimeSuite; import org.eclipse.ceylon.compiler.java.test.statement.OptimizationTests; import org.eclipse.ceylon.compiler.java.test.statement.StatementTests; import org.eclipse.ceylon.compiler.java.test.statement.TryCatchTests; import org.eclipse.ceylon.compiler.java.test.structure.ConstructorTests; import org.eclipse.ceylon.compiler.java.test.structure.SerializableTests; import org.eclipse.ceylon.compiler.java.test.structure.StaticTests; import org.eclipse.ceylon.compiler.java.test.structure.StructureTests; import org.eclipse.ceylon.compiler.java.test.structure.StructureTests2; import org.eclipse.ceylon.compiler.java.test.structure.StructureTests3; import org.eclipse.ceylon.compiler.java.test.structure.ee.EeTests; import org.eclipse.ceylon.launcher.test.BootstrapTests; import org.eclipse.ceylon.tools.TopLevelToolTests; import org.eclipse.ceylon.tools.test.CompilerToolsTests; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ ExpressionTests.class, ExpressionTests2.class, StructureTests.class, StructureTests2.class, StructureTests3.class, SerializableTests.class, CMRHTTPTests.class, IssuesTests_0000_0499.class, IssuesTests_0500_0999.class, IssuesTests_1000_1499.class, IssuesTests_1500_1999.class, IssuesTests_2000_2499.class, IssuesTests_5500_5999.class, IssuesTests_6000_6499.class, MiscTests.class, CeylonDocToolTests.class, CompilerToolsTests.class, NamingTests.class, StaticTests.class, ConstructorTests.class, AnnotationsTests.class, InteropTests.class, ModelLoaderTests.class, ValueTypeTests.class, PackageIssuesTests.class, RecoveryTests.class, StatementTests.class, OptimizationTests.class, TryCatchTests.class, TypeParserTests.class, QuotingTests.class, CMRTests.class, RuntimeSuite.class, MetamodelTests.class, LanguageSatisfactionSuite.class, LanguageSuite.class, BcTests.class, CompatTests.class, ComprehensionTests.class, StaticRefTests.class, AntToolTests.class, TraceTests.class, CarGenerationTests.class, ReportingTests.class, SourcePositionsTests.class, NativeTests.class, BootstrapTests.class, EeTests.class, TopLevelToolTests.class, // Unable to run due to OOMs // IntegrationTests.class, }) public class AllCompilerTests { }
change order of tests
compiler-java/test/src/org/eclipse/ceylon/compiler/java/test/AllCompilerTests.java
change order of tests
<ide><path>ompiler-java/test/src/org/eclipse/ceylon/compiler/java/test/AllCompilerTests.java <ide> IssuesTests_2000_2499.class, <ide> IssuesTests_5500_5999.class, <ide> IssuesTests_6000_6499.class, <del> MiscTests.class, <del> CeylonDocToolTests.class, <del> CompilerToolsTests.class, <del> <ide> NamingTests.class, <ide> StaticTests.class, <ide> ConstructorTests.class, <ide> TryCatchTests.class, <ide> TypeParserTests.class, <ide> QuotingTests.class, <add> ComprehensionTests.class, <add> StaticRefTests.class, <add> NativeTests.class, <add> EeTests.class, <add> <add> MiscTests.class, <add> CeylonDocToolTests.class, <add> CompilerToolsTests.class, <ide> CMRTests.class, <ide> RuntimeSuite.class, <ide> MetamodelTests.class, <ide> LanguageSuite.class, <ide> BcTests.class, <ide> CompatTests.class, <del> ComprehensionTests.class, <del> StaticRefTests.class, <ide> AntToolTests.class, <ide> TraceTests.class, <ide> CarGenerationTests.class, <ide> ReportingTests.class, <ide> SourcePositionsTests.class, <del> NativeTests.class, <ide> BootstrapTests.class, <del> EeTests.class, <ide> TopLevelToolTests.class, <ide> // Unable to run due to OOMs <ide> // IntegrationTests.class,
Java
epl-1.0
error: pathspec 'org.eclipse.scanning.api/src/org/eclipse/scanning/api/scan/ParsingException.java' did not match any file(s) known to git
2406b8a9bf270eaa20fcc1c510981b91c3033b8c
1
Mark-Booth/daq-eclipse,Mark-Booth/daq-eclipse,Mark-Booth/daq-eclipse
package org.eclipse.scanning.api.scan; public class ParsingException extends Exception { public ParsingException() { super(); // TODO Auto-generated constructor stub } public ParsingException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); // TODO Auto-generated constructor stub } public ParsingException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public ParsingException(String message) { super(message); // TODO Auto-generated constructor stub } public ParsingException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } }
org.eclipse.scanning.api/src/org/eclipse/scanning/api/scan/ParsingException.java
Added exception
org.eclipse.scanning.api/src/org/eclipse/scanning/api/scan/ParsingException.java
Added exception
<ide><path>rg.eclipse.scanning.api/src/org/eclipse/scanning/api/scan/ParsingException.java <add>package org.eclipse.scanning.api.scan; <add> <add>public class ParsingException extends Exception { <add> <add> public ParsingException() { <add> super(); <add> // TODO Auto-generated constructor stub <add> } <add> <add> public ParsingException(String message, Throwable cause, <add> boolean enableSuppression, boolean writableStackTrace) { <add> super(message, cause, enableSuppression, writableStackTrace); <add> // TODO Auto-generated constructor stub <add> } <add> <add> public ParsingException(String message, Throwable cause) { <add> super(message, cause); <add> // TODO Auto-generated constructor stub <add> } <add> <add> public ParsingException(String message) { <add> super(message); <add> // TODO Auto-generated constructor stub <add> } <add> <add> public ParsingException(Throwable cause) { <add> super(cause); <add> // TODO Auto-generated constructor stub <add> } <add> <add>}
JavaScript
mit
b16150b2f3a4dd20657880be1d5f7823f95dbc99
0
apizzimenti/isometric-features,apizzimenti/isometric-features
/** * Created by apizzimenti on 5/19/16. */ "use strict"; /** * @author Anthony Pizzimenti * * @desc Game map object. * * @param game {object} Current game instance. * @param group {object} Phaser group. * @param tileSet Tileset and corresponding JSON or tile key. * @param tileSize {number} Size of an individual tile. * @param mapSize {number} Desired map size. * @param [preferredTiles=object[]] {object[]} Array of tiles; by default, the Map class creates this for you. * @param [fog=true] {boolean} Is the fog of war on or off? * * @property game {object} Current game instance. * @property tileSet Tileset and corresponding JSON. * @property tileSize {number} Size of an individual tile. * @property mapSize {number} Set map size. * @property tileMap {sprite[]} Array of tile sprites. * @property group {object} Phaser game group. * @property blocked {number[]} Array of numbers indicating which tiles are blocked (1) and which aren't (0). * @property fog {boolean} Is the fog of war on or off? * * @class {object} Map * @this Map * @constructor */ function Map (game, group, tileSet, tileSize, mapSize, preferredTiles, fog) { var tile, tileArray = [], blockedArray = [], tiles = preferredTiles || this.createTileMap(mapSize), worldBounds = dim(tileSize, mapSize, 1), atlas_json_exists = game.cache.checkImageKey(tileSet), frame = null; this.game = game; this.tileSet = tileSet; this.tileSize = tileSize; this.mapSize = mapSize; this.group = group; this.fog = fog; if (atlas_json_exists) { this.generateMapKeys(); frame = globals.mapTileKey[3]; } else { frame = null; } for (var row = 0; row < tiles.length; row++) { tileArray[row] = []; blockedArray[row] = []; for (var col = 0; col < tiles[0].length; col++) { tile = this.game.add.isoSprite(row * this.tileSize, col * this.tileSize, 0, this.tileSet, frame, this.group); if (col > tiles.length - 2 || row < 1 || row > tiles.length - 2 || col < 1) { tile.tint = this.fog ? 0x571F57 : 0xFFFFFF; tile.blocked = true; blockedArray[row].push(0); } else { tile.blocked = false; tile.tint = this.fog ? 0x571F57 : 0xFFFFFF; blockedArray[row].push(1); } tile.discovered = this.fog ? false : true; tile.type = "tile"; tile.anchor.set(0.5, 1); tile.smoothed = false; tile.row = row; tile.col = col; tileArray[row][col] = tile; // add comparison method for tiles tile.compareTo = function (tile) { var row = this.row === tile.row, col = this.col === tile.col; if (row && col) { return true; } } } } this.game.physics.isoArcade.bounds.frontX = worldBounds; this.game.physics.isoArcade.bounds.frontY = worldBounds; this.game.physics.isoArcade.bounds.backX = 0; this.game.physics.isoArcade.bounds.backY = 0; this.tileMap = tileArray; this.blocked = blockedArray; } /** * @author Anthony Pizzimenti * * @desc Creates a size * size array with randomly assigned tiles. Can be modified to create a custom game map. * * @param size {number} Desired map size. * * @returns {sprite[]} */ Map.prototype.createTileMap = function (size) { var tileMap = []; for (var row = 0; row < size; row++) { tileMap[row] = []; for (var col = 0; col < size; col++) { var tileNum = Math.floor(Math.random() * 3); if (tileNum > 0) { tileMap[row][col] = tileNum; } else { tileMap[row][col] = 0; } } } return tileMap; }; /** * @author Anthony Pizzimenti * * @desc Generates global list of available tile keys. * * @this Map */ Map.prototype.generateMapKeys = function () { for (var frame of this.game.cache._cache.image[this.tileSet].frameData._frames) { globals.mapTileKey.push(frame.name); } };
lib/world/Map.js
/** * Created by apizzimenti on 5/19/16. */ "use strict"; /** * @author Anthony Pizzimenti * * @desc Game map object. * * @param game {object} Current game instance. * @param group {object} Phaser group. * @param tileSet Tileset and corresponding JSON. * @param tileSize {number} Size of an individual tile. * @param mapSize {number} Desired map size. * @param [preferredTiles=object[]] {object[]} Array of tiles; by default, the Map class creates this for you. * @param [fog=true] {boolean} Is the fog of war on or off? * * @property game {object} Current game instance. * @property tileSet Tileset and corresponding JSON. * @property tileSize {number} Size of an individual tile. * @property mapSize {number} Set map size. * @property tileMap {sprite[]} Array of tile sprites. * @property group {object} Phaser game group. * @property blocked {number[]} Array of numbers indicating which tiles are blocked (1) and which aren't (0). * @property fog {boolean} Is the fog of war on or off? * * @class {object} Map * @this Map * @constructor */ function Map (game, group, tileSet, tileSize, mapSize, preferredTiles, fog) { var tile, tileArray = [], blockedArray = [], tiles = preferredTiles || this.createTileMap(mapSize), worldBounds = dim(tileSize, mapSize, 1); this.game = game; this.tileSet = tileSet; this.tileSize = tileSize; this.mapSize = mapSize; this.group = group; this.fog = fog; for (var row = 0; row < tiles.length; row++) { tileArray[row] = []; blockedArray[row] = []; for (var col = 0; col < tiles[0].length; col++) { tile = this.game.add.isoSprite(row * this.tileSize, col * this.tileSize, 0, this.tileSet, globals.mapTileKey[tiles[row][col]], this.group); if (col > tiles.length - 2 || row < 1 || row > tiles.length - 2 || col < 1) { tile.tint = 0x571F57; tile.blocked = true; blockedArray[row].push(0); } else { tile.blocked = false; tile.tint = this.fog ? 0x571F57 : 0xFFFFFF; blockedArray[row].push(1); } tile.discovered = this.fog ? false : true; tile.type = "tile"; tile.anchor.set(0.5, 1); tile.smoothed = false; tile.row = row; tile.col = col; tileArray[row][col] = tile; // add comparison method for tiles tile.compareTo = function (tile) { var row = this.row === tile.row, col = this.col === tile.col; if (row && col) { return true; } } } } this.game.physics.isoArcade.bounds.frontX = worldBounds; this.game.physics.isoArcade.bounds.frontY = worldBounds; this.game.physics.isoArcade.bounds.backX = 0; this.game.physics.isoArcade.bounds.backY = 0; this.tileMap = tileArray; this.blocked = blockedArray; } /** * @author Anthony Pizzimenti * * @desc Creates a size * size array with randomly assigned tiles. Can be modified to create a custom game map. * * @param size {number} Desired map size. * * @returns {sprite[]} */ Map.prototype.createTileMap = function (size) { var tileMap = []; for (var row = 0; row < size; row++) { tileMap[row] = []; for (var col = 0; col < size; col++) { var tileNum = Math.floor(Math.random() * 3); if (tileNum > 0) { tileMap[row][col] = tileNum; } else { tileMap[row][col] = 0; } } } return tileMap; };
generate global tile keys; check Phaser global cache for existing json associations; fog of war on/off
lib/world/Map.js
generate global tile keys; check Phaser global cache for existing json associations; fog of war on/off
<ide><path>ib/world/Map.js <ide> * <ide> * @param game {object} Current game instance. <ide> * @param group {object} Phaser group. <del> * @param tileSet Tileset and corresponding JSON. <add> * @param tileSet Tileset and corresponding JSON or tile key. <ide> * @param tileSize {number} Size of an individual tile. <ide> * @param mapSize {number} Desired map size. <ide> * @param [preferredTiles=object[]] {object[]} Array of tiles; by default, the Map class creates this for you. <ide> tileArray = [], <ide> blockedArray = [], <ide> tiles = preferredTiles || this.createTileMap(mapSize), <del> worldBounds = dim(tileSize, mapSize, 1); <add> worldBounds = dim(tileSize, mapSize, 1), <add> atlas_json_exists = game.cache.checkImageKey(tileSet), <add> frame = null; <ide> <ide> this.game = game; <ide> this.tileSet = tileSet; <ide> this.mapSize = mapSize; <ide> this.group = group; <ide> this.fog = fog; <add> <add> if (atlas_json_exists) { <add> this.generateMapKeys(); <add> frame = globals.mapTileKey[3]; <add> } else { <add> frame = null; <add> } <ide> <ide> for (var row = 0; row < tiles.length; row++) { <ide> <ide> <ide> for (var col = 0; col < tiles[0].length; col++) { <ide> <del> tile = this.game.add.isoSprite(row * this.tileSize, col * this.tileSize, 0, this.tileSet, globals.mapTileKey[tiles[row][col]], this.group); <add> tile = this.game.add.isoSprite(row * this.tileSize, col * this.tileSize, 0, this.tileSet, frame, this.group); <ide> <ide> if (col > tiles.length - 2 || row < 1 || row > tiles.length - 2 || col < 1) { <del> tile.tint = 0x571F57; <add> tile.tint = this.fog ? 0x571F57 : 0xFFFFFF; <ide> tile.blocked = true; <ide> blockedArray[row].push(0); <ide> } else { <ide> <ide> return tileMap; <ide> }; <add> <add> <add>/** <add> * @author Anthony Pizzimenti <add> * <add> * @desc Generates global list of available tile keys. <add> * <add> * @this Map <add> */ <add> <add>Map.prototype.generateMapKeys = function () { <add> for (var frame of this.game.cache._cache.image[this.tileSet].frameData._frames) { <add> globals.mapTileKey.push(frame.name); <add> } <add>};
Java
apache-2.0
72f990461b426728baf7e4709229fde0e549e297
0
miyakawataku/piggybank-ltsv,miyakawataku/piggybank-ltsv,miyakawataku/piggybank-ltsv,miyakawataku/piggybank-ltsv,miyakawataku/piggybank-ltsv,miyakawataku/piggybank-ltsv
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pig.piggybank.storage; import java.util.List; import java.util.Map; import java.util.Set; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Properties; import java.util.Collections; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pig.Expression; import org.apache.pig.FileInputLoadFunc; import org.apache.pig.LoadCaster; import org.apache.pig.LoadPushDown; import org.apache.pig.ResourceStatistics; import org.apache.pig.ResourceSchema; import org.apache.pig.ResourceSchema.ResourceFieldSchema; import org.apache.pig.PigWarning; import org.apache.pig.PigException; import org.apache.pig.LoadMetadata; import org.apache.pig.bzip2r.Bzip2TextInputFormat; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigTextInputFormat; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.util.CastUtils; import org.apache.pig.impl.util.Utils; import org.apache.pig.impl.util.UDFContext; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; /** * Loader UDF for <a href="http://ltsv.org/">LTSV</a> files, * or Labeled Tab-separated Values files. * * <h3>About LTSV</h3> * * <p> * LTSV, or Labeled Tab-separated Values format is a format for log files. * LTSV is based on TSV. * Columns are separated by tab characters, * and each of columns includes a label and a value, * separated by a ":" character. * </p> * * <p> * This is an example LTSV log file. * Suppose that columns are separated by tab characters. * </p> * * <pre> * host:host1.example.org req:GET /index.html ua:Opera/9.80 * host:host1.example.org req:GET /favicon.ico ua:Opera/9.80 * host:pc.example.com req:GET /news.html ua:Mozilla/5.0 * </pre> * * <p>You can read about LTSV on <a href="http://ltsv.org/">http://ltsv.org/</a>.</p> * * <p> * You can use the UDF in two ways. * First, you can specify labels and get them as Pig fields. * Second, you can extract a map of all columns of each LTSV line. * </p> * * <h3>Extract fields from each line</h3> * * <p> * To extract fields from each line, * construct a loader function with a schema string. * </p> * * <dl> * <dt><em>Syntax</em></dt> * <dd>org.apache.pig.piggybank.storage.LTSVLoader('&lt;schema-string&gt;')</dd> * * <dt><em>Output</em></dt> * <dd>The schema of the output is specified by the argument of the constructor. * The value of a field comes from a column whoes label is equal to the field name. * If the corresponding label does not exist in the LTSV line, * the field is set to null.</dd> * </dl> * * <p> * This example script loads an LTSV file shown in the previous section, named access.log. * </p> * * <pre> * -- Parses the access log and count the number of lines * -- for each pair of the host column and the ua column. * access = LOAD 'access.log' USING org.apache.pig.piggybank.storage.LTSVLoader('host:chararray, ua:chararray'); * grouped_access = GROUP access BY (host, ua); * count_for_host_ua = FOREACH grouped_access GENERATE group.host, group.ua, COUNT(access); * * -- Prints out the result. * DUMP count_for_host_ua; * </pre> * * <p>The below text will be printed out.</p> * * <pre> * (host1.example.org,Opera/9.80,2) * (pc.example.com,Firefox/5.0,1) * </pre> * * <h3>Extract a map from each line</h3> * * <p> * To extract a map from each line, * construct a loader function without parameters. * </p> * * <dl> * <dt><em>Syntax</em></dt> * <dd>org.apache.pig.piggybank.storage.LTSVLoader()</dd> * * <dt><em>Output</em></dt> * <dd>The schema of the output is (:map[]), or an unary tuple of a map, for each LTSV row. * The key of a map is a label of the LTSV column. * The value of a map comes from characters after ":" in the LTSV column.</dd> * </dl> * * <p> * This example script loads an LTSV file shown in the previous section, named access.log. * </p> * * <pre> * -- Parses the access log and projects the user agent field. * access = LOAD 'access.log' USING org.apache.pig.piggybank.storage.LTSVLoader() AS (m); * user_agent = FOREACH access GENERATE m#'ua' AS ua; * -- Prints out the user agent for each access. * DUMP user_agent; * </pre> * * <p>The below text will be printed out.</p> * * <pre> * (Opera/9.80) * (Opera/9.80) * (Firefox/5.0) * </pre> * * <h3>Handling of malformed input</h3> * * <p> * All valid LTSV columns contain ":" to separate a field and a value. * If a column does not contain ":", the column is malformed. * </p> * * <p> * For each of malformed column, the counter * {@link PigWarning#UDF_WARNING_8} will be counted up. * This counter is printed out when the Pig job completes. * </p> * * <p> * In the mapreduce mode, the counter shall be output like below. * </p> * * <pre> * 2013-02-17 12:14:22,070 [main] WARN org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - Encountered Warning UDF_WARNING_8 10000 time(s). * </pre> * * <p> * For the first 100 of malformed columns in each task, * warning messages are written to the tasklog. * Such as: * </p> * * <pre> * 2013-02-17 12:13:42,142 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata1" does not contain ":". * 2013-02-17 12:13:42,158 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata2" does not contain ":". * 2013-02-17 12:13:42,158 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata3" does not contain ":". * 2013-02-17 12:13:42,158 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata4" does not contain ":". * 2013-02-17 12:13:42,158 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata5" does not contain ":". * 2013-02-17 12:13:42,159 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata6" does not contain ":". * 2013-02-17 12:13:42,159 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata7" does not contain ":". * 2013-02-17 12:13:42,159 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata8" does not contain ":". * 2013-02-17 12:13:42,159 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata9" does not contain ":". * ... * </pre> */ public class LTSVLoader extends FileInputLoadFunc implements LoadPushDown, LoadMetadata { /** Logger of this class. */ private static final Log LOG = LogFactory.getLog(LTSVLoader.class); /** Emitter of tuples */ private final TupleEmitter tupleEmitter; /** Length of "\t" in UTF-8. */ private static int TAB_LENGTH = 1; /** Length of ":" in UTF-8. */ private static int COLON_LENGTH = 1; /** Factory of tuples. */ private final TupleFactory tupleFactory = TupleFactory.getInstance(); /** Schema of the output of the loader, which is (:map[]). */ private static final ResourceSchema MAP_SCHEMA = new ResourceSchema(new Schema(new Schema.FieldSchema(null, DataType.MAP))); /** * An error code of an input error. * See https://cwiki.apache.org/confluence/display/PIG/PigErrorHandlingFunctionalSpecification. */ private static final int INPUT_ERROR_CODE = 6018; /** * An error message of an input error. * See https://cwiki.apache.org/confluence/display/PIG/PigErrorHandlingFunctionalSpecification. */ private static final String INPUT_ERROR_MESSAGE = "Error while reading input"; /** Underlying record reader of a text file. */ @SuppressWarnings("rawtypes") private RecordReader reader = null; /** Sequence number of the next log message, which starts from 0. */ private int warnLogSeqNum = 0; /** Max count of warning logs which will be output to the task log. */ private static final int MAX_WARN_LOG_COUNT = 100; /** Key of a property which contains Set[String] of labels to output. */ private static final String LABELS_TO_OUTPUT = "LABELS_TO_OUTPUT"; /** Key of a property which contains Set[Integer] of indexes of fields to output in a schema. */ private static final String INDEXES_TO_OUTPUT_IN_SCHEMA = "INDEXES_TO_OUTPUT_IN_SCHEMA"; /** * An error code of an internal error. * See https://cwiki.apache.org/confluence/display/PIG/PigErrorHandlingFunctionalSpecification. */ private static final int INTERNAL_ERROR_CODE = 2998; /** Location of input files. */ private String loadLocation; /** Signature of the UDF invocation, used to get UDFContext. */ private String signature; /** * Constructs a loader which extracts a tuple including a single map * for each column of an LTSV line. */ public LTSVLoader() { this.tupleEmitter = new MapTupleEmitter(); } /** * Constructs a loader which extracts a tuple including specified fields * for each column of an LTSV line. * * @param schemaString * Schema of fields to extract. * * @throws IOException * Thrown when an I/O error occurs during construction. */ public LTSVLoader(String schemaString) throws IOException { this.tupleEmitter = new FieldsTupleEmitter(schemaString); } /** * Reads an LTSV line and returns a tuple, * or returns {@code null} if the loader reaches the end of the block. * * @return * Tuple corresponding to an LTSV line, * or {@code null} if the loader reaches the end of the block. * * @throws IOException * If an I/O error occurs while reading the line. */ @Override public Tuple getNext() throws IOException { Text line = readLine(); if (line == null) { return null; } // Current line: lineBytes[0, lineLength) byte[] lineBytes = line.getBytes(); int lineLength = line.getLength(); this.tupleEmitter.startTuple(); // Reads columns. int startOfColumn = 0; while (startOfColumn <= lineLength) { int endOfColumn = findUntil((byte) '\t', lineBytes, startOfColumn, lineLength); readColumn(lineBytes, startOfColumn, endOfColumn); startOfColumn = endOfColumn + TAB_LENGTH; } return this.tupleEmitter.emitTuple(); } /** * Reads a column to the tuple emitter. */ private void readColumn(byte[] bytes, int start, int end) throws IOException { int colon = findUntil((byte) ':', bytes, start, end); boolean isLabeled = colon < end; if (! isLabeled) { warnMalformedColumn(Text.decode(bytes, start, end - start)); return; } // Label: bytes[start, colon) // Colon: bytes[colon, colon + 1) // Value: bytes[colon + 1 = startOfValue, end) String label = Text.decode(bytes, start, colon - start); int startOfValue = colon + COLON_LENGTH; this.tupleEmitter.addColumnToTuple(label, bytes, startOfValue, end); } /** * Returns the index of the first target in bytes[start, end), * or the index of the end. */ private static int findUntil(byte target, byte[] bytes, int start, int end) { for (int index = start; index < end; ++ index) { if (bytes[index] == target) { return index; } } return end; } /** Outputs a warning for a malformed column. */ private void warnMalformedColumn(String column) { String message = String.format("MalformedColumn: Column \"%s\" does not contain \":\".", column); warn(message, PigWarning.UDF_WARNING_8); // Output at most MAX_WARN_LOG_COUNT warning messages. if (this.warnLogSeqNum < MAX_WARN_LOG_COUNT) { LOG.warn(message); ++ this.warnLogSeqNum; } } /** * Reads a line from the block, * or {@code null} if the loader reaches the end of the block. */ private Text readLine() throws IOException { try { if (! this.reader.nextKeyValue()) { return null; } return (Text) this.reader.getCurrentValue(); } catch (InterruptedException exception) { throw new ExecException(INPUT_ERROR_MESSAGE, INPUT_ERROR_CODE, PigException.REMOTE_ENVIRONMENT, exception); } } /** * Constructs a tuple from columns and emits it. * * This interface is used to switch the output type between a map and fields. * * For each row, these methods are called. * * <ol> * <li>startTuple</li> * <li>addColumnToTuple * the number of tuples</li> * <li>emitTuple</li> * </ol> */ private interface TupleEmitter { /** * Notifies the start of a tuple. */ void startTuple(); /** * Adds a value from bytes[startOfValue, endOfValue), corresponding to the label, * if the columns is required for the output. * * @param label * Label of the column. * * @param bytes * Byte array including the value. * * @param startOfValue * Index a the start of the value (inclusive). * * @param endOfValue * Index a the end of the value (exclusive). */ void addColumnToTuple(String label, byte[] bytes, int startOfValue, int endOfValue) throws IOException; /** * Emits a tuple. */ Tuple emitTuple(); /** * Returns the schema of tuples. */ ResourceSchema getSchema(); /** * Notifies required fields in the script. * * <p>Delegation target from {@link LTSVLoader#pushProjection}.</p> */ RequiredFieldResponse pushProjection(RequiredFieldList requiredFieldList) throws FrontendException; } /** * Reads columns and emits a tuple with a single map field (:map[]). */ private class MapTupleEmitter implements TupleEmitter { /** Contents of the single map field. */ private Map<String, Object> map; @Override public void startTuple() { this.map = new HashMap<String, Object>(); } @Override public void addColumnToTuple(String label, byte[] bytes, int startOfValue, int endOfValue) throws IOException { if (shouldOutput(label)) { DataByteArray value = new DataByteArray(bytes, startOfValue, endOfValue); this.map.put(label, value); } } @Override public Tuple emitTuple() { return tupleFactory.newTuple(map); } /** * Returns {@code true} if the column should be output. */ private boolean shouldOutput(String label) { boolean outputsEveryColumn = (labelsToOutput() == null); return outputsEveryColumn || labelsToOutput().contains(label); } /** True if {@link labelsToOutput} is initialized. */ private boolean isProjectionInitialized; /** * Labels of columns to output, or {@code null} if all columns should be output. * This field should be accessed from {@link #labelsToOutput}. */ private Set<String> labelsToOutput; /** * Returns labels of columns to output, * or {@code null} if all columns should be output. */ private Set<String> labelsToOutput() { if (! this.isProjectionInitialized) { @SuppressWarnings("unchecked") Set<String> labels = (Set<String>) getProperties().get(LABELS_TO_OUTPUT); this.labelsToOutput = labels; LOG.debug("Labels to output: " + this.labelsToOutput); this.isProjectionInitialized = true; } return this.labelsToOutput; } @Override public ResourceSchema getSchema() { return MAP_SCHEMA; } @Override public RequiredFieldResponse pushProjection(RequiredFieldList requiredFieldList) throws FrontendException { List<RequiredField> fields = requiredFieldList.getFields(); if (fields == null || fields.isEmpty()) { LOG.debug("No fields specified as required."); return new RequiredFieldResponse(false); } if (fields.size() != 1) { String message = String.format( "The loader expects at most one field but %d fields are specified." , fields.size()); throw new FrontendException(message, INTERNAL_ERROR_CODE, PigException.BUG); } RequiredField field = fields.get(0); if (field.getIndex() != 0) { String message = String.format( "The loader produces only 1ary tuples, but the index %d is specified." , field.getIndex()); throw new FrontendException(message, INTERNAL_ERROR_CODE, PigException.BUG); } List<RequiredField> mapKeys = field.getSubFields(); if (mapKeys == null) { LOG.debug("All the labels are required."); return new RequiredFieldResponse(false); } Set<String> labels = new HashSet<String>(); for (RequiredField mapKey : mapKeys) { labels.add(mapKey.getAlias()); } getProperties().put(LABELS_TO_OUTPUT, labels); LOG.debug("Labels to output: " + labels); return new RequiredFieldResponse(true); } } /** * Reads columns and emits a tuple with fields specified * by the constructor of the load function. */ private class FieldsTupleEmitter implements TupleEmitter { // TODO note about two different types of indexes. /** Schema of tuples. */ private final ResourceSchema schema; /** Tuple to emit. */ private Tuple tuple; /** Caster of values. */ private final LoadCaster loadCaster = getLoadCaster(); /** Mapping from labels to indexes in a tuple. */ private Map<String, Integer> labelToIndexInTuple; /** Schemas of fields in a tuple. */ private List<ResourceFieldSchema> fieldSchemasInTuple; /** Set of labels which have occurred and been skipped. */ private final Set<String> skippedLabels = new HashSet<String>(); /** * Constructs an emitter with the schema. */ private FieldsTupleEmitter(String schemaString) throws IOException { Schema rawSchema = Utils.getSchemaFromString(schemaString); this.schema = new ResourceSchema(rawSchema); } @Override public void startTuple() { initOrderOfFieldsInTuple(); this.tuple = tupleFactory.newTuple(this.labelToIndexInTuple.size()); } @Override public void addColumnToTuple(String label, byte[] bytes, int startOfValue, int endOfValue) throws IOException { if (! this.labelToIndexInTuple.containsKey(label)) { logSkippedLabelAtFirstOccurrence(label); return; } int indexInTuple = this.labelToIndexInTuple.get(label); ResourceFieldSchema fieldSchema = this.fieldSchemasInTuple.get(indexInTuple); int valueLength = endOfValue - startOfValue; byte[] valueBytes = new byte[valueLength]; System.arraycopy(bytes, startOfValue, valueBytes, 0, valueLength); Object value = CastUtils.convertToType(this.loadCaster, valueBytes, fieldSchema, fieldSchema.getType()); this.tuple.set(indexInTuple, value); } /** * Initializes {@link labelsToOutput} and {@link fieldSchemasInTuple} if required. */ private void initOrderOfFieldsInTuple() { if (this.labelToIndexInTuple != null && this.fieldSchemasInTuple != null) { return; } @SuppressWarnings("unchecked") Set<Integer> indexesToOutputInSchema = (Set<Integer>) getProperties().get(INDEXES_TO_OUTPUT_IN_SCHEMA); Map<String, Integer> labelToIndexInTuple = new HashMap<String, Integer>(); List<ResourceFieldSchema> fieldSchemasInTuple = new ArrayList<ResourceFieldSchema>(); for (int indexInSchema = 0; indexInSchema < this.schema.getFields().length; ++ indexInSchema) { if (indexesToOutputInSchema == null || indexesToOutputInSchema.contains(indexInSchema)) { ResourceFieldSchema fieldSchema = this.schema.getFields()[indexInSchema]; int indexInTuple = fieldSchemasInTuple.size(); labelToIndexInTuple.put(fieldSchema.getName(), indexInTuple); fieldSchemasInTuple.add(fieldSchema); } } LOG.debug("Label -> Index: " + labelToIndexInTuple); this.labelToIndexInTuple = labelToIndexInTuple; this.fieldSchemasInTuple = fieldSchemasInTuple; } /** * Outputs the label of a skipped column to the task log at the first occurrence. */ private void logSkippedLabelAtFirstOccurrence(String label) { if (LOG.isDebugEnabled() && ! this.skippedLabels.contains(label)) { this.skippedLabels.add(label); LOG.debug("Skipped label: " + label); } } @Override public Tuple emitTuple() { return this.tuple; } @Override public ResourceSchema getSchema() { return this.schema; } @Override public RequiredFieldResponse pushProjection(RequiredFieldList requiredFieldList) { List<RequiredField> fields = requiredFieldList.getFields(); if (fields == null) { LOG.debug("No fields specified as required."); return new RequiredFieldResponse(false); } Set<Integer> indexesToOutputInSchema = new HashSet<Integer>(); for (RequiredField field : fields) { indexesToOutputInSchema.add(field.getIndex()); } getProperties().put(INDEXES_TO_OUTPUT_IN_SCHEMA, indexesToOutputInSchema); LOG.debug("Indexes of fields to output in the schema: " + indexesToOutputInSchema); return new RequiredFieldResponse(true); } } /** * Saves the RecordReader. * * @param reader * RecordReader to read LTSV lines from. * * @param split * Ignored. * */ @Override public void prepareToRead(@SuppressWarnings("rawtypes") RecordReader reader, PigSplit split) { this.reader = reader; } /** * Extracts information about which labels are required in the script. * * @param requiredFieldList * {@inheritDoc}. * * @return * {@code new RequiredFieldResponse(true)} if projection will be performed, * or {@code new RequiredFieldResponse(false)} otherwise. * * @throws FrontendException * When an unexpected internal error occurs. */ @Override public RequiredFieldResponse pushProjection(RequiredFieldList requiredFieldList) throws FrontendException { return this.tupleEmitter.pushProjection(requiredFieldList); } /** * <p>This UDF supports * {@linkplain org.apache.pig.LoadPushDown.OperatorSet#PROJECTION projection push-down}.</p> * * @return * Singleton list of * {@link org.apache.pig.LoadPushDown.OperatorSet#PROJECTION}. */ @Override public List<OperatorSet> getFeatures() { return Collections.singletonList(OperatorSet.PROJECTION); } /** * Configures the underlying input format * to read lines from {@code location}. * * @param location * Location of LTSV file(s). * * @param job * Job. * * @throws IOException * If an I/O error occurs while configuring the job. */ @Override public void setLocation(String location, Job job) throws IOException { this.loadLocation = location; FileInputFormat.setInputPaths(job, location); } /** * Makes an instance of an input format from which LTSV lines are read. * * @return * Instance of {@link PigTextInputFormat}. */ @Override public InputFormat getInputFormat() { if (loadLocation.endsWith(".bz2") || loadLocation.endsWith(".bz")) { // Bzip2TextInputFormat can split bzipped files. LOG.debug("Uses Bzip2TextInputFormat"); return new Bzip2TextInputFormat(); } else { LOG.debug("Uses PigTextInputFormat"); return new PigTextInputFormat(); } } /** * Saves the signature of the current invocation of the UDF. * * @param signature * Signature of the current invocation of the UDF. */ @Override public void setUDFContextSignature(String signature) { this.signature = signature; } /** * Returns the properties related with the current invocation of the UDF. */ private Properties getProperties() { return UDFContext.getUDFContext().getUDFProperties( getClass(), new String[] { this.signature }); } // Methods for LoadMetadata /** * Does nothing, * because the loader does not know about partitioning. * * @param partitionFilter * Ignored. */ @Override public void setPartitionFilter(Expression partitionFilter) { } /** * Returns {@code null}, * because the loader does not know about partitioning. * * @param location * Ignored. * * @param job * Ignored. * * @return * null. */ @Override public String[] getPartitionKeys(String location, Job job) { return null; } /** * Returns {@code null}, because no statistics are available. * * @param location * Ignored. * * @param job * Ignored. * * @return * null. */ @Override public ResourceStatistics getStatistics(String location, Job job) { return null; } /** * Returns the schema of the output of the loader. * * @param location * Ignored, because the schema is constant. * * @param job * Ignored, because the schema is constant. * * @return * Schema of the output of the loader. */ @Override public ResourceSchema getSchema(String location, Job job) { return this.tupleEmitter.getSchema(); } } // vim: et sw=4 sts=4
contrib/piggybank/java/src/main/java/org/apache/pig/piggybank/storage/LTSVLoader.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pig.piggybank.storage; import java.util.List; import java.util.Map; import java.util.Set; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Properties; import java.util.Collections; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pig.Expression; import org.apache.pig.FileInputLoadFunc; import org.apache.pig.LoadCaster; import org.apache.pig.LoadPushDown; import org.apache.pig.ResourceStatistics; import org.apache.pig.ResourceSchema; import org.apache.pig.ResourceSchema.ResourceFieldSchema; import org.apache.pig.PigWarning; import org.apache.pig.PigException; import org.apache.pig.LoadMetadata; import org.apache.pig.bzip2r.Bzip2TextInputFormat; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigTextInputFormat; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.util.CastUtils; import org.apache.pig.impl.util.Utils; import org.apache.pig.impl.util.UDFContext; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; /** * Loader UDF for <a href="http://ltsv.org/">LTSV</a> files, * or Labeled Tab-separated Values files. * * <h3>About LTSV</h3> * * <p> * LTSV, or Labeled Tab-separated Values format is a format for log files. * LTSV is based on TSV. * Columns are separated by tab characters, * and each of columns includes a label and a value, * separated by a ":" character. * </p> * * <p> * This is an example LTSV log file. * Suppose that columns are separated by tab characters. * </p> * * <pre> * host:host1.example.org req:GET /index.html ua:Opera/9.80 * host:host1.example.org req:GET /favicon.ico ua:Opera/9.80 * host:pc.example.com req:GET /news.html ua:Mozilla/5.0 * </pre> * * <p>You can read about LTSV on <a href="http://ltsv.org/">http://ltsv.org/</a>.</p> * * <p> * You can use the UDF in two ways. * First, you can specify labels and get them as Pig fields. * Second, you can extract a map of all columns of each LTSV line. * </p> * * <h3>Extract fields from each line</h3> * * <p> * To extract fields from each line, * construct a loader function with a schema string. * </p> * * <dl> * <dt><em>Syntax</em></dt> * <dd>org.apache.pig.piggybank.storage.LTSVLoader('&lt;schema-string&gt;')</dd> * * <dt><em>Output</em></dt> * <dd>The schema of the output is specified by the argument of the constructor. * The value of a field comes from a column whoes label is equal to the field name. * If the corresponding label does not exist in the LTSV line, * the field is set to null.</dd> * </dl> * * <p> * This example script loads an LTSV file shown in the previous section, named access.log. * </p> * * <pre> * -- Parses the access log and count the number of lines * -- for each pair of the host column and the ua column. * access = LOAD 'access.log' USING org.apache.pig.piggybank.storage.LTSVLoader('host:chararray, ua:chararray'); * grouped_access = GROUP access BY (host, ua); * count_for_host_ua = FOREACH grouped_access GENERATE group.host, group.ua, COUNT(access); * * -- Prints out the result. * DUMP count_for_host_ua; * </pre> * * <p>The below text will be printed out.</p> * * <pre> * (host1.example.org,Opera/9.80,2) * (pc.example.com,Firefox/5.0,1) * </pre> * * <h3>Extract a map from each line</h3> * * <p> * To extract a map from each line, * construct a loader function without parameters. * </p> * * <dl> * <dt><em>Syntax</em></dt> * <dd>org.apache.pig.piggybank.storage.LTSVLoader()</dd> * * <dt><em>Output</em></dt> * <dd>The schema of the output is (:map[]), or an unary tuple of a map, for each LTSV row. * The key of a map is a label of the LTSV column. * The value of a map comes from characters after ":" in the LTSV column.</dd> * </dl> * * <p> * This example script loads an LTSV file shown in the previous section, named access.log. * </p> * * <pre> * -- Parses the access log and projects the user agent field. * access = LOAD 'access.log' USING org.apache.pig.piggybank.storage.LTSVLoader() AS (m); * user_agent = FOREACH access GENERATE m#'ua' AS ua; * -- Prints out the user agent for each access. * DUMP user_agent; * </pre> * * <p>The below text will be printed out.</p> * * <pre> * (Opera/9.80) * (Opera/9.80) * (Firefox/5.0) * </pre> * * <h3>Handling of malformed input</h3> * * <p> * All valid LTSV columns contain ":" to separate a field and a value. * If a column does not contain ":", the column is malformed. * </p> * * <p> * For each of malformed column, the counter * {@link PigWarning#UDF_WARNING_8} will be counted up. * This counter is printed out when the Pig job completes. * </p> * * <p> * In the mapreduce mode, the counter shall be output like below. * </p> * * <pre> * 2013-02-17 12:14:22,070 [main] WARN org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - Encountered Warning UDF_WARNING_8 10000 time(s). * </pre> * * <p> * For the first 100 of malformed columns in each task, * warning messages are written to the tasklog. * Such as: * </p> * * <pre> * 2013-02-17 12:13:42,142 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata1" does not contain ":". * 2013-02-17 12:13:42,158 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata2" does not contain ":". * 2013-02-17 12:13:42,158 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata3" does not contain ":". * 2013-02-17 12:13:42,158 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata4" does not contain ":". * 2013-02-17 12:13:42,158 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata5" does not contain ":". * 2013-02-17 12:13:42,159 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata6" does not contain ":". * 2013-02-17 12:13:42,159 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata7" does not contain ":". * 2013-02-17 12:13:42,159 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata8" does not contain ":". * 2013-02-17 12:13:42,159 WARN org.apache.pig.piggybank.storage.LTSVLoader: MalformedColumn: Column "errordata9" does not contain ":". * ... * </pre> */ public class LTSVLoader extends FileInputLoadFunc implements LoadPushDown, LoadMetadata { /** Logger of this class. */ private static final Log LOG = LogFactory.getLog(LTSVLoader.class); /** Emitter of tuples */ private final TupleEmitter tupleEmitter; /** Length of "\t" in UTF-8. */ private static int TAB_LENGTH = 1; /** Length of ":" in UTF-8. */ private static int COLON_LENGTH = 1; /** Factory of tuples. */ private final TupleFactory tupleFactory = TupleFactory.getInstance(); /** Schema of the output of the loader, which is (:map[]). */ private static final ResourceSchema MAP_SCHEMA = new ResourceSchema(new Schema(new Schema.FieldSchema(null, DataType.MAP))); /** * An error code of an input error. * See https://cwiki.apache.org/confluence/display/PIG/PigErrorHandlingFunctionalSpecification. */ private static final int INPUT_ERROR_CODE = 6018; /** * An error message of an input error. * See https://cwiki.apache.org/confluence/display/PIG/PigErrorHandlingFunctionalSpecification. */ private static final String INPUT_ERROR_MESSAGE = "Error while reading input"; /** Underlying record reader of a text file. */ @SuppressWarnings("rawtypes") private RecordReader reader = null; /** Sequence number of the next log message, which starts from 0. */ private int warnLogSeqNum = 0; /** Max count of warning logs which will be output to the task log. */ private static final int MAX_WARN_LOG_COUNT = 100; /** Key of a property which contains Set[String] of labels to output. */ private static final String LABELS_TO_OUTPUT = "LABELS_TO_OUTPUT"; /** Key of a property which contains Set[Integer] of indexes of fields to output in a schema. */ private static final String INDEXES_TO_OUTPUT_IN_SCHEMA = "INDEXES_TO_OUTPUT_IN_SCHEMA"; /** * An error code of an internal error. * See https://cwiki.apache.org/confluence/display/PIG/PigErrorHandlingFunctionalSpecification. */ private static final int INTERNAL_ERROR_CODE = 2998; /** Location of input files. */ private String loadLocation; /** Signature of the UDF invocation, used to get UDFContext. */ private String signature; /** * Constructs a loader which extracts a tuple including a single map * for each column of an LTSV line. */ public LTSVLoader() { this.tupleEmitter = new MapTupleEmitter(); } /** * Constructs a loader which extracts a tuple including specified fields * for each column of an LTSV line. * * @param schemaString * Schema of fields to extract. * * @throws IOException * Thrown when an I/O error occurs during construction. */ public LTSVLoader(String schemaString) throws IOException { this.tupleEmitter = new FieldsTupleEmitter(schemaString); } /** * Reads an LTSV line and returns a tuple, * or returns {@code null} if the loader reaches the end of the block. * * @return * Tuple corresponding to an LTSV line, * or {@code null} if the loader reaches the end of the block. * * @throws IOException * If an I/O error occurs while reading the line. */ @Override public Tuple getNext() throws IOException { Text line = readLine(); if (line == null) { return null; } // Current line: lineBytes[0, lineLength) byte[] lineBytes = line.getBytes(); int lineLength = line.getLength(); // Reads an map entry from each column. int startOfColumn = 0; while (startOfColumn <= lineLength) { int endOfColumn = findUntil((byte) '\t', lineBytes, startOfColumn, lineLength); readColumn(lineBytes, startOfColumn, endOfColumn); startOfColumn = endOfColumn + TAB_LENGTH; } return this.tupleEmitter.emitTuple(); } /** * Reads a column to the tuple emitter. */ private void readColumn(byte[] bytes, int start, int end) throws IOException { int colon = findUntil((byte) ':', bytes, start, end); boolean isLabeled = colon < end; if (! isLabeled) { warnMalformedColumn(Text.decode(bytes, start, end - start)); return; } // Label: bytes[start, colon) // Colon: bytes[colon, colon + 1) // Value: bytes[colon + 1 = startOfValue, end) String label = Text.decode(bytes, start, colon - start); int startOfValue = colon + COLON_LENGTH; this.tupleEmitter.addColumn(label, bytes, startOfValue, end); } /** * Returns the index of the first target in bytes[start, end), * or the index of the end. */ private static int findUntil(byte target, byte[] bytes, int start, int end) { for (int index = start; index < end; ++ index) { if (bytes[index] == target) { return index; } } return end; } /** Outputs a warning for a malformed column. */ private void warnMalformedColumn(String column) { String message = String.format("MalformedColumn: Column \"%s\" does not contain \":\".", column); warn(message, PigWarning.UDF_WARNING_8); // Output at most MAX_WARN_LOG_COUNT warning messages. if (this.warnLogSeqNum < MAX_WARN_LOG_COUNT) { LOG.warn(message); ++ this.warnLogSeqNum; } } /** * Reads a line from the block, * or {@code null} if the loader reaches the end of the block. */ private Text readLine() throws IOException { try { if (! this.reader.nextKeyValue()) { return null; } return (Text) this.reader.getCurrentValue(); } catch (InterruptedException exception) { throw new ExecException(INPUT_ERROR_MESSAGE, INPUT_ERROR_CODE, PigException.REMOTE_ENVIRONMENT, exception); } } /** * Constructs a tuple from columns and emits it. * * This interface is used to switch the output type between a map and fields. */ private interface TupleEmitter { /** * Adds a value from bytes[startOfValue, endOfValue), corresponding to the label, * if the columns is required for the output. * * @param label * Label of the column. * * @param bytes * Byte array including the value. * * @param startOfValue * Index a the start of the value (inclusive). * * @param endOfValue * Index a the end of the value (exclusive). */ void addColumn(String label, byte[] bytes, int startOfValue, int endOfValue) throws IOException; /** * Emits a tuple and reinitialize the state of the emitter. */ Tuple emitTuple(); /** * Returns the schema of tuples. */ ResourceSchema getSchema(); /** * Notifies required fields in the script. * * <p>Delegation target from {@link LTSVLoader#pushProjection}.</p> */ RequiredFieldResponse pushProjection(RequiredFieldList requiredFieldList) throws FrontendException; } /** * Reads columns and emits a tuple with a single map field (:map[]). */ private class MapTupleEmitter implements TupleEmitter { /** Contents of the single map field. */ private Map<String, Object> map = new HashMap<String, Object>(); @Override public void addColumn(String label, byte[] bytes, int startOfValue, int endOfValue) throws IOException { if (shouldOutput(label)) { DataByteArray value = new DataByteArray(bytes, startOfValue, endOfValue); this.map.put(label, value); } } @Override public Tuple emitTuple() { Tuple tuple = tupleFactory.newTuple(map); this.map = new HashMap<String, Object>(); return tuple; } /** * Returns {@code true} if the column should be output. */ private boolean shouldOutput(String label) { boolean outputsEveryColumn = (labelsToOutput() == null); return outputsEveryColumn || labelsToOutput().contains(label); } /** True if {@link labelsToOutput} is initialized. */ private boolean isProjectionInitialized; /** * Labels of columns to output, or {@code null} if all columns should be output. * This field should be accessed from {@link #labelsToOutput}. */ private Set<String> labelsToOutput; /** * Returns labels of columns to output, * or {@code null} if all columns should be output. */ private Set<String> labelsToOutput() { if (! this.isProjectionInitialized) { @SuppressWarnings("unchecked") Set<String> labels = (Set<String>) getProperties().get(LABELS_TO_OUTPUT); this.labelsToOutput = labels; LOG.debug("Labels to output: " + this.labelsToOutput); this.isProjectionInitialized = true; } return this.labelsToOutput; } @Override public ResourceSchema getSchema() { return MAP_SCHEMA; } @Override public RequiredFieldResponse pushProjection(RequiredFieldList requiredFieldList) throws FrontendException { List<RequiredField> fields = requiredFieldList.getFields(); if (fields == null || fields.isEmpty()) { LOG.debug("No fields specified as required."); return new RequiredFieldResponse(false); } if (fields.size() != 1) { String message = String.format( "The loader expects at most one field but %d fields are specified." , fields.size()); throw new FrontendException(message, INTERNAL_ERROR_CODE, PigException.BUG); } RequiredField field = fields.get(0); if (field.getIndex() != 0) { String message = String.format( "The loader produces only 1ary tuples, but the index %d is specified." , field.getIndex()); throw new FrontendException(message, INTERNAL_ERROR_CODE, PigException.BUG); } List<RequiredField> mapKeys = field.getSubFields(); if (mapKeys == null) { LOG.debug("All the labels are required."); return new RequiredFieldResponse(false); } Set<String> labels = new HashSet<String>(); for (RequiredField mapKey : mapKeys) { labels.add(mapKey.getAlias()); } getProperties().put(LABELS_TO_OUTPUT, labels); LOG.debug("Labels to output: " + labels); return new RequiredFieldResponse(true); } } /** * Reads columns and emits a tuple with fields specified * by the constructor of the load function. */ private class FieldsTupleEmitter implements TupleEmitter { // TODO note about two different types of indexes. /** Schema of tuples. */ private final ResourceSchema schema; /** Tuple to emit. */ private Tuple tuple; /** Caster of values. */ private final LoadCaster loadCaster = getLoadCaster(); /** Mapping from labels to indexes in a tuple. */ private Map<String, Integer> labelToIndexInTuple; /** Schemas of fields in a tuple. */ private List<ResourceFieldSchema> fieldSchemasInTuple; /** Set of labels which have occurred and been skipped. */ private final Set<String> skippedLabels = new HashSet<String>(); /** * Constructs an emitter with the schema. */ private FieldsTupleEmitter(String schemaString) throws IOException { Schema rawSchema = Utils.getSchemaFromString(schemaString); this.schema = new ResourceSchema(rawSchema); // FIXME exact size of tuples is fieldSchemasInTuple.size(), but not initialized yet. this.tuple = tupleFactory.newTuple(this.schema.getFields().length); } @Override public void addColumn(String label, byte[] bytes, int startOfValue, int endOfValue) throws IOException { initOrderOfFieldsInTuple(); if (! this.labelToIndexInTuple.containsKey(label)) { logSkippedLabelAtFirstOccurrence(label); return; } int indexInTuple = this.labelToIndexInTuple.get(label); ResourceFieldSchema fieldSchema = this.fieldSchemasInTuple.get(indexInTuple); int valueLength = endOfValue - startOfValue; byte[] valueBytes = new byte[valueLength]; System.arraycopy(bytes, startOfValue, valueBytes, 0, valueLength); Object value = CastUtils.convertToType(this.loadCaster, valueBytes, fieldSchema, fieldSchema.getType()); this.tuple.set(indexInTuple, value); } /** * Initializes {@link labelsToOutput} and {@link fieldSchemasInTuple} if required. */ private void initOrderOfFieldsInTuple() { if (this.labelToIndexInTuple != null && this.fieldSchemasInTuple != null) { return; } @SuppressWarnings("unchecked") Set<Integer> indexesToOutputInSchema = (Set<Integer>) getProperties().get(INDEXES_TO_OUTPUT_IN_SCHEMA); Map<String, Integer> labelToIndexInTuple = new HashMap<String, Integer>(); List<ResourceFieldSchema> fieldSchemasInTuple = new ArrayList<ResourceFieldSchema>(); for (int indexInSchema = 0; indexInSchema < this.schema.getFields().length; ++ indexInSchema) { if (indexesToOutputInSchema == null || indexesToOutputInSchema.contains(indexInSchema)) { ResourceFieldSchema fieldSchema = this.schema.getFields()[indexInSchema]; int indexInTuple = fieldSchemasInTuple.size(); labelToIndexInTuple.put(fieldSchema.getName(), indexInTuple); fieldSchemasInTuple.add(fieldSchema); } } LOG.debug("Label -> Index: " + labelToIndexInTuple); this.labelToIndexInTuple = labelToIndexInTuple; this.fieldSchemasInTuple = fieldSchemasInTuple; } /** * Outputs the label of a skipped column to the task log at the first occurrence. */ private void logSkippedLabelAtFirstOccurrence(String label) { if (LOG.isDebugEnabled() && ! this.skippedLabels.contains(label)) { this.skippedLabels.add(label); LOG.debug("Skipped label: " + label); } } @Override public Tuple emitTuple() { Tuple resultTuple = this.tuple; this.tuple = tupleFactory.newTuple(this.labelToIndexInTuple.size()); return resultTuple; } @Override public ResourceSchema getSchema() { return this.schema; } @Override public RequiredFieldResponse pushProjection(RequiredFieldList requiredFieldList) { List<RequiredField> fields = requiredFieldList.getFields(); if (fields == null) { LOG.debug("No fields specified as required."); return new RequiredFieldResponse(false); } Set<Integer> indexesToOutputInSchema = new HashSet<Integer>(); for (RequiredField field : fields) { indexesToOutputInSchema.add(field.getIndex()); } getProperties().put(INDEXES_TO_OUTPUT_IN_SCHEMA, indexesToOutputInSchema); LOG.debug("Indexes of fields to output in the schema: " + indexesToOutputInSchema); return new RequiredFieldResponse(true); } } /** * Saves the RecordReader. * * @param reader * RecordReader to read LTSV lines from. * * @param split * Ignored. * */ @Override public void prepareToRead(@SuppressWarnings("rawtypes") RecordReader reader, PigSplit split) { this.reader = reader; } /** * Extracts information about which labels are required in the script. * * @param requiredFieldList * {@inheritDoc}. * * @return * {@code new RequiredFieldResponse(true)} if projection will be performed, * or {@code new RequiredFieldResponse(false)} otherwise. * * @throws FrontendException * When an unexpected internal error occurs. */ @Override public RequiredFieldResponse pushProjection(RequiredFieldList requiredFieldList) throws FrontendException { return this.tupleEmitter.pushProjection(requiredFieldList); } /** * <p>This UDF supports * {@linkplain org.apache.pig.LoadPushDown.OperatorSet#PROJECTION projection push-down}.</p> * * @return * Singleton list of * {@link org.apache.pig.LoadPushDown.OperatorSet#PROJECTION}. */ @Override public List<OperatorSet> getFeatures() { return Collections.singletonList(OperatorSet.PROJECTION); } /** * Configures the underlying input format * to read lines from {@code location}. * * @param location * Location of LTSV file(s). * * @param job * Job. * * @throws IOException * If an I/O error occurs while configuring the job. */ @Override public void setLocation(String location, Job job) throws IOException { this.loadLocation = location; FileInputFormat.setInputPaths(job, location); } /** * Makes an instance of an input format from which LTSV lines are read. * * @return * Instance of {@link PigTextInputFormat}. */ @Override public InputFormat getInputFormat() { if (loadLocation.endsWith(".bz2") || loadLocation.endsWith(".bz")) { // Bzip2TextInputFormat can split bzipped files. LOG.debug("Uses Bzip2TextInputFormat"); return new Bzip2TextInputFormat(); } else { LOG.debug("Uses PigTextInputFormat"); return new PigTextInputFormat(); } } /** * Saves the signature of the current invocation of the UDF. * * @param signature * Signature of the current invocation of the UDF. */ @Override public void setUDFContextSignature(String signature) { this.signature = signature; } /** * Returns the properties related with the current invocation of the UDF. */ private Properties getProperties() { return UDFContext.getUDFContext().getUDFProperties( getClass(), new String[] { this.signature }); } // Methods for LoadMetadata /** * Does nothing, * because the loader does not know about partitioning. * * @param partitionFilter * Ignored. */ @Override public void setPartitionFilter(Expression partitionFilter) { } /** * Returns {@code null}, * because the loader does not know about partitioning. * * @param location * Ignored. * * @param job * Ignored. * * @return * null. */ @Override public String[] getPartitionKeys(String location, Job job) { return null; } /** * Returns {@code null}, because no statistics are available. * * @param location * Ignored. * * @param job * Ignored. * * @return * null. */ @Override public ResourceStatistics getStatistics(String location, Job job) { return null; } /** * Returns the schema of the output of the loader. * * @param location * Ignored, because the schema is constant. * * @param job * Ignored, because the schema is constant. * * @return * Schema of the output of the loader. */ @Override public ResourceSchema getSchema(String location, Job job) { return this.tupleEmitter.getSchema(); } } // vim: et sw=4 sts=4
Improves the state transition while reading a row
contrib/piggybank/java/src/main/java/org/apache/pig/piggybank/storage/LTSVLoader.java
Improves the state transition while reading a row
<ide><path>ontrib/piggybank/java/src/main/java/org/apache/pig/piggybank/storage/LTSVLoader.java <ide> byte[] lineBytes = line.getBytes(); <ide> int lineLength = line.getLength(); <ide> <del> // Reads an map entry from each column. <add> this.tupleEmitter.startTuple(); <add> <add> // Reads columns. <ide> int startOfColumn = 0; <ide> while (startOfColumn <= lineLength) { <ide> int endOfColumn = findUntil((byte) '\t', lineBytes, startOfColumn, lineLength); <ide> <ide> String label = Text.decode(bytes, start, colon - start); <ide> int startOfValue = colon + COLON_LENGTH; <del> this.tupleEmitter.addColumn(label, bytes, startOfValue, end); <add> this.tupleEmitter.addColumnToTuple(label, bytes, startOfValue, end); <ide> } <ide> <ide> /** <ide> * Constructs a tuple from columns and emits it. <ide> * <ide> * This interface is used to switch the output type between a map and fields. <add> * <add> * For each row, these methods are called. <add> * <add> * <ol> <add> * <li>startTuple</li> <add> * <li>addColumnToTuple * the number of tuples</li> <add> * <li>emitTuple</li> <add> * </ol> <ide> */ <ide> private interface TupleEmitter { <add> <add> /** <add> * Notifies the start of a tuple. <add> */ <add> void startTuple(); <ide> <ide> /** <ide> * Adds a value from bytes[startOfValue, endOfValue), corresponding to the label, <ide> * @param endOfValue <ide> * Index a the end of the value (exclusive). <ide> */ <del> void addColumn(String label, byte[] bytes, int startOfValue, int endOfValue) <add> void addColumnToTuple(String label, byte[] bytes, int startOfValue, int endOfValue) <ide> throws IOException; <ide> <ide> /** <del> * Emits a tuple and reinitialize the state of the emitter. <add> * Emits a tuple. <ide> */ <ide> Tuple emitTuple(); <ide> <ide> private class MapTupleEmitter implements TupleEmitter { <ide> <ide> /** Contents of the single map field. */ <del> private Map<String, Object> map = new HashMap<String, Object>(); <del> <del> @Override <del> public void addColumn(String label, byte[] bytes, int startOfValue, int endOfValue) <add> private Map<String, Object> map; <add> <add> @Override <add> public void startTuple() { <add> this.map = new HashMap<String, Object>(); <add> } <add> <add> @Override <add> public void addColumnToTuple(String label, byte[] bytes, int startOfValue, int endOfValue) <ide> throws IOException { <ide> if (shouldOutput(label)) { <ide> DataByteArray value = new DataByteArray(bytes, startOfValue, endOfValue); <ide> <ide> @Override <ide> public Tuple emitTuple() { <del> Tuple tuple = tupleFactory.newTuple(map); <del> this.map = new HashMap<String, Object>(); <del> return tuple; <add> return tupleFactory.newTuple(map); <ide> } <ide> <ide> /** <ide> private FieldsTupleEmitter(String schemaString) throws IOException { <ide> Schema rawSchema = Utils.getSchemaFromString(schemaString); <ide> this.schema = new ResourceSchema(rawSchema); <del> // FIXME exact size of tuples is fieldSchemasInTuple.size(), but not initialized yet. <del> this.tuple = tupleFactory.newTuple(this.schema.getFields().length); <del> } <del> <del> @Override <del> public void addColumn(String label, byte[] bytes, int startOfValue, int endOfValue) <add> } <add> <add> @Override <add> public void startTuple() { <add> initOrderOfFieldsInTuple(); <add> this.tuple = tupleFactory.newTuple(this.labelToIndexInTuple.size()); <add> } <add> <add> @Override <add> public void addColumnToTuple(String label, byte[] bytes, int startOfValue, int endOfValue) <ide> throws IOException { <del> initOrderOfFieldsInTuple(); <del> <ide> if (! this.labelToIndexInTuple.containsKey(label)) { <ide> logSkippedLabelAtFirstOccurrence(label); <ide> return; <ide> <ide> @Override <ide> public Tuple emitTuple() { <del> Tuple resultTuple = this.tuple; <del> this.tuple = tupleFactory.newTuple(this.labelToIndexInTuple.size()); <del> return resultTuple; <add> return this.tuple; <ide> } <ide> <ide> @Override
JavaScript
mit
417617661b6d77719e3933913e9f392df1cbf1df
0
pcanz/MyWord,pcanz/MyWord
// -- x-markup: Browser interface to markit framework --------------------------- /* The MIT License (MIT) * * Copyright (c) 2016 Rick Workman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // mark this script for the load handler ;(document.currentScript || (function () { var scripts = document.getElementsByTagName('script') // for old browsers not supporting currentScript return scripts[scripts.length - 1] })()).id = 'x-markitApp' // add load event handler window.addEventListener('load', function (ev) { // Note: doesn't overwrite other handlers like "onload = function(ev) {..} " var globals = window // some semblance of environment independence var target = ev.currentTarget.document // ; console.log("onload:",target,"\n",this) var appScriptURL = target.querySelector('script#x-markitApp').getAttribute('src') var appName = (appScriptURL.lastIndexOf('/') === -1) ? appScriptURL : appScriptURL.substring(appScriptURL.lastIndexOf('/') + 1) var versionString = appName + ' Version: 0.1ß7' var errorLabel = ['*** ', appName, ' error: '].join('') var mimeType = 'text/x-markup.' // in practice: text/x-markup.transformName var workerName = 'markit.js' var lingoName = 'x-markup.mmk' var errorMessage = function (msgComponents) { return errorLabel + msgComponents.join('') } // errorMessage(msgComponents) // handle load event console.log(navigator.appCodeName, navigator.appVersion) console.log(versionString) var MarkIt = initWorker(appScriptURL.replace(appName, workerName)) // make Web Worker object which does all the work var noArrow = false try { eval('(() => true)') } catch (err) { noArrow = true } // just a test, not used console.log(['Arrow functions are ', noArrow ? 'NOT ' : '', 'supported in this browser.'].join('')) // append relative .mmk path to location.href directory to get full URL for markit() var lingoURL = globals.location.href.substring(0, globals.location.href.lastIndexOf('/') + 1) + appScriptURL.replace(appName, lingoName) var request = new globals.XMLHttpRequest() request.open('GET', lingoURL, true) request.onload = function () { var status = 0 status = ((status === 0) ? this.status : status) // ; console.log("status=",status) if ((status === 200 || status === 0)) { MarkIt.queue.push({document: document, elemID: null}) try { MarkIt.postMessage([lingoURL, 'metamark', this.responseText]) // ; console.log("posting ",type," ",tElement," to ",document) } catch (err) { MarkIt.queue.shift() // remove queue item // log message to console, no x-markup.mmk to use, so ignore console.error(errorMessage([err.message, ' posting metamark content to ', document])) } } else { console.log('Error reading', lingoURL, ' code=', status) } processScripts() } request.onerror = function () { console.log('Error reading', lingoURL, ' code= 404') processScripts() } request.send() // ; console.log(request.status,url,"["+request.responseText.length+"]") // helper functions function initWorker (workerURL) { // init Worker object and return it var worker = new globals.Worker(workerURL) // worker is co-located with this script file worker.onmessage = function (content) { updateDOM(content.data) } worker.onerror = function (err) { // if this happens, it's a bug (uncaught exception in Worker?) var eMsg = errorMessage(['Worker ', err.message]) var element = null if (worker.queue.length > 0) { element = updateDOM( ['<pre><mark style="color:blue"><br>', eMsg, '<br></mark></pre>'].join('')) // ES6: `<mark style='color:blue'>${eMsg}</mark><br>` } console.error(eMsg, (element) ? ' translating ' + element : '') } worker.queue = [] // queue to keep "job" details for async post-processing worker.nxtID = 1 return worker } // initWorker() function processScripts () { if (target) { var dmScripts = target.body.querySelectorAll(["script[type^='", mimeType, "']"].join('')) var typeValue for (var s = 0; s < dmScripts.length; s++) { typeValue = dmScripts[s].getAttribute('type') post(target, typeValue.substring(mimeType.length), dmScripts[s]) } // for } } // processScripts() function post (document, type, element) { // post message to MarkIt with structured text object if (type) { element.setAttribute('hidden', 'hidden') // hide element while rewriting it var source = element.textContent var tElement, srcURL if (element.tagName.toLowerCase() === 'script') { // if a <script> element, convert it to empty <div> srcURL = element.getAttribute('src') if (srcURL) { element.removeAttribute('src') if (srcURL === '?') { var docURL = document.documentURI srcURL = docURL.substring(0, docURL.lastIndexOf('.')) + '.myw' if (document.title.length === 0) { document.title = srcURL.substring(srcURL.lastIndexOf('/') + 1) } } var request = new globals.XMLHttpRequest() request.open('GET', srcURL, true) request.onload = function () { var status = 0 status = ((status === 0) ? this.status : status) // ; console.log("status=",status) if ((status === 200 || status === 0)) { element.textContent = this.responseText post(document, type, element) // re-post with loaded content } else { element.parentNode.replaceChild(errElement(srcURL, status), element) } } request.onerror = function () { element.parentNode.replaceChild(errElement(srcURL, 404), element) } request.send() // ; console.log(request.status,url,"["+request.responseText.length+"]") return } tElement = document.createElement('div') var attrs = element.attributes for (var a = 0; a < attrs.length; a++) { tElement.setAttribute(attrs[ a ].name, attrs[ a ].value) } element.parentNode.replaceChild(tElement, element) } else { tElement = element } if (!tElement.getAttribute('id')) { // if element doesn't have an ID, manufacture one tElement.setAttribute('id', 'FWmsg' + MarkIt.nxtID++) } MarkIt.queue.push({document: document, elemID: tElement.getAttribute('id')}) try { MarkIt.postMessage([document.location.href, type, source]) // ; console.log("posting ",type," ",tElement," to ",document) } catch (err) { MarkIt.queue.shift() // remove queue item element.removeAttribute('hidden') // make element visible again // leave element alone, error message in console console.error(errorMessage([err.message, ' posting ', type, ' content to ', document])) } } function errElement (url, status) { var preElement = document.createElement('pre') preElement.innerHTML = ['<mark style="color:blue"><br/>Error reading "', url, '": status=', status, '<br></mark>'].join('') return preElement } // errElement(url, status) } // post(document,type,element) function updateDOM (content) { // update DOM with Worker result, returns modified element var item = MarkIt.queue.shift() // get work item var document = item.document // retrieve window // and element. Note special case - elemID == null, means loading x-markup.mmk var element = (item.elemID) ? document.getElementById(item.elemID) : document.body // console.log("receiving "+((content)?"content":"null")+" for ",element) if (content && (content.length > 0)) { try { if (element.tagName.toLowerCase() === 'body') { // reply from x-markup.mmk translation var temp = document.createElement('div') // will be garbage collected temp.innerHTML = content var tempChildren = temp.children var bodyFirst = element.firstChild for (var i = 0; i < tempChildren.length; i++) { element.insertBefore(tempChildren[i], bodyFirst) } return element } else { element.innerHTML = content element.removeAttribute('hidden') // have to render before adjusting size if (document.defaultView.frameElement) adjustSize(document.defaultView.frameElement) var scripts = element.getElementsByTagName('script') // have to clone & replace scripts to get them executed var script, newscript for (var s = 0; s < scripts.length; s++) { script = scripts[s] newscript = document.createElement('script') newscript.innerHTML = script.innerHTML for (var ai = 0; ai < script.attributes.length; ai++) { newscript.setAttribute(script.attributes[ai].name, script.attributes[ai].value) } script.parentElement.replaceChild(newscript, script) } } dispatchUpdate(document, element) // invoke listeners for update } catch (err) { element.removeAttribute('hidden') // something failed, just make element visible again console.error(errorMessage([err.message, ' updating ', element])) } } else element.removeAttribute('hidden') // no new content, make it visible return element } // updateDOM(content) function adjustSize (iframe) { // adjust size of iframe element after DOM modified var document = iframe.contentDocument.documentElement // console.log("New frame size",document.scrollHeight," : ",iframe) // Wait for images - sometimes necessary, particularly on Chrome var images = document.getElementsByTagName('img') // ES6: for (var img of images) { for (var i = 0; i < images.length; i++) { var img = images[i] // ; console.log("Checking ", img, img.complete) if (!img.complete) { // ; console.log("Waiting for ",img) img.onload = function () { this.onload = null adjustSize(iframe) } img.onerror = function () { this.onerror = null adjustSize(iframe) } return } } // Some browsers require height setting to be deferred (render complete?) // Messages would be faster than setTimeout(fn,0) but effieciency not a big issue for this // Other alternatives: setImmediate(fn) (not standard) or requestAnimationFrame(fn) (normal usage?) setTimeout(function () { iframe.style.height = (document.scrollHeight) + 'px' // console.log("New frame style.height",iframe.style.height," : ",iframe) var parentFrame = iframe.ownerDocument.defaultView.frameElement if (parentFrame) adjustSize(parentFrame) }, 0) } // adjustSize(iframe) /* ****************** Start of "feature" listeners ********************* */ var listeners = [] // listener events dispatched to listeners whenever MarkIt returns new HTML content var addListener = function (listener) { if (typeof listener === 'function') { for (var l = 0; l < listeners.length; l++) { if (listeners[ l ] === listener) return // listener already registered, return } listeners.push(listener) // new listener, add it } else console.error(errorMessage(['Invalid listener: ', listener])) } // addListener(listener) var removeListener = function (listener) { for (var l = 0; l < listeners.length; l++) { if (listeners[l] === listener) { listeners.splice(l, 1) break } } } // removeListener(listener) var dispatchUpdate = function (document, element) { // called from updateDOM() for (var l = 0; l < listeners.length; l++) listeners[l].call(null, document, element) } // dispatchUpdate(document, element) // Math plug-in : use MathJax if loaded function hasMathML () { // returns true if platform has native MathML support var hasMML = false if (document.createElement) { var div = document.createElement('div') div.style.position = 'absolute' div.style.top = div.style.left = 0 div.style.visibility = 'hidden' div.style.width = div.style.height = 'auto' div.style.fontFamily = 'serif' div.style.lineheight = 'normal' div.innerHTML = '<math><mfrac><mi>xx</mi><mi>yy</mi></mfrac></math>' document.body.appendChild(div) hasMML = (div.offsetHeight > div.offsetWidth) // proper fraction rendering has height > width document.body.removeChild(div) } return hasMML } var noMML = !hasMathML() // not used in this version console.log(['MML is ', noMML ? 'NOT ' : '', 'supported in this browser.'].join('')) if (/* noMML && */ (typeof globals.MathJax !== 'undefined')) { // if (MathJax) add it feature listeners addListener(function (document, element) { globals.MathJax.Hub.Queue([ 'Typeset', globals.MathJax.Hub, element ]) }) } /* Polyfill for scoped styles - plagerized from (https://github.com/thomaspark/scoper) Copyright (c) 2015 Thomas Park Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ function scopeIt (document, element) { if (!(MarkIt.scopeID)) MarkIt.scopeID = 0 var styles = element.querySelectorAll('style[scoped]') if (styles.length > 0) { var head = document.head || document.getElementsByTagName('head')[0] var newstyle = document.createElement('style') var csses = '' for (var i = 0; i < styles.length; i++) { var style = styles[i] var css = style.innerHTML if (css) { var parent = style.parentNode // don't process any immediate decendants of body element (shouldn't wrap body element) if (parent.tagName.toLowerCase() !== 'body') { var id = 'scoper-' + (MarkIt.scopeID++) var prefix = '#' + id var wrapper = document.createElement('span') wrapper.id = id var grandparent = parent.parentNode grandparent.replaceChild(wrapper, parent) wrapper.appendChild(parent) style.parentNode.removeChild(style) csses = csses + scoper(css, prefix) } } } if (newstyle.styleSheet) { newstyle.styleSheet.cssText = csses } else { newstyle.appendChild(document.createTextNode(csses)) } head.appendChild(newstyle) } function scoper (css, prefix) { var re = new RegExp('([^\\r\\n,{}]+)(,(?=[^}]*{)|\\s*{)', 'g') // escaped '\' - issue for scoper? css = css.replace(re, function (g0, g1, g2) { if (g1.match(/^\s*(@media|@keyframes|to|from)/)) { return g1 + g2 } g1 = g1.replace(/^(\s*)/, '$1' + prefix + ' ') return g1 + g2 }) return css } // scoper(css, prefix) } // scopeIt(document, element) var noscoped = !('scoped' in document.createElement('style')) console.log(['Scoped styles are ', noscoped ? 'NOT ' : '', 'supported in this browser.'].join('')) if (noscoped) addListener(scopeIt) // add scopeIt to feature listeners // Document feature to build table of contents // Triggered by generation of // <script type='application/x-markit.buildTOC'> // The <script> element content is the transform name for the generated toc data and the range of headers to collect, // e.g., contentTable 1..4 - collects <h1> to <h4> elements in the document for the transform contentTable // The generated TOC entries are of the form: levelNumber\theaderID\theaderContent // which is posted back to FirstWord to generate HTML to replace <script> using the transform specified // All attributes in <script> element are preserved in the <div> element which replaces it (see post()). function buildTOC (document, element) { try { var tocScripts = element.querySelectorAll(['script[type="', mimeType, 'buildTOC"]'].join('')) // console.log("tocScripts=",tocScripts) var tocScript, tocSpec, hmin, hmax, headers, tocContent, header, level for (var s = 0; s < tocScripts.length; s++) { tocScript = tocScripts[s] tocSpec = tocScript.textContent.match(/^\s*(\S+)\s*(\d*)\s*(?:..\s*(\d*))?/) // ; console.log("tocSpec=", tocSpec) if (tocSpec) { hmin = (tocSpec[2]) ? parseInt(tocSpec[2]) : 0 hmax = (tocSpec[3]) ? parseInt(tocSpec[3]) : 99 if (hmin > hmax) { var temp = hmin; hmin = hmax; hmax = temp // ; console.log("hmin=",hmin,"hmax=",hmax) } headers = document.querySelectorAll('*[id^="hdr:"]') // ; console.log("headers=", headers) tocContent = [] for (var h = 0; h < headers.length; h++) { header = headers[h] level = header.parentElement.tagName.match(/[hH](\d)/) if (level) { level = parseInt(level[1], 10) if ((level >= hmin) && (level <= hmax)) { tocContent.push(level, '\t', header.id, '\t', header.textContent.trim(), '\n') } } } // for tocScript.textContent = tocContent.join('') // ; console.log('tocScript=', tocScript) post(document, tocSpec[1], tocScript) } } // for } catch (err) { console.error('buildTOC error=', err) } } // buildTOC(document, element) //addListener(buildTOC) // add buildTOC to feature listeners } // event handler ) // Toggle fullscreen handler document.addEventListener('keydown', function (e) { if (e.keyCode === 13) { toggleFullScreen() } function toggleFullScreen () { if (!document.fullscreenElement && // alternative standard method !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) { // current working methods if (document.documentElement.requestFullscreen) { document.documentElement.requestFullscreen() } else if (document.documentElement.msRequestFullscreen) { document.documentElement.msRequestFullscreen() } else if (document.documentElement.mozRequestFullScreen) { document.documentElement.mozRequestFullScreen() } else if (document.documentElement.webkitRequestFullscreen) { document.documentElement.webkitRequestFullscreen(window.Element.ALLOW_KEYBOARD_INPUT) } } else { if (document.exitFullscreen) { document.exitFullscreen() } else if (document.msExitFullscreen) { document.msExitFullscreen() } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen() } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen() } } } }, false)
lib/x-markup.js
// -- x-markup: Browser interface to markit framework --------------------------- /* The MIT License (MIT) * * Copyright (c) 2016 Rick Workman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // mark this script for the load handler ;(document.currentScript || (function () { var scripts = document.getElementsByTagName('script') // for old browsers not supporting currentScript return scripts[scripts.length - 1] })()).id = 'x-markitApp' // add load event handler window.addEventListener('load', function (ev) { // Note: doesn't overwrite other handlers like "onload = function(ev) {..} " var globals = window // some semblance of environment independence var target = ev.currentTarget.document // ; console.log("onload:",target,"\n",this) var appScriptURL = target.querySelector('script#x-markitApp').getAttribute('src') var appName = (appScriptURL.lastIndexOf('/') === -1) ? appScriptURL : appScriptURL.substring(appScriptURL.lastIndexOf('/') + 1) var versionString = appName + ' Version: 0.1ß7' var errorLabel = ['*** ', appName, ' error: '].join('') var mimeType = 'text/x-markup.' // in practice: text/x-markup.transformName var workerName = 'markit.js' var lingoName = 'x-markup.mmk' var errorMessage = function (msgComponents) { return errorLabel + msgComponents.join('') } // errorMessage(msgComponents) // handle load event console.log(navigator.appCodeName, navigator.appVersion) console.log(versionString) var MarkIt = initWorker(appScriptURL.replace(appName, workerName)) // make Web Worker object which does all the work var noArrow = false try { eval('(() => true)') } catch (err) { noArrow = true } // just a test, not used console.log(['Arrow functions are ', noArrow ? 'NOT ' : '', 'supported in this browser.'].join('')) // append relative .mmk path to location.href directory to get full URL for markit() var lingoURL = globals.location.href.substring(0, globals.location.href.lastIndexOf('/') + 1) + appScriptURL.replace(appName, lingoName) var request = new globals.XMLHttpRequest() request.open('GET', lingoURL, true) request.onload = function () { var status = 0 status = ((status === 0) ? this.status : status) // ; console.log("status=",status) if ((status === 200 || status === 0)) { MarkIt.queue.push({document: document, elemID: null}) try { MarkIt.postMessage([lingoURL, 'metamark', this.responseText]) // ; console.log("posting ",type," ",tElement," to ",document) } catch (err) { MarkIt.queue.shift() // remove queue item // log message to console, no x-markup.mmk to use, so ignore console.error(errorMessage([err.message, ' posting metamark content to ', document])) } } else { console.log('Error reading', lingoURL, ' code=', status) } processScripts() } request.onerror = function () { console.log('Error reading', lingoURL, ' code= 404') processScripts() } request.send() // ; console.log(request.status,url,"["+request.responseText.length+"]") // helper functions function initWorker (workerURL) { // init Worker object and return it var worker = new globals.Worker(workerURL) // worker is colocated with this script file worker.onmessage = function (content) { updateDOM(content.data) } worker.onerror = function (err) { // if this happens, it's a bug (uncaught exception in Worker?) var eMsg = errorMessage(['Worker ', err.message]) var element = null if (worker.queue.length > 0) { element = updateDOM( ['<pre><mark style="color:blue"><br>', eMsg, '<br></mark></pre>'].join('')) // ES6: `<mark style='color:blue'>${eMsg}</mark><br>` } console.error(eMsg, (element) ? ' translating ' + element : '') } worker.queue = [] // queue to keep "job" details for async post-processing worker.nxtID = 1 return worker } // initWorker() function processScripts () { if (target) { var dmScripts = target.body.querySelectorAll(["script[type^='", mimeType, "']"].join('')) var typeValue for (var s = 0; s < dmScripts.length; s++) { typeValue = dmScripts[s].getAttribute('type') post(target, typeValue.substring(mimeType.length), dmScripts[s]) } // for } } // processScripts() function post (document, type, element) { // post message to MarkIt with structured text object if (type) { element.setAttribute('hidden', 'hidden') // hide element while rewriting it var source = element.textContent var tElement, srcURL if (element.tagName.toLowerCase() === 'script') { // if a <script> element, convert it to empty <div> srcURL = element.getAttribute('src') if (srcURL) { element.removeAttribute('src') if (srcURL === '?') { var docURL = document.documentURI srcURL = docURL.substring(0, docURL.lastIndexOf('.')) + '.myw' if (document.title.length === 0) { document.title = srcURL.substring(srcURL.lastIndexOf('/') + 1) } } var request = new globals.XMLHttpRequest() request.open('GET', srcURL, true) request.onload = function () { var status = 0 status = ((status === 0) ? this.status : status) // ; console.log("status=",status) if ((status === 200 || status === 0)) { element.textContent = this.responseText post(document, type, element) // re-post with loaded content } else { element.parentNode.replaceChild(errElement(srcURL, status), element) } } request.onerror = function () { element.parentNode.replaceChild(errElement(srcURL, 404), element) } request.send() // ; console.log(request.status,url,"["+request.responseText.length+"]") return } tElement = document.createElement('div') var attrs = element.attributes for (var a = 0; a < attrs.length; a++) { tElement.setAttribute(attrs[ a ].name, attrs[ a ].value) } element.parentNode.replaceChild(tElement, element) } else { tElement = element } if (!tElement.getAttribute('id')) { // if element doesn't have an ID, manufacture one tElement.setAttribute('id', 'FWmsg' + MarkIt.nxtID++) } MarkIt.queue.push({document: document, elemID: tElement.getAttribute('id')}) try { MarkIt.postMessage([document.location.href, type, source]) // ; console.log("posting ",type," ",tElement," to ",document) } catch (err) { MarkIt.queue.shift() // remove queue item element.removeAttribute('hidden') // make element visible again // leave element alone, error message in console console.error(errorMessage([err.message, ' posting ', type, ' content to ', document])) } } function errElement (url, status) { var preElement = document.createElement('pre') preElement.innerHTML = ['<mark style="color:blue"><br/>Error reading "', url, '": status=', status, '<br></mark>'].join('') return preElement } // errElement(url, status) } // post(document,type,element) function updateDOM (content) { // update DOM with Worker result, returns modified element var item = MarkIt.queue.shift() // get work item var document = item.document // retrieve window // and element. Note special case - elemID == null, means loading x-markup.mmk var element = (item.elemID) ? document.getElementById(item.elemID) : document.body // console.log("receiving "+((content)?"content":"null")+" for ",element) if (content && (content.length > 0)) { try { if (element.tagName.toLowerCase() === 'body') { // reply from x-markup.mmk translation var temp = document.createElement('div') // will be garbage collected temp.innerHTML = content var tempChildren = temp.children var bodyFirst = element.firstChild for (var i = 0; i < tempChildren.length; i++) { element.insertBefore(tempChildren[i], bodyFirst) } return element } else { element.innerHTML = content element.removeAttribute('hidden') // have to render before adjusting size if (document.defaultView.frameElement) adjustSize(document.defaultView.frameElement) var scripts = element.getElementsByTagName('script') // have to clone & replace scripts to get them executed var script, newscript for (var s = 0; s < scripts.length; s++) { script = scripts[s] newscript = document.createElement('script') newscript.innerHTML = script.innerHTML for (var ai = 0; ai < script.attributes.length; ai++) { newscript.setAttribute(script.attributes[ai].name, script.attributes[ai].value) } script.parentElement.replaceChild(newscript, script) } } dispatchUpdate(document, element) // invoke listeners for update } catch (err) { element.removeAttribute('hidden') // something failed, just make element visible again console.error(errorMessage([err.message, ' updating ', element])) } } else element.removeAttribute('hidden') // no new content, make it visible return element } // updateDOM(content) function adjustSize (iframe) { // adjust size of iframe element after DOM modified var document = iframe.contentDocument.documentElement // console.log("New frame size",document.scrollHeight," : ",iframe) // Wait for images - sometimes necessary, particularly on Chrome var images = document.getElementsByTagName('img') // ES6: for (var img of images) { for (var i = 0; i < images.length; i++) { var img = images[i] // ; console.log("Checking ", img, img.complete) if (!img.complete) { // ; console.log("Waiting for ",img) img.onload = function () { this.onload = null adjustSize(iframe) } img.onerror = function () { this.onerror = null adjustSize(iframe) } return } } // Some browsers require height setting to be deferred (render complete?) // Messages would be faster than setTimeout(fn,0) but effieciency not a big issue for this // Other alternatives: setImmediate(fn) (not standard) or requestAnimationFrame(fn) (normal usage?) setTimeout(function () { iframe.style.height = (document.scrollHeight) + 'px' // console.log("New frame style.height",iframe.style.height," : ",iframe) var parentFrame = iframe.ownerDocument.defaultView.frameElement if (parentFrame) adjustSize(parentFrame) }, 0) } // adjustSize(iframe) /* ****************** Start of "feature" listeners ********************* */ var listeners = [] // listener events dispatched to listeners whenever MarkIt returns new HTML content var addListener = function (listener) { if (typeof listener === 'function') { for (var l = 0; l < listeners.length; l++) { if (listeners[ l ] === listener) return // listener already registered, return } listeners.push(listener) // new listener, add it } else console.error(errorMessage(['Invalid listener: ', listener])) } // addListener(listener) var removeListener = function (listener) { for (var l = 0; l < listeners.length; l++) { if (listeners[l] === listener) { listeners.splice(l, 1) break } } } // removeListener(listener) var dispatchUpdate = function (document, element) { // called from updateDOM() for (var l = 0; l < listeners.length; l++) listeners[l].call(null, document, element) } // dispatchUpdate(document, element) // Math plug-in : use MathJax if loaded function hasMathML () { // returns true if platform has native MathML support var hasMML = false if (document.createElement) { var div = document.createElement('div') div.style.position = 'absolute' div.style.top = div.style.left = 0 div.style.visibility = 'hidden' div.style.width = div.style.height = 'auto' div.style.fontFamily = 'serif' div.style.lineheight = 'normal' div.innerHTML = '<math><mfrac><mi>xx</mi><mi>yy</mi></mfrac></math>' document.body.appendChild(div) hasMML = (div.offsetHeight > div.offsetWidth) // proper fraction rendering has height > width document.body.removeChild(div) } return hasMML } var noMML = !hasMathML() // not used in this version console.log(['MML is ', noMML ? 'NOT ' : '', 'supported in this browser.'].join('')) if (/* noMML && */ (typeof globals.MathJax !== 'undefined')) { // if (MathJax) add it feature listeners addListener(function (document, element) { globals.MathJax.Hub.Queue([ 'Typeset', globals.MathJax.Hub, element ]) }) } /* Polyfill for scoped styles - plagerized from (https://github.com/thomaspark/scoper) Copyright (c) 2015 Thomas Park Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ function scopeIt (document, element) { if (!(MarkIt.scopeID)) MarkIt.scopeID = 0 var styles = element.querySelectorAll('style[scoped]') if (styles.length > 0) { var head = document.head || document.getElementsByTagName('head')[0] var newstyle = document.createElement('style') var csses = '' for (var i = 0; i < styles.length; i++) { var style = styles[i] var css = style.innerHTML if (css) { var parent = style.parentNode // don't process any immediate decendants of body element (shouldn't wrap body element) if (parent.tagName.toLowerCase() !== 'body') { var id = 'scoper-' + (MarkIt.scopeID++) var prefix = '#' + id var wrapper = document.createElement('span') wrapper.id = id var grandparent = parent.parentNode grandparent.replaceChild(wrapper, parent) wrapper.appendChild(parent) style.parentNode.removeChild(style) csses = csses + scoper(css, prefix) } } } if (newstyle.styleSheet) { newstyle.styleSheet.cssText = csses } else { newstyle.appendChild(document.createTextNode(csses)) } head.appendChild(newstyle) } function scoper (css, prefix) { var re = new RegExp('([^\\r\\n,{}]+)(,(?=[^}]*{)|\\s*{)', 'g') // escaped '\' - issue for scoper? css = css.replace(re, function (g0, g1, g2) { if (g1.match(/^\s*(@media|@keyframes|to|from)/)) { return g1 + g2 } g1 = g1.replace(/^(\s*)/, '$1' + prefix + ' ') return g1 + g2 }) return css } // scoper(css, prefix) } // scopeIt(document, element) var noscoped = !('scoped' in document.createElement('style')) console.log(['Scoped styles are ', noscoped ? 'NOT ' : '', 'supported in this browser.'].join('')) if (noscoped) addListener(scopeIt) // add scopeIt to feature listeners // Document feature to build table of contents // Triggered by generation of // <script type='application/x-markit.buildTOC'> // The <script> element content is the transform name for the generated toc data and the range of headers to collect, // e.g., contentTable 1..4 - collects <h1> to <h4> elements in the document for the transform contentTable // The generated TOC entries are of the form: levelNumber\theaderID\theaderContent // which is posted back to FirstWord to generate HTML to replace <script> using the transform specified // All attributes in <script> element are preserved in the <div> element which replaces it (see post()). function buildTOC (document, element) { try { var tocScripts = element.querySelectorAll(['script[type="', mimeType, 'buildTOC"]'].join('')) // console.log("tocScripts=",tocScripts) var tocScript, tocSpec, hmin, hmax, headers, tocContent, header, level for (var s = 0; s < tocScripts.length; s++) { tocScript = tocScripts[s] tocSpec = tocScript.textContent.match(/^\s*(\S+)\s*(\d*)\s*(?:..\s*(\d*))?/) // ; console.log("tocSpec=", tocSpec) if (tocSpec) { hmin = (tocSpec[2]) ? parseInt(tocSpec[2]) : 0 hmax = (tocSpec[3]) ? parseInt(tocSpec[3]) : 99 if (hmin > hmax) { var temp = hmin; hmin = hmax; hmax = temp // ; console.log("hmin=",hmin,"hmax=",hmax) } headers = document.querySelectorAll('*[id^="hdr:"]') // ; console.log("headers=", headers) tocContent = [] for (var h = 0; h < headers.length; h++) { header = headers[h] level = header.parentElement.tagName.match(/[hH](\d)/) if (level) { level = parseInt(level[1], 10) if ((level >= hmin) && (level <= hmax)) { tocContent.push(level, '\t', header.id, '\t', header.textContent.trim(), '\n') } } } // for tocScript.textContent = tocContent.join('') // ; console.log('tocScript=', tocScript) post(document, tocSpec[1], tocScript) } } // for } catch (err) { console.error('buildTOC error=', err) } } // buildTOC(document, element) //addListener(buildTOC) // add buildTOC to feature listeners } // event handler ) // Toggle fullscreen handler document.addEventListener('keydown', function (e) { if (e.keyCode === 13) { toggleFullScreen() } function toggleFullScreen () { if (!document.fullscreenElement && // alternative standard method !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) { // current working methods if (document.documentElement.requestFullscreen) { document.documentElement.requestFullscreen() } else if (document.documentElement.msRequestFullscreen) { document.documentElement.msRequestFullscreen() } else if (document.documentElement.mozRequestFullScreen) { document.documentElement.mozRequestFullScreen() } else if (document.documentElement.webkitRequestFullscreen) { document.documentElement.webkitRequestFullscreen(window.Element.ALLOW_KEYBOARD_INPUT) } } else { if (document.exitFullscreen) { document.exitFullscreen() } else if (document.msExitFullscreen) { document.msExitFullscreen() } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen() } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen() } } } }, false)
x-markup.js converted to 'JavaScript Standard Style'. (http://standardjs.com)
lib/x-markup.js
x-markup.js converted to 'JavaScript Standard Style'. (http://standardjs.com)
<ide><path>ib/x-markup.js <ide> // helper functions <ide> <ide> function initWorker (workerURL) { // init Worker object and return it <del> var worker = new globals.Worker(workerURL) // worker is colocated with this script file <add> var worker = new globals.Worker(workerURL) // worker is co-located with this script file <ide> worker.onmessage = function (content) { <ide> updateDOM(content.data) <ide> }
Java
agpl-3.0
f40c893961961fc6eb0e367ba3334d62dead1270
0
mnip91/proactive-component-monitoring,mnip91/proactive-component-monitoring,acontes/programming,lpellegr/programming,paraita/programming,mnip91/programming-multiactivities,ow2-proactive/programming,ow2-proactive/programming,PaulKh/scale-proactive,ow2-proactive/programming,mnip91/programming-multiactivities,acontes/scheduling,mnip91/proactive-component-monitoring,paraita/programming,mnip91/proactive-component-monitoring,fviale/programming,lpellegr/programming,jrochas/scale-proactive,acontes/programming,PaulKh/scale-proactive,jrochas/scale-proactive,jrochas/scale-proactive,acontes/programming,paraita/programming,lpellegr/programming,ow2-proactive/programming,paraita/programming,fviale/programming,mnip91/programming-multiactivities,jrochas/scale-proactive,ow2-proactive/programming,paraita/programming,acontes/programming,jrochas/scale-proactive,lpellegr/programming,acontes/scheduling,fviale/programming,jrochas/scale-proactive,PaulKh/scale-proactive,acontes/scheduling,PaulKh/scale-proactive,mnip91/programming-multiactivities,paraita/programming,PaulKh/scale-proactive,acontes/scheduling,fviale/programming,acontes/programming,PaulKh/scale-proactive,acontes/scheduling,fviale/programming,lpellegr/programming,mnip91/proactive-component-monitoring,lpellegr/programming,jrochas/scale-proactive,acontes/scheduling,acontes/programming,mnip91/programming-multiactivities,ow2-proactive/programming,acontes/scheduling,acontes/programming,fviale/programming,mnip91/proactive-component-monitoring,mnip91/programming-multiactivities,PaulKh/scale-proactive
/* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis * Contact: [email protected] * * 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, or any later version. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * Initial developer(s): The ProActive Team * http://www.inria.fr/oasis/ProActive/contacts.html * Contributor(s): * * ################################################################ */ package org.objectweb.proactive.core.body.proxy; //add comments import org.objectweb.proactive.core.mop.ClassNotReifiableException; import org.objectweb.proactive.core.mop.MOP; import org.objectweb.proactive.core.mop.MethodCall; import org.objectweb.proactive.core.mop.Proxy; public abstract class AbstractProxy implements Proxy, java.io.Serializable { // // -- STATIC MEMBERS ----------------------------------------------- // // // -- CONSTRUCTORS ----------------------------------------------- // public AbstractProxy() { } // // -- PUBLIC METHODS ----------------------------------------------- // // // -- STATIC METHODS ----------------------------------------------- // // ------------------------------------------------------------------------------------------- // // ASYNCHRONOUS CALL // // ------------------------------------------------------------------------------------------- /** * The hashtable that caches Method/isAsynchronousCall * This dramatically improves performances, since we do not have to call * isAsynchronousCall for every call, but only once for a given method */ private static transient java.util.Hashtable ASYNORNOT = new java.util.Hashtable(); /** * Checks if the given <code>Call</code> object <code>c</code> can be * processed with a future semantics, i-e if its returned object * can be a future object. * * Two conditions must be met : <UL> * <LI> The returned object is reifiable * <LI> The invoked method does not throw any exceptions * </UL> * @return true if and only if the method call can be asynchronous */ protected static boolean isAsynchronousCall(MethodCall c) { return isAsynchronousCall(c.getReifiedMethod()); } /** * Returns a boolean saying whether the methode is one-way or not. * Being one-way method is equivalent to <UL> * <LI>having <code>void</code> as return type * <LI>and not throwing any checked exceptions</UL> * @return true if and only if the method call is one way */ protected static boolean isOneWayCall(MethodCall c) { return isOneWayCall(c.getReifiedMethod()); } /** * Returns a boolean saying whether the methode is one-way or not. * Being one-way method is equivalent to <UL> * <LI>having <code>void</code> as return type * <LI>and not throwing any checked exceptions</UL> * @return true if and only if the method call is one way */ protected static boolean isOneWayCall(java.lang.reflect.Method m) { return (m.getReturnType().equals(java.lang.Void.TYPE)) && (m.getExceptionTypes().length == 0); } /** * Checks if the given <code>Call</code> object <code>c</code> can be * processed with a future semantics, i-e if its returned object * can be a future object. * * Two conditions must be met : <UL> * <LI> The returned object is reifiable * <LI> The invoked method does not throw any exceptions * </UL> */ private static boolean isAsynchronousCall(java.lang.reflect.Method m) { // Is the result cached ? Boolean b = (Boolean)ASYNORNOT.get(m); if (b != null) { return b.booleanValue(); } else // Computes the result { boolean result; // A Method that returns void is the only case where a method that returns // a non-reifiable type is asynchronous if (isOneWayCall(m)) { result = true; } else { try { MOP.checkClassIsReifiable(m.getReturnType()); // If the method can throw exceptions, then the result if false if (m.getExceptionTypes().length > 0) { //System.out.println(" ------ isAsynchronousCall() The method can throw exceptions "); result = false; } else { result = true; } } catch (ClassNotReifiableException e) { //System.out.println(" ------ isAsynchronousCall() The class " + m.getReturnType() + " is not reifiable "); result = false; } // Now that we have computed the result, let's cache it //System.out.println(" ------ isAsynchronousCall() method " + m + " ===> "+result); ASYNORNOT.put(m, new Boolean(result)); } return result; } } }
src/org/objectweb/proactive/core/body/proxy/AbstractProxy.java
/* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis * Contact: [email protected] * * 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, or any later version. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * Initial developer(s): The ProActive Team * http://www.inria.fr/oasis/ProActive/contacts.html * Contributor(s): * * ################################################################ */ package org.objectweb.proactive.core.body.proxy; import org.objectweb.proactive.core.mop.ClassNotReifiableException; import org.objectweb.proactive.core.mop.MOP; import org.objectweb.proactive.core.mop.MethodCall; import org.objectweb.proactive.core.mop.Proxy; public abstract class AbstractProxy implements Proxy, java.io.Serializable { // // -- STATIC MEMBERS ----------------------------------------------- // // // -- CONSTRUCTORS ----------------------------------------------- // public AbstractProxy() { } // // -- PUBLIC METHODS ----------------------------------------------- // // // -- STATIC METHODS ----------------------------------------------- // // ------------------------------------------------------------------------------------------- // // ASYNCHRONOUS CALL // // ------------------------------------------------------------------------------------------- /** * The hashtable that caches Method/isAsynchronousCall * This dramatically improves performances, since we do not have to call * isAsynchronousCall for every call, but only once for a given method */ private static transient java.util.Hashtable ASYNORNOT = new java.util.Hashtable(); /** * Checks if the given <code>Call</code> object <code>c</code> can be * processed with a future semantics, i-e if its returned object * can be a future object. * * Two conditions must be met : <UL> * <LI> The returned object is reifiable * <LI> The invoked method does not throw any exceptions * </UL> * @return true if and only if the method call can be asynchronous */ protected static boolean isAsynchronousCall(MethodCall c) { return isAsynchronousCall(c.getReifiedMethod()); } /** * Returns a boolean saying whether the methode is one-way or not. * Being one-way method is equivalent to <UL> * <LI>having <code>void</code> as return type * <LI>and not throwing any checked exceptions</UL> * @return true if and only if the method call is one way */ protected static boolean isOneWayCall(MethodCall c) { return isOneWayCall(c.getReifiedMethod()); } /** * Returns a boolean saying whether the methode is one-way or not. * Being one-way method is equivalent to <UL> * <LI>having <code>void</code> as return type * <LI>and not throwing any checked exceptions</UL> * @return true if and only if the method call is one way */ protected static boolean isOneWayCall(java.lang.reflect.Method m) { return (m.getReturnType().equals(java.lang.Void.TYPE)) && (m.getExceptionTypes().length == 0); } /** * Checks if the given <code>Call</code> object <code>c</code> can be * processed with a future semantics, i-e if its returned object * can be a future object. * * Two conditions must be met : <UL> * <LI> The returned object is reifiable * <LI> The invoked method does not throw any exceptions * </UL> */ private static boolean isAsynchronousCall(java.lang.reflect.Method m) { // Is the result cached ? Boolean b = (Boolean)ASYNORNOT.get(m); if (b != null) { return b.booleanValue(); } else // Computes the result { boolean result; // A Method that returns void is the only case where a method that returns // a non-reifiable type is asynchronous if (isOneWayCall(m)) { result = true; } else { try { MOP.checkClassIsReifiable(m.getReturnType()); // If the method can throw exceptions, then the result if false if (m.getExceptionTypes().length > 0) { //System.out.println(" ------ isAsynchronousCall() The method can throw exceptions "); result = false; } else { result = true; } } catch (ClassNotReifiableException e) { //System.out.println(" ------ isAsynchronousCall() The class " + m.getReturnType() + " is not reifiable "); result = false; } // Now that we have computed the result, let's cache it //System.out.println(" ------ isAsynchronousCall() method " + m + " ===> "+result); ASYNORNOT.put(m, new Boolean(result)); } return result; } } }
comments added git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@243 28e8926c-6b08-0410-baaa-805c5e19b8d6
src/org/objectweb/proactive/core/body/proxy/AbstractProxy.java
comments added
<ide><path>rc/org/objectweb/proactive/core/body/proxy/AbstractProxy.java <ide> * ################################################################ <ide> */ <ide> package org.objectweb.proactive.core.body.proxy; <del> <add>//add comments <ide> import org.objectweb.proactive.core.mop.ClassNotReifiableException; <ide> import org.objectweb.proactive.core.mop.MOP; <ide> import org.objectweb.proactive.core.mop.MethodCall;
JavaScript
mit
33e605d9bb826831466241738fabc1e0707068e0
0
hpe-idol/java-powerpoint-report,hpe-idol/java-powerpoint-report,hpe-idol/find,hpautonomy/find,hpautonomy/find,hpe-idol/find,hpautonomy/find,hpautonomy/find,hpe-idol/find,hpe-idol/find,hpautonomy/find,hpe-idol/find
/* * Copyright 2016 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ define([ 'backbone', 'jquery', 'find/app/configuration', 'i18n!find/nls/bundle', 'find/app/page/search/document/document-detail-tabs', 'find/app/model/document-model' ], function(Backbone, $, configuration, i18n, documentDetailTabs, DocumentModel) { function filterTabs(model) { return _.filter(documentDetailTabs, function(tab) { return tab.shown(model); }); } function byTitleKey(tabs, titleKey) { return _.findWhere(tabs, {title: i18n[titleKey]}); } describe('Document detail tabs', function() { describe('with the location tab enabled', function() { beforeEach(function() { configuration.and.returnValue({ map: { enabled: true }, hasBiRole: true }); }); it('displays every tab for a complete model with map enabled', function() { var model = new DocumentModel({ authors: ['Humbert', 'Gereon'], media: true, sourceType: 'news', thumbnail: 'VGhlIGJhc2UgNjQgZW5jb2RlZCB0aHVtYm5haWw=', transcript: 'test transcript', locations: [{ displayName: 'test', latitude: 12.5, longitude: 42.2 }], url: true }); expect(filterTabs(model).length).toBe(documentDetailTabs.length); }); it('displays default tabs for an empty model', function() { var model = new DocumentModel({ authors: [], latitude: undefined, longitude: undefined }); expect(filterTabs(model).length).toBe(3); }); it('displays the author tab when an authors attribute is present', function() { var model = new DocumentModel({ authors: ['Humbert', 'Gereon'] }); var tabs = filterTabs(model); expect(tabs.length).toBe(4); expect(byTitleKey(tabs, 'search.document.detail.tabs.authors')).toBeDefined(); }); it('displays similar sources tab when a source attribute is present', function() { var model = new DocumentModel({ sourceType: 'News' }); var tabs = filterTabs(model); expect(tabs.length).toBe(4); expect(byTitleKey(tabs, 'search.document.detail.tabs.similarSources')).toBeDefined(); }); it('displays the transcript tab when the model has transcript, media and url attributes', function() { var model = new DocumentModel({ media: true, url: true, transcript: 'test transcript' }); var tabs = filterTabs(model); expect(tabs.length).toBe(4); expect(byTitleKey(tabs, 'search.document.detail.tabs.transcript')).toBeDefined(); }); it('displays the location tab if the locations property is preset', function() { var model = new DocumentModel({ locations: [{ displayName: 'test', latitude: 12.5, longitude: 42.2 }] }); var tabs = filterTabs(model); expect(tabs.length).toBe(4); expect(byTitleKey(tabs, 'search.document.detail.tabs.location')).toBeDefined(); }); it('does not display the location tab if the locations property is absent', function() { var model = new DocumentModel({locations: undefined}); var tabs = filterTabs(model); expect(tabs.length).toBe(3); expect(byTitleKey(tabs, 'search.document.detail.tabs.location')).toBeUndefined(); }); }); describe('with the location tab disabled', function() { beforeEach(function() { configuration.and.returnValue({ map: { enabled: false } }); }); it('does not display the location tab even if longitude and latitude attributes are present', function() { var model = new DocumentModel({ longitude: 123.4, latitude: 73 }); var tabs = filterTabs(model); expect(tabs.length).toBe(2); expect(byTitleKey(tabs, 'search.document.detail.tabs.location')).toBeUndefined(); }); }); }); });
core/src/test/js/spec/app/page/search/document/document-detail-tabs.js
/* * Copyright 2016 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ define([ 'backbone', 'jquery', 'find/app/configuration', 'i18n!find/nls/bundle', 'find/app/page/search/document/document-detail-tabs', 'find/app/model/document-model' ], function(Backbone, $, configuration, i18n, documentDetailTabs, DocumentModel) { function filterTabs(model) { return _.filter(documentDetailTabs, function(tab) { return tab.shown(model); }); } function byTitleKey(tabs, titleKey) { return _.findWhere(tabs, {title: i18n[titleKey]}); } describe('Document detail tabs', function() { describe('with the location tab enabled', function() { beforeEach(function() { configuration.and.returnValue({ map: { enabled: true } }); }); it('displays every tab for a complete model with map enabled', function() { var model = new DocumentModel({ authors: ['Humbert', 'Gereon'], media: true, sourceType: 'news', thumbnail: 'VGhlIGJhc2UgNjQgZW5jb2RlZCB0aHVtYm5haWw=', transcript: 'test transcript', locations: [{ displayName: 'test', latitude: 12.5, longitude: 42.2 }], url: true }); expect(filterTabs(model).length).toBe(documentDetailTabs.length); }); it('displays default tabs for an empty model', function() { var model = new DocumentModel({ authors: [], latitude: undefined, longitude: undefined }); expect(filterTabs(model).length).toBe(3); }); it('displays the author tab when an authors attribute is present', function() { var model = new DocumentModel({ authors: ['Humbert', 'Gereon'] }); var tabs = filterTabs(model); expect(tabs.length).toBe(4); expect(byTitleKey(tabs, 'search.document.detail.tabs.authors')).toBeDefined(); }); it('displays similar sources tab when a source attribute is present', function() { var model = new DocumentModel({ sourceType: 'News' }); var tabs = filterTabs(model); expect(tabs.length).toBe(4); expect(byTitleKey(tabs, 'search.document.detail.tabs.similarSources')).toBeDefined(); }); it('displays the transcript tab when the model has transcript, media and url attributes', function() { var model = new DocumentModel({ media: true, url: true, transcript: 'test transcript' }); var tabs = filterTabs(model); expect(tabs.length).toBe(4); expect(byTitleKey(tabs, 'search.document.detail.tabs.transcript')).toBeDefined(); }); it('displays the location tab if the locations property is preset', function() { var model = new DocumentModel({ locations: [{ displayName: 'test', latitude: 12.5, longitude: 42.2 }] }); var tabs = filterTabs(model); expect(tabs.length).toBe(4); expect(byTitleKey(tabs, 'search.document.detail.tabs.location')).toBeDefined(); }); it('does not display the location tab if the locations property is absent', function() { var model = new DocumentModel({locations: undefined}); var tabs = filterTabs(model); expect(tabs.length).toBe(3); expect(byTitleKey(tabs, 'search.document.detail.tabs.location')).toBeUndefined(); }); }); describe('with the location tab disabled', function() { beforeEach(function() { configuration.and.returnValue({ map: { enabled: false } }); }); it('does not display the location tab even if longitude and latitude attributes are present', function() { var model = new DocumentModel({ longitude: 123.4, latitude: 73 }); var tabs = filterTabs(model); expect(tabs.length).toBe(3); expect(byTitleKey(tabs, 'search.document.detail.tabs.location')).toBeUndefined(); }); }); }); });
Fix failing tests.
core/src/test/js/spec/app/page/search/document/document-detail-tabs.js
Fix failing tests.
<ide><path>ore/src/test/js/spec/app/page/search/document/document-detail-tabs.js <ide> configuration.and.returnValue({ <ide> map: { <ide> enabled: true <del> } <add> }, <add> hasBiRole: true <ide> }); <ide> }); <ide> <ide> }); <ide> <ide> var tabs = filterTabs(model); <del> expect(tabs.length).toBe(3); <add> expect(tabs.length).toBe(2); <ide> expect(byTitleKey(tabs, 'search.document.detail.tabs.location')).toBeUndefined(); <ide> }); <ide> });
JavaScript
mit
f27838b16f392c4cfd7a855f45198f77f2973c5d
0
Jaywing/atomic,Jaywing/atomic
var config = require('../config') if(!config.tasks.svgSprite) return var browserSync = require('browser-sync') var gulp = require('gulp') var imagemin = require('gulp-imagemin') var svgstore = require('gulp-svgstore') var path = require('path') var svgSpriteTask = function() { var settings = { src: path.join(config.root.src, config.tasks.svgSprite.src, '/*.svg'), dest: path.join(config.root.dest, config.tasks.svgSprite.dest) } return gulp.src(settings.src) .pipe(imagemin({ progressive: true, use: [pngquant()] })) // Optimize .pipe(svgstore()) .pipe(gulp.dest(settings.dest)) .pipe(browserSync.stream()) } gulp.task('svgSprite', svgSpriteTask) module.exports = svgSpriteTask
gulpfile.js/tasks/svgSprite.js
var config = require('../config') if(!config.tasks.svgSprite) return var browserSync = require('browser-sync') var gulp = require('gulp') var imagemin = require('gulp-imagemin') var svgstore = require('gulp-svgstore') var path = require('path') var svgSpriteTask = function() { var settings = { src: path.join(config.root.src, config.tasks.svgSprite.src, '/*.svg'), dest: path.join(config.root.dest, config.tasks.svgSprite.dest) } return gulp.src(settings.src) .pipe(imagemin()) .pipe(svgstore()) .pipe(gulp.dest(settings.dest)) .pipe(browserSync.stream()) } gulp.task('svgSprite', svgSpriteTask) module.exports = svgSpriteTask
Added the refactored imagemin to svgSprite task
gulpfile.js/tasks/svgSprite.js
Added the refactored imagemin to svgSprite task
<ide><path>ulpfile.js/tasks/svgSprite.js <ide> } <ide> <ide> return gulp.src(settings.src) <del> .pipe(imagemin()) <add> .pipe(imagemin({ <add> progressive: true, <add> use: [pngquant()] <add> })) // Optimize <ide> .pipe(svgstore()) <ide> .pipe(gulp.dest(settings.dest)) <ide> .pipe(browserSync.stream())
Java
bsd-3-clause
0194d505fa37fae0423e5bf5e14227dd5f5785f3
0
NCIP/cadsr-semantic-tools,NCIP/cadsr-semantic-tools
/* * Copyright 2000-2005 Oracle, Inc. This software was developed in conjunction with the National Cancer Institute, and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer of Article 3, below. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: * * "This product includes software developed by Oracle, Inc. and the National Cancer Institute." * * If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself, wherever such third-party acknowledgments normally appear. * * 3. The names "The National Cancer Institute", "NCI" and "Oracle" must not be used to endorse or promote products derived from this software. * * 4. This license does not authorize the incorporation of this software into any proprietary programs. This license does not authorize the recipient to use any trademarks owned by either NCI or Oracle, Inc. * * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, ORACLE, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE */ package gov.nih.nci.ncicb.cadsr.loader.parser; import gov.nih.nci.ncicb.cadsr.domain.*; import gov.nih.nci.ncicb.cadsr.loader.*; import gov.nih.nci.ncicb.cadsr.loader.persister.OCRRoleNameBuilder; import gov.nih.nci.ncicb.cadsr.loader.util.*; import gov.nih.nci.ncicb.cadsr.loader.event.ProgressListener; import gov.nih.nci.ncicb.cadsr.loader.event.ProgressEvent; import gov.nih.nci.ncicb.xmiinout.handler.*; import gov.nih.nci.ncicb.xmiinout.domain.*; import java.util.*; /** * A writer for XMI files * * @author <a href="mailto:[email protected]">Christophe Ludet</a> */ public class XMIWriter2 implements ElementWriter { private String output = null; private HashMap<String, UMLClass> classMap = new HashMap<String, UMLClass>(); private HashMap<String, UMLAttribute> attributeMap = new HashMap<String, UMLAttribute>(); private HashMap<String, UMLAssociation> assocMap = new HashMap<String, UMLAssociation>(); private HashMap<String, UMLAssociationEnd> assocEndMap = new HashMap<String, UMLAssociationEnd>(); private ElementsLists cadsrObjects = null; private ReviewTracker ownerReviewTracker = ReviewTracker.getInstance(ReviewTrackerType.Owner), curatorReviewTracker = ReviewTracker.getInstance(ReviewTrackerType.Curator); private ChangeTracker changeTracker = ChangeTracker.getInstance(); private ProgressListener progressListener; private UMLModel model = null; private XmiInOutHandler handler = null; public XMIWriter2() { } public void write(ElementsLists elements) throws ParserException { try { handler = (XmiInOutHandler)(UserSelections.getInstance().getProperty("XMI_HANDLER")); model = handler.getModel("EA Model"); this.cadsrObjects = elements; sendProgressEvent(0, 0, "Parsing Model"); readModel(); // doReviewTagLogic(); sendProgressEvent(0, 0, "Marking Human reviewed"); markHumanReviewed(); sendProgressEvent(0, 0, "Updating Elements"); updateChangedElements(); sendProgressEvent(0, 0, "ReWriting Model"); handler.save(output); } catch (Exception ex) { throw new RuntimeException("Error initializing model", ex); } } public void setOutput(String url) { this.output = url; } public void setProgressListener(ProgressListener listener) { progressListener = listener; } private void readModel() { for(UMLPackage pkg : model.getPackages()) doPackage(pkg); for(UMLAssociation assoc : model.getAssociations()) { List<UMLAssociationEnd> ends = assoc.getAssociationEnds(); UMLAssociationEnd aEnd = ends.get(0); UMLAssociationEnd bEnd = ends.get(1); UMLAssociationEnd source = bEnd, target = aEnd; // direction B? if (bEnd.isNavigable() && !aEnd.isNavigable()) { source = aEnd; target = bEnd; } String key = assoc.getRoleName()+"~"+source.getRoleName()+"~"+target.getRoleName(); assocMap.put(key,assoc); assocEndMap.put(key+"~source",source); assocEndMap.put(key+"~target",target); } } private void updateChangedElements() { List<ObjectClass> ocs = cadsrObjects.getElements(DomainObjectFactory.newObjectClass()); List<DataElement> des = cadsrObjects.getElements(DomainObjectFactory.newDataElement()); List<ValueDomain> vds = cadsrObjects.getElements(DomainObjectFactory.newValueDomain()); List<ObjectClassRelationship> ocrs = cadsrObjects.getElements(DomainObjectFactory.newObjectClassRelationship()); int goal = ocs.size() + des.size() + vds.size() + ocrs.size(); int status = 0; sendProgressEvent(status, goal, ""); for(ObjectClass oc : ocs) { String fullClassName = null; for(AlternateName an : oc.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) fullClassName = an.getName(); } sendProgressEvent(status++, goal, "Class: " + fullClassName); UMLClass clazz = classMap.get(fullClassName); boolean changed = changeTracker.get(fullClassName); if(changed) { // drop all current concept tagged values Collection<UMLTaggedValue> allTvs = clazz.getTaggedValues(); for(UMLTaggedValue tv : allTvs) { if(tv.getName().startsWith("ObjectClass") || tv.getName().startsWith("ObjectQualifier")) clazz.removeTaggedValue(tv.getName()); } String [] conceptCodes = oc.getPreferredName().split(":"); addConceptTvs(clazz, conceptCodes, XMIParser2.TV_TYPE_CLASS); } } for(DataElement de : des) { DataElementConcept dec = de.getDataElementConcept(); String fullPropName = null; for(AlternateName an : de.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_FULL_NAME)) fullPropName = an.getName(); } sendProgressEvent(status++, goal, "Attribute: " + fullPropName); UMLAttribute att = attributeMap.get(fullPropName); boolean changed = changeTracker.get(fullPropName); if(changed) { // drop all current concept tagged values Collection<UMLTaggedValue> allTvs = att.getTaggedValues(); for(UMLTaggedValue tv : allTvs) { if(tv.getName().startsWith("Property") || tv.getName().startsWith("PropertyQualifier")) att.removeTaggedValue(tv.getName()); } // Map to Existing DE if(!StringUtil.isEmpty(de.getPublicId()) && de.getVersion() != null) { att.addTaggedValue(XMIParser2.TV_DE_ID, de.getPublicId()); att.addTaggedValue(XMIParser2.TV_DE_VERSION, de.getVersion().toString()); } else { att.removeTaggedValue(XMIParser2.TV_DE_ID); att.removeTaggedValue(XMIParser2.TV_DE_VERSION); if(!StringUtil.isEmpty(de.getValueDomain().getPublicId()) && de.getValueDomain().getVersion() != null) { att.addTaggedValue(XMIParser2.TV_VD_ID, de.getValueDomain().getPublicId()); att.addTaggedValue(XMIParser2.TV_VD_VERSION, de.getValueDomain().getVersion().toString()); } else { att.removeTaggedValue(XMIParser2.TV_VD_ID); att.removeTaggedValue(XMIParser2.TV_VD_VERSION); } String [] conceptCodes = dec.getProperty().getPreferredName().split(":"); addConceptTvs(att, conceptCodes, XMIParser2.TV_TYPE_PROPERTY); } } } for(ValueDomain vd : vds) { sendProgressEvent(status++, goal, "Value Domain: " + vd.getLongName()); for(PermissibleValue pv : vd.getPermissibleValues()) { ValueMeaning vm = pv.getValueMeaning(); String fullPropName = "ValueDomains." + vd.getLongName() + "." + vm.getLongName(); UMLAttribute att = attributeMap.get(fullPropName); boolean changed = changeTracker.get(fullPropName); if(changed) { // drop all current concept tagged values Collection<UMLTaggedValue> allTvs = att.getTaggedValues(); for(UMLTaggedValue tv : allTvs) { if(tv.getName().startsWith(XMIParser2.TV_TYPE_VM) || tv.getName().startsWith(XMIParser2.TV_TYPE_VM + "Qualifier")) att.removeTaggedValue(tv.getName()); } String [] conceptCodes = ConceptUtil.getConceptCodes(vm); addConceptTvs(att, conceptCodes, XMIParser2.TV_TYPE_VM); } } } for(ObjectClassRelationship ocr : ocrs) { ConceptDerivationRule rule = ocr.getConceptDerivationRule(); ConceptDerivationRule srule = ocr.getSourceRoleConceptDerivationRule(); ConceptDerivationRule trule = ocr.getTargetRoleConceptDerivationRule(); OCRRoleNameBuilder nameBuilder = new OCRRoleNameBuilder(); String fullName = nameBuilder.buildRoleName(ocr); sendProgressEvent(status++, goal, "Relationship: " + fullName); String key = ocr.getLongName()+"~"+ocr.getSourceRole()+"~"+ocr.getTargetRole(); UMLAssociation assoc = assocMap.get(key); UMLAssociationEnd source = assocEndMap.get(key+"~source"); UMLAssociationEnd target = assocEndMap.get(key+"~target"); boolean changed = changeTracker.get(fullName); boolean changedSource = changeTracker.get(fullName+" Source"); boolean changedTarget = changeTracker.get(fullName+" Target"); if(changed) { dropCurrentAssocTvs(assoc); List<ComponentConcept> rConcepts = rule.getComponentConcepts(); String[] rcodes = new String[rConcepts.size()]; int i = 0; for (ComponentConcept con: rConcepts) { rcodes[i++] = con.getConcept().getPreferredName(); } addConceptTvs(assoc, rcodes, XMIParser2.TV_TYPE_ASSOC_ROLE); } if(changedSource) { dropCurrentAssocTvs(source); List<ComponentConcept> sConcepts = srule.getComponentConcepts(); String[] scodes = new String[sConcepts.size()]; int i = 0; for (ComponentConcept con: sConcepts) { scodes[i++] = con.getConcept().getPreferredName(); } addConceptTvs(source, scodes, XMIParser2.TV_TYPE_ASSOC_SOURCE); } if(changedTarget) { dropCurrentAssocTvs(target); List<ComponentConcept> tConcepts = trule.getComponentConcepts(); String[] tcodes = new String[tConcepts.size()]; int i = 0; for (ComponentConcept con: tConcepts) { tcodes[i++] = con.getConcept().getPreferredName(); } addConceptTvs(target, tcodes, XMIParser2.TV_TYPE_ASSOC_TARGET); } } changeTracker.clear(); } private void dropCurrentAssocTvs(UMLTaggableElement elt) { Collection<UMLTaggedValue> allTvs = elt.getTaggedValues(); for(UMLTaggedValue tv : allTvs) { String name = tv.getName(); if(name.startsWith(XMIParser2.TV_TYPE_ASSOC_ROLE) || name.startsWith(XMIParser2.TV_TYPE_ASSOC_SOURCE)|| name.startsWith(XMIParser2.TV_TYPE_ASSOC_TARGET)) { elt.removeTaggedValue(name); } } } private void addConceptTvs(UMLTaggableElement elt, String[] conceptCodes, String type) { if(conceptCodes.length == 0) return; addConceptTv(elt, conceptCodes[conceptCodes.length - 1], type, "", 0); for(int i= 1; i < conceptCodes.length; i++) { addConceptTv(elt, conceptCodes[conceptCodes.length - i - 1], type, XMIParser2.TV_QUALIFIER, i); } } private void addConceptTv(UMLTaggableElement elt, String conceptCode, String type, String pre, int n) { Concept con = LookupUtil.lookupConcept(conceptCode); if(con == null) return; String tvName = type + pre + XMIParser2.TV_CONCEPT_CODE + ((n>0)?""+n:""); if(con.getPreferredName() != null) elt.addTaggedValue(tvName,con.getPreferredName()); tvName = type + pre + XMIParser2.TV_CONCEPT_DEFINITION + ((n>0)?""+n:""); if(con.getPreferredDefinition() != null) elt.addTaggedValue(tvName,con.getPreferredDefinition()); tvName = type + pre + XMIParser2.TV_CONCEPT_DEFINITION_SOURCE + ((n>0)?""+n:""); if(con.getDefinitionSource() != null) elt.addTaggedValue(tvName,con.getDefinitionSource()); tvName = type + pre + XMIParser2.TV_CONCEPT_PREFERRED_NAME + ((n>0)?""+n:""); if(con.getLongName() != null) elt.addTaggedValue (tvName, con.getLongName()); // tvName = type + pre + XMIParser2.TV_TYPE_VM + ((n>0)?""+n:""); // // if(con.getLongName() != null) // elt.addTaggedValue // (tvName, // con.getLongName()); } private void markHumanReviewed() throws ParserException { try{ List<ObjectClass> ocs = cadsrObjects.getElements(DomainObjectFactory.newObjectClass()); List<DataElementConcept> decs = cadsrObjects.getElements(DomainObjectFactory.newDataElementConcept()); List<ValueDomain> vds = cadsrObjects.getElements(DomainObjectFactory.newValueDomain()); List<ObjectClassRelationship> ocrs = cadsrObjects.getElements(DomainObjectFactory.newObjectClassRelationship()); for(ObjectClass oc : ocs) { String fullClassName = null; for(AlternateName an : oc.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) fullClassName = an.getName(); } UMLClass clazz = classMap.get(fullClassName); Boolean reviewed = ownerReviewTracker.get(fullClassName); if(reviewed != null) { clazz.removeTaggedValue(XMIParser2.TV_OWNER_REVIEWED); clazz.addTaggedValue(XMIParser2.TV_OWNER_REVIEWED, reviewed?"1":"0"); } reviewed = curatorReviewTracker.get(fullClassName); if(reviewed != null) { clazz.removeTaggedValue(XMIParser2.TV_CURATOR_REVIEWED); clazz.addTaggedValue(XMIParser2.TV_CURATOR_REVIEWED, reviewed?"1":"0"); } } for(DataElementConcept dec : decs) { String fullClassName = null; for(AlternateName an : dec.getObjectClass().getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) fullClassName = an.getName(); } String fullPropName = fullClassName + "." + dec.getProperty().getLongName(); Boolean reviewed = ownerReviewTracker.get(fullPropName); if(reviewed != null) { UMLAttribute umlAtt = attributeMap.get(fullPropName); umlAtt.removeTaggedValue(XMIParser2.TV_OWNER_REVIEWED); umlAtt.addTaggedValue(XMIParser2.TV_OWNER_REVIEWED, reviewed?"1":"0"); } reviewed = curatorReviewTracker.get(fullPropName); if(reviewed != null) { UMLAttribute umlAtt = attributeMap.get(fullPropName); umlAtt.removeTaggedValue(XMIParser2.TV_CURATOR_REVIEWED); umlAtt.addTaggedValue(XMIParser2.TV_CURATOR_REVIEWED, reviewed?"1":"0"); } } for(ValueDomain vd : vds) { for(PermissibleValue pv : vd.getPermissibleValues()) { ValueMeaning vm = pv.getValueMeaning(); String fullPropName = "ValueDomains." + vd.getLongName() + "." + vm.getLongName(); Boolean reviewed = ownerReviewTracker.get(fullPropName); if(reviewed == null) { continue; } UMLAttribute umlAtt = attributeMap.get(fullPropName); umlAtt.removeTaggedValue(XMIParser2.TV_OWNER_REVIEWED); umlAtt.addTaggedValue(XMIParser2.TV_OWNER_REVIEWED, reviewed?"1":"0"); reviewed = curatorReviewTracker.get(fullPropName); if(reviewed == null) { continue; } umlAtt = attributeMap.get(fullPropName); umlAtt.removeTaggedValue(XMIParser2.TV_CURATOR_REVIEWED); umlAtt.addTaggedValue(XMIParser2.TV_CURATOR_REVIEWED, reviewed?"1":"0"); } } for(ObjectClassRelationship ocr : ocrs) { final OCRRoleNameBuilder nameBuilder = new OCRRoleNameBuilder(); final String fullPropName = nameBuilder.buildRoleName(ocr); final String tPropName = fullPropName + " Target"; final String sPropName = fullPropName + " Source"; final String key = ocr.getLongName()+"~"+ocr.getSourceRole()+"~"+ocr.getTargetRole(); final UMLAssociation assoc = assocMap.get(key); final UMLAssociationEnd target = assocEndMap.get(key+"~target"); final UMLAssociationEnd source = assocEndMap.get(key+"~source"); // ROLE Boolean reviewed = ownerReviewTracker.get(fullPropName); if(reviewed != null) refreshOwnerTag(assoc, reviewed); reviewed = curatorReviewTracker.get(fullPropName); if(reviewed != null) refreshCuratorTag(assoc, reviewed); // SOURCE reviewed = ownerReviewTracker.get(sPropName); if(reviewed != null) refreshOwnerTag(source, reviewed); reviewed = curatorReviewTracker.get(sPropName); if(reviewed != null) refreshCuratorTag(source, reviewed); // TARGET reviewed = ownerReviewTracker.get(tPropName); if(reviewed != null) refreshOwnerTag(target, reviewed); reviewed = curatorReviewTracker.get(tPropName); if(reviewed != null) refreshCuratorTag(target, reviewed); } } catch (RuntimeException e) { throw new ParserException(e); } } private void refreshCuratorTag(UMLTaggableElement umlElement, boolean reviewed) { umlElement.removeTaggedValue(XMIParser2.TV_CURATOR_REVIEWED); umlElement.addTaggedValue(XMIParser2.TV_CURATOR_REVIEWED, reviewed?"1":"0"); } private void refreshOwnerTag(UMLTaggableElement umlElement, boolean reviewed) { umlElement.removeTaggedValue(XMIParser2.TV_OWNER_REVIEWED); umlElement.addTaggedValue(XMIParser2.TV_OWNER_REVIEWED, reviewed?"1":"0"); } private void doPackage(UMLPackage pkg) { for(UMLClass clazz : pkg.getClasses()) { String className = null; String st = clazz.getStereotype(); boolean foundVd = false; if(st != null) for(int i=0; i < XMIParser2.validVdStereotypes.length; i++) { if(st.equalsIgnoreCase(XMIParser2.validVdStereotypes[i])) foundVd = true; } if(foundVd) { className = "ValueDomains." + clazz.getName(); } else { className = getPackageName(pkg) + "." + clazz.getName(); } classMap.put(className, clazz); for(UMLAttribute att : clazz.getAttributes()) { attributeMap.put(className + "." + att.getName(), att); } } for(UMLPackage subPkg : pkg.getPackages()) { doPackage(subPkg); } } protected void sendProgressEvent(int status, int goal, String message) { if(progressListener != null) { ProgressEvent pEvent = new ProgressEvent(); pEvent.setMessage(message); pEvent.setStatus(status); pEvent.setGoal(goal); progressListener.newProgressEvent(pEvent); } } private String getPackageName(UMLPackage pkg) { StringBuffer pack = new StringBuffer(); String s = null; do { s = null; if(pkg != null) { s = pkg.getName(); if(s.indexOf(" ") == -1) { if(pack.length() > 0) pack.insert(0, '.'); pack.insert(0, s); } pkg = pkg.getParent(); } } while (s != null); return pack.toString(); } }
src/gov/nih/nci/ncicb/cadsr/loader/parser/XMIWriter2.java
/* * Copyright 2000-2005 Oracle, Inc. This software was developed in conjunction with the National Cancer Institute, and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer of Article 3, below. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: * * "This product includes software developed by Oracle, Inc. and the National Cancer Institute." * * If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself, wherever such third-party acknowledgments normally appear. * * 3. The names "The National Cancer Institute", "NCI" and "Oracle" must not be used to endorse or promote products derived from this software. * * 4. This license does not authorize the incorporation of this software into any proprietary programs. This license does not authorize the recipient to use any trademarks owned by either NCI or Oracle, Inc. * * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, ORACLE, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE */ package gov.nih.nci.ncicb.cadsr.loader.parser; import gov.nih.nci.ncicb.cadsr.domain.*; import gov.nih.nci.ncicb.cadsr.loader.*; import gov.nih.nci.ncicb.cadsr.loader.persister.OCRRoleNameBuilder; import gov.nih.nci.ncicb.cadsr.loader.util.*; import gov.nih.nci.ncicb.cadsr.loader.event.ProgressListener; import gov.nih.nci.ncicb.cadsr.loader.event.ProgressEvent; import gov.nih.nci.ncicb.xmiinout.handler.*; import gov.nih.nci.ncicb.xmiinout.domain.*; import java.util.*; /** * A writer for XMI files * * @author <a href="mailto:[email protected]">Christophe Ludet</a> */ public class XMIWriter2 implements ElementWriter { private String output = null; private HashMap<String, UMLClass> classMap = new HashMap<String, UMLClass>(); private HashMap<String, UMLAttribute> attributeMap = new HashMap<String, UMLAttribute>(); private HashMap<String, UMLAssociation> assocMap = new HashMap<String, UMLAssociation>(); private HashMap<String, UMLAssociationEnd> assocEndMap = new HashMap<String, UMLAssociationEnd>(); private ElementsLists cadsrObjects = null; private ReviewTracker ownerReviewTracker = ReviewTracker.getInstance(ReviewTrackerType.Owner), curatorReviewTracker = ReviewTracker.getInstance(ReviewTrackerType.Curator); private ChangeTracker changeTracker = ChangeTracker.getInstance(); private ProgressListener progressListener; private UMLModel model = null; private XmiInOutHandler handler = null; public XMIWriter2() { } public void write(ElementsLists elements) throws ParserException { try { handler = (XmiInOutHandler)(UserSelections.getInstance().getProperty("XMI_HANDLER")); model = handler.getModel("EA Model"); this.cadsrObjects = elements; sendProgressEvent(0, 0, "Parsing Model"); readModel(); // doReviewTagLogic(); sendProgressEvent(0, 0, "Marking Human reviewed"); markHumanReviewed(); sendProgressEvent(0, 0, "Updating Elements"); updateChangedElements(); sendProgressEvent(0, 0, "ReWriting Model"); handler.save(output); } catch (Exception ex) { throw new RuntimeException("Error initializing model", ex); } } public void setOutput(String url) { this.output = url; } public void setProgressListener(ProgressListener listener) { progressListener = listener; } private void readModel() { for(UMLPackage pkg : model.getPackages()) doPackage(pkg); for(UMLAssociation assoc : model.getAssociations()) { List<UMLAssociationEnd> ends = assoc.getAssociationEnds(); UMLAssociationEnd aEnd = ends.get(0); UMLAssociationEnd bEnd = ends.get(1); UMLAssociationEnd source = bEnd, target = aEnd; // direction B? if (bEnd.isNavigable() && !aEnd.isNavigable()) { source = aEnd; target = bEnd; } String key = assoc.getRoleName()+"~"+source.getRoleName()+"~"+target.getRoleName(); assocMap.put(key,assoc); assocEndMap.put(key+"~source",source); assocEndMap.put(key+"~target",target); } } private void updateChangedElements() { List<ObjectClass> ocs = cadsrObjects.getElements(DomainObjectFactory.newObjectClass()); List<DataElement> des = cadsrObjects.getElements(DomainObjectFactory.newDataElement()); List<ValueDomain> vds = cadsrObjects.getElements(DomainObjectFactory.newValueDomain()); List<ObjectClassRelationship> ocrs = cadsrObjects.getElements(DomainObjectFactory.newObjectClassRelationship()); int goal = ocs.size() + des.size() + vds.size() + ocrs.size(); int status = 0; sendProgressEvent(status, goal, ""); for(ObjectClass oc : ocs) { String fullClassName = null; for(AlternateName an : oc.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) fullClassName = an.getName(); } sendProgressEvent(status++, goal, "Class: " + fullClassName); UMLClass clazz = classMap.get(fullClassName); boolean changed = changeTracker.get(fullClassName); if(changed) { // drop all current concept tagged values Collection<UMLTaggedValue> allTvs = clazz.getTaggedValues(); for(UMLTaggedValue tv : allTvs) { if(tv.getName().startsWith("ObjectClass") || tv.getName().startsWith("ObjectQualifier")) clazz.removeTaggedValue(tv.getName()); } String [] conceptCodes = oc.getPreferredName().split(":"); addConceptTvs(clazz, conceptCodes, XMIParser2.TV_TYPE_CLASS); } } for(DataElement de : des) { DataElementConcept dec = de.getDataElementConcept(); String fullPropName = null; for(AlternateName an : de.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_FULL_NAME)) fullPropName = an.getName(); } sendProgressEvent(status++, goal, "Attribute: " + fullPropName); UMLAttribute att = attributeMap.get(fullPropName); boolean changed = changeTracker.get(fullPropName); if(changed) { // drop all current concept tagged values Collection<UMLTaggedValue> allTvs = att.getTaggedValues(); for(UMLTaggedValue tv : allTvs) { if(tv.getName().startsWith("Property") || tv.getName().startsWith("PropertyQualifier")); att.removeTaggedValue(tv.getName()); } // Map to Existing DE if(!StringUtil.isEmpty(de.getPublicId()) && de.getVersion() != null) { att.addTaggedValue(XMIParser2.TV_DE_ID, de.getPublicId()); att.addTaggedValue(XMIParser2.TV_DE_VERSION, de.getVersion().toString()); } else { att.removeTaggedValue(XMIParser2.TV_DE_ID); att.removeTaggedValue(XMIParser2.TV_DE_VERSION); if(!StringUtil.isEmpty(de.getValueDomain().getPublicId()) && de.getValueDomain().getVersion() != null) { att.addTaggedValue(XMIParser2.TV_VD_ID, de.getValueDomain().getPublicId()); att.addTaggedValue(XMIParser2.TV_VD_VERSION, de.getValueDomain().getVersion().toString()); } else { att.removeTaggedValue(XMIParser2.TV_VD_ID); att.removeTaggedValue(XMIParser2.TV_VD_VERSION); } String [] conceptCodes = dec.getProperty().getPreferredName().split(":"); addConceptTvs(att, conceptCodes, XMIParser2.TV_TYPE_PROPERTY); } } } for(ValueDomain vd : vds) { sendProgressEvent(status++, goal, "Value Domain: " + vd.getLongName()); for(PermissibleValue pv : vd.getPermissibleValues()) { ValueMeaning vm = pv.getValueMeaning(); String fullPropName = "ValueDomains." + vd.getLongName() + "." + vm.getLongName(); UMLAttribute att = attributeMap.get(fullPropName); boolean changed = changeTracker.get(fullPropName); if(changed) { // drop all current concept tagged values Collection<UMLTaggedValue> allTvs = att.getTaggedValues(); for(UMLTaggedValue tv : allTvs) { if(tv.getName().startsWith(XMIParser2.TV_TYPE_VM) || tv.getName().startsWith(XMIParser2.TV_TYPE_VM + "Qualifier")) att.removeTaggedValue(tv.getName()); } String [] conceptCodes = ConceptUtil.getConceptCodes(vm); addConceptTvs(att, conceptCodes, XMIParser2.TV_TYPE_VM); } } } for(ObjectClassRelationship ocr : ocrs) { ConceptDerivationRule rule = ocr.getConceptDerivationRule(); ConceptDerivationRule srule = ocr.getSourceRoleConceptDerivationRule(); ConceptDerivationRule trule = ocr.getTargetRoleConceptDerivationRule(); OCRRoleNameBuilder nameBuilder = new OCRRoleNameBuilder(); String fullName = nameBuilder.buildRoleName(ocr); sendProgressEvent(status++, goal, "Relationship: " + fullName); String key = ocr.getLongName()+"~"+ocr.getSourceRole()+"~"+ocr.getTargetRole(); UMLAssociation assoc = assocMap.get(key); UMLAssociationEnd source = assocEndMap.get(key+"~source"); UMLAssociationEnd target = assocEndMap.get(key+"~target"); boolean changed = changeTracker.get(fullName); boolean changedSource = changeTracker.get(fullName+" Source"); boolean changedTarget = changeTracker.get(fullName+" Target"); if(changed) { dropCurrentAssocTvs(assoc); List<ComponentConcept> rConcepts = rule.getComponentConcepts(); String[] rcodes = new String[rConcepts.size()]; int i = 0; for (ComponentConcept con: rConcepts) { rcodes[i++] = con.getConcept().getPreferredName(); } addConceptTvs(assoc, rcodes, XMIParser2.TV_TYPE_ASSOC_ROLE); } if(changedSource) { dropCurrentAssocTvs(source); List<ComponentConcept> sConcepts = srule.getComponentConcepts(); String[] scodes = new String[sConcepts.size()]; int i = 0; for (ComponentConcept con: sConcepts) { scodes[i++] = con.getConcept().getPreferredName(); } addConceptTvs(source, scodes, XMIParser2.TV_TYPE_ASSOC_SOURCE); } if(changedTarget) { dropCurrentAssocTvs(target); List<ComponentConcept> tConcepts = trule.getComponentConcepts(); String[] tcodes = new String[tConcepts.size()]; int i = 0; for (ComponentConcept con: tConcepts) { tcodes[i++] = con.getConcept().getPreferredName(); } addConceptTvs(target, tcodes, XMIParser2.TV_TYPE_ASSOC_TARGET); } } changeTracker.clear(); } private void dropCurrentAssocTvs(UMLTaggableElement elt) { Collection<UMLTaggedValue> allTvs = elt.getTaggedValues(); for(UMLTaggedValue tv : allTvs) { String name = tv.getName(); if(name.startsWith(XMIParser2.TV_TYPE_ASSOC_ROLE) || name.startsWith(XMIParser2.TV_TYPE_ASSOC_SOURCE)|| name.startsWith(XMIParser2.TV_TYPE_ASSOC_TARGET)) { elt.removeTaggedValue(name); } } } private void addConceptTvs(UMLTaggableElement elt, String[] conceptCodes, String type) { if(conceptCodes.length == 0) return; addConceptTv(elt, conceptCodes[conceptCodes.length - 1], type, "", 0); for(int i= 1; i < conceptCodes.length; i++) { addConceptTv(elt, conceptCodes[conceptCodes.length - i - 1], type, XMIParser2.TV_QUALIFIER, i); } } private void addConceptTv(UMLTaggableElement elt, String conceptCode, String type, String pre, int n) { Concept con = LookupUtil.lookupConcept(conceptCode); if(con == null) return; String tvName = type + pre + XMIParser2.TV_CONCEPT_CODE + ((n>0)?""+n:""); if(con.getPreferredName() != null) elt.addTaggedValue(tvName,con.getPreferredName()); tvName = type + pre + XMIParser2.TV_CONCEPT_DEFINITION + ((n>0)?""+n:""); if(con.getPreferredDefinition() != null) elt.addTaggedValue(tvName,con.getPreferredDefinition()); tvName = type + pre + XMIParser2.TV_CONCEPT_DEFINITION_SOURCE + ((n>0)?""+n:""); if(con.getDefinitionSource() != null) elt.addTaggedValue(tvName,con.getDefinitionSource()); tvName = type + pre + XMIParser2.TV_CONCEPT_PREFERRED_NAME + ((n>0)?""+n:""); if(con.getLongName() != null) elt.addTaggedValue (tvName, con.getLongName()); // tvName = type + pre + XMIParser2.TV_TYPE_VM + ((n>0)?""+n:""); // // if(con.getLongName() != null) // elt.addTaggedValue // (tvName, // con.getLongName()); } private void markHumanReviewed() throws ParserException { try{ List<ObjectClass> ocs = cadsrObjects.getElements(DomainObjectFactory.newObjectClass()); List<DataElementConcept> decs = cadsrObjects.getElements(DomainObjectFactory.newDataElementConcept()); List<ValueDomain> vds = cadsrObjects.getElements(DomainObjectFactory.newValueDomain()); List<ObjectClassRelationship> ocrs = cadsrObjects.getElements(DomainObjectFactory.newObjectClassRelationship()); for(ObjectClass oc : ocs) { String fullClassName = null; for(AlternateName an : oc.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) fullClassName = an.getName(); } UMLClass clazz = classMap.get(fullClassName); Boolean reviewed = ownerReviewTracker.get(fullClassName); if(reviewed != null) { clazz.removeTaggedValue(XMIParser2.TV_OWNER_REVIEWED); clazz.addTaggedValue(XMIParser2.TV_OWNER_REVIEWED, reviewed?"1":"0"); } reviewed = curatorReviewTracker.get(fullClassName); if(reviewed != null) { clazz.removeTaggedValue(XMIParser2.TV_CURATOR_REVIEWED); clazz.addTaggedValue(XMIParser2.TV_CURATOR_REVIEWED, reviewed?"1":"0"); } } for(DataElementConcept dec : decs) { String fullClassName = null; for(AlternateName an : dec.getObjectClass().getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) fullClassName = an.getName(); } String fullPropName = fullClassName + "." + dec.getProperty().getLongName(); Boolean reviewed = ownerReviewTracker.get(fullPropName); if(reviewed != null) { UMLAttribute umlAtt = attributeMap.get(fullPropName); umlAtt.removeTaggedValue(XMIParser2.TV_OWNER_REVIEWED); umlAtt.addTaggedValue(XMIParser2.TV_OWNER_REVIEWED, reviewed?"1":"0"); } reviewed = curatorReviewTracker.get(fullPropName); if(reviewed != null) { UMLAttribute umlAtt = attributeMap.get(fullPropName); umlAtt.removeTaggedValue(XMIParser2.TV_CURATOR_REVIEWED); umlAtt.addTaggedValue(XMIParser2.TV_CURATOR_REVIEWED, reviewed?"1":"0"); } } for(ValueDomain vd : vds) { for(PermissibleValue pv : vd.getPermissibleValues()) { ValueMeaning vm = pv.getValueMeaning(); String fullPropName = "ValueDomains." + vd.getLongName() + "." + vm.getLongName(); Boolean reviewed = ownerReviewTracker.get(fullPropName); if(reviewed == null) { continue; } UMLAttribute umlAtt = attributeMap.get(fullPropName); umlAtt.removeTaggedValue(XMIParser2.TV_OWNER_REVIEWED); umlAtt.addTaggedValue(XMIParser2.TV_OWNER_REVIEWED, reviewed?"1":"0"); reviewed = curatorReviewTracker.get(fullPropName); if(reviewed == null) { continue; } umlAtt = attributeMap.get(fullPropName); umlAtt.removeTaggedValue(XMIParser2.TV_CURATOR_REVIEWED); umlAtt.addTaggedValue(XMIParser2.TV_CURATOR_REVIEWED, reviewed?"1":"0"); } } for(ObjectClassRelationship ocr : ocrs) { final OCRRoleNameBuilder nameBuilder = new OCRRoleNameBuilder(); final String fullPropName = nameBuilder.buildRoleName(ocr); final String tPropName = fullPropName + " Target"; final String sPropName = fullPropName + " Source"; final String key = ocr.getLongName()+"~"+ocr.getSourceRole()+"~"+ocr.getTargetRole(); final UMLAssociation assoc = assocMap.get(key); final UMLAssociationEnd target = assocEndMap.get(key+"~target"); final UMLAssociationEnd source = assocEndMap.get(key+"~source"); // ROLE Boolean reviewed = ownerReviewTracker.get(fullPropName); if(reviewed != null) refreshOwnerTag(assoc, reviewed); reviewed = curatorReviewTracker.get(fullPropName); if(reviewed != null) refreshCuratorTag(assoc, reviewed); // SOURCE reviewed = ownerReviewTracker.get(sPropName); if(reviewed != null) refreshOwnerTag(source, reviewed); reviewed = curatorReviewTracker.get(sPropName); if(reviewed != null) refreshCuratorTag(source, reviewed); // TARGET reviewed = ownerReviewTracker.get(tPropName); if(reviewed != null) refreshOwnerTag(target, reviewed); reviewed = curatorReviewTracker.get(tPropName); if(reviewed != null) refreshCuratorTag(target, reviewed); } } catch (RuntimeException e) { throw new ParserException(e); } } private void refreshCuratorTag(UMLTaggableElement umlElement, boolean reviewed) { umlElement.removeTaggedValue(XMIParser2.TV_CURATOR_REVIEWED); umlElement.addTaggedValue(XMIParser2.TV_CURATOR_REVIEWED, reviewed?"1":"0"); } private void refreshOwnerTag(UMLTaggableElement umlElement, boolean reviewed) { umlElement.removeTaggedValue(XMIParser2.TV_OWNER_REVIEWED); umlElement.addTaggedValue(XMIParser2.TV_OWNER_REVIEWED, reviewed?"1":"0"); } private void doPackage(UMLPackage pkg) { for(UMLClass clazz : pkg.getClasses()) { String className = null; String st = clazz.getStereotype(); boolean foundVd = false; if(st != null) for(int i=0; i < XMIParser2.validVdStereotypes.length; i++) { if(st.equalsIgnoreCase(XMIParser2.validVdStereotypes[i])) foundVd = true; } if(foundVd) { className = "ValueDomains." + clazz.getName(); } else { className = getPackageName(pkg) + "." + clazz.getName(); } classMap.put(className, clazz); for(UMLAttribute att : clazz.getAttributes()) { attributeMap.put(className + "." + att.getName(), att); } } for(UMLPackage subPkg : pkg.getPackages()) { doPackage(subPkg); } } protected void sendProgressEvent(int status, int goal, String message) { if(progressListener != null) { ProgressEvent pEvent = new ProgressEvent(); pEvent.setMessage(message); pEvent.setStatus(status); pEvent.setGoal(goal); progressListener.newProgressEvent(pEvent); } } private String getPackageName(UMLPackage pkg) { StringBuffer pack = new StringBuffer(); String s = null; do { s = null; if(pkg != null) { s = pkg.getName(); if(s.indexOf(" ") == -1) { if(pack.length() > 0) pack.insert(0, '.'); pack.insert(0, s); } pkg = pkg.getParent(); } } while (s != null); return pack.toString(); } }
fixed human reviewed tags not being saved SVN-Revision: 1259
src/gov/nih/nci/ncicb/cadsr/loader/parser/XMIWriter2.java
fixed human reviewed tags not being saved
<ide><path>rc/gov/nih/nci/ncicb/cadsr/loader/parser/XMIWriter2.java <ide> Collection<UMLTaggedValue> allTvs = att.getTaggedValues(); <ide> for(UMLTaggedValue tv : allTvs) { <ide> if(tv.getName().startsWith("Property") || <del> tv.getName().startsWith("PropertyQualifier")); <del> att.removeTaggedValue(tv.getName()); <add> tv.getName().startsWith("PropertyQualifier")) <add> att.removeTaggedValue(tv.getName()); <ide> } <ide> <ide> // Map to Existing DE
Java
apache-2.0
096b8b84e0dba8cdf0e0f7afae8d118a68e06e6c
0
mihbor/kafka,guozhangwang/kafka,rhauch/kafka,mihbor/kafka,ijuma/kafka,lindong28/kafka,ollie314/kafka,TiVo/kafka,sslavic/kafka,sslavic/kafka,ijuma/kafka,Esquive/kafka,ijuma/kafka,geeag/kafka,rhauch/kafka,gf53520/kafka,sebadiaz/kafka,eribeiro/kafka,geeag/kafka,lindong28/kafka,TiVo/kafka,MyPureCloud/kafka,ErikKringen/kafka,lindong28/kafka,themarkypantz/kafka,themarkypantz/kafka,gf53520/kafka,Chasego/kafka,eribeiro/kafka,richhaase/kafka,KevinLiLu/kafka,MyPureCloud/kafka,Ishiihara/kafka,Esquive/kafka,airbnb/kafka,geeag/kafka,KevinLiLu/kafka,ollie314/kafka,Ishiihara/kafka,sebadiaz/kafka,ErikKringen/kafka,sebadiaz/kafka,mihbor/kafka,apache/kafka,Ishiihara/kafka,rhauch/kafka,ollie314/kafka,Chasego/kafka,guozhangwang/kafka,TiVo/kafka,richhaase/kafka,noslowerdna/kafka,airbnb/kafka,MyPureCloud/kafka,apache/kafka,sslavic/kafka,noslowerdna/kafka,guozhangwang/kafka,rhauch/kafka,richhaase/kafka,apache/kafka,gf53520/kafka,ijuma/kafka,KevinLiLu/kafka,apache/kafka,richhaase/kafka,ollie314/kafka,sslavic/kafka,Ishiihara/kafka,noslowerdna/kafka,ErikKringen/kafka,guozhangwang/kafka,sebadiaz/kafka,themarkypantz/kafka,themarkypantz/kafka,noslowerdna/kafka,eribeiro/kafka,Chasego/kafka,airbnb/kafka,geeag/kafka,airbnb/kafka,eribeiro/kafka,KevinLiLu/kafka,gf53520/kafka,lindong28/kafka,mihbor/kafka,Chasego/kafka,ErikKringen/kafka,MyPureCloud/kafka,Esquive/kafka,TiVo/kafka,Esquive/kafka
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.clients.producer; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.record.Record; /** * The metadata for a record that has been acknowledged by the server */ public final class RecordMetadata { /** * Partition value for record without partition assigned */ public static final int UNKNOWN_PARTITION = -1; private final long offset; // The timestamp of the message. // If LogAppendTime is used for the topic, the timestamp will be the timestamp returned by the broker. // If CreateTime is used for the topic, the timestamp is the timestamp in the corresponding ProducerRecord if the // user provided one. Otherwise, it will be the producer local time when the producer record was handed to the // producer. private final long timestamp; private final long checksum; private final int serializedKeySize; private final int serializedValueSize; private final TopicPartition topicPartition; private RecordMetadata(TopicPartition topicPartition, long offset, long timestamp, long checksum, int serializedKeySize, int serializedValueSize) { super(); this.offset = offset; this.timestamp = timestamp; this.checksum = checksum; this.serializedKeySize = serializedKeySize; this.serializedValueSize = serializedValueSize; this.topicPartition = topicPartition; } @Deprecated public RecordMetadata(TopicPartition topicPartition, long baseOffset, long relativeOffset) { this(topicPartition, baseOffset, relativeOffset, Record.NO_TIMESTAMP, -1, -1, -1); } public RecordMetadata(TopicPartition topicPartition, long baseOffset, long relativeOffset, long timestamp, long checksum, int serializedKeySize, int serializedValueSize) { // ignore the relativeOffset if the base offset is -1, // since this indicates the offset is unknown this(topicPartition, baseOffset == -1 ? baseOffset : baseOffset + relativeOffset, timestamp, checksum, serializedKeySize, serializedValueSize); } /** * The offset of the record in the topic/partition. */ public long offset() { return this.offset; } /** * The timestamp of the record in the topic/partition. */ public long timestamp() { return timestamp; } /** * The checksum (CRC32) of the record. */ public long checksum() { return this.checksum; } /** * The size of the serialized, uncompressed key in bytes. If key is null, the returned size * is -1. */ public int serializedKeySize() { return this.serializedKeySize; } /** * The size of the serialized, uncompressed value in bytes. If value is null, the returned * size is -1. */ public int serializedValueSize() { return this.serializedValueSize; } /** * The topic the record was appended to */ public String topic() { return this.topicPartition.topic(); } /** * The partition the record was sent to */ public int partition() { return this.topicPartition.partition(); } @Override public String toString() { return topicPartition.toString() + "@" + offset; } }
clients/src/main/java/org/apache/kafka/clients/producer/RecordMetadata.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.clients.producer; import org.apache.kafka.common.TopicPartition; /** * The metadata for a record that has been acknowledged by the server */ public final class RecordMetadata { /** * Partition value for record without partition assigned */ public static final int UNKNOWN_PARTITION = -1; private final long offset; // The timestamp of the message. // If LogAppendTime is used for the topic, the timestamp will be the timestamp returned by the broker. // If CreateTime is used for the topic, the timestamp is the timestamp in the corresponding ProducerRecord if the // user provided one. Otherwise, it will be the producer local time when the producer record was handed to the // producer. private final long timestamp; private final long checksum; private final int serializedKeySize; private final int serializedValueSize; private final TopicPartition topicPartition; private RecordMetadata(TopicPartition topicPartition, long offset, long timestamp, long checksum, int serializedKeySize, int serializedValueSize) { super(); this.offset = offset; this.timestamp = timestamp; this.checksum = checksum; this.serializedKeySize = serializedKeySize; this.serializedValueSize = serializedValueSize; this.topicPartition = topicPartition; } public RecordMetadata(TopicPartition topicPartition, long baseOffset, long relativeOffset, long timestamp, long checksum, int serializedKeySize, int serializedValueSize) { // ignore the relativeOffset if the base offset is -1, // since this indicates the offset is unknown this(topicPartition, baseOffset == -1 ? baseOffset : baseOffset + relativeOffset, timestamp, checksum, serializedKeySize, serializedValueSize); } /** * The offset of the record in the topic/partition. */ public long offset() { return this.offset; } /** * The timestamp of the record in the topic/partition. */ public long timestamp() { return timestamp; } /** * The checksum (CRC32) of the record. */ public long checksum() { return this.checksum; } /** * The size of the serialized, uncompressed key in bytes. If key is null, the returned size * is -1. */ public int serializedKeySize() { return this.serializedKeySize; } /** * The size of the serialized, uncompressed value in bytes. If value is null, the returned * size is -1. */ public int serializedValueSize() { return this.serializedValueSize; } /** * The topic the record was appended to */ public String topic() { return this.topicPartition.topic(); } /** * The partition the record was sent to */ public int partition() { return this.topicPartition.partition(); } @Override public String toString() { return topicPartition.toString() + "@" + offset; } }
KAFKA-3641; Fix RecordMetadata constructor backward compatibility Author: Grant Henke <[email protected]> Reviewers: Gwen Shapira, Ismael Juma Closes #1292 from granthenke/recordmeta-compat
clients/src/main/java/org/apache/kafka/clients/producer/RecordMetadata.java
KAFKA-3641; Fix RecordMetadata constructor backward compatibility
<ide><path>lients/src/main/java/org/apache/kafka/clients/producer/RecordMetadata.java <ide> package org.apache.kafka.clients.producer; <ide> <ide> import org.apache.kafka.common.TopicPartition; <add>import org.apache.kafka.common.record.Record; <ide> <ide> /** <ide> * The metadata for a record that has been acknowledged by the server <ide> this.serializedKeySize = serializedKeySize; <ide> this.serializedValueSize = serializedValueSize; <ide> this.topicPartition = topicPartition; <add> } <add> <add> @Deprecated <add> public RecordMetadata(TopicPartition topicPartition, long baseOffset, long relativeOffset) { <add> this(topicPartition, baseOffset, relativeOffset, Record.NO_TIMESTAMP, -1, -1, -1); <ide> } <ide> <ide> public RecordMetadata(TopicPartition topicPartition, long baseOffset, long relativeOffset,
Java
apache-2.0
d7cf7775b4b7378bde09ae3242152efe58d0249a
0
HaiJiaoXinHeng/server-1,hongsudt/server,HaiJiaoXinHeng/server-1,HaiJiaoXinHeng/server-1,hongsudt/server,hongsudt/server
package edu.ucla.cens.awserver.validator.json; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import edu.ucla.cens.awserver.datatransfer.AwRequest; import edu.ucla.cens.awserver.util.JsonUtils; import edu.ucla.cens.awserver.validator.AwRequestAnnotator; /** * An implementation of AwRequestAnnotator for validation failures which ultimately result in JSON output (initially used * in response to phone/device data uploads). * * @author selsky */ public class FailedJsonRequestAnnotator implements AwRequestAnnotator { private static Logger logger = Logger.getLogger(FailedJsonRequestAnnotator.class); private String _jsonErrorMessage; /** * The provided error message will be used as JSON output and must be a syntactically valid JSON Object. * * @throws IllegalArgumentException if jsonErrorMessage is null * @throws IllegalArgumentException if jsonErrorMessage string cannot be parsed to syntactically correct JSON (it must be a * valid JSON array.) */ public FailedJsonRequestAnnotator(String jsonErrorMessage) { if(null == jsonErrorMessage) { throw new IllegalArgumentException("a null jsonErrorObject string is not allowed"); } try { new JSONObject(jsonErrorMessage); // No variable assignment because all that's needed is the parse implicit in the // constructor. Unfortunately, this particular JSON API does not contain static // methods such as JSONObject.isValid(String jsonString) so the constructor is abused // instead. } catch (JSONException jsonException) { throw new IllegalArgumentException("the jsonErrorObject is invalid JSON"); } _jsonErrorMessage = jsonErrorMessage; } /** * Annotates the request with a failed error message using JSON syntax. The JSON message is of the form: * <pre> * { * "request_url":"user's request url", * "request_json":"the original JSON sent with the request", * "errors":[ * { * A JSON Object that is represented by the message supplied on construction of this class. * } * ] * } * </pre> * * The message passed in is used for debug output only. For cases where the JSONObject representing the error output message * must be passed into this method, @see FailedJsonSuppliedMessageRequestAnnotator. * * Since the upload URL is public to the internet, there are cases where no data is posted because someone (malicious or not) * is hitting the URL. In this case, only the request URL is logged. * */ public void annotate(AwRequest awRequest, String message) { awRequest.setFailedRequest(true); JSONObject jsonObject = null; try { jsonObject = new JSONObject(_jsonErrorMessage); // this is ugly because it assumes the structure of the error message, the way errors should be configured is // that error codes and text should be set instead of a JSON string TODO JSONArray errorArray = JsonUtils.getJsonArrayFromJsonObject(jsonObject, "errors"); JSONObject errorObject = JsonUtils.getJsonObjectFromJsonArray(errorArray, 0); if(null != awRequest.getAttribute("currentMessageIndex")) { errorObject.put("at_record_number", (Integer) awRequest.getAttribute("currentMessageIndex")); } if(null != awRequest.getAttribute("currentPromptId")) { // a prompt upload is being handled. errorObject.put("at_prompt_id", (Integer) awRequest.getAttribute("currentPromptId")); } // Now add the original request URL and the original JSON input message to the error output // If the JSON data is longer than 250 characters, an info message is sent back instead in order to // avoid echoing extremely large messages back to the client and into the server logs jsonObject.put("request_url", awRequest.getAttribute("requestUrl")); Object data = awRequest.getAttribute("jsonData"); if(null != data) { jsonObject.put("request_json", getDataTruncatedMessage(((JSONArray) data).toString())); } } catch(JSONException jsone) { // invalid JSON at this point is a logical error throw new IllegalStateException(jsone); } awRequest.setFailedRequestErrorMessage(jsonObject.toString()); if(logger.isDebugEnabled()) { logger.debug(message); } } /** * @return "check server logs for input data" if the input string is over 250 characters */ private String getDataTruncatedMessage(String string) { if(null != string) { if(string.length() > 250) { return "check upload file dump for input data"; } } return string; } }
src/edu/ucla/cens/awserver/validator/json/FailedJsonRequestAnnotator.java
package edu.ucla.cens.awserver.validator.json; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import edu.ucla.cens.awserver.datatransfer.AwRequest; import edu.ucla.cens.awserver.util.JsonUtils; import edu.ucla.cens.awserver.validator.AwRequestAnnotator; /** * An implementation of AwRequestAnnotator for validation failures which ultimately result in JSON output (initially used * in response to phone/device data uploads). * * @author selsky */ public class FailedJsonRequestAnnotator implements AwRequestAnnotator { private static Logger logger = Logger.getLogger(FailedJsonRequestAnnotator.class); private String _jsonErrorMessage; /** * The provided error message will be used as JSON output and must be a syntactically valid JSON Object. * * @throws IllegalArgumentException if jsonErrorMessage is null * @throws IllegalArgumentException if jsonErrorMessage string cannot be parsed to syntactically correct JSON (it must be a * valid JSON array.) */ public FailedJsonRequestAnnotator(String jsonErrorMessage) { if(null == jsonErrorMessage) { throw new IllegalArgumentException("a null jsonErrorObject string is not allowed"); } try { new JSONObject(jsonErrorMessage); // No variable assignment because all that's needed is the parse implicit in the // constructor. Unfortunately, this particular JSON API does not contain static // methods such as JSONObject.isValid(String jsonString) so the constructor is abused // instead. } catch (JSONException jsonException) { throw new IllegalArgumentException("the jsonErrorObject is invalid JSON"); } _jsonErrorMessage = jsonErrorMessage; } /** * Annotates the request with a failed error message using JSON syntax. The JSON message is of the form: * <pre> * { * "request_url":"user's request url", * "request_json":"the original JSON sent with the request", * "errors":[ * { * A JSON Object that is represented by the message supplied on construction of this class. * } * ] * } * </pre> * * The message passed in is used for debug output only. For cases where the JSONObject representing the error output message * must be passed into this method, @see FailedJsonSuppliedMessageRequestAnnotator. */ public void annotate(AwRequest awRequest, String message) { awRequest.setFailedRequest(true); JSONObject jsonObject = null; try { jsonObject = new JSONObject(_jsonErrorMessage); // this is ugly because it assumes the structure of the error message, the way errors should be configured is // that error codes and text should be set instead of a JSON string TODO JSONArray errorArray = JsonUtils.getJsonArrayFromJsonObject(jsonObject, "errors"); JSONObject errorObject = JsonUtils.getJsonObjectFromJsonArray(errorArray, 0); errorObject.put("at_record_number", (Integer) awRequest.getAttribute("currentMessageIndex")); if(null != awRequest.getAttribute("currentPromptId")) { // a prompt upload is being handled. errorObject.put("at_prompt_id", (Integer) awRequest.getAttribute("currentPromptId")); } // Now add the original request URL and the original JSON input message to the error output // If the JSON data is longer than 250 characters, an info message is sent back instead in order to // avoid echoing extremely large messages back to the client and into the server logs jsonObject.put("request_url", awRequest.getAttribute("requestUrl")); jsonObject.put("request_json", getDataTruncatedMessage(((JSONArray) awRequest.getAttribute("jsonData")).toString())); } catch(JSONException jsone) { // invalid JSON at this point is a logical error throw new IllegalStateException(jsone); } awRequest.setFailedRequestErrorMessage(jsonObject.toString()); if(logger.isDebugEnabled()) { logger.debug(message); } } /** * @return "check server logs for input data" if the input string is over 250 characters */ private String getDataTruncatedMessage(String string) { if(null != string) { if(string.length() > 250) { return "check upload file dump for input data"; } } return string; } }
added defensive code to handle cases where the request fails due to missing parameter data
src/edu/ucla/cens/awserver/validator/json/FailedJsonRequestAnnotator.java
added defensive code to handle cases where the request fails due to missing parameter data
<ide><path>rc/edu/ucla/cens/awserver/validator/json/FailedJsonRequestAnnotator.java <ide> * <ide> * The message passed in is used for debug output only. For cases where the JSONObject representing the error output message <ide> * must be passed into this method, @see FailedJsonSuppliedMessageRequestAnnotator. <add> * <add> * Since the upload URL is public to the internet, there are cases where no data is posted because someone (malicious or not) <add> * is hitting the URL. In this case, only the request URL is logged. <add> * <ide> */ <ide> public void annotate(AwRequest awRequest, String message) { <ide> awRequest.setFailedRequest(true); <ide> <ide> // this is ugly because it assumes the structure of the error message, the way errors should be configured is <ide> // that error codes and text should be set instead of a JSON string TODO <add> <ide> JSONArray errorArray = JsonUtils.getJsonArrayFromJsonObject(jsonObject, "errors"); <ide> JSONObject errorObject = JsonUtils.getJsonObjectFromJsonArray(errorArray, 0); <ide> <del> errorObject.put("at_record_number", (Integer) awRequest.getAttribute("currentMessageIndex")); <add> if(null != awRequest.getAttribute("currentMessageIndex")) { <add> <add> errorObject.put("at_record_number", (Integer) awRequest.getAttribute("currentMessageIndex")); <add> <add> } <ide> <ide> if(null != awRequest.getAttribute("currentPromptId")) { // a prompt upload is being handled. <ide> <ide> // If the JSON data is longer than 250 characters, an info message is sent back instead in order to <ide> // avoid echoing extremely large messages back to the client and into the server logs <ide> jsonObject.put("request_url", awRequest.getAttribute("requestUrl")); <del> jsonObject.put("request_json", getDataTruncatedMessage(((JSONArray) awRequest.getAttribute("jsonData")).toString())); <del> <add> <add> Object data = awRequest.getAttribute("jsonData"); <add> if(null != data) { <add> <add> jsonObject.put("request_json", getDataTruncatedMessage(((JSONArray) data).toString())); <add> <add> } <ide> <ide> } catch(JSONException jsone) { // invalid JSON at this point is a logical error <ide>
JavaScript
mit
f0879a6ab9b27fb854b7519719a1cbbdce58a8f2
0
Kenny-/Pokemon-Showdown
/** * Rooms * Pokemon Showdown - http://pokemonshowdown.com/ * * Every chat room and battle is a room, and what they do is done in * rooms.js. There's also a global room which every user is in, and * handles miscellaneous things like welcoming the user. * * @license MIT license */ const TIMEOUT_EMPTY_DEALLOCATE = 10 * 60 * 1000; const TIMEOUT_INACTIVE_DEALLOCATE = 40 * 60 * 1000; const REPORT_USER_STATS_INTERVAL = 1000 * 60 * 10; var fs = require('fs'); var GlobalRoom = (function () { function GlobalRoom(roomid) { this.id = roomid; this.i = {}; // init battle rooms this.rooms = []; this.battleCount = 0; this.searchers = []; // Never do any other file IO synchronously // but this is okay to prevent race conditions as we start up PS this.lastBattle = 0; try { this.lastBattle = parseInt(fs.readFileSync('logs/lastbattle.txt')) || 0; } catch (e) {} // file doesn't exist [yet] this.chatRoomData = []; try { this.chatRoomData = JSON.parse(fs.readFileSync('config/chatrooms.json')); if (!Array.isArray(this.chatRoomData)) this.chatRoomData = []; } catch (e) {} // file doesn't exist [yet] if (!this.chatRoomData.length) { this.chatRoomData = [{ title: 'Lobby', autojoin: true }, { title: 'Staff', isPrivate: true, staffRoom: true, staffAutojoin: true }]; } this.chatRooms = []; this.autojoin = []; // rooms that users autojoin upon connecting this.staffAutojoin = []; // rooms that staff autojoin upon connecting for (var i = 0; i < this.chatRoomData.length; i++) { if (!this.chatRoomData[i] || !this.chatRoomData[i].title) { console.log('ERROR: Room number ' + i + ' has no data.'); continue; } var id = toId(this.chatRoomData[i].title); console.log("NEW CHATROOM: " + id); var room = rooms[id] = new ChatRoom(id, this.chatRoomData[i].title, this.chatRoomData[i]); this.chatRooms.push(room); if (room.autojoin) this.autojoin.push(id); if (room.staffAutojoin) this.staffAutojoin.push(id); } // this function is complex in order to avoid several race conditions var self = this; this.writeNumRooms = (function () { var writing = false; var lastBattle; // last lastBattle to be written to file var finishWriting = function () { writing = false; if (lastBattle < self.lastBattle) { self.writeNumRooms(); } }; return function () { if (writing) return; // batch writing lastbattle.txt for every 10 battles if (lastBattle >= self.lastBattle) return; lastBattle = self.lastBattle + 10; writing = true; fs.writeFile('logs/lastbattle.txt.0', '' + lastBattle, function () { // rename is atomic on POSIX, but will throw an error on Windows fs.rename('logs/lastbattle.txt.0', 'logs/lastbattle.txt', function (err) { if (err) { // This should only happen on Windows. fs.writeFile('logs/lastbattle.txt', '' + lastBattle, finishWriting); return; } finishWriting(); }); }); }; })(); this.writeChatRoomData = (function () { var writing = false; var writePending = false; // whether or not a new write is pending var finishWriting = function () { writing = false; if (writePending) { writePending = false; self.writeChatRoomData(); } }; return function () { if (writing) { writePending = true; return; } writing = true; var data = JSON.stringify(self.chatRoomData).replace(/\{"title"\:/g, '\n{"title":').replace(/\]$/, '\n]'); fs.writeFile('config/chatrooms.json.0', data, function () { // rename is atomic on POSIX, but will throw an error on Windows fs.rename('config/chatrooms.json.0', 'config/chatrooms.json', function (err) { if (err) { // This should only happen on Windows. fs.writeFile('config/chatrooms.json', data, finishWriting); return; } finishWriting(); }); }); }; })(); // init users this.users = {}; this.userCount = 0; // cache of `Object.size(this.users)` this.maxUsers = 0; this.maxUsersDate = 0; this.reportUserStatsInterval = setInterval( this.reportUserStats.bind(this), REPORT_USER_STATS_INTERVAL ); } GlobalRoom.prototype.type = 'global'; GlobalRoom.prototype.formatListText = '|formats'; GlobalRoom.prototype.reportUserStats = function () { if (this.maxUsersDate) { LoginServer.request('updateuserstats', { date: this.maxUsersDate, users: this.maxUsers }, function () {}); this.maxUsersDate = 0; } LoginServer.request('updateuserstats', { date: Date.now(), users: Object.size(this.users) }, function () {}); }; GlobalRoom.prototype.getFormatListText = function () { var formatListText = '|formats'; var curSection = ''; for (var i in Tools.data.Formats) { var format = Tools.data.Formats[i]; if (!format.challengeShow && !format.searchShow) continue; var section = format.section; if (section === undefined) section = format.mod; if (!section) section = ''; if (section !== curSection) { curSection = section; formatListText += '|,' + (format.column || 1) + '|' + section; } formatListText += '|' + format.name; if (!format.challengeShow) formatListText += ',,'; else if (!format.searchShow) formatListText += ','; if (format.team) formatListText += ',#'; } return formatListText; }; GlobalRoom.prototype.getRoomList = function (filter) { var roomList = {}; var total = 0; for (var i = this.rooms.length - 1; i >= 0; i--) { var room = this.rooms[i]; if (!room || !room.active) continue; if (filter && filter !== room.format && filter !== true) continue; var roomData = {}; if (room.active && room.battle) { if (room.battle.players[0]) roomData.p1 = room.battle.players[0].getIdentity(); if (room.battle.players[1]) roomData.p2 = room.battle.players[1].getIdentity(); } if (!roomData.p1 || !roomData.p2) continue; roomList[room.id] = roomData; total++; if (total >= 6 && !filter) break; } return roomList; }; GlobalRoom.prototype.getRooms = function () { var rooms = {official:[], chat:[], userCount: this.userCount, battleCount: this.battleCount}; for (var i = 0; i < this.chatRooms.length; i++) { var room = this.chatRooms[i]; if (!room) continue; if (room.isPrivate) continue; (room.isOfficial ? rooms.official : rooms.chat).push({ title: room.title, desc: room.desc, userCount: Object.size(room.users) }); } return rooms; }; GlobalRoom.prototype.cancelSearch = function (user) { var success = false; user.cancelChallengeTo(); for (var i = 0; i < this.searchers.length; i++) { var search = this.searchers[i]; var searchUser = Users.get(search.userid); if (!searchUser.connected) { this.searchers.splice(i, 1); i--; continue; } if (searchUser === user) { this.searchers.splice(i, 1); i--; if (!success) { searchUser.send('|updatesearch|' + JSON.stringify({searching: false})); success = true; } continue; } } return success; }; GlobalRoom.prototype.searchBattle = function (user, formatid) { if (!user.connected) return; formatid = toId(formatid); user.prepBattle(formatid, 'search', null, this.finishSearchBattle.bind(this, user, formatid)); }; GlobalRoom.prototype.finishSearchBattle = function (user, formatid, result) { if (!result) return; // tell the user they've started searching var newSearchData = { format: formatid }; user.send('|updatesearch|' + JSON.stringify({searching: newSearchData})); // get the user's rating before actually starting to search var newSearch = { userid: user.userid, formatid: formatid, team: user.team, rating: 1000, time: new Date().getTime() }; var self = this; user.doWithMMR(formatid, function (mmr, error) { if (error) { user.popup("Connection to ladder server failed with error: " + error + "; please try again later"); return; } newSearch.rating = mmr; self.addSearch(newSearch, user); }); }; GlobalRoom.prototype.matchmakingOK = function (search1, search2, user1, user2) { // users must be different if (user1 === user2) return false; // users must not have been matched immediately previously if (user1.lastMatch === user2.userid || user2.lastMatch === user1.userid) return false; // search must be within range var searchRange = 100, formatid = search1.formatid, elapsed = Math.abs(search1.time - search2.time); if (formatid === 'ou' || formatid === 'oucurrent' || formatid === 'randombattle') searchRange = 50; searchRange += elapsed / 300; // +1 every .3 seconds if (searchRange > 300) searchRange = 300; if (Math.abs(search1.rating - search2.rating) > searchRange) return false; user1.lastMatch = user2.userid; user2.lastMatch = user1.userid; return true; }; GlobalRoom.prototype.addSearch = function (newSearch, user) { if (!user.connected) return; for (var i = 0; i < this.searchers.length; i++) { var search = this.searchers[i]; var searchUser = Users.get(search.userid); if (!searchUser || !searchUser.connected) { this.searchers.splice(i, 1); i--; continue; } if (newSearch.formatid === search.formatid && searchUser === user) return; // only one search per format if (newSearch.formatid === search.formatid && this.matchmakingOK(search, newSearch, searchUser, user)) { this.cancelSearch(user, true); this.cancelSearch(searchUser, true); user.send('|updatesearch|' + JSON.stringify({searching: false})); this.startBattle(searchUser, user, search.formatid, true, search.team, newSearch.team); return; } } this.searchers.push(newSearch); }; GlobalRoom.prototype.send = function (message, user) { if (user) { user.sendTo(this, message); } else { Sockets.channelBroadcast(this.id, message); } }; GlobalRoom.prototype.sendAuth = function (message) { for (var i in this.users) { var user = this.users[i]; if (user.connected && user.can('receiveauthmessages', null, this)) { user.sendTo(this, message); } } }; GlobalRoom.prototype.updateRooms = function (excludeUser) { // do nothing }; GlobalRoom.prototype.add = function (message, noUpdate) { if (rooms.lobby) rooms.lobby.add(message, noUpdate); }; GlobalRoom.prototype.addRaw = function (message) { if (rooms.lobby) rooms.lobby.addRaw(message); }; GlobalRoom.prototype.addChatRoom = function (title) { var id = toId(title); if (rooms[id]) return false; var chatRoomData = { title: title }; var room = rooms[id] = new ChatRoom(id, title, chatRoomData); this.chatRoomData.push(chatRoomData); this.chatRooms.push(room); this.writeChatRoomData(); return true; }; GlobalRoom.prototype.deregisterChatRoom = function (id) { id = toId(id); var room = rooms[id]; if (!room) return false; // room doesn't exist if (!room.chatRoomData) return false; // room isn't registered // deregister from global chatRoomData // looping from the end is a pretty trivial optimization, but the // assumption is that more recently added rooms are more likely to // be deleted for (var i = this.chatRoomData.length - 1; i >= 0; i--) { if (id === toId(this.chatRoomData[i].title)) { this.chatRoomData.splice(i, 1); this.writeChatRoomData(); break; } } delete room.chatRoomData; return true; }; GlobalRoom.prototype.delistChatRoom = function (id) { id = toId(id); if (!rooms[id]) return false; // room doesn't exist for (var i = this.chatRooms.length - 1; i >= 0; i--) { if (id === this.chatRooms[i].id) { this.chatRooms.splice(i, 1); break; } } }; GlobalRoom.prototype.removeChatRoom = function (id) { id = toId(id); var room = rooms[id]; if (!room) return false; // room doesn't exist room.destroy(); return true; }; GlobalRoom.prototype.autojoinRooms = function (user, connection) { // we only autojoin regular rooms if the client requests it with /autojoin // note that this restriction doesn't apply to staffAutojoin for (var i = 0; i < this.autojoin.length; i++) { user.joinRoom(this.autojoin[i], connection); } }; GlobalRoom.prototype.checkAutojoin = function (user, connection) { if (user.isStaff) { for (var i = 0; i < this.staffAutojoin.length; i++) { user.joinRoom(this.staffAutojoin[i], connection); } } }; GlobalRoom.prototype.onJoinConnection = function (user, connection) { var initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n'; connection.send(initdata + this.formatListText); if (this.chatRooms.length > 2) connection.send('|queryresponse|rooms|null'); // should display room list }; GlobalRoom.prototype.onJoin = function (user, connection, merging) { if (!user) return false; // ??? if (this.users[user.userid]) return user; this.users[user.userid] = user; if (++this.userCount > this.maxUsers) { this.maxUsers = this.userCount; this.maxUsersDate = Date.now(); } if (!merging) { var initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n'; connection.send(initdata + this.formatListText); if (this.chatRooms.length > 2) connection.send('|queryresponse|rooms|null'); // should display room list } return user; }; GlobalRoom.prototype.onRename = function (user, oldid, joining) { delete this.users[oldid]; this.users[user.userid] = user; return user; }; GlobalRoom.prototype.onUpdateIdentity = function () {}; GlobalRoom.prototype.onLeave = function (user) { if (!user) return; // ... delete this.users[user.userid]; --this.userCount; this.cancelSearch(user, true); }; GlobalRoom.prototype.startBattle = function (p1, p2, format, rated, p1team, p2team) { var newRoom; p1 = Users.get(p1); p2 = Users.get(p2); if (!p1 || !p2) { // most likely, a user was banned during the battle start procedure this.cancelSearch(p1, true); this.cancelSearch(p2, true); return; } if (p1 === p2) { this.cancelSearch(p1, true); this.cancelSearch(p2, true); p1.popup("You can't battle your own account. Please use something like Private Browsing to battle yourself."); return; } if (this.lockdown) { this.cancelSearch(p1, true); this.cancelSearch(p2, true); p1.popup("The server is shutting down. Battles cannot be started at this time."); p2.popup("The server is shutting down. Battles cannot be started at this time."); return; } //console.log('BATTLE START BETWEEN: ' + p1.userid + ' ' + p2.userid); var i = this.lastBattle + 1; var formaturlid = format.toLowerCase().replace(/[^a-z0-9]+/g, ''); while(rooms['battle-' + formaturlid + i]) { i++; } this.lastBattle = i; rooms.global.writeNumRooms(); newRoom = this.addRoom('battle-' + formaturlid + '-' + i, format, p1, p2, this.id, rated); p1.joinRoom(newRoom); p2.joinRoom(newRoom); newRoom.joinBattle(p1, p1team); newRoom.joinBattle(p2, p2team); this.cancelSearch(p1, true); this.cancelSearch(p2, true); if (Config.reportbattles && rooms.lobby) { rooms.lobby.add('|b|' + newRoom.id + '|' + p1.getIdentity() + '|' + p2.getIdentity()); } return newRoom; }; GlobalRoom.prototype.addRoom = function (room, format, p1, p2, parent, rated) { room = newRoom(room, format, p1, p2, parent, rated); if (this.id in room.i) return; room.i[this.id] = this.rooms.length; this.rooms.push(room); return room; }; GlobalRoom.prototype.removeRoom = function (room) { room = getRoom(room); if (!room) return; if (this.id in room.i) { this.rooms.splice(room.i[this.id], 1); delete room.i[this.id]; for (var i = 0; i < this.rooms.length; i++) { this.rooms[i].i[this.id] = i; } } }; GlobalRoom.prototype.chat = function (user, message, connection) { if (rooms.lobby) return rooms.lobby.chat(user, message, connection); message = CommandParser.parse(message, this, user, connection); if (message) { connection.sendPopup("You can't send messages directly to the server."); } }; return GlobalRoom; })(); var BattleRoom = (function () { function BattleRoom(roomid, format, p1, p2, parentid, rated) { this.id = roomid; this.title = "" + p1.name + " vs. " + p2.name; this.i = {}; this.modchat = (Config.battlemodchat || false); format = '' + (format || ''); this.users = {}; this.format = format; this.auth = {}; //console.log("NEW BATTLE"); var formatid = toId(format); if (rated && Tools.getFormat(formatid).rated !== false) { rated = { p1: p1.userid, p2: p2.userid, format: format }; } else { rated = false; } this.rated = rated; this.battle = Simulator.create(this.id, format, rated, this); this.parentid = parentid || ''; this.p1 = p1 || ''; this.p2 = p2 || ''; this.sideTicksLeft = [21, 21]; if (!rated) this.sideTicksLeft = [28, 28]; this.sideTurnTicks = [0, 0]; this.disconnectTickDiff = [0, 0]; this.log = []; if (Config.forcetimer) this.requestKickInactive(false); } BattleRoom.prototype.type = 'battle'; BattleRoom.prototype.resetTimer = null; BattleRoom.prototype.resetUser = ''; BattleRoom.prototype.expireTimer = null; BattleRoom.prototype.active = false; BattleRoom.prototype.lastUpdate = 0; BattleRoom.prototype.push = function (message) { if (typeof message === 'string') { this.log.push(message); } else { this.log = this.log.concat(message); } }; BattleRoom.prototype.win = function (winner) { if (Clans.setWarMatchResult(this.p1, this.p2, winner)) { var result = "drawn"; if (toId(winner) === toId(this.p1)) result = "won"; else if (toId(winner) === toId(this.p2)) result = "lost"; var war = Clans.findWarFromClan(Clans.findClanFromMember(this.p1)); Clans.getWarRoom(war[0]).add('|raw|<div class="clans-war-battle-result">(' + Tools.escapeHTML(war[0]) + " vs " + Tools.escapeHTML(war[1]) + ") " + Tools.escapeHTML(this.p1) + " has " + result + " the clan war battle against " + Tools.escapeHTML(this.p2) + '</div>'); var room = Clans.getWarRoom(war[0]); var warEnd = Clans.isWarEnded(war[0]); if (warEnd) { result = "drawn"; if (warEnd.result === 1) result = "won"; else if (warEnd.result === 0) result = "lost"; room.add('|raw|' + '<div class="clans-war-end">' + Tools.escapeHTML(war[0]) + " has " + result + " the clan war against " + Tools.escapeHTML(war[1]) + '</div>' + '<strong>' + Tools.escapeHTML(war[0]) + ':</strong> ' + warEnd.oldRatings[0] + " &rarr; " + warEnd.newRatings[0] + " (" + Clans.ratingToName(warEnd.newRatings[0]) + ")<br />" + '<strong>' + Tools.escapeHTML(war[1]) + ':</strong> ' + warEnd.oldRatings[1] + " &rarr; " + warEnd.newRatings[1] + " (" + Clans.ratingToName(warEnd.newRatings[1]) + ")" ); } } if (this.rated) { var winnerid = toId(winner); var rated = this.rated; this.rated = false; var p1score = 0.5; if (winnerid === rated.p1) { p1score = 1; } else if (winnerid === rated.p2) { p1score = 0; } var p1 = rated.p1; if (Users.getExact(rated.p1)) p1 = Users.getExact(rated.p1).name; var p2 = rated.p2; if (Users.getExact(rated.p2)) p2 = Users.getExact(rated.p2).name; //update.updates.push('[DEBUG] uri: ' + Config.loginserver + 'action.php?act=ladderupdate&serverid=' + Config.serverid + '&p1=' + encodeURIComponent(p1) + '&p2=' + encodeURIComponent(p2) + '&score=' + p1score + '&format=' + toId(rated.format) + '&servertoken=[token]'); if (!rated.p1 || !rated.p2) { this.push('|raw|ERROR: Ladder not updated: a player does not exist'); } else { var winner = Users.get(winnerid); if (winner && !winner.authenticated) { this.send('|askreg|' + winner.userid, winner); } var p1rating, p2rating; // update rankings this.push('|raw|Ladder updating...'); var self = this; LoginServer.request('ladderupdate', { p1: p1, p2: p2, score: p1score, format: toId(rated.format) }, function (data, statusCode, error) { if (!self.battle) { console.log('room expired before ladder update was received'); return; } if (!data) { self.addRaw('Ladder (probably) updated, but score could not be retrieved (' + error + ').'); self.update(); // log the battle anyway if (!Tools.getFormat(self.format).noLog) { self.logBattle(p1score); } return; } else if (data.errorip) { self.addRaw("This server's request IP " + data.errorip + " is not a registered server."); return; } else { try { p1rating = data.p1rating; p2rating = data.p2rating; //self.add("Ladder updated."); var oldacre = Math.round(data.p1rating.oldacre); var acre = Math.round(data.p1rating.acre); var reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.99 ? 'winning' : (p1score < 0.01 ? 'losing' : 'tying')); if (reasons.substr(0, 1) !== '-') reasons = '+' + reasons; self.addRaw(Tools.escapeHTML(p1) + '\'s rating: ' + oldacre + ' &rarr; <strong>' + acre + '</strong><br />(' + reasons + ')'); oldacre = Math.round(data.p2rating.oldacre); acre = Math.round(data.p2rating.acre); reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.99 ? 'losing' : (p1score < 0.01 ? 'winning' : 'tying')); if (reasons.substr(0, 1) !== '-') reasons = '+' + reasons; self.addRaw(Tools.escapeHTML(p2) + '\'s rating: ' + oldacre + ' &rarr; <strong>' + acre + '</strong><br />(' + reasons + ')'); Users.get(p1).cacheMMR(rated.format, data.p1rating); Users.get(p2).cacheMMR(rated.format, data.p2rating); self.update(); } catch(e) { self.addRaw('There was an error calculating rating changes.'); self.update(); } if (!Tools.getFormat(self.format).noLog) { self.logBattle(p1score, p1rating, p2rating); } } }); } } rooms.global.battleCount += 0 - (this.active ? 1 : 0); this.active = false; this.update(); }; // idx = 0, 1 : player log // idx = 2 : spectator log // idx = 3 : replay log BattleRoom.prototype.getLog = function (idx) { var log = []; for (var i = 0; i < this.log.length; ++i) { var line = this.log[i]; if (line === '|split') { log.push(this.log[i + idx + 1]); i += 4; } else { log.push(line); } } return log; }; BattleRoom.prototype.getLogForUser = function (user) { var slot = this.battle.getSlot(user); if (slot < 0) slot = 2; return this.getLog(slot); }; BattleRoom.prototype.update = function (excludeUser) { if (this.log.length <= this.lastUpdate) return; var logs = [[], [], []]; var updateLines = this.log.slice(this.lastUpdate); for (var i = 0; i < updateLines.length;) { var line = updateLines[i++]; if (line === '|split') { logs[0].push(updateLines[i++]); // player 0 logs[1].push(updateLines[i++]); // player 1 logs[2].push(updateLines[i++]); // spectators i++; // replays } else { logs[0].push(line); logs[1].push(line); logs[2].push(line); } } var roomid = this.id; var self = this; logs = logs.map(function (log) { return log.join('\n'); }); this.lastUpdate = this.log.length; var hasUsers = false; for (var i in this.users) { var user = this.users[i]; hasUsers = true; if (user === excludeUser) continue; var slot = this.battle.getSlot(user); if (slot < 0) slot = 2; this.send(logs[slot], user); } // empty rooms time out after ten minutes if (!hasUsers) { if (!this.expireTimer) { this.expireTimer = setTimeout(this.tryExpire.bind(this), TIMEOUT_EMPTY_DEALLOCATE); } } else { if (this.expireTimer) clearTimeout(this.expireTimer); this.expireTimer = setTimeout(this.tryExpire.bind(this), TIMEOUT_INACTIVE_DEALLOCATE); } }; BattleRoom.prototype.logBattle = function (p1score, p1rating, p2rating) { var logData = this.battle.logData; logData.p1rating = p1rating; logData.p2rating = p2rating; logData.endType = this.battle.endType; if (!p1rating) logData.ladderError = true; logData.log = BattleRoom.prototype.getLog.call(logData, 3); // replay log (exact damage) var date = new Date(); var logfolder = date.format('{yyyy}-{MM}'); var logsubfolder = date.format('{yyyy}-{MM}-{dd}'); var curpath = 'logs/' + logfolder; var self = this; fs.mkdir(curpath, '0755', function () { var tier = self.format.toLowerCase().replace(/[^a-z0-9]+/g, ''); curpath += '/' + tier; fs.mkdir(curpath, '0755', function () { curpath += '/' + logsubfolder; fs.mkdir(curpath, '0755', function () { fs.writeFile(curpath + '/' + self.id + '.log.json', JSON.stringify(logData)); }); }); }); // asychronicity //console.log(JSON.stringify(logData)); }; BattleRoom.prototype.send = function (message, user) { if (user) { user.sendTo(this, message); } else { Sockets.channelBroadcast(this.id, '>' + this.id + '\n' + message); } }; BattleRoom.prototype.tryExpire = function () { this.expire(); }; BattleRoom.prototype.reset = function (reload) { clearTimeout(this.resetTimer); this.resetTimer = null; this.resetUser = ''; if (rooms.global.lockdown) { this.add('The battle was not restarted because the server is preparing to shut down.'); return; } this.add('RESET'); this.update(); rooms.global.battleCount += 0 - (this.active ? 1 : 0); this.active = false; if (this.parentid) { getRoom(this.parentid).updateRooms(); } }; BattleRoom.prototype.getInactiveSide = function () { if (this.battle.players[0] && !this.battle.players[1]) return 1; if (this.battle.players[1] && !this.battle.players[0]) return 0; return this.battle.inactiveSide; }; BattleRoom.prototype.forfeit = function (user, message, side) { if (!this.battle || this.battle.ended || !this.battle.started) return false; if (!message) message = ' forfeited.'; if (side === undefined) { if (user && user.userid === this.battle.playerids[0]) side = 0; if (user && user.userid === this.battle.playerids[1]) side = 1; } if (side === undefined) return false; var ids = ['p1', 'p2']; var otherids = ['p2', 'p1']; var name = 'Player ' + (side + 1); if (user) { name = user.name; } else if (this.rated) { name = this.rated[ids[side]]; } this.addCmd('-message', name + message); this.battle.endType = 'forfeit'; this.battle.send('win', otherids[side]); rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; this.update(); return true; }; BattleRoom.prototype.kickInactive = function () { clearTimeout(this.resetTimer); this.resetTimer = null; if (!this.battle || this.battle.ended || !this.battle.started) return false; var inactiveSide = this.getInactiveSide(); var ticksLeft = [0, 0]; if (inactiveSide != 1) { // side 0 is inactive this.sideTurnTicks[0]--; this.sideTicksLeft[0]--; } if (inactiveSide != 0) { // side 1 is inactive this.sideTurnTicks[1]--; this.sideTicksLeft[1]--; } ticksLeft[0] = Math.min(this.sideTurnTicks[0], this.sideTicksLeft[0]); ticksLeft[1] = Math.min(this.sideTurnTicks[1], this.sideTicksLeft[1]); if (ticksLeft[0] && ticksLeft[1]) { if (inactiveSide === 0 || inactiveSide === 1) { // one side is inactive var inactiveTicksLeft = ticksLeft[inactiveSide]; var inactiveUser = this.battle.getPlayer(inactiveSide); if (inactiveTicksLeft % 3 === 0 || inactiveTicksLeft <= 4) { this.send('|inactive|' + (inactiveUser ? inactiveUser.name : 'Player ' + (inactiveSide + 1)) + ' has ' + (inactiveTicksLeft * 10) + ' seconds left.'); } } else { // both sides are inactive var inactiveUser0 = this.battle.getPlayer(0); if (ticksLeft[0] % 3 === 0 || ticksLeft[0] <= 4) { this.send('|inactive|' + (inactiveUser0 ? inactiveUser0.name : 'Player 1') + ' has ' + (ticksLeft[0] * 10) + ' seconds left.', inactiveUser0); } var inactiveUser1 = this.battle.getPlayer(1); if (ticksLeft[1] % 3 === 0 || ticksLeft[1] <= 4) { this.send('|inactive|' + (inactiveUser1 ? inactiveUser1.name : 'Player 2') + ' has ' + (ticksLeft[1] * 10) + ' seconds left.', inactiveUser1); } } this.resetTimer = setTimeout(this.kickInactive.bind(this), 10 * 1000); return; } if (inactiveSide < 0) { if (ticksLeft[0]) inactiveSide = 1; else if (ticksLeft[1]) inactiveSide = 0; } this.forfeit(this.battle.getPlayer(inactiveSide), ' lost due to inactivity.', inactiveSide); this.resetUser = ''; if (this.parentid) { getRoom(this.parentid).updateRooms(); } }; BattleRoom.prototype.requestKickInactive = function (user, force) { if (this.resetTimer) { if (user) this.send('|inactive|The inactivity timer is already counting down.', user); return false; } if (user) { if (!force && this.battle.getSlot(user) < 0) return false; this.resetUser = user.userid; this.send('|inactive|Battle timer is now ON: inactive players will automatically lose when time\'s up. (requested by ' + user.name + ')'); } else if (user === false) { this.resetUser = '~'; this.add('|inactive|Battle timer is ON: inactive players will automatically lose when time\'s up.'); } // a tick is 10 seconds var maxTicksLeft = 15; // 2 minutes 30 seconds if (!this.battle.p1 || !this.battle.p2) { // if a player has left, don't wait longer than 6 ticks (1 minute) maxTicksLeft = 6; } if (!this.rated) maxTicksLeft = 30; this.sideTurnTicks = [maxTicksLeft, maxTicksLeft]; var inactiveSide = this.getInactiveSide(); if (inactiveSide < 0) { // add 10 seconds to bank if they're below 160 seconds if (this.sideTicksLeft[0] < 16) this.sideTicksLeft[0]++; if (this.sideTicksLeft[1] < 16) this.sideTicksLeft[1]++; } this.sideTicksLeft[0]++; this.sideTicksLeft[1]++; if (inactiveSide != 1) { // side 0 is inactive var ticksLeft0 = Math.min(this.sideTicksLeft[0] + 1, maxTicksLeft); this.send('|inactive|You have ' + (ticksLeft0 * 10) + ' seconds to make your decision.', this.battle.getPlayer(0)); } if (inactiveSide != 0) { // side 1 is inactive var ticksLeft1 = Math.min(this.sideTicksLeft[1] + 1, maxTicksLeft); this.send('|inactive|You have ' + (ticksLeft1 * 10) + ' seconds to make your decision.', this.battle.getPlayer(1)); } this.resetTimer = setTimeout(this.kickInactive.bind(this), 10 * 1000); return true; }; BattleRoom.prototype.nextInactive = function () { if (this.resetTimer) { this.update(); clearTimeout(this.resetTimer); this.resetTimer = null; this.requestKickInactive(); } }; BattleRoom.prototype.stopKickInactive = function (user, force) { if (!force && user && user.userid !== this.resetUser) return false; if (this.resetTimer) { clearTimeout(this.resetTimer); this.resetTimer = null; this.send('|inactiveoff|Battle timer is now OFF.'); return true; } return false; }; BattleRoom.prototype.kickInactiveUpdate = function () { if (!this.rated) return false; if (this.resetTimer) { var inactiveSide = this.getInactiveSide(); var changed = false; if ((!this.battle.p1 || !this.battle.p2) && !this.disconnectTickDiff[0] && !this.disconnectTickDiff[1]) { if ((!this.battle.p1 && inactiveSide === 0) || (!this.battle.p2 && inactiveSide === 1)) { var inactiveUser = this.battle.getPlayer(inactiveSide); if (!this.battle.p1 && inactiveSide === 0 && this.sideTurnTicks[0] > 7) { this.disconnectTickDiff[0] = this.sideTurnTicks[0] - 7; this.sideTurnTicks[0] = 7; changed = true; } else if (!this.battle.p2 && inactiveSide === 1 && this.sideTurnTicks[1] > 7) { this.disconnectTickDiff[1] = this.sideTurnTicks[1] - 7; this.sideTurnTicks[1] = 7; changed = true; } if (changed) { this.send('|inactive|' + (inactiveUser ? inactiveUser.name : 'Player ' + (inactiveSide + 1)) + ' disconnected and has a minute to reconnect!'); return true; } } } else if (this.battle.p1 && this.battle.p2) { // Only one of the following conditions should happen, but do // them both since you never know... if (this.disconnectTickDiff[0]) { this.sideTurnTicks[0] = this.sideTurnTicks[0] + this.disconnectTickDiff[0]; this.disconnectTickDiff[0] = 0; changed = 0; } if (this.disconnectTickDiff[1]) { this.sideTurnTicks[1] = this.sideTurnTicks[1] + this.disconnectTickDiff[1]; this.disconnectTickDiff[1] = 0; changed = 1; } if (changed !== false) { var user = this.battle.getPlayer(changed); this.send('|inactive|' + (user ? user.name : 'Player ' + (changed + 1)) + ' reconnected and has ' + (this.sideTurnTicks[changed] * 10) + ' seconds left!'); return true; } } } return false; }; BattleRoom.prototype.decision = function (user, choice, data) { this.battle.sendFor(user, choice, data); if (this.active !== this.battle.active) { rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; if (this.parentid) { getRoom(this.parentid).updateRooms(); } } this.update(); }; // This function is only called when the room is not empty. // Joining an empty room calls this.join() below instead. BattleRoom.prototype.onJoinConnection = function (user, connection) { this.send('|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n'), connection); // this handles joining a battle in which a user is a participant, // where the user has already identified before attempting to join // the battle this.battle.resendRequest(user); }; BattleRoom.prototype.onJoin = function (user, connection) { if (!user) return false; if (this.users[user.userid]) return user; this.users[user.userid] = user; if (user.named) { this.addCmd('join', user.name); this.update(user); } this.send('|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n'), connection); return user; }; BattleRoom.prototype.onRename = function (user, oldid, joining) { if (joining) { this.addCmd('join', user.name); } var resend = joining || !this.battle.playerTable[oldid]; if (this.battle.playerTable[oldid]) { if (this.rated) { this.add('|message|' + user.name + ' forfeited by changing their name.'); this.battle.lose(oldid); this.battle.leave(oldid); resend = false; } else { this.battle.rename(); } } delete this.users[oldid]; this.users[user.userid] = user; this.update(); if (resend) { // this handles a named user renaming themselves into a user in the // battle (i.e. by using /nick) this.battle.resendRequest(user); } return user; }; BattleRoom.prototype.onUpdateIdentity = function () {}; BattleRoom.prototype.onLeave = function (user) { if (!user) return; // ... if (user.battles[this.id]) { this.battle.leave(user); rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; if (this.parentid) { getRoom(this.parentid).updateRooms(); } } else if (!user.named) { delete this.users[user.userid]; return; } delete this.users[user.userid]; this.addCmd('leave', user.name); if (Object.isEmpty(this.users)) { rooms.global.battleCount += 0 - (this.active ? 1 : 0); this.active = false; } this.update(); this.kickInactiveUpdate(); }; BattleRoom.prototype.joinBattle = function (user, team) { var slot = undefined; if (this.rated) { if (this.rated.p1 === user.userid) { slot = 0; } else if (this.rated.p2 === user.userid) { slot = 1; } else { user.popup("This is a rated battle; your username must be " + this.rated.p1 + " or " + this.rated.p2 + " to join."); return false; } } this.auth[user.userid] = '\u2605'; this.battle.join(user, slot, team); rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; if (this.active) { this.title = "" + this.battle.p1 + " vs. " + this.battle.p2; this.send('|title|' + this.title); } this.update(); this.kickInactiveUpdate(); if (this.parentid) { getRoom(this.parentid).updateRooms(); } }; BattleRoom.prototype.leaveBattle = function (user) { if (!user) return false; // ... if (user.battles[this.id]) { this.battle.leave(user); } else { return false; } this.auth[user.userid] = '+'; rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; this.update(); this.kickInactiveUpdate(); if (this.parentid) { getRoom(this.parentid).updateRooms(); } return true; }; BattleRoom.prototype.addCmd = function () { this.log.push('|' + Array.prototype.slice.call(arguments).join('|')); }; BattleRoom.prototype.add = function (message) { if (message.rawMessage) { this.addCmd('raw', message.rawMessage); } else if (message.name) { this.addCmd('chat', message.name.substr(1), message.message); } else { this.log.push(message); } }; BattleRoom.prototype.addRaw = function (message) { this.addCmd('raw', message); }; BattleRoom.prototype.chat = function (user, message, connection) { // Battle actions are actually just text commands that are handled in // parseCommand(), which in turn often calls Simulator.prototype.sendFor(). // Sometimes the call to sendFor is done indirectly, by calling // room.decision(), where room.constructor === BattleRoom. message = CommandParser.parse(message, this, user, connection); if (message) { if (ShadowBan.isShadowBanned(user)) { ShadowBan.room.add('|c|' + user.getIdentity() + "|__(To " + this.id + ")__ " + message); connection.sendTo(this, '|chat|' + user.name + '|' + message); } else { this.battle.chat(user, message); } } this.update(); }; BattleRoom.prototype.logEntry = function () {}; BattleRoom.prototype.expire = function () { this.send('|expire|'); this.destroy(); }; BattleRoom.prototype.destroy = function () { // deallocate ourself // remove references to ourself for (var i in this.users) { this.users[i].leaveRoom(this); delete this.users[i]; } this.users = null; rooms.global.removeRoom(this.id); // deallocate children and get rid of references to them if (this.battle) { this.battle.destroy(); } this.battle = null; if (this.resetTimer) { clearTimeout(this.resetTimer); } this.resetTimer = null; // get rid of some possibly-circular references delete rooms[this.id]; }; return BattleRoom; })(); var ChatRoom = (function () { function ChatRoom(roomid, title, options) { if (options) { this.chatRoomData = options; Object.merge(this, options); } this.id = roomid; this.title = title || roomid; this.i = {}; this.log = []; this.logTimes = []; this.lastUpdate = 0; this.users = {}; this.searchers = []; this.logFile = null; this.logFilename = ''; this.destroyingLog = false; this.bannedUsers = {}; this.bannedIps = {}; this.active = true; this.inactiveCount = 0; if (!this.modchat) this.modchat = (Config.chatmodchat || false); if (Config.logchat) { this.rollLogFile(true); this.logEntry = function (entry, date) { var timestamp = (new Date()).format('{HH}:{mm}:{ss} '); this.logFile.write(timestamp + entry + '\n'); }; this.logEntry('NEW CHATROOM: ' + this.id); if (Config.loguserstats) { setInterval(this.logUserStats.bind(this), Config.loguserstats); } } if (Config.reportjoinsperiod) { this.userList = this.getUserList(); this.reportJoinsQueue = []; this.reportJoinsInterval = setInterval( this.reportRecentJoins.bind(this), Config.reportjoinsperiod ); } } ChatRoom.prototype.type = 'chat'; ChatRoom.prototype.reportRecentJoins = function () { if (this.reportJoinsQueue.length === 0) { // nothing to report return; } if (Config.reportjoinsperiod) { this.userList = this.getUserList(); } this.send(this.reportJoinsQueue.join('\n')); this.reportJoinsQueue.length = 0; }; ChatRoom.prototype.rollLogFile = function (sync) { var mkdir = sync ? (function (path, mode, callback) { try { fs.mkdirSync(path, mode); } catch (e) {} // directory already exists callback(); }) : fs.mkdir; var date = new Date(); var basepath = 'logs/chat/' + this.id + '/'; var self = this; mkdir(basepath, '0755', function () { var path = date.format('{yyyy}-{MM}'); mkdir(basepath + path, '0755', function () { if (self.destroyingLog) return; path += '/' + date.format('{yyyy}-{MM}-{dd}') + '.txt'; if (path !== self.logFilename) { self.logFilename = path; if (self.logFile) self.logFile.destroySoon(); self.logFile = fs.createWriteStream(basepath + path, {flags: 'a'}); // Create a symlink to today's lobby log. // These operations need to be synchronous, but it's okay // because this code is only executed once every 24 hours. var link0 = basepath + 'today.txt.0'; try { fs.unlinkSync(link0); } catch (e) {} // file doesn't exist try { fs.symlinkSync(path, link0); // `basepath` intentionally not included try { fs.renameSync(link0, basepath + 'today.txt'); } catch (e) {} // OS doesn't support atomic rename } catch (e) {} // OS doesn't support symlinks } var timestamp = +date; date.advance('1 hour').reset('minutes').advance('1 second'); setTimeout(self.rollLogFile.bind(self), +date - timestamp); }); }); }; ChatRoom.prototype.destroyLog = function (initialCallback, finalCallback) { this.destroyingLog = true; initialCallback(); if (this.logFile) { this.logEntry = function () { }; this.logFile.on('close', finalCallback); this.logFile.destroySoon(); } else { finalCallback(); } }; ChatRoom.prototype.logUserStats = function () { var total = 0; var guests = 0; var groups = {}; Config.groupsranking.forEach(function (group) { groups[group] = 0; }); for (var i in this.users) { var user = this.users[i]; ++total; if (!user.named) { ++guests; } ++groups[user.group]; } var entry = '|userstats|total:' + total + '|guests:' + guests; for (var i in groups) { entry += '|' + i + ':' + groups[i]; } this.logEntry(entry); }; ChatRoom.prototype.getUserList = function () { var buffer = ''; var counter = 0; for (var i in this.users) { if (!this.users[i].named) { continue; } counter++; buffer += ',' + this.users[i].getIdentity(this.id); } var msg = '|users|' + counter + buffer; return msg; }; ChatRoom.prototype.update = function () { if (this.log.length <= this.lastUpdate) return; var entries = this.log.slice(this.lastUpdate); var update = entries.join('\n'); if (this.log.length > 100) { this.log.splice(0, this.log.length - 100); this.logTimes.splice(0, this.logTimes.length - 100); } this.lastUpdate = this.log.length; this.send(update); }; ChatRoom.prototype.send = function (message, user) { if (user) { user.sendTo(this, message); } else { if (this.id !== 'lobby') message = '>' + this.id + '\n' + message; Sockets.channelBroadcast(this.id, message); } }; ChatRoom.prototype.sendAuth = function (message) { for (var i in this.users) { var user = this.users[i]; if (user.connected && user.can('receiveauthmessages', null, this)) { user.sendTo(this, message); } } }; ChatRoom.prototype.add = function (message, noUpdate) { this.logTimes.push(~~(Date.now() / 1000)); this.log.push(message); this.logEntry(message); if (!noUpdate) { this.update(); } }; ChatRoom.prototype.addRaw = function (message) { this.add('|raw|' + message); }; ChatRoom.prototype.logGetLast = function (amount, noTime) { if (!amount) { return []; } if (amount < 0) { amount *= -1; } var logLength = this.log.length; if (!logLength) { return []; } var log = []; var time = ~~(Date.now() / 1000); for (var i = logLength - amount - 1; i < logLength; i++) { if (i < 0) { i = 0; } var logText = this.log[i]; if (!logText){ continue; } if (!noTime && logText.substr(0, 3) === '|c|') { // Time is only added when it's a normal chat message logText = '|tc|' + (time - this.logTimes[i]) + '|' + logText.substr(3); } log.push(logText); } return log; }; ChatRoom.prototype.getIntroMessage = function () { var html = this.introMessage || ''; if (this.modchat) { if (html) html += '<br /><br />'; html += '<div class="broadcast-red">'; html += '<b>Moderated chat is currently set to ' + this.modchat + '!</b><br />'; html += 'Only users of rank ' + this.modchat + ' and higher can talk.'; html += '</div>'; } if (html) return '\n|raw|<div class="infobox">' + html + '</div>'; return ''; }; ChatRoom.prototype.onJoinConnection = function (user, connection) { var userList = this.userList ? this.userList : this.getUserList(); this.send('|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.logGetLast(25).join('\n') + this.getIntroMessage(), connection); if (global.Tournaments && Tournaments.get(this.id)) Tournaments.get(this.id).update(user); }; ChatRoom.prototype.onJoin = function (user, connection, merging) { if (!user) return false; // ??? if (this.users[user.userid]) return user; this.users[user.userid] = user; if (user.named && Config.reportjoins) { this.add('|j|' + user.getIdentity(this.id), true); this.update(user); } else if (user.named) { var entry = '|J|' + user.getIdentity(this.id); if (Config.reportjoinsperiod) { this.reportJoinsQueue.push(entry); } else { this.send(entry); } this.logEntry(entry); } if (!merging) { var userList = this.userList ? this.userList : this.getUserList(); this.send('|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.logGetLast(100).join('\n') + this.getIntroMessage(), connection); } if (global.Tournaments && Tournaments.get(this.id)) Tournaments.get(this.id).update(user); return user; }; ChatRoom.prototype.onRename = function (user, oldid, joining) { delete this.users[oldid]; if (this.bannedUsers && (user.userid in this.bannedUsers || user.autoconfirmed in this.bannedUsers)) { this.bannedUsers[oldid] = true; for (var ip in user.ips) this.bannedIps[ip] = true; user.leaveRoom(this); var alts = user.getAlts(); for (var i = 0; i < alts.length; ++i) { this.bannedUsers[toId(alts[i])] = true; Users.getExact(alts[i]).leaveRoom(this); } return; } this.users[user.userid] = user; var entry; if (joining) { if (Config.reportjoins) { entry = '|j|' + user.getIdentity(this.id); } else { entry = '|J|' + user.getIdentity(this.id); } } else if (!user.named) { entry = '|L| ' + oldid; } else { entry = '|N|' + user.getIdentity(this.id) + '|' + oldid; } if (Config.reportjoins) { this.add(entry); } else { if (Config.reportjoinsperiod) { this.reportJoinsQueue.push(entry); } else { this.send(entry); } this.logEntry(entry); } if (global.Tournaments && Tournaments.get(this.id)) Tournaments.get(this.id).update(user); return user; }; /** * onRename, but without a userid change */ ChatRoom.prototype.onUpdateIdentity = function (user) { if (user && user.connected && user.named) { if (!this.users[user.userid]) return false; var entry = '|N|' + user.getIdentity(this.id) + '|' + user.userid; if (Config.reportjoinsperiod) { this.reportJoinsQueue.push(entry); } else { this.send(entry); } } }; ChatRoom.prototype.onLeave = function (user) { if (!user) return; // ... delete this.users[user.userid]; if (user.named && Config.reportjoins) { this.add('|l|' + user.getIdentity(this.id)); } else if (user.named) { var entry = '|L|' + user.getIdentity(this.id); if (Config.reportjoinsperiod) { this.reportJoinsQueue.push(entry); } else { this.send(entry); } this.logEntry(entry); } }; ChatRoom.prototype.chat = function (user, message, connection) { message = CommandParser.parse(message, this, user, connection); if (message) { if (ShadowBan.isShadowBanned(user)) { ShadowBan.room.add('|c|' + user.getIdentity() + "|__(To " + this.id + ")__ " + message); connection.sendTo(this, '|c|' + user.getIdentity(this.id) + '|' + message); } else { this.add('|c|' + user.getIdentity(this.id) + '|' + message, true); } } this.update(); }; ChatRoom.prototype.logEntry = function () {}; ChatRoom.prototype.destroy = function () { // deallocate ourself // remove references to ourself for (var i in this.users) { this.users[i].leaveRoom(this); delete this.users[i]; } this.users = null; rooms.global.deregisterChatRoom(this.id); rooms.global.delistChatRoom(this.id); // get rid of some possibly-circular references delete rooms[this.id]; }; return ChatRoom; })(); // to make sure you don't get null returned, pass the second argument var getRoom = function (roomid, fallback) { if (roomid && roomid.id) return roomid; if (!roomid) roomid = 'default'; if (!rooms[roomid] && fallback) { return rooms.global; } return rooms[roomid]; }; var newRoom = function (roomid, format, p1, p2, parent, rated) { if (roomid && roomid.id) return roomid; if (!p1 || !p2) return false; if (!roomid) roomid = 'default'; if (!rooms[roomid]) { // console.log("NEW BATTLE ROOM: " + roomid); ResourceMonitor.countBattle(p1.latestIp, p1.name); ResourceMonitor.countBattle(p2.latestIp, p2.name); rooms[roomid] = new BattleRoom(roomid, format, p1, p2, parent, rated); } return rooms[roomid]; }; var rooms = Object.create(null); console.log("NEW GLOBAL: global"); rooms.global = new GlobalRoom('global'); exports.GlobalRoom = GlobalRoom; exports.BattleRoom = BattleRoom; exports.ChatRoom = ChatRoom; exports.get = getRoom; exports.create = newRoom; exports.rooms = rooms; exports.global = rooms.global; exports.lobby = rooms.lobby;
rooms.js
/** * Rooms * Pokemon Showdown - http://pokemonshowdown.com/ * * Every chat room and battle is a room, and what they do is done in * rooms.js. There's also a global room which every user is in, and * handles miscellaneous things like welcoming the user. * * @license MIT license */ const TIMEOUT_EMPTY_DEALLOCATE = 10 * 60 * 1000; const TIMEOUT_INACTIVE_DEALLOCATE = 40 * 60 * 1000; const REPORT_USER_STATS_INTERVAL = 1000 * 60 * 10; var fs = require('fs'); var GlobalRoom = (function () { function GlobalRoom(roomid) { this.id = roomid; this.i = {}; // init battle rooms this.rooms = []; this.battleCount = 0; this.searchers = []; // Never do any other file IO synchronously // but this is okay to prevent race conditions as we start up PS this.lastBattle = 0; try { this.lastBattle = parseInt(fs.readFileSync('logs/lastbattle.txt')) || 0; } catch (e) {} // file doesn't exist [yet] this.chatRoomData = []; try { this.chatRoomData = JSON.parse(fs.readFileSync('config/chatrooms.json')); if (!Array.isArray(this.chatRoomData)) this.chatRoomData = []; } catch (e) {} // file doesn't exist [yet] if (!this.chatRoomData.length) { this.chatRoomData = [{ title: 'Lobby', autojoin: true }, { title: 'Staff', isPrivate: true, staffRoom: true, staffAutojoin: true }]; } this.chatRooms = []; this.autojoin = []; // rooms that users autojoin upon connecting this.staffAutojoin = []; // rooms that staff autojoin upon connecting for (var i = 0; i < this.chatRoomData.length; i++) { if (!this.chatRoomData[i] || !this.chatRoomData[i].title) { console.log('ERROR: Room number ' + i + ' has no data.'); continue; } var id = toId(this.chatRoomData[i].title); console.log("NEW CHATROOM: " + id); var room = rooms[id] = new ChatRoom(id, this.chatRoomData[i].title, this.chatRoomData[i]); this.chatRooms.push(room); if (room.autojoin) this.autojoin.push(id); if (room.staffAutojoin) this.staffAutojoin.push(id); } // this function is complex in order to avoid several race conditions var self = this; this.writeNumRooms = (function () { var writing = false; var lastBattle; // last lastBattle to be written to file var finishWriting = function () { writing = false; if (lastBattle < self.lastBattle) { self.writeNumRooms(); } }; return function () { if (writing) return; // batch writing lastbattle.txt for every 10 battles if (lastBattle >= self.lastBattle) return; lastBattle = self.lastBattle + 10; writing = true; fs.writeFile('logs/lastbattle.txt.0', '' + lastBattle, function () { // rename is atomic on POSIX, but will throw an error on Windows fs.rename('logs/lastbattle.txt.0', 'logs/lastbattle.txt', function (err) { if (err) { // This should only happen on Windows. fs.writeFile('logs/lastbattle.txt', '' + lastBattle, finishWriting); return; } finishWriting(); }); }); }; })(); this.writeChatRoomData = (function () { var writing = false; var writePending = false; // whether or not a new write is pending var finishWriting = function () { writing = false; if (writePending) { writePending = false; self.writeChatRoomData(); } }; return function () { if (writing) { writePending = true; return; } writing = true; var data = JSON.stringify(self.chatRoomData).replace(/\{"title"\:/g, '\n{"title":').replace(/\]$/, '\n]'); fs.writeFile('config/chatrooms.json.0', data, function () { // rename is atomic on POSIX, but will throw an error on Windows fs.rename('config/chatrooms.json.0', 'config/chatrooms.json', function (err) { if (err) { // This should only happen on Windows. fs.writeFile('config/chatrooms.json', data, finishWriting); return; } finishWriting(); }); }); }; })(); // init users this.users = {}; this.userCount = 0; // cache of `Object.size(this.users)` this.maxUsers = 0; this.maxUsersDate = 0; this.reportUserStatsInterval = setInterval( this.reportUserStats.bind(this), REPORT_USER_STATS_INTERVAL ); } GlobalRoom.prototype.type = 'global'; GlobalRoom.prototype.formatListText = '|formats'; GlobalRoom.prototype.reportUserStats = function () { if (this.maxUsersDate) { LoginServer.request('updateuserstats', { date: this.maxUsersDate, users: this.maxUsers }, function () {}); this.maxUsersDate = 0; } LoginServer.request('updateuserstats', { date: Date.now(), users: Object.size(this.users) }, function () {}); }; GlobalRoom.prototype.getFormatListText = function () { var formatListText = '|formats'; var curSection = ''; for (var i in Tools.data.Formats) { var format = Tools.data.Formats[i]; if (!format.challengeShow && !format.searchShow) continue; var section = format.section; if (section === undefined) section = format.mod; if (!section) section = ''; if (section !== curSection) { curSection = section; formatListText += '|,' + (format.column || 1) + '|' + section; } formatListText += '|' + format.name; if (!format.challengeShow) formatListText += ',,'; else if (!format.searchShow) formatListText += ','; if (format.team) formatListText += ',#'; } return formatListText; }; GlobalRoom.prototype.getRoomList = function (filter) { var roomList = {}; var total = 0; for (var i = this.rooms.length - 1; i >= 0; i--) { var room = this.rooms[i]; if (!room || !room.active) continue; if (filter && filter !== room.format && filter !== true) continue; var roomData = {}; if (room.active && room.battle) { if (room.battle.players[0]) roomData.p1 = room.battle.players[0].getIdentity(); if (room.battle.players[1]) roomData.p2 = room.battle.players[1].getIdentity(); } if (!roomData.p1 || !roomData.p2) continue; roomList[room.id] = roomData; total++; if (total >= 6 && !filter) break; } return roomList; }; GlobalRoom.prototype.getRooms = function () { var rooms = {official:[], chat:[], userCount: this.userCount, battleCount: this.battleCount}; for (var i = 0; i < this.chatRooms.length; i++) { var room = this.chatRooms[i]; if (!room) continue; if (room.isPrivate) continue; (room.isOfficial ? rooms.official : rooms.chat).push({ title: room.title, desc: room.desc, userCount: Object.size(room.users) }); } return rooms; }; GlobalRoom.prototype.cancelSearch = function (user) { var success = false; user.cancelChallengeTo(); for (var i = 0; i < this.searchers.length; i++) { var search = this.searchers[i]; var searchUser = Users.get(search.userid); if (!searchUser.connected) { this.searchers.splice(i, 1); i--; continue; } if (searchUser === user) { this.searchers.splice(i, 1); i--; if (!success) { searchUser.send('|updatesearch|' + JSON.stringify({searching: false})); success = true; } continue; } } return success; }; GlobalRoom.prototype.searchBattle = function (user, formatid) { if (!user.connected) return; formatid = toId(formatid); user.prepBattle(formatid, 'search', null, this.finishSearchBattle.bind(this, user, formatid)); }; GlobalRoom.prototype.finishSearchBattle = function (user, formatid, result) { if (!result) return; // tell the user they've started searching var newSearchData = { format: formatid }; user.send('|updatesearch|' + JSON.stringify({searching: newSearchData})); // get the user's rating before actually starting to search var newSearch = { userid: user.userid, formatid: formatid, team: user.team, rating: 1000, time: new Date().getTime() }; var self = this; user.doWithMMR(formatid, function (mmr, error) { if (error) { user.popup("Connection to ladder server failed with error: " + error + "; please try again later"); return; } newSearch.rating = mmr; self.addSearch(newSearch, user); }); }; GlobalRoom.prototype.matchmakingOK = function (search1, search2, user1, user2) { // users must be different if (user1 === user2) return false; // users must not have been matched immediately previously if (user1.lastMatch === user2.userid || user2.lastMatch === user1.userid) return false; // search must be within range var searchRange = 100, formatid = search1.formatid, elapsed = Math.abs(search1.time - search2.time); if (formatid === 'ou' || formatid === 'oucurrent' || formatid === 'randombattle') searchRange = 50; searchRange += elapsed / 300; // +1 every .3 seconds if (searchRange > 300) searchRange = 300; if (Math.abs(search1.rating - search2.rating) > searchRange) return false; user1.lastMatch = user2.userid; user2.lastMatch = user1.userid; return true; }; GlobalRoom.prototype.addSearch = function (newSearch, user) { if (!user.connected) return; for (var i = 0; i < this.searchers.length; i++) { var search = this.searchers[i]; var searchUser = Users.get(search.userid); if (!searchUser || !searchUser.connected) { this.searchers.splice(i, 1); i--; continue; } if (newSearch.formatid === search.formatid && searchUser === user) return; // only one search per format if (newSearch.formatid === search.formatid && this.matchmakingOK(search, newSearch, searchUser, user)) { this.cancelSearch(user, true); this.cancelSearch(searchUser, true); user.send('|updatesearch|' + JSON.stringify({searching: false})); this.startBattle(searchUser, user, search.formatid, true, search.team, newSearch.team); return; } } this.searchers.push(newSearch); }; GlobalRoom.prototype.send = function (message, user) { if (user) { user.sendTo(this, message); } else { Sockets.channelBroadcast(this.id, message); } }; GlobalRoom.prototype.sendAuth = function (message) { for (var i in this.users) { var user = this.users[i]; if (user.connected && user.can('receiveauthmessages', null, this)) { user.sendTo(this, message); } } }; GlobalRoom.prototype.updateRooms = function (excludeUser) { // do nothing }; GlobalRoom.prototype.add = function (message, noUpdate) { if (rooms.lobby) rooms.lobby.add(message, noUpdate); }; GlobalRoom.prototype.addRaw = function (message) { if (rooms.lobby) rooms.lobby.addRaw(message); }; GlobalRoom.prototype.addChatRoom = function (title) { var id = toId(title); if (rooms[id]) return false; var chatRoomData = { title: title }; var room = rooms[id] = new ChatRoom(id, title, chatRoomData); this.chatRoomData.push(chatRoomData); this.chatRooms.push(room); this.writeChatRoomData(); return true; }; GlobalRoom.prototype.deregisterChatRoom = function (id) { id = toId(id); var room = rooms[id]; if (!room) return false; // room doesn't exist if (!room.chatRoomData) return false; // room isn't registered // deregister from global chatRoomData // looping from the end is a pretty trivial optimization, but the // assumption is that more recently added rooms are more likely to // be deleted for (var i = this.chatRoomData.length - 1; i >= 0; i--) { if (id === toId(this.chatRoomData[i].title)) { this.chatRoomData.splice(i, 1); this.writeChatRoomData(); break; } } delete room.chatRoomData; return true; }; GlobalRoom.prototype.delistChatRoom = function (id) { id = toId(id); if (!rooms[id]) return false; // room doesn't exist for (var i = this.chatRooms.length - 1; i >= 0; i--) { if (id === this.chatRooms[i].id) { this.chatRooms.splice(i, 1); break; } } }; GlobalRoom.prototype.removeChatRoom = function (id) { id = toId(id); var room = rooms[id]; if (!room) return false; // room doesn't exist room.destroy(); return true; }; GlobalRoom.prototype.autojoinRooms = function (user, connection) { // we only autojoin regular rooms if the client requests it with /autojoin // note that this restriction doesn't apply to staffAutojoin for (var i = 0; i < this.autojoin.length; i++) { user.joinRoom(this.autojoin[i], connection); } }; GlobalRoom.prototype.checkAutojoin = function (user, connection) { if (user.isStaff) { for (var i = 0; i < this.staffAutojoin.length; i++) { user.joinRoom(this.staffAutojoin[i], connection); } } }; GlobalRoom.prototype.onJoinConnection = function (user, connection) { var initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n'; connection.send(initdata + this.formatListText); if (this.chatRooms.length > 2) connection.send('|queryresponse|rooms|null'); // should display room list }; GlobalRoom.prototype.onJoin = function (user, connection, merging) { if (!user) return false; // ??? if (this.users[user.userid]) return user; this.users[user.userid] = user; if (++this.userCount > this.maxUsers) { this.maxUsers = this.userCount; this.maxUsersDate = Date.now(); } if (!merging) { var initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n'; connection.send(initdata + this.formatListText); if (this.chatRooms.length > 2) connection.send('|queryresponse|rooms|null'); // should display room list } return user; }; GlobalRoom.prototype.onRename = function (user, oldid, joining) { delete this.users[oldid]; this.users[user.userid] = user; return user; }; GlobalRoom.prototype.onUpdateIdentity = function () {}; GlobalRoom.prototype.onLeave = function (user) { if (!user) return; // ... delete this.users[user.userid]; --this.userCount; this.cancelSearch(user, true); }; GlobalRoom.prototype.startBattle = function (p1, p2, format, rated, p1team, p2team) { var newRoom; p1 = Users.get(p1); p2 = Users.get(p2); if (!p1 || !p2) { // most likely, a user was banned during the battle start procedure this.cancelSearch(p1, true); this.cancelSearch(p2, true); return; } if (p1 === p2) { this.cancelSearch(p1, true); this.cancelSearch(p2, true); p1.popup("You can't battle your own account. Please use something like Private Browsing to battle yourself."); return; } if (this.lockdown) { this.cancelSearch(p1, true); this.cancelSearch(p2, true); p1.popup("The server is shutting down. Battles cannot be started at this time."); p2.popup("The server is shutting down. Battles cannot be started at this time."); return; } //console.log('BATTLE START BETWEEN: ' + p1.userid + ' ' + p2.userid); var i = this.lastBattle + 1; var formaturlid = format.toLowerCase().replace(/[^a-z0-9]+/g, ''); while(rooms['battle-' + formaturlid + i]) { i++; } this.lastBattle = i; rooms.global.writeNumRooms(); newRoom = this.addRoom('battle-' + formaturlid + '-' + i, format, p1, p2, this.id, rated); p1.joinRoom(newRoom); p2.joinRoom(newRoom); newRoom.joinBattle(p1, p1team); newRoom.joinBattle(p2, p2team); this.cancelSearch(p1, true); this.cancelSearch(p2, true); if (Config.reportbattles && rooms.lobby) { rooms.lobby.add('|b|' + newRoom.id + '|' + p1.getIdentity() + '|' + p2.getIdentity()); } return newRoom; }; GlobalRoom.prototype.addRoom = function (room, format, p1, p2, parent, rated) { room = newRoom(room, format, p1, p2, parent, rated); if (this.id in room.i) return; room.i[this.id] = this.rooms.length; this.rooms.push(room); return room; }; GlobalRoom.prototype.removeRoom = function (room) { room = getRoom(room); if (!room) return; if (this.id in room.i) { this.rooms.splice(room.i[this.id], 1); delete room.i[this.id]; for (var i = 0; i < this.rooms.length; i++) { this.rooms[i].i[this.id] = i; } } }; GlobalRoom.prototype.chat = function (user, message, connection) { if (rooms.lobby) return rooms.lobby.chat(user, message, connection); message = CommandParser.parse(message, this, user, connection); if (message) { connection.sendPopup("You can't send messages directly to the server."); } }; return GlobalRoom; })(); var BattleRoom = (function () { function BattleRoom(roomid, format, p1, p2, parentid, rated) { this.id = roomid; this.title = "" + p1.name + " vs. " + p2.name; this.i = {}; this.modchat = (Config.battlemodchat || false); format = '' + (format || ''); this.users = {}; this.format = format; this.auth = {}; //console.log("NEW BATTLE"); var formatid = toId(format); if (rated && Tools.getFormat(formatid).rated !== false) { rated = { p1: p1.userid, p2: p2.userid, format: format }; } else { rated = false; } this.rated = rated; this.battle = Simulator.create(this.id, format, rated, this); this.parentid = parentid || ''; this.p1 = p1 || ''; this.p2 = p2 || ''; this.sideTicksLeft = [21, 21]; if (!rated) this.sideTicksLeft = [28, 28]; this.sideTurnTicks = [0, 0]; this.disconnectTickDiff = [0, 0]; this.log = []; if (Config.forcetimer) this.requestKickInactive(false); } BattleRoom.prototype.type = 'battle'; BattleRoom.prototype.resetTimer = null; BattleRoom.prototype.resetUser = ''; BattleRoom.prototype.expireTimer = null; BattleRoom.prototype.active = false; BattleRoom.prototype.lastUpdate = 0; BattleRoom.prototype.push = function (message) { if (typeof message === 'string') { this.log.push(message); } else { this.log = this.log.concat(message); } }; BattleRoom.prototype.win = function (winner) { if (this.rated) { var winnerid = toId(winner); var rated = this.rated; this.rated = false; var p1score = 0.5; if (winnerid === rated.p1) { p1score = 1; } else if (winnerid === rated.p2) { p1score = 0; } var p1 = rated.p1; if (Users.getExact(rated.p1)) p1 = Users.getExact(rated.p1).name; var p2 = rated.p2; if (Users.getExact(rated.p2)) p2 = Users.getExact(rated.p2).name; //update.updates.push('[DEBUG] uri: ' + Config.loginserver + 'action.php?act=ladderupdate&serverid=' + Config.serverid + '&p1=' + encodeURIComponent(p1) + '&p2=' + encodeURIComponent(p2) + '&score=' + p1score + '&format=' + toId(rated.format) + '&servertoken=[token]'); if (!rated.p1 || !rated.p2) { this.push('|raw|ERROR: Ladder not updated: a player does not exist'); } else { var winner = Users.get(winnerid); if (winner && !winner.authenticated) { this.send('|askreg|' + winner.userid, winner); } var p1rating, p2rating; // update rankings this.push('|raw|Ladder updating...'); var self = this; LoginServer.request('ladderupdate', { p1: p1, p2: p2, score: p1score, format: toId(rated.format) }, function (data, statusCode, error) { if (!self.battle) { console.log('room expired before ladder update was received'); return; } if (!data) { self.addRaw('Ladder (probably) updated, but score could not be retrieved (' + error + ').'); self.update(); // log the battle anyway if (!Tools.getFormat(self.format).noLog) { self.logBattle(p1score); } return; } else if (data.errorip) { self.addRaw("This server's request IP " + data.errorip + " is not a registered server."); return; } else { try { p1rating = data.p1rating; p2rating = data.p2rating; //self.add("Ladder updated."); var oldacre = Math.round(data.p1rating.oldacre); var acre = Math.round(data.p1rating.acre); var reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.99 ? 'winning' : (p1score < 0.01 ? 'losing' : 'tying')); if (reasons.substr(0, 1) !== '-') reasons = '+' + reasons; self.addRaw(Tools.escapeHTML(p1) + '\'s rating: ' + oldacre + ' &rarr; <strong>' + acre + '</strong><br />(' + reasons + ')'); oldacre = Math.round(data.p2rating.oldacre); acre = Math.round(data.p2rating.acre); reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.99 ? 'losing' : (p1score < 0.01 ? 'winning' : 'tying')); if (reasons.substr(0, 1) !== '-') reasons = '+' + reasons; self.addRaw(Tools.escapeHTML(p2) + '\'s rating: ' + oldacre + ' &rarr; <strong>' + acre + '</strong><br />(' + reasons + ')'); Users.get(p1).cacheMMR(rated.format, data.p1rating); Users.get(p2).cacheMMR(rated.format, data.p2rating); self.update(); } catch(e) { self.addRaw('There was an error calculating rating changes.'); self.update(); } if (!Tools.getFormat(self.format).noLog) { self.logBattle(p1score, p1rating, p2rating); } } }); } } rooms.global.battleCount += 0 - (this.active ? 1 : 0); this.active = false; this.update(); }; // idx = 0, 1 : player log // idx = 2 : spectator log // idx = 3 : replay log BattleRoom.prototype.getLog = function (idx) { var log = []; for (var i = 0; i < this.log.length; ++i) { var line = this.log[i]; if (line === '|split') { log.push(this.log[i + idx + 1]); i += 4; } else { log.push(line); } } return log; }; BattleRoom.prototype.getLogForUser = function (user) { var slot = this.battle.getSlot(user); if (slot < 0) slot = 2; return this.getLog(slot); }; BattleRoom.prototype.update = function (excludeUser) { if (this.log.length <= this.lastUpdate) return; var logs = [[], [], []]; var updateLines = this.log.slice(this.lastUpdate); for (var i = 0; i < updateLines.length;) { var line = updateLines[i++]; if (line === '|split') { logs[0].push(updateLines[i++]); // player 0 logs[1].push(updateLines[i++]); // player 1 logs[2].push(updateLines[i++]); // spectators i++; // replays } else { logs[0].push(line); logs[1].push(line); logs[2].push(line); } } var roomid = this.id; var self = this; logs = logs.map(function (log) { return log.join('\n'); }); this.lastUpdate = this.log.length; var hasUsers = false; for (var i in this.users) { var user = this.users[i]; hasUsers = true; if (user === excludeUser) continue; var slot = this.battle.getSlot(user); if (slot < 0) slot = 2; this.send(logs[slot], user); } // empty rooms time out after ten minutes if (!hasUsers) { if (!this.expireTimer) { this.expireTimer = setTimeout(this.tryExpire.bind(this), TIMEOUT_EMPTY_DEALLOCATE); } } else { if (this.expireTimer) clearTimeout(this.expireTimer); this.expireTimer = setTimeout(this.tryExpire.bind(this), TIMEOUT_INACTIVE_DEALLOCATE); } }; BattleRoom.prototype.logBattle = function (p1score, p1rating, p2rating) { var logData = this.battle.logData; logData.p1rating = p1rating; logData.p2rating = p2rating; logData.endType = this.battle.endType; if (!p1rating) logData.ladderError = true; logData.log = BattleRoom.prototype.getLog.call(logData, 3); // replay log (exact damage) var date = new Date(); var logfolder = date.format('{yyyy}-{MM}'); var logsubfolder = date.format('{yyyy}-{MM}-{dd}'); var curpath = 'logs/' + logfolder; var self = this; fs.mkdir(curpath, '0755', function () { var tier = self.format.toLowerCase().replace(/[^a-z0-9]+/g, ''); curpath += '/' + tier; fs.mkdir(curpath, '0755', function () { curpath += '/' + logsubfolder; fs.mkdir(curpath, '0755', function () { fs.writeFile(curpath + '/' + self.id + '.log.json', JSON.stringify(logData)); }); }); }); // asychronicity //console.log(JSON.stringify(logData)); }; BattleRoom.prototype.send = function (message, user) { if (user) { user.sendTo(this, message); } else { Sockets.channelBroadcast(this.id, '>' + this.id + '\n' + message); } }; BattleRoom.prototype.tryExpire = function () { this.expire(); }; BattleRoom.prototype.reset = function (reload) { clearTimeout(this.resetTimer); this.resetTimer = null; this.resetUser = ''; if (rooms.global.lockdown) { this.add('The battle was not restarted because the server is preparing to shut down.'); return; } this.add('RESET'); this.update(); rooms.global.battleCount += 0 - (this.active ? 1 : 0); this.active = false; if (this.parentid) { getRoom(this.parentid).updateRooms(); } }; BattleRoom.prototype.getInactiveSide = function () { if (this.battle.players[0] && !this.battle.players[1]) return 1; if (this.battle.players[1] && !this.battle.players[0]) return 0; return this.battle.inactiveSide; }; BattleRoom.prototype.forfeit = function (user, message, side) { if (!this.battle || this.battle.ended || !this.battle.started) return false; if (!message) message = ' forfeited.'; if (side === undefined) { if (user && user.userid === this.battle.playerids[0]) side = 0; if (user && user.userid === this.battle.playerids[1]) side = 1; } if (side === undefined) return false; var ids = ['p1', 'p2']; var otherids = ['p2', 'p1']; var name = 'Player ' + (side + 1); if (user) { name = user.name; } else if (this.rated) { name = this.rated[ids[side]]; } this.addCmd('-message', name + message); this.battle.endType = 'forfeit'; this.battle.send('win', otherids[side]); rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; this.update(); return true; }; BattleRoom.prototype.kickInactive = function () { clearTimeout(this.resetTimer); this.resetTimer = null; if (!this.battle || this.battle.ended || !this.battle.started) return false; var inactiveSide = this.getInactiveSide(); var ticksLeft = [0, 0]; if (inactiveSide != 1) { // side 0 is inactive this.sideTurnTicks[0]--; this.sideTicksLeft[0]--; } if (inactiveSide != 0) { // side 1 is inactive this.sideTurnTicks[1]--; this.sideTicksLeft[1]--; } ticksLeft[0] = Math.min(this.sideTurnTicks[0], this.sideTicksLeft[0]); ticksLeft[1] = Math.min(this.sideTurnTicks[1], this.sideTicksLeft[1]); if (ticksLeft[0] && ticksLeft[1]) { if (inactiveSide === 0 || inactiveSide === 1) { // one side is inactive var inactiveTicksLeft = ticksLeft[inactiveSide]; var inactiveUser = this.battle.getPlayer(inactiveSide); if (inactiveTicksLeft % 3 === 0 || inactiveTicksLeft <= 4) { this.send('|inactive|' + (inactiveUser ? inactiveUser.name : 'Player ' + (inactiveSide + 1)) + ' has ' + (inactiveTicksLeft * 10) + ' seconds left.'); } } else { // both sides are inactive var inactiveUser0 = this.battle.getPlayer(0); if (ticksLeft[0] % 3 === 0 || ticksLeft[0] <= 4) { this.send('|inactive|' + (inactiveUser0 ? inactiveUser0.name : 'Player 1') + ' has ' + (ticksLeft[0] * 10) + ' seconds left.', inactiveUser0); } var inactiveUser1 = this.battle.getPlayer(1); if (ticksLeft[1] % 3 === 0 || ticksLeft[1] <= 4) { this.send('|inactive|' + (inactiveUser1 ? inactiveUser1.name : 'Player 2') + ' has ' + (ticksLeft[1] * 10) + ' seconds left.', inactiveUser1); } } this.resetTimer = setTimeout(this.kickInactive.bind(this), 10 * 1000); return; } if (inactiveSide < 0) { if (ticksLeft[0]) inactiveSide = 1; else if (ticksLeft[1]) inactiveSide = 0; } this.forfeit(this.battle.getPlayer(inactiveSide), ' lost due to inactivity.', inactiveSide); this.resetUser = ''; if (this.parentid) { getRoom(this.parentid).updateRooms(); } }; BattleRoom.prototype.requestKickInactive = function (user, force) { if (this.resetTimer) { if (user) this.send('|inactive|The inactivity timer is already counting down.', user); return false; } if (user) { if (!force && this.battle.getSlot(user) < 0) return false; this.resetUser = user.userid; this.send('|inactive|Battle timer is now ON: inactive players will automatically lose when time\'s up. (requested by ' + user.name + ')'); } else if (user === false) { this.resetUser = '~'; this.add('|inactive|Battle timer is ON: inactive players will automatically lose when time\'s up.'); } // a tick is 10 seconds var maxTicksLeft = 15; // 2 minutes 30 seconds if (!this.battle.p1 || !this.battle.p2) { // if a player has left, don't wait longer than 6 ticks (1 minute) maxTicksLeft = 6; } if (!this.rated) maxTicksLeft = 30; this.sideTurnTicks = [maxTicksLeft, maxTicksLeft]; var inactiveSide = this.getInactiveSide(); if (inactiveSide < 0) { // add 10 seconds to bank if they're below 160 seconds if (this.sideTicksLeft[0] < 16) this.sideTicksLeft[0]++; if (this.sideTicksLeft[1] < 16) this.sideTicksLeft[1]++; } this.sideTicksLeft[0]++; this.sideTicksLeft[1]++; if (inactiveSide != 1) { // side 0 is inactive var ticksLeft0 = Math.min(this.sideTicksLeft[0] + 1, maxTicksLeft); this.send('|inactive|You have ' + (ticksLeft0 * 10) + ' seconds to make your decision.', this.battle.getPlayer(0)); } if (inactiveSide != 0) { // side 1 is inactive var ticksLeft1 = Math.min(this.sideTicksLeft[1] + 1, maxTicksLeft); this.send('|inactive|You have ' + (ticksLeft1 * 10) + ' seconds to make your decision.', this.battle.getPlayer(1)); } this.resetTimer = setTimeout(this.kickInactive.bind(this), 10 * 1000); return true; }; BattleRoom.prototype.nextInactive = function () { if (this.resetTimer) { this.update(); clearTimeout(this.resetTimer); this.resetTimer = null; this.requestKickInactive(); } }; BattleRoom.prototype.stopKickInactive = function (user, force) { if (!force && user && user.userid !== this.resetUser) return false; if (this.resetTimer) { clearTimeout(this.resetTimer); this.resetTimer = null; this.send('|inactiveoff|Battle timer is now OFF.'); return true; } return false; }; BattleRoom.prototype.kickInactiveUpdate = function () { if (!this.rated) return false; if (this.resetTimer) { var inactiveSide = this.getInactiveSide(); var changed = false; if ((!this.battle.p1 || !this.battle.p2) && !this.disconnectTickDiff[0] && !this.disconnectTickDiff[1]) { if ((!this.battle.p1 && inactiveSide === 0) || (!this.battle.p2 && inactiveSide === 1)) { var inactiveUser = this.battle.getPlayer(inactiveSide); if (!this.battle.p1 && inactiveSide === 0 && this.sideTurnTicks[0] > 7) { this.disconnectTickDiff[0] = this.sideTurnTicks[0] - 7; this.sideTurnTicks[0] = 7; changed = true; } else if (!this.battle.p2 && inactiveSide === 1 && this.sideTurnTicks[1] > 7) { this.disconnectTickDiff[1] = this.sideTurnTicks[1] - 7; this.sideTurnTicks[1] = 7; changed = true; } if (changed) { this.send('|inactive|' + (inactiveUser ? inactiveUser.name : 'Player ' + (inactiveSide + 1)) + ' disconnected and has a minute to reconnect!'); return true; } } } else if (this.battle.p1 && this.battle.p2) { // Only one of the following conditions should happen, but do // them both since you never know... if (this.disconnectTickDiff[0]) { this.sideTurnTicks[0] = this.sideTurnTicks[0] + this.disconnectTickDiff[0]; this.disconnectTickDiff[0] = 0; changed = 0; } if (this.disconnectTickDiff[1]) { this.sideTurnTicks[1] = this.sideTurnTicks[1] + this.disconnectTickDiff[1]; this.disconnectTickDiff[1] = 0; changed = 1; } if (changed !== false) { var user = this.battle.getPlayer(changed); this.send('|inactive|' + (user ? user.name : 'Player ' + (changed + 1)) + ' reconnected and has ' + (this.sideTurnTicks[changed] * 10) + ' seconds left!'); return true; } } } return false; }; BattleRoom.prototype.decision = function (user, choice, data) { this.battle.sendFor(user, choice, data); if (this.active !== this.battle.active) { rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; if (this.parentid) { getRoom(this.parentid).updateRooms(); } } this.update(); }; // This function is only called when the room is not empty. // Joining an empty room calls this.join() below instead. BattleRoom.prototype.onJoinConnection = function (user, connection) { this.send('|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n'), connection); // this handles joining a battle in which a user is a participant, // where the user has already identified before attempting to join // the battle this.battle.resendRequest(user); }; BattleRoom.prototype.onJoin = function (user, connection) { if (!user) return false; if (this.users[user.userid]) return user; this.users[user.userid] = user; if (user.named) { this.addCmd('join', user.name); this.update(user); } this.send('|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n'), connection); return user; }; BattleRoom.prototype.onRename = function (user, oldid, joining) { if (joining) { this.addCmd('join', user.name); } var resend = joining || !this.battle.playerTable[oldid]; if (this.battle.playerTable[oldid]) { if (this.rated) { this.add('|message|' + user.name + ' forfeited by changing their name.'); this.battle.lose(oldid); this.battle.leave(oldid); resend = false; } else { this.battle.rename(); } } delete this.users[oldid]; this.users[user.userid] = user; this.update(); if (resend) { // this handles a named user renaming themselves into a user in the // battle (i.e. by using /nick) this.battle.resendRequest(user); } return user; }; BattleRoom.prototype.onUpdateIdentity = function () {}; BattleRoom.prototype.onLeave = function (user) { if (!user) return; // ... if (user.battles[this.id]) { this.battle.leave(user); rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; if (this.parentid) { getRoom(this.parentid).updateRooms(); } } else if (!user.named) { delete this.users[user.userid]; return; } delete this.users[user.userid]; this.addCmd('leave', user.name); if (Object.isEmpty(this.users)) { rooms.global.battleCount += 0 - (this.active ? 1 : 0); this.active = false; } this.update(); this.kickInactiveUpdate(); }; BattleRoom.prototype.joinBattle = function (user, team) { var slot = undefined; if (this.rated) { if (this.rated.p1 === user.userid) { slot = 0; } else if (this.rated.p2 === user.userid) { slot = 1; } else { user.popup("This is a rated battle; your username must be " + this.rated.p1 + " or " + this.rated.p2 + " to join."); return false; } } this.auth[user.userid] = '\u2605'; this.battle.join(user, slot, team); rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; if (this.active) { this.title = "" + this.battle.p1 + " vs. " + this.battle.p2; this.send('|title|' + this.title); } this.update(); this.kickInactiveUpdate(); if (this.parentid) { getRoom(this.parentid).updateRooms(); } }; BattleRoom.prototype.leaveBattle = function (user) { if (!user) return false; // ... if (user.battles[this.id]) { this.battle.leave(user); } else { return false; } this.auth[user.userid] = '+'; rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; this.update(); this.kickInactiveUpdate(); if (this.parentid) { getRoom(this.parentid).updateRooms(); } return true; }; BattleRoom.prototype.addCmd = function () { this.log.push('|' + Array.prototype.slice.call(arguments).join('|')); }; BattleRoom.prototype.add = function (message) { if (message.rawMessage) { this.addCmd('raw', message.rawMessage); } else if (message.name) { this.addCmd('chat', message.name.substr(1), message.message); } else { this.log.push(message); } }; BattleRoom.prototype.addRaw = function (message) { this.addCmd('raw', message); }; BattleRoom.prototype.chat = function (user, message, connection) { // Battle actions are actually just text commands that are handled in // parseCommand(), which in turn often calls Simulator.prototype.sendFor(). // Sometimes the call to sendFor is done indirectly, by calling // room.decision(), where room.constructor === BattleRoom. message = CommandParser.parse(message, this, user, connection); if (message) { if (ShadowBan.isShadowBanned(user)) { ShadowBan.room.add('|c|' + user.getIdentity() + "|__(To " + this.id + ")__ " + message); connection.sendTo(this, '|chat|' + user.name + '|' + message); } else { this.battle.chat(user, message); } } this.update(); }; BattleRoom.prototype.logEntry = function () {}; BattleRoom.prototype.expire = function () { this.send('|expire|'); this.destroy(); }; BattleRoom.prototype.destroy = function () { // deallocate ourself // remove references to ourself for (var i in this.users) { this.users[i].leaveRoom(this); delete this.users[i]; } this.users = null; rooms.global.removeRoom(this.id); // deallocate children and get rid of references to them if (this.battle) { this.battle.destroy(); } this.battle = null; if (this.resetTimer) { clearTimeout(this.resetTimer); } this.resetTimer = null; // get rid of some possibly-circular references delete rooms[this.id]; }; return BattleRoom; })(); var ChatRoom = (function () { function ChatRoom(roomid, title, options) { if (options) { this.chatRoomData = options; Object.merge(this, options); } this.id = roomid; this.title = title || roomid; this.i = {}; this.log = []; this.logTimes = []; this.lastUpdate = 0; this.users = {}; this.searchers = []; this.logFile = null; this.logFilename = ''; this.destroyingLog = false; this.bannedUsers = {}; this.bannedIps = {}; this.active = true; this.inactiveCount = 0; if (!this.modchat) this.modchat = (Config.chatmodchat || false); if (Config.logchat) { this.rollLogFile(true); this.logEntry = function (entry, date) { var timestamp = (new Date()).format('{HH}:{mm}:{ss} '); this.logFile.write(timestamp + entry + '\n'); }; this.logEntry('NEW CHATROOM: ' + this.id); if (Config.loguserstats) { setInterval(this.logUserStats.bind(this), Config.loguserstats); } } if (Config.reportjoinsperiod) { this.userList = this.getUserList(); this.reportJoinsQueue = []; this.reportJoinsInterval = setInterval( this.reportRecentJoins.bind(this), Config.reportjoinsperiod ); } } ChatRoom.prototype.type = 'chat'; ChatRoom.prototype.reportRecentJoins = function () { if (this.reportJoinsQueue.length === 0) { // nothing to report return; } if (Config.reportjoinsperiod) { this.userList = this.getUserList(); } this.send(this.reportJoinsQueue.join('\n')); this.reportJoinsQueue.length = 0; }; ChatRoom.prototype.rollLogFile = function (sync) { var mkdir = sync ? (function (path, mode, callback) { try { fs.mkdirSync(path, mode); } catch (e) {} // directory already exists callback(); }) : fs.mkdir; var date = new Date(); var basepath = 'logs/chat/' + this.id + '/'; var self = this; mkdir(basepath, '0755', function () { var path = date.format('{yyyy}-{MM}'); mkdir(basepath + path, '0755', function () { if (self.destroyingLog) return; path += '/' + date.format('{yyyy}-{MM}-{dd}') + '.txt'; if (path !== self.logFilename) { self.logFilename = path; if (self.logFile) self.logFile.destroySoon(); self.logFile = fs.createWriteStream(basepath + path, {flags: 'a'}); // Create a symlink to today's lobby log. // These operations need to be synchronous, but it's okay // because this code is only executed once every 24 hours. var link0 = basepath + 'today.txt.0'; try { fs.unlinkSync(link0); } catch (e) {} // file doesn't exist try { fs.symlinkSync(path, link0); // `basepath` intentionally not included try { fs.renameSync(link0, basepath + 'today.txt'); } catch (e) {} // OS doesn't support atomic rename } catch (e) {} // OS doesn't support symlinks } var timestamp = +date; date.advance('1 hour').reset('minutes').advance('1 second'); setTimeout(self.rollLogFile.bind(self), +date - timestamp); }); }); }; ChatRoom.prototype.destroyLog = function (initialCallback, finalCallback) { this.destroyingLog = true; initialCallback(); if (this.logFile) { this.logEntry = function () { }; this.logFile.on('close', finalCallback); this.logFile.destroySoon(); } else { finalCallback(); } }; ChatRoom.prototype.logUserStats = function () { var total = 0; var guests = 0; var groups = {}; Config.groupsranking.forEach(function (group) { groups[group] = 0; }); for (var i in this.users) { var user = this.users[i]; ++total; if (!user.named) { ++guests; } ++groups[user.group]; } var entry = '|userstats|total:' + total + '|guests:' + guests; for (var i in groups) { entry += '|' + i + ':' + groups[i]; } this.logEntry(entry); }; ChatRoom.prototype.getUserList = function () { var buffer = ''; var counter = 0; for (var i in this.users) { if (!this.users[i].named) { continue; } counter++; buffer += ',' + this.users[i].getIdentity(this.id); } var msg = '|users|' + counter + buffer; return msg; }; ChatRoom.prototype.update = function () { if (this.log.length <= this.lastUpdate) return; var entries = this.log.slice(this.lastUpdate); var update = entries.join('\n'); if (this.log.length > 100) { this.log.splice(0, this.log.length - 100); this.logTimes.splice(0, this.logTimes.length - 100); } this.lastUpdate = this.log.length; this.send(update); }; ChatRoom.prototype.send = function (message, user) { if (user) { user.sendTo(this, message); } else { if (this.id !== 'lobby') message = '>' + this.id + '\n' + message; Sockets.channelBroadcast(this.id, message); } }; ChatRoom.prototype.sendAuth = function (message) { for (var i in this.users) { var user = this.users[i]; if (user.connected && user.can('receiveauthmessages', null, this)) { user.sendTo(this, message); } } }; ChatRoom.prototype.add = function (message, noUpdate) { this.logTimes.push(~~(Date.now() / 1000)); this.log.push(message); this.logEntry(message); if (!noUpdate) { this.update(); } }; ChatRoom.prototype.addRaw = function (message) { this.add('|raw|' + message); }; ChatRoom.prototype.logGetLast = function (amount, noTime) { if (!amount) { return []; } if (amount < 0) { amount *= -1; } var logLength = this.log.length; if (!logLength) { return []; } var log = []; var time = ~~(Date.now() / 1000); for (var i = logLength - amount - 1; i < logLength; i++) { if (i < 0) { i = 0; } var logText = this.log[i]; if (!logText){ continue; } if (!noTime && logText.substr(0, 3) === '|c|') { // Time is only added when it's a normal chat message logText = '|tc|' + (time - this.logTimes[i]) + '|' + logText.substr(3); } log.push(logText); } return log; }; ChatRoom.prototype.getIntroMessage = function () { var html = this.introMessage || ''; if (this.modchat) { if (html) html += '<br /><br />'; html += '<div class="broadcast-red">'; html += '<b>Moderated chat is currently set to ' + this.modchat + '!</b><br />'; html += 'Only users of rank ' + this.modchat + ' and higher can talk.'; html += '</div>'; } if (html) return '\n|raw|<div class="infobox">' + html + '</div>'; return ''; }; ChatRoom.prototype.onJoinConnection = function (user, connection) { var userList = this.userList ? this.userList : this.getUserList(); this.send('|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.logGetLast(25).join('\n') + this.getIntroMessage(), connection); if (global.Tournaments && Tournaments.get(this.id)) Tournaments.get(this.id).update(user); }; ChatRoom.prototype.onJoin = function (user, connection, merging) { if (!user) return false; // ??? if (this.users[user.userid]) return user; this.users[user.userid] = user; if (user.named && Config.reportjoins) { this.add('|j|' + user.getIdentity(this.id), true); this.update(user); } else if (user.named) { var entry = '|J|' + user.getIdentity(this.id); if (Config.reportjoinsperiod) { this.reportJoinsQueue.push(entry); } else { this.send(entry); } this.logEntry(entry); } if (!merging) { var userList = this.userList ? this.userList : this.getUserList(); this.send('|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.logGetLast(100).join('\n') + this.getIntroMessage(), connection); } if (global.Tournaments && Tournaments.get(this.id)) Tournaments.get(this.id).update(user); return user; }; ChatRoom.prototype.onRename = function (user, oldid, joining) { delete this.users[oldid]; if (this.bannedUsers && (user.userid in this.bannedUsers || user.autoconfirmed in this.bannedUsers)) { this.bannedUsers[oldid] = true; for (var ip in user.ips) this.bannedIps[ip] = true; user.leaveRoom(this); var alts = user.getAlts(); for (var i = 0; i < alts.length; ++i) { this.bannedUsers[toId(alts[i])] = true; Users.getExact(alts[i]).leaveRoom(this); } return; } this.users[user.userid] = user; var entry; if (joining) { if (Config.reportjoins) { entry = '|j|' + user.getIdentity(this.id); } else { entry = '|J|' + user.getIdentity(this.id); } } else if (!user.named) { entry = '|L| ' + oldid; } else { entry = '|N|' + user.getIdentity(this.id) + '|' + oldid; } if (Config.reportjoins) { this.add(entry); } else { if (Config.reportjoinsperiod) { this.reportJoinsQueue.push(entry); } else { this.send(entry); } this.logEntry(entry); } if (global.Tournaments && Tournaments.get(this.id)) Tournaments.get(this.id).update(user); return user; }; /** * onRename, but without a userid change */ ChatRoom.prototype.onUpdateIdentity = function (user) { if (user && user.connected && user.named) { if (!this.users[user.userid]) return false; var entry = '|N|' + user.getIdentity(this.id) + '|' + user.userid; if (Config.reportjoinsperiod) { this.reportJoinsQueue.push(entry); } else { this.send(entry); } } }; ChatRoom.prototype.onLeave = function (user) { if (!user) return; // ... delete this.users[user.userid]; if (user.named && Config.reportjoins) { this.add('|l|' + user.getIdentity(this.id)); } else if (user.named) { var entry = '|L|' + user.getIdentity(this.id); if (Config.reportjoinsperiod) { this.reportJoinsQueue.push(entry); } else { this.send(entry); } this.logEntry(entry); } }; ChatRoom.prototype.chat = function (user, message, connection) { message = CommandParser.parse(message, this, user, connection); if (message) { if (ShadowBan.isShadowBanned(user)) { ShadowBan.room.add('|c|' + user.getIdentity() + "|__(To " + this.id + ")__ " + message); connection.sendTo(this, '|c|' + user.getIdentity(this.id) + '|' + message); } else { this.add('|c|' + user.getIdentity(this.id) + '|' + message, true); } } this.update(); }; ChatRoom.prototype.logEntry = function () {}; ChatRoom.prototype.destroy = function () { // deallocate ourself // remove references to ourself for (var i in this.users) { this.users[i].leaveRoom(this); delete this.users[i]; } this.users = null; rooms.global.deregisterChatRoom(this.id); rooms.global.delistChatRoom(this.id); // get rid of some possibly-circular references delete rooms[this.id]; }; return ChatRoom; })(); // to make sure you don't get null returned, pass the second argument var getRoom = function (roomid, fallback) { if (roomid && roomid.id) return roomid; if (!roomid) roomid = 'default'; if (!rooms[roomid] && fallback) { return rooms.global; } return rooms[roomid]; }; var newRoom = function (roomid, format, p1, p2, parent, rated) { if (roomid && roomid.id) return roomid; if (!p1 || !p2) return false; if (!roomid) roomid = 'default'; if (!rooms[roomid]) { // console.log("NEW BATTLE ROOM: " + roomid); ResourceMonitor.countBattle(p1.latestIp, p1.name); ResourceMonitor.countBattle(p2.latestIp, p2.name); rooms[roomid] = new BattleRoom(roomid, format, p1, p2, parent, rated); } return rooms[roomid]; }; var rooms = Object.create(null); console.log("NEW GLOBAL: global"); rooms.global = new GlobalRoom('global'); exports.GlobalRoom = GlobalRoom; exports.BattleRoom = BattleRoom; exports.ChatRoom = ChatRoom; exports.get = getRoom; exports.create = newRoom; exports.rooms = rooms; exports.global = rooms.global; exports.lobby = rooms.lobby;
Revert "Revert "clans"" This reverts commit 2410e35885e2422db38f2f09a838ebab524aabae.
rooms.js
Revert "Revert "clans""
<ide><path>ooms.js <ide> } <ide> }; <ide> BattleRoom.prototype.win = function (winner) { <add> if (Clans.setWarMatchResult(this.p1, this.p2, winner)) { <add> var result = "drawn"; <add> if (toId(winner) === toId(this.p1)) <add> result = "won"; <add> else if (toId(winner) === toId(this.p2)) <add> result = "lost"; <add> <add> var war = Clans.findWarFromClan(Clans.findClanFromMember(this.p1)); <add> Clans.getWarRoom(war[0]).add('|raw|<div class="clans-war-battle-result">(' + Tools.escapeHTML(war[0]) + " vs " + Tools.escapeHTML(war[1]) + ") " + Tools.escapeHTML(this.p1) + " has " + result + " the clan war battle against " + Tools.escapeHTML(this.p2) + '</div>'); <add> <add> var room = Clans.getWarRoom(war[0]); <add> var warEnd = Clans.isWarEnded(war[0]); <add> if (warEnd) { <add> result = "drawn"; <add> if (warEnd.result === 1) <add> result = "won"; <add> else if (warEnd.result === 0) <add> result = "lost"; <add> room.add('|raw|' + <add> '<div class="clans-war-end">' + Tools.escapeHTML(war[0]) + " has " + result + " the clan war against " + Tools.escapeHTML(war[1]) + '</div>' + <add> '<strong>' + Tools.escapeHTML(war[0]) + ':</strong> ' + warEnd.oldRatings[0] + " &rarr; " + warEnd.newRatings[0] + " (" + Clans.ratingToName(warEnd.newRatings[0]) + ")<br />" + <add> '<strong>' + Tools.escapeHTML(war[1]) + ':</strong> ' + warEnd.oldRatings[1] + " &rarr; " + warEnd.newRatings[1] + " (" + Clans.ratingToName(warEnd.newRatings[1]) + ")" <add> ); <add> } <add> } <add> <ide> if (this.rated) { <ide> var winnerid = toId(winner); <ide> var rated = this.rated;
Java
agpl-3.0
06ab4732ea18b8b9b815795799fcc492cf519db4
0
fviale/programming,PaulKh/scale-proactive,mnip91/programming-multiactivities,PaulKh/scale-proactive,mnip91/proactive-component-monitoring,jrochas/scale-proactive,mnip91/programming-multiactivities,mnip91/proactive-component-monitoring,fviale/programming,paraita/programming,paraita/programming,lpellegr/programming,paraita/programming,fviale/programming,lpellegr/programming,PaulKh/scale-proactive,paraita/programming,mnip91/programming-multiactivities,PaulKh/scale-proactive,PaulKh/scale-proactive,acontes/programming,lpellegr/programming,mnip91/programming-multiactivities,paraita/programming,mnip91/proactive-component-monitoring,lpellegr/programming,ow2-proactive/programming,mnip91/programming-multiactivities,fviale/programming,mnip91/proactive-component-monitoring,PaulKh/scale-proactive,PaulKh/scale-proactive,jrochas/scale-proactive,acontes/programming,ow2-proactive/programming,acontes/programming,ow2-proactive/programming,fviale/programming,mnip91/programming-multiactivities,acontes/programming,acontes/programming,mnip91/proactive-component-monitoring,acontes/programming,jrochas/scale-proactive,lpellegr/programming,jrochas/scale-proactive,jrochas/scale-proactive,lpellegr/programming,mnip91/proactive-component-monitoring,ow2-proactive/programming,jrochas/scale-proactive,acontes/programming,ow2-proactive/programming,jrochas/scale-proactive,ow2-proactive/programming,fviale/programming,paraita/programming
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: [email protected] or [email protected] * * This library 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; version 3 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero 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 * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package unitTests.gcmdeployment.descriptorParser; import java.io.File; import java.io.FileNotFoundException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.xml.xpath.XPath; import org.junit.Test; import org.objectweb.proactive.core.ProActiveException; import org.objectweb.proactive.extensions.gcmdeployment.Helpers; import org.objectweb.proactive.extensions.gcmdeployment.GCMApplication.GCMApplicationImpl; import org.objectweb.proactive.extensions.gcmdeployment.GCMApplication.GCMApplicationParser; import org.objectweb.proactive.extensions.gcmdeployment.GCMApplication.GCMApplicationParserImpl; import org.objectweb.proactive.extensions.gcmdeployment.GCMApplication.TechnicalServicesProperties; import org.objectweb.proactive.extensions.gcmdeployment.GCMApplication.commandbuilder.AbstractApplicationParser; import org.objectweb.proactive.extensions.gcmdeployment.GCMApplication.commandbuilder.CommandBuilder; import org.objectweb.proactive.extensions.gcmdeployment.GCMApplication.commandbuilder.CommandBuilderExecutable; import org.w3c.dom.Node; import functionalTests.FunctionalTest; public class TestApplicationDescriptorParser extends FunctionalTest { final static URL TEST_APP_DIR = TestApplicationDescriptorParser.class.getClass().getResource( "/unitTests/gcmdeployment/descriptorParser/testfiles/application"); final static String[] skipDescriptors = { "script_ext.xml", "oldDescriptor.xml", "scriptInvalid.xml", "script6.xml" }; @Test public void test() throws Exception { descloop: for (File descriptor : getApplicationDescriptors()) { for (String skipIt : skipDescriptors) { if (descriptor.toString().contains(skipIt)) continue descloop; } System.out.println("parsing " + descriptor.getCanonicalPath()); GCMApplicationParserImpl parser = new GCMApplicationParserImpl(Helpers.fileToURL(descriptor), null); parser.getCommandBuilder(); parser.getVirtualNodes(); parser.getNodeProviders(); } } /** * User application node parser used to demonstrate how to install custom app parsers * @author The ProActive Team * */ protected static class UserApplicationNodeParser extends AbstractApplicationParser { @Override protected CommandBuilder createCommandBuilder() { return new CommandBuilderExecutable(); } public String getNodeName() { return "paext:myapplication"; } @Override public void parseApplicationNode(Node paNode, GCMApplicationParser applicationParser, XPath xpath) throws Exception { super.parseApplicationNode(paNode, applicationParser, xpath); System.out.println("User Application Parser - someattr value = " + paNode.getAttributes().getNamedItem("someattr").getNodeValue()); } public TechnicalServicesProperties getTechnicalServicesProperties() { // TODO Auto-generated method stub return null; } } // @Test public void userSchemaTest() throws Exception { for (File file : getApplicationDescriptors()) { if (!file.toString().contains("script_ext")) { continue; } System.out.println(file); URL userSchema = getClass() .getResource( "/unitTests/gcmdeployment/descriptorParser/testfiles/application/SampleApplicationExtension.xsd"); ArrayList<String> schemas = new ArrayList<String>(); schemas.add(userSchema.toString()); GCMApplicationParserImpl parser = new GCMApplicationParserImpl(Helpers.fileToURL(file), null, schemas); parser.registerApplicationParser(new UserApplicationNodeParser()); parser.getCommandBuilder(); parser.getVirtualNodes(); parser.getNodeProviders(); } } // @Test public void doit() throws ProActiveException, FileNotFoundException, URISyntaxException { for (File file : getApplicationDescriptors()) { if (!file.toString().contains("scriptHostname") || file.toString().contains("Invalid") || file.toString().contains("oldDesc")) { continue; } System.out.println(file); new GCMApplicationImpl(Helpers.fileToURL(file)); } } private List<File> getApplicationDescriptors() throws URISyntaxException { List<File> ret = new ArrayList<File>(); File dir = null; dir = new File(TEST_APP_DIR.toURI()); for (String file : dir.list()) { if (file.endsWith(".xml")) { ret.add(new File(dir, file)); } } return ret; } @Test(expected = Exception.class) public void validationTest() throws Exception { validationGenericTest("/unitTests/gcmdeployment/descriptorParser/testfiles/application/scriptInvalid.xml"); } @Test(expected = Exception.class) public void validationOldSchemaTest() throws Exception { validationGenericTest("/unitTests/gcmdeployment/descriptorParser/testfiles/application/oldDescriptor.xml"); } @Test(expected = Exception.class) public void validationBrokenXMLTest() throws Exception { validationGenericTest("/unitTests/gcmdeployment/descriptorParser/testfiles/application/script6.xml"); } protected void validationGenericTest(String desc) throws Exception { File descriptor = new File(this.getClass().getResource(desc).getFile()); System.out.println("Parsing " + descriptor.getAbsolutePath()); GCMApplicationParserImpl parser = new GCMApplicationParserImpl(Helpers.fileToURL(descriptor), null); } }
src/Tests/unitTests/gcmdeployment/descriptorParser/TestApplicationDescriptorParser.java
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: [email protected] or [email protected] * * This library 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; version 3 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero 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 * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package unitTests.gcmdeployment.descriptorParser; import java.io.File; import java.io.FileNotFoundException; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.xml.xpath.XPath; import org.junit.Test; import org.objectweb.proactive.core.ProActiveException; import org.objectweb.proactive.extensions.gcmdeployment.Helpers; import org.objectweb.proactive.extensions.gcmdeployment.GCMApplication.GCMApplicationImpl; import org.objectweb.proactive.extensions.gcmdeployment.GCMApplication.GCMApplicationParser; import org.objectweb.proactive.extensions.gcmdeployment.GCMApplication.GCMApplicationParserImpl; import org.objectweb.proactive.extensions.gcmdeployment.GCMApplication.TechnicalServicesProperties; import org.objectweb.proactive.extensions.gcmdeployment.GCMApplication.commandbuilder.AbstractApplicationParser; import org.objectweb.proactive.extensions.gcmdeployment.GCMApplication.commandbuilder.CommandBuilder; import org.objectweb.proactive.extensions.gcmdeployment.GCMApplication.commandbuilder.CommandBuilderExecutable; import org.w3c.dom.Node; import functionalTests.FunctionalTest; public class TestApplicationDescriptorParser extends FunctionalTest { final static String TEST_APP_DIR = TestApplicationDescriptorParser.class.getClass().getResource( "/unitTests/gcmdeployment/descriptorParser/testfiles/application").getFile(); final static String[] skipDescriptors = { "script_ext.xml", "oldDescriptor.xml", "scriptInvalid.xml", "script6.xml" }; @Test public void test() throws Exception { descloop: for (File descriptor : getApplicationDescriptors()) { for (String skipIt : skipDescriptors) { if (descriptor.toString().contains(skipIt)) continue descloop; } System.out.println("parsing " + descriptor.getCanonicalPath()); GCMApplicationParserImpl parser = new GCMApplicationParserImpl(Helpers.fileToURL(descriptor), null); parser.getCommandBuilder(); parser.getVirtualNodes(); parser.getNodeProviders(); } } /** * User application node parser used to demonstrate how to install custom app parsers * @author The ProActive Team * */ protected static class UserApplicationNodeParser extends AbstractApplicationParser { @Override protected CommandBuilder createCommandBuilder() { return new CommandBuilderExecutable(); } public String getNodeName() { return "paext:myapplication"; } @Override public void parseApplicationNode(Node paNode, GCMApplicationParser applicationParser, XPath xpath) throws Exception { super.parseApplicationNode(paNode, applicationParser, xpath); System.out.println("User Application Parser - someattr value = " + paNode.getAttributes().getNamedItem("someattr").getNodeValue()); } public TechnicalServicesProperties getTechnicalServicesProperties() { // TODO Auto-generated method stub return null; } } // @Test public void userSchemaTest() throws Exception { for (File file : getApplicationDescriptors()) { if (!file.toString().contains("script_ext")) { continue; } System.out.println(file); URL userSchema = getClass() .getResource( "/unitTests/gcmdeployment/descriptorParser/testfiles/application/SampleApplicationExtension.xsd"); ArrayList<String> schemas = new ArrayList<String>(); schemas.add(userSchema.toString()); GCMApplicationParserImpl parser = new GCMApplicationParserImpl(Helpers.fileToURL(file), null, schemas); parser.registerApplicationParser(new UserApplicationNodeParser()); parser.getCommandBuilder(); parser.getVirtualNodes(); parser.getNodeProviders(); } } // @Test public void doit() throws ProActiveException, FileNotFoundException { for (File file : getApplicationDescriptors()) { if (!file.toString().contains("scriptHostname") || file.toString().contains("Invalid") || file.toString().contains("oldDesc")) { continue; } System.out.println(file); new GCMApplicationImpl(Helpers.fileToURL(file)); } } private List<File> getApplicationDescriptors() { List<File> ret = new ArrayList<File>(); File dir = new File(TEST_APP_DIR); for (String file : dir.list()) { if (file.endsWith(".xml")) { ret.add(new File(dir, file)); } } return ret; } @Test(expected = Exception.class) public void validationTest() throws Exception { validationGenericTest("/unitTests/gcmdeployment/descriptorParser/testfiles/application/scriptInvalid.xml"); } @Test(expected = Exception.class) public void validationOldSchemaTest() throws Exception { validationGenericTest("/unitTests/gcmdeployment/descriptorParser/testfiles/application/oldDescriptor.xml"); } @Test(expected = Exception.class) public void validationBrokenXMLTest() throws Exception { validationGenericTest("/unitTests/gcmdeployment/descriptorParser/testfiles/application/script6.xml"); } protected void validationGenericTest(String desc) throws Exception { File descriptor = new File(this.getClass().getResource(desc).getFile()); System.out.println("Parsing " + descriptor.getAbsolutePath()); GCMApplicationParserImpl parser = new GCMApplicationParserImpl(Helpers.fileToURL(descriptor), null); } }
PROACTIVE-1093: type of variable TEST_APP_DIR has been changed from String to URL git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@19988 28e8926c-6b08-0410-baaa-805c5e19b8d6
src/Tests/unitTests/gcmdeployment/descriptorParser/TestApplicationDescriptorParser.java
PROACTIVE-1093: type of variable TEST_APP_DIR has been changed from String to URL
<ide><path>rc/Tests/unitTests/gcmdeployment/descriptorParser/TestApplicationDescriptorParser.java <ide> <ide> import java.io.File; <ide> import java.io.FileNotFoundException; <add>import java.net.URISyntaxException; <ide> import java.net.URL; <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> <ide> <ide> public class TestApplicationDescriptorParser extends FunctionalTest { <del> final static String TEST_APP_DIR = TestApplicationDescriptorParser.class.getClass().getResource( <del> "/unitTests/gcmdeployment/descriptorParser/testfiles/application").getFile(); <add> final static URL TEST_APP_DIR = TestApplicationDescriptorParser.class.getClass().getResource( <add> "/unitTests/gcmdeployment/descriptorParser/testfiles/application"); <ide> <ide> final static String[] skipDescriptors = { "script_ext.xml", "oldDescriptor.xml", "scriptInvalid.xml", <ide> "script6.xml" }; <ide> } <ide> <ide> // @Test <del> public void doit() throws ProActiveException, FileNotFoundException { <add> public void doit() throws ProActiveException, FileNotFoundException, URISyntaxException { <ide> for (File file : getApplicationDescriptors()) { <ide> if (!file.toString().contains("scriptHostname") || file.toString().contains("Invalid") || <ide> file.toString().contains("oldDesc")) { <ide> } <ide> } <ide> <del> private List<File> getApplicationDescriptors() { <add> private List<File> getApplicationDescriptors() throws URISyntaxException { <ide> List<File> ret = new ArrayList<File>(); <del> File dir = new File(TEST_APP_DIR); <add> File dir = null; <add> dir = new File(TEST_APP_DIR.toURI()); <ide> <ide> for (String file : dir.list()) { <ide> if (file.endsWith(".xml")) {
Java
apache-2.0
6f76d114711148b88ec3f8dff1656ea3ad55c9c1
0
jruesga/rview,jruesga/rview,jruesga/rview
/* * Copyright (C) 2016 Jorge Ruesga * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ruesga.rview; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.Keep; import android.support.annotation.MenuRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SlidingPaneLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.ruesga.rview.databinding.ContentBinding; import com.ruesga.rview.drawer.DrawerNavigationView; import com.ruesga.rview.drawer.DrawerNavigationView.OnDrawerNavigationItemSelectedListener; import com.ruesga.rview.fragments.PageableFragment.PageFragmentAdapter; import com.ruesga.rview.fragments.SelectableFragment; import com.ruesga.rview.misc.ActivityHelper; import com.ruesga.rview.misc.AndroidHelper; import com.ruesga.rview.misc.ExceptionHelper; import com.ruesga.rview.misc.ModelHelper; import com.ruesga.rview.model.Account; import com.ruesga.rview.model.EmptyState; import com.ruesga.rview.preferences.Preferences; import com.ruesga.rview.widget.PagerControllerLayout; import com.ruesga.rview.widget.PagerControllerLayout.OnPageSelectionListener; import com.ruesga.rview.widget.PagerControllerLayout.PagerControllerAdapter; import com.ruesga.rview.widget.ScrollAwareFloatingActionButtonBehavior; import com.ruesga.rview.wizards.AuthorizationAccountSetupActivity; import java.util.List; import javax.net.ssl.SSLException; public abstract class BaseActivity extends AppCompatDelegateActivity implements OnRefreshListener { public static final String FRAGMENT_TAG_LIST = "list"; public static final String FRAGMENT_TAG_DETAILS = "details"; public interface OnFabPressedListener { void onFabPressed(FloatingActionButton fab); } @Keep @SuppressWarnings("unused") public static class EventHandlers { BaseActivity mActivity; EventHandlers(BaseActivity activity) { mActivity = activity; } public void onFabPressed(View view) { if (mActivity.mOnFabPressedListener != null) { mActivity.mOnFabPressedListener.onFabPressed((FloatingActionButton) view); } } } @Keep public static class Model implements Parcelable { public boolean isInProgress = false; public boolean hasTabs = false; public boolean hasPages = false; public boolean useTowPane = true; public boolean hasMiniDrawer = true; public boolean hasForceSinglePanel = false; public boolean hasFab = false; public Model() { } protected Model(Parcel in) { isInProgress = in.readByte() != 0; hasTabs = in.readByte() != 0; hasPages = in.readByte() != 0; useTowPane = in.readByte() != 0; hasMiniDrawer = in.readByte() != 0; hasForceSinglePanel = in.readByte() != 0; hasFab = in.readByte() != 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeByte((byte) (isInProgress ? 1 : 0)); dest.writeByte((byte) (hasTabs ? 1 : 0)); dest.writeByte((byte) (hasPages ? 1 : 0)); dest.writeByte((byte) (useTowPane ? 1 : 0)); dest.writeByte((byte) (hasMiniDrawer ? 1 : 0)); dest.writeByte((byte) (hasForceSinglePanel ? 1 : 0)); dest.writeByte((byte) (hasFab ? 1 : 0)); } @Override public int describeContents() { return 0; } public static final Creator<Model> CREATOR = new Creator<Model>() { @Override public Model createFromParcel(Parcel in) { return new Model(in); } @Override public Model[] newArray(int size) { return new Model[size]; } }; } private Handler mUiHandler; private Model mModel = new Model(); private final EventHandlers mHandlers = new EventHandlers(this); private ViewPager mViewPager; private boolean mHasStateSaved; private OnFabPressedListener mOnFabPressedListener; private AlertDialog mDialog; private SlidingPaneLayout mMiniDrawerLayout; public abstract DrawerLayout getDrawerLayout(); public abstract ContentBinding getContentBinding(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidHelper.configureTaskDescription(this); mUiHandler = new Handler(); } @Override protected void onDestroy() { super.onDestroy(); if (mDialog != null) { mDialog.dismiss(); mDialog = null; } } protected void setupActivity() { mMiniDrawerLayout = getContentBinding().getRoot().findViewById(R.id.mini_drawer_layout); if (mMiniDrawerLayout != null) { // Disable drawer elevation to match AppBarLayout View v = getContentBinding().getRoot().findViewById(R.id.drawer_navigation_view); ViewCompat.setElevation(v, 0); } setSupportActionBar(getContentBinding().toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); setupDrawer(); configureOptionsDrawer(); } getContentBinding().setHandlers(mHandlers); } private void setupDrawer() { if (mMiniDrawerLayout != null && mModel.useTowPane) { configureMiniDrawer(); } else { configureFullDrawer(); } } public void setupFab(OnFabPressedListener cb) { final Account account = Preferences.getAccount(this); mOnFabPressedListener = cb; mModel.hasFab = account != null && account.hasAuthenticatedAccessMode() && mOnFabPressedListener != null; if (!mModel.hasFab) { getContentBinding().fab.hide(); } else { getContentBinding().fab.show(); } getContentBinding().setModel(mModel); } public void registerFabWithRecyclerView(RecyclerView view) { final Account mAccount = Preferences.getAccount(BaseActivity.this); if (mAccount != null && mAccount.hasAuthenticatedAccessMode()) { view.addOnScrollListener(new RecyclerView.OnScrollListener() { final ScrollAwareFloatingActionButtonBehavior mBehavior = new ScrollAwareFloatingActionButtonBehavior(BaseActivity.this, null); @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { if (mOnFabPressedListener != null) { //noinspection ConstantConditions mBehavior.onNestedScroll( null, getContentBinding().fab, view, dx, dy, 0, 0, -1); } } }); } } private void configureMiniDrawer() { if (getDrawerLayout() != null) { mModel.hasMiniDrawer = true; ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle( this, getDrawerLayout(), getContentBinding().toolbar, 0, 0); getDrawerLayout().addDrawerListener(drawerToggle); getContentBinding().drawerLayout.setDrawerLockMode( DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.START); drawerToggle.syncState(); getContentBinding().toolbar.setNavigationOnClickListener(view -> { if (mMiniDrawerLayout.isOpen()) { mMiniDrawerLayout.closePane(); } else { mMiniDrawerLayout.openPane(); } }); mMiniDrawerLayout.closePane(); getContentBinding().drawerNavigationView.configureWithMiniDrawer(mMiniDrawerLayout); } else { // Don't use mini drawer mModel.hasMiniDrawer = false; } getContentBinding().setModel(mModel); } SlidingPaneLayout getMiniDrawerLayout() { return mMiniDrawerLayout; } private void configureFullDrawer() { if (getDrawerLayout() != null) { ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle( this, getDrawerLayout(), getContentBinding().toolbar, 0, 0); getDrawerLayout().addDrawerListener(drawerToggle); getDrawerLayout().setDrawerLockMode( DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.START); drawerToggle.syncState(); } else { final ViewGroup.LayoutParams params = getContentBinding().drawerLayout.getLayoutParams(); if (!(params instanceof SlidingPaneLayout.LayoutParams)) { getContentBinding().drawerLayout.setDrawerLockMode( DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.START); } if (mModel.hasForceSinglePanel) { // Someones is requesting a single panel in a multipanel layout // Just hide the multipanel mModel.hasMiniDrawer = false; } } } private void configureOptionsDrawer() { // Options is open/closed programmatically getContentBinding().drawerLayout.setDrawerLockMode( DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END); // Listen for options close getContentBinding().drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() { @Override public void onDrawerSlide(View drawerView, float slideOffset) { } @Override public void onDrawerOpened(View drawerView) { } @Override public void onDrawerClosed(View drawerView) { if (getContentBinding().drawerOptionsView == drawerView) { getContentBinding().drawerLayout.setDrawerLockMode( DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END); } } @Override public void onDrawerStateChanged(int newState) { } }); } public boolean hasStateSaved() { return mHasStateSaved; } public void setUseTwoPanel(boolean useTwoPanel) { mModel.useTowPane = useTwoPanel; getContentBinding().setModel(mModel); } public void setForceSinglePanel(boolean singlePanel) { mModel.hasForceSinglePanel = singlePanel; getContentBinding().setModel(mModel); } public void invalidateTabs() { mModel.hasPages = false; mModel.hasTabs = false; getContentBinding().tabs.setupWithViewPager(null); getContentBinding().setModel(mModel); } public void configureTabs(ViewPager viewPager, boolean fixedMode) { mViewPager = viewPager; mModel.hasPages = false; mModel.hasTabs = true; getContentBinding().tabs.setTabMode( fixedMode ? TabLayout.MODE_FIXED : TabLayout.MODE_SCROLLABLE); getContentBinding().tabs.setupWithViewPager(viewPager); getContentBinding().tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { PageFragmentAdapter adapter = (PageFragmentAdapter) mViewPager.getAdapter(); Fragment fragment = adapter.getCachedFragment(tab.getPosition()); if (fragment != null && fragment instanceof SelectableFragment) { mUiHandler.post(((SelectableFragment) fragment)::onFragmentSelected); } // Show fab if necessary showFab(); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); viewPager.getAdapter().notifyDataSetChanged(); getContentBinding().setModel(mModel); } public void invalidatePages() { mModel.hasPages = false; mModel.hasTabs = false; getContentBinding().pagerController.listenOn(null).with(null); getContentBinding().setModel(mModel); } private void showFab() { final Account account = Preferences.getAccount(this); if (account != null && account.hasAuthenticatedAccessMode() && mOnFabPressedListener != null) { getContentBinding().fab.show(); } } public void configurePages(PagerControllerAdapter adapter, OnPageSelectionListener cb) { mViewPager = null; mModel.hasPages = true; mModel.hasTabs = false; getContentBinding().pagerController .listenOn((position, fromUser) -> { if (getSupportActionBar() != null) { getSupportActionBar().setSubtitle( position == PagerControllerLayout.INVALID_PAGE ? null : adapter.getPageTitle(position)); if (cb != null) { cb.onPageSelected(position, fromUser); } } }) .with(adapter); getContentBinding().setModel(mModel); } public void configureOptionsMenu(@MenuRes int menu, OnDrawerNavigationItemSelectedListener cb) { if (menu != 0) { getOptionsMenu().inflateMenu(menu); getOptionsMenu().setDrawerNavigationItemSelectedListener(cb); } } public void configureOptionsTitle(String title) { TextView tv = getContentBinding().drawerOptionsView .getHeaderView(0).findViewById(R.id.options_title); tv.setText(title); } @Override public void onResume() { super.onResume(); mHasStateSaved = false; } @Override protected void onRestoreInstanceState(Bundle savedState) { if (savedState != null) { super.onRestoreInstanceState(savedState); mModel = savedState.getParcelable(getClass().getSimpleName() + "_base_activity_model"); } mHasStateSaved = false; // We need to restore drawer layout lock state if (getContentBinding() != null) { setupDrawer(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(getClass().getSimpleName() + "_base_activity_model", mModel); mHasStateSaved = true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case android.R.id.home: return ActivityHelper.performFinishActivity(this, false); default: return super.onOptionsItemSelected(item); } } @Override public void onBackPressed() { if (getContentBinding() != null && getContentBinding().drawerLayout != null) { final DrawerLayout drawer = getContentBinding().drawerLayout; final DrawerNavigationView optionsView = getContentBinding().drawerOptionsView; final DrawerNavigationView navigationView = getContentBinding().drawerNavigationView; if (optionsView != null && drawer.isDrawerOpen(optionsView)) { closeOptionsDrawer(); return; } if (mMiniDrawerLayout == null && navigationView != null && drawer.isDrawerOpen(navigationView)) { drawer.closeDrawer(navigationView); return; } else if (mMiniDrawerLayout != null && mMiniDrawerLayout.isOpen()) { mMiniDrawerLayout.closePane(); return; } } if (!ActivityHelper.performFinishActivity(this, false)) { super.onBackPressed(); } } public void showError(@StringRes int message) { AndroidHelper.showErrorSnackbar(this, getSnackBarTarget(getContentBinding().getRoot()), message); } public void showWarning(@StringRes int message) { AndroidHelper.showWarningSnackbar(this, getSnackBarTarget(getContentBinding().getRoot()), message); } private View getSnackBarTarget(View root) { View v = root.findViewById(R.id.page_content_layout); if (v != null && v instanceof CoordinatorLayout) { return v; } return root; } public void showToast(@StringRes int message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } public void handleException(String tag, Throwable cause) { handleException(tag, cause, null); } public void handleException(String tag, Throwable cause, final EmptyState.EventHandlers emptyHandler) { int level = ExceptionHelper.exceptionToLevel(cause); int res = ExceptionHelper.exceptionToMessage(this, tag, cause); if (level == 0) { showError(res); } else { showWarning(res); } // Handle authentication denied if (ExceptionHelper.isAuthenticationException(cause)) { if (!ExceptionHelper.hasPreviousAuthenticationFailure(this)) { // Handle Unauthorized exception ExceptionHelper.markAsAuthenticationFailure(this); Intent i = new Intent(BaseActivity.this, AuthorizationAccountSetupActivity.class); i.putExtra(ExceptionHelper.EXTRA_AUTHENTICATION_FAILURE, true); startActivity(i); return; } } // Handle SSL exceptions, so we can ask the user for temporary trust the server connection final Account account = Preferences.getAccount(this); if (account != null && emptyHandler != null && ExceptionHelper.isException(cause, SSLException.class) && (account.mRepository == null || !account.mRepository.mTrustAllCertificates) && !ModelHelper.hasTemporaryTrustAllCertificatesAccessRequested(account)) { // Ask the user for temporary access mDialog = new AlertDialog.Builder(this) .setTitle(R.string.untrusted_connection_title) .setMessage(R.string.untrusted_connection_message) .setIcon(R.drawable.ic_warning) .setPositiveButton(R.string.untrusted_connection_action_trust, (dialogInterface, i) -> { ModelHelper.setTemporaryTrustAllCertificatesAccessGrant(account, true); emptyHandler.onRetry(null); }) .setNegativeButton(R.string.untrusted_connection_action_no_trust, (dialogInterface, i) -> ModelHelper.setTemporaryTrustAllCertificatesAccessGrant( account, false)) .setOnCancelListener(dialogInterface -> ModelHelper.setTemporaryTrustAllCertificatesAccessGrant( account, false)) .setOnDismissListener(dialogInterface -> mDialog = null) .create(); mDialog.show(); } } private void changeInProgressStatus(boolean status) { mModel.isInProgress = status; getContentBinding().setModel(mModel); } @Override public void onRefreshStart(Fragment from) { changeInProgressStatus(true); } @Override public <T> void onRefreshEnd(Fragment from, T result) { changeInProgressStatus(false); } public void openOptionsDrawer() { if (!getContentBinding().drawerLayout.isDrawerOpen(getContentBinding().drawerOptionsView)) { getContentBinding().drawerLayout.setDrawerLockMode( DrawerLayout.LOCK_MODE_UNLOCKED, GravityCompat.END); getContentBinding().drawerLayout.openDrawer(getContentBinding().drawerOptionsView); } } public void closeOptionsDrawer() { if (getContentBinding().drawerLayout.isDrawerOpen(getContentBinding().drawerOptionsView)) { getContentBinding().drawerLayout.closeDrawer(getContentBinding().drawerOptionsView); } getContentBinding().drawerLayout.setDrawerLockMode( DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END); } public DrawerNavigationView getOptionsMenu() { return getContentBinding().drawerOptionsView; } @Override public void onRequestPermissionsResult( int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); List<Fragment> fragments = getSupportFragmentManager().getFragments(); if (fragments != null) { for (Fragment fragment : fragments) { fragment.onRequestPermissionsResult(requestCode, permissions, grantResults); } } } }
app/src/main/java/com/ruesga/rview/BaseActivity.java
/* * Copyright (C) 2016 Jorge Ruesga * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ruesga.rview; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.Keep; import android.support.annotation.MenuRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SlidingPaneLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.ruesga.rview.databinding.ContentBinding; import com.ruesga.rview.drawer.DrawerNavigationView; import com.ruesga.rview.drawer.DrawerNavigationView.OnDrawerNavigationItemSelectedListener; import com.ruesga.rview.fragments.PageableFragment.PageFragmentAdapter; import com.ruesga.rview.fragments.SelectableFragment; import com.ruesga.rview.misc.ActivityHelper; import com.ruesga.rview.misc.AndroidHelper; import com.ruesga.rview.misc.ExceptionHelper; import com.ruesga.rview.misc.ModelHelper; import com.ruesga.rview.model.Account; import com.ruesga.rview.model.EmptyState; import com.ruesga.rview.preferences.Preferences; import com.ruesga.rview.widget.PagerControllerLayout; import com.ruesga.rview.widget.PagerControllerLayout.OnPageSelectionListener; import com.ruesga.rview.widget.PagerControllerLayout.PagerControllerAdapter; import com.ruesga.rview.widget.ScrollAwareFloatingActionButtonBehavior; import com.ruesga.rview.wizards.AuthorizationAccountSetupActivity; import java.util.List; import javax.net.ssl.SSLException; public abstract class BaseActivity extends AppCompatDelegateActivity implements OnRefreshListener { public static final String FRAGMENT_TAG_LIST = "list"; public static final String FRAGMENT_TAG_DETAILS = "details"; public interface OnFabPressedListener { void onFabPressed(FloatingActionButton fab); } @Keep @SuppressWarnings("unused") public static class EventHandlers { BaseActivity mActivity; EventHandlers(BaseActivity activity) { mActivity = activity; } public void onFabPressed(View view) { if (mActivity.mOnFabPressedListener != null) { mActivity.mOnFabPressedListener.onFabPressed((FloatingActionButton) view); } } } @Keep public static class Model implements Parcelable { public boolean isInProgress = false; public boolean hasTabs = false; public boolean hasPages = false; public boolean useTowPane = true; public boolean hasMiniDrawer = true; public boolean hasForceSinglePanel = false; public boolean hasFab = false; public Model() { } protected Model(Parcel in) { isInProgress = in.readByte() != 0; hasTabs = in.readByte() != 0; hasPages = in.readByte() != 0; useTowPane = in.readByte() != 0; hasMiniDrawer = in.readByte() != 0; hasForceSinglePanel = in.readByte() != 0; hasFab = in.readByte() != 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeByte((byte) (isInProgress ? 1 : 0)); dest.writeByte((byte) (hasTabs ? 1 : 0)); dest.writeByte((byte) (hasPages ? 1 : 0)); dest.writeByte((byte) (useTowPane ? 1 : 0)); dest.writeByte((byte) (hasMiniDrawer ? 1 : 0)); dest.writeByte((byte) (hasForceSinglePanel ? 1 : 0)); dest.writeByte((byte) (hasFab ? 1 : 0)); } @Override public int describeContents() { return 0; } public static final Creator<Model> CREATOR = new Creator<Model>() { @Override public Model createFromParcel(Parcel in) { return new Model(in); } @Override public Model[] newArray(int size) { return new Model[size]; } }; } private Handler mUiHandler; private Model mModel = new Model(); private final EventHandlers mHandlers = new EventHandlers(this); private ViewPager mViewPager; private boolean mHasStateSaved; private OnFabPressedListener mOnFabPressedListener; private AlertDialog mDialog; private SlidingPaneLayout mMiniDrawerLayout; public abstract DrawerLayout getDrawerLayout(); public abstract ContentBinding getContentBinding(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidHelper.configureTaskDescription(this); mUiHandler = new Handler(); } @Override protected void onDestroy() { super.onDestroy(); if (mDialog != null) { mDialog.dismiss(); mDialog = null; } } protected void setupActivity() { mMiniDrawerLayout = getContentBinding().getRoot().findViewById(R.id.mini_drawer_layout); if (mMiniDrawerLayout != null) { // Disable drawer elevation to match AppBarLayout View v = getContentBinding().getRoot().findViewById(R.id.drawer_navigation_view); ViewCompat.setElevation(v, 0); } setSupportActionBar(getContentBinding().toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); setupDrawer(); configureOptionsDrawer(); } getContentBinding().setHandlers(mHandlers); } private void setupDrawer() { if (mMiniDrawerLayout != null && mModel.useTowPane) { configureMiniDrawer(); } else { configureFullDrawer(); } } public void setupFab(OnFabPressedListener cb) { final Account account = Preferences.getAccount(this); mOnFabPressedListener = cb; mModel.hasFab = account != null && account.hasAuthenticatedAccessMode() && mOnFabPressedListener != null; if (!mModel.hasFab) { getContentBinding().fab.hide(); } else { getContentBinding().fab.show(); } getContentBinding().setModel(mModel); } public void registerFabWithRecyclerView(RecyclerView view) { view.addOnScrollListener(new RecyclerView.OnScrollListener() { final ScrollAwareFloatingActionButtonBehavior mBehavior = new ScrollAwareFloatingActionButtonBehavior(BaseActivity.this, null); @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { //noinspection ConstantConditions mBehavior.onNestedScroll(null, getContentBinding().fab, view, dx, dy, 0, 0, -1); } }); } private void configureMiniDrawer() { if (getDrawerLayout() != null) { mModel.hasMiniDrawer = true; ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle( this, getDrawerLayout(), getContentBinding().toolbar, 0, 0); getDrawerLayout().addDrawerListener(drawerToggle); getContentBinding().drawerLayout.setDrawerLockMode( DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.START); drawerToggle.syncState(); getContentBinding().toolbar.setNavigationOnClickListener(view -> { if (mMiniDrawerLayout.isOpen()) { mMiniDrawerLayout.closePane(); } else { mMiniDrawerLayout.openPane(); } }); mMiniDrawerLayout.closePane(); getContentBinding().drawerNavigationView.configureWithMiniDrawer(mMiniDrawerLayout); } else { // Don't use mini drawer mModel.hasMiniDrawer = false; } getContentBinding().setModel(mModel); } SlidingPaneLayout getMiniDrawerLayout() { return mMiniDrawerLayout; } private void configureFullDrawer() { if (getDrawerLayout() != null) { ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle( this, getDrawerLayout(), getContentBinding().toolbar, 0, 0); getDrawerLayout().addDrawerListener(drawerToggle); getDrawerLayout().setDrawerLockMode( DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.START); drawerToggle.syncState(); } else { final ViewGroup.LayoutParams params = getContentBinding().drawerLayout.getLayoutParams(); if (!(params instanceof SlidingPaneLayout.LayoutParams)) { getContentBinding().drawerLayout.setDrawerLockMode( DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.START); } if (mModel.hasForceSinglePanel) { // Someones is requesting a single panel in a multipanel layout // Just hide the multipanel mModel.hasMiniDrawer = false; } } } private void configureOptionsDrawer() { // Options is open/closed programmatically getContentBinding().drawerLayout.setDrawerLockMode( DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END); // Listen for options close getContentBinding().drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() { @Override public void onDrawerSlide(View drawerView, float slideOffset) { } @Override public void onDrawerOpened(View drawerView) { } @Override public void onDrawerClosed(View drawerView) { if (getContentBinding().drawerOptionsView == drawerView) { getContentBinding().drawerLayout.setDrawerLockMode( DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END); } } @Override public void onDrawerStateChanged(int newState) { } }); } public boolean hasStateSaved() { return mHasStateSaved; } public void setUseTwoPanel(boolean useTwoPanel) { mModel.useTowPane = useTwoPanel; getContentBinding().setModel(mModel); } public void setForceSinglePanel(boolean singlePanel) { mModel.hasForceSinglePanel = singlePanel; getContentBinding().setModel(mModel); } public void invalidateTabs() { mModel.hasPages = false; mModel.hasTabs = false; getContentBinding().tabs.setupWithViewPager(null); getContentBinding().setModel(mModel); } public void configureTabs(ViewPager viewPager, boolean fixedMode) { mViewPager = viewPager; mModel.hasPages = false; mModel.hasTabs = true; getContentBinding().tabs.setTabMode( fixedMode ? TabLayout.MODE_FIXED : TabLayout.MODE_SCROLLABLE); getContentBinding().tabs.setupWithViewPager(viewPager); getContentBinding().tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { PageFragmentAdapter adapter = (PageFragmentAdapter) mViewPager.getAdapter(); Fragment fragment = adapter.getCachedFragment(tab.getPosition()); if (fragment != null && fragment instanceof SelectableFragment) { mUiHandler.post(((SelectableFragment) fragment)::onFragmentSelected); } // Show fab if necessary showFab(); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); viewPager.getAdapter().notifyDataSetChanged(); getContentBinding().setModel(mModel); } public void invalidatePages() { mModel.hasPages = false; mModel.hasTabs = false; getContentBinding().pagerController.listenOn(null).with(null); getContentBinding().setModel(mModel); } private void showFab() { final Account account = Preferences.getAccount(this); if (account != null && account.hasAuthenticatedAccessMode() && mOnFabPressedListener != null) { getContentBinding().fab.show(); } } public void configurePages(PagerControllerAdapter adapter, OnPageSelectionListener cb) { mViewPager = null; mModel.hasPages = true; mModel.hasTabs = false; getContentBinding().pagerController .listenOn((position, fromUser) -> { if (getSupportActionBar() != null) { getSupportActionBar().setSubtitle( position == PagerControllerLayout.INVALID_PAGE ? null : adapter.getPageTitle(position)); if (cb != null) { cb.onPageSelected(position, fromUser); } } }) .with(adapter); getContentBinding().setModel(mModel); } public void configureOptionsMenu(@MenuRes int menu, OnDrawerNavigationItemSelectedListener cb) { if (menu != 0) { getOptionsMenu().inflateMenu(menu); getOptionsMenu().setDrawerNavigationItemSelectedListener(cb); } } public void configureOptionsTitle(String title) { TextView tv = getContentBinding().drawerOptionsView .getHeaderView(0).findViewById(R.id.options_title); tv.setText(title); } @Override public void onResume() { super.onResume(); mHasStateSaved = false; } @Override protected void onRestoreInstanceState(Bundle savedState) { if (savedState != null) { super.onRestoreInstanceState(savedState); mModel = savedState.getParcelable(getClass().getSimpleName() + "_base_activity_model"); } mHasStateSaved = false; // We need to restore drawer layout lock state if (getContentBinding() != null) { setupDrawer(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(getClass().getSimpleName() + "_base_activity_model", mModel); mHasStateSaved = true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case android.R.id.home: return ActivityHelper.performFinishActivity(this, false); default: return super.onOptionsItemSelected(item); } } @Override public void onBackPressed() { if (getContentBinding() != null && getContentBinding().drawerLayout != null) { final DrawerLayout drawer = getContentBinding().drawerLayout; final DrawerNavigationView optionsView = getContentBinding().drawerOptionsView; final DrawerNavigationView navigationView = getContentBinding().drawerNavigationView; if (optionsView != null && drawer.isDrawerOpen(optionsView)) { closeOptionsDrawer(); return; } if (mMiniDrawerLayout == null && navigationView != null && drawer.isDrawerOpen(navigationView)) { drawer.closeDrawer(navigationView); return; } else if (mMiniDrawerLayout != null && mMiniDrawerLayout.isOpen()) { mMiniDrawerLayout.closePane(); return; } } if (!ActivityHelper.performFinishActivity(this, false)) { super.onBackPressed(); } } public void showError(@StringRes int message) { AndroidHelper.showErrorSnackbar(this, getSnackBarTarget(getContentBinding().getRoot()), message); } public void showWarning(@StringRes int message) { AndroidHelper.showWarningSnackbar(this, getSnackBarTarget(getContentBinding().getRoot()), message); } private View getSnackBarTarget(View root) { View v = root.findViewById(R.id.page_content_layout); if (v != null && v instanceof CoordinatorLayout) { return v; } return root; } public void showToast(@StringRes int message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } public void handleException(String tag, Throwable cause) { handleException(tag, cause, null); } public void handleException(String tag, Throwable cause, final EmptyState.EventHandlers emptyHandler) { int level = ExceptionHelper.exceptionToLevel(cause); int res = ExceptionHelper.exceptionToMessage(this, tag, cause); if (level == 0) { showError(res); } else { showWarning(res); } // Handle authentication denied if (ExceptionHelper.isAuthenticationException(cause)) { if (!ExceptionHelper.hasPreviousAuthenticationFailure(this)) { // Handle Unauthorized exception ExceptionHelper.markAsAuthenticationFailure(this); Intent i = new Intent(BaseActivity.this, AuthorizationAccountSetupActivity.class); i.putExtra(ExceptionHelper.EXTRA_AUTHENTICATION_FAILURE, true); startActivity(i); return; } } // Handle SSL exceptions, so we can ask the user for temporary trust the server connection final Account account = Preferences.getAccount(this); if (account != null && emptyHandler != null && ExceptionHelper.isException(cause, SSLException.class) && (account.mRepository == null || !account.mRepository.mTrustAllCertificates) && !ModelHelper.hasTemporaryTrustAllCertificatesAccessRequested(account)) { // Ask the user for temporary access mDialog = new AlertDialog.Builder(this) .setTitle(R.string.untrusted_connection_title) .setMessage(R.string.untrusted_connection_message) .setIcon(R.drawable.ic_warning) .setPositiveButton(R.string.untrusted_connection_action_trust, (dialogInterface, i) -> { ModelHelper.setTemporaryTrustAllCertificatesAccessGrant(account, true); emptyHandler.onRetry(null); }) .setNegativeButton(R.string.untrusted_connection_action_no_trust, (dialogInterface, i) -> ModelHelper.setTemporaryTrustAllCertificatesAccessGrant( account, false)) .setOnCancelListener(dialogInterface -> ModelHelper.setTemporaryTrustAllCertificatesAccessGrant( account, false)) .setOnDismissListener(dialogInterface -> mDialog = null) .create(); mDialog.show(); } } private void changeInProgressStatus(boolean status) { mModel.isInProgress = status; getContentBinding().setModel(mModel); } @Override public void onRefreshStart(Fragment from) { changeInProgressStatus(true); } @Override public <T> void onRefreshEnd(Fragment from, T result) { changeInProgressStatus(false); } public void openOptionsDrawer() { if (!getContentBinding().drawerLayout.isDrawerOpen(getContentBinding().drawerOptionsView)) { getContentBinding().drawerLayout.setDrawerLockMode( DrawerLayout.LOCK_MODE_UNLOCKED, GravityCompat.END); getContentBinding().drawerLayout.openDrawer(getContentBinding().drawerOptionsView); } } public void closeOptionsDrawer() { if (getContentBinding().drawerLayout.isDrawerOpen(getContentBinding().drawerOptionsView)) { getContentBinding().drawerLayout.closeDrawer(getContentBinding().drawerOptionsView); } getContentBinding().drawerLayout.setDrawerLockMode( DrawerLayout.LOCK_MODE_LOCKED_CLOSED, GravityCompat.END); } public DrawerNavigationView getOptionsMenu() { return getContentBinding().drawerOptionsView; } @Override public void onRequestPermissionsResult( int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); List<Fragment> fragments = getSupportFragmentManager().getFragments(); if (fragments != null) { for (Fragment fragment : fragments) { fragment.onRequestPermissionsResult(requestCode, permissions, grantResults); } } } }
Only if it should be handled Signed-off-by: Jorge Ruesga <[email protected]>
app/src/main/java/com/ruesga/rview/BaseActivity.java
Only if it should be handled
<ide><path>pp/src/main/java/com/ruesga/rview/BaseActivity.java <ide> } <ide> <ide> public void registerFabWithRecyclerView(RecyclerView view) { <del> view.addOnScrollListener(new RecyclerView.OnScrollListener() { <del> final ScrollAwareFloatingActionButtonBehavior mBehavior = <del> new ScrollAwareFloatingActionButtonBehavior(BaseActivity.this, null); <del> <del> @Override <del> public void onScrolled(RecyclerView recyclerView, int dx, int dy) { <del> //noinspection ConstantConditions <del> mBehavior.onNestedScroll(null, getContentBinding().fab, view, dx, dy, 0, 0, -1); <del> } <del> }); <add> final Account mAccount = Preferences.getAccount(BaseActivity.this); <add> if (mAccount != null && mAccount.hasAuthenticatedAccessMode()) { <add> view.addOnScrollListener(new RecyclerView.OnScrollListener() { <add> final ScrollAwareFloatingActionButtonBehavior mBehavior = <add> new ScrollAwareFloatingActionButtonBehavior(BaseActivity.this, null); <add> <add> @Override <add> public void onScrolled(RecyclerView recyclerView, int dx, int dy) { <add> if (mOnFabPressedListener != null) { <add> //noinspection ConstantConditions <add> mBehavior.onNestedScroll( <add> null, getContentBinding().fab, view, dx, dy, 0, 0, -1); <add> } <add> } <add> }); <add> } <ide> } <ide> <ide> private void configureMiniDrawer() {
Java
apache-2.0
48f76aeaa7aca185dfeed02e86ce161532750374
0
gnuhub/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,petteyg/intellij-community,izonder/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,holmes/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,xfournet/intellij-community,samthor/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,kool79/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,semonte/intellij-community,caot/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,holmes/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,signed/intellij-community,kool79/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,allotria/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,FHannes/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,semonte/intellij-community,jagguli/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,slisson/intellij-community,da1z/intellij-community,diorcety/intellij-community,dslomov/intellij-community,da1z/intellij-community,petteyg/intellij-community,samthor/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,izonder/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,diorcety/intellij-community,apixandru/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,apixandru/intellij-community,supersven/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,clumsy/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,caot/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,allotria/intellij-community,kool79/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,petteyg/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,signed/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,kdwink/intellij-community,apixandru/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,samthor/intellij-community,caot/intellij-community,holmes/intellij-community,FHannes/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,adedayo/intellij-community,allotria/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,semonte/intellij-community,izonder/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,caot/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,fnouama/intellij-community,ryano144/intellij-community,jagguli/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,samthor/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,izonder/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,adedayo/intellij-community,jagguli/intellij-community,signed/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,supersven/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,adedayo/intellij-community,da1z/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,amith01994/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,da1z/intellij-community,FHannes/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,signed/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,allotria/intellij-community,suncycheng/intellij-community,slisson/intellij-community,diorcety/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,izonder/intellij-community,caot/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,fitermay/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,ryano144/intellij-community,asedunov/intellij-community,FHannes/intellij-community,semonte/intellij-community,allotria/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,holmes/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,diorcety/intellij-community,izonder/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,jagguli/intellij-community,semonte/intellij-community,hurricup/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,holmes/intellij-community,holmes/intellij-community,signed/intellij-community,da1z/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,ryano144/intellij-community,fitermay/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,caot/intellij-community,kdwink/intellij-community,dslomov/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,kool79/intellij-community,supersven/intellij-community,allotria/intellij-community,ahb0327/intellij-community,supersven/intellij-community,robovm/robovm-studio,dslomov/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,apixandru/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,fnouama/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,retomerz/intellij-community,ryano144/intellij-community,izonder/intellij-community,fitermay/intellij-community,FHannes/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,adedayo/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,xfournet/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,retomerz/intellij-community,retomerz/intellij-community,ryano144/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,kool79/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,samthor/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,slisson/intellij-community,signed/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,signed/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,holmes/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,xfournet/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,petteyg/intellij-community,xfournet/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,fnouama/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,caot/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,slisson/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,slisson/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,semonte/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,clumsy/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,semonte/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,allotria/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,slisson/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,adedayo/intellij-community,caot/intellij-community,FHannes/intellij-community,jagguli/intellij-community,adedayo/intellij-community,holmes/intellij-community,samthor/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,blademainer/intellij-community,blademainer/intellij-community,caot/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,ryano144/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,signed/intellij-community,signed/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,da1z/intellij-community,clumsy/intellij-community,diorcety/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,kdwink/intellij-community,signed/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,semonte/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,dslomov/intellij-community,blademainer/intellij-community,kdwink/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,amith01994/intellij-community,izonder/intellij-community,da1z/intellij-community,gnuhub/intellij-community,supersven/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,fitermay/intellij-community,samthor/intellij-community,retomerz/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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.jetbrains.plugins.groovy.intentions.base; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.GroovyFileType; import org.jetbrains.plugins.groovy.annotator.intentions.QuickfixUtil; import org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle; import org.jetbrains.plugins.groovy.intentions.utils.BoolUtils; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringUtil; public abstract class Intention implements IntentionAction { private final PsiElementPredicate predicate; /** * @noinspection AbstractMethodCallInConstructor, OverridableMethodCallInConstructor */ protected Intention() { super(); predicate = getElementPredicate(); } public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { if (!QuickfixUtil.ensureFileWritable(project, file)) { return; } final PsiElement element = findMatchingElement(file, editor); if (element == null) { return; } assert element.isValid() : element; processIntention(element, project, editor); } protected abstract void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException; @NotNull protected abstract PsiElementPredicate getElementPredicate(); protected static void replaceExpressionWithNegatedExpressionString(@NotNull String newExpression, @NotNull GrExpression expression) throws IncorrectOperationException { final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(expression.getProject()); GrExpression expressionToReplace = expression; final String expString; if (BoolUtils.isNegated(expression)) { expressionToReplace = BoolUtils.findNegation(expression); expString = newExpression; } else { expString = "!(" + newExpression + ')'; } final GrExpression newCall = factory.createExpressionFromText(expString); assert expressionToReplace != null; expressionToReplace.replaceWithExpression(newCall, true); } @Nullable PsiElement findMatchingElement(PsiFile file, Editor editor) { if (!file.getViewProvider().getLanguages().contains(GroovyFileType.GROOVY_LANGUAGE)) { return null; } SelectionModel selectionModel = editor.getSelectionModel(); if (selectionModel.hasSelection() && !selectionModel.hasBlockSelection()) { int start = selectionModel.getSelectionStart(); int end = selectionModel.getSelectionEnd(); if (0 <= start && start <= end) { TextRange selectionRange = new TextRange(start, end); PsiElement element = GroovyRefactoringUtil.findElementInRange(file, start, end, PsiElement.class); while (element != null && element.getTextRange() != null && selectionRange.contains(element.getTextRange())) { if (predicate.satisfiedBy(element)) return element; element = element.getParent(); } } } final int position = editor.getCaretModel().getOffset(); PsiElement element = file.findElementAt(position); while (element != null) { if (predicate.satisfiedBy(element)) return element; if (isStopElement(element)) break; element = element.getParent(); } element = file.findElementAt(position - 1); while (element != null) { if (predicate.satisfiedBy(element)) return element; if (isStopElement(element)) return null; element = element.getParent(); } return null; } protected boolean isStopElement(PsiElement element) { return element instanceof PsiFile; } public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { return findMatchingElement(file, editor) != null; } public boolean startInWriteAction() { return true; } private String getPrefix() { final Class<? extends Intention> aClass = getClass(); final String name = aClass.getSimpleName(); final StringBuilder buffer = new StringBuilder(name.length() + 10); buffer.append(Character.toLowerCase(name.charAt(0))); for (int i = 1; i < name.length(); i++) { final char c = name.charAt(i); if (Character.isUpperCase(c)) { buffer.append('.'); buffer.append(Character.toLowerCase(c)); } else { buffer.append(c); } } return buffer.toString(); } @NotNull public String getText() { return GroovyIntentionsBundle.message(getPrefix() + ".name"); } @NotNull public String getFamilyName() { return GroovyIntentionsBundle.message(getPrefix() + ".family.name"); } }
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/base/Intention.java
/* * Copyright 2000-2013 JetBrains s.r.o. * * 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.jetbrains.plugins.groovy.intentions.base; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.GroovyFileType; import org.jetbrains.plugins.groovy.annotator.intentions.QuickfixUtil; import org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle; import org.jetbrains.plugins.groovy.intentions.utils.BoolUtils; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringUtil; public abstract class Intention implements IntentionAction { private final PsiElementPredicate predicate; /** * @noinspection AbstractMethodCallInConstructor, OverridableMethodCallInConstructor */ protected Intention() { super(); predicate = getElementPredicate(); } public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { if (!QuickfixUtil.ensureFileWritable(project, file)) { return; } final PsiElement element = findMatchingElement(file, editor); if (element == null) { return; } assert element.isValid() : element; processIntention(element, project, editor); } protected abstract void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException; @NotNull protected abstract PsiElementPredicate getElementPredicate(); protected static void replaceExpressionWithNegatedExpressionString(@NotNull String newExpression, @NotNull GrExpression expression) throws IncorrectOperationException { final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(expression.getProject()); GrExpression expressionToReplace = expression; final String expString; if (BoolUtils.isNegated(expression)) { expressionToReplace = BoolUtils.findNegation(expression); expString = newExpression; } else { expString = "!(" + newExpression + ')'; } final GrExpression newCall = factory.createExpressionFromText(expString); assert expressionToReplace != null; expressionToReplace.replaceWithExpression(newCall, true); } @Nullable PsiElement findMatchingElement(PsiFile file, Editor editor) { if (!file.getViewProvider().getLanguages().contains(GroovyFileType.GROOVY_LANGUAGE)) { return null; } SelectionModel selectionModel = editor.getSelectionModel(); if (selectionModel.hasSelection() && !selectionModel.hasBlockSelection()) { TextRange selectionRange = new TextRange(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()); PsiElement element = GroovyRefactoringUtil .findElementInRange(file, selectionModel.getSelectionStart(), selectionModel.getSelectionEnd(), PsiElement.class); while (element != null && element.getTextRange() != null && selectionRange.contains(element.getTextRange())) { if (predicate.satisfiedBy(element)) return element; element = element.getParent(); } } final int position = editor.getCaretModel().getOffset(); PsiElement element = file.findElementAt(position); while (element != null) { if (predicate.satisfiedBy(element)) return element; if (isStopElement(element)) break; element = element.getParent(); } element = file.findElementAt(position - 1); while (element != null) { if (predicate.satisfiedBy(element)) return element; if (isStopElement(element)) return null; element = element.getParent(); } return null; } protected boolean isStopElement(PsiElement element) { return element instanceof PsiFile; } public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { return findMatchingElement(file, editor) != null; } public boolean startInWriteAction() { return true; } private String getPrefix() { final Class<? extends Intention> aClass = getClass(); final String name = aClass.getSimpleName(); final StringBuilder buffer = new StringBuilder(name.length() + 10); buffer.append(Character.toLowerCase(name.charAt(0))); for (int i = 1; i < name.length(); i++) { final char c = name.charAt(i); if (Character.isUpperCase(c)) { buffer.append('.'); buffer.append(Character.toLowerCase(c)); } else { buffer.append(c); } } return buffer.toString(); } @NotNull public String getText() { return GroovyIntentionsBundle.message(getPrefix() + ".name"); } @NotNull public String getFamilyName() { return GroovyIntentionsBundle.message(getPrefix() + ".family.name"); } }
EA-49782 - assert: TextRange.<init>
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/base/Intention.java
EA-49782 - assert: TextRange.<init>
<ide><path>lugins/groovy/src/org/jetbrains/plugins/groovy/intentions/base/Intention.java <ide> /* <del> * Copyright 2000-2013 JetBrains s.r.o. <add> * Copyright 2000-2014 JetBrains s.r.o. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> SelectionModel selectionModel = editor.getSelectionModel(); <ide> if (selectionModel.hasSelection() && !selectionModel.hasBlockSelection()) { <del> TextRange selectionRange = new TextRange(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()); <del> PsiElement element = GroovyRefactoringUtil <del> .findElementInRange(file, selectionModel.getSelectionStart(), selectionModel.getSelectionEnd(), PsiElement.class); <del> while (element != null && element.getTextRange() != null && selectionRange.contains(element.getTextRange())) { <del> if (predicate.satisfiedBy(element)) return element; <del> element = element.getParent(); <add> int start = selectionModel.getSelectionStart(); <add> int end = selectionModel.getSelectionEnd(); <add> <add> if (0 <= start && start <= end) { <add> TextRange selectionRange = new TextRange(start, end); <add> PsiElement element = GroovyRefactoringUtil.findElementInRange(file, start, end, PsiElement.class); <add> while (element != null && element.getTextRange() != null && selectionRange.contains(element.getTextRange())) { <add> if (predicate.satisfiedBy(element)) return element; <add> element = element.getParent(); <add> } <ide> } <ide> } <ide>
Java
agpl-3.0
affbd9159aaaba4eb6008992c2c21389864e53e8
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
b5242532-2e5f-11e5-9284-b827eb9e62be
hello.java
b51eaaf8-2e5f-11e5-9284-b827eb9e62be
b5242532-2e5f-11e5-9284-b827eb9e62be
hello.java
b5242532-2e5f-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>b51eaaf8-2e5f-11e5-9284-b827eb9e62be <add>b5242532-2e5f-11e5-9284-b827eb9e62be
JavaScript
mit
793527c0e58e580bb67a8c2c15e6a1e5cbd502f4
0
phetsims/scenery-phet,phetsims/scenery-phet,phetsims/scenery-phet
// Copyright 2016, University of Colorado Boulder /** * A key accumulator that collects user input for integer and floating point values, intended for use in conjunction * with the common-code keypad. * * @author Aadish Gupta * @author John Blanco * @author Chris Malley (PixelZoom, Inc.) */ define( function( require ) { 'use strict'; // modules var AbstractKeyAccumulator = require( 'SCENERY_PHET/keypad/AbstractKeyAccumulator' ); var DerivedProperty = require( 'AXON/DerivedProperty' ); var inherit = require( 'PHET_CORE/inherit' ); var KeyID = require( 'SCENERY_PHET/keypad/KeyID' ); var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' ); var Tandem = require( 'TANDEM/Tandem' ); // constants var NEGATIVE_CHAR = '\u2212'; var DECIMAL_CHAR = '.'; /** * @param {Object} [options] * @constructor */ function NumberAccumulator( options ) { Tandem.indicateUninstrumentedCode(); var self = this; options = _.extend( { maxDigitsRightOfMantissa: 0, maxDigits: Number.MAX_SAFE_INTEGER.toString().length }, options ); AbstractKeyAccumulator.call( this, options ); this.maxDigitsRightOfMantissa = options.maxDigitsRightOfMantissa; // @private this.maxDigits = options.maxDigits; // @private // @public (read-only) - string representation of the keys entered by the user this.stringProperty = new DerivedProperty( [ this.accumulatedKeysProperty ], function( accumulatedKeys ) { return self.keysToString( accumulatedKeys ); } ); // @public (read-only) - numerical value of the keys entered by the user this.valueProperty = new DerivedProperty( [ this.stringProperty ], function( stringValue ) { return self.stringToInteger( stringValue ); } ); } sceneryPhet.register( 'NumberAccumulator', NumberAccumulator ); return inherit( AbstractKeyAccumulator, NumberAccumulator, { /** * invoked when a key is pressed and creates proposed set of keys to be passed to the validator * @param {KeyID} keyIdentifier - identifier for the key pressed * @public * @override */ handleKeyPressed: function( keyIdentifier ) { var newArray = this.handleClearOnNextKeyPress( keyIdentifier ); if ( this.isDigit( keyIdentifier ) ) { this.removeLeadingZero( newArray ); newArray.push( keyIdentifier ); } else if ( keyIdentifier === KeyID.BACKSPACE ) { newArray.pop(); } else if ( keyIdentifier === KeyID.PLUS_MINUS ) { // check if first element of array is instance of this class if ( newArray.length > 0 && newArray[ 0 ] === KeyID.PLUS_MINUS ) { newArray.shift(); } else { newArray.unshift( keyIdentifier ); } } else if ( keyIdentifier === KeyID.DECIMAL ) { if ( !this.containsFloatingPoint( newArray ) ) { newArray.push( keyIdentifier ); } } else { assert && assert( false, 'This type of Key is not supported Number Keypad' ); } this.validateAndUpdate( newArray ); }, /** * removes leading zeros from the array * @param {Array.<KeyID>} array * @private */ removeLeadingZero: function( array ) { if ( this.valueProperty.get() === 0 && !this.containsFloatingPoint( array ) ) { array.pop(); } }, /** * validate a proposed set of keys * @param {Array.<KeyID>} proposedKeys - the proposed set of keys, to be validated * @returns {boolean} * @public * @override */ defaultValidator: function( proposedKeys ) { return ( this.getNumberOfDigits( proposedKeys ) <= this.maxDigits && !( this.getNumberOfDigits( proposedKeys ) === this.maxDigits && proposedKeys[ proposedKeys.length - 1 ] === KeyID.DECIMAL ) && this.getNumberOfDigitsRightOfMantissa( proposedKeys ) <= this.maxDigitsRightOfMantissa ); }, /** * Converts a set of keys to a string. * @param {Array.<KeyID>} keys * @returns {string} * @private */ keysToString: function( keys ) { var returnValue = ''; var i = 0; // PlusMinusKey (if present) will be first key, and indicates that the number is negative if ( keys.length > 0 && keys[ i ] === KeyID.PLUS_MINUS ) { returnValue = NEGATIVE_CHAR; i++; } // process remaining keys for ( ; i < keys.length; i++ ) { if ( keys[ i ] === KeyID.DECIMAL ) { returnValue = returnValue + DECIMAL_CHAR; } else { // PlusMinusKey (if present) should only be first assert && assert( this.isDigit( keys[ i ] ), 'unexpected key type' ); returnValue = returnValue + keys[ i ]; } } return returnValue; }, /** * Converts a string representation to a number. * @param {string} stringValue * @returns {number} * @private */ stringToInteger: function( stringValue ) { var returnValue = null; // if stringValue contains something other than just a minus sign... if ( stringValue.length > 0 && !( stringValue.length === 1 && stringValue[ 0 ] === NEGATIVE_CHAR ) && ( this.getNumberOfDigitsLeftOfMantissa( this.accumulatedKeysProperty.get() ) > 0 || this.getNumberOfDigitsRightOfMantissa( this.accumulatedKeysProperty.get() ) > 0 ) ) { // replace Unicode minus with vanilla '-', or parseInt will fail for negative numbers returnValue = parseFloat( stringValue.replace( NEGATIVE_CHAR, '-' ).replace( DECIMAL_CHAR, '.' ) ); assert && assert( !isNaN( returnValue ), 'invalid number: ' + returnValue ); } return returnValue; }, /** * Gets the number of digits to the left of mantissa in the accumulator. * @param {Array.<KeyID>} keys * @returns {number} * @private */ getNumberOfDigitsLeftOfMantissa: function( keys ) { var numberOfDigits = 0; for ( var i = 0; i < keys.length; i++ ) { if ( this.isDigit( keys[ i ] ) ) { numberOfDigits++; } if ( keys[ i ] === KeyID.DECIMAL ) { break; } } return numberOfDigits; }, /** * Gets the number of digits to the right of mantissa in the accumulator. * @param {Array.<KeyID>} keys * @returns {number} * @private */ getNumberOfDigitsRightOfMantissa: function( keys ) { var decimalKeyIndex = keys.indexOf( KeyID.DECIMAL ); var numberOfDigits = 0; if ( decimalKeyIndex >= 0 ) { for ( var i = decimalKeyIndex; i < keys.length; i++ ) { if ( this.isDigit( keys[ i ] ) ) { numberOfDigits++; } } } return numberOfDigits; }, /** * Gets the number of digits in the accumulator. * @param {Array.<KeyID>} keys * @returns {number} * @private */ getNumberOfDigits: function( keys ) { var numberOfDigits = 0; for ( var i = 0; i < keys.length; i++ ) { if ( this.isDigit( keys[ i ] ) ) { numberOfDigits++; } } return numberOfDigits; }, /** * Gets the number of digits in the accumulator. * @param {Array.<KeyID>} keys * @returns {boolean} * @private */ containsFloatingPoint: function( keys ) { return ( keys.indexOf( KeyID.DECIMAL ) >= 0 ); }, /** * Returns weather the character is valid digit or not * @param char * @returns {boolean} * @private */ isDigit: function( char ) { return !isNaN( char ) && char >= '0' && char <= '9'; }, /** * clear the accumulator * @public */ clear: function() { AbstractKeyAccumulator.prototype.clear.call( this ); this.setClearOnNextKeyPress( false ); }, /** * Cleans up references. * @public */ dispose: function(){ this.valueProperty.dispose(); this.stringProperty.dispose(); AbstractKeyAccumulator.prototype.dispose.call( this ); } } ); } );
js/keypad/NumberAccumulator.js
// Copyright 2016, University of Colorado Boulder /** * A key accumulator that collects user input for integer and floating point values, intended for use in conjunction * with the common-code keypad. * * @author Aadish Gupta * @author John Blanco * @author Chris Malley (PixelZoom, Inc.) */ define( function( require ) { 'use strict'; // modules var AbstractKeyAccumulator = require( 'SCENERY_PHET/keypad/AbstractKeyAccumulator' ); var DerivedProperty = require( 'AXON/DerivedProperty' ); var inherit = require( 'PHET_CORE/inherit' ); var KeyID = require( 'SCENERY_PHET/keypad/KeyID' ); var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' ); var Tandem = require( 'TANDEM/Tandem' ); // constants var NEGATIVE_CHAR = '\u2212'; var DECIMAL_CHAR = '.'; /** * @param {Object} [options] * @constructor */ function NumberAccumulator( options ) { Tandem.indicateUninstrumentedCode(); var self = this; options = _.extend( { maxDigitsRightOfMantissa: 0, maxDigits: Number.MAX_SAFE_INTEGER.toString().length }, options ); AbstractKeyAccumulator.call( this, options ); this.maxDigitsRightOfMantissa = options.maxDigitsRightOfMantissa; // @private this.maxDigits = options.maxDigits; // @private // @public (read-only) - string representation of the keys entered by the user this.stringProperty = new DerivedProperty( [ this.accumulatedKeysProperty ], function( accumulatedKeys ) { return self.keysToString( accumulatedKeys ); } ); // @public (read-only) - numerical value of the keys entered by the user this.valueProperty = new DerivedProperty( [ this.stringProperty ], function( stringValue ) { return self.stringToInteger( stringValue ); } ); } sceneryPhet.register( 'NumberAccumulator', NumberAccumulator ); return inherit( AbstractKeyAccumulator, NumberAccumulator, { /** * invoked when a key is pressed and creates proposed set of keys to be passed to the validator * @param {KeyID} keyIdentifier - identifier for the key pressed * @public * @override */ handleKeyPressed: function( keyIdentifier ) { var newArray = this.handleClearOnNextKeyPress( keyIdentifier ); if ( this.isDigit( keyIdentifier ) ) { this.removeLeadingZero( newArray ); newArray.push( keyIdentifier ); } else if ( keyIdentifier === KeyID.BACKSPACE ) { newArray.pop(); } else if ( keyIdentifier === KeyID.PLUS_MINUS ) { // check if first element of array is instance of this class if ( newArray.length > 0 && newArray[ 0 ] === KeyID.PLUS_MINUS ) { newArray.shift(); } else { newArray.unshift( keyIdentifier ); } } else if ( keyIdentifier === KeyID.DECIMAL ) { if ( !this.containsFloatingPoint( newArray ) ) { newArray.push( keyIdentifier ); } } else { assert && assert( false, 'This type of Key is not supported Number Keypad' ); } this.validateAndUpdate( newArray ); }, /** * removes leading zeros from the array * @param {Array.<KeyID>} array * @private */ removeLeadingZero: function( array ) { if ( this.valueProperty.get() === 0 && !this.containsFloatingPoint( array ) ) { array.pop(); } }, /** * validate a proposed set of keys * @param {Array.<KeyID>} proposedKeys - the proposed set of keys, to be validated * @returns {boolean} * @public * @override */ defaultValidator: function( proposedKeys ) { return ( this.getNumberOfDigits( proposedKeys ) <= this.maxDigits && !( this.getNumberOfDigits( proposedKeys ) === this.maxDigits && proposedKeys[ proposedKeys.length - 1 ] === KeyID.DECIMAL ) && this.getNumberOfDigitsRightOfMantissa( proposedKeys ) <= this.maxDigitsRightOfMantissa ); }, /** * Converts a set of keys to a string. * @param {Array.<KeyID>} keys * @returns {string} * @private */ keysToString: function( keys ) { var returnValue = ''; var i = 0; // PlusMinusKey (if present) will be first key, and indicates that the number is negative if ( keys.length > 0 && keys[ i ] === KeyID.PLUS_MINUS ) { returnValue = NEGATIVE_CHAR; i++; } // process remaining keys for ( ; i < keys.length; i++ ) { if ( keys[ i ] === KeyID.DECIMAL ) { returnValue = returnValue + DECIMAL_CHAR; } else { // PlusMinusKey (if present) should only be first assert && assert( this.isDigit( keys[ i ] ), 'unexpected key type' ); returnValue = returnValue + keys[ i ]; } } return returnValue; }, /** * Converts a string representation to a number. * @param {string} stringValue * @returns {number} * @private */ stringToInteger: function( stringValue ) { var returnValue = null; // if stringValue contains something other than just a minus sign... if ( stringValue.length > 0 && !( stringValue.length === 1 && stringValue[ 0 ] === NEGATIVE_CHAR ) && ( this.getNumberOfDigitsLeftOfMantissa( this.accumulatedKeysProperty.get() ) > 0 || this.getNumberOfDigitsRightOfMantissa( this.accumulatedKeysProperty.get() ) > 0 ) ) { // replace Unicode minus with vanilla '-', or parseInt will fail for negative numbers returnValue = parseFloat( stringValue.replace( NEGATIVE_CHAR, '-' ).replace( DECIMAL_CHAR, '.' ) ); assert && assert( !isNaN( returnValue ), 'invalid number: ' + returnValue ); } return returnValue; }, /** * Gets the number of digits to the left of mantissa in the accumulator. * @param {Array.<KeyID>} keys * @returns {number} * @private */ getNumberOfDigitsLeftOfMantissa: function( keys ) { var numberOfDigits = 0; for ( var i = 0; i < keys.length; i++ ) { if ( this.isDigit( keys[ i ] ) ) { numberOfDigits++; } if ( keys[ i ] === KeyID.DECIMAL ) { break; } } return numberOfDigits; }, /** * Gets the number of digits to the right of mantissa in the accumulator. * @param {Array.<KeyID>} keys * @returns {number} * @private */ getNumberOfDigitsRightOfMantissa: function( keys ) { var decimalKeyIndex = keys.indexOf( KeyID.DECIMAL ); var numberOfDigits = 0; if ( decimalKeyIndex >= 0 ) { for ( var i = decimalKeyIndex; i < keys.length; i++ ) { if ( this.isDigit( keys[ i ] ) ) { numberOfDigits++; } } } return numberOfDigits; }, /** * Gets the number of digits in the accumulator. * @param {Array.<KeyID>} keys * @returns {number} * @private */ getNumberOfDigits: function( keys ) { var numberOfDigits = 0; for ( var i = 0; i < keys.length; i++ ) { if ( this.isDigit( keys[ i ] ) ) { numberOfDigits++; } } return numberOfDigits; }, /** * Gets the number of digits in the accumulator. * @param {Array.<KeyID>} keys * @returns {boolean} * @private */ containsFloatingPoint: function( keys ) { return ( keys.indexOf( KeyID.DECIMAL ) >= 0 ); }, /** * Returns weather the character is valid digit or not * @param char * @returns {boolean} * @private */ isDigit: function( char ) { return !isNaN( char ) && char >= '0' && char <= '9'; }, /** * clear the accumulator * @public */ clear: function() { AbstractKeyAccumulator.prototype.clear.call( this ); this.setClearOnNextKeyPress( false ); }, /** * Cleans up references. * @public */ dispose: function(){ this.valueProperty.dispose(); this.stringProperty.dispose(); AbstractKeyAccumulator.prototype.dispose.call( this ); } } ); } );
formatting #283
js/keypad/NumberAccumulator.js
formatting #283
<ide><path>s/keypad/NumberAccumulator.js <ide> returnValue = returnValue + DECIMAL_CHAR; <ide> } <ide> else { <add> <ide> // PlusMinusKey (if present) should only be first <ide> assert && assert( this.isDigit( keys[ i ] ), 'unexpected key type' ); <ide> returnValue = returnValue + keys[ i ];
JavaScript
mit
26c8ca3c62722874b865d4bb2e5a2eea6d37317c
0
Combitech/codefarm,Combitech/codefarm,Combitech/codefarm
import React from "react"; import Immutable from "immutable"; import LightComponent from "ui-lib/light_component"; import { Row, Col } from "react-flexbox-grid"; import moment from "moment"; import api from "api.io/api.io-client"; import stateVar from "ui-lib/state_var"; import BaselineList from "../../observables/baseline_list"; import { CardList, RevisionCard, AddCommentCard, CommentCard, ReviewCard, JobCard } from "ui-components/data_card"; class Overview extends LightComponent { constructor(props) { super(props); this.baselines = new BaselineList({ type: props.item.type, id: props.item._id }); this.state = { comment: stateVar(this, "comment", ""), baselines: this.baselines.value.getValue() }; } componentDidMount() { this.addDisposable(this.baselines.start()); this.addDisposable(this.baselines.value.subscribe((baselines) => this.setState({ baselines }))); } componentWillReceiveProps(nextProps) { this.baselines.setOpts({ id: nextProps.item._id, type: nextProps.item.type }); } async onComment(comment) { await api.type.action(this.props.item.type, this.props.item._id, "comment", comment); } render() { this.log("render", this.props, this.state); const list = [ { id: "addcomment", time: Number.MAX_SAFE_INTEGER, Card: AddCommentCard, props: { onComment: this.onComment.bind(this) } } ]; for (const comment of this.props.item.comments) { list.push({ id: comment.time, time: moment(comment.time).unix(), item: comment, Card: CommentCard, props: {} }); } this.props.item.patches.forEach((patch, patchIndex) => { list.push({ id: `${this.props.item._id}-${patchIndex}`, time: moment(patch.submitted).unix(), item: this.props.item, Card: RevisionCard, props: { patchIndex: patchIndex } }); }); this.props.item.reviews // Filter out reviews without author (email) //TODO: Remove filter once we are sure Email is resolved correctly .filter((review) => review.userEmail) .forEach((review, reviewIndex) => { list.push({ id: `review-${reviewIndex}`, time: moment(review.updated).unix(), item: review, Card: ReviewCard, props: {} }); }); // for (const baseline of this.state.baselines.toJS()) { // const time = moment(baseline.created); // // list.push({ // timestamp: time.unix(), // id: `baseline-${baseline._id}`, // avatar: ( // <img // className={this.props.theme.icon} // src={icons.baseline} // /> // ), // time: time, // title: `Qualified for baseline ${baseline.name} `, // description: `${baseline._id}`, // details: { // content: baseline.content // } // }); // } const jobs = this.props.itemExt.data.refs .filter((ref) => ref.data && ref.data.type === "exec.job") .map((ref) => ref.data); for (const job of jobs) { list.push({ id: job._id, time: moment(job.finished ? job.finished : job.saved).unix(), item: job, Card: JobCard, props: { } }); } return ( <div> <Row className={this.props.theme.row}> <Col xs={12} md={6} className={this.props.theme.col}> <h5 className={this.props.theme.sectionHeader}>Revision</h5> <RevisionCard theme={this.props.theme} item={this.props.item} expanded={true} expandable={false} /> </Col> <Col xs={12} md={6} className={this.props.theme.col}> <h5 className={this.props.theme.sectionHeader}>Events</h5> <CardList list={Immutable.fromJS(list)} /> </Col> </Row> </div> ); } } Overview.propTypes = { theme: React.PropTypes.object, item: React.PropTypes.object.isRequired, itemExt: React.PropTypes.object.isRequired }; export default Overview;
src/app/UI/lib/managers/code/client/components/sections/Overview.js
import React from "react"; import Immutable from "immutable"; import LightComponent from "ui-lib/light_component"; import { Row, Col } from "react-flexbox-grid"; import moment from "moment"; import api from "api.io/api.io-client"; import stateVar from "ui-lib/state_var"; import BaselineList from "../../observables/baseline_list"; import { CardList, RevisionCard, AddCommentCard, CommentCard, ReviewCard, JobCard } from "ui-components/data_card"; class Overview extends LightComponent { constructor(props) { super(props); this.baselines = new BaselineList({ type: props.item.type, id: props.item._id }); this.state = { comment: stateVar(this, "comment", ""), baselines: this.baselines.value.getValue() }; } componentDidMount() { this.addDisposable(this.baselines.start()); this.addDisposable(this.baselines.value.subscribe((baselines) => this.setState({ baselines }))); } componentWillReceiveProps(nextProps) { this.baselines.setOpts({ id: nextProps.item._id, type: nextProps.item.type }); } async onComment(comment) { await api.type.action(this.props.item.type, this.props.item._id, "comment", comment); } render() { this.log("render", this.props, this.state); const list = [ { id: "addcomment", time: Number.MAX_SAFE_INTEGER, Card: AddCommentCard, props: { onComment: this.onComment.bind(this) } } ]; for (const comment of this.props.item.comments) { list.push({ id: comment.time, time: moment(comment.time).unix(), item: comment, Card: CommentCard, props: {} }); } this.props.item.patches.forEach((patch, patchIndex) => { list.push({ id: `${this.props.item._id}-${patchIndex}`, time: moment(patch.submitted).unix(), item: this.props.item, Card: RevisionCard, props: { patchIndex: patchIndex } }); }); this.props.item.reviews.forEach((review, reviewIndex) => { list.push({ id: `review-${reviewIndex}`, time: moment(review.updated).unix(), item: review, Card: ReviewCard, props: {} }); }); // for (const baseline of this.state.baselines.toJS()) { // const time = moment(baseline.created); // // list.push({ // timestamp: time.unix(), // id: `baseline-${baseline._id}`, // avatar: ( // <img // className={this.props.theme.icon} // src={icons.baseline} // /> // ), // time: time, // title: `Qualified for baseline ${baseline.name} `, // description: `${baseline._id}`, // details: { // content: baseline.content // } // }); // } const jobs = this.props.itemExt.data.refs .filter((ref) => ref.data && ref.data.type === "exec.job") .map((ref) => ref.data); for (const job of jobs) { list.push({ id: job._id, time: moment(job.finished ? job.finished : job.saved).unix(), item: job, Card: JobCard, props: { } }); } return ( <div> <Row className={this.props.theme.row}> <Col xs={12} md={6} className={this.props.theme.col}> <h5 className={this.props.theme.sectionHeader}>Revision</h5> <RevisionCard theme={this.props.theme} item={this.props.item} expanded={true} expandable={false} /> </Col> <Col xs={12} md={6} className={this.props.theme.col}> <h5 className={this.props.theme.sectionHeader}>Events</h5> <CardList list={Immutable.fromJS(list)} /> </Col> </Row> </div> ); } } Overview.propTypes = { theme: React.PropTypes.object, item: React.PropTypes.object.isRequired, itemExt: React.PropTypes.object.isRequired }; export default Overview;
[fix] Dont show review card when no email set
src/app/UI/lib/managers/code/client/components/sections/Overview.js
[fix] Dont show review card when no email set
<ide><path>rc/app/UI/lib/managers/code/client/components/sections/Overview.js <ide> }); <ide> }); <ide> <del> this.props.item.reviews.forEach((review, reviewIndex) => { <del> list.push({ <del> id: `review-${reviewIndex}`, <del> time: moment(review.updated).unix(), <del> item: review, <del> Card: ReviewCard, <del> props: {} <add> this.props.item.reviews <add> // Filter out reviews without author (email) <add> //TODO: Remove filter once we are sure Email is resolved correctly <add> .filter((review) => review.userEmail) <add> .forEach((review, reviewIndex) => { <add> list.push({ <add> id: `review-${reviewIndex}`, <add> time: moment(review.updated).unix(), <add> item: review, <add> Card: ReviewCard, <add> props: {} <add> }); <ide> }); <del> }); <ide> <ide> // for (const baseline of this.state.baselines.toJS()) { <ide> // const time = moment(baseline.created);
Java
apache-2.0
646462329177f42e7ad08a4c927b08cef0d8bf21
0
finmath/finmath-lib,finmath/finmath-lib
/* * (c) Copyright Christian P. Fries, Germany. Contact: [email protected]. * * Created on 27.04.2012 */ package net.finmath.montecarlo.assetderivativevaluation.products; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import net.finmath.exception.CalculationException; import net.finmath.montecarlo.RandomVariableFromDoubleArray; import net.finmath.montecarlo.assetderivativevaluation.AssetModelMonteCarloSimulationModel; import net.finmath.montecarlo.automaticdifferentiation.RandomVariableDifferentiable; import net.finmath.montecarlo.conditionalexpectation.MonteCarloConditionalExpectationRegression; import net.finmath.stochastic.ConditionalExpectationEstimator; import net.finmath.stochastic.RandomVariable; /** * This class implements a delta hedged portfolio (a hedge simulator). * The delta hedge uses numerical calculation of * the delta and - in theory - works for any model implementing <code>AssetModelMonteCarloSimulationModel</code> * and any product implementing <code>AbstractAssetMonteCarloProduct</code>. * The results however somewhat depend on the choice of the internal regression basis functions. * * The <code>getValue</code>-method returns the random variable \( \Pi(t) \) representing the value * of the replication portfolio \( \Pi(t) = \phi_0(t) N(t) + \phi_1(t) S(t) \). * * @author Christian Fries * @version 1.1 */ public class DeltaHedgedPortfolioWithAAD extends AbstractAssetMonteCarloProduct { // The financial product we like to replicate private final AssetMonteCarloProduct productToReplicate; private int orderOfRegressionPolynomial = 4; private double lastOperationTimingValuation = Double.NaN; private double lastOperationTimingDerivative = Double.NaN; /** * Construction of a delta hedge portfolio. The delta hedge uses numerical calculation of * the delta and - in theory - works for any model implementing <code>AssetModelMonteCarloSimulationModel</code> * and any product implementing <code>AbstractAssetMonteCarloProduct</code>. * The results however somewhat depend on the choice of the internal regression basis functions. * * @param productToReplicate The product for which the replication portfolio should be build. May be any product implementing the <code>AbstractAssetMonteCarloProduct</code> interface. */ public DeltaHedgedPortfolioWithAAD(AssetMonteCarloProduct productToReplicate) { super(); this.productToReplicate = productToReplicate; } @Override public RandomVariable getValue(double evaluationTime, AssetModelMonteCarloSimulationModel model) throws CalculationException { // Ask the model for its discretization int timeIndexEvaluationTime = model.getTimeIndex(evaluationTime); /* * Going forward in time we monitor the hedge portfolio on each path. */ long timingValuationStart = System.currentTimeMillis(); RandomVariableDifferentiable value = (RandomVariableDifferentiable) productToReplicate.getValue(model.getTime(0), model); RandomVariable exerciseTime = null; if(productToReplicate instanceof BermudanOption) { exerciseTime = ((BermudanOption) productToReplicate).getLastValuationExerciseTime(); } long timingValuationEnd = System.currentTimeMillis(); RandomVariable valueOfOption = model.getRandomVariableForConstant(value.getAverage()); // Initialize the portfolio to zero stocks and as much cash as the Black-Scholes Model predicts we need. RandomVariable underlyingToday = model.getAssetValue(0.0,0); RandomVariable numeraireToday = model.getNumeraire(0.0); // We store the composition of the hedge portfolio (depending on the path) RandomVariable amountOfNumeraireAsset = valueOfOption.div(numeraireToday); RandomVariable amountOfUderlyingAsset = model.getRandomVariableForConstant(0.0); // Delta of option to replicate long timingDerivativeStart = System.currentTimeMillis(); Map<Long, RandomVariable> gradient = value.getGradient(); long timingDerivativeEnd = System.currentTimeMillis(); lastOperationTimingValuation = (timingValuationEnd-timingValuationStart) / 1000.0; lastOperationTimingDerivative = (timingDerivativeEnd-timingDerivativeStart) / 1000.0; for(int timeIndex = 0; timeIndex<timeIndexEvaluationTime; timeIndex++) { // Get value of underlying and numeraire assets RandomVariable underlyingAtTimeIndex = model.getAssetValue(timeIndex,0); RandomVariable numeraireAtTimeIndex = model.getNumeraire(timeIndex); // Get delta RandomVariable delta = gradient.get(((RandomVariableDifferentiable)underlyingAtTimeIndex).getID()); if(delta == null) { delta = underlyingAtTimeIndex.mult(0.0); } delta = delta.mult(numeraireAtTimeIndex); RandomVariable indicator = new RandomVariableFromDoubleArray(1.0); if(exerciseTime != null) { indicator = exerciseTime.sub(model.getTime(timeIndex)+0.001).choose(new RandomVariableFromDoubleArray(1.0), new RandomVariableFromDoubleArray(0.0)); } // Create a conditional expectation estimator with some basis functions (predictor variables) for conditional expectation estimation. ArrayList<RandomVariable> basisFunctions = getRegressionBasisFunctionsBinning(underlyingAtTimeIndex, indicator); ConditionalExpectationEstimator conditionalExpectationOperator = new MonteCarloConditionalExpectationRegression(basisFunctions.toArray(new RandomVariable[0])); delta = delta.getConditionalExpectation(conditionalExpectationOperator); /* * Change the portfolio according to the trading strategy */ // Determine the delta hedge RandomVariable newNumberOfStocks = delta; RandomVariable stocksToBuy = newNumberOfStocks.sub(amountOfUderlyingAsset); // Ensure self financing RandomVariable numeraireAssetsToSell = stocksToBuy.mult(underlyingAtTimeIndex).div(numeraireAtTimeIndex); RandomVariable newNumberOfNumeraireAsset = amountOfNumeraireAsset.sub(numeraireAssetsToSell); // Update portfolio amountOfNumeraireAsset = newNumberOfNumeraireAsset; amountOfUderlyingAsset = newNumberOfStocks; } /* * At maturity, calculate the value of the replication portfolio */ // Get value of underlying and numeraire assets RandomVariable underlyingAtEvaluationTime = model.getAssetValue(evaluationTime,0); RandomVariable numeraireAtEvaluationTime = model.getNumeraire(evaluationTime); RandomVariable portfolioValue = amountOfNumeraireAsset.mult(numeraireAtEvaluationTime) .add(amountOfUderlyingAsset.mult(underlyingAtEvaluationTime)); return portfolioValue; } public double getLastOperationTimingValuation() { return lastOperationTimingValuation; } public double getLastOperationTimingDerivative() { return lastOperationTimingDerivative; } private ArrayList<RandomVariable> getRegressionBasisFunctions(RandomVariable underlying, RandomVariable indicator) { ArrayList<RandomVariable> basisFunctions = new ArrayList<RandomVariable>(); // Create basis functions - here: 1, S, S^2, S^3, S^4 for(int powerOfRegressionMonomial=0; powerOfRegressionMonomial<=orderOfRegressionPolynomial; powerOfRegressionMonomial++) { basisFunctions.add(underlying.pow(powerOfRegressionMonomial).mult(indicator)); } return basisFunctions; } private ArrayList<RandomVariable> getRegressionBasisFunctionsBinning(RandomVariable underlying, RandomVariable indicator) { ArrayList<RandomVariable> basisFunctions = new ArrayList<RandomVariable>(); if(underlying.isDeterministic()) { basisFunctions.add(underlying); } else { int numberOfBins = 20; double[] values = underlying.getRealizations(); Arrays.sort(values); for(int i = 0; i<numberOfBins; i++) { double binLeft = values[(int)((double)i/(double)numberOfBins*values.length)]; RandomVariable basisFunction = underlying.sub(binLeft).choose(new RandomVariableFromDoubleArray(1.0), new RandomVariableFromDoubleArray(0.0)).mult(indicator); basisFunctions.add(basisFunction); } } return basisFunctions; } }
src/main/java/net/finmath/montecarlo/assetderivativevaluation/products/DeltaHedgedPortfolioWithAAD.java
/* * (c) Copyright Christian P. Fries, Germany. Contact: [email protected]. * * Created on 27.04.2012 */ package net.finmath.montecarlo.assetderivativevaluation.products; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import net.finmath.exception.CalculationException; import net.finmath.montecarlo.RandomVariableFromDoubleArray; import net.finmath.montecarlo.assetderivativevaluation.AssetModelMonteCarloSimulationModel; import net.finmath.montecarlo.automaticdifferentiation.RandomVariableDifferentiable; import net.finmath.montecarlo.conditionalexpectation.MonteCarloConditionalExpectationRegression; import net.finmath.stochastic.ConditionalExpectationEstimator; import net.finmath.stochastic.RandomVariable; /** * This class implements a delta hedged portfolio (a hedge simulator). * The delta hedge uses numerical calculation of * the delta and - in theory - works for any model implementing <code>AssetModelMonteCarloSimulationModel</code> * and any product implementing <code>AbstractAssetMonteCarloProduct</code>. * The results however somewhat depend on the choice of the internal regression basis functions. * * The <code>getValue</code>-method returns the random variable \( \Pi(t) \) representing the value * of the replication portfolio \( \Pi(t) = \phi_0(t) N(t) + \phi_1(t) S(t) \). * * @author Christian Fries * @version 1.1 */ public class DeltaHedgedPortfolioWithAAD extends AbstractAssetMonteCarloProduct { // The financial product we like to replicate private final AssetMonteCarloProduct productToReplicate; private int orderOfRegressionPolynomial = 4; private double lastOperationTimingValuation = Double.NaN; private double lastOperationTimingDerivative = Double.NaN; /** * Construction of a delta hedge portfolio. The delta hedge uses numerical calculation of * the delta and - in theory - works for any model implementing <code>AssetModelMonteCarloSimulationModel</code> * and any product implementing <code>AbstractAssetMonteCarloProduct</code>. * The results however somewhat depend on the choice of the internal regression basis functions. * * @param productToReplicate The product for which the replication portfolio should be build. May be any product implementing the <code>AbstractAssetMonteCarloProduct</code> interface. */ public DeltaHedgedPortfolioWithAAD(AssetMonteCarloProduct productToReplicate) { super(); this.productToReplicate = productToReplicate; } @Override public RandomVariable getValue(double evaluationTime, AssetModelMonteCarloSimulationModel model) throws CalculationException { // Ask the model for its discretization int timeIndexEvaluationTime = model.getTimeIndex(evaluationTime); /* * Going forward in time we monitor the hedge portfolio on each path. */ long timingValuationStart = System.currentTimeMillis(); RandomVariableDifferentiable value = (RandomVariableDifferentiable) productToReplicate.getValue(model.getTime(0), model); RandomVariable exerciseTime = null; if(productToReplicate instanceof BermudanOption) { exerciseTime = ((BermudanOption) productToReplicate).getLastValuationExerciseTime(); } long timingValuationEnd = System.currentTimeMillis(); RandomVariable valueOfOption = model.getRandomVariableForConstant(value.getAverage()); // Initialize the portfolio to zero stocks and as much cash as the Black-Scholes Model predicts we need. RandomVariable underlyingToday = model.getAssetValue(0.0,0); RandomVariable numeraireToday = model.getNumeraire(0.0); // We store the composition of the hedge portfolio (depending on the path) RandomVariable amountOfNumeraireAsset = valueOfOption.div(numeraireToday); RandomVariable amountOfUderlyingAsset = model.getRandomVariableForConstant(0.0); // Delta of option to replicate long timingDerivativeStart = System.currentTimeMillis(); Map<Long, RandomVariable> gradient = value.getGradient(); long timingDerivativeEnd = System.currentTimeMillis(); lastOperationTimingValuation = (timingValuationEnd-timingValuationStart) / 1000.0; lastOperationTimingDerivative = (timingDerivativeEnd-timingDerivativeStart) / 1000.0; for(int timeIndex = 0; timeIndex<timeIndexEvaluationTime; timeIndex++) { // Get value of underlying and numeraire assets RandomVariable underlyingAtTimeIndex = model.getAssetValue(timeIndex,0); RandomVariable numeraireAtTimeIndex = model.getNumeraire(timeIndex); // Get delta RandomVariable delta = gradient.get(((RandomVariableDifferentiable)underlyingAtTimeIndex).getID()); if(delta == null) { delta = underlyingAtTimeIndex.mult(0.0); } delta = delta.mult(numeraireAtTimeIndex); RandomVariable indicator = new RandomVariableFromDoubleArray(1.0); if(exerciseTime != null) { indicator = exerciseTime.sub(model.getTime(timeIndex)+0.001).choose(new RandomVariableFromDoubleArray(1.0), new RandomVariableFromDoubleArray(0.0)); } // Create a conditional expectation estimator with some basis functions (predictor variables) for conditional expectation estimation. ArrayList<RandomVariable> basisFunctions = getRegressionBasisFunctionsBinning(underlyingAtTimeIndex, indicator); ConditionalExpectationEstimator conditionalExpectationOperator = new MonteCarloConditionalExpectationRegression(basisFunctions.toArray(new RandomVariable[0])); delta = delta.getConditionalExpectation(conditionalExpectationOperator); /* * Change the portfolio according to the trading strategy */ // Determine the delta hedge RandomVariable newNumberOfStocks = delta; RandomVariable stocksToBuy = newNumberOfStocks.sub(amountOfUderlyingAsset); // Ensure self financing RandomVariable numeraireAssetsToSell = stocksToBuy.mult(underlyingAtTimeIndex).div(numeraireAtTimeIndex); RandomVariable newNumberOfNumeraireAsset = amountOfNumeraireAsset.sub(numeraireAssetsToSell); // Update portfolio amountOfNumeraireAsset = newNumberOfNumeraireAsset; amountOfUderlyingAsset = newNumberOfStocks; } /* * At maturity, calculate the value of the replication portfolio */ // Get value of underlying and numeraire assets RandomVariable underlyingAtEvaluationTime = model.getAssetValue(evaluationTime,0); RandomVariable numeraireAtEvaluationTime = model.getNumeraire(evaluationTime); RandomVariable portfolioValue = amountOfNumeraireAsset.mult(numeraireAtEvaluationTime) .add(amountOfUderlyingAsset.mult(underlyingAtEvaluationTime)); return portfolioValue; } public double getLastOperationTimingValuation() { return lastOperationTimingValuation; } public double getLastOperationTimingDerivative() { return lastOperationTimingDerivative; } private ArrayList<RandomVariable> getRegressionBasisFunctions(RandomVariable underlying, RandomVariable indicator) { ArrayList<RandomVariable> basisFunctions = new ArrayList<RandomVariable>(); // Create basis functions - here: 1, S, S^2, S^3, S^4 for(int powerOfRegressionMonomial=0; powerOfRegressionMonomial<=orderOfRegressionPolynomial; powerOfRegressionMonomial++) { basisFunctions.add(underlying.pow(powerOfRegressionMonomial).mult(indicator)); } return basisFunctions; } private ArrayList<RandomVariable> getRegressionBasisFunctionsBinning(RandomVariable underlying, RandomVariable indicator) { ArrayList<RandomVariable> basisFunctions = new ArrayList<RandomVariable>(); int numberOfBins = 20; double[] values = underlying.getRealizations(); Arrays.sort(values); for(int i = 0; i<numberOfBins; i++) { double binLeft = values[(int)((double)i/(double)numberOfBins*values.length)]; RandomVariable basisFunction = underlying.sub(binLeft).choose(new RandomVariableFromDoubleArray(1.0), new RandomVariableFromDoubleArray(0.0)).mult(indicator); basisFunctions.add(basisFunction); } return basisFunctions; } }
Fixed NPE for basis functions derived from deterministic random variable
src/main/java/net/finmath/montecarlo/assetderivativevaluation/products/DeltaHedgedPortfolioWithAAD.java
Fixed NPE for basis functions derived from deterministic random variable
<ide><path>rc/main/java/net/finmath/montecarlo/assetderivativevaluation/products/DeltaHedgedPortfolioWithAAD.java <ide> private ArrayList<RandomVariable> getRegressionBasisFunctionsBinning(RandomVariable underlying, RandomVariable indicator) { <ide> ArrayList<RandomVariable> basisFunctions = new ArrayList<RandomVariable>(); <ide> <del> int numberOfBins = 20; <del> double[] values = underlying.getRealizations(); <del> Arrays.sort(values); <del> for(int i = 0; i<numberOfBins; i++) { <del> double binLeft = values[(int)((double)i/(double)numberOfBins*values.length)]; <del> RandomVariable basisFunction = underlying.sub(binLeft).choose(new RandomVariableFromDoubleArray(1.0), new RandomVariableFromDoubleArray(0.0)).mult(indicator); <del> basisFunctions.add(basisFunction); <add> if(underlying.isDeterministic()) { <add> basisFunctions.add(underlying); <add> } <add> else { <add> int numberOfBins = 20; <add> double[] values = underlying.getRealizations(); <add> Arrays.sort(values); <add> for(int i = 0; i<numberOfBins; i++) { <add> double binLeft = values[(int)((double)i/(double)numberOfBins*values.length)]; <add> RandomVariable basisFunction = underlying.sub(binLeft).choose(new RandomVariableFromDoubleArray(1.0), new RandomVariableFromDoubleArray(0.0)).mult(indicator); <add> basisFunctions.add(basisFunction); <add> } <ide> } <ide> <ide> return basisFunctions;
JavaScript
mit
9fd7c4537deb0dc22e1b66bb2752e6dcc67da390
0
vseryakov/backendjs,vseryakov/backendjs,vseryakov/backendjs
// // Author: Vlad Seryakov [email protected] // Sep 2013 // var path = require('path'); var stream = require('stream'); var util = require('util'); var fs = require('fs'); var os = require('os'); var http = require('http'); var https = require('https'); var url = require('url'); var qs = require('qs'); var toobusy = require('toobusy'); var crypto = require('crypto'); var async = require('async'); var express = require('express'); var cookieParser = require('cookie-parser'); var session = require('cookie-session'); var serveStatic = require('serve-static'); var formidable = require('formidable'); var mime = require('mime'); var consolidate = require('consolidate'); var domain = require('domain'); var metrics = require(__dirname + '/metrics'); var core = require(__dirname + '/core'); var printf = require('printf'); var logger = require(__dirname + '/logger'); var backend = require(__dirname + '/build/Release/backend'); // HTTP API to the server from the clients, this module implements the basic HTTP(S) API functionality with some common features. The API module // incorporates the Express server which is exposed as api.app object, the master server spawns Web workers which perform actual operations and monitors // the worker processes if they die and restart them automatically. How many processes to spawn can be configured via `-server-max-workers` config parameter. var api = { // No authentication for these urls allow: ["^/$", "\\.html$", "\\.(ico|gif|png|jpg|svg)$", "\\.(ttf|eof|woff)$", "\\.(js|css)$", "^/public", "^/account/add$" ], // Allow only HTTPS requests alowSsl: null, // Refuse access to these urls deny: null, // Where images/file are kept imagesUrl: '', imagesS3: '', fileS3: '', tables: { // Authentication by login, only keeps id and secret to check the siganture bk_auth: { login: { primary: 1 }, // Account login id: {}, // Auto generated UUID secret: {}, // Account password type: {}, // Account type: admin, .... acl_deny: {}, // Deny access to matched url acl_allow: {}, // Only grant access if matched this regexp expires: { type: "bigint" }, // Deny access to the account if this value is before current date, milliseconds mtime: { type: "bigint", now: 1 } }, // Basic account information bk_account: { id: { primary: 1, pub: 1 }, login: {}, name: {}, alias: { pub: 1 }, status: {}, email: {}, phone: {}, website: {}, birthday: {}, gender: {}, address: {}, city: {}, state: {}, zipcode: {}, country: {}, latitude: { type: "real", noadd: 1 }, longitude: { type: "real", noadd: 1 }, geohash: { noadd: 1 }, location: { noadd: 1 }, ltime: { type: "bigint", noadd: 1 }, ctime: { type: "bigint" }, mtime: { type: "bigint", now: 1 } }, // Keep track of icons uploaded bk_icon: { id: { primary: 1, pub: 1 }, // Account id type: { primary: 1, pub: 1 }, // prefix:type acl_allow: {}, // Who can see it: all, auth, id:id... descr: {}, latitude: { type: "real" }, longitude: { type: "real" }, geohash: {}, mtime: { type: "bigint", now: 1 }}, // Last time added/updated // Locations for all accounts to support distance searches bk_location: { geohash: { primary: 1, semipub: 1 }, // geohash, minDistance defines the size id: { primary: 1, pub: 1 }, // my account id, part of the primary key for pagination latitude: { type: "real", semipub: 1 }, // for distance must be semipub or no distance and no coordinates longitude: { type: "real", semipub: 1 }, mtime: { type: "bigint", now: 1 }}, // All connections between accounts: like,dislike,friend... bk_connection: { id: { primary: 1 }, // my account_id type: { primary: 1 }, // type:connection_id state: {}, mtime: { type: "bigint", now: 1 }}, // References from other accounts, likes,dislikes... bk_reference: { id: { primary: 1 }, // connection_id type: { primary: 1 }, // type:account_id state: {}, mtime: { type: "bigint", now: 1 }}, // Messages between accounts bk_message: { id: { primary: 1 }, // my account_id mtime: { primary: 1 }, // mtime:sender, the current timestamp in milliseconds and the sender status: { index: 1 }, // status: R:mtime:sender or N:mtime:sender, where R - read, N - new sender: { index1: 1 }, // sender:mtime, reverse index by sender msg: { type: "text" }, // Text of the message icon: {}}, // Icon base64 or url // All accumulated counters for accounts bk_counter: { id: { primary: 1, pub: 1 }, // account id ping: { type: "counter", value: 0, pub: 1 }, // public column to ping the buddy like0: { type: "counter", value: 0, incr: 1 }, // who i liked like1: { type: "counter", value: 0 }, // reversed, who liked me dislike0: { type: "counter", value: 0, incr: 1 }, dislike1: { type: "counter", value: 0 }, follow0: { type: "counter", value: 0, incr: 1 }, follow1: { type: "counter", value: 0, }, invite0: { type: "counter", value: 0, incr: 1 }, invite1: { type: "counter", value: 0, }, view0: { type: "counter", value: 0, incr: 1 }, view1: { type: "counter", value: 0, }, msg_count: { type: "counter", value: 0 }, // total msgs received msg_read: { type: "counter", value: 0 }}, // total msgs read // Keep historic data about account activity bk_history: { id: { primary: 1 }, mtime: { type: "bigint", primary: 1, now: 1 }, type: {}, data: {} } }, // tables // Access handlers to grant access to the endpoint before checking for signature. // Authorization handlers after the account has been authenticated. // Post process, callbacks to be called after successfull API calls, takes as input the result. hooks: { access: [], auth: [], post: [] }, // Disabled API endpoints disable: [], disableSession: [], // Upload limit, bytes uploadLimit: 10*1024*1024, subscribeTimeout: 600000, subscribeInterval: 5000, // Collect body MIME types as binary blobs mimeBody: [], // Sessions sessionAge: 86400 * 14 * 1000, // Default busy latency 1 sec busyLatency: 1000, // Default endpoints endpoints: { "account": 'initAccountAPI', "connection": 'initConnectionAPI', "location": 'initLocationAPI', "history": 'initHistoryAPI', "counter": 'initCounterAPI', "icon": 'initIconAPI', "message": 'initMessageAPI', "data": 'initDataAPI' }, // Config parameters args: [{ name: "images-url", descr: "URL where images are stored, for cases of central image server(s)" }, { name: "images-s3", descr: "S3 bucket name where to store images" }, { name: "files-s3", descr: "S3 bucket name where to store files" }, { name: "busy-latency", type: "number", descr: "Max time in ms for a request to wait in the queue, if exceeds this value server returns too busy error" }, { name: "access-log", descr: "File for access logging" }, { name: "templating", descr: "Templating engne to use, see consolidate.js for supported engines, default is ejs" }, { name: "session-age", type: "int", descr: "Session age in milliseconds, for cookie based authentication" }, { name: "session-secret", descr: "Secret for session cookies, session support enabled only if it is not empty" }, { name: "data-endpoint-unsecure", type: "bool", descr: "Allow the Data API functions to retrieve and show all columns, not just public, this exposes the database to every authenticated call, use with caution" }, { name: "disable", type: "list", descr: "Disable default API by endpoint name: account, message, icon....." }, { name: "disable-session", type: "list", descr: "Disable access to API endpoints for Web sessions, must be signed properly" }, { name: "allow", array: 1, descr: "Regexp for URLs that dont need credentials, replace the whole access list" }, { name: "allow-path", array: 1, key: "allow", descr: "Add to the list of allowed URL paths without authentication" }, { name: "disallow-path", type: "callback", value: function(v) {this.allow.splice(this.allow.indexOf(v),1)}, descr: "Remove from the list of allowed URL paths that dont need authentication, most common case is to to remove ^/account/add$ to disable open registration" }, { name: "allow-ssl", array: 1, descr: "Add to the list of allowed URL paths using HTRPs only, plain HTTP requetss to these urls will be refused" }, { name: "mime-body", array: 1, descr: "Collect full request body in the req.body property for the given MIME type in addition to json and form posts, this is for custom body processing" }, { name: "deny", type: "regexp", descr: "Regexp for URLs that will be denied access, replaces the whole access list" }, { name: "deny-path", array: 1, key: "deny", descr: "Add to the list of URL paths to be denied without authentication" }, { name: "subscribe-timeout", type: "number", min: 60000, max: 3600000, descr: "Timeout for Long POLL subscribe listener, how long to wait for events, milliseconds" }, { name: "subscribe-interval", type: "number", min: 500, max: 3600000, descr: "Interval between delivering events to subscribed clients, milliseconds" }, { name: "upload-limit", type: "number", min: 1024*1024, max: 1024*1024*10, descr: "Max size for uploads, bytes" }], } module.exports = api; // Initialize API layer, this must be called before the `api` module can be used but it is called by the server module automatically so `api.init` is // rearely need to called directly, only for new server implementation or if using in the shell for testing. // // During the init sequence, this function calls `api.initMiddleware` and `api.initApplication` methods which by default are empty but can be redefined in the user aplications. // // The backend.js uses its own request parser that places query parameters into `req.query` or `req.body` depending on the method. // // For GET method, `req.query` contains all url-encoded parameters, for POST method `req.body` contains url-encoded parameters or parsed JSON payload or multipart payload. // // The simple way of dealing transparently with this is to check for method in the route handler like this: // // if (req.method == "POST") req.query = req.body; // // The reason not to do this by default is that this may not be the alwayse wanted case and distinguishing data coming in the request or in the body may be desirable, // also, this will needed only for Express handlers `.all`, when registering handler by method like `.get` or `.post` then the handler needs to deal with only either source of the request data. // api.init = function(callback) { var self = this; var db = core.context.db; // Performance statistics self.metrics = new metrics(); self.collectStatistics(); setInterval(function() { self.collectStatistics() }, 300000); // Setup toobusy timer to detect when our requests waiting in the queue for too long if (self.busyLatency) toobusy.maxLag(self.busyLatency); else toobusy.shutdown(); self.app = express(); // Wrap all calls in domain to catch exceptions self.app.use(function(req, res, next) { if (self.busyLatency && toobusy()) return res.send(503, "Server is unavailable"); var d = domain.create(); d.add(req); d.add(res); d.on('error', function(err) { req.next(err); }); d.run(next); }); // Allow cross site requests self.app.use(function(req, res, next) { res.header('Server', core.name + '/' + core.version); res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'b-signature'); next(); }); // Metrics starts early self.app.use(function(req, res, next) { self.metrics.Meter('rate').mark(); req.stopwatch = self.metrics.Timer('response').start(); self.metrics.Histogram('queue').update(self.metrics.Counter('count').inc()); var end = res.end; res.end = function(chunk, encoding) { res.end = end; res.end(chunk, encoding); req.stopwatch.end(); self.metrics.Counter('count').dec(); } next(); }); // Access log via file or syslog if (logger.syslog) { self.accesslog = new stream.Stream(); self.accesslog.writable = true; self.accesslog.write = function(data) { logger.printSyslog('info:local5', data); return true; } } else if (self.accessLog) { self.accesslog = fs.createWriteStream(path.join(core.path.log, self.accessLog), { flags: 'a' }); self.accesslog.on('error', function(err) { logger.error('accesslog:', err); self.accesslog = logger; }) } else { self.accesslog = logger; } self.app.use(function(req, res, next) { if (req._accessLog) return; req._accessLog = true; req._startTime = new Date; var end = res.end; res.end = function(chunk, encoding) { res.end = end; res.end(chunk, encoding); var now = new Date(); var line = (req.ip || (req.socket.socket ? req.socket.socket.remoteAddress : "-")) + " - " + (logger.syslog ? "-" : '[' + now.toUTCString() + ']') + " " + req.method + " " + (req.originalUrl || req.url) + " " + "HTTP/" + req.httpVersionMajor + '.' + req.httpVersionMinor + " " + res.statusCode + " " + (res.get("Content-Length") || '-') + " - " + (now - req._startTime) + " ms - " + (req.headers['user-agent'] || "-") + " " + (req.headers['version'] || "-") + " " + (req.account ? req.account.login : "-") + "\n"; self.accesslog.write(line); } next(); }); // Request parsers self.app.use(cookieParser()); self.app.use(function(req, res, next) { return self.checkQuery(req, res, next); }); self.app.use(function(req, res, next) { return self.checkBody(req, res, next); }); // Keep session in the cookies self.app.use(session({ key: 'bk_sid', secret: self.sessionSecret || core.name, cookie: { path: '/', httpOnly: false, maxAge: self.sessionAge || null } })); // Check the signature self.app.use(function(req, res, next) { return self.checkRequest(req, res, next); }); // Assign custom middleware just after the security handler self.initMiddleware.call(self); // Templating engine setup self.app.engine('html', consolidate[self.templating || 'ejs']); self.app.set('view engine', 'html'); // Use app specific views path if created even if it is empty self.app.set('views', fs.existsSync(core.path.web + "/views") ? core.path.web + "/view" : __dirname + '/views'); // Serve from default web location in the package or from application specific location self.app.use(serveStatic(core.path.web)); self.app.use(serveStatic(__dirname + "/web")); self.app.use(self.app.router); // Default error handler to show erros in the log self.app.use(function(err, req, res, next) { console.error(err.stack); self.sendReply(res, err); }); // Return images by prefix, id and possibly type self.app.all(/^\/image\/([a-z]+)\/([a-z0-9-]+)\/?([0-9])?$/, function(req, res) { self.getIcon(req, res, req.params[1], { prefix: req.params[0], type: req.params[2] }); }); // Convert allow/deny lists into single regexp if (this.allow) this.allow = new RegExp(this.allow.map(function(x) { return "(" + x + ")"}).join("|")); if (this.allowSsl) this.allowSsl = new RegExp(this.allowSsl.map(function(x) { return "(" + x + ")"}).join("|")); if (this.deny) this.deny = new RegExp(this.deny.map(function(x) { return "(" + x + ")"}).join("|")); // Managing accounts, basic functionality for (var p in self.endpoints) { if (self.disable.indexOf(p) == -1) self[self.endpoints[p]].call(this); } // Remove default API tables for disabled endpoints self.disable.forEach(function(x) { delete self.tables['bk_' + x] }); if (!self.tables.bk_account) delete self.tables.bk_auth; if (!self.tables.bk_connection) delete self.tables.bk_reference; // Disable access to endpoints if session exists, meaning Web app self.disableSession.forEach(function(x) { self.registerAuthCheck('', new RegExp(x), function(req, callback) { if (req.session && req.session['bk-signature']) return callback({ status: 401, message: "Not authorized" }); callback(); }); }); // Custom application logic self.initApplication.call(self, function(err) { // Setup all tables self.initTables(function(err) { var server = self.app.listen(core.port, core.bind, function(err) { if (err) return logger.error('api: init:', core.port, core.bind, err); this.timeout = core.timeout; // Start the SSL server as well if (core.ssl.key || core.ssl.pfx) { server = https.createServer(core.ssl, self.app).listen(core.ssl.port, core.ssl.bind, function(err) { if (err) logger.error('api: ssl failed:', err, core.ssl); else logger.log('api: ssl started', 'port:', core.ssl.port, 'bind:', core.ssl.bind, 'timeout:', core.timeout); this.timeout = core.timeout; if (callback) callback(err); }); } else if (callback) callback(err); }); }); }); } // This handler is called after the Express server has been setup and all default API endpoints initialized but the server // is not ready for incoming requests yet. This handler can setup additional API endpoints, add/modify table descriptions. api.initApplication = function(callback) { callback() }; // This handler is called during the Express server initialization just after the security middleware. // this.app refers to the Express instance. api.initMiddleware = function() {}; // Perform authorization of the incoming request for access and permissions api.checkRequest = function(req, res, callback) { var self = this; self.checkAccess(req, function(rc1) { // Status is given, return an error or proceed to the next module if (rc1) { if (rc1.status == 200) return callback(); if (rc1.status) self.sendStatus(res, rc1); return; } // Verify account access for signature self.checkSignature(req, function(rc2) { res.header("cache-control", "no-cache"); res.header("pragma", "no-cache"); // Determine what to do with the request even if the status is not success, a hook may deal with it differently, // the most obvous case is for a Web app to perform redirection on authentication failure self.checkAuthorization(req, rc2, function(rc3) { if (rc3 && rc3.status != 200) return self.sendStatus(res, rc3); callback(); }); }); }); } // Parse incoming query parameters api.checkQuery = function(req, res, next) { var self = this; if (req._body) return next(); req.body = req.body || {}; var type = (req.get("content-type") || "").split(";")[0]; switch (type) { case 'application/json': case 'application/x-www-form-urlencoded': req.setEncoding('utf8'); break; default: // Custom types to be collected if (self.mimeBody.indexOf(type) == -1) return next(); req.setEncoding('binary'); } req._body = true; var buf = '', size = 0; var sig = core.parseSignature(req); req.on('data', function(chunk) { size += chunk.length; if (size > self.uploadLimit) return req.destroy(); buf += chunk; }); req.on('end', function() { try { // Verify data checksum before parsing if (sig && sig.checksum && core.hash(buf) != sig.checksum) { var err = new Error("invalid data checksum"); err.status = 400; return next(err); } switch (type) { case 'application/json': req.body = JSON.parse(buf); break; case 'application/x-www-form-urlencoded': req.body = buf.length ? qs.parse(buf) : {}; // Keep the parametrs in the body so we can distinguish GET and POST requests but use them in signature verification sig.query = buf; break; default: req.body = buf; } next(); } catch (err) { err.status = 400; next(err); } }); } // Parse multipart forms for uploaded files api.checkBody = function(req, res, next) { var self = this; if (req._body) return next(); req.files = req.files || {}; if ('GET' == req.method || 'HEAD' == req.method) return next(); var type = (req.get("content-type") || "").split(";")[0]; if (type != 'multipart/form-data') return next(); req._body = true; var data = {}, files = {}, done; var form = new formidable.IncomingForm({ uploadDir: core.path.tmp, keepExtensions: true }); function ondata(name, val, data) { if (Array.isArray(data[name])) { data[name].push(val); } else if (data[name]) { data[name] = [data[name], val]; } else { data[name] = val; } } form.on('field', function(name, val) { ondata(name, val, data); }); form.on('file', function(name, val) { ondata(name, val, files); }); form.on('error', function(err) { next(err); done = true; }); form.on('end', function() { if (done) return; try { req.body = qs.parse(data); req.files = qs.parse(files); next(); } catch (err) { err.status = 400; next(err); } }); form.parse(req); } // Perform URL based access checks // Check access permissions, calls the callback with the following argument: // - nothing if checkSignature needs to be called // - an object with status: 200 to skip authorization and proceed with the next module // - an object with status: 0 means response has been sent, just stop // - an object with status other than 0 or 200 to return the status and stop request processing api.checkAccess = function(req, callback) { if (this.deny && req.path.match(this.deny)) return callback({ status: 401, message: "Access denied" }); if (this.allow && req.path.match(this.allow)) return callback({ status: 200, message: "" }); // Call custom access handler for the endpoint var hook = this.findHook('access', req.method, req.path); if (hook) return hook.callbacks.call(this, req, callback) callback(); } // Perform authorization checks after the account been checked for valid signature, this is called even if the signature verification failed // - req is Express request object // - status contains the signature verification status, an object wth status: and message: properties // - callback is a function(req, status) to be called with the resulted status where status must be an object with status and message properties as well api.checkAuthorization = function(req, status, callback) { var hook = this.findHook('auth', req.method, req.path); if (hook) return hook.callbacks.call(this, req, status, callback); // Pass the status back to the checkRequest callback(status); } // Verify request signature from the request object, uses properties: .host, .method, .url or .originalUrl, .headers api.checkSignature = function(req, callback) { // Make sure we will not crash on wrong object if (!req || !req.headers) req = { headers: {} }; if (!callback) callback = function(x) { return x; } // Extract all signature components from the request var sig = core.parseSignature(req); // Show request in the log on demand for diagnostics if (logger.level >= 1 || req.query._debug) logger.log('checkSignature:', sig, 'hdrs:', req.headers, 'session:', JSON.stringify(req.session)); // Sanity checks, required headers must be present and not empty if (!sig.method || !sig.host || !sig.expires || !sig.login || !sig.signature) { return callback({ status: 401, message: "Invalid request: " + (!sig.method ? "no method provided" : !sig.host ? "no host provided" : !sig.login ? "no login provided" : !sig.expires ? "no expiration provided" : !sig.signature ? "no signature provided" : "") }); } // Make sure it is not expired, it may be milliseconds or ISO date if (sig.expires <= Date.now()) { return callback({ status: 400, message: "Expired request" }); } // Verify if the access key is valid, they all are cached so a bad cache may result in rejects core.context.db.getCached("bk_auth", { login: sig.login }, function(err, account) { if (err) return callback({ status: 500, message: String(err) }); if (!account) return callback({ status: 404, message: "No account record found" }); // Account expiration time if (account.expires && account.expires < Date.now()) { return callback({ status: 404, message: "This account has expired" }); } // Verify ACL regex if specified, test the whole query string as it appears in the request query line if (account.acl_deny && sig.url.match(account.acl_deny)) { return callback({ status: 401, message: "Access denied" }); } if (account.acl_allow && !sig.url.match(account.acl_allow)) { return callback({ status: 401, message: "Not permitted" }); } // Deal with encrypted body, use our account secret to decrypt, this is for raw data requests // if it is JSON or query it needs to be reparsed in the application if (req.body && req.get("content-encoding") == "encrypted") { req.body = core.decrypt(account.secret, req.body); } // Verify the signature with account secret if (!core.checkSignature(sig, account)) { if (logger.level >= 1 || req.query._debug) logger.log('checkSignature:', 'failed', sig, account); return callback({ status: 401, message: "Not authenticated" }); } // Save account and signature in the request, it will be used later req.signature = sig; req.account = account; logger.debug(req.path, req.account, req.query); return callback({ status: 200, message: "Ok" }); }); } // Account management api.initAccountAPI = function() { var self = this; var db = core.context.db; this.app.all(/^\/account\/([a-z\/]+)$/, function(req, res, next) { if (req.method == "POST") req.query = req.body; var options = self.getOptions(req); switch (req.params[0]) { case "get": if (!req.query.id) { db.get("bk_account", { id: req.account.id }, options, function(err, rows) { if (err) return self.sendReply(res, err); if (!rows.length) return self.sendReply(res, 404); // Setup session cookies for automatic authentication without signing if (req.query._session) { switch (req.query._session) { case "1": var sig = core.signRequest(req.account.login, req.account.secret, "", req.headers.host, "", { sigversion: 2, expires: self.sessionAge }); req.session["bk-signature"] = sig["bk-signature"]; break; case "0": delete req.session["bk-signature"]; break; } } self.sendJSON(req, res, rows[0]); }); } else { db.list("bk_account", req.query.id, options, function(err, rows) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, rows); }); } break; case "add": self.addAccount(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; case "update": self.updateAccount(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; case "del": db.get("bk_account", { id: req.account.id }, options, function(err, rows) { if (err) return self.sendReply(res, err); if (!rows.length) return self.sendReply(res, 404); // Pass the whole account record downstream to the possible hooks and return it as well to our client for (var p in rows[0]) req.account[p] = rows[0][p]; self.deleteAccount(req.account, options, function(err) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, core.cloneObj(req.account, { secret: true })); }); }); break; case "subscribe": // Ignore not matching events, the whole string is checked if (req.query.match) req.query.match = new RegExp(req.query.match); // Returns opaque handle depending on the pub/sub system req.pubSock = core.ipcSubscribe(req.account.id, function(data) { if (typeof data != "string") data = JSON.stringify(data); if (req.query.match && !data.match(req.query.match)) return; logger.debug('subscribe:', req.account.id, this.socket, data, res.headersSent); if (res.headersSent) return (req.pubSock = core.ipcUnsubscribe(req.pubSock)); if (req.pubTimeout) clearTimeout(req.pubTimeout); // Concatenate all messages received within the interval if (!req.pubData) req.pubData = ""; else req.pubData += ","; req.pubData += data; req.pubTimeout = setTimeout(function() { if (!res.headersSent) res.type('application/json').send("[" + req.pubData + "]"); // Returns null and clears the reference req.pubSock = core.ipcUnsubscribe(req.pubSock, req.account.id); }, self.subscribeInterval); }); if (!req.pubSock) return self.sendReply(res, 500, "Service is not activated"); // Listen for timeout and ignore it, this way the socket will be alive forever until we close it res.on("timeout", function() { logger.debug('subscribe:', 'timeout', req.account.id, req.pubSock); setTimeout(function() { req.socket.destroy(); }, self.subscribeTimeout); }); req.on("close", function() { logger.debug('subscribe:', 'close', req.account.id, req.pubSock); req.pubSock = core.ipcUnsubscribe(req.pubSock, req.account.id); }); logger.debug('subscribe:', 'start', req.account.id, req.pubSock); break; case "select": db.select("bk_account", req.query, options, function(err, rows, info) { if (err) return self.sendReply(res, err); var next_token = info.next_token ? core.toBase64(info.next_token) : ""; self.sendJSON(req, res, { count: rows.length, data: rows, next_token: next_token }); }); break; case "put/secret": if (!req.query.secret) return self.sendReply(res, 400, "secret is required"); req.account.secret = req.query.secret; db.update("bk_auth", req.account, { cached: 1 }, function(err) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, {}); }); break; case "get/icon": if (!req.query.id) req.query.id = req.account.id; if (!req.query.type) req.query.type = '0'; self.getIcon(req, res, req.query.id, { prefix: 'account', type: req.query.type }); break; case "select/icon": if (!req.query.id) req.query.id = req.account.id; options.ops = { type: "begins_with" }; db.select("bk_icon", { id: req.query.id, type: "account:" }, options, function(err, rows) { if (err) return self.sendReply(res, err); // Filter out not allowed icons rows = rows.filter(function(x) { return self.checkIcon(req, req.query.id, x); }); rows.forEach(function(x) { self.formatIcon(req, req.query.id, x); }); self.sendJSON(req, res, rows); }); break; case "put/icon": case "del/icon": options.op = req.params[0].substr(0, 3); req.query.prefix = 'account'; if (!req.query.type) req.query.type = '0'; self.handleIcon(req, res, options); break; default: self.sendReply(res, 400, "Invalid command"); } }); } // Generic icon management api.initIconAPI = function() { var self = this; var db = core.context.db; this.app.all(/^\/icon\/([a-z]+)\/([a-z0-9\.\_\-]+)\/?([a-z0-9\.\_\-])?$/, function(req, res) { if (req.method == "POST") req.query = req.body; var options = self.getOptions(req); if (!req.query.id) req.query.id = req.account.id; req.query.prefix = req.params[1]; req.query.type = req.params[2] || ""; switch (req.params[0]) { case "get": self.getIcon(req, res, req.query.id, { prefix: req.query.prefix, type: req.query.type }); break; case "select": options.ops = { type: "begins_with" }; db.select("bk_icon", { id: req.query.id, type: req.query.prefix + ":" + req.query.type }, options, function(err, rows) { if (err) return self.sendReply(res, err); // Filter out not allowed icons rows = rows.filter(function(x) { return self.checkIcon(req, req.query.id, x); }); rows.forEach(function(x) { self.formatIcon(req, req.query.id, x); }); self.sendJSON(req, res, rows); }); break; case "del": case "put": options.op = req.params[0]; self.handleIcon(req, res, options); break; default: self.sendReply(res, 400, "Invalid command"); } }); } // Messaging management api.initMessageAPI = function() { var self = this; var db = core.context.db; function processRows(rows) { rows.forEach(function(row) { var mtime = row.mtime.split(":"); row.mtime = core.toNumber(mtime[0]); row.sender = mtime[1]; row.status = row.status[0]; if (row.icon) row.icon = '/message/image?sender=' + row.sender + '&mtime=' + row.mtime; }); return rows; } this.app.all(/^\/message\/([a-z\/]+)$/, function(req, res) { if (req.method == "POST") req.query = req.body; var options = self.getOptions(req); var now = Date.now(); switch (req.params[0]) { case "image": if (!req.query.sender || !req.query.mtime) return self.sendReply(res, 400, "sender and mtime are required"); self.sendIcon(req, res, req.account.id, { prefix: 'message', type: req.query.mtime + ":" + req.query.sender}); break; case "get": req.query.id = req.account.id; // Must be a string for DynamoDB at least if (req.query.mtime) { options.ops.mtime = "gt"; req.query.mtime = String(req.query.mtime); } // Using sender index, all msgs from the sender if (req.query.sender) { options.sort = "sender"; options.ops.sender = "begins_with"; options.select = Object.keys(db.getColumns("bk_message", options)); req.query.sender += ":"; } db.select("bk_message", req.query, options, function(err, rows, info) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, { count: rows.length, data: processRows(rows), next_token: info.next_token ? core.toBase64(info.next_token) : "" }); }); break; case "get/unread": req.query.id = req.account.id; req.query.status = "N:"; options.sort = "status"; options.ops.status = "begins_with"; db.select("bk_message", req.query, options, function(err, rows, info) { if (err) return self.sendReply(res, err); // Mark all existing as read if (core.toBool(req.query._read)) { var nread = 0; async.forEachSeries(rows, function(row, next) { db.update("bk_message", { id: req.account.id, mtime: row.mtime, status: 'R:' + row.mtime }, function(err) { if (!err) nread++; next(); }); }, function(err) { if (nread) db.incr("bk_counter", { id: req.account.id, msg_read: nread }, { cached: 1 }); self.sendJSON(req, res, { count: rows.length, data: processRows(rows), next_token: info.next_token ? core.toBase64(info.next_token) : "" }); }); } else { self.sendJSON(req, res, { count: rows.length, data: processRows(rows), next_token: info.next_token ? core.toBase64(info.next_token) : "" }); } }); break; case "read": if (!req.query.sender || !req.query.mtime) return self.sendReply(res, 400, "sender and mtime are required"); req.query.mtime += ":" + req.query.sender; db.update("bk_message", { id: req.account.id, mtime: req.query.mtime, status: "R:" + req.query.mtime }, function(err, rows) { if (!err) db.incr("bk_counter", { id: req.account.id, msg_read: 1 }, { cached: 1 }); self.sendReply(res, err); }); break; case "add": self.addMessage(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; case "del": self.delMessages(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; default: self.sendReply(res, 400, "Invalid command"); } }); } // History management api.initHistoryAPI = function() { var self = this; var db = core.context.db; this.app.all(/^\/history\/([a-z]+)$/, function(req, res) { if (req.method == "POST") req.query = req.body; var options = self.getOptions(req); switch (req.params[0]) { case "add": if (!req.query.type || !req.query.data) return self.sendReply(res, 400, "type and data are required"); self.sendReply(res); req.query.id = req.account.id; req.query.mtime = Date.now(); db.add("bk_history", req.query); break; case "get": options.ops = { mtime: 'gt' }; db.select("bk_history", { id: req.account.id, mtime: req.query.mtime || 0 }, options, function(err, rows) { res.json(rows); }); break; default: self.sendReply(res, 400, "Invalid command"); } }); } // Counters management api.initCounterAPI = function() { var self = this; var db = core.context.db; this.app.all(/^\/counter\/([a-z]+)$/, function(req, res) { if (req.method == "POST") req.query = req.body; var options = self.getOptions(req); var now = Date.now(); switch (req.params[0]) { case "put": req.query.id = req.account.id; case "incr": // Remove non public columns when updating other account if (req.query.id && req.query.id != req.account.id) { var obj = { id: req.query.id }; db.getPublicColumns("bk_counter").forEach(function(x) { if (req.query[x]) obj[x] = req.query[x]; }); } else { var obj = req.query; obj.id = req.account.id; } db[req.params[0]]("bk_counter", obj, { cached: 1 }, function(err, rows) { if (err) return self.sendReply(res, db.convertError("bk_counter", err)); // Update history log if (options.history) { db.add("bk_history", { id: req.account.id, type: req.path, data: core.cloneObj(obj, { mtime: 1 }) }); } self.sendJSON(req, res, rows); core.ipcPublish(req.query.id, { path: req.path, mtime: now, data: core.cloneObj(obj, { id: 1, mtime: 1 })}); }); break; case "get": var id = req.query.id || req.account.id; db.getCached("bk_counter", { id: id }, options, function(err, row) { res.json(row); }); break; default: self.sendReply(res, 400, "Invalid command"); } }); } // Connections management api.initConnectionAPI = function() { var self = this; var db = core.context.db; this.app.all(/^\/(connection|reference)\/([a-z]+)$/, function(req, res) { if (req.method == "POST") req.query = req.body; var options = self.getOptions(req); var now = Date.now(); switch (req.params[1]) { case "add": case "put": case "update": self.putConnections(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; case "del": self.delConnections(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; case "get": self.getConnections(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; default: self.sendReply(res, 400, "Invalid command"); } }); } // Geo locations management api.initLocationAPI = function() { var self = this; var db = core.context.db; this.app.all(/^\/location\/([a-z]+)$/, function(req, res) { if (req.method == "POST") req.query = req.body; var options = self.getOptions(req); switch (req.params[0]) { case "put": self.putLocations(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; case "get": self.getLocations(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; default: self.sendReply(res, 400, "Invalid command"); } }); } // API for internal provisioning, by default supports access to all tables api.initDataAPI = function() { var self = this; var db = core.context.db; // Return current statistics this.app.all("/data/stats", function(req, res) { res.json(self.getStatistics()); }); this.app.all(/^\/data\/cache\/(.+)$/, function(req, res) { switch (req.params[0]) { case "keys": core.ipcSend("keys", "", function(data) { res.send(data) }); break; case "clear": core.ipcSend("clear", ""); res.json(); break; case "get": core.ipcGetCache(req.query.name, function(data) { res.send(data) }); break; case "del": core.ipcDelCache(req.query.name); break; case "incr": core.ipcIncrCache(req.query.name, core.toNumber(req.query.value)); break; case "put": core.ipcPutCache(req.params[0].split("/").pop(), req.query); break; default: res.send(404); } }); // Load columns into the cache this.app.all("/data/columns", function(req, res) { db.cacheColumns({}, function() { res.json(db.getPool().dbcolumns); }); }); // Return table columns this.app.all(/^\/data\/columns\/([a-z_0-9]+)$/, function(req, res) { res.json(db.getColumns(req.params[0])); }); // Return table keys this.app.all(/^\/data\/keys\/([a-z_0-9]+)$/, function(req, res) { res.json(db.getKeys(req.params[0])); }); // Basic operations on a table this.app.all(/^\/data\/(select|search|list|get|add|put|update|del|incr|replace)\/([a-z_0-9]+)$/, function(req, res, info) { // Table must exist var dbcols = db.getColumns(req.params[1]); if (!dbcols) return self.sendReply(res, "Unknown table"); if (req.method == "POST") req.query = req.body; var options = self.getOptions(req); // Allow access to all columns and db pools if (self.dataEndpointUnsecure) { delete options.check_public; if (req.query._pool) options.pool = req.query._pool; } db[req.params[0]](req.params[1], req.query, options, function(err, rows) { if (err) return self.sendReply(res, err); switch (req.params[0]) { case "select": case "search": self.sendJSON(req, res, { count: rows.length, data: rows, next_token: info.next_token }); break; default: self.sendJSON(req, res, rows); } }); }); } // Called in the master process to create/upgrade API related tables api.initTables = function(callback) { core.context.db.initTables(this.tables, callback); } // Convert query options into database options, most options are the same as for `db.select` but prepended with underscore to // distinguish control parameters from query parameters. api.getOptions = function(req) { var options = { check_public: req.account ? req.account.id : null, ops: {} }; ["details", "consistent", "desc", "total"].forEach(function(x) { if (typeof req.query["_" + x] != "undefined") options[x] = core.toBool(req.query["_" + x]); }); if (req.query._select) options.select = req.query._select; if (req.query._count) options.count = core.toNumber(req.query._count, 0, 50); if (req.query._start) options.start = core.toJson(req.query._start); if (req.query._sort) options.sort = req.query._sort; if (req.query._page) options.page = core.toNumber(req.query._page, 0, 0, 0, 9999); if (req.query._keys) { options.keys = core.strSplit(req.query._keys); if (!options.keys.length) delete options.keys; } if (req.query._width) options.width = core.toNumber(req.query._width); if (req.query._height) options.height = core.toNumber(req.query._height); if (req.query._ext) options.ext = req.query._ext; if (req.query._ops) { if (!options.ops) options.ops = {}; var ops = core.strSplit(req.query._ops); for (var i = 0; i < ops.length -1; i+= 2) options.ops[ops[i]] = ops[i+1]; } return options; } // Add columns to account tables, makes sense in case of SQL database for extending supported properties and/or adding indexes // Used during initialization of the external modules which may add custom columns to the existing tables. api.describeTables = function(tables) { var self = this; for (var p in tables) { if (!self.tables[p]) self.tables[p] = {}; for (var c in tables[p]) { if (!self.tables[p][c]) self.tables[p][c] = {}; // Override columns for (var k in tables[p][c]) { self.tables[p][c][k] = tables[p][c][k]; } } } } // Clear request query properties specified in the table definition, if any columns for the table contains the property `name` nonempty, then // all request properties with the same name as this column name will be removed from the query. This for example is used for the `bk_account` // table to disable updating location related columns because speial location API maintains location data and updates the accounts table. api.clearQuery = function(req, options, table, name) { var cols = core.context.db.getColumns(table, options); for (var p in cols) { if (cols[p][name]) delete req.query[p]; } } // Find registered hook for given type and path api.findHook = function(type, method, path) { var routes = this.hooks[type]; if (!routes) return null; for (var i = 0; i < routes.length; ++i) { if ((!routes[i].method || routes[i].method == method) && routes[i].match(path)) { return routes[i]; } } return null; } api.addHook = function(type, method, path, callback) { this.hooks[type].push(new express.Route(method, path, callback)); } // Register a handler to check access for any given endpoint, it works the same way as the global accessCheck function and is called before // validating the signature or session cookies. // - method can be '' in such case all mathods will be matched // - path is a string or regexp of the request URL similr to registering Express routes // - callback is a function with the following parameters: function(req, cb) {}, to indicate an error condition pass an object // with the callback with status: and message: properties, status != 200 means error // // Example: // // api.registerAccessCheck('', 'account', function(req, cb) { cb({status:500,message:"access disabled"}) })) // // api.registerAccessCheck('POST', 'account/add', function(req, cb) { // if (!req.query.invitecode) return cb({ status: 400, message: "invitation code is required" }); // cb(); // }); api.registerAccessCheck = function(method, path, callback) { this.addHook('access', method, path, callback); } // Similar to `registerAccessCheck` but this callback will be called after the signature or session is verified. // The purpose of this hook is too check permissions of a valid user to resources or in case of error perform any other action // like redirection or returning something explaining what to do in case of failure. The callback for this call is different then in `checkAccess` hooks. // - method can be '' in such case all mathods will be matched // - path is a string or regexp of the request URL similr to registering Express routes // - callback is a function(req, status, cb) where status is an object { status:..., message: ..} passed from the checkSignature call, if status != 200 it means // an error condition, the callback must pass the same or modified status object in its own `cb` callback // // Example: // // api.registerAuthCheck('GET', '/account/get', function(req, status, cb) { // if (status.status != 200) status = { status: 302, url: '/error.html' }; // cb(status) // }); api.registerAuthCheck = function(method, path, callback) { this.addHook('auth', method, path, callback); } // Register a callback to be called after successfull API action, status 200 only. // The purpose is to perform some additional actions after the standard API completed or to customize the result // - method can be '' in such case all mathods will be matched // - path is a string or regexp of the request URL similar to registering Express routes // - callback is a function with the following parameters: function(req, res, rows) where rows is the result returned by the API handler, // the callback MUST return data back to the client or any other status code api.registerPostProcess = function(method, path, callback) { this.addHook('post', method, path, callback); } // Send result back with possibly executing post-process callback, this is used by all API handlers to allow custom post processing in teh apps api.sendJSON = function(req, res, rows) { var hook = this.findHook('post', req.method, req.path); if (hook) return hook.callbacks.call(this, req, res, rows); res.json(rows); } // Send formatted JSON reply to API client, if status is an instance of Error then error message with status 500 is sent back api.sendReply = function(res, status, msg) { if (status instanceof Error || status instanceof Object) msg = status.message, status = status.status || 500; if (!status) status = 200, msg = ""; return this.sendStatus(res, { status: status, message: String(msg || "") }); } // Return reply to the client using the options object, it cantains the following properties: // - status - defines the respone status code // - message - property to be sent as status line and in the body // - type - defines Content-Type header, the message will be sent in the body // - url - for redirects when status is 301 or 302 api.sendStatus = function(res, options) { if (!options) options = { status: 200, message: "" }; if (!options.status) options.status = 200; switch (options.status) { case 301: case 302: res.redirect(options.status, options.url); break; default: if (options.type) { res.type(type); res.send(options.status, options.message || ""); } else { res.json(options.status, options); } } return false; } // Send file back to the client, res is Express response object api.sendFile = function(req, res, file, redirect) { fs.exists(file, function(yes) { if (req.method == 'HEAD') return res.send(yes ? 200 : 404); if (yes) return res.sendfile(file); if (redirect) return res.redirect(redirect); res.send(404); }); } // Return all connections for the current account, this function is called by the `/connection/get` API call. api.getConnections = function(req, options, callback) { var self = this; var db = core.context.db; if (req.query.type) req.query.type += ":" + (req.query.id || ""); req.query.id = req.account.id; options.ops.type = "begins_with"; db.select("bk_" + req.params[0], req.query, options, function(err, rows, info) { if (err) return self.sendReply(res, err); var next_token = info.next_token ? core.toBase64(info.next_token) : ""; // Split type and reference id rows.forEach(function(row) { var d = row.type.split(":"); row.type = d[0]; row.id = d[1]; }); if (!core.toNumber(options.details)) return callback(null, { count: rows.length, data: rows, next_token: next_token }); // Get all account records for the id list db.list("bk_account", rows, { select: req.query._select, check_public: req.account.id }, function(err, rows) { if (err) return self.sendReply(res, err); callback(null, { count: rows.length, data: rows, next_token: next_token }); }); }); } // Create a connection between 2 accounts, this function is called by the `/connection/add` API call. api.putConnections = function(req, options, callback) { var self = this; var db = core.context.db; var now = Date.now(); var id = req.query.id, type = req.query.type; if (!id || !type) return callback({ status: 400, message: "id and type are required"}); if (id == req.account.id) return callback({ status: 400, message: "cannot connect to itself"}); // Override primary key properties, the rest of the properties will be added as is req.query.id = req.account.id; req.query.type = type + ":" + id; req.query.mtime = now; db[req.params[1]]("bk_connection", req.query, function(err) { if (err) return callback(db.convertError("bk_connection", err)); // Reverse reference to the same connection req.query.id = id; req.query.type = type + ":"+ req.account.id; db[req.params[1]]("bk_reference", req.query, function(err) { if (err) { db.del("bk_connection", { id: req.account.id, type: type + ":" + id }); return callback(err); } // We need to know if the other side is connected too, this will save one extra API call if (req.query._connected) { db.get("bk_connection", req.query, function(err, rows) { callback(null, { connected: rows.length }); }); } else { callback(null, {}); } core.ipcPublish(id, { path: req.path, mtime: now, type: type, id: req.account.id }); async.series([ function(next) { // Update history log if (!options.history) return next(); db.add("bk_history", { id: req.account.id, type: req.path, data: type + ":" + id }, next); }, function(next) { // Update accumulated counter if we support this column and do it automatically next(req.params[1] == 'update' ? new Error("stop") : null); }, function(next) { var col = db.getColumn("bk_counter", type + '0'); if (!col || !col.incr) return next(); db.incr("bk_counter", core.newObj('id', req.account.id, type + '0', 1), { cached: 1 }, function() { db.incr("bk_counter", core.newObj('id', id, type + '1', 1), { cached: 1 }, next); }); }]); }); }); } // Delete a connection, this function is called by the `/connection/del` API call api.delConnections = function(req, options, callback) { var self = this; var db = core.context.db; var now = Date.now(); var id = req.query.id; var type = req.query.type; if (id && type) { db.del("bk_connection", { id: req.account.id, type: type + ":" + id }, options, function(err) { if (err) return callback(err); db.del("bk_reference", { id: id, type: type + ":" + req.account.id }, options, function(err) { if (err) return callback(err); callback(null, {}); core.ipcPublish(id, { path: req.path, mtime: now, type: type, id: req.account.id }); // Update history log if (options.history) { db.add("bk_history", { id: req.account.id, type: req.path, data: type + ":" + id }); } // Update accumulated counter if we support this column and do it automatically var col = db.getColumn("bk_counter", req.query.type + "0"); if (col && col.incr) { db.incr("bk_counter", core.newObj('id', req.account.id, type + '0', -1), { cached: 1 }); db.incr("bk_counter", core.newObj('id', id, type + '1', -1), { cached: 1 }); } }); }); } else { var counters = {}; db.select("bk_connection", { id: req.account.id }, options, function(err, rows) { if (err) return next(err) async.forEachSeries(rows, function(row, next2) { var t = row.type.split(":"); if (id && t[1] != id) return next2(); if (type && t[0] != type) return next2(); // Keep track of all counters var name0 = t[0] + '0', name1 = t[0] + '1'; var col = db.getColumn("bk_counter", name0); if (col && col.incr) { if (!counters[req.account.id]) counters[req.account.id] = { id: req.account.id }; if (!counters[req.account.id][name0]) counters[req.account.id][name0] = 0; counters[req.account.id][name0]--; if (!counters[t[1]]) counters[t[1]] = { id: t[1] }; if (!counters[t[1]][name1]) counters[t[1]][name1] = 0; counters[t[1]][name1]--; } db.del("bk_reference", { id: t[1], type: t[0] + ":" + req.account.id }, options, function(err) { db.del("bk_connection", row, options, next2); }); }, function(err) { if (err) return callback(err); // Update history log if (options.history) { db.add("bk_history", { id: req.account.id, type: req.path, data: type + ":" + id }); } logger.log('COUNTERS:', counters) // Update all counters for each id async.forEachSeries(Object.keys(counters), function(id, next) { db.incr("bk_counter", counters[id], { cached: 1 }, next); }, function(err) { callback(err, {}); }); }); }); } } // Perform locations search, request comes from the Express server, callback will takes err and data to be returned back to the client, this function // is used in `/location/get` request. It can be used in the applications with customized input and output if neccesary for the application specific logic. // // Example // // # Request will look like: /recent/locations?latitude=34.1&longitude=-118.1&mtime=123456789 // this.app.all(/^\/recent\/locations$/, function(req, res) { // var options = self.getOptions(req); // options.keys = ["geohash","mtime"]; // options.ops = { mtime: 'gt' }; // options.details = true; // self.getLocations(req, options, function(err, data) { // self.sendJSON(req, res, data); // }); // }); // api.getLocations = function(req, options, callback) { var self = this; var db = core.context.db; // Perform location search based on hash key that covers the whole region for our configured max distance if (!req.query.latitude || !req.query.longitude) return callback({ status: 400, message: "latitude/longitude are required" }); // Pass all query parameters for custom filters if any, do not override existing options for (var p in req.query) { if (p[0] != "_" && !options[p]) options[p] = req.query[p]; } // Limit the distance within our configured range options.distance = core.toNumber(req.query.distance, 0, core.minDistance, core.minDistance, core.maxDistance); // Continue pagination using the search token var token = core.toJson(req.query._token); if (token && token.geohash) { if (token.latitude != options.latitude || token.longitude != options.longitude || token.distance != options.distance) return callback({ status: 400, message: "invalid token, latitude, longitude and distance must be the same" }); options = token; } // Rounded distance, not precise to keep from pin-pointing locations if (!options.round) options.round = core.minDistance; db.getLocations("bk_location", options, function(err, rows, info) { var next_token = info.more ? core.toBase64(info) : null; // Ignore current account, db still retrieves it but in the API we skip it rows = rows.filter(function(row) { return row.id != req.account.id }); // Return accounts with locations if (core.toNumber(options.details) && rows.length) { var list = {}, ids = []; rows = rows.map(function(row) { // Skip duplicates if (list[row.id]) return row; ids.push({ id: row.id }); list[row.id] = row; return row; }); db.list("bk_account", ids, { select: req.query._select, check_public: req.account.id }, function(err, rows) { if (err) return self.sendReply(res, err); // Merge locations and accounts rows.forEach(function(row) { var item = list[row.id]; for (var p in item) row[p] = item[p]; }); callback(null, { count: rows.length, data: rows, next_token: next_token }); }); } else { callback(null, { count: rows.length, data: rows, next_token: next_token }); } }); } // Save locstion coordinates for current account, this function is called by the `/location/put` API call api.putLocations = function(req, options, callback) { var self = this; var db = core.context.db; var now = Date.now(); var latitude = req.query.latitude, longitude = req.query.longitude; if (!latitude || !longitude) return callback({ status: 400, message: "latitude/longitude are required" }); // Get current location db.get("bk_account", { id: req.account.id }, function(err, rows) { if (err || !rows.length) return callback(err); // Keep old coordinates in the account record var old = rows[0]; // Skip if within minimal distance var distance = backend.geoDistance(old.latitude, old.longitude, latitude, longitude); if (distance < core.minDistance) return callback({ status: 305, message: "ignored, min distance: " + core.minDistance}); // Build new location record var geo = core.geoHash(latitude, longitude); req.query.id = req.account.id; req.query.geohash = geo.geohash; var cols = db.getColumns("bk_location", options); // Update all account columns in the location, they are very tightly connected and custom filters can // be used for filtering locations based on other account properties like gender. for (var p in cols) if (old[p] && !req.query[p]) req.query[p] = old[p]; var obj = { id: req.account.id, geohash: geo.geohash, latitude: latitude, longitude: longitude, ltime: now, location: req.query.location }; db.update("bk_account", obj, function(err) { if (err) return callback(err); db.put("bk_location", req.query, function(err) { if (err) return callback(err); // Return new location record with the old coordinates req.query.old = old; callback(null, req.query); // Delete the old location, no need to wait even if fails we still have a new one recorded db.del("bk_location", old); }); // Update history log if (options.history) { db.add("bk_history", { id: req.account.id, type: req.path, data: geo.hash + ":" + latitude + ":" + longitude }); } }); }); } // Process icon request, put or del, update table and deal with the actual image data, always overwrite the icon file api.handleIcon = function(req, res, options) { var self = this; var db = core.context.db; var op = options.op || "put"; if (!req.query.type) req.query.type = ""; req.query.id = req.account.id; req.query.type = req.query.prefix + ":" + req.query.type; if (req.query.latitude && req.query.longitude) req.query.geohash = core.geoHash(req.query.latitude, req.query.longitude); db[op]("bk_icon", req.query, function(err, rows) { if (err) return self.sendReply(res, err); options.force = true; options.prefix = req.query.prefix; options.type = req.query.type; self[op + 'Icon'](req, req.account.id, options, function(err, icon) { if ((err || !icon) && op == "put") db.del('bk_icon', obj); self.sendReply(res, err); }); }); } // Return formatted icon URL for the given account api.formatIcon = function(req, id, row) { var type = row.type.split(":"); row.prefix = type[0]; row.type = type[1]; // Provide public url if allowed if (row.allow && row.allow == "all" && this.allow && ("/image/" + row.prefix + "/").match(this.allow)) { row.url = '/image/' + row.prefix + '/' + req.query.id + '/' + row.type; } else { if (row.prefix == "account") { row.url = '/account/get/icon?type=' + row.type; } else { row.url = '/icon/get/' + row.prefix + "/" + row.type + "?"; } if (id != req.account.id) row.url += "&id=" + id; } } // Return icon to the client, checks the bk_icon table for existence and permissions api.getIcon = function(req, res, id, options) { var self = this; var db = core.context.db; db.get("bk_icon", { id: id, type: options.prefix + ":" + options.type }, options, function(err, rows) { if (err) return self.sendReply(res, err); if (!rows.length) return self.sendReply(res, 404, "Not found"); if (!self.checkIcon(req, id, rows[0])) return self.sendReply(res, 401, "Not allowed"); self.sendIcon(req, res, id, options); }); } // Send an icon to the client, only handles files api.sendIcon = function(req, res, id, options) { var self = this; var aws = core.context.aws; var icon = core.iconPath(id, options); logger.log('sendIcon:', icon, id, options) if (self.imagesS3) { aws.queryS3(self.imagesS3, icon, options, function(err, params) { if (err) return self.sendReply(res, err); res.type("image/" + (options.ext || "jpeg")); res.send(200, params.data); }); } else { self.sendFile(req, res, icon); } } // Verify icon permissions for given account id, returns true if allowed api.checkIcon = function(req, id, row) { var acl = row.acl_allow || ""; if (acl == "all") return true; if (acl == "auth" && req.account) return true; if (acl.split(",").filter(function(x) { return x == id }).length) return true; return id == req.account.id; } // Store an icon for account, .type defines icon prefix api.putIcon = function(req, id, options, callback) { var self = this; // Multipart upload can provide more than one icon, file name can be accompanied by file_type property to define type for each icon, for // only one uploaded file req.query.type still will be used var nfiles = req.files ? Object.keys(req.files).length : 0; if (nfiles) { var outfile = null, type = req.query.type; async.forEachSeries(Object.keys(req.files), function(f, next) { var opts = core.extendObj(options, 'type', req.body[f + '_type'] || (type && nfiles == 1 ? type : "")); self.storeIcon(req.files[f].path, id, opts, function(err, ofile) { outfile = ofile; next(err); }); }, function(err) { callback(err, outfile); }); } else // JSON object submitted with .icon property if (typeof req.body == "object" && req.body.icon) { var icon = new Buffer(req.body.icon, "base64"); this.storeIcon(icon, id, options, callback); } else // Query base64 encoded parameter if (req.query.icon) { var icon = new Buffer(req.query.icon, "base64"); this.storeIcon(icon, id, options, callback); } else { return callback(); } } // Place the icon data to the destination api.storeIcon = function(icon, id, options, callback) { if (this.imagesS3) { this.putIconS3(icon, id, options, callback); } else { core.putIcon(icon, id, options, callback); } } // Delete an icon for account, .type defines icon prefix api.delIcon = function(req, id, options, callback) { if (typeof options == "function") callback = options, options = null; if (!options) options = {}; var icon = core.iconPath(id, options); if (this.imagesS3) { var aws = core.context.aws; aws.queryS3(this.imagesS3, icon, { method: "DELETE" }, function(err) { logger.edebug(err, 'delIcon:', id, options); if (callback) callback(); }); } else { fs.unlink(icon, function(err) { logger.edebug(err, 'delIcon:', id, options); if (callback) callback(); }); } } // Same as putIcon but store the icon in the S3 bucket, icon can be a file or a buffer with image data api.putIconS3 = function(file, id, options, callback) { var self = this; if (typeof options == "function") callback = options, options = null; if (!options) options = {}; var aws = core.context.aws; var icon = core.iconPath(id, options); core.scaleIcon(file, options, function(err, data) { if (err) return callback ? callback(err) : null; var headers = { 'content-type': 'image/' + (options.ext || "jpeg") }; aws.queryS3(self.imagesS3, icon, { method: "PUT", postdata: data, headers: headers }, function(err) { if (callback) callback(err, icon); }); }); } // Upload file and store in the filesystem or S3, try to find the file in multipart form, in the body or query by the given name // - name is the name property to look for in the multipart body or in the request body or query // - callback will be called with err and actual filename saved // Output file name is built according to the following options properties: // - name - defines the basename for the file, no extention, if not given same name as property will be used // - ext - what file extention to use, appended to name, if no ext is given the extension from the uploaded file will be used or no extention if could not determine one. // - extkeep - tells always to keep actual extention from the uploaded file api.putFile = function(req, name, options, callback) { var self = this; if (typeof options == "function") callback = options, options = null; if (!options) options = {}; var outfile = (options.name || name) + (options.ext || ""); if (req.files && req.files[name]) { if (!options.ext || options.extkeep) outfile += path.extname(req.files[name].name || req.files[name].path); self.storeFile(req.files[name].path, outfile, options, callback); } else // JSON object submitted with .name property with the icon contents if (typeof req.body == "object" && req.body[name]) { var data = new Buffer(req.body[name], "base64"); self.storeFile(data, outfile, options, callback); } else // Query base64 encoded parameter if (req.query[name]) { var data = new Buffer(req.query[name], "base64"); self.storeFile(data, outfile, options, callback); } else { return callback(); } } // Place the uploaded tmpfile to the destination pointed by outfile api.storeFile = function(tmpfile, outfile, options, callback) { if (typeof options == "function") callback = options, options = null; if (!options) options = {}; if (this.fileS3) { var headers = { 'content-type': mime.lookup(outfile) }; var ops = { method: "PUT", headers: headers } opts[Buffer.isBuffer(tmfile) ? 'postdata' : 'postfile'] = tmpfile; aws.queryS3(this.filesS3, outfile, opts, function(err) { if (callback) callback(err, outfile); }); } else { if (Buffer.isBuffer(tmpfile)) { fs.writeFile(path.join(core.path.files, outfile), tmpfile, function(err) { if (err) logger.error('storeFile:', outfile, err); if (callback) callback(err, outfile); }); } else { core.moveFile(tmpfile, path.join(core.path.files, outfile), true, function(err) { if (err) logger.error('storeFile:', outfile, err); if (callback) callback(err, outfile); }); } } } // Delete file by name api.deleteFile = function(file, options, callback) { if (typeof options == "function") callback = options, options = null; if (!options) options = {}; if (this.fileS3) { aws.queryS3(this.filesS3, file, { method: "DELETE" }, function(err) { if (callback) callback(err, outfile); }); } else { fs.unlink(path.join(core.path.files, file), function(err) { if (err) logger.error('deleteFile:', file, err); if (callback) callback(err, outfile); }) } } // Add new message, used in /message/add API call api.addMessage = function(req, options, callback) { var self = this; var db = core.context.db; var now = Date.now(); if (!req.query.id) return callback({ status: 400, message: "receiver id is required" }); if (!req.query.msg && !req.query.icon) return callback({ status: 400, message: "msg or icon is required" }); req.query.mtime = now + ":" + req.account.id; req.query.sender = req.account.id + ":" + now; req.query.status = 'N:' + req.query.mtime; self.putIcon(req, req.query.id, { prefix: 'message', type: req.query.mtime }, function(err, icon) { if (err) return callback(err); req.query.icon = icon ? 1 : "0"; db.add("bk_message", req.query, {}, function(err, rows) { if (err) return callback(db.convertError("bk_message", err)); callback(null, { id: req.query.id, mtime: now, sender: req.account.id, icon: req.query.icon }); core.ipcPublish(req.query.id, { path: req.path, mtime: now, sender: req.query.sender }); db.incr("bk_counter", { id: req.account.id, msg_count: 1 }, { cached: 1 }); // Update history log if (options.history) { db.add("bk_history", { id: req.account.id, type: req.path, mtime: now, data: req.query.id }); } }); }); } // Delete a message or all messages for the given account from the given sender, used in /messge/del` API call api.delMessages = function(req, options, callback) { var self = this; var db = core.context.db; if (!req.query.sender) return callback({ status: 400, message: "sender is required" }); if (req.query.mtime) { req.query.mtime += ":" + req.query.sender; db.del("bk_message", { id: req.account.id, mtime: req.query.mtime }, function(err, rows) { if (err) return callback(err); db.incr("bk_counter", { id: req.account.id, msg_count: -1 }, { cached: 1 }); callback(null, {}); }); } else { options.sort = "sender"; options.ops = { sender: "begins_with" }; db.select("bk_message", { id: req.account.id, sender: req.query.sender + ":" }, options, function(err, rows) { if (err) return callback(err); async.forEachSeries(rows, function(row, next) { var sender = row.sender.split(":"); row.mtime = sender[1] + ":" + sender[0]; db.del("bk_message", row, options, next); }, function(err) { if (!err && rows.count) { db.incr("bk_counter", { id: req.account.id, msg_count: -rows.count }, { cached: 1 }); } callback(null, {}); }); }); } } // Register new account, used in /account/add API call api.addAccount = function(req, options, callback) { var self = this; var db = core.context.db; // Verify required fields if (!req.query.secret) return callback({ status: 400, message: "secret is required"}); if (!req.query.name) return callback({ status: 400, message: "name is required"}); if (!req.query.login) return callback({ status: 400, message: "login is required"}); if (!req.query.alias) req.query.alias = req.query.name; req.query.id = core.uuid(); req.query.mtime = req.query.ctime = Date.now(); // Add new auth record with only columns we support, NoSQL db can add any columns on the fly and we want to keep auth table very small var auth = { id: req.query.id, login: req.query.login, secret: req.query.secret }; // Only admin can add accounts with the type if (req.account && req.account.type == "admin" && req.query.type) auth.type = req.query.type; db.add("bk_auth", auth, function(err) { if (err) return callback(db.convertError("bk_auth", err)); // Skip location related properties self.clearQuery(req, options, "bk_account", "noadd"); db.add("bk_account", req.query, function(err) { if (err) { db.del("bk_auth", auth); return callback(db.convertError("bk_account", err)); } db.processRows(null, "bk_account", req.query, options); // Link account record for other middleware req.account = req.query; // Some dbs require the record to exist, just make one with default values db.put("bk_counter", { id: req.query.id, like0: 0 }); callback(null, req.query); }); }); } // Update existing account, used in /account/update API call api.updateAccount = function(req, options, callback) { var self = this; var db = core.context.db; req.query.mtime = Date.now(); req.query.id = req.account.id; // Skip location related properties self.clearQuery(req, options, "bk_account", "noadd"); db.update("bk_account", req.query, callback); } // Delete account specified in the obj, this must be merged object from bk_auth and bk_account tables. // Return err if something wrong occured in the callback. api.deleteAccount = function(obj, options, callback) { var self = this; if (!obj || !obj.id || !obj.login) return callback ? callback(new Error("id, login must be specified")) : null; if (typeof options == "function") callback = options, options = {}; var db = core.context.db; options = db.getOptions("bk_account", options); db.get("bk_account", { id: obj.id }, options, function(err, rows) { if (err || !rows.length) if (err) return callback ? callback(err) : null; async.series([ function(next) { options.cached = true db.del("bk_auth", { login: obj.login }, options, function(err) { options.cached = false; next(err); }); }, function(next) { db.del("bk_account", { id: obj.id }, options, function() { next() }); }, function(next) { db.del("bk_counter", { id: obj.id }, options, function() { next() }); }, function(next) { db.select("bk_connection", { id: obj.id }, options, function(err, rows) { if (err) return next(err) async.forEachSeries(rows, function(row, next2) { var type = row.type.split(":"); db.del("bk_reference", { id: type[1], type: type[0] + ":" + obj.id }, options, function(err) { db.del("bk_connection", row, options, next2); }); }, next); }); }, function(next) { db.delAll("bk_message", { id: obj.id }, options, function() { next() }); }, function(next) { db.delAll("bk_icon", { id: obj.id }, options, function() { next() }); }, function(next) { var geo = core.geoHash(rows[0].latitude, rows[0].longitude); db.del("bk_location", { geohash: geo.geohash, id: obj.id }, options, next); }], callback); }); } // Returns an object with collected db and api statstics and metrics api.getStatistics = function() { return { toobusy: toobusy.lag(), pool: core.context.db.getPool().metrics, api: this.metrics }; } // Metrics about the process api.collectStatistics = function() { var avg = os.loadavg(); var mem = process.memoryUsage(); this.metrics.Histogram('rss').update(mem.rss); this.metrics.Histogram('heap').update(mem.heapUsed); this.metrics.Histogram('loadavg').update(avg[2]); this.metrics.Histogram('freemem').update(os.freemem()); }
api.js
// // Author: Vlad Seryakov [email protected] // Sep 2013 // var path = require('path'); var stream = require('stream'); var util = require('util'); var fs = require('fs'); var os = require('os'); var http = require('http'); var https = require('https'); var url = require('url'); var qs = require('qs'); var toobusy = require('toobusy'); var crypto = require('crypto'); var async = require('async'); var express = require('express'); var cookieParser = require('cookie-parser'); var session = require('cookie-session'); var serveStatic = require('serve-static'); var formidable = require('formidable'); var mime = require('mime'); var consolidate = require('consolidate'); var domain = require('domain'); var metrics = require(__dirname + '/metrics'); var core = require(__dirname + '/core'); var printf = require('printf'); var logger = require(__dirname + '/logger'); var backend = require(__dirname + '/build/Release/backend'); // HTTP API to the server from the clients, this module implements the basic HTTP(S) API functionality with some common features. The API module // incorporates the Express server which is exposed as api.app object, the master server spawns Web workers which perform actual operations and monitors // the worker processes if they die and restart them automatically. How many processes to spawn can be configured via `-server-max-workers` config parameter. var api = { // No authentication for these urls allow: ["^/$", "\\.html$", "\\.(ico|gif|png|jpg|svg)$", "\\.(ttf|eof|woff)$", "\\.(js|css)$", "^/public", "^/account/add$" ], // Allow only HTTPS requests alowSsl: null, // Refuse access to these urls deny: null, // Where images/file are kept imagesUrl: '', imagesS3: '', fileS3: '', tables: { // Authentication by login, only keeps id and secret to check the siganture bk_auth: { login: { primary: 1 }, // Account login id: {}, // Auto generated UUID secret: {}, // Account password type: {}, // Account type: admin, .... acl_deny: {}, // Deny access to matched url acl_allow: {}, // Only grant access if matched this regexp expires: { type: "bigint" }, // Deny access to the account if this value is before current date, milliseconds mtime: { type: "bigint", now: 1 } }, // Basic account information bk_account: { id: { primary: 1, pub: 1 }, login: {}, name: {}, alias: { pub: 1 }, status: {}, email: {}, phone: {}, website: {}, birthday: {}, gender: {}, address: {}, city: {}, state: {}, zipcode: {}, country: {}, latitude: { type: "real", noadd: 1 }, longitude: { type: "real", noadd: 1 }, geohash: { noadd: 1 }, location: { noadd: 1 }, ltime: { type: "bigint", noadd: 1 }, ctime: { type: "bigint" }, mtime: { type: "bigint", now: 1 } }, // Keep track of icons uploaded bk_icon: { id: { primary: 1, pub: 1 }, // Account id type: { primary: 1, pub: 1 }, // prefix:type acl_allow: {}, // Who can see it: all, auth, id:id... descr: {}, latitude: { type: "real" }, longitude: { type: "real" }, geohash: {}, mtime: { type: "bigint", now: 1 }}, // Last time added/updated // Locations for all accounts to support distance searches bk_location: { geohash: { primary: 1, semipub: 1 }, // geohash, minDistance defines the size id: { primary: 1, pub: 1 }, // my account id, part of the primary key for pagination latitude: { type: "real", semipub: 1 }, // for distance must be semipub or no distance and no coordinates longitude: { type: "real", semipub: 1 }, mtime: { type: "bigint", now: 1 }}, // All connections between accounts: like,dislike,friend... bk_connection: { id: { primary: 1 }, // my account_id type: { primary: 1 }, // type:connection_id state: {}, mtime: { type: "bigint", now: 1 }}, // References from other accounts, likes,dislikes... bk_reference: { id: { primary: 1 }, // connection_id type: { primary: 1 }, // type:account_id state: {}, mtime: { type: "bigint", now: 1 }}, // Messages between accounts bk_message: { id: { primary: 1 }, // my account_id mtime: { primary: 1 }, // mtime:sender, the current timestamp in milliseconds and the sender status: { index: 1 }, // status: R:mtime:sender or N:mtime:sender, where R - read, N - new sender: { index1: 1 }, // sender:mtime, reverse index by sender msg: { type: "text" }, // Text of the message icon: {}}, // Icon base64 or url // All accumulated counters for accounts bk_counter: { id: { primary: 1, pub: 1 }, // account id ping: { type: "counter", value: 0, pub: 1 }, // public column to ping the buddy like0: { type: "counter", value: 0, incr: 1 }, // who i liked like1: { type: "counter", value: 0 }, // reversed, who liked me dislike0: { type: "counter", value: 0, incr: 1 }, dislike1: { type: "counter", value: 0 }, follow0: { type: "counter", value: 0, incr: 1 }, follow1: { type: "counter", value: 0, }, invite0: { type: "counter", value: 0, incr: 1 }, invite1: { type: "counter", value: 0, }, view0: { type: "counter", value: 0, incr: 1 }, view1: { type: "counter", value: 0, }, msg_count: { type: "counter", value: 0 }, // total msgs received msg_read: { type: "counter", value: 0 }}, // total msgs read // Keep historic data about account activity bk_history: { id: { primary: 1 }, mtime: { type: "bigint", primary: 1, now: 1 }, type: {}, data: {} } }, // tables // Access handlers to grant access to the endpoint before checking for signature. // Authorization handlers after the account has been authenticated. // Post process, callbacks to be called after successfull API calls, takes as input the result. hooks: { access: [], auth: [], post: [] }, // Disabled API endpoints disable: [], disableSession: [], // Upload limit, bytes uploadLimit: 10*1024*1024, subscribeTimeout: 600000, subscribeInterval: 5000, // Collect body MIME types as binary blobs mimeBody: [], // Sessions sessionAge: 86400 * 14 * 1000, // Default busy latency 1 sec busyLatency: 1000, // Default endpoints endpoints: { "account": 'initAccountAPI', "connection": 'initConnectionAPI', "location": 'initLocationAPI', "history": 'initHistoryAPI', "counter": 'initCounterAPI', "icon": 'initIconAPI', "message": 'initMessageAPI', "data": 'initDataAPI' }, // Config parameters args: [{ name: "images-url", descr: "URL where images are stored, for cases of central image server(s)" }, { name: "images-s3", descr: "S3 bucket name where to store images" }, { name: "files-s3", descr: "S3 bucket name where to store files" }, { name: "busy-latency", type: "number", descr: "Max time in ms for a request to wait in the queue, if exceeds this value server returns too busy error" }, { name: "access-log", descr: "File for access logging" }, { name: "templating", descr: "Templating engne to use, see consolidate.js for supported engines, default is ejs" }, { name: "session-age", type: "int", descr: "Session age in milliseconds, for cookie based authentication" }, { name: "session-secret", descr: "Secret for session cookies, session support enabled only if it is not empty" }, { name: "data-endpoint-unsecure", type: "bool", descr: "Allow the Data API functions to retrieve and show all columns, not just public, this exposes the database to every authenticated call, use with caution" }, { name: "disable", type: "list", descr: "Disable default API by endpoint name: account, message, icon....." }, { name: "disable-session", type: "list", descr: "Disable access to API endpoints for Web sessions, must be signed properly" }, { name: "allow", array: 1, descr: "Regexp for URLs that dont need credentials, replace the whole access list" }, { name: "allow-path", array: 1, key: "allow", descr: "Add to the list of allowed URL paths without authentication" }, { name: "disallow-path", type: "callback", value: function(v) {this.allow.splice(this.allow.indexOf(v),1)}, descr: "Remove from the list of allowed URL paths that dont need authentication, most common case is to to remove ^/account/add$ to disable open registration" }, { name: "allow-ssl", array: 1, descr: "Add to the list of allowed URL paths using HTRPs only, plain HTTP requetss to these urls will be refused" }, { name: "mime-body", array: 1, descr: "Collect full request body in the req.body property for the given MIME type in addition to json and form posts, this is for custom body processing" }, { name: "deny", type: "regexp", descr: "Regexp for URLs that will be denied access, replaces the whole access list" }, { name: "deny-path", array: 1, key: "deny", descr: "Add to the list of URL paths to be denied without authentication" }, { name: "subscribe-timeout", type: "number", min: 60000, max: 3600000, descr: "Timeout for Long POLL subscribe listener, how long to wait for events, milliseconds" }, { name: "subscribe-interval", type: "number", min: 500, max: 3600000, descr: "Interval between delivering events to subscribed clients, milliseconds" }, { name: "upload-limit", type: "number", min: 1024*1024, max: 1024*1024*10, descr: "Max size for uploads, bytes" }], } module.exports = api; // Initialize API layer, this must be called before the `api` module can be used but it is called by the server module automatically so `api.init` is // rearely need to called directly, only for new server implementation or if using in the shell for testing. // // During the init sequence, this function calls `api.initMiddleware` and `api.initApplication` methods which by default are empty but can be redefined in the user aplications. // // The backend.js uses its own request parser that places query parameters into `req.query` or `req.body` depending on the method. // // For GET method, `req.query` contains all url-encoded parameters, for POST method `req.body` contains url-encoded parameters or parsed JSON payload or multipart payload. // // The simple way of dealing transparently with this is to check for method in the route handler like this: // // if (req.method == "POST") req.query = req.body; // // The reason not to do this by default is that this may not be the alwayse wanted case and distinguishing data coming in the request or in the body may be desirable, // also, this will needed only for Express handlers `.all`, when registering handler by method like `.get` or `.post` then the handler needs to deal with only either source of the request data. // api.init = function(callback) { var self = this; var db = core.context.db; // Performance statistics self.metrics = new metrics(); self.collectStatistics(); setInterval(function() { self.collectStatistics() }, 300000); // Setup toobusy timer to detect when our requests waiting in the queue for too long if (self.busyLatency) toobusy.maxLag(self.busyLatency); else toobusy.shutdown(); self.app = express(); // Wrap all calls in domain to catch exceptions self.app.use(function(req, res, next) { if (self.busyLatency && toobusy()) return res.send(503, "Server is unavailable"); var d = domain.create(); d.add(req); d.add(res); d.on('error', function(err) { req.next(err); }); d.run(next); }); // Allow cross site requests self.app.use(function(req, res, next) { res.header('Server', core.name + '/' + core.version); res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'b-signature'); next(); }); // Metrics starts early self.app.use(function(req, res, next) { self.metrics.Meter('rate').mark(); req.stopwatch = self.metrics.Timer('response').start(); self.metrics.Histogram('queue').update(self.metrics.Counter('count').inc()); var end = res.end; res.end = function(chunk, encoding) { res.end = end; res.end(chunk, encoding); req.stopwatch.end(); self.metrics.Counter('count').dec(); } next(); }); // Access log via file or syslog if (logger.syslog) { self.accesslog = new stream.Stream(); self.accesslog.writable = true; self.accesslog.write = function(data) { logger.printSyslog('info:local5', data); return true; } } else if (self.accessLog) { self.accesslog = fs.createWriteStream(path.join(core.path.log, self.accessLog), { flags: 'a' }); self.accesslog.on('error', function(err) { logger.error('accesslog:', err); self.accesslog = logger; }) } else { self.accesslog = logger; } self.app.use(function(req, res, next) { if (req._accessLog) return; req._accessLog = true; req._startTime = new Date; var end = res.end; res.end = function(chunk, encoding) { res.end = end; res.end(chunk, encoding); var now = new Date(); var line = (req.ip || (req.socket.socket ? req.socket.socket.remoteAddress : "-")) + " - " + (logger.syslog ? "-" : '[' + now.toUTCString() + ']') + " " + req.method + " " + (req.originalUrl || req.url) + " " + "HTTP/" + req.httpVersionMajor + '.' + req.httpVersionMinor + " " + res.statusCode + " " + (res.get("Content-Length") || '-') + " - " + (now - req._startTime) + " ms - " + (req.headers['user-agent'] || "-") + " " + (req.headers['version'] || "-") + " " + (req.account ? req.account.login : "-") + "\n"; self.accesslog.write(line); } next(); }); // Request parsers self.app.use(cookieParser()); self.app.use(function(req, res, next) { return self.checkQuery(req, res, next); }); self.app.use(function(req, res, next) { return self.checkBody(req, res, next); }); // Keep session in the cookies self.app.use(session({ key: 'bk_sid', secret: self.sessionSecret || core.name, cookie: { path: '/', httpOnly: false, maxAge: self.sessionAge || null } })); // Check the signature self.app.use(function(req, res, next) { return self.checkRequest(req, res, next); }); // Assign custom middleware just after the security handler self.initMiddleware.call(self); // Templating engine setup self.app.engine('html', consolidate[self.templating || 'ejs']); self.app.set('view engine', 'html'); // Use app specific views path if created even if it is empty self.app.set('views', fs.existsSync(core.path.web + "/views") ? core.path.web + "/view" : __dirname + '/views'); // Serve from default web location in the package or from application specific location self.app.use(serveStatic(core.path.web)); self.app.use(serveStatic(__dirname + "/web")); self.app.use(self.app.router); // Default error handler to show erros in the log self.app.use(function(err, req, res, next) { console.error(err.stack); self.sendReply(res, err); }); // Return images by prefix, id and possibly type self.app.all(/^\/image\/([a-z]+)\/([a-z0-9-]+)\/?([0-9])?$/, function(req, res) { self.getIcon(req, res, req.params[1], { prefix: req.params[0], type: req.params[2] }); }); // Convert allow/deny lists into single regexp if (this.allow) this.allow = new RegExp(this.allow.map(function(x) { return "(" + x + ")"}).join("|")); if (this.allowSsl) this.allowSsl = new RegExp(this.allowSsl.map(function(x) { return "(" + x + ")"}).join("|")); if (this.deny) this.deny = new RegExp(this.deny.map(function(x) { return "(" + x + ")"}).join("|")); // Managing accounts, basic functionality for (var p in self.endpoints) { if (self.disable.indexOf(p) == -1) self[self.endpoints[p]].call(this); } // Remove default API tables for disabled endpoints self.disable.forEach(function(x) { delete self.tables['bk_' + x] }); if (!self.tables.bk_account) delete self.tables.bk_auth; if (!self.tables.bk_connection) delete self.tables.bk_reference; // Disable access to endpoints if session exists, meaning Web app self.disableSession.forEach(function(x) { self.registerAuthCheck('', new RegExp(x), function(req, callback) { if (req.session && req.session['bk-signature']) return callback({ status: 401, message: "Not authorized" }); callback(); }); }); // Custom application logic self.initApplication.call(self, function(err) { // Setup all tables self.initTables(function(err) { var server = self.app.listen(core.port, core.bind, function(err) { if (err) return logger.error('api: init:', core.port, core.bind, err); this.timeout = core.timeout; // Start the SSL server as well if (core.ssl.key || core.ssl.pfx) { server = https.createServer(core.ssl, self.app).listen(core.ssl.port, core.ssl.bind, function(err) { if (err) logger.error('api: ssl failed:', err, core.ssl); else logger.log('api: ssl started', 'port:', core.ssl.port, 'bind:', core.ssl.bind, 'timeout:', core.timeout); this.timeout = core.timeout; if (callback) callback(err); }); } else if (callback) callback(err); }); }); }); } // This handler is called after the Express server has been setup and all default API endpoints initialized but the server // is not ready for incoming requests yet. This handler can setup additional API endpoints, add/modify table descriptions. api.initApplication = function(callback) { callback() }; // This handler is called during the Express server initialization just after the security middleware. // this.app refers to the Express instance. api.initMiddleware = function() {}; // Perform authorization of the incoming request for access and permissions api.checkRequest = function(req, res, callback) { var self = this; self.checkAccess(req, function(rc1) { // Status is given, return an error or proceed to the next module if (rc1) { if (rc1.status == 200) return callback(); if (rc1.status) self.sendStatus(res, rc1); return; } // Verify account access for signature self.checkSignature(req, function(rc2) { res.header("cache-control", "no-cache"); res.header("pragma", "no-cache"); // Determine what to do with the request even if the status is not success, a hook may deal with it differently, // the most obvous case is for a Web app to perform redirection on authentication failure self.checkAuthorization(req, rc2, function(rc3) { if (rc3 && rc3.status != 200) return self.sendStatus(res, rc3); callback(); }); }); }); } // Parse incoming query parameters api.checkQuery = function(req, res, next) { var self = this; if (req._body) return next(); req.body = req.body || {}; var type = (req.get("content-type") || "").split(";")[0]; switch (type) { case 'application/json': case 'application/x-www-form-urlencoded': req.setEncoding('utf8'); break; default: // Custom types to be collected if (self.mimeBody.indexOf(type) == -1) return next(); req.setEncoding('binary'); } req._body = true; var buf = '', size = 0; var sig = core.parseSignature(req); req.on('data', function(chunk) { size += chunk.length; if (size > self.uploadLimit) return req.destroy(); buf += chunk; }); req.on('end', function() { try { // Verify data checksum before parsing if (sig && sig.checksum && core.hash(buf) != sig.checksum) { var err = new Error("invalid data checksum"); err.status = 400; return next(err); } switch (type) { case 'application/json': req.body = JSON.parse(buf); break; case 'application/x-www-form-urlencoded': req.body = buf.length ? qs.parse(buf) : {}; // Keep the parametrs in the body so we can distinguish GET and POST requests but use them in signature verification sig.query = buf; break; default: req.body = buf; } next(); } catch (err) { err.status = 400; next(err); } }); } // Parse multipart forms for uploaded files api.checkBody = function(req, res, next) { var self = this; if (req._body) return next(); req.files = req.files || {}; if ('GET' == req.method || 'HEAD' == req.method) return next(); var type = (req.get("content-type") || "").split(";")[0]; if (type != 'multipart/form-data') return next(); req._body = true; var data = {}, files = {}, done; var form = new formidable.IncomingForm({ uploadDir: core.path.tmp, keepExtensions: true }); function ondata(name, val, data) { if (Array.isArray(data[name])) { data[name].push(val); } else if (data[name]) { data[name] = [data[name], val]; } else { data[name] = val; } } form.on('field', function(name, val) { ondata(name, val, data); }); form.on('file', function(name, val) { ondata(name, val, files); }); form.on('error', function(err) { next(err); done = true; }); form.on('end', function() { if (done) return; try { req.body = qs.parse(data); req.files = qs.parse(files); next(); } catch (err) { err.status = 400; next(err); } }); form.parse(req); } // Perform URL based access checks // Check access permissions, calls the callback with the following argument: // - nothing if checkSignature needs to be called // - an object with status: 200 to skip authorization and proceed with the next module // - an object with status: 0 means response has been sent, just stop // - an object with status other than 0 or 200 to return the status and stop request processing api.checkAccess = function(req, callback) { if (this.deny && req.path.match(this.deny)) return callback({ status: 401, message: "Access denied" }); if (this.allow && req.path.match(this.allow)) return callback({ status: 200, message: "" }); // Call custom access handler for the endpoint var hook = this.findHook('access', req.method, req.path); if (hook) return hook.callbacks.call(this, req, callback) callback(); } // Perform authorization checks after the account been checked for valid signature, this is called even if the signature verification failed // - req is Express request object // - status contains the signature verification status, an object wth status: and message: properties // - callback is a function(req, status) to be called with the resulted status where status must be an object with status and message properties as well api.checkAuthorization = function(req, status, callback) { var hook = this.findHook('auth', req.method, req.path); if (hook) return hook.callbacks.call(this, req, status, callback); // Pass the status back to the checkRequest callback(status); } // Verify request signature from the request object, uses properties: .host, .method, .url or .originalUrl, .headers api.checkSignature = function(req, callback) { // Make sure we will not crash on wrong object if (!req || !req.headers) req = { headers: {} }; if (!callback) callback = function(x) { return x; } // Extract all signature components from the request var sig = core.parseSignature(req); // Show request in the log on demand for diagnostics if (logger.level >= 1 || req.query._debug) logger.log('checkSignature:', sig, 'hdrs:', req.headers, 'session:', JSON.stringify(req.session)); // Sanity checks, required headers must be present and not empty if (!sig.method || !sig.host || !sig.expires || !sig.login || !sig.signature) { return callback({ status: 401, message: "Invalid request: " + (!sig.method ? "no method provided" : !sig.host ? "no host provided" : !sig.login ? "no login provided" : !sig.expires ? "no expiration provided" : !sig.signature ? "no signature provided" : "") }); } // Make sure it is not expired, it may be milliseconds or ISO date if (sig.expires <= Date.now()) { return callback({ status: 400, message: "Expired request" }); } // Verify if the access key is valid, they all are cached so a bad cache may result in rejects core.context.db.getCached("bk_auth", { login: sig.login }, function(err, account) { if (err) return callback({ status: 500, message: String(err) }); if (!account) return callback({ status: 404, message: "No account record found" }); // Account expiration time if (account.expires && account.expires < Date.now()) { return callback({ status: 404, message: "This account has expired" }); } // Verify ACL regex if specified, test the whole query string as it appears in the request query line if (account.acl_deny && sig.url.match(account.acl_deny)) { return callback({ status: 401, message: "Access denied" }); } if (account.acl_allow && !sig.url.match(account.acl_allow)) { return callback({ status: 401, message: "Not permitted" }); } // Deal with encrypted body, use our account secret to decrypt, this is for raw data requests // if it is JSON or query it needs to be reparsed in the application if (req.body && req.get("content-encoding") == "encrypted") { req.body = core.decrypt(account.secret, req.body); } // Verify the signature with account secret if (!core.checkSignature(sig, account)) { if (logger.level >= 1 || req.query._debug) logger.log('checkSignature:', 'failed', sig, account); return callback({ status: 401, message: "Not authenticated" }); } // Save account and signature in the request, it will be used later req.signature = sig; req.account = account; logger.debug(req.path, req.account, req.query); return callback({ status: 200, message: "Ok" }); }); } // Account management api.initAccountAPI = function() { var self = this; var db = core.context.db; this.app.all(/^\/account\/([a-z\/]+)$/, function(req, res, next) { if (req.method == "POST") req.query = req.body; var options = self.getOptions(req); switch (req.params[0]) { case "get": if (!req.query.id) { db.get("bk_account", { id: req.account.id }, options, function(err, rows) { if (err) return self.sendReply(res, err); if (!rows.length) return self.sendReply(res, 404); // Setup session cookies for automatic authentication without signing if (req.query._session) { switch (req.query._session) { case "1": var sig = core.signRequest(req.account.login, req.account.secret, "", req.headers.host, "", { sigversion: 2, expires: self.sessionAge }); req.session["bk-signature"] = sig["bk-signature"]; break; case "0": delete req.session["bk-signature"]; break; } } self.sendJSON(req, res, rows[0]); }); } else { db.list("bk_account", req.query.id, options, function(err, rows) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, rows); }); } break; case "add": self.addAccount(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; case "update": self.updateAccount(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; case "del": db.get("bk_account", { id: req.account.id }, options, function(err, rows) { if (err) return self.sendReply(res, err); if (!rows.length) return self.sendReply(res, 404); // Pass the whole account record downstream to the possible hooks and return it as well to our client for (var p in rows[0]) req.account[p] = rows[0][p]; self.deleteAccount(req.account, options, function(err) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, core.cloneObj(req.account, { secret: true })); }); }); break; case "subscribe": // Ignore not matching events, the whole string is checked if (req.query.match) req.query.match = new RegExp(req.query.match); // Returns opaque handle depending on the pub/sub system req.pubSock = core.ipcSubscribe(req.account.id, function(data) { if (typeof data != "string") data = JSON.stringify(data); if (req.query.match && !data.match(req.query.match)) return; logger.debug('subscribe:', req.account.id, this.socket, data, res.headersSent); if (res.headersSent) return (req.pubSock = core.ipcUnsubscribe(req.pubSock)); if (req.pubTimeout) clearTimeout(req.pubTimeout); // Concatenate all messages received within the interval if (!req.pubData) req.pubData = ""; else req.pubData += ","; req.pubData += data; req.pubTimeout = setTimeout(function() { if (!res.headersSent) res.type('application/json').send("[" + req.pubData + "]"); // Returns null and clears the reference req.pubSock = core.ipcUnsubscribe(req.pubSock, req.account.id); }, self.subscribeInterval); }); if (!req.pubSock) return self.sendReply(res, 500, "Service is not activated"); // Listen for timeout and ignore it, this way the socket will be alive forever until we close it res.on("timeout", function() { logger.debug('subscribe:', 'timeout', req.account.id, req.pubSock); setTimeout(function() { req.socket.destroy(); }, self.subscribeTimeout); }); req.on("close", function() { logger.debug('subscribe:', 'close', req.account.id, req.pubSock); req.pubSock = core.ipcUnsubscribe(req.pubSock, req.account.id); }); logger.debug('subscribe:', 'start', req.account.id, req.pubSock); break; case "select": db.select("bk_account", req.query, options, function(err, rows, info) { if (err) return self.sendReply(res, err); var next_token = info.next_token ? core.toBase64(info.next_token) : ""; self.sendJSON(req, res, { count: rows.length, data: rows, next_token: next_token }); }); break; case "put/secret": if (!req.query.secret) return self.sendReply(res, 400, "secret is required"); req.account.secret = req.query.secret; db.update("bk_auth", req.account, { cached: 1 }, function(err) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, {}); }); break; case "get/icon": if (!req.query.id) req.query.id = req.account.id; if (!req.query.type) req.query.type = '0'; self.getIcon(req, res, req.query.id, { prefix: 'account', type: req.query.type }); break; case "select/icon": if (!req.query.id) req.query.id = req.account.id; options.ops = { type: "begins_with" }; db.select("bk_icon", { id: req.query.id, type: "account:" }, options, function(err, rows) { if (err) return self.sendReply(res, err); // Filter out not allowed icons rows = rows.filter(function(x) { return self.checkIcon(req, req.query.id, x); }); rows.forEach(function(x) { self.formatIcon(req, req.query.id, x); }); self.sendJSON(req, res, rows); }); break; case "put/icon": case "del/icon": options.op = req.params[0].substr(0, 3); req.query.prefix = 'account'; if (!req.query.type) req.query.type = '0'; self.handleIcon(req, res, options); break; default: self.sendReply(res, 400, "Invalid command"); } }); } // Generic icon management api.initIconAPI = function() { var self = this; var db = core.context.db; this.app.all(/^\/icon\/([a-z]+)\/([a-z0-9\.\_\-]+)\/?([a-z0-9\.\_\-])?$/, function(req, res) { if (req.method == "POST") req.query = req.body; var options = self.getOptions(req); if (!req.query.id) req.query.id = req.account.id; req.query.prefix = req.params[1]; req.query.type = req.params[2] || ""; switch (req.params[0]) { case "get": self.getIcon(req, res, req.query.id, { prefix: req.query.prefix, type: req.query.type }); break; case "select": options.ops = { type: "begins_with" }; db.select("bk_icon", { id: req.query.id, type: req.query.prefix + ":" + req.query.type }, options, function(err, rows) { if (err) return self.sendReply(res, err); // Filter out not allowed icons rows = rows.filter(function(x) { return self.checkIcon(req, req.query.id, x); }); rows.forEach(function(x) { self.formatIcon(req, req.query.id, x); }); self.sendJSON(req, res, rows); }); break; case "del": case "put": options.op = req.params[0]; self.handleIcon(req, res, options); break; default: self.sendReply(res, 400, "Invalid command"); } }); } // Messaging management api.initMessageAPI = function() { var self = this; var db = core.context.db; function processRows(rows) { rows.forEach(function(row) { var mtime = row.mtime.split(":"); row.mtime = core.toNumber(mtime[0]); row.sender = mtime[1]; row.status = row.status[0]; if (row.icon) row.icon = '/message/image?sender=' + row.sender + '&mtime=' + row.mtime; }); return rows; } this.app.all(/^\/message\/([a-z\/]+)$/, function(req, res) { if (req.method == "POST") req.query = req.body; var options = self.getOptions(req); var now = Date.now(); switch (req.params[0]) { case "image": if (!req.query.sender || !req.query.mtime) return self.sendReply(res, 400, "sender and mtime are required"); self.sendIcon(req, res, req.account.id, { prefix: 'message', type: req.query.mtime + ":" + req.query.sender}); break; case "get": req.query.id = req.account.id; // Must be a string for DynamoDB at least if (req.query.mtime) { options.ops.mtime = "gt"; req.query.mtime = String(req.query.mtime); } // Using sender index, all msgs from the sender if (req.query.sender) { options.sort = "sender"; options.ops.sender = "begins_with"; options.select = Object.keys(db.getColumns("bk_message", options)); req.query.sender += ":"; } db.select("bk_message", req.query, options, function(err, rows, info) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, { count: rows.length, data: processRows(rows), next_token: info.next_token ? core.toBase64(info.next_token) : "" }); }); break; case "get/unread": req.query.id = req.account.id; req.query.status = "N:"; options.sort = "status"; options.ops.status = "begins_with"; db.select("bk_message", req.query, options, function(err, rows, info) { if (err) return self.sendReply(res, err); // Mark all existing as read if (core.toBool(req.query._read)) { var nread = 0; async.forEachSeries(rows, function(row, next) { db.update("bk_message", { id: req.account.id, mtime: row.mtime, status: 'R:' + row.mtime }, function(err) { if (!err) nread++; next(); }); }, function(err) { if (nread) db.incr("bk_counter", { id: req.account.id, msg_read: nread }, { cached: 1 }); self.sendJSON(req, res, { count: rows.length, data: processRows(rows), next_token: info.next_token ? core.toBase64(info.next_token) : "" }); }); } else { self.sendJSON(req, res, { count: rows.length, data: processRows(rows), next_token: info.next_token ? core.toBase64(info.next_token) : "" }); } }); break; case "read": if (!req.query.sender || !req.query.mtime) return self.sendReply(res, 400, "sender and mtime are required"); req.query.mtime += ":" + req.query.sender; db.update("bk_message", { id: req.account.id, mtime: req.query.mtime, status: "R:" + req.query.mtime }, function(err, rows) { if (!err) db.incr("bk_counter", { id: req.account.id, msg_read: 1 }, { cached: 1 }); self.sendReply(res, err); }); break; case "add": self.addMessage(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; case "del": self.delMessages(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; default: self.sendReply(res, 400, "Invalid command"); } }); } // History management api.initHistoryAPI = function() { var self = this; var db = core.context.db; this.app.all(/^\/history\/([a-z]+)$/, function(req, res) { if (req.method == "POST") req.query = req.body; var options = self.getOptions(req); switch (req.params[0]) { case "add": if (!req.query.type || !req.query.data) return self.sendReply(res, 400, "type and data are required"); self.sendReply(res); req.query.id = req.account.id; req.query.mtime = Date.now(); db.add("bk_history", req.query); break; case "get": options.ops = { mtime: 'gt' }; db.select("bk_history", { id: req.account.id, mtime: req.query.mtime || 0 }, options, function(err, rows) { res.json(rows); }); break; default: self.sendReply(res, 400, "Invalid command"); } }); } // Counters management api.initCounterAPI = function() { var self = this; var db = core.context.db; this.app.all(/^\/counter\/([a-z]+)$/, function(req, res) { if (req.method == "POST") req.query = req.body; var options = self.getOptions(req); var now = Date.now(); switch (req.params[0]) { case "put": req.query.id = req.account.id; case "incr": // Remove non public columns when updating other account if (req.query.id && req.query.id != req.account.id) { var obj = { id: req.query.id }; db.getPublicColumns("bk_counter").forEach(function(x) { if (req.query[x]) obj[x] = req.query[x]; }); } else { var obj = req.query; obj.id = req.account.id; } db[req.params[0]]("bk_counter", obj, { cached: 1 }, function(err, rows) { if (err) return self.sendReply(res, db.convertError("bk_counter", err)); // Update history log if (options.history) { db.add("bk_history", { id: req.account.id, type: req.path, data: core.cloneObj(obj, { mtime: 1 }) }); } self.sendJSON(req, res, rows); core.ipcPublish(req.query.id, { path: req.path, mtime: now, data: core.cloneObj(obj, { id: 1, mtime: 1 })}); }); break; case "get": var id = req.query.id || req.account.id; db.getCached("bk_counter", { id: id }, options, function(err, row) { res.json(row); }); break; default: self.sendReply(res, 400, "Invalid command"); } }); } // Connections management api.initConnectionAPI = function() { var self = this; var db = core.context.db; this.app.all(/^\/(connection|reference)\/([a-z]+)$/, function(req, res) { if (req.method == "POST") req.query = req.body; var options = self.getOptions(req); var now = Date.now(); switch (req.params[1]) { case "add": case "put": case "update": self.putConnections(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; case "del": self.delConnections(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; case "get": self.getConnections(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; default: self.sendReply(res, 400, "Invalid command"); } }); } // Geo locations management api.initLocationAPI = function() { var self = this; var db = core.context.db; this.app.all(/^\/location\/([a-z]+)$/, function(req, res) { if (req.method == "POST") req.query = req.body; var options = self.getOptions(req); switch (req.params[0]) { case "put": self.putLocations(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; case "get": self.getLocations(req, options, function(err, data) { if (err) return self.sendReply(res, err); self.sendJSON(req, res, data); }); break; default: self.sendReply(res, 400, "Invalid command"); } }); } // API for internal provisioning, by default supports access to all tables api.initDataAPI = function() { var self = this; var db = core.context.db; // Return current statistics this.app.all("/data/stats", function(req, res) { res.json(self.getStatistics()); }); // Load columns into the cache this.app.all("/data/columns", function(req, res) { db.cacheColumns({}, function() { res.json(db.getPool().dbcolumns); }); }); // Return table columns this.app.all(/^\/data\/columns\/([a-z_0-9]+)$/, function(req, res) { res.json(db.getColumns(req.params[0])); }); // Return table keys this.app.all(/^\/data\/keys\/([a-z_0-9]+)$/, function(req, res) { res.json(db.getKeys(req.params[0])); }); // Basic operations on a table this.app.all(/^\/data\/(select|search|list|get|add|put|update|del|incr|replace)\/([a-z_0-9]+)$/, function(req, res, info) { // Table must exist var dbcols = db.getColumns(req.params[1]); if (!dbcols) return self.sendReply(res, "Unknown table"); if (req.method == "POST") req.query = req.body; var options = self.getOptions(req); // Allow access to all columns and db pools if (self.dataEndpointUnsecure) { delete options.check_public; if (req.query._pool) options.pool = req.query._pool; } db[req.params[0]](req.params[1], req.query, options, function(err, rows) { if (err) return self.sendReply(res, err); switch (req.params[0]) { case "select": case "search": self.sendJSON(req, res, { count: rows.length, data: rows, next_token: info.next_token }); break; default: self.sendJSON(req, res, rows); } }); }); } // Called in the master process to create/upgrade API related tables api.initTables = function(callback) { core.context.db.initTables(this.tables, callback); } // Convert query options into database options, most options are the same as for `db.select` but prepended with underscore to // distinguish control parameters from query parameters. api.getOptions = function(req) { var options = { check_public: req.account ? req.account.id : null, ops: {} }; ["details", "consistent", "desc", "total"].forEach(function(x) { if (typeof req.query["_" + x] != "undefined") options[x] = core.toBool(req.query["_" + x]); }); if (req.query._select) options.select = req.query._select; if (req.query._count) options.count = core.toNumber(req.query._count, 0, 50); if (req.query._start) options.start = core.toJson(req.query._start); if (req.query._sort) options.sort = req.query._sort; if (req.query._page) options.page = core.toNumber(req.query._page, 0, 0, 0, 9999); if (req.query._keys) { options.keys = core.strSplit(req.query._keys); if (!options.keys.length) delete options.keys; } if (req.query._width) options.width = core.toNumber(req.query._width); if (req.query._height) options.height = core.toNumber(req.query._height); if (req.query._ext) options.ext = req.query._ext; if (req.query._ops) { if (!options.ops) options.ops = {}; var ops = core.strSplit(req.query._ops); for (var i = 0; i < ops.length -1; i+= 2) options.ops[ops[i]] = ops[i+1]; } return options; } // Add columns to account tables, makes sense in case of SQL database for extending supported properties and/or adding indexes // Used during initialization of the external modules which may add custom columns to the existing tables. api.describeTables = function(tables) { var self = this; for (var p in tables) { if (!self.tables[p]) self.tables[p] = {}; for (var c in tables[p]) { if (!self.tables[p][c]) self.tables[p][c] = {}; // Override columns for (var k in tables[p][c]) { self.tables[p][c][k] = tables[p][c][k]; } } } } // Clear request query properties specified in the table definition, if any columns for the table contains the property `name` nonempty, then // all request properties with the same name as this column name will be removed from the query. This for example is used for the `bk_account` // table to disable updating location related columns because speial location API maintains location data and updates the accounts table. api.clearQuery = function(req, options, table, name) { var cols = core.context.db.getColumns(table, options); for (var p in cols) { if (cols[p][name]) delete req.query[p]; } } // Find registered hook for given type and path api.findHook = function(type, method, path) { var routes = this.hooks[type]; if (!routes) return null; for (var i = 0; i < routes.length; ++i) { if ((!routes[i].method || routes[i].method == method) && routes[i].match(path)) { return routes[i]; } } return null; } api.addHook = function(type, method, path, callback) { this.hooks[type].push(new express.Route(method, path, callback)); } // Register a handler to check access for any given endpoint, it works the same way as the global accessCheck function and is called before // validating the signature or session cookies. // - method can be '' in such case all mathods will be matched // - path is a string or regexp of the request URL similr to registering Express routes // - callback is a function with the following parameters: function(req, cb) {}, to indicate an error condition pass an object // with the callback with status: and message: properties, status != 200 means error // // Example: // // api.registerAccessCheck('', 'account', function(req, cb) { cb({status:500,message:"access disabled"}) })) // // api.registerAccessCheck('POST', 'account/add', function(req, cb) { // if (!req.query.invitecode) return cb({ status: 400, message: "invitation code is required" }); // cb(); // }); api.registerAccessCheck = function(method, path, callback) { this.addHook('access', method, path, callback); } // Similar to `registerAccessCheck` but this callback will be called after the signature or session is verified. // The purpose of this hook is too check permissions of a valid user to resources or in case of error perform any other action // like redirection or returning something explaining what to do in case of failure. The callback for this call is different then in `checkAccess` hooks. // - method can be '' in such case all mathods will be matched // - path is a string or regexp of the request URL similr to registering Express routes // - callback is a function(req, status, cb) where status is an object { status:..., message: ..} passed from the checkSignature call, if status != 200 it means // an error condition, the callback must pass the same or modified status object in its own `cb` callback // // Example: // // api.registerAuthCheck('GET', '/account/get', function(req, status, cb) { // if (status.status != 200) status = { status: 302, url: '/error.html' }; // cb(status) // }); api.registerAuthCheck = function(method, path, callback) { this.addHook('auth', method, path, callback); } // Register a callback to be called after successfull API action, status 200 only. // The purpose is to perform some additional actions after the standard API completed or to customize the result // - method can be '' in such case all mathods will be matched // - path is a string or regexp of the request URL similar to registering Express routes // - callback is a function with the following parameters: function(req, res, rows) where rows is the result returned by the API handler, // the callback MUST return data back to the client or any other status code api.registerPostProcess = function(method, path, callback) { this.addHook('post', method, path, callback); } // Send result back with possibly executing post-process callback, this is used by all API handlers to allow custom post processing in teh apps api.sendJSON = function(req, res, rows) { var hook = this.findHook('post', req.method, req.path); if (hook) return hook.callbacks.call(this, req, res, rows); res.json(rows); } // Send formatted JSON reply to API client, if status is an instance of Error then error message with status 500 is sent back api.sendReply = function(res, status, msg) { if (status instanceof Error || status instanceof Object) msg = status.message, status = status.status || 500; if (!status) status = 200, msg = ""; return this.sendStatus(res, { status: status, message: String(msg || "") }); } // Return reply to the client using the options object, it cantains the following properties: // - status - defines the respone status code // - message - property to be sent as status line and in the body // - type - defines Content-Type header, the message will be sent in the body // - url - for redirects when status is 301 or 302 api.sendStatus = function(res, options) { if (!options) options = { status: 200, message: "" }; if (!options.status) options.status = 200; switch (options.status) { case 301: case 302: res.redirect(options.status, options.url); break; default: if (options.type) { res.type(type); res.send(options.status, options.message || ""); } else { res.json(options.status, options); } } return false; } // Send file back to the client, res is Express response object api.sendFile = function(req, res, file, redirect) { fs.exists(file, function(yes) { if (req.method == 'HEAD') return res.send(yes ? 200 : 404); if (yes) return res.sendfile(file); if (redirect) return res.redirect(redirect); res.send(404); }); } // Return all connections for the current account, this function is called by the `/connection/get` API call. api.getConnections = function(req, options, callback) { var self = this; var db = core.context.db; if (req.query.type) req.query.type += ":" + (req.query.id || ""); req.query.id = req.account.id; options.ops.type = "begins_with"; db.select("bk_" + req.params[0], req.query, options, function(err, rows, info) { if (err) return self.sendReply(res, err); var next_token = info.next_token ? core.toBase64(info.next_token) : ""; // Split type and reference id rows.forEach(function(row) { var d = row.type.split(":"); row.type = d[0]; row.id = d[1]; }); if (!core.toNumber(options.details)) return callback(null, { count: rows.length, data: rows, next_token: next_token }); // Get all account records for the id list db.list("bk_account", rows, { select: req.query._select, check_public: req.account.id }, function(err, rows) { if (err) return self.sendReply(res, err); callback(null, { count: rows.length, data: rows, next_token: next_token }); }); }); } // Create a connection between 2 accounts, this function is called by the `/connection/add` API call. api.putConnections = function(req, options, callback) { var self = this; var db = core.context.db; var now = Date.now(); var id = req.query.id, type = req.query.type; if (!id || !type) return callback({ status: 400, message: "id and type are required"}); if (id == req.account.id) return callback({ status: 400, message: "cannot connect to itself"}); // Override primary key properties, the rest of the properties will be added as is req.query.id = req.account.id; req.query.type = type + ":" + id; req.query.mtime = now; db[req.params[1]]("bk_connection", req.query, function(err) { if (err) return callback(db.convertError("bk_connection", err)); // Reverse reference to the same connection req.query.id = id; req.query.type = type + ":"+ req.account.id; db[req.params[1]]("bk_reference", req.query, function(err) { if (err) { db.del("bk_connection", { id: req.account.id, type: type + ":" + id }); return callback(err); } // We need to know if the other side is connected too, this will save one extra API call if (req.query._connected) { db.get("bk_connection", req.query, function(err, rows) { callback(null, { connected: rows.length }); }); } else { callback(null, {}); } core.ipcPublish(id, { path: req.path, mtime: now, type: type, id: req.account.id }); async.series([ function(next) { // Update history log if (!options.history) return next(); db.add("bk_history", { id: req.account.id, type: req.path, data: type + ":" + id }, next); }, function(next) { // Update accumulated counter if we support this column and do it automatically next(req.params[1] == 'update' ? new Error("stop") : null); }, function(next) { var col = db.getColumn("bk_counter", type + '0'); if (!col || !col.incr) return next(); db.incr("bk_counter", core.newObj('id', req.account.id, type + '0', 1), { cached: 1 }, function() { db.incr("bk_counter", core.newObj('id', id, type + '1', 1), { cached: 1 }, next); }); }]); }); }); } // Delete a connection, this function is called by the `/connection/del` API call api.delConnections = function(req, options, callback) { var self = this; var db = core.context.db; var now = Date.now(); var id = req.query.id; var type = req.query.type; if (id && type) { db.del("bk_connection", { id: req.account.id, type: type + ":" + id }, options, function(err) { if (err) return callback(err); db.del("bk_reference", { id: id, type: type + ":" + req.account.id }, options, function(err) { if (err) return callback(err); callback(null, {}); core.ipcPublish(id, { path: req.path, mtime: now, type: type, id: req.account.id }); // Update history log if (options.history) { db.add("bk_history", { id: req.account.id, type: req.path, data: type + ":" + id }); } // Update accumulated counter if we support this column and do it automatically var col = db.getColumn("bk_counter", req.query.type + "0"); if (col && col.incr) { db.incr("bk_counter", core.newObj('id', req.account.id, type + '0', -1), { cached: 1 }); db.incr("bk_counter", core.newObj('id', id, type + '1', -1), { cached: 1 }); } }); }); } else { var counters = {}; db.select("bk_connection", { id: req.account.id }, options, function(err, rows) { if (err) return next(err) async.forEachSeries(rows, function(row, next2) { var t = row.type.split(":"); if (id && t[1] != id) return next2(); if (type && t[0] != type) return next2(); // Keep track of all counters var name0 = t[0] + '0', name1 = t[0] + '1'; var col = db.getColumn("bk_counter", name0); if (col && col.incr) { if (!counters[req.account.id]) counters[req.account.id] = { id: req.account.id }; if (!counters[req.account.id][name0]) counters[req.account.id][name0] = 0; counters[req.account.id][name0]--; if (!counters[t[1]]) counters[t[1]] = { id: t[1] }; if (!counters[t[1]][name1]) counters[t[1]][name1] = 0; counters[t[1]][name1]--; } db.del("bk_reference", { id: t[1], type: t[0] + ":" + req.account.id }, options, function(err) { db.del("bk_connection", row, options, next2); }); }, function(err) { if (err) return callback(err); // Update history log if (options.history) { db.add("bk_history", { id: req.account.id, type: req.path, data: type + ":" + id }); } logger.log('COUNTERS:', counters) // Update all counters for each id async.forEachSeries(Object.keys(counters), function(id, next) { db.incr("bk_counter", counters[id], { cached: 1 }, next); }, function(err) { callback(err, {}); }); }); }); } } // Perform locations search, request comes from the Express server, callback will takes err and data to be returned back to the client, this function // is used in `/location/get` request. It can be used in the applications with customized input and output if neccesary for the application specific logic. // // Example // // # Request will look like: /recent/locations?latitude=34.1&longitude=-118.1&mtime=123456789 // this.app.all(/^\/recent\/locations$/, function(req, res) { // var options = self.getOptions(req); // options.keys = ["geohash","mtime"]; // options.ops = { mtime: 'gt' }; // options.details = true; // self.getLocations(req, options, function(err, data) { // self.sendJSON(req, res, data); // }); // }); // api.getLocations = function(req, options, callback) { var self = this; var db = core.context.db; // Perform location search based on hash key that covers the whole region for our configured max distance if (!req.query.latitude || !req.query.longitude) return callback({ status: 400, message: "latitude/longitude are required" }); // Pass all query parameters for custom filters if any, do not override existing options for (var p in req.query) { if (p[0] != "_" && !options[p]) options[p] = req.query[p]; } // Limit the distance within our configured range options.distance = core.toNumber(req.query.distance, 0, core.minDistance, core.minDistance, core.maxDistance); // Continue pagination using the search token var token = core.toJson(req.query._token); if (token && token.geohash) { if (token.latitude != options.latitude || token.longitude != options.longitude || token.distance != options.distance) return callback({ status: 400, message: "invalid token, latitude, longitude and distance must be the same" }); options = token; } // Rounded distance, not precise to keep from pin-pointing locations if (!options.round) options.round = core.minDistance; db.getLocations("bk_location", options, function(err, rows, info) { var next_token = info.more ? core.toBase64(info) : null; // Ignore current account, db still retrieves it but in the API we skip it rows = rows.filter(function(row) { return row.id != req.account.id }); // Return accounts with locations if (core.toNumber(options.details) && rows.length) { var list = {}, ids = []; rows = rows.map(function(row) { // Skip duplicates if (list[row.id]) return row; ids.push({ id: row.id }); list[row.id] = row; return row; }); db.list("bk_account", ids, { select: req.query._select, check_public: req.account.id }, function(err, rows) { if (err) return self.sendReply(res, err); // Merge locations and accounts rows.forEach(function(row) { var item = list[row.id]; for (var p in item) row[p] = item[p]; }); callback(null, { count: rows.length, data: rows, next_token: next_token }); }); } else { callback(null, { count: rows.length, data: rows, next_token: next_token }); } }); } // Save locstion coordinates for current account, this function is called by the `/location/put` API call api.putLocations = function(req, options, callback) { var self = this; var db = core.context.db; var now = Date.now(); var latitude = req.query.latitude, longitude = req.query.longitude; if (!latitude || !longitude) return callback({ status: 400, message: "latitude/longitude are required" }); // Get current location db.get("bk_account", { id: req.account.id }, function(err, rows) { if (err || !rows.length) return callback(err); // Keep old coordinates in the account record var old = rows[0]; // Skip if within minimal distance var distance = backend.geoDistance(old.latitude, old.longitude, latitude, longitude); if (distance < core.minDistance) return callback({ status: 305, message: "ignored, min distance: " + core.minDistance}); // Build new location record var geo = core.geoHash(latitude, longitude); req.query.id = req.account.id; req.query.geohash = geo.geohash; var cols = db.getColumns("bk_location", options); // Update all account columns in the location, they are very tightly connected and custom filters can // be used for filtering locations based on other account properties like gender. for (var p in cols) if (old[p] && !req.query[p]) req.query[p] = old[p]; var obj = { id: req.account.id, geohash: geo.geohash, latitude: latitude, longitude: longitude, ltime: now, location: req.query.location }; db.update("bk_account", obj, function(err) { if (err) return callback(err); db.put("bk_location", req.query, function(err) { if (err) return callback(err); // Return new location record with the old coordinates req.query.old = old; callback(null, req.query); // Delete the old location, no need to wait even if fails we still have a new one recorded db.del("bk_location", old); }); // Update history log if (options.history) { db.add("bk_history", { id: req.account.id, type: req.path, data: geo.hash + ":" + latitude + ":" + longitude }); } }); }); } // Process icon request, put or del, update table and deal with the actual image data, always overwrite the icon file api.handleIcon = function(req, res, options) { var self = this; var db = core.context.db; var op = options.op || "put"; if (!req.query.type) req.query.type = ""; req.query.id = req.account.id; req.query.type = req.query.prefix + ":" + req.query.type; if (req.query.latitude && req.query.longitude) req.query.geohash = core.geoHash(req.query.latitude, req.query.longitude); db[op]("bk_icon", req.query, function(err, rows) { if (err) return self.sendReply(res, err); options.force = true; options.prefix = req.query.prefix; options.type = req.query.type; self[op + 'Icon'](req, req.account.id, options, function(err, icon) { if ((err || !icon) && op == "put") db.del('bk_icon', obj); self.sendReply(res, err); }); }); } // Return formatted icon URL for the given account api.formatIcon = function(req, id, row) { var type = row.type.split(":"); row.prefix = type[0]; row.type = type[1]; // Provide public url if allowed if (row.allow && row.allow == "all" && this.allow && ("/image/" + row.prefix + "/").match(this.allow)) { row.url = '/image/' + row.prefix + '/' + req.query.id + '/' + row.type; } else { if (row.prefix == "account") { row.url = '/account/get/icon?type=' + row.type; } else { row.url = '/icon/get/' + row.prefix + "/" + row.type + "?"; } if (id != req.account.id) row.url += "&id=" + id; } } // Return icon to the client, checks the bk_icon table for existence and permissions api.getIcon = function(req, res, id, options) { var self = this; var db = core.context.db; db.get("bk_icon", { id: id, type: options.prefix + ":" + options.type }, options, function(err, rows) { if (err) return self.sendReply(res, err); if (!rows.length) return self.sendReply(res, 404, "Not found"); if (!self.checkIcon(req, id, rows[0])) return self.sendReply(res, 401, "Not allowed"); self.sendIcon(req, res, id, options); }); } // Send an icon to the client, only handles files api.sendIcon = function(req, res, id, options) { var self = this; var aws = core.context.aws; var icon = core.iconPath(id, options); logger.log('sendIcon:', icon, id, options) if (self.imagesS3) { aws.queryS3(self.imagesS3, icon, options, function(err, params) { if (err) return self.sendReply(res, err); res.type("image/" + (options.ext || "jpeg")); res.send(200, params.data); }); } else { self.sendFile(req, res, icon); } } // Verify icon permissions for given account id, returns true if allowed api.checkIcon = function(req, id, row) { var acl = row.acl_allow || ""; if (acl == "all") return true; if (acl == "auth" && req.account) return true; if (acl.split(",").filter(function(x) { return x == id }).length) return true; return id == req.account.id; } // Store an icon for account, .type defines icon prefix api.putIcon = function(req, id, options, callback) { var self = this; // Multipart upload can provide more than one icon, file name can be accompanied by file_type property to define type for each icon, for // only one uploaded file req.query.type still will be used var nfiles = req.files ? Object.keys(req.files).length : 0; if (nfiles) { var outfile = null, type = req.query.type; async.forEachSeries(Object.keys(req.files), function(f, next) { var opts = core.extendObj(options, 'type', req.body[f + '_type'] || (type && nfiles == 1 ? type : "")); self.storeIcon(req.files[f].path, id, opts, function(err, ofile) { outfile = ofile; next(err); }); }, function(err) { callback(err, outfile); }); } else // JSON object submitted with .icon property if (typeof req.body == "object" && req.body.icon) { var icon = new Buffer(req.body.icon, "base64"); this.storeIcon(icon, id, options, callback); } else // Query base64 encoded parameter if (req.query.icon) { var icon = new Buffer(req.query.icon, "base64"); this.storeIcon(icon, id, options, callback); } else { return callback(); } } // Place the icon data to the destination api.storeIcon = function(icon, id, options, callback) { if (this.imagesS3) { this.putIconS3(icon, id, options, callback); } else { core.putIcon(icon, id, options, callback); } } // Delete an icon for account, .type defines icon prefix api.delIcon = function(req, id, options, callback) { if (typeof options == "function") callback = options, options = null; if (!options) options = {}; var icon = core.iconPath(id, options); if (this.imagesS3) { var aws = core.context.aws; aws.queryS3(this.imagesS3, icon, { method: "DELETE" }, function(err) { logger.edebug(err, 'delIcon:', id, options); if (callback) callback(); }); } else { fs.unlink(icon, function(err) { logger.edebug(err, 'delIcon:', id, options); if (callback) callback(); }); } } // Same as putIcon but store the icon in the S3 bucket, icon can be a file or a buffer with image data api.putIconS3 = function(file, id, options, callback) { var self = this; if (typeof options == "function") callback = options, options = null; if (!options) options = {}; var aws = core.context.aws; var icon = core.iconPath(id, options); core.scaleIcon(file, options, function(err, data) { if (err) return callback ? callback(err) : null; var headers = { 'content-type': 'image/' + (options.ext || "jpeg") }; aws.queryS3(self.imagesS3, icon, { method: "PUT", postdata: data, headers: headers }, function(err) { if (callback) callback(err, icon); }); }); } // Upload file and store in the filesystem or S3, try to find the file in multipart form, in the body or query by the given name // - name is the name property to look for in the multipart body or in the request body or query // - callback will be called with err and actual filename saved // Output file name is built according to the following options properties: // - name - defines the basename for the file, no extention, if not given same name as property will be used // - ext - what file extention to use, appended to name, if no ext is given the extension from the uploaded file will be used or no extention if could not determine one. // - extkeep - tells always to keep actual extention from the uploaded file api.putFile = function(req, name, options, callback) { var self = this; if (typeof options == "function") callback = options, options = null; if (!options) options = {}; var outfile = (options.name || name) + (options.ext || ""); if (req.files && req.files[name]) { if (!options.ext || options.extkeep) outfile += path.extname(req.files[name].name || req.files[name].path); self.storeFile(req.files[name].path, outfile, options, callback); } else // JSON object submitted with .name property with the icon contents if (typeof req.body == "object" && req.body[name]) { var data = new Buffer(req.body[name], "base64"); self.storeFile(data, outfile, options, callback); } else // Query base64 encoded parameter if (req.query[name]) { var data = new Buffer(req.query[name], "base64"); self.storeFile(data, outfile, options, callback); } else { return callback(); } } // Place the uploaded tmpfile to the destination pointed by outfile api.storeFile = function(tmpfile, outfile, options, callback) { if (typeof options == "function") callback = options, options = null; if (!options) options = {}; if (this.fileS3) { var headers = { 'content-type': mime.lookup(outfile) }; var ops = { method: "PUT", headers: headers } opts[Buffer.isBuffer(tmfile) ? 'postdata' : 'postfile'] = tmpfile; aws.queryS3(this.filesS3, outfile, opts, function(err) { if (callback) callback(err, outfile); }); } else { if (Buffer.isBuffer(tmpfile)) { fs.writeFile(path.join(core.path.files, outfile), tmpfile, function(err) { if (err) logger.error('storeFile:', outfile, err); if (callback) callback(err, outfile); }); } else { core.moveFile(tmpfile, path.join(core.path.files, outfile), true, function(err) { if (err) logger.error('storeFile:', outfile, err); if (callback) callback(err, outfile); }); } } } // Delete file by name api.deleteFile = function(file, options, callback) { if (typeof options == "function") callback = options, options = null; if (!options) options = {}; if (this.fileS3) { aws.queryS3(this.filesS3, file, { method: "DELETE" }, function(err) { if (callback) callback(err, outfile); }); } else { fs.unlink(path.join(core.path.files, file), function(err) { if (err) logger.error('deleteFile:', file, err); if (callback) callback(err, outfile); }) } } // Add new message, used in /message/add API call api.addMessage = function(req, options, callback) { var self = this; var db = core.context.db; var now = Date.now(); if (!req.query.id) return callback({ status: 400, message: "receiver id is required" }); if (!req.query.msg && !req.query.icon) return callback({ status: 400, message: "msg or icon is required" }); req.query.mtime = now + ":" + req.account.id; req.query.sender = req.account.id + ":" + now; req.query.status = 'N:' + req.query.mtime; self.putIcon(req, req.query.id, { prefix: 'message', type: req.query.mtime }, function(err, icon) { if (err) return callback(err); req.query.icon = icon ? 1 : "0"; db.add("bk_message", req.query, {}, function(err, rows) { if (err) return callback(db.convertError("bk_message", err)); callback(null, { id: req.query.id, mtime: now, sender: req.account.id, icon: req.query.icon }); core.ipcPublish(req.query.id, { path: req.path, mtime: now, sender: req.query.sender }); db.incr("bk_counter", { id: req.account.id, msg_count: 1 }, { cached: 1 }); // Update history log if (options.history) { db.add("bk_history", { id: req.account.id, type: req.path, mtime: now, data: req.query.id }); } }); }); } // Delete a message or all messages for the given account from the given sender, used in /messge/del` API call api.delMessages = function(req, options, callback) { var self = this; var db = core.context.db; if (!req.query.sender) return callback({ status: 400, message: "sender is required" }); if (req.query.mtime) { req.query.mtime += ":" + req.query.sender; db.del("bk_message", { id: req.account.id, mtime: req.query.mtime }, function(err, rows) { if (err) return callback(err); db.incr("bk_counter", { id: req.account.id, msg_count: -1 }, { cached: 1 }); callback(null, {}); }); } else { options.sort = "sender"; options.ops = { sender: "begins_with" }; db.select("bk_message", { id: req.account.id, sender: req.query.sender + ":" }, options, function(err, rows) { if (err) return callback(err); async.forEachSeries(rows, function(row, next) { var sender = row.sender.split(":"); row.mtime = sender[1] + ":" + sender[0]; db.del("bk_message", row, options, next); }, function(err) { if (!err && rows.count) { db.incr("bk_counter", { id: req.account.id, msg_count: -rows.count }, { cached: 1 }); } callback(null, {}); }); }); } } // Register new account, used in /account/add API call api.addAccount = function(req, options, callback) { var self = this; var db = core.context.db; // Verify required fields if (!req.query.secret) return callback({ status: 400, message: "secret is required"}); if (!req.query.name) return callback({ status: 400, message: "name is required"}); if (!req.query.login) return callback({ status: 400, message: "login is required"}); if (!req.query.alias) req.query.alias = req.query.name; req.query.id = core.uuid(); req.query.mtime = req.query.ctime = Date.now(); // Add new auth record with only columns we support, NoSQL db can add any columns on the fly and we want to keep auth table very small var auth = { id: req.query.id, login: req.query.login, secret: req.query.secret }; // Only admin can add accounts with the type if (req.account && req.account.type == "admin" && req.query.type) auth.type = req.query.type; db.add("bk_auth", auth, function(err) { if (err) return callback(db.convertError("bk_auth", err)); // Skip location related properties self.clearQuery(req, options, "bk_account", "noadd"); db.add("bk_account", req.query, function(err) { if (err) { db.del("bk_auth", auth); return callback(db.convertError("bk_account", err)); } db.processRows(null, "bk_account", req.query, options); // Link account record for other middleware req.account = req.query; // Some dbs require the record to exist, just make one with default values db.put("bk_counter", { id: req.query.id, like0: 0 }); callback(null, req.query); }); }); } // Update existing account, used in /account/update API call api.updateAccount = function(req, options, callback) { var self = this; var db = core.context.db; req.query.mtime = Date.now(); req.query.id = req.account.id; // Skip location related properties self.clearQuery(req, options, "bk_account", "noadd"); db.update("bk_account", req.query, callback); } // Delete account specified in the obj, this must be merged object from bk_auth and bk_account tables. // Return err if something wrong occured in the callback. api.deleteAccount = function(obj, options, callback) { var self = this; if (!obj || !obj.id || !obj.login) return callback ? callback(new Error("id, login must be specified")) : null; if (typeof options == "function") callback = options, options = {}; var db = core.context.db; options = db.getOptions("bk_account", options); db.get("bk_account", { id: obj.id }, options, function(err, rows) { if (err || !rows.length) if (err) return callback ? callback(err) : null; async.series([ function(next) { options.cached = true db.del("bk_auth", { login: obj.login }, options, function(err) { options.cached = false; next(err); }); }, function(next) { db.del("bk_account", { id: obj.id }, options, function() { next() }); }, function(next) { db.del("bk_counter", { id: obj.id }, options, function() { next() }); }, function(next) { db.select("bk_connection", { id: obj.id }, options, function(err, rows) { if (err) return next(err) async.forEachSeries(rows, function(row, next2) { var type = row.type.split(":"); db.del("bk_reference", { id: type[1], type: type[0] + ":" + obj.id }, options, function(err) { db.del("bk_connection", row, options, next2); }); }, next); }); }, function(next) { db.delAll("bk_message", { id: obj.id }, options, function() { next() }); }, function(next) { db.delAll("bk_icon", { id: obj.id }, options, function() { next() }); }, function(next) { var geo = core.geoHash(rows[0].latitude, rows[0].longitude); db.del("bk_location", { geohash: geo.geohash, id: obj.id }, options, next); }], callback); }); } // Returns an object with collected db and api statstics and metrics api.getStatistics = function() { return { toobusy: toobusy.lag(), pool: core.context.db.getPool().metrics, api: this.metrics }; } // Metrics about the process api.collectStatistics = function() { var avg = os.loadavg(); var mem = process.memoryUsage(); this.metrics.Histogram('rss').update(mem.rss); this.metrics.Histogram('heap').update(mem.heapUsed); this.metrics.Histogram('loadavg').update(avg[2]); this.metrics.Histogram('freemem').update(os.freemem()); }
aded cache API
api.js
aded cache API
<ide><path>pi.js <ide> // Return current statistics <ide> this.app.all("/data/stats", function(req, res) { <ide> res.json(self.getStatistics()); <add> }); <add> <add> this.app.all(/^\/data\/cache\/(.+)$/, function(req, res) { <add> switch (req.params[0]) { <add> case "keys": <add> core.ipcSend("keys", "", function(data) { res.send(data) }); <add> break; <add> case "clear": <add> core.ipcSend("clear", ""); <add> res.json(); <add> break; <add> case "get": <add> core.ipcGetCache(req.query.name, function(data) { res.send(data) }); <add> break; <add> case "del": <add> core.ipcDelCache(req.query.name); <add> break; <add> case "incr": <add> core.ipcIncrCache(req.query.name, core.toNumber(req.query.value)); <add> break; <add> case "put": <add> core.ipcPutCache(req.params[0].split("/").pop(), req.query); <add> break; <add> default: <add> res.send(404); <add> } <ide> }); <ide> <ide> // Load columns into the cache
Java
apache-2.0
3ae09f1bd47076fca42a604a39e1fdf94fddcaab
0
ruspl-afed/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,AndrewKhitrin/dbeaver,AndrewKhitrin/dbeaver,liuyuanyuan/dbeaver,ruspl-afed/dbeaver,ruspl-afed/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,ruspl-afed/dbeaver
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider ([email protected]) * * 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.jkiss.dbeaver.model; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IAdaptable; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.ModelPreferences; import org.jkiss.dbeaver.model.app.DBPDataSourceRegistry; import org.jkiss.dbeaver.model.data.*; import org.jkiss.dbeaver.model.exec.*; import org.jkiss.dbeaver.model.impl.data.DefaultValueHandler; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.sql.*; import org.jkiss.dbeaver.model.struct.*; import org.jkiss.dbeaver.model.struct.rdb.*; import org.jkiss.dbeaver.utils.GeneralUtils; import org.jkiss.utils.CommonUtils; import java.util.*; /** * DBUtils */ public final class DBUtils { private static final Log log = Log.getLog(DBUtils.class); @NotNull public static String getQuotedIdentifier(@NotNull DBSObject object) { return getQuotedIdentifier(object.getDataSource(), object.getName()); } public static boolean isQuotedIdentifier(@NotNull DBPDataSource dataSource, @NotNull String str) { if (dataSource instanceof SQLDataSource) { final String quote = ((SQLDataSource) dataSource).getSQLDialect().getIdentifierQuoteString(); return quote != null && str.startsWith(quote) && str.endsWith(quote); } else { return false; } } @NotNull public static String getUnQuotedIdentifier(@NotNull DBPDataSource dataSource, @NotNull String str) { if (dataSource instanceof SQLDataSource) { String quote = ((SQLDataSource) dataSource).getSQLDialect().getIdentifierQuoteString(); if (quote == null) { quote = SQLConstants.DEFAULT_IDENTIFIER_QUOTE; } if (str.startsWith(quote) && str.endsWith(quote)) { return str.substring(quote.length(), str.length() - quote.length()); } } return str; } @NotNull public static String getUnQuotedIdentifier(@NotNull String str, String quote) { if (quote != null && str.startsWith(quote) && str.endsWith(quote)) { return str.substring(quote.length(), str.length() - quote.length()); } return str; } @NotNull public static String getQuotedIdentifier(@NotNull DBPDataSource dataSource, @NotNull String str) { if (dataSource instanceof SQLDataSource) { return getQuotedIdentifier((SQLDataSource)dataSource, str, true); } else { return str; } } @NotNull public static String getQuotedIdentifier(@NotNull SQLDataSource dataSource, @NotNull String str, boolean caseSensitiveNames) { final SQLDialect sqlDialect = dataSource.getSQLDialect(); String quoteString = sqlDialect.getIdentifierQuoteString(); if (quoteString == null) { return str; } if (str.startsWith(quoteString) && str.endsWith(quoteString)) { // Already quoted return str; } // Check for keyword conflict final DBPKeywordType keywordType = sqlDialect.getKeywordType(str); boolean hasBadChars = (keywordType == DBPKeywordType.KEYWORD || keywordType == DBPKeywordType.TYPE) && sqlDialect.isQuoteReservedWords(); if (!hasBadChars && !str.isEmpty()) { hasBadChars = Character.isDigit(str.charAt(0)); } if (caseSensitiveNames) { // Check for case of quoted idents. Do not check for unquoted case - we don't need to quote em anyway if (!hasBadChars && sqlDialect.supportsQuotedMixedCase()) { // See how unquoted idents are stored // If passed identifier case differs from unquoted then we need to escape it if (sqlDialect.storesUnquotedCase() == DBPIdentifierCase.UPPER) { hasBadChars = !str.equals(str.toUpperCase()); } else if (sqlDialect.storesUnquotedCase() == DBPIdentifierCase.LOWER) { hasBadChars = !str.equals(str.toLowerCase()); } } } // Check for bad characters if (!hasBadChars && !str.isEmpty()) { if (str.charAt(0) == '_') { hasBadChars = true; } else { for (int i = 0; i < str.length(); i++) { if (!sqlDialect.validUnquotedCharacter(str.charAt(i))) { hasBadChars = true; break; } } } } if (!hasBadChars) { return str; } // Escape quote chars if (str.contains(quoteString)) { str = str.replace(quoteString, quoteString + quoteString); } return quoteString + str + quoteString; } @NotNull public static String getFullQualifiedName(@NotNull DBPDataSource dataSource, @NotNull DBPNamedObject ... path) { StringBuilder name = new StringBuilder(20 * path.length); if (!(dataSource instanceof SQLDataSource)) { // It is not SQL identifier, let's just make it simple then for (DBPNamedObject namePart : path) { if (name.length() > 0) { name.append('.'); } name.append(namePart.getName()); } } else { final SQLDialect sqlDialect = ((SQLDataSource) dataSource).getSQLDialect(); DBPNamedObject parent = null; for (DBPNamedObject namePart : path) { if (namePart == null) { continue; } if (namePart instanceof DBSCatalog && ((sqlDialect.getCatalogUsage() & SQLDialect.USAGE_DML) == 0)) { // Do not use catalog name in FQ name continue; } if (namePart instanceof DBSSchema && ((sqlDialect.getSchemaUsage() & SQLDialect.USAGE_DML) == 0)) { // Do not use schema name in FQ name continue; } // Check for valid object name if (!isValidObjectName(namePart.getName())) { continue; } if (name.length() > 0) { if (parent instanceof DBSCatalog) { if (!sqlDialect.isCatalogAtStart()) { log.warn("Catalog name should be at the start of full-qualified name!"); } name.append(sqlDialect.getCatalogSeparator()); } else { name.append(sqlDialect.getStructSeparator()); } } name.append(DBUtils.getQuotedIdentifier(dataSource, namePart.getName())); parent = namePart; } } return name.toString(); } @NotNull public static String getSimpleQualifiedName(@NotNull Object... names) { StringBuilder name = new StringBuilder(names.length * 16); for (Object namePart : names) { if (namePart == null) { continue; } if (name.length() > 0 && name.charAt(name.length() - 1) != '.') { name.append('.'); } name.append(namePart); } return name.toString(); } /** * Checks that object has valid object name. * Some DB objects have dummy names (like "" or ".") - we won't use them for certain purposes. * @param name object name * @return true or false */ public static boolean isValidObjectName(@Nullable String name) { if (name == null || name.isEmpty()) { return false; } boolean validName = false; for (int i = 0; i < name.length(); i++) { if (Character.isLetterOrDigit(name.charAt(i))) { validName = true; break; } } return validName; } /** * Finds catalog, schema or table within specified object container * @param monitor progress monitor * @param rootSC container * @param catalogName catalog name (optional) * @param schemaName schema name (optional) * @param objectName table name (optional) * @return found object or null * @throws DBException */ @Nullable public static DBSObject getObjectByPath( @NotNull DBRProgressMonitor monitor, @NotNull DBSObjectContainer rootSC, @Nullable String catalogName, @Nullable String schemaName, @Nullable String objectName) throws DBException { if (!CommonUtils.isEmpty(catalogName) && !CommonUtils.isEmpty(schemaName)) { // We have both both - just search both DBSObject catalog = rootSC.getChild(monitor, catalogName); if (!(catalog instanceof DBSObjectContainer)) { return null; } rootSC = (DBSObjectContainer) catalog; DBSObject schema = rootSC.getChild(monitor, schemaName); if (!(schema instanceof DBSObjectContainer)) { return null; } rootSC = (DBSObjectContainer) schema; } else if (!CommonUtils.isEmpty(catalogName) || !CommonUtils.isEmpty(schemaName)) { // One container name String containerName = !CommonUtils.isEmpty(catalogName) ? catalogName : schemaName; DBSObject sc = rootSC.getChild(monitor, containerName); if (!(sc instanceof DBSObjectContainer)) { // Not found - try to find in selected object DBSObject selectedObject = getSelectedObject(rootSC, false); if (selectedObject instanceof DBSObjectContainer) { sc = ((DBSObjectContainer) selectedObject).getChild(monitor, containerName); } if (!(sc instanceof DBSObjectContainer)) { return null; } } rootSC = (DBSObjectContainer) sc; } if (objectName == null) { return rootSC; } final DBSObject object = rootSC.getChild(monitor, objectName); if (object instanceof DBSEntity) { return object; } else { // Child is not an entity. May be catalog/schema names was omitted. // Try to use selected object DBSObject selectedObject = DBUtils.getSelectedObject(rootSC, true); if (selectedObject instanceof DBSObjectContainer) { return ((DBSObjectContainer) selectedObject).getChild(monitor, objectName); } // Table container not found return object; } } @Nullable public static DBSObject findNestedObject( @NotNull DBRProgressMonitor monitor, @NotNull DBSObjectContainer parent, @NotNull List<String> names) throws DBException { for (int i = 0; i < names.size(); i++) { String childName = names.get(i); DBSObject child = parent.getChild(monitor, childName); if (child == null) { DBSObjectSelector selector = DBUtils.getAdapter(DBSObjectSelector.class, parent); if (selector != null) { DBSObjectContainer container = DBUtils.getAdapter(DBSObjectContainer.class, selector.getDefaultObject()); if (container != null) { parent = container; child = parent.getChild(monitor, childName); } } } if (child == null) { break; } if (i == names.size() - 1) { return child; } if (child instanceof DBSObjectContainer) { parent = DBSObjectContainer.class.cast(child); } else { break; } } return null; } /** * Finds object by its name (case insensitive) * * @param theList object list * @param objectName object name * @return object or null */ @Nullable public static <T extends DBPNamedObject> T findObject(@Nullable Collection<T> theList, String objectName) { if (theList != null && !theList.isEmpty()) { for (T object : theList) { if (object.getName().equalsIgnoreCase(objectName)) { return object; } } } return null; } @Nullable public static <T extends DBPNamedObject> T findObject(@Nullable List<T> theList, String objectName) { if (theList != null) { int size = theList.size(); for (int i = 0; i < size; i++) { if (theList.get(i).getName().equalsIgnoreCase(objectName)) { return theList.get(i); } } } return null; } /** * Finds object by its name (case insensitive) * * @param theList object list * @param objectName object name * @return object or null */ @Nullable public static <T extends DBPNamedObject> List<T> findObjects(@Nullable Collection<T> theList, @Nullable String objectName) { if (theList != null && !theList.isEmpty()) { List<T> result = new ArrayList<>(); for (T object : theList) { if (object.getName().equalsIgnoreCase(objectName)) { result.add(object); } } return result; } return null; } @Nullable public static <T> T getAdapter(@NotNull Class<T> adapterType, @Nullable Object object) { if (object instanceof DBPDataSourceContainer) { // Root object's parent is data source container (not datasource) // So try to get adapter from real datasource object object = ((DBPDataSourceContainer)object).getDataSource(); } if (object == null) { return null; } if (adapterType.isAssignableFrom(object.getClass())) { return adapterType.cast(object); } else if (object instanceof IAdaptable) { return adapterType.cast(((IAdaptable)object).getAdapter(adapterType)); } else { return null; } } @Nullable public static <T> T getParentAdapter(@NotNull Class<T> i, DBSObject object) { if (object == null) { return null; } DBSObject parent = object.getParentObject(); if (parent == null) { return null; } T adapter = getAdapter(i, parent); // In some cases parent's adapter is object itself (e.g. DS maybe DS adapter of container) return adapter == object ? null : adapter; } /** * Search for virtual entity descriptor * @param object object * @return object path */ @NotNull public static DBSObject[] getObjectPath(@NotNull DBSObject object, boolean includeSelf) { int depth = 0; final DBSObject root = includeSelf ? object : object.getParentObject(); for (DBSObject obj = root; obj != null; obj = obj.getParentObject()) { depth++; } DBSObject[] path = new DBSObject[depth]; for (DBSObject obj = root; obj != null; obj = obj.getParentObject()) { path[depth-- - 1] = obj; } return path; } public static boolean isNullValue(@Nullable Object value) { return (value == null || (value instanceof DBDValue && ((DBDValue) value).isNull())); } @Nullable public static Object makeNullValue(@NotNull DBCSession session, @NotNull DBDValueHandler valueHandler, @NotNull DBSTypedObject type) throws DBCException { return valueHandler.getValueFromObject(session, type, null, false); } @NotNull public static DBDAttributeBindingMeta getAttributeBinding(@NotNull DBCSession session, @NotNull DBCAttributeMetaData attributeMeta) { return new DBDAttributeBindingMeta(session, attributeMeta); } @NotNull public static DBDValueHandler findValueHandler(@NotNull DBCSession session, @NotNull DBSTypedObject column) { return findValueHandler(session.getDataSource(), session, column); } @NotNull public static DBDValueHandler findValueHandler(@NotNull DBPDataSource dataSource, @NotNull DBSTypedObject column) { return findValueHandler(dataSource, dataSource.getContainer(), column); } @NotNull public static DBDValueHandler findValueHandler(@NotNull DBPDataSource dataSource, @Nullable DBDPreferences preferences, @NotNull DBSTypedObject column) { DBDValueHandler typeHandler = null; // Get handler provider from datasource DBDValueHandlerProvider typeProvider = getAdapter(DBDValueHandlerProvider.class, dataSource); if (typeProvider != null) { typeHandler = typeProvider.getValueHandler(dataSource, preferences, column); if (typeHandler != null) { return typeHandler; } } // Get handler provider from registry typeProvider = dataSource.getContainer().getPlatform().getValueHandlerRegistry().getDataTypeProvider( dataSource, column); if (typeProvider != null) { typeHandler = typeProvider.getValueHandler(dataSource, preferences, column); } // Use default handler if (typeHandler == null) { if (preferences == null) { typeHandler = DefaultValueHandler.INSTANCE; } else { typeHandler = preferences.getDefaultValueHandler(); } } return typeHandler; } /** * Identifying association is an association which associated entity's attributes are included into owner entity primary key. I.e. they * identifies entity. */ public static boolean isIdentifyingAssociation(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntityAssociation association) throws DBException { if (!(association instanceof DBSEntityReferrer)) { return false; } final DBSEntityReferrer referrer = (DBSEntityReferrer)association; final DBSEntity refEntity = association.getAssociatedEntity(); final DBSEntity ownerEntity = association.getParentObject(); assert ownerEntity != null; if (refEntity == ownerEntity) { // Can't migrate into itself return false; } // Migrating association is: if all referenced attributes are included in some unique key List<DBSEntityAttribute> ownAttrs = getEntityAttributes(monitor, referrer); Collection<? extends DBSEntityConstraint> constraints = ownerEntity.getConstraints(monitor); if (constraints != null) { boolean hasPrimaryKey = false; for (DBSEntityConstraint constraint : constraints) { if (constraint.getConstraintType() == DBSEntityConstraintType.PRIMARY_KEY) { hasPrimaryKey = true; break; } } for (DBSEntityConstraint constraint : constraints) { if (constraint instanceof DBSEntityReferrer && ((hasPrimaryKey && constraint.getConstraintType() == DBSEntityConstraintType.PRIMARY_KEY) || (!hasPrimaryKey && constraint.getConstraintType().isUnique()))) { List<DBSEntityAttribute> constAttrs = getEntityAttributes(monitor, (DBSEntityReferrer) constraint); boolean included = true; for (DBSEntityAttribute attr : ownAttrs) { if (!constAttrs.contains(attr)) { included = false; break; } } if (included) { return true; } } } } return false; } @NotNull public static String getDefaultDataTypeName(@NotNull DBPDataSource dataSource, DBPDataKind dataKind) { if (dataSource instanceof DBPDataTypeProvider) { return ((DBPDataTypeProvider) dataSource).getDefaultDataTypeName(dataKind); } else { // Unsupported data kind return "?"; } } @Nullable public static DBDAttributeBinding findBinding(@NotNull Collection<DBDAttributeBinding> bindings, @NotNull DBSAttributeBase attribute) { for (DBDAttributeBinding binding : bindings) { if (binding.matches(attribute, true)) { return binding; } List<DBDAttributeBinding> nestedBindings = binding.getNestedBindings(); if (nestedBindings != null) { DBDAttributeBinding subBinding = findBinding(nestedBindings, attribute); if (subBinding != null) { return subBinding; } } } return null; } @Nullable public static DBDAttributeBinding findBinding(@NotNull DBDAttributeBinding[] bindings, @Nullable DBSAttributeBase attribute) { if (attribute == null) { return null; } for (DBDAttributeBinding binding : bindings) { if (binding.matches(attribute, true)) { return binding; } List<DBDAttributeBinding> nestedBindings = binding.getNestedBindings(); if (nestedBindings != null) { DBDAttributeBinding subBinding = findBinding(nestedBindings, attribute); if (subBinding != null) { return subBinding; } } } return null; } @NotNull public static List<DBSEntityReferrer> getAttributeReferrers(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntityAttribute entityAttribute) throws DBException { DBSEntity entity = entityAttribute.getParentObject(); assert entity != null; List<DBSEntityReferrer> refs = null; Collection<? extends DBSEntityAssociation> associations = entity.getAssociations(monitor); if (associations != null) { for (DBSEntityAssociation fk : associations) { if (fk instanceof DBSEntityReferrer && DBUtils.getConstraintAttribute(monitor, (DBSEntityReferrer) fk, entityAttribute) != null) { if (refs == null) { refs = new ArrayList<>(); } refs.add((DBSEntityReferrer)fk); } } } return refs != null ? refs : Collections.<DBSEntityReferrer>emptyList(); } @NotNull public static Collection<? extends DBSEntityAttribute> getBestTableIdentifier(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntity entity) throws DBException { if (entity instanceof DBSTable && ((DBSTable) entity).isView()) { return Collections.emptyList(); } if (CommonUtils.isEmpty(entity.getAttributes(monitor))) { return Collections.emptyList(); } List<DBSEntityConstraint> identifiers = new ArrayList<>(); // Check indexes if (entity instanceof DBSTable) { try { Collection<? extends DBSTableIndex> indexes = ((DBSTable)entity).getIndexes(monitor); if (!CommonUtils.isEmpty(indexes)) { for (DBSTableIndex index : indexes) { if (isIdentifierIndex(monitor, index)) { identifiers.add(index); } } } } catch (DBException e) { log.debug(e); } } // Check constraints only if no unique indexes found if (identifiers.isEmpty()) { Collection<? extends DBSEntityConstraint> uniqueKeys = entity.getConstraints(monitor); if (uniqueKeys != null) { for (DBSEntityConstraint constraint : uniqueKeys) { if (isIdentifierConstraint(monitor, constraint)) { identifiers.add(constraint); } } } } if (!identifiers.isEmpty()) { // Find PK or unique key DBSEntityConstraint uniqueId = null; //DBSEntityConstraint uniqueIndex = null; for (DBSEntityConstraint id : identifiers) { if (id instanceof DBSEntityReferrer && id.getConstraintType() == DBSEntityConstraintType.PRIMARY_KEY) { return getEntityAttributes(monitor, (DBSEntityReferrer) id); } else if (id.getConstraintType().isUnique()) { uniqueId = id; } else if (id instanceof DBSTableIndex && ((DBSTableIndex) id).isUnique()) { uniqueId = id; } } return uniqueId instanceof DBSEntityReferrer ? getEntityAttributes(monitor, (DBSEntityReferrer)uniqueId) : Collections.<DBSTableColumn>emptyList(); } else { return Collections.emptyList(); } } public static boolean isIdentifierIndex(DBRProgressMonitor monitor, DBSTableIndex index) throws DBException { if (!index.isUnique()) { return false; } List<? extends DBSTableIndexColumn> attrs = index.getAttributeReferences(monitor); if (attrs == null || attrs.isEmpty()) { return false; } for (DBSTableIndexColumn col : attrs) { if (col.getTableColumn() == null || !col.getTableColumn().isRequired()) { // Do not use indexes with NULL columns (because they are not actually unique: #424) return false; } } return true; } public static boolean isIdentifierConstraint(DBRProgressMonitor monitor, DBSEntityConstraint constraint) throws DBException { if (constraint instanceof DBSEntityReferrer && constraint.getConstraintType().isUnique()) { List<? extends DBSEntityAttributeRef> attrs = ((DBSEntityReferrer) constraint).getAttributeReferences(monitor); if (attrs == null || attrs.isEmpty()) { return false; } for (DBSEntityAttributeRef col : attrs) { if (col.getAttribute() == null || !col.getAttribute().isRequired()) { // Do not use constraints with NULL columns (because they are not actually unique: #424) return false; } } return true; } return false; } public static DBSEntityConstraint findEntityConstraint(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntity entity, @NotNull Collection<? extends DBSEntityAttribute> attributes) throws DBException { // Check constraints Collection<? extends DBSEntityConstraint> constraints = entity.getConstraints(monitor); if (!CommonUtils.isEmpty(constraints)) { for (DBSEntityConstraint constraint : constraints) { if (constraint instanceof DBSEntityReferrer && referrerMatches(monitor, (DBSEntityReferrer)constraint, attributes)) { return constraint; } } } if (entity instanceof DBSTable) { Collection<? extends DBSTableIndex> indexes = ((DBSTable) entity).getIndexes(monitor); if (!CommonUtils.isEmpty(indexes)) { for (DBSTableIndex index : indexes) { if (index.isUnique() && referrerMatches(monitor, index, attributes)) { return index; } } } } return null; } public static boolean referrerMatches(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntityReferrer referrer, @NotNull Collection<? extends DBSEntityAttribute> attributes) throws DBException { final List<? extends DBSEntityAttributeRef> refs = referrer.getAttributeReferences(monitor); if (refs != null && !refs.isEmpty()) { Iterator<? extends DBSEntityAttribute> attrIterator = attributes.iterator(); for (DBSEntityAttributeRef ref : refs) { if (!attrIterator.hasNext()) { return false; } if (ref.getAttribute() == null || !CommonUtils.equalObjects(ref.getAttribute().getName(), attrIterator.next().getName())) { return false; } } return true; } return false; } @NotNull public static List<DBSEntityAttribute> getEntityAttributes(@NotNull DBRProgressMonitor monitor, @Nullable DBSEntityReferrer referrer) { Collection<? extends DBSEntityAttributeRef> constraintColumns = null; if (referrer != null) { try { constraintColumns = referrer.getAttributeReferences(monitor); } catch (DBException e) { log.warn("Error reading reference attributes", e); } } if (constraintColumns == null) { return Collections.emptyList(); } List<DBSEntityAttribute> attributes = new ArrayList<>(constraintColumns.size()); for (DBSEntityAttributeRef column : constraintColumns) { final DBSEntityAttribute attribute = column.getAttribute(); if (attribute != null) { attributes.add(attribute); } } return attributes; } @Nullable public static DBSEntityAttributeRef getConstraintAttribute(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntityReferrer constraint, @NotNull DBSEntityAttribute tableColumn) throws DBException { Collection<? extends DBSEntityAttributeRef> columns = constraint.getAttributeReferences(monitor); if (columns != null) { for (DBSEntityAttributeRef constraintColumn : columns) { if (constraintColumn.getAttribute() == tableColumn) { return constraintColumn; } } } return null; } @Nullable public static DBSEntityAttributeRef getConstraintAttribute(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntityReferrer constraint, @NotNull String columnName) throws DBException { Collection<? extends DBSEntityAttributeRef> columns = constraint.getAttributeReferences(monitor); if (columns != null) { for (DBSEntityAttributeRef constraintColumn : columns) { final DBSEntityAttribute attribute = constraintColumn.getAttribute(); if (attribute != null && attribute.getName().equals(columnName)) { return constraintColumn; } } } return null; } /** * Return reference column of referrer association (FK). * Assumes that columns in both constraints are in the same order. */ @Nullable public static DBSEntityAttribute getReferenceAttribute(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntityAssociation association, @NotNull DBSEntityAttribute tableColumn) throws DBException { final DBSEntityConstraint refConstr = association.getReferencedConstraint(); if (association instanceof DBSEntityReferrer && refConstr instanceof DBSEntityReferrer) { final Collection<? extends DBSEntityAttributeRef> ownAttrs = ((DBSEntityReferrer) association).getAttributeReferences(monitor); final Collection<? extends DBSEntityAttributeRef> refAttrs = ((DBSEntityReferrer) refConstr).getAttributeReferences(monitor); if (ownAttrs == null || refAttrs == null || ownAttrs.size() != refAttrs.size()) { log.error("Invalid internal state of referrer association"); return null; } final Iterator<? extends DBSEntityAttributeRef> ownIterator = ownAttrs.iterator(); final Iterator<? extends DBSEntityAttributeRef> refIterator = refAttrs.iterator(); while (ownIterator.hasNext()) { if (ownIterator.next().getAttribute() == tableColumn) { return refIterator.next().getAttribute(); } refIterator.next(); } } return null; } @NotNull public static DBCStatement makeStatement( @NotNull DBCExecutionSource executionSource, @NotNull DBCSession session, @NotNull DBCStatementType statementType, @NotNull String query, long offset, long maxRows) throws DBCException { SQLQuery sqlQuery = new SQLQuery(session.getDataSource(), query); return makeStatement( executionSource, session, statementType, sqlQuery, offset, maxRows); } @NotNull public static DBCStatement makeStatement( @NotNull DBCExecutionSource executionSource, @NotNull DBCSession session, @NotNull DBCStatementType statementType, @NotNull SQLQuery sqlQuery, long offset, long maxRows) throws DBCException { // We need to detect whether it is a plain select statement // or some DML. For DML statements we mustn't set limits // because it sets update rows limit [SQL Server] boolean selectQuery = sqlQuery.getType() == SQLQueryType.SELECT && sqlQuery.isPlainSelect(); final boolean hasLimits = selectQuery && offset >= 0 && maxRows > 0; DBCQueryTransformer limitTransformer = null, fetchAllTransformer = null; if (selectQuery) { DBCQueryTransformProvider transformProvider = DBUtils.getAdapter(DBCQueryTransformProvider.class, session.getDataSource()); if (transformProvider != null) { if (hasLimits) { if (session.getDataSource().getContainer().getPreferenceStore().getBoolean(ModelPreferences.RESULT_SET_MAX_ROWS_USE_SQL)) { limitTransformer = transformProvider.createQueryTransformer(DBCQueryTransformType.RESULT_SET_LIMIT); } } else if (offset <= 0 && maxRows <= 0) { fetchAllTransformer = transformProvider.createQueryTransformer(DBCQueryTransformType.FETCH_ALL_TABLE); } } } String queryText; if (hasLimits && limitTransformer != null) { limitTransformer.setParameters(offset, maxRows); queryText = limitTransformer.transformQueryString(sqlQuery); } else if (fetchAllTransformer != null) { queryText = fetchAllTransformer.transformQueryString(sqlQuery); } else { queryText = sqlQuery.getText(); } DBCStatement dbStat = statementType == DBCStatementType.SCRIPT ? createStatement(session, queryText, hasLimits) : makeStatement(session, queryText, hasLimits); dbStat.setStatementSource(executionSource); if (hasLimits || offset > 0) { if (limitTransformer == null) { // Set explicit limit - it is safe because we pretty sure that this is a plain SELECT query dbStat.setLimit(offset, maxRows); } else { limitTransformer.transformStatement(dbStat, 0); } } else if (fetchAllTransformer != null) { fetchAllTransformer.transformStatement(dbStat, 0); } return dbStat; } @NotNull public static DBCStatement createStatement( @NotNull DBCSession session, @NotNull String query, boolean scrollable) throws DBCException { DBCStatementType statementType = DBCStatementType.SCRIPT; query = SQLUtils.makeUnifiedLineFeeds(query); if (SQLUtils.isExecQuery(SQLUtils.getDialectFromObject(session.getDataSource()), query)) { statementType = DBCStatementType.EXEC; } return session.prepareStatement( statementType, query, scrollable && session.getDataSource().getInfo().supportsResultSetScroll(), false, false); } @NotNull public static DBCStatement makeStatement( @NotNull DBCSession session, @NotNull String query, boolean scrollable) throws DBCException { DBCStatementType statementType = DBCStatementType.QUERY; // Normalize query query = SQLUtils.makeUnifiedLineFeeds(query); if (SQLUtils.isExecQuery(SQLUtils.getDialectFromObject(session.getDataSource()), query)) { statementType = DBCStatementType.EXEC; } return session.prepareStatement( statementType, query, scrollable && session.getDataSource().getInfo().supportsResultSetScroll(), false, false); } public static void fireObjectUpdate(@NotNull DBSObject object) { fireObjectUpdate(object, null); } public static void fireObjectUpdate(DBSObject object, @Nullable Object data) { final DBPDataSourceContainer container = getContainer(object); if (container != null) { container.fireEvent(new DBPEvent(DBPEvent.Action.OBJECT_UPDATE, object, data)); } } public static void fireObjectUpdate(DBSObject object, boolean enabled) { final DBPDataSourceContainer container = getContainer(object); if (container != null) { container.fireEvent(new DBPEvent(DBPEvent.Action.OBJECT_UPDATE, object, enabled)); } } public static void fireObjectAdd(DBSObject object) { final DBPDataSourceContainer container = getContainer(object); if (container != null) { container.fireEvent(new DBPEvent(DBPEvent.Action.OBJECT_ADD, object)); } } public static void fireObjectRemove(DBSObject object) { final DBPDataSourceContainer container = getContainer(object); if (container != null) { container.fireEvent(new DBPEvent(DBPEvent.Action.OBJECT_REMOVE, object)); } } public static void fireObjectSelect(DBSObject object, boolean select) { final DBPDataSourceContainer container = getContainer(object); if (container != null) { container.fireEvent(new DBPEvent(DBPEvent.Action.OBJECT_SELECT, object, select)); } } /** * Refresh object in UI */ public static void fireObjectRefresh(DBSObject object) { // Select with true parameter is the same as refresh fireObjectSelect(object, true); } @NotNull public static String getObjectUniqueName(@NotNull DBSObject object) { if (object instanceof DBPUniqueObject) { return ((DBPUniqueObject) object).getUniqueName(); } else { return object.getName(); } } @Nullable public static DBSDataType findBestDataType(@NotNull Collection<? extends DBSDataType> allTypes, @NotNull String ... typeNames) { for (String testType : typeNames) { for (DBSDataType dataType : allTypes) { if (dataType.getName().equalsIgnoreCase(testType)) { return dataType; } } } return null; } @Nullable public static DBSDataType resolveDataType( @NotNull DBRProgressMonitor monitor, @NotNull DBPDataSource dataSource, @NotNull String fullTypeName) throws DBException { DBPDataTypeProvider dataTypeProvider = getAdapter(DBPDataTypeProvider.class, dataSource); if (dataTypeProvider == null) { // NoSuchElementException data type provider return null; } return dataTypeProvider.resolveDataType(monitor, fullTypeName); } @Nullable public static DBSDataType getLocalDataType( @NotNull DBPDataSource dataSource, @NotNull String fullTypeName) { DBPDataTypeProvider dataTypeProvider = getAdapter(DBPDataTypeProvider.class, dataSource); if (dataTypeProvider == null) { return null; } return dataTypeProvider.getLocalDataType(fullTypeName); } public static DBPObject getPublicObject(@NotNull DBPObject object) { if (object instanceof DBPDataSourceContainer) { return ((DBPDataSourceContainer) object).getDataSource(); } else { return object; } } @Nullable public static DBPDataSourceContainer getContainer(@Nullable DBSObject object) { if (object == null) { return null; } if (object instanceof DBPDataSourceContainer) { return (DBPDataSourceContainer) object; } final DBPDataSource dataSource = object.getDataSource(); return dataSource == null ? null : dataSource.getContainer(); } @NotNull public static DBPDataSourceRegistry getObjectRegistry(@NotNull DBSObject object) { DBPDataSourceContainer container; if (object instanceof DBPDataSourceContainer) { container = (DBPDataSourceContainer) object; } else { DBPDataSource dataSource = object.getDataSource(); container = dataSource.getContainer(); } return container.getRegistry(); } @NotNull public static IProject getObjectOwnerProject(DBSObject object) { return getObjectRegistry(object).getProject(); } @NotNull public static String getObjectShortName(Object object) { String strValue; if (object instanceof DBPNamedObject) { strValue = ((DBPNamedObject)object).getName(); } else { strValue = String.valueOf(object); } return strValue; } @NotNull public static String getObjectFullName(@NotNull DBPNamedObject object, DBPEvaluationContext context) { if (object instanceof DBPQualifiedObject) { return ((DBPQualifiedObject) object).getFullyQualifiedName(context); } else if (object instanceof DBSObject) { return getObjectFullName(((DBSObject) object).getDataSource(), object, context); } else { return object.getName(); } } @NotNull public static String getObjectFullName(@NotNull DBPDataSource dataSource, @NotNull DBPNamedObject object, DBPEvaluationContext context) { if (object instanceof DBPQualifiedObject) { return ((DBPQualifiedObject) object).getFullyQualifiedName(context); } else { return getQuotedIdentifier(dataSource, object.getName()); } } @NotNull public static String getFullTypeName(@NotNull DBSTypedObject typedObject) { String typeName = typedObject.getTypeName(); String typeModifiers = SQLUtils.getColumnTypeModifiers(typedObject, typeName, typedObject.getDataKind()); return typeModifiers == null ? typeName : (typeName + CommonUtils.notEmpty(typeModifiers)); } public static void releaseValue(@Nullable Object value) { if (value instanceof DBDValue) { ((DBDValue)value).release(); } } public static void resetValue(@Nullable Object value) { if (value instanceof DBDContent) { ((DBDContent)value).resetContents(); } } @NotNull public static DBCLogicalOperator[] getAttributeOperators(DBSTypedObject attribute) { if (attribute instanceof DBSTypedObjectEx) { DBSDataType dataType = ((DBSTypedObjectEx) attribute).getDataType(); if (dataType != null) { return dataType.getSupportedOperators(attribute); } } return getDefaultOperators(attribute); } @NotNull public static DBCLogicalOperator[] getDefaultOperators(DBSTypedObject attribute) { List<DBCLogicalOperator> operators = new ArrayList<>(); DBPDataKind dataKind = attribute.getDataKind(); if (attribute instanceof DBSAttributeBase && !((DBSAttributeBase)attribute).isRequired()) { operators.add(DBCLogicalOperator.IS_NULL); operators.add(DBCLogicalOperator.IS_NOT_NULL); } if (dataKind == DBPDataKind.BOOLEAN || dataKind == DBPDataKind.ROWID || dataKind == DBPDataKind.OBJECT || dataKind == DBPDataKind.BINARY) { operators.add(DBCLogicalOperator.EQUALS); operators.add(DBCLogicalOperator.NOT_EQUALS); } else if (dataKind == DBPDataKind.NUMERIC || dataKind == DBPDataKind.DATETIME || dataKind == DBPDataKind.STRING) { operators.add(DBCLogicalOperator.EQUALS); operators.add(DBCLogicalOperator.NOT_EQUALS); operators.add(DBCLogicalOperator.GREATER); //operators.add(DBCLogicalOperator.GREATER_EQUALS); operators.add(DBCLogicalOperator.LESS); //operators.add(DBCLogicalOperator.LESS_EQUALS); operators.add(DBCLogicalOperator.IN); } if (dataKind == DBPDataKind.STRING) { operators.add(DBCLogicalOperator.LIKE); } return operators.toArray(new DBCLogicalOperator[operators.size()]); } public static Object getRawValue(Object value) { if (value instanceof DBDValue) { return ((DBDValue)value).getRawValue(); } else { return value; } } public static boolean isIndexedAttribute(DBRProgressMonitor monitor, DBSEntityAttribute attribute) throws DBException { DBSEntity entity = attribute.getParentObject(); if (entity instanceof DBSTable) { Collection<? extends DBSTableIndex> indexes = ((DBSTable) entity).getIndexes(monitor); if (!CommonUtils.isEmpty(indexes)) { for (DBSTableIndex index : indexes) { if (getConstraintAttribute(monitor, index, attribute) != null) { return true; } } } } return false; } @Nullable public static DBCTransactionManager getTransactionManager(@Nullable DBCExecutionContext executionContext) { if (executionContext != null && executionContext.isConnected()) { return getAdapter(DBCTransactionManager.class, executionContext); } return null; } @SuppressWarnings("unchecked") @NotNull public static <T> Class<T> getDriverClass(@NotNull DBPDataSource dataSource, @NotNull String className) throws ClassNotFoundException { return (Class<T>) Class.forName(className, true, dataSource.getContainer().getDriver().getClassLoader()); } @SuppressWarnings("unchecked") @NotNull public static <T extends DBCSession> T openMetaSession(@NotNull DBRProgressMonitor monitor, @NotNull DBPDataSource dataSource, @NotNull String task) { return (T) dataSource.getDefaultContext(true).openSession(monitor, DBCExecutionPurpose.META, task); } @SuppressWarnings("unchecked") @NotNull public static <T extends DBCSession> T openUtilSession(@NotNull DBRProgressMonitor monitor, @NotNull DBPDataSource dataSource, @NotNull String task) { return (T) dataSource.getDefaultContext(false).openSession(monitor, DBCExecutionPurpose.UTIL, task); } @Nullable public static DBSObject getFromObject(Object object) { if (object instanceof DBSWrapper) { return ((DBSWrapper) object).getObject(); } else if (object instanceof DBSObject) { return (DBSObject) object; } else { return null; } } public static boolean isAtomicParameter(Object o) { return o == null || o instanceof CharSequence || o instanceof Number || o instanceof java.util.Date || o instanceof Boolean; } @NotNull public static DBSObject getDefaultOrActiveObject(@NotNull DBSInstance object) { DBSObject selectedObject = getActiveInstanceObject(object); return selectedObject == null ? object : selectedObject; } @Nullable public static DBSObject getActiveInstanceObject(@NotNull DBSInstance object) { return getSelectedObject(object, true); } @Nullable public static DBSObject getSelectedObject(@NotNull DBSObject object, boolean searchNested) { DBSObjectSelector objectSelector = getAdapter(DBSObjectSelector.class, object); if (objectSelector != null) { DBSObject selectedObject1 = objectSelector.getDefaultObject(); if (searchNested && selectedObject1 != null) { DBSObject nestedObject = getSelectedObject(selectedObject1, true); if (nestedObject != null) { return nestedObject; } } return selectedObject1; } return null; } @NotNull public static DBSObject[] getSelectedObjects(@NotNull DBSObject object) { DBSObjectSelector objectSelector = getAdapter(DBSObjectSelector.class, object); if (objectSelector != null) { DBSObject selectedObject1 = objectSelector.getDefaultObject(); if (selectedObject1 != null) { DBSObject nestedObject = getSelectedObject(selectedObject1, true); if (nestedObject != null) { return new DBSObject[] { selectedObject1, nestedObject }; } else { return new DBSObject[] { selectedObject1 }; } } } return new DBSObject[0]; } public static boolean isHiddenObject(Object object) { return object instanceof DBPHiddenObject && ((DBPHiddenObject) object).isHidden(); } public static DBDPseudoAttribute getRowIdAttribute(DBSEntity entity) { if (entity instanceof DBDPseudoAttributeContainer) { try { return DBDPseudoAttribute.getAttribute( ((DBDPseudoAttributeContainer) entity).getPseudoAttributes(), DBDPseudoAttributeType.ROWID); } catch (DBException e) { log.warn("Can't get pseudo attributes for '" + entity.getName() + "'", e); } } return null; } public static DBDPseudoAttribute getPseudoAttribute(DBSEntity entity, String attrName) { if (entity instanceof DBDPseudoAttributeContainer) { try { DBDPseudoAttribute[] pseudoAttributes = ((DBDPseudoAttributeContainer) entity).getPseudoAttributes(); if (pseudoAttributes != null && pseudoAttributes.length > 0) { for (int i = 0; i < pseudoAttributes.length; i++) { DBDPseudoAttribute pa = pseudoAttributes[i]; String attrId = pa.getAlias(); if (CommonUtils.isEmpty(attrId)) { attrId = pa.getName(); } if (attrId.equals(attrName)) { return pa; } } } } catch (DBException e) { log.warn("Can't get pseudo attributes for '" + entity.getName() + "'", e); } } return null; } public static boolean isPseudoAttribute(DBSAttributeBase attr) { return attr instanceof DBDAttributeBinding && ((DBDAttributeBinding) attr).isPseudoAttribute(); } public static <TYPE extends DBPNamedObject> Comparator<TYPE> nameComparator() { return new Comparator<TYPE>() { @Override public int compare(DBPNamedObject o1, DBPNamedObject o2) { return o1.getName().compareTo(o2.getName()); } }; } public static Comparator<? super DBSAttributeBase> orderComparator() { return new Comparator<DBSAttributeBase>() { @Override public int compare(DBSAttributeBase o1, DBSAttributeBase o2) { return o1.getOrdinalPosition() - o2.getOrdinalPosition(); } }; } public static <T extends DBPNamedObject> void orderObjects(@NotNull List<T> objects) { Collections.sort(objects, new Comparator<T>() { @Override public int compare(T o1, T o2) { String name1 = o1.getName(); String name2 = o2.getName(); return name1 == null && name2 == null ? 0 : (name1 == null ? -1 : (name2 == null ? 1 : name1.compareTo(name2))); } }); } public static String getClientApplicationName(DBPDataSourceContainer container, String purpose) { if (container.getPreferenceStore().getBoolean(ModelPreferences.META_CLIENT_NAME_OVERRIDE)) { return container.getPreferenceStore().getString(ModelPreferences.META_CLIENT_NAME_VALUE); } final String productTitle = GeneralUtils.getProductTitle(); return purpose == null ? productTitle : productTitle + " - " + purpose; } @NotNull public static DBPErrorAssistant.ErrorType discoverErrorType(@NotNull DBPDataSource dataSource, @NotNull Throwable error) { DBPErrorAssistant errorAssistant = getAdapter(DBPErrorAssistant.class, dataSource); if (errorAssistant != null) { return ((DBPErrorAssistant) dataSource).discoverErrorType(error); } return DBPErrorAssistant.ErrorType.NORMAL; } }
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/DBUtils.java
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider ([email protected]) * * 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.jkiss.dbeaver.model; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IAdaptable; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.ModelPreferences; import org.jkiss.dbeaver.model.app.DBPDataSourceRegistry; import org.jkiss.dbeaver.model.data.*; import org.jkiss.dbeaver.model.exec.*; import org.jkiss.dbeaver.model.impl.data.DefaultValueHandler; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.sql.*; import org.jkiss.dbeaver.model.struct.*; import org.jkiss.dbeaver.model.struct.rdb.*; import org.jkiss.dbeaver.utils.GeneralUtils; import org.jkiss.utils.CommonUtils; import java.util.*; /** * DBUtils */ public final class DBUtils { private static final Log log = Log.getLog(DBUtils.class); @NotNull public static String getQuotedIdentifier(@NotNull DBSObject object) { return getQuotedIdentifier(object.getDataSource(), object.getName()); } public static boolean isQuotedIdentifier(@NotNull DBPDataSource dataSource, @NotNull String str) { if (dataSource instanceof SQLDataSource) { final String quote = ((SQLDataSource) dataSource).getSQLDialect().getIdentifierQuoteString(); return quote != null && str.startsWith(quote) && str.endsWith(quote); } else { return false; } } @NotNull public static String getUnQuotedIdentifier(@NotNull DBPDataSource dataSource, @NotNull String str) { if (dataSource instanceof SQLDataSource) { String quote = ((SQLDataSource) dataSource).getSQLDialect().getIdentifierQuoteString(); if (quote == null) { quote = SQLConstants.DEFAULT_IDENTIFIER_QUOTE; } if (str.startsWith(quote) && str.endsWith(quote)) { return str.substring(quote.length(), str.length() - quote.length()); } } return str; } @NotNull public static String getUnQuotedIdentifier(@NotNull String str, String quote) { if (quote != null && str.startsWith(quote) && str.endsWith(quote)) { return str.substring(quote.length(), str.length() - quote.length()); } return str; } @NotNull public static String getQuotedIdentifier(@NotNull DBPDataSource dataSource, @NotNull String str) { if (dataSource instanceof SQLDataSource) { return getQuotedIdentifier((SQLDataSource)dataSource, str, true); } else { return str; } } @NotNull public static String getQuotedIdentifier(@NotNull SQLDataSource dataSource, @NotNull String str, boolean caseSensitiveNames) { final SQLDialect sqlDialect = dataSource.getSQLDialect(); String quoteString = sqlDialect.getIdentifierQuoteString(); if (quoteString == null) { return str; } if (str.startsWith(quoteString) && str.endsWith(quoteString)) { // Already quoted return str; } // Check for keyword conflict final DBPKeywordType keywordType = sqlDialect.getKeywordType(str); boolean hasBadChars = (keywordType == DBPKeywordType.KEYWORD || keywordType == DBPKeywordType.TYPE) && sqlDialect.isQuoteReservedWords(); if (!hasBadChars && !str.isEmpty()) { hasBadChars = Character.isDigit(str.charAt(0)); } if (caseSensitiveNames) { // Check for case of quoted idents. Do not check for unquoted case - we don't need to quote em anyway if (!hasBadChars && sqlDialect.supportsQuotedMixedCase()) { // See how unquoted idents are stored // If passed identifier case differs from unquoted then we need to escape it if (sqlDialect.storesUnquotedCase() == DBPIdentifierCase.UPPER) { hasBadChars = !str.equals(str.toUpperCase()); } else if (sqlDialect.storesUnquotedCase() == DBPIdentifierCase.LOWER) { hasBadChars = !str.equals(str.toLowerCase()); } } } // Check for bad characters if (!hasBadChars && !str.isEmpty()) { if (str.charAt(0) == '_') { hasBadChars = true; } else { for (int i = 0; i < str.length(); i++) { if (!sqlDialect.validUnquotedCharacter(str.charAt(i))) { hasBadChars = true; break; } } } } if (!hasBadChars) { return str; } // Escape quote chars if (str.contains(quoteString)) { str = str.replace(quoteString, quoteString + quoteString); } return quoteString + str + quoteString; } @NotNull public static String getFullQualifiedName(@NotNull DBPDataSource dataSource, @NotNull DBPNamedObject ... path) { StringBuilder name = new StringBuilder(20 * path.length); if (!(dataSource instanceof SQLDataSource)) { // It is not SQL identifier, let's just make it simple then for (DBPNamedObject namePart : path) { if (name.length() > 0) { name.append('.'); } name.append(namePart.getName()); } } else { final SQLDialect sqlDialect = ((SQLDataSource) dataSource).getSQLDialect(); DBPNamedObject parent = null; for (DBPNamedObject namePart : path) { if (namePart == null) { continue; } if (namePart instanceof DBSCatalog && ((sqlDialect.getCatalogUsage() & SQLDialect.USAGE_DML) == 0)) { // Do not use catalog name in FQ name continue; } if (namePart instanceof DBSSchema && ((sqlDialect.getSchemaUsage() & SQLDialect.USAGE_DML) == 0)) { // Do not use schema name in FQ name continue; } // Check for valid object name if (!isValidObjectName(namePart.getName())) { continue; } if (name.length() > 0) { if (parent instanceof DBSCatalog) { if (!sqlDialect.isCatalogAtStart()) { log.warn("Catalog name should be at the start of full-qualified name!"); } name.append(sqlDialect.getCatalogSeparator()); } else { name.append(sqlDialect.getStructSeparator()); } } name.append(DBUtils.getQuotedIdentifier(dataSource, namePart.getName())); parent = namePart; } } return name.toString(); } @NotNull public static String getSimpleQualifiedName(@NotNull Object... names) { StringBuilder name = new StringBuilder(names.length * 16); for (Object namePart : names) { if (namePart == null) { continue; } if (name.length() > 0) { name.append('.'); } name.append(namePart); } return name.toString(); } /** * Checks that object has valid object name. * Some DB objects have dummy names (like "" or ".") - we won't use them for certain purposes. * @param name object name * @return true or false */ public static boolean isValidObjectName(@Nullable String name) { if (name == null || name.isEmpty()) { return false; } boolean validName = false; for (int i = 0; i < name.length(); i++) { if (Character.isLetterOrDigit(name.charAt(i))) { validName = true; break; } } return validName; } /** * Finds catalog, schema or table within specified object container * @param monitor progress monitor * @param rootSC container * @param catalogName catalog name (optional) * @param schemaName schema name (optional) * @param objectName table name (optional) * @return found object or null * @throws DBException */ @Nullable public static DBSObject getObjectByPath( @NotNull DBRProgressMonitor monitor, @NotNull DBSObjectContainer rootSC, @Nullable String catalogName, @Nullable String schemaName, @Nullable String objectName) throws DBException { if (!CommonUtils.isEmpty(catalogName) && !CommonUtils.isEmpty(schemaName)) { // We have both both - just search both DBSObject catalog = rootSC.getChild(monitor, catalogName); if (!(catalog instanceof DBSObjectContainer)) { return null; } rootSC = (DBSObjectContainer) catalog; DBSObject schema = rootSC.getChild(monitor, schemaName); if (!(schema instanceof DBSObjectContainer)) { return null; } rootSC = (DBSObjectContainer) schema; } else if (!CommonUtils.isEmpty(catalogName) || !CommonUtils.isEmpty(schemaName)) { // One container name String containerName = !CommonUtils.isEmpty(catalogName) ? catalogName : schemaName; DBSObject sc = rootSC.getChild(monitor, containerName); if (!(sc instanceof DBSObjectContainer)) { // Not found - try to find in selected object DBSObject selectedObject = getSelectedObject(rootSC, false); if (selectedObject instanceof DBSObjectContainer) { sc = ((DBSObjectContainer) selectedObject).getChild(monitor, containerName); } if (!(sc instanceof DBSObjectContainer)) { return null; } } rootSC = (DBSObjectContainer) sc; } if (objectName == null) { return rootSC; } final DBSObject object = rootSC.getChild(monitor, objectName); if (object instanceof DBSEntity) { return object; } else { // Child is not an entity. May be catalog/schema names was omitted. // Try to use selected object DBSObject selectedObject = DBUtils.getSelectedObject(rootSC, true); if (selectedObject instanceof DBSObjectContainer) { return ((DBSObjectContainer) selectedObject).getChild(monitor, objectName); } // Table container not found return object; } } @Nullable public static DBSObject findNestedObject( @NotNull DBRProgressMonitor monitor, @NotNull DBSObjectContainer parent, @NotNull List<String> names) throws DBException { for (int i = 0; i < names.size(); i++) { String childName = names.get(i); DBSObject child = parent.getChild(monitor, childName); if (child == null) { DBSObjectSelector selector = DBUtils.getAdapter(DBSObjectSelector.class, parent); if (selector != null) { DBSObjectContainer container = DBUtils.getAdapter(DBSObjectContainer.class, selector.getDefaultObject()); if (container != null) { parent = container; child = parent.getChild(monitor, childName); } } } if (child == null) { break; } if (i == names.size() - 1) { return child; } if (child instanceof DBSObjectContainer) { parent = DBSObjectContainer.class.cast(child); } else { break; } } return null; } /** * Finds object by its name (case insensitive) * * @param theList object list * @param objectName object name * @return object or null */ @Nullable public static <T extends DBPNamedObject> T findObject(@Nullable Collection<T> theList, String objectName) { if (theList != null && !theList.isEmpty()) { for (T object : theList) { if (object.getName().equalsIgnoreCase(objectName)) { return object; } } } return null; } @Nullable public static <T extends DBPNamedObject> T findObject(@Nullable List<T> theList, String objectName) { if (theList != null) { int size = theList.size(); for (int i = 0; i < size; i++) { if (theList.get(i).getName().equalsIgnoreCase(objectName)) { return theList.get(i); } } } return null; } /** * Finds object by its name (case insensitive) * * @param theList object list * @param objectName object name * @return object or null */ @Nullable public static <T extends DBPNamedObject> List<T> findObjects(@Nullable Collection<T> theList, @Nullable String objectName) { if (theList != null && !theList.isEmpty()) { List<T> result = new ArrayList<>(); for (T object : theList) { if (object.getName().equalsIgnoreCase(objectName)) { result.add(object); } } return result; } return null; } @Nullable public static <T> T getAdapter(@NotNull Class<T> adapterType, @Nullable Object object) { if (object instanceof DBPDataSourceContainer) { // Root object's parent is data source container (not datasource) // So try to get adapter from real datasource object object = ((DBPDataSourceContainer)object).getDataSource(); } if (object == null) { return null; } if (adapterType.isAssignableFrom(object.getClass())) { return adapterType.cast(object); } else if (object instanceof IAdaptable) { return adapterType.cast(((IAdaptable)object).getAdapter(adapterType)); } else { return null; } } @Nullable public static <T> T getParentAdapter(@NotNull Class<T> i, DBSObject object) { if (object == null) { return null; } DBSObject parent = object.getParentObject(); if (parent == null) { return null; } T adapter = getAdapter(i, parent); // In some cases parent's adapter is object itself (e.g. DS maybe DS adapter of container) return adapter == object ? null : adapter; } /** * Search for virtual entity descriptor * @param object object * @return object path */ @NotNull public static DBSObject[] getObjectPath(@NotNull DBSObject object, boolean includeSelf) { int depth = 0; final DBSObject root = includeSelf ? object : object.getParentObject(); for (DBSObject obj = root; obj != null; obj = obj.getParentObject()) { depth++; } DBSObject[] path = new DBSObject[depth]; for (DBSObject obj = root; obj != null; obj = obj.getParentObject()) { path[depth-- - 1] = obj; } return path; } public static boolean isNullValue(@Nullable Object value) { return (value == null || (value instanceof DBDValue && ((DBDValue) value).isNull())); } @Nullable public static Object makeNullValue(@NotNull DBCSession session, @NotNull DBDValueHandler valueHandler, @NotNull DBSTypedObject type) throws DBCException { return valueHandler.getValueFromObject(session, type, null, false); } @NotNull public static DBDAttributeBindingMeta getAttributeBinding(@NotNull DBCSession session, @NotNull DBCAttributeMetaData attributeMeta) { return new DBDAttributeBindingMeta(session, attributeMeta); } @NotNull public static DBDValueHandler findValueHandler(@NotNull DBCSession session, @NotNull DBSTypedObject column) { return findValueHandler(session.getDataSource(), session, column); } @NotNull public static DBDValueHandler findValueHandler(@NotNull DBPDataSource dataSource, @NotNull DBSTypedObject column) { return findValueHandler(dataSource, dataSource.getContainer(), column); } @NotNull public static DBDValueHandler findValueHandler(@NotNull DBPDataSource dataSource, @Nullable DBDPreferences preferences, @NotNull DBSTypedObject column) { DBDValueHandler typeHandler = null; // Get handler provider from datasource DBDValueHandlerProvider typeProvider = getAdapter(DBDValueHandlerProvider.class, dataSource); if (typeProvider != null) { typeHandler = typeProvider.getValueHandler(dataSource, preferences, column); if (typeHandler != null) { return typeHandler; } } // Get handler provider from registry typeProvider = dataSource.getContainer().getPlatform().getValueHandlerRegistry().getDataTypeProvider( dataSource, column); if (typeProvider != null) { typeHandler = typeProvider.getValueHandler(dataSource, preferences, column); } // Use default handler if (typeHandler == null) { if (preferences == null) { typeHandler = DefaultValueHandler.INSTANCE; } else { typeHandler = preferences.getDefaultValueHandler(); } } return typeHandler; } /** * Identifying association is an association which associated entity's attributes are included into owner entity primary key. I.e. they * identifies entity. */ public static boolean isIdentifyingAssociation(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntityAssociation association) throws DBException { if (!(association instanceof DBSEntityReferrer)) { return false; } final DBSEntityReferrer referrer = (DBSEntityReferrer)association; final DBSEntity refEntity = association.getAssociatedEntity(); final DBSEntity ownerEntity = association.getParentObject(); assert ownerEntity != null; if (refEntity == ownerEntity) { // Can't migrate into itself return false; } // Migrating association is: if all referenced attributes are included in some unique key List<DBSEntityAttribute> ownAttrs = getEntityAttributes(monitor, referrer); Collection<? extends DBSEntityConstraint> constraints = ownerEntity.getConstraints(monitor); if (constraints != null) { boolean hasPrimaryKey = false; for (DBSEntityConstraint constraint : constraints) { if (constraint.getConstraintType() == DBSEntityConstraintType.PRIMARY_KEY) { hasPrimaryKey = true; break; } } for (DBSEntityConstraint constraint : constraints) { if (constraint instanceof DBSEntityReferrer && ((hasPrimaryKey && constraint.getConstraintType() == DBSEntityConstraintType.PRIMARY_KEY) || (!hasPrimaryKey && constraint.getConstraintType().isUnique()))) { List<DBSEntityAttribute> constAttrs = getEntityAttributes(monitor, (DBSEntityReferrer) constraint); boolean included = true; for (DBSEntityAttribute attr : ownAttrs) { if (!constAttrs.contains(attr)) { included = false; break; } } if (included) { return true; } } } } return false; } @NotNull public static String getDefaultDataTypeName(@NotNull DBPDataSource dataSource, DBPDataKind dataKind) { if (dataSource instanceof DBPDataTypeProvider) { return ((DBPDataTypeProvider) dataSource).getDefaultDataTypeName(dataKind); } else { // Unsupported data kind return "?"; } } @Nullable public static DBDAttributeBinding findBinding(@NotNull Collection<DBDAttributeBinding> bindings, @NotNull DBSAttributeBase attribute) { for (DBDAttributeBinding binding : bindings) { if (binding.matches(attribute, true)) { return binding; } List<DBDAttributeBinding> nestedBindings = binding.getNestedBindings(); if (nestedBindings != null) { DBDAttributeBinding subBinding = findBinding(nestedBindings, attribute); if (subBinding != null) { return subBinding; } } } return null; } @Nullable public static DBDAttributeBinding findBinding(@NotNull DBDAttributeBinding[] bindings, @Nullable DBSAttributeBase attribute) { if (attribute == null) { return null; } for (DBDAttributeBinding binding : bindings) { if (binding.matches(attribute, true)) { return binding; } List<DBDAttributeBinding> nestedBindings = binding.getNestedBindings(); if (nestedBindings != null) { DBDAttributeBinding subBinding = findBinding(nestedBindings, attribute); if (subBinding != null) { return subBinding; } } } return null; } @NotNull public static List<DBSEntityReferrer> getAttributeReferrers(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntityAttribute entityAttribute) throws DBException { DBSEntity entity = entityAttribute.getParentObject(); assert entity != null; List<DBSEntityReferrer> refs = null; Collection<? extends DBSEntityAssociation> associations = entity.getAssociations(monitor); if (associations != null) { for (DBSEntityAssociation fk : associations) { if (fk instanceof DBSEntityReferrer && DBUtils.getConstraintAttribute(monitor, (DBSEntityReferrer) fk, entityAttribute) != null) { if (refs == null) { refs = new ArrayList<>(); } refs.add((DBSEntityReferrer)fk); } } } return refs != null ? refs : Collections.<DBSEntityReferrer>emptyList(); } @NotNull public static Collection<? extends DBSEntityAttribute> getBestTableIdentifier(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntity entity) throws DBException { if (entity instanceof DBSTable && ((DBSTable) entity).isView()) { return Collections.emptyList(); } if (CommonUtils.isEmpty(entity.getAttributes(monitor))) { return Collections.emptyList(); } List<DBSEntityConstraint> identifiers = new ArrayList<>(); // Check indexes if (entity instanceof DBSTable) { try { Collection<? extends DBSTableIndex> indexes = ((DBSTable)entity).getIndexes(monitor); if (!CommonUtils.isEmpty(indexes)) { for (DBSTableIndex index : indexes) { if (isIdentifierIndex(monitor, index)) { identifiers.add(index); } } } } catch (DBException e) { log.debug(e); } } // Check constraints only if no unique indexes found if (identifiers.isEmpty()) { Collection<? extends DBSEntityConstraint> uniqueKeys = entity.getConstraints(monitor); if (uniqueKeys != null) { for (DBSEntityConstraint constraint : uniqueKeys) { if (isIdentifierConstraint(monitor, constraint)) { identifiers.add(constraint); } } } } if (!identifiers.isEmpty()) { // Find PK or unique key DBSEntityConstraint uniqueId = null; //DBSEntityConstraint uniqueIndex = null; for (DBSEntityConstraint id : identifiers) { if (id instanceof DBSEntityReferrer && id.getConstraintType() == DBSEntityConstraintType.PRIMARY_KEY) { return getEntityAttributes(monitor, (DBSEntityReferrer) id); } else if (id.getConstraintType().isUnique()) { uniqueId = id; } else if (id instanceof DBSTableIndex && ((DBSTableIndex) id).isUnique()) { uniqueId = id; } } return uniqueId instanceof DBSEntityReferrer ? getEntityAttributes(monitor, (DBSEntityReferrer)uniqueId) : Collections.<DBSTableColumn>emptyList(); } else { return Collections.emptyList(); } } public static boolean isIdentifierIndex(DBRProgressMonitor monitor, DBSTableIndex index) throws DBException { if (!index.isUnique()) { return false; } List<? extends DBSTableIndexColumn> attrs = index.getAttributeReferences(monitor); if (attrs == null || attrs.isEmpty()) { return false; } for (DBSTableIndexColumn col : attrs) { if (col.getTableColumn() == null || !col.getTableColumn().isRequired()) { // Do not use indexes with NULL columns (because they are not actually unique: #424) return false; } } return true; } public static boolean isIdentifierConstraint(DBRProgressMonitor monitor, DBSEntityConstraint constraint) throws DBException { if (constraint instanceof DBSEntityReferrer && constraint.getConstraintType().isUnique()) { List<? extends DBSEntityAttributeRef> attrs = ((DBSEntityReferrer) constraint).getAttributeReferences(monitor); if (attrs == null || attrs.isEmpty()) { return false; } for (DBSEntityAttributeRef col : attrs) { if (col.getAttribute() == null || !col.getAttribute().isRequired()) { // Do not use constraints with NULL columns (because they are not actually unique: #424) return false; } } return true; } return false; } public static DBSEntityConstraint findEntityConstraint(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntity entity, @NotNull Collection<? extends DBSEntityAttribute> attributes) throws DBException { // Check constraints Collection<? extends DBSEntityConstraint> constraints = entity.getConstraints(monitor); if (!CommonUtils.isEmpty(constraints)) { for (DBSEntityConstraint constraint : constraints) { if (constraint instanceof DBSEntityReferrer && referrerMatches(monitor, (DBSEntityReferrer)constraint, attributes)) { return constraint; } } } if (entity instanceof DBSTable) { Collection<? extends DBSTableIndex> indexes = ((DBSTable) entity).getIndexes(monitor); if (!CommonUtils.isEmpty(indexes)) { for (DBSTableIndex index : indexes) { if (index.isUnique() && referrerMatches(monitor, index, attributes)) { return index; } } } } return null; } public static boolean referrerMatches(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntityReferrer referrer, @NotNull Collection<? extends DBSEntityAttribute> attributes) throws DBException { final List<? extends DBSEntityAttributeRef> refs = referrer.getAttributeReferences(monitor); if (refs != null && !refs.isEmpty()) { Iterator<? extends DBSEntityAttribute> attrIterator = attributes.iterator(); for (DBSEntityAttributeRef ref : refs) { if (!attrIterator.hasNext()) { return false; } if (ref.getAttribute() == null || !CommonUtils.equalObjects(ref.getAttribute().getName(), attrIterator.next().getName())) { return false; } } return true; } return false; } @NotNull public static List<DBSEntityAttribute> getEntityAttributes(@NotNull DBRProgressMonitor monitor, @Nullable DBSEntityReferrer referrer) { Collection<? extends DBSEntityAttributeRef> constraintColumns = null; if (referrer != null) { try { constraintColumns = referrer.getAttributeReferences(monitor); } catch (DBException e) { log.warn("Error reading reference attributes", e); } } if (constraintColumns == null) { return Collections.emptyList(); } List<DBSEntityAttribute> attributes = new ArrayList<>(constraintColumns.size()); for (DBSEntityAttributeRef column : constraintColumns) { final DBSEntityAttribute attribute = column.getAttribute(); if (attribute != null) { attributes.add(attribute); } } return attributes; } @Nullable public static DBSEntityAttributeRef getConstraintAttribute(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntityReferrer constraint, @NotNull DBSEntityAttribute tableColumn) throws DBException { Collection<? extends DBSEntityAttributeRef> columns = constraint.getAttributeReferences(monitor); if (columns != null) { for (DBSEntityAttributeRef constraintColumn : columns) { if (constraintColumn.getAttribute() == tableColumn) { return constraintColumn; } } } return null; } @Nullable public static DBSEntityAttributeRef getConstraintAttribute(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntityReferrer constraint, @NotNull String columnName) throws DBException { Collection<? extends DBSEntityAttributeRef> columns = constraint.getAttributeReferences(monitor); if (columns != null) { for (DBSEntityAttributeRef constraintColumn : columns) { final DBSEntityAttribute attribute = constraintColumn.getAttribute(); if (attribute != null && attribute.getName().equals(columnName)) { return constraintColumn; } } } return null; } /** * Return reference column of referrer association (FK). * Assumes that columns in both constraints are in the same order. */ @Nullable public static DBSEntityAttribute getReferenceAttribute(@NotNull DBRProgressMonitor monitor, @NotNull DBSEntityAssociation association, @NotNull DBSEntityAttribute tableColumn) throws DBException { final DBSEntityConstraint refConstr = association.getReferencedConstraint(); if (association instanceof DBSEntityReferrer && refConstr instanceof DBSEntityReferrer) { final Collection<? extends DBSEntityAttributeRef> ownAttrs = ((DBSEntityReferrer) association).getAttributeReferences(monitor); final Collection<? extends DBSEntityAttributeRef> refAttrs = ((DBSEntityReferrer) refConstr).getAttributeReferences(monitor); if (ownAttrs == null || refAttrs == null || ownAttrs.size() != refAttrs.size()) { log.error("Invalid internal state of referrer association"); return null; } final Iterator<? extends DBSEntityAttributeRef> ownIterator = ownAttrs.iterator(); final Iterator<? extends DBSEntityAttributeRef> refIterator = refAttrs.iterator(); while (ownIterator.hasNext()) { if (ownIterator.next().getAttribute() == tableColumn) { return refIterator.next().getAttribute(); } refIterator.next(); } } return null; } @NotNull public static DBCStatement makeStatement( @NotNull DBCExecutionSource executionSource, @NotNull DBCSession session, @NotNull DBCStatementType statementType, @NotNull String query, long offset, long maxRows) throws DBCException { SQLQuery sqlQuery = new SQLQuery(session.getDataSource(), query); return makeStatement( executionSource, session, statementType, sqlQuery, offset, maxRows); } @NotNull public static DBCStatement makeStatement( @NotNull DBCExecutionSource executionSource, @NotNull DBCSession session, @NotNull DBCStatementType statementType, @NotNull SQLQuery sqlQuery, long offset, long maxRows) throws DBCException { // We need to detect whether it is a plain select statement // or some DML. For DML statements we mustn't set limits // because it sets update rows limit [SQL Server] boolean selectQuery = sqlQuery.getType() == SQLQueryType.SELECT && sqlQuery.isPlainSelect(); final boolean hasLimits = selectQuery && offset >= 0 && maxRows > 0; DBCQueryTransformer limitTransformer = null, fetchAllTransformer = null; if (selectQuery) { DBCQueryTransformProvider transformProvider = DBUtils.getAdapter(DBCQueryTransformProvider.class, session.getDataSource()); if (transformProvider != null) { if (hasLimits) { if (session.getDataSource().getContainer().getPreferenceStore().getBoolean(ModelPreferences.RESULT_SET_MAX_ROWS_USE_SQL)) { limitTransformer = transformProvider.createQueryTransformer(DBCQueryTransformType.RESULT_SET_LIMIT); } } else if (offset <= 0 && maxRows <= 0) { fetchAllTransformer = transformProvider.createQueryTransformer(DBCQueryTransformType.FETCH_ALL_TABLE); } } } String queryText; if (hasLimits && limitTransformer != null) { limitTransformer.setParameters(offset, maxRows); queryText = limitTransformer.transformQueryString(sqlQuery); } else if (fetchAllTransformer != null) { queryText = fetchAllTransformer.transformQueryString(sqlQuery); } else { queryText = sqlQuery.getText(); } DBCStatement dbStat = statementType == DBCStatementType.SCRIPT ? createStatement(session, queryText, hasLimits) : makeStatement(session, queryText, hasLimits); dbStat.setStatementSource(executionSource); if (hasLimits || offset > 0) { if (limitTransformer == null) { // Set explicit limit - it is safe because we pretty sure that this is a plain SELECT query dbStat.setLimit(offset, maxRows); } else { limitTransformer.transformStatement(dbStat, 0); } } else if (fetchAllTransformer != null) { fetchAllTransformer.transformStatement(dbStat, 0); } return dbStat; } @NotNull public static DBCStatement createStatement( @NotNull DBCSession session, @NotNull String query, boolean scrollable) throws DBCException { DBCStatementType statementType = DBCStatementType.SCRIPT; query = SQLUtils.makeUnifiedLineFeeds(query); if (SQLUtils.isExecQuery(SQLUtils.getDialectFromObject(session.getDataSource()), query)) { statementType = DBCStatementType.EXEC; } return session.prepareStatement( statementType, query, scrollable && session.getDataSource().getInfo().supportsResultSetScroll(), false, false); } @NotNull public static DBCStatement makeStatement( @NotNull DBCSession session, @NotNull String query, boolean scrollable) throws DBCException { DBCStatementType statementType = DBCStatementType.QUERY; // Normalize query query = SQLUtils.makeUnifiedLineFeeds(query); if (SQLUtils.isExecQuery(SQLUtils.getDialectFromObject(session.getDataSource()), query)) { statementType = DBCStatementType.EXEC; } return session.prepareStatement( statementType, query, scrollable && session.getDataSource().getInfo().supportsResultSetScroll(), false, false); } public static void fireObjectUpdate(@NotNull DBSObject object) { fireObjectUpdate(object, null); } public static void fireObjectUpdate(DBSObject object, @Nullable Object data) { final DBPDataSourceContainer container = getContainer(object); if (container != null) { container.fireEvent(new DBPEvent(DBPEvent.Action.OBJECT_UPDATE, object, data)); } } public static void fireObjectUpdate(DBSObject object, boolean enabled) { final DBPDataSourceContainer container = getContainer(object); if (container != null) { container.fireEvent(new DBPEvent(DBPEvent.Action.OBJECT_UPDATE, object, enabled)); } } public static void fireObjectAdd(DBSObject object) { final DBPDataSourceContainer container = getContainer(object); if (container != null) { container.fireEvent(new DBPEvent(DBPEvent.Action.OBJECT_ADD, object)); } } public static void fireObjectRemove(DBSObject object) { final DBPDataSourceContainer container = getContainer(object); if (container != null) { container.fireEvent(new DBPEvent(DBPEvent.Action.OBJECT_REMOVE, object)); } } public static void fireObjectSelect(DBSObject object, boolean select) { final DBPDataSourceContainer container = getContainer(object); if (container != null) { container.fireEvent(new DBPEvent(DBPEvent.Action.OBJECT_SELECT, object, select)); } } /** * Refresh object in UI */ public static void fireObjectRefresh(DBSObject object) { // Select with true parameter is the same as refresh fireObjectSelect(object, true); } @NotNull public static String getObjectUniqueName(@NotNull DBSObject object) { if (object instanceof DBPUniqueObject) { return ((DBPUniqueObject) object).getUniqueName(); } else { return object.getName(); } } @Nullable public static DBSDataType findBestDataType(@NotNull Collection<? extends DBSDataType> allTypes, @NotNull String ... typeNames) { for (String testType : typeNames) { for (DBSDataType dataType : allTypes) { if (dataType.getName().equalsIgnoreCase(testType)) { return dataType; } } } return null; } @Nullable public static DBSDataType resolveDataType( @NotNull DBRProgressMonitor monitor, @NotNull DBPDataSource dataSource, @NotNull String fullTypeName) throws DBException { DBPDataTypeProvider dataTypeProvider = getAdapter(DBPDataTypeProvider.class, dataSource); if (dataTypeProvider == null) { // NoSuchElementException data type provider return null; } return dataTypeProvider.resolveDataType(monitor, fullTypeName); } @Nullable public static DBSDataType getLocalDataType( @NotNull DBPDataSource dataSource, @NotNull String fullTypeName) { DBPDataTypeProvider dataTypeProvider = getAdapter(DBPDataTypeProvider.class, dataSource); if (dataTypeProvider == null) { return null; } return dataTypeProvider.getLocalDataType(fullTypeName); } public static DBPObject getPublicObject(@NotNull DBPObject object) { if (object instanceof DBPDataSourceContainer) { return ((DBPDataSourceContainer) object).getDataSource(); } else { return object; } } @Nullable public static DBPDataSourceContainer getContainer(@Nullable DBSObject object) { if (object == null) { return null; } if (object instanceof DBPDataSourceContainer) { return (DBPDataSourceContainer) object; } final DBPDataSource dataSource = object.getDataSource(); return dataSource == null ? null : dataSource.getContainer(); } @NotNull public static DBPDataSourceRegistry getObjectRegistry(@NotNull DBSObject object) { DBPDataSourceContainer container; if (object instanceof DBPDataSourceContainer) { container = (DBPDataSourceContainer) object; } else { DBPDataSource dataSource = object.getDataSource(); container = dataSource.getContainer(); } return container.getRegistry(); } @NotNull public static IProject getObjectOwnerProject(DBSObject object) { return getObjectRegistry(object).getProject(); } @NotNull public static String getObjectShortName(Object object) { String strValue; if (object instanceof DBPNamedObject) { strValue = ((DBPNamedObject)object).getName(); } else { strValue = String.valueOf(object); } return strValue; } @NotNull public static String getObjectFullName(@NotNull DBPNamedObject object, DBPEvaluationContext context) { if (object instanceof DBPQualifiedObject) { return ((DBPQualifiedObject) object).getFullyQualifiedName(context); } else if (object instanceof DBSObject) { return getObjectFullName(((DBSObject) object).getDataSource(), object, context); } else { return object.getName(); } } @NotNull public static String getObjectFullName(@NotNull DBPDataSource dataSource, @NotNull DBPNamedObject object, DBPEvaluationContext context) { if (object instanceof DBPQualifiedObject) { return ((DBPQualifiedObject) object).getFullyQualifiedName(context); } else { return getQuotedIdentifier(dataSource, object.getName()); } } @NotNull public static String getFullTypeName(@NotNull DBSTypedObject typedObject) { String typeName = typedObject.getTypeName(); String typeModifiers = SQLUtils.getColumnTypeModifiers(typedObject, typeName, typedObject.getDataKind()); return typeModifiers == null ? typeName : (typeName + CommonUtils.notEmpty(typeModifiers)); } public static void releaseValue(@Nullable Object value) { if (value instanceof DBDValue) { ((DBDValue)value).release(); } } public static void resetValue(@Nullable Object value) { if (value instanceof DBDContent) { ((DBDContent)value).resetContents(); } } @NotNull public static DBCLogicalOperator[] getAttributeOperators(DBSTypedObject attribute) { if (attribute instanceof DBSTypedObjectEx) { DBSDataType dataType = ((DBSTypedObjectEx) attribute).getDataType(); if (dataType != null) { return dataType.getSupportedOperators(attribute); } } return getDefaultOperators(attribute); } @NotNull public static DBCLogicalOperator[] getDefaultOperators(DBSTypedObject attribute) { List<DBCLogicalOperator> operators = new ArrayList<>(); DBPDataKind dataKind = attribute.getDataKind(); if (attribute instanceof DBSAttributeBase && !((DBSAttributeBase)attribute).isRequired()) { operators.add(DBCLogicalOperator.IS_NULL); operators.add(DBCLogicalOperator.IS_NOT_NULL); } if (dataKind == DBPDataKind.BOOLEAN || dataKind == DBPDataKind.ROWID || dataKind == DBPDataKind.OBJECT || dataKind == DBPDataKind.BINARY) { operators.add(DBCLogicalOperator.EQUALS); operators.add(DBCLogicalOperator.NOT_EQUALS); } else if (dataKind == DBPDataKind.NUMERIC || dataKind == DBPDataKind.DATETIME || dataKind == DBPDataKind.STRING) { operators.add(DBCLogicalOperator.EQUALS); operators.add(DBCLogicalOperator.NOT_EQUALS); operators.add(DBCLogicalOperator.GREATER); //operators.add(DBCLogicalOperator.GREATER_EQUALS); operators.add(DBCLogicalOperator.LESS); //operators.add(DBCLogicalOperator.LESS_EQUALS); operators.add(DBCLogicalOperator.IN); } if (dataKind == DBPDataKind.STRING) { operators.add(DBCLogicalOperator.LIKE); } return operators.toArray(new DBCLogicalOperator[operators.size()]); } public static Object getRawValue(Object value) { if (value instanceof DBDValue) { return ((DBDValue)value).getRawValue(); } else { return value; } } public static boolean isIndexedAttribute(DBRProgressMonitor monitor, DBSEntityAttribute attribute) throws DBException { DBSEntity entity = attribute.getParentObject(); if (entity instanceof DBSTable) { Collection<? extends DBSTableIndex> indexes = ((DBSTable) entity).getIndexes(monitor); if (!CommonUtils.isEmpty(indexes)) { for (DBSTableIndex index : indexes) { if (getConstraintAttribute(monitor, index, attribute) != null) { return true; } } } } return false; } @Nullable public static DBCTransactionManager getTransactionManager(@Nullable DBCExecutionContext executionContext) { if (executionContext != null && executionContext.isConnected()) { return getAdapter(DBCTransactionManager.class, executionContext); } return null; } @SuppressWarnings("unchecked") @NotNull public static <T> Class<T> getDriverClass(@NotNull DBPDataSource dataSource, @NotNull String className) throws ClassNotFoundException { return (Class<T>) Class.forName(className, true, dataSource.getContainer().getDriver().getClassLoader()); } @SuppressWarnings("unchecked") @NotNull public static <T extends DBCSession> T openMetaSession(@NotNull DBRProgressMonitor monitor, @NotNull DBPDataSource dataSource, @NotNull String task) { return (T) dataSource.getDefaultContext(true).openSession(monitor, DBCExecutionPurpose.META, task); } @SuppressWarnings("unchecked") @NotNull public static <T extends DBCSession> T openUtilSession(@NotNull DBRProgressMonitor monitor, @NotNull DBPDataSource dataSource, @NotNull String task) { return (T) dataSource.getDefaultContext(false).openSession(monitor, DBCExecutionPurpose.UTIL, task); } @Nullable public static DBSObject getFromObject(Object object) { if (object instanceof DBSWrapper) { return ((DBSWrapper) object).getObject(); } else if (object instanceof DBSObject) { return (DBSObject) object; } else { return null; } } public static boolean isAtomicParameter(Object o) { return o == null || o instanceof CharSequence || o instanceof Number || o instanceof java.util.Date || o instanceof Boolean; } @NotNull public static DBSObject getDefaultOrActiveObject(@NotNull DBSInstance object) { DBSObject selectedObject = getActiveInstanceObject(object); return selectedObject == null ? object : selectedObject; } @Nullable public static DBSObject getActiveInstanceObject(@NotNull DBSInstance object) { return getSelectedObject(object, true); } @Nullable public static DBSObject getSelectedObject(@NotNull DBSObject object, boolean searchNested) { DBSObjectSelector objectSelector = getAdapter(DBSObjectSelector.class, object); if (objectSelector != null) { DBSObject selectedObject1 = objectSelector.getDefaultObject(); if (searchNested && selectedObject1 != null) { DBSObject nestedObject = getSelectedObject(selectedObject1, true); if (nestedObject != null) { return nestedObject; } } return selectedObject1; } return null; } @NotNull public static DBSObject[] getSelectedObjects(@NotNull DBSObject object) { DBSObjectSelector objectSelector = getAdapter(DBSObjectSelector.class, object); if (objectSelector != null) { DBSObject selectedObject1 = objectSelector.getDefaultObject(); if (selectedObject1 != null) { DBSObject nestedObject = getSelectedObject(selectedObject1, true); if (nestedObject != null) { return new DBSObject[] { selectedObject1, nestedObject }; } else { return new DBSObject[] { selectedObject1 }; } } } return new DBSObject[0]; } public static boolean isHiddenObject(Object object) { return object instanceof DBPHiddenObject && ((DBPHiddenObject) object).isHidden(); } public static DBDPseudoAttribute getRowIdAttribute(DBSEntity entity) { if (entity instanceof DBDPseudoAttributeContainer) { try { return DBDPseudoAttribute.getAttribute( ((DBDPseudoAttributeContainer) entity).getPseudoAttributes(), DBDPseudoAttributeType.ROWID); } catch (DBException e) { log.warn("Can't get pseudo attributes for '" + entity.getName() + "'", e); } } return null; } public static DBDPseudoAttribute getPseudoAttribute(DBSEntity entity, String attrName) { if (entity instanceof DBDPseudoAttributeContainer) { try { DBDPseudoAttribute[] pseudoAttributes = ((DBDPseudoAttributeContainer) entity).getPseudoAttributes(); if (pseudoAttributes != null && pseudoAttributes.length > 0) { for (int i = 0; i < pseudoAttributes.length; i++) { DBDPseudoAttribute pa = pseudoAttributes[i]; String attrId = pa.getAlias(); if (CommonUtils.isEmpty(attrId)) { attrId = pa.getName(); } if (attrId.equals(attrName)) { return pa; } } } } catch (DBException e) { log.warn("Can't get pseudo attributes for '" + entity.getName() + "'", e); } } return null; } public static boolean isPseudoAttribute(DBSAttributeBase attr) { return attr instanceof DBDAttributeBinding && ((DBDAttributeBinding) attr).isPseudoAttribute(); } public static <TYPE extends DBPNamedObject> Comparator<TYPE> nameComparator() { return new Comparator<TYPE>() { @Override public int compare(DBPNamedObject o1, DBPNamedObject o2) { return o1.getName().compareTo(o2.getName()); } }; } public static Comparator<? super DBSAttributeBase> orderComparator() { return new Comparator<DBSAttributeBase>() { @Override public int compare(DBSAttributeBase o1, DBSAttributeBase o2) { return o1.getOrdinalPosition() - o2.getOrdinalPosition(); } }; } public static <T extends DBPNamedObject> void orderObjects(@NotNull List<T> objects) { Collections.sort(objects, new Comparator<T>() { @Override public int compare(T o1, T o2) { String name1 = o1.getName(); String name2 = o2.getName(); return name1 == null && name2 == null ? 0 : (name1 == null ? -1 : (name2 == null ? 1 : name1.compareTo(name2))); } }); } public static String getClientApplicationName(DBPDataSourceContainer container, String purpose) { if (container.getPreferenceStore().getBoolean(ModelPreferences.META_CLIENT_NAME_OVERRIDE)) { return container.getPreferenceStore().getString(ModelPreferences.META_CLIENT_NAME_VALUE); } final String productTitle = GeneralUtils.getProductTitle(); return purpose == null ? productTitle : productTitle + " - " + purpose; } @NotNull public static DBPErrorAssistant.ErrorType discoverErrorType(@NotNull DBPDataSource dataSource, @NotNull Throwable error) { DBPErrorAssistant errorAssistant = getAdapter(DBPErrorAssistant.class, dataSource); if (errorAssistant != null) { return ((DBPErrorAssistant) dataSource).discoverErrorType(error); } return DBPErrorAssistant.ErrorType.NORMAL; } }
Full object name gen fix
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/DBUtils.java
Full object name gen fix
<ide><path>lugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/DBUtils.java <ide> if (namePart == null) { <ide> continue; <ide> } <del> if (name.length() > 0) { <add> if (name.length() > 0 && name.charAt(name.length() - 1) != '.') { <ide> name.append('.'); <ide> } <ide> name.append(namePart);
Java
apache-2.0
d6d90c61ee818da3cfa8e726027d757152cd73fb
0
WilliamZapata/alluxio,PasaLab/tachyon,yuluo-ding/alluxio,PasaLab/tachyon,calvinjia/tachyon,ShailShah/alluxio,bf8086/alluxio,madanadit/alluxio,jswudi/alluxio,madanadit/alluxio,wwjiang007/alluxio,Reidddddd/mo-alluxio,jsimsa/alluxio,WilliamZapata/alluxio,Alluxio/alluxio,maboelhassan/alluxio,maobaolong/alluxio,ChangerYoung/alluxio,aaudiber/alluxio,jsimsa/alluxio,aaudiber/alluxio,ChangerYoung/alluxio,Alluxio/alluxio,jswudi/alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,wwjiang007/alluxio,ChangerYoung/alluxio,bf8086/alluxio,calvinjia/tachyon,Alluxio/alluxio,uronce-cc/alluxio,maboelhassan/alluxio,WilliamZapata/alluxio,maboelhassan/alluxio,Reidddddd/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,uronce-cc/alluxio,calvinjia/tachyon,ChangerYoung/alluxio,EvilMcJerkface/alluxio,EvilMcJerkface/alluxio,PasaLab/tachyon,apc999/alluxio,yuluo-ding/alluxio,PasaLab/tachyon,bf8086/alluxio,uronce-cc/alluxio,madanadit/alluxio,WilliamZapata/alluxio,apc999/alluxio,Reidddddd/mo-alluxio,Reidddddd/alluxio,apc999/alluxio,madanadit/alluxio,Alluxio/alluxio,Alluxio/alluxio,jswudi/alluxio,Reidddddd/alluxio,PasaLab/tachyon,PasaLab/tachyon,Reidddddd/alluxio,yuluo-ding/alluxio,wwjiang007/alluxio,maboelhassan/alluxio,maboelhassan/alluxio,wwjiang007/alluxio,maobaolong/alluxio,uronce-cc/alluxio,riversand963/alluxio,bf8086/alluxio,jsimsa/alluxio,Reidddddd/mo-alluxio,EvilMcJerkface/alluxio,jsimsa/alluxio,calvinjia/tachyon,maobaolong/alluxio,ShailShah/alluxio,ShailShah/alluxio,Reidddddd/alluxio,riversand963/alluxio,yuluo-ding/alluxio,wwjiang007/alluxio,WilliamZapata/alluxio,apc999/alluxio,maboelhassan/alluxio,ChangerYoung/alluxio,maobaolong/alluxio,jswudi/alluxio,maobaolong/alluxio,apc999/alluxio,maobaolong/alluxio,Reidddddd/mo-alluxio,Reidddddd/alluxio,madanadit/alluxio,Alluxio/alluxio,ShailShah/alluxio,EvilMcJerkface/alluxio,ChangerYoung/alluxio,EvilMcJerkface/alluxio,jsimsa/alluxio,apc999/alluxio,yuluo-ding/alluxio,Alluxio/alluxio,Alluxio/alluxio,madanadit/alluxio,Reidddddd/mo-alluxio,uronce-cc/alluxio,ShailShah/alluxio,PasaLab/tachyon,maobaolong/alluxio,bf8086/alluxio,bf8086/alluxio,calvinjia/tachyon,calvinjia/tachyon,Reidddddd/mo-alluxio,aaudiber/alluxio,bf8086/alluxio,madanadit/alluxio,Alluxio/alluxio,WilliamZapata/alluxio,wwjiang007/alluxio,EvilMcJerkface/alluxio,jswudi/alluxio,uronce-cc/alluxio,jsimsa/alluxio,wwjiang007/alluxio,bf8086/alluxio,aaudiber/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,Reidddddd/alluxio,yuluo-ding/alluxio,maobaolong/alluxio,maobaolong/alluxio,jswudi/alluxio,apc999/alluxio,maobaolong/alluxio,ShailShah/alluxio,aaudiber/alluxio,aaudiber/alluxio,riversand963/alluxio,aaudiber/alluxio,calvinjia/tachyon,madanadit/alluxio,calvinjia/tachyon,riversand963/alluxio,maboelhassan/alluxio,riversand963/alluxio,wwjiang007/alluxio
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the “License”). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.security.login; import alluxio.security.User; import java.security.Principal; import java.util.Map; import java.util.Set; import javax.annotation.concurrent.NotThreadSafe; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; /** * A login module that search the Kerberos or OS user from Subject, and then convert to an Alluxio * user. It does not really authenticate the user in its login method. */ @NotThreadSafe public final class AlluxioLoginModule implements LoginModule { private Subject mSubject; private User mUser; @Override public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) { mSubject = subject; } /** * Authenticates the user (first phase). * * The implementation does not really authenticate the user here. Always return true. * @return true in all cases * @throws LoginException when the login fails */ @Override public boolean login() throws LoginException { return true; } /** * Aborts the authentication (second phase). * * This method is called if the LoginContext's overall authentication failed. (login failed) * It cleans up any state that was changed in the login and commit methods. * @return true in all cases * @throws LoginException when the abortion fails */ @Override public boolean abort() throws LoginException { logout(); mUser = null; return true; } /** * Commits the authentication (second phase). * * This method is called if the LoginContext's overall authentication succeeded. (login * succeeded) * The implementation searches the Kerberos or OS user in the Subject. If existed, * convert it to an Alluxio user and add into the Subject. * @return true in all cases * @throws LoginException if the user extending a specific Principal is not found */ @Override public boolean commit() throws LoginException { // if there is already an Alluxio user, it's done. if (!mSubject.getPrincipals(User.class).isEmpty()) { return true; } Principal user = null; // TODO(dong): get a Kerberos user if we are using Kerberos. // user = getKerberosUser(); // get a OS user if (user == null) { user = getPrincipalUser(LoginModuleConfigurationUtils.OS_PRINCIPAL_CLASS_NAME); } // if a user is found, convert it to an Alluxio user and save it. if (user != null) { mUser = new User(user.getName()); mSubject.getPrincipals().add(mUser); return true; } throw new LoginException("Cannot find a user"); } /** * Logs out the user. * * The implementation removes the User associated with the Subject. * @return true in all cases * @throws LoginException if logout fails */ @Override public boolean logout() throws LoginException { if (mSubject.isReadOnly()) { throw new LoginException("logout Failed: Subject is Readonly."); } if (mUser != null) { mSubject.getPrincipals().remove(mUser); } return true; } private Principal getPrincipalUser(String className) throws LoginException { // load the principal class ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = ClassLoader.getSystemClassLoader(); } Class<? extends Principal> clazz; try { // Declare a temp variable so that we can suppress warnings locally @SuppressWarnings("unchecked") Class<? extends Principal> tmpClazz = (Class<? extends Principal>) loader.loadClass(className); clazz = tmpClazz; } catch (ClassNotFoundException e) { throw new LoginException("Unable to find JAAS principal class:" + e.getMessage()); } // find corresponding user based on the principal Set<? extends Principal> userSet = mSubject.getPrincipals(clazz); if (!userSet.isEmpty()) { if (userSet.size() == 1) { return userSet.iterator().next(); } throw new LoginException("More than one instance of Principal " + className + " is found"); } return null; } }
core/common/src/main/java/alluxio/security/login/AlluxioLoginModule.java
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the “License”). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.security.login; import alluxio.security.User; import java.security.Principal; import java.util.Map; import java.util.Set; import javax.annotation.concurrent.NotThreadSafe; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; /** * A login module that search the Kerberos or OS user from Subject, and then convert to an Alluxio * user. It does not really authenticate the user in its login method. */ @NotThreadSafe public final class AlluxioLoginModule implements LoginModule { private Subject mSubject; private User mUser; @Override public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) { mSubject = subject; } /** * Authenticates the user (first phase). * * The implementation does not really authenticate the user here. Always return true. * @return true in all cases * @throws LoginException when the login fails */ @Override public boolean login() throws LoginException { return true; } /** * Aborts the authentication (second phase). * * This method is called if the LoginContext's overall authentication failed. (login failed) * It cleans up any state that was changed in the login and commit methods. * @return true in all cases * @throws LoginException when the abortion fails */ @Override public boolean abort() throws LoginException { logout(); mUser = null; return true; } /** * Commits the authentication (second phase). * * This method is called if the LoginContext's overall authentication succeeded. (login * succeeded) * The implementation searches the Kerberos or OS user in the Subject. If existed, * convert it to an Alluxio user and add into the Subject. * @return true in all cases * @throws LoginException if the user extending a specific Principal is not found */ @Override public boolean commit() throws LoginException { // if there is already an Alluxio user, it's done. if (!mSubject.getPrincipals(User.class).isEmpty()) { return true; } Principal user = null; // TODO(dong): get a Kerberos user if we are using Kerberos. // user = getKerberosUser(); // get a OS user if (user == null) { user = getPrincipalUser(LoginModuleConfigurationUtils.OS_PRINCIPAL_CLASS_NAME); } // if a user is found, convert it to an Alluxio user and save it. if (user != null) { mUser = new User(user.getName()); mSubject.getPrincipals().add(mUser); return true; } throw new LoginException("Cannot find a user"); } /** * Logs out the user. * * The implementation removes the User associated with the Subject. * @return true in all cases * @throws LoginException if logout fails */ @Override public boolean logout() throws LoginException { if (mSubject.isReadOnly()) { throw new LoginException("logout Failed: Subject is Readonly."); } if (mUser != null) { mSubject.getPrincipals().remove(mUser); } return true; } private Principal getPrincipalUser(String className) throws LoginException { // load the principal class ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = ClassLoader.getSystemClassLoader(); } Class<? extends Principal> clazz = null; try { // Declare a temp variable so that we can suppress warnings locally @SuppressWarnings("unchecked") Class<? extends Principal> tmpClazz = (Class<? extends Principal>) loader.loadClass(className); clazz = tmpClazz; } catch (ClassNotFoundException e) { throw new LoginException("Unable to find JAAS principal class:" + e.getMessage()); } // find corresponding user based on the principal Set<? extends Principal> userSet = mSubject.getPrincipals(clazz); if (!userSet.isEmpty()) { if (userSet.size() == 1) { return userSet.iterator().next(); } throw new LoginException("More than one instance of Principal " + className + " is found"); } return null; } }
[SMALLFIX] Removed redundant initializer in AlluxioLoginModule
core/common/src/main/java/alluxio/security/login/AlluxioLoginModule.java
[SMALLFIX] Removed redundant initializer in AlluxioLoginModule
<ide><path>ore/common/src/main/java/alluxio/security/login/AlluxioLoginModule.java <ide> loader = ClassLoader.getSystemClassLoader(); <ide> } <ide> <del> Class<? extends Principal> clazz = null; <add> Class<? extends Principal> clazz; <ide> try { <ide> // Declare a temp variable so that we can suppress warnings locally <ide> @SuppressWarnings("unchecked")
Java
apache-2.0
dad0ba8de4d07653babe687af0d70930a4cf9c8f
0
jnidzwetzki/scalephant,jnidzwetzki/bboxdb,jnidzwetzki/bboxdb,jnidzwetzki/bboxdb,jnidzwetzki/scalephant
/******************************************************************************* * * Copyright (C) 2015-2018 the BBoxDB project * * 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.bboxdb.network.client; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Inet4Address; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import java.util.stream.Collectors; import org.bboxdb.commons.CloseableHelper; import org.bboxdb.commons.DuplicateResolver; import org.bboxdb.commons.MicroSecondTimestampProvider; import org.bboxdb.commons.NetworkInterfaceHelper; import org.bboxdb.commons.ServiceState; import org.bboxdb.distribution.TupleStoreConfigurationCache; import org.bboxdb.distribution.zookeeper.ZookeeperException; import org.bboxdb.misc.Const; import org.bboxdb.network.NetworkConst; import org.bboxdb.network.NetworkPackageDecoder; import org.bboxdb.network.capabilities.PeerCapabilities; import org.bboxdb.network.client.future.EmptyResultFuture; import org.bboxdb.network.client.future.FutureHelper; import org.bboxdb.network.client.future.HelloFuture; import org.bboxdb.network.client.future.JoinedTupleListFuture; import org.bboxdb.network.client.future.OperationFuture; import org.bboxdb.network.client.future.SSTableNameListFuture; import org.bboxdb.network.client.future.TupleListFuture; import org.bboxdb.network.client.response.CompressionHandler; import org.bboxdb.network.client.response.ErrorHandler; import org.bboxdb.network.client.response.HelloHandler; import org.bboxdb.network.client.response.JoinedTupleHandler; import org.bboxdb.network.client.response.ListTablesHandler; import org.bboxdb.network.client.response.MultipleTupleEndHandler; import org.bboxdb.network.client.response.MultipleTupleStartHandler; import org.bboxdb.network.client.response.PageEndHandler; import org.bboxdb.network.client.response.ServerResponseHandler; import org.bboxdb.network.client.response.SuccessHandler; import org.bboxdb.network.client.response.TupleHandler; import org.bboxdb.network.packages.NetworkRequestPackage; import org.bboxdb.network.packages.PackageEncodeException; import org.bboxdb.network.packages.request.CancelQueryRequest; import org.bboxdb.network.packages.request.CompressionEnvelopeRequest; import org.bboxdb.network.packages.request.CreateDistributionGroupRequest; import org.bboxdb.network.packages.request.CreateTableRequest; import org.bboxdb.network.packages.request.DeleteDistributionGroupRequest; import org.bboxdb.network.packages.request.DeleteTableRequest; import org.bboxdb.network.packages.request.DeleteTupleRequest; import org.bboxdb.network.packages.request.DisconnectRequest; import org.bboxdb.network.packages.request.HelloRequest; import org.bboxdb.network.packages.request.InsertTupleRequest; import org.bboxdb.network.packages.request.KeepAliveRequest; import org.bboxdb.network.packages.request.ListTablesRequest; import org.bboxdb.network.packages.request.NextPageRequest; import org.bboxdb.network.packages.request.QueryBoundingBoxContinuousRequest; import org.bboxdb.network.packages.request.QueryBoundingBoxRequest; import org.bboxdb.network.packages.request.QueryBoundingBoxTimeRequest; import org.bboxdb.network.packages.request.QueryInsertTimeRequest; import org.bboxdb.network.packages.request.QueryJoinRequest; import org.bboxdb.network.packages.request.QueryKeyRequest; import org.bboxdb.network.packages.request.QueryVersionTimeRequest; import org.bboxdb.network.packages.response.HelloResponse; import org.bboxdb.network.routing.RoutingHeader; import org.bboxdb.storage.entity.BoundingBox; import org.bboxdb.storage.entity.DistributionGroupConfiguration; import org.bboxdb.storage.entity.PagedTransferableEntity; import org.bboxdb.storage.entity.Tuple; import org.bboxdb.storage.entity.TupleStoreConfiguration; import org.bboxdb.storage.entity.TupleStoreName; import org.bboxdb.storage.sstable.duplicateresolver.DoNothingDuplicateResolver; import org.bboxdb.storage.tuplestore.manager.TupleStoreManagerRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.io.ByteStreams; public class BBoxDBClient implements BBoxDB { /** * The sequence number generator */ protected final SequenceNumberGenerator sequenceNumberGenerator; /** * The socket of the connection */ protected Socket clientSocket = null; /** * The input stream of the socket */ protected BufferedInputStream inputStream; /** * The output stream of the socket */ protected BufferedOutputStream outputStream; /** * The pending calls */ protected final Map<Short, OperationFuture> pendingCalls = new HashMap<>(); /** * The result buffer */ protected final Map<Short, List<PagedTransferableEntity>> resultBuffer = new HashMap<>(); /** * The retryer */ protected final NetworkOperationRetryer networkOperationRetryer; /** * The server response reader */ protected ServerResponseReader serverResponseReader; /** * The server response reader thread */ protected Thread serverResponseReaderThread; /** * The maintenance handler instance */ protected ConnectionMainteinanceThread mainteinanceHandler; /** * The maintenance thread */ protected Thread mainteinanceThread; /** * The default timeout */ public static final long DEFAULT_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(30); /** * The connection state */ protected final ServiceState connectionState; /** * The number of in flight requests * @return */ protected volatile short maxInFlightCalls = MAX_IN_FLIGHT_CALLS; /** * The capabilities of the connection */ protected PeerCapabilities connectionCapabilities = new PeerCapabilities(); /** * The capabilities of the client */ protected PeerCapabilities clientCapabilities = new PeerCapabilities(); /** * Is the paging for queries enabled? */ protected boolean pagingEnabled; /** * The amount of tuples per page */ protected short tuplesPerPage; /** * The tuple store manager registry (used for gossip) */ protected TupleStoreManagerRegistry tupleStoreManagerRegistry; /** * The pending packages for compression */ protected final List<NetworkRequestPackage> pendingCompressionPackages; /** * The Server response handler */ protected final Map<Short, ServerResponseHandler> serverResponseHandler; /** * The server address */ protected InetSocketAddress serverAddress; /** * The Logger */ private final static Logger logger = LoggerFactory.getLogger(BBoxDBClient.class); @VisibleForTesting public BBoxDBClient() { this(new InetSocketAddress("localhost", 1234)); } public BBoxDBClient(final InetSocketAddress serverAddress) { this.serverAddress = Objects.requireNonNull(serverAddress); // External IP is used to create proper package routing if(serverAddress.getAddress().isLoopbackAddress()) { try { final Inet4Address nonLoopbackAdress = NetworkInterfaceHelper.getFirstNonLoopbackIPv4(); this.serverAddress = new InetSocketAddress(nonLoopbackAdress, serverAddress.getPort()); } catch (SocketException e) { logger.error("Connection to loopback IP " + serverAddress + " requested and unable replace the IP with external IP", e); } } this.sequenceNumberGenerator = new SequenceNumberGenerator(); this.connectionState = new ServiceState(); // Default: Enable gzip compression clientCapabilities.setGZipCompression(); pagingEnabled = true; tuplesPerPage = 50; pendingCompressionPackages = new ArrayList<>(); serverResponseHandler = new HashMap<>(); networkOperationRetryer = new NetworkOperationRetryer((p, f) -> {sendPackageToServer(p, f);}); initResponseHandler(); } /** * Init the response handler */ protected void initResponseHandler() { serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_COMPRESSION, new CompressionHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_HELLO, new HelloHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_SUCCESS, new SuccessHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_ERROR, new ErrorHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_LIST_TABLES, new ListTablesHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_TUPLE, new TupleHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_MULTIPLE_TUPLE_START, new MultipleTupleStartHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_MULTIPLE_TUPLE_END, new MultipleTupleEndHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_PAGE_END, new PageEndHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_JOINED_TUPLE, new JoinedTupleHandler()); } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#connect() */ @Override public boolean connect() { if(clientSocket != null || ! connectionState.isInNewState()) { logger.warn("Connect() called on an active connection, ignoring (state: {})", connectionState); return true; } logger.debug("Connecting to server: {}", getConnectionName()); try { connectionState.dipatchToStarting(); connectionState.registerCallback((c) -> { if(c.isInFailedState() ) { killPendingCalls(); } }); clientSocket = new Socket(serverAddress.getAddress(), serverAddress.getPort()); inputStream = new BufferedInputStream(clientSocket.getInputStream()); outputStream = new BufferedOutputStream(clientSocket.getOutputStream()); synchronized (pendingCalls) { pendingCalls.clear(); } getResultBuffer().clear(); // Start up the response reader serverResponseReader = new ServerResponseReader(this); serverResponseReaderThread = new Thread(serverResponseReader); serverResponseReaderThread.setName("Server response reader for " + getConnectionName()); serverResponseReaderThread.start(); runHandshake(); } catch (Exception e) { logger.error("Got an exception while connecting to server", e); closeSocket(); connectionState.dispatchToFailed(e); return false; } return true; } /** * Close the socket */ public void closeSocket() { logger.info("Closing socket to server: {}", getConnectionName()); CloseableHelper.closeWithoutException(clientSocket); clientSocket = null; } /** * The name of the connection * @return */ public String getConnectionName() { return serverAddress.getHostString() + " / " + serverAddress.getPort(); } /** * Get the next sequence number * @return */ protected short getNextSequenceNumber() { return sequenceNumberGenerator.getNextSequenceNummber(); } /** * Run the handshake with the server * @throws ExecutionException * @throws InterruptedException */ protected void runHandshake() throws Exception { final HelloFuture operationFuture = new HelloFuture(1); if(! connectionState.isInStartingState()) { logger.error("Handshaking called in wrong state: {}", connectionState); } // Capabilities are reported to server; now freeze client capabilities. clientCapabilities.freeze(); final HelloRequest requestPackage = new HelloRequest(getNextSequenceNumber(), NetworkConst.PROTOCOL_VERSION, clientCapabilities); registerPackageCallback(requestPackage, operationFuture); sendPackageToServer(requestPackage, operationFuture); operationFuture.waitForAll(); if(operationFuture.isFailed()) { throw new Exception("Got an error during handshake"); } final HelloResponse helloResponse = operationFuture.get(0); connectionCapabilities = helloResponse.getPeerCapabilities(); connectionState.dispatchToRunning(); logger.debug("Handshaking with {} done", getConnectionName()); mainteinanceHandler = new ConnectionMainteinanceThread(this); mainteinanceThread = new Thread(mainteinanceHandler); mainteinanceThread.setName("Connection mainteinace thread for: " + getConnectionName()); mainteinanceThread.start(); } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#disconnect() */ @Override public void disconnect() { if(! connectionState.isInRunningState()) { logger.error("Unable to disconnect, connection is in state {}", connectionState); return; } synchronized (this) { logger.info("Disconnecting from server: {}", getConnectionName()); connectionState.dispatchToStopping(); final DisconnectRequest requestPackage = new DisconnectRequest(getNextSequenceNumber()); final EmptyResultFuture operationFuture = new EmptyResultFuture(1); registerPackageCallback(requestPackage, operationFuture); sendPackageToServer(requestPackage, operationFuture); } settlePendingCalls(DEFAULT_TIMEOUT_MILLIS); terminateConnection(); } /** * Settle all pending calls */ public void settlePendingCalls(final long shutdownTimeMillis) { final long shutdownStarted = System.currentTimeMillis(); // Wait for all pending calls to settle synchronized (pendingCalls) { while(getInFlightCalls() > 0) { final long shutdownDuration = System.currentTimeMillis() - shutdownStarted; final long timeoutLeft = shutdownTimeMillis - shutdownDuration; if(timeoutLeft <= 0) { break; } if(! isConnected()) { logger.warn("Connection already closed but {} requests are pending", getInFlightCalls()); return; } logger.info("Waiting up to {} seconds for pending requests to settle " + "(pending {} / server {})", TimeUnit.MILLISECONDS.toSeconds(timeoutLeft), getInFlightCalls(), getConnectionName()); try { // Recheck connection state all 5 seconds final long maxWaitTime = Math.min(timeoutLeft, TimeUnit.SECONDS.toMillis(5)); pendingCalls.wait(maxWaitTime); } catch (InterruptedException e) { logger.debug("Got an InterruptedException during pending calls wait."); Thread.currentThread().interrupt(); return; } } if(! pendingCalls.isEmpty()) { logger.warn("Connection is closed. Still pending calls: {} ", pendingCalls); } } } /** * Kill all pending requests */ protected void killPendingCalls() { synchronized (pendingCalls) { if(! pendingCalls.isEmpty()) { logger.warn("Socket is closed unexpected, killing pending calls: " + pendingCalls.size()); for(final short requestId : pendingCalls.keySet()) { final OperationFuture future = pendingCalls.get(requestId); future.setFailedState(); future.fireCompleteEvent(); } pendingCalls.clear(); pendingCalls.notifyAll(); } } } /** * Close the connection to the server without sending a disconnect package. For a * regular disconnect, see the disconnect() method. */ public void terminateConnection() { if(connectionState.isInRunningState()) { connectionState.dispatchToStopping(); } killPendingCalls(); getResultBuffer().clear(); closeSocket(); logger.info("Disconnected from server: {}", getConnectionName()); connectionState.forceDispatchToTerminated(); } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#createTable(java.lang.String) */ @Override public EmptyResultFuture createTable(final String table, final TupleStoreConfiguration configuration) throws BBoxDBException { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedEmptyResultFuture("createTable called, but connection not ready: " + this); } final EmptyResultFuture clientOperationFuture = new EmptyResultFuture(1); final CreateTableRequest requestPackage = new CreateTableRequest(getNextSequenceNumber(), table, configuration); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#deleteTable(java.lang.String) */ @Override public EmptyResultFuture deleteTable(final String table) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedEmptyResultFuture("deleteTable called, but connection not ready: " + this); } final EmptyResultFuture clientOperationFuture = new EmptyResultFuture(1); final DeleteTableRequest requestPackage = new DeleteTableRequest(getNextSequenceNumber(), table); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#insertTuple(java.lang.String, org.bboxdb.storage.entity.Tuple) */ @Override public EmptyResultFuture insertTuple(final String table, final Tuple tuple) throws BBoxDBException { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedEmptyResultFuture("insertTuple called, but connection not ready: " + this); } final Supplier<RoutingHeader> routingHeader = () -> RoutingHeaderHelper.getRoutingHeaderForLocalSystemNE( table, tuple.getBoundingBox(), false, serverAddress); return insertTuple(table, tuple, routingHeader); } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#insertTuple(java.lang.String, org.bboxdb.storage.entity.Tuple) */ public EmptyResultFuture insertTuple(final String table, final Tuple tuple, final Supplier<RoutingHeader> routingHeaderSupplier) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedEmptyResultFuture("insertTuple called, but connection not ready: " + this); } final EmptyResultFuture clientOperationFuture = new EmptyResultFuture(1); final TupleStoreName ssTableName = new TupleStoreName(table); final short sequenceNumber = getNextSequenceNumber(); final InsertTupleRequest requestPackage = new InsertTupleRequest( sequenceNumber, routingHeaderSupplier, ssTableName, tuple); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#deleteTuple(java.lang.String, java.lang.String) */ @Override public EmptyResultFuture deleteTuple(final String table, final String key, final long timestamp) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedEmptyResultFuture("deleteTuple called, but connection not ready: " + this); } final EmptyResultFuture clientOperationFuture = new EmptyResultFuture(1); final Supplier<RoutingHeader> routingHeaderSupplier = () -> RoutingHeaderHelper.getRoutingHeaderForLocalSystemNE( table, BoundingBox.EMPTY_BOX, true, serverAddress); final short sequenceNumber = getNextSequenceNumber(); final DeleteTupleRequest requestPackage = new DeleteTupleRequest(sequenceNumber, routingHeaderSupplier, table, key, timestamp); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#deleteTuple(java.lang.String, java.lang.String) */ @Override public EmptyResultFuture deleteTuple(final String table, final String key) throws BBoxDBException { final long timestamp = MicroSecondTimestampProvider.getNewTimestamp(); return deleteTuple(table, key, timestamp); } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#listTables() */ @Override public SSTableNameListFuture listTables() { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedSStableNameFuture("listTables called, but connection not ready: " + this); } final SSTableNameListFuture clientOperationFuture = new SSTableNameListFuture(1); final ListTablesRequest requestPackage = new ListTablesRequest(getNextSequenceNumber()); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#createDistributionGroup(java.lang.String, short) */ @Override public EmptyResultFuture createDistributionGroup(final String distributionGroup, final DistributionGroupConfiguration distributionGroupConfiguration) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedEmptyResultFuture("listTables called, but connection not ready: " + this); } final EmptyResultFuture clientOperationFuture = new EmptyResultFuture(1); final CreateDistributionGroupRequest requestPackage = new CreateDistributionGroupRequest( getNextSequenceNumber(), distributionGroup, distributionGroupConfiguration); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#deleteDistributionGroup(java.lang.String) */ @Override public EmptyResultFuture deleteDistributionGroup(final String distributionGroup) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedEmptyResultFuture("delete distribution group called, but connection not ready: " + this); } final EmptyResultFuture clientOperationFuture = new EmptyResultFuture(1); final DeleteDistributionGroupRequest requestPackage = new DeleteDistributionGroupRequest( getNextSequenceNumber(), distributionGroup); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#queryKey(java.lang.String, java.lang.String) */ @Override public TupleListFuture queryKey(final String table, final String key) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedTupleListFuture("queryKey called, but connection not ready: " + this, table); } try { final RoutingHeader routingHeader = RoutingHeaderHelper.getRoutingHeaderForLocalSystem( table, BoundingBox.EMPTY_BOX, true, serverAddress); final DuplicateResolver<Tuple> duplicateResolver = TupleStoreConfigurationCache.getInstance().getDuplicateResolverForTupleStore(table); final TupleListFuture clientOperationFuture = new TupleListFuture(1, duplicateResolver, table); final QueryKeyRequest requestPackage = new QueryKeyRequest(getNextSequenceNumber(), routingHeader, table, key, pagingEnabled, tuplesPerPage); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); // Send query immediately flushPendingCompressionPackages(); return clientOperationFuture; } catch (BBoxDBException | ZookeeperException e) { // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for systems list"); Thread.currentThread().interrupt(); // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#queryBoundingBox(java.lang.String, org.bboxdb.storage.entity.BoundingBox) */ @Override public TupleListFuture queryBoundingBox(final String table, final BoundingBox boundingBox) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedTupleListFuture("queryBoundingBox called, but connection not ready: " + this, table); } try { final RoutingHeader routingHeader = RoutingHeaderHelper.getRoutingHeaderForLocalSystem( table, boundingBox, false, serverAddress); final TupleListFuture clientOperationFuture = new TupleListFuture(1, new DoNothingDuplicateResolver(), table); final QueryBoundingBoxRequest requestPackage = new QueryBoundingBoxRequest(getNextSequenceNumber(), routingHeader, table, boundingBox, pagingEnabled, tuplesPerPage); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); // Send query immediately flushPendingCompressionPackages(); return clientOperationFuture; } catch (BBoxDBException | ZookeeperException e) { // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for systems list"); Thread.currentThread().interrupt(); // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } } /** * Execute a continuous bounding box query * */ @Override public TupleListFuture queryBoundingBoxContinuous(final String table, final BoundingBox boundingBox) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedTupleListFuture("queryBoundingBoxContinuous called, but connection not ready: " + this, table); } try { final RoutingHeader routingHeader = RoutingHeaderHelper.getRoutingHeaderForLocalSystem( table, boundingBox, false, serverAddress); final TupleListFuture clientOperationFuture = new TupleListFuture(1, new DoNothingDuplicateResolver(), table); final QueryBoundingBoxContinuousRequest requestPackage = new QueryBoundingBoxContinuousRequest(getNextSequenceNumber(), routingHeader, table, boundingBox); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); // Send query immediately flushPendingCompressionPackages(); return clientOperationFuture; } catch (BBoxDBException | ZookeeperException e) { // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for systems list"); Thread.currentThread().interrupt(); // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#queryBoundingBoxAndTime(java.lang.String, org.bboxdb.storage.entity.BoundingBox) */ @Override public TupleListFuture queryBoundingBoxAndTime(final String table, final BoundingBox boundingBox, final long timestamp) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedTupleListFuture("queryBoundingBox called, but connection not ready: " + this, table); } try { final RoutingHeader routingHeader = RoutingHeaderHelper.getRoutingHeaderForLocalSystem( table, boundingBox, false, serverAddress); final TupleListFuture clientOperationFuture = new TupleListFuture(1, new DoNothingDuplicateResolver(), table); final QueryBoundingBoxTimeRequest requestPackage = new QueryBoundingBoxTimeRequest(getNextSequenceNumber(), routingHeader, table, boundingBox, timestamp, pagingEnabled, tuplesPerPage); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); // Send query immediately flushPendingCompressionPackages(); return clientOperationFuture; } catch (BBoxDBException | ZookeeperException e) { // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for systems list"); Thread.currentThread().interrupt(); // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#queryTime(java.lang.String, long) */ @Override public TupleListFuture queryVersionTime(final String table, final long timestamp) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedTupleListFuture("queryTime called, but connection not ready: " + this, table); } try { final RoutingHeader routingHeader = RoutingHeaderHelper.getRoutingHeaderForLocalSystem( table, BoundingBox.EMPTY_BOX, true, serverAddress); final TupleListFuture clientOperationFuture = new TupleListFuture(1, new DoNothingDuplicateResolver(), table); final QueryVersionTimeRequest requestPackage = new QueryVersionTimeRequest(getNextSequenceNumber(), routingHeader, table, timestamp, pagingEnabled, tuplesPerPage); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); // Send query immediately flushPendingCompressionPackages(); return clientOperationFuture; } catch (BBoxDBException | ZookeeperException e) { // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for systems list"); Thread.currentThread().interrupt(); // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#queryTime(java.lang.String, long) */ @Override public TupleListFuture queryInsertedTime(final String table, final long timestamp) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedTupleListFuture("queryTime called, but connection not ready: " + this, table); } try { final RoutingHeader routingHeader = RoutingHeaderHelper.getRoutingHeaderForLocalSystem( table, BoundingBox.EMPTY_BOX, true, serverAddress); final TupleListFuture clientOperationFuture = new TupleListFuture(1, new DoNothingDuplicateResolver(), table); final QueryInsertTimeRequest requestPackage = new QueryInsertTimeRequest(getNextSequenceNumber(), routingHeader, table, timestamp, pagingEnabled, tuplesPerPage); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); // Send query immediately flushPendingCompressionPackages(); return clientOperationFuture; } catch (BBoxDBException | ZookeeperException e) { // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for systems list"); Thread.currentThread().interrupt(); // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#queryJoin */ @Override public JoinedTupleListFuture queryJoin(final List<String> tableNames, final BoundingBox boundingBox) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedJoinedTupleListFuture("queryTime called, but connection not ready: " + this); } try { final RoutingHeader routingHeader = RoutingHeaderHelper.getRoutingHeaderForLocalSystem( tableNames.get(0), boundingBox, true, serverAddress); final JoinedTupleListFuture clientOperationFuture = new JoinedTupleListFuture(1); final List<TupleStoreName> tupleStoreNames = tableNames .stream() .map(t -> new TupleStoreName(t)) .collect(Collectors.toList()); final QueryJoinRequest requestPackage = new QueryJoinRequest(getNextSequenceNumber(), routingHeader, tupleStoreNames, boundingBox, pagingEnabled, tuplesPerPage); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); // Send query immediately flushPendingCompressionPackages(); return clientOperationFuture; } catch (BBoxDBException | ZookeeperException e) { // Return after exception return FutureHelper.getFailedJoinedTupleListFuture(e.getMessage()); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for systems list"); Thread.currentThread().interrupt(); // Return after exception return FutureHelper.getFailedJoinedTupleListFuture(e.getMessage()); } } /** * Send a keep alive package to the server, to keep the TCP connection open. * @return */ public EmptyResultFuture sendKeepAlivePackage() { return sendKeepAlivePackage("", new ArrayList<>()); } /** * Send a keep alive package with some gossip * @param tablename * @param tuples * @return */ public EmptyResultFuture sendKeepAlivePackage(final String tablename, final List<Tuple> tuples) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedEmptyResultFuture("sendKeepAlivePackage called, but connection not ready: " + this); } final EmptyResultFuture clientOperationFuture = new EmptyResultFuture(1); final KeepAliveRequest requestPackage = new KeepAliveRequest(getNextSequenceNumber(), tablename, tuples); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /** * Get the next page for a given query * @param queryPackageId * @return */ public OperationFuture getNextPage(final short queryPackageId) { if(! getResultBuffer().containsKey(queryPackageId)) { final String errorMessage = "Query package " + queryPackageId + " not found in the result buffer"; logger.error(errorMessage); return FutureHelper.getFailedTupleListFuture(errorMessage, ""); } final TupleListFuture clientOperationFuture = new TupleListFuture(1, new DoNothingDuplicateResolver(), ""); final NextPageRequest requestPackage = new NextPageRequest( getNextSequenceNumber(), queryPackageId); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); // Send query immediately flushPendingCompressionPackages(); return clientOperationFuture; } /** * Cancel the given query on the server * @param queryPackageId * @return */ public EmptyResultFuture cancelQuery(final short queryPackageId) { final EmptyResultFuture clientOperationFuture = new EmptyResultFuture(1); final CancelQueryRequest requestPackage = new CancelQueryRequest(getNextSequenceNumber(), queryPackageId); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#isConnected() */ @Override public boolean isConnected() { if(clientSocket != null) { return ! clientSocket.isClosed(); } return false; } /** * Get the state of the connection */ public ServiceState getConnectionState() { return connectionState; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#getInFlightCalls() */ @Override public int getInFlightCalls() { synchronized (pendingCalls) { return pendingCalls.size(); } } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#getMaxInFlightCalls() */ @Override public short getMaxInFlightCalls() { return maxInFlightCalls; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#setMaxInFlightCalls(short) */ @Override public void setMaxInFlightCalls(short maxInFlightCalls) { this.maxInFlightCalls = (short) Math.min(maxInFlightCalls, MAX_IN_FLIGHT_CALLS); } /** * Send a request package to the server * @param responsePackage * @return * @throws IOException */ protected void sendPackageToServer(final NetworkRequestPackage requestPackage, final OperationFuture future) { future.setConnection(0, this); final short sequenceNumber = requestPackage.getSequenceNumber(); final boolean result = recalculateRoutingHeader(requestPackage, future); // Package don't need to be send if(result == false) { sequenceNumberGenerator.releaseNumber(sequenceNumber); return; } if(! networkOperationRetryer.isPackageIdKnown(sequenceNumber)) { networkOperationRetryer.registerOperation(sequenceNumber, requestPackage, future); } try { synchronized (pendingCalls) { // Ensure that not more then maxInFlightCalls are active while(pendingCalls.size() > maxInFlightCalls) { pendingCalls.wait(); } } } catch(InterruptedException e) { logger.warn("Got an exception while waiting for pending requests", e); Thread.currentThread().interrupt(); return; } if(connectionCapabilities.hasGZipCompression()) { writePackageWithCompression(requestPackage, future); } else { writePackageUncompressed(requestPackage, future); } } /** * Recalculate the routing header and handle the exceptions * @param requestPackage * @param future * @return */ private boolean recalculateRoutingHeader(final NetworkRequestPackage requestPackage, final OperationFuture future) { try { requestPackage.recalculateRoutingHeaderIfSupported(); // Check if package needs to be send final RoutingHeader routingHeader = requestPackage.getRoutingHeader(); if(routingHeader.isRoutedPackage()) { if(routingHeader.getHopCount() == 0) { future.setMessage(0, "No distribution regions in next hop, not sending to server"); future.fireCompleteEvent(); return false; } } } catch (PackageEncodeException e) { final String message = "Got a exception during package encoding"; logger.error(message); future.setMessage(0, message); future.setFailedState(); future.fireCompleteEvent(); return false; } return true; } /** * Write a package uncompresssed to the socket * @param requestPackage * @param future */ protected void writePackageUncompressed(final NetworkRequestPackage requestPackage, final OperationFuture future) { try { writePackageToSocket(requestPackage); } catch (IOException | PackageEncodeException e) { logger.warn("Got an exception while sending package to server", e); future.setFailedState(); future.fireCompleteEvent(); terminateConnection(); } } /** * Handle compression and package chunking * @param requestPackage * @param future */ protected void writePackageWithCompression(NetworkRequestPackage requestPackage, OperationFuture future) { boolean queueFull = false; synchronized (pendingCompressionPackages) { pendingCompressionPackages.add(requestPackage); queueFull = pendingCompressionPackages.size() >= Const.MAX_UNCOMPRESSED_QUEUE_SIZE; } if(queueFull) { flushPendingCompressionPackages(); } } /** * Write all pending compression packages to server, called by the maintainance thread * */ protected void flushPendingCompressionPackages() { final List<NetworkRequestPackage> packagesToWrite = new ArrayList<>(); synchronized (pendingCompressionPackages) { if(pendingCompressionPackages.isEmpty()) { return; } packagesToWrite.addAll(pendingCompressionPackages); pendingCompressionPackages.clear(); } if(logger.isDebugEnabled()) { logger.debug("Chunk size is: {}", packagesToWrite.size()); } final NetworkRequestPackage compressionEnvelopeRequest = new CompressionEnvelopeRequest(NetworkConst.COMPRESSION_TYPE_GZIP, packagesToWrite); try { writePackageToSocket(compressionEnvelopeRequest); } catch (PackageEncodeException | IOException e) { logger.error("Got an exception while write pending compression packages to server", e); terminateConnection(); } } /** * Write the package onto the socket * @param requestPackage * @throws PackageEncodeException * @throws IOException */ protected void writePackageToSocket(final NetworkRequestPackage requestPackage) throws PackageEncodeException, IOException { synchronized (outputStream) { requestPackage.writeToOutputStream(outputStream); outputStream.flush(); } // Could be null during handshake if(mainteinanceHandler != null) { mainteinanceHandler.updateLastDataSendTimestamp(); } } /** * Register a new package callback * @param requestPackage * @param future * @return */ protected short registerPackageCallback(final NetworkRequestPackage requestPackage, final OperationFuture future) { final short sequenceNumber = requestPackage.getSequenceNumber(); future.setRequestId(0, sequenceNumber); synchronized (pendingCalls) { assert (! pendingCalls.containsKey(sequenceNumber)) : "Old call exists: " + pendingCalls.get(sequenceNumber); pendingCalls.put(sequenceNumber, future); } return sequenceNumber; } /** * Handle the next result package * @param packageHeader * @throws PackageEncodeException */ protected void handleResultPackage(final ByteBuffer encodedPackage) throws PackageEncodeException { final short sequenceNumber = NetworkPackageDecoder.getRequestIDFromResponsePackage(encodedPackage); final short packageType = NetworkPackageDecoder.getPackageTypeFromResponse(encodedPackage); OperationFuture future = null; synchronized (pendingCalls) { future = pendingCalls.get(Short.valueOf(sequenceNumber)); } if(! serverResponseHandler.containsKey(packageType)) { logger.error("Unknown respose package type: {}", packageType); sequenceNumberGenerator.releaseNumber(sequenceNumber); if(future != null) { future.setFailedState(); future.fireCompleteEvent(); } } else { final ServerResponseHandler handler = serverResponseHandler.get(packageType); final boolean removeFuture = handler.handleServerResult(this, encodedPackage, future); // Remove pending call if(removeFuture) { synchronized (pendingCalls) { sequenceNumberGenerator.releaseNumber(sequenceNumber); pendingCalls.remove(Short.valueOf(sequenceNumber)); pendingCalls.notifyAll(); } } } } /** * Read the full package * @param packageHeader * @param inputStream2 * @return * @throws IOException */ protected ByteBuffer readFullPackage(final ByteBuffer packageHeader, final InputStream inputStream) throws IOException { final int bodyLength = (int) NetworkPackageDecoder.getBodyLengthFromResponsePackage(packageHeader); final int headerLength = packageHeader.limit(); final ByteBuffer encodedPackage = ByteBuffer.allocate(headerLength + bodyLength); //System.out.println("Trying to read: " + bodyLength + " avail " + inputStream.available()); encodedPackage.put(packageHeader.array()); ByteStreams.readFully(inputStream, encodedPackage.array(), encodedPackage.position(), bodyLength); return encodedPackage; } @Override public String toString() { return "BBoxDBClient [serverHostname=" + serverAddress.getHostString() + ", serverPort=" + serverAddress.getPort() + ", pendingCalls=" + pendingCalls.size() + ", connectionState=" + connectionState + "]"; } /** * Get the capabilities (e.g. gzip compression) of the client */ public PeerCapabilities getConnectionCapabilities() { return connectionCapabilities; } /** * Get the capabilities of the client * @return */ public PeerCapabilities getClientCapabilities() { return clientCapabilities; } /** * Is the paging for queries enables * @return */ public boolean isPagingEnabled() { return pagingEnabled; } /** * Enable or disable paging * @param pagingEnabled */ public void setPagingEnabled(final boolean pagingEnabled) { this.pagingEnabled = pagingEnabled; } /** * Get the amount of tuples per page * @return */ public short getTuplesPerPage() { return tuplesPerPage; } /** * Set the tuples per page * @param tuplesPerPage */ public void setTuplesPerPage(final short tuplesPerPage) { this.tuplesPerPage = tuplesPerPage; } /** * Get the result buffer * @return */ public Map<Short, List<PagedTransferableEntity>> getResultBuffer() { return resultBuffer; } /** * Get the network operation retryer * @return */ public NetworkOperationRetryer getNetworkOperationRetryer() { return networkOperationRetryer; } /** * Get the server response reader * @return */ public ServerResponseReader getServerResponseReader() { return serverResponseReader; } /** * The tuple store manager registry * @return */ public TupleStoreManagerRegistry getTupleStoreManagerRegistry() { return tupleStoreManagerRegistry; } /** * The tuple store manager registry * @param tupleStoreManagerRegistry */ public void setTupleStoreManagerRegistry(final TupleStoreManagerRegistry tupleStoreManagerRegistry) { this.tupleStoreManagerRegistry = tupleStoreManagerRegistry; } }
bboxdb-server/src/main/java/org/bboxdb/network/client/BBoxDBClient.java
/******************************************************************************* * * Copyright (C) 2015-2018 the BBoxDB project * * 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.bboxdb.network.client; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Inet4Address; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import java.util.stream.Collectors; import org.bboxdb.commons.CloseableHelper; import org.bboxdb.commons.DuplicateResolver; import org.bboxdb.commons.MicroSecondTimestampProvider; import org.bboxdb.commons.NetworkInterfaceHelper; import org.bboxdb.commons.ServiceState; import org.bboxdb.distribution.TupleStoreConfigurationCache; import org.bboxdb.distribution.zookeeper.ZookeeperException; import org.bboxdb.misc.Const; import org.bboxdb.network.NetworkConst; import org.bboxdb.network.NetworkPackageDecoder; import org.bboxdb.network.capabilities.PeerCapabilities; import org.bboxdb.network.client.future.EmptyResultFuture; import org.bboxdb.network.client.future.FutureHelper; import org.bboxdb.network.client.future.HelloFuture; import org.bboxdb.network.client.future.JoinedTupleListFuture; import org.bboxdb.network.client.future.OperationFuture; import org.bboxdb.network.client.future.SSTableNameListFuture; import org.bboxdb.network.client.future.TupleListFuture; import org.bboxdb.network.client.response.CompressionHandler; import org.bboxdb.network.client.response.ErrorHandler; import org.bboxdb.network.client.response.HelloHandler; import org.bboxdb.network.client.response.JoinedTupleHandler; import org.bboxdb.network.client.response.ListTablesHandler; import org.bboxdb.network.client.response.MultipleTupleEndHandler; import org.bboxdb.network.client.response.MultipleTupleStartHandler; import org.bboxdb.network.client.response.PageEndHandler; import org.bboxdb.network.client.response.ServerResponseHandler; import org.bboxdb.network.client.response.SuccessHandler; import org.bboxdb.network.client.response.TupleHandler; import org.bboxdb.network.packages.NetworkRequestPackage; import org.bboxdb.network.packages.PackageEncodeException; import org.bboxdb.network.packages.request.CancelQueryRequest; import org.bboxdb.network.packages.request.CompressionEnvelopeRequest; import org.bboxdb.network.packages.request.CreateDistributionGroupRequest; import org.bboxdb.network.packages.request.CreateTableRequest; import org.bboxdb.network.packages.request.DeleteDistributionGroupRequest; import org.bboxdb.network.packages.request.DeleteTableRequest; import org.bboxdb.network.packages.request.DeleteTupleRequest; import org.bboxdb.network.packages.request.DisconnectRequest; import org.bboxdb.network.packages.request.HelloRequest; import org.bboxdb.network.packages.request.InsertTupleRequest; import org.bboxdb.network.packages.request.KeepAliveRequest; import org.bboxdb.network.packages.request.ListTablesRequest; import org.bboxdb.network.packages.request.NextPageRequest; import org.bboxdb.network.packages.request.QueryBoundingBoxContinuousRequest; import org.bboxdb.network.packages.request.QueryBoundingBoxRequest; import org.bboxdb.network.packages.request.QueryBoundingBoxTimeRequest; import org.bboxdb.network.packages.request.QueryInsertTimeRequest; import org.bboxdb.network.packages.request.QueryJoinRequest; import org.bboxdb.network.packages.request.QueryKeyRequest; import org.bboxdb.network.packages.request.QueryVersionTimeRequest; import org.bboxdb.network.packages.response.HelloResponse; import org.bboxdb.network.routing.RoutingHeader; import org.bboxdb.storage.entity.BoundingBox; import org.bboxdb.storage.entity.DistributionGroupConfiguration; import org.bboxdb.storage.entity.PagedTransferableEntity; import org.bboxdb.storage.entity.Tuple; import org.bboxdb.storage.entity.TupleStoreConfiguration; import org.bboxdb.storage.entity.TupleStoreName; import org.bboxdb.storage.sstable.duplicateresolver.DoNothingDuplicateResolver; import org.bboxdb.storage.tuplestore.manager.TupleStoreManagerRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.io.ByteStreams; public class BBoxDBClient implements BBoxDB { /** * The sequence number generator */ protected final SequenceNumberGenerator sequenceNumberGenerator; /** * The socket of the connection */ protected Socket clientSocket = null; /** * The input stream of the socket */ protected BufferedInputStream inputStream; /** * The output stream of the socket */ protected BufferedOutputStream outputStream; /** * The pending calls */ protected final Map<Short, OperationFuture> pendingCalls = new HashMap<>(); /** * The result buffer */ protected final Map<Short, List<PagedTransferableEntity>> resultBuffer = new HashMap<>(); /** * The retryer */ protected final NetworkOperationRetryer networkOperationRetryer; /** * The server response reader */ protected ServerResponseReader serverResponseReader; /** * The server response reader thread */ protected Thread serverResponseReaderThread; /** * The maintenance handler instance */ protected ConnectionMainteinanceThread mainteinanceHandler; /** * The maintenance thread */ protected Thread mainteinanceThread; /** * The default timeout */ public static final long DEFAULT_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(30); /** * The connection state */ protected final ServiceState connectionState; /** * The number of in flight requests * @return */ protected volatile short maxInFlightCalls = MAX_IN_FLIGHT_CALLS; /** * The capabilities of the connection */ protected PeerCapabilities connectionCapabilities = new PeerCapabilities(); /** * The capabilities of the client */ protected PeerCapabilities clientCapabilities = new PeerCapabilities(); /** * Is the paging for queries enabled? */ protected boolean pagingEnabled; /** * The amount of tuples per page */ protected short tuplesPerPage; /** * The tuple store manager registry (used for gossip) */ protected TupleStoreManagerRegistry tupleStoreManagerRegistry; /** * The pending packages for compression */ protected final List<NetworkRequestPackage> pendingCompressionPackages; /** * The Server response handler */ protected final Map<Short, ServerResponseHandler> serverResponseHandler; /** * The server address */ protected InetSocketAddress serverAddress; /** * The Logger */ private final static Logger logger = LoggerFactory.getLogger(BBoxDBClient.class); @VisibleForTesting public BBoxDBClient() { this(new InetSocketAddress("localhost", 1234)); } public BBoxDBClient(final InetSocketAddress serverAddress) { this.serverAddress = Objects.requireNonNull(serverAddress); // External IP is used to create proper package routing if(serverAddress.getAddress().isLoopbackAddress()) { try { final Inet4Address nonLoopbackAdress = NetworkInterfaceHelper.getFirstNonLoopbackIPv4(); this.serverAddress = new InetSocketAddress(nonLoopbackAdress, serverAddress.getPort()); } catch (SocketException e) { logger.error("Connection to loopback IP " + serverAddress + " requested and unable replace the IP with external IP", e); } } this.sequenceNumberGenerator = new SequenceNumberGenerator(); this.connectionState = new ServiceState(); // Default: Enable gzip compression clientCapabilities.setGZipCompression(); pagingEnabled = true; tuplesPerPage = 50; pendingCompressionPackages = new ArrayList<>(); serverResponseHandler = new HashMap<>(); networkOperationRetryer = new NetworkOperationRetryer((p, f) -> {sendPackageToServer(p, f);}); initResponseHandler(); } /** * Init the response handler */ protected void initResponseHandler() { serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_COMPRESSION, new CompressionHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_HELLO, new HelloHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_SUCCESS, new SuccessHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_ERROR, new ErrorHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_LIST_TABLES, new ListTablesHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_TUPLE, new TupleHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_MULTIPLE_TUPLE_START, new MultipleTupleStartHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_MULTIPLE_TUPLE_END, new MultipleTupleEndHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_PAGE_END, new PageEndHandler()); serverResponseHandler.put(NetworkConst.RESPONSE_TYPE_JOINED_TUPLE, new JoinedTupleHandler()); } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#connect() */ @Override public boolean connect() { if(clientSocket != null || ! connectionState.isInNewState()) { logger.warn("Connect() called on an active connection, ignoring (state: {})", connectionState); return true; } logger.debug("Connecting to server: {}", getConnectionName()); try { connectionState.dipatchToStarting(); connectionState.registerCallback((c) -> { if(c.isInFailedState() ) { killPendingCalls(); } }); clientSocket = new Socket(serverAddress.getAddress(), serverAddress.getPort()); inputStream = new BufferedInputStream(clientSocket.getInputStream()); outputStream = new BufferedOutputStream(clientSocket.getOutputStream()); synchronized (pendingCalls) { pendingCalls.clear(); } getResultBuffer().clear(); // Start up the response reader serverResponseReader = new ServerResponseReader(this); serverResponseReaderThread = new Thread(serverResponseReader); serverResponseReaderThread.setName("Server response reader for " + getConnectionName()); serverResponseReaderThread.start(); runHandshake(); } catch (Exception e) { logger.error("Got an exception while connecting to server", e); closeSocket(); connectionState.dispatchToFailed(e); return false; } return true; } /** * Close the socket */ public void closeSocket() { logger.info("Closing socket to server: {}", getConnectionName()); CloseableHelper.closeWithoutException(clientSocket); clientSocket = null; } /** * The name of the connection * @return */ public String getConnectionName() { return serverAddress.getHostString() + " / " + serverAddress.getPort(); } /** * Get the next sequence number * @return */ protected short getNextSequenceNumber() { return sequenceNumberGenerator.getNextSequenceNummber(); } /** * Run the handshake with the server * @throws ExecutionException * @throws InterruptedException */ protected void runHandshake() throws Exception { final HelloFuture operationFuture = new HelloFuture(1); if(! connectionState.isInStartingState()) { logger.error("Handshaking called in wrong state: {}", connectionState); } // Capabilities are reported to server; now freeze client capabilities. clientCapabilities.freeze(); final HelloRequest requestPackage = new HelloRequest(getNextSequenceNumber(), NetworkConst.PROTOCOL_VERSION, clientCapabilities); registerPackageCallback(requestPackage, operationFuture); sendPackageToServer(requestPackage, operationFuture); operationFuture.waitForAll(); if(operationFuture.isFailed()) { throw new Exception("Got an error during handshake"); } final HelloResponse helloResponse = operationFuture.get(0); connectionCapabilities = helloResponse.getPeerCapabilities(); connectionState.dispatchToRunning(); logger.debug("Handshaking with {} done", getConnectionName()); mainteinanceHandler = new ConnectionMainteinanceThread(this); mainteinanceThread = new Thread(mainteinanceHandler); mainteinanceThread.setName("Connection mainteinace thread for: " + getConnectionName()); mainteinanceThread.start(); } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#disconnect() */ @Override public void disconnect() { if(! connectionState.isInRunningState()) { logger.error("Unable to disconnect, connection is in state {}", connectionState); return; } synchronized (this) { logger.info("Disconnecting from server: {}", getConnectionName()); connectionState.dispatchToStopping(); final DisconnectRequest requestPackage = new DisconnectRequest(getNextSequenceNumber()); final EmptyResultFuture operationFuture = new EmptyResultFuture(1); registerPackageCallback(requestPackage, operationFuture); sendPackageToServer(requestPackage, operationFuture); } settlePendingCalls(DEFAULT_TIMEOUT_MILLIS); terminateConnection(); } /** * Settle all pending calls */ public void settlePendingCalls(final long shutdownTimeMillis) { final long shutdownStarted = System.currentTimeMillis(); // Wait for all pending calls to settle synchronized (pendingCalls) { while(getInFlightCalls() > 0) { final long shutdownDuration = System.currentTimeMillis() - shutdownStarted; final long timeoutLeft = shutdownTimeMillis - shutdownDuration; if(timeoutLeft <= 0) { break; } if(! isConnected()) { logger.warn("Connection already closed but {} requests are pending", getInFlightCalls()); return; } logger.info("Waiting up to {} seconds for pending requests to settle " + "(pending {} / server {})", TimeUnit.MILLISECONDS.toSeconds(timeoutLeft), getInFlightCalls(), getConnectionName()); try { // Recheck connection state all 5 seconds final long maxWaitTime = Math.min(timeoutLeft, TimeUnit.SECONDS.toMillis(5)); pendingCalls.wait(maxWaitTime); } catch (InterruptedException e) { logger.debug("Got an InterruptedException during pending calls wait."); Thread.currentThread().interrupt(); return; } } if(! pendingCalls.isEmpty()) { logger.warn("Connection is closed. Still pending calls: {} ", pendingCalls); } } } /** * Kill all pending requests */ protected void killPendingCalls() { synchronized (pendingCalls) { if(! pendingCalls.isEmpty()) { logger.warn("Socket is closed unexpected, killing pending calls: " + pendingCalls.size()); for(final short requestId : pendingCalls.keySet()) { final OperationFuture future = pendingCalls.get(requestId); future.setFailedState(); future.fireCompleteEvent(); } pendingCalls.clear(); pendingCalls.notifyAll(); } } } /** * Close the connection to the server without sending a disconnect package. For a * regular disconnect, see the disconnect() method. */ public void terminateConnection() { if(connectionState.isInRunningState()) { connectionState.dispatchToStopping(); } killPendingCalls(); getResultBuffer().clear(); closeSocket(); logger.info("Disconnected from server: {}", getConnectionName()); connectionState.forceDispatchToTerminated(); } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#createTable(java.lang.String) */ @Override public EmptyResultFuture createTable(final String table, final TupleStoreConfiguration configuration) throws BBoxDBException { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedEmptyResultFuture("createTable called, but connection not ready: " + this); } final EmptyResultFuture clientOperationFuture = new EmptyResultFuture(1); final CreateTableRequest requestPackage = new CreateTableRequest(getNextSequenceNumber(), table, configuration); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#deleteTable(java.lang.String) */ @Override public EmptyResultFuture deleteTable(final String table) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedEmptyResultFuture("deleteTable called, but connection not ready: " + this); } final EmptyResultFuture clientOperationFuture = new EmptyResultFuture(1); final DeleteTableRequest requestPackage = new DeleteTableRequest(getNextSequenceNumber(), table); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#insertTuple(java.lang.String, org.bboxdb.storage.entity.Tuple) */ @Override public EmptyResultFuture insertTuple(final String table, final Tuple tuple) throws BBoxDBException { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedEmptyResultFuture("insertTuple called, but connection not ready: " + this); } final Supplier<RoutingHeader> routingHeader = () -> RoutingHeaderHelper.getRoutingHeaderForLocalSystemNE( table, tuple.getBoundingBox(), false, serverAddress); return insertTuple(table, tuple, routingHeader); } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#insertTuple(java.lang.String, org.bboxdb.storage.entity.Tuple) */ public EmptyResultFuture insertTuple(final String table, final Tuple tuple, final Supplier<RoutingHeader> routingHeaderSupplier) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedEmptyResultFuture("insertTuple called, but connection not ready: " + this); } final EmptyResultFuture clientOperationFuture = new EmptyResultFuture(1); final TupleStoreName ssTableName = new TupleStoreName(table); final short sequenceNumber = getNextSequenceNumber(); final InsertTupleRequest requestPackage = new InsertTupleRequest( sequenceNumber, routingHeaderSupplier, ssTableName, tuple); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#deleteTuple(java.lang.String, java.lang.String) */ @Override public EmptyResultFuture deleteTuple(final String table, final String key, final long timestamp) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedEmptyResultFuture("deleteTuple called, but connection not ready: " + this); } final EmptyResultFuture clientOperationFuture = new EmptyResultFuture(1); final Supplier<RoutingHeader> routingHeaderSupplier = () -> RoutingHeaderHelper.getRoutingHeaderForLocalSystemNE( table, BoundingBox.EMPTY_BOX, true, serverAddress); final short sequenceNumber = getNextSequenceNumber(); final DeleteTupleRequest requestPackage = new DeleteTupleRequest(sequenceNumber, routingHeaderSupplier, table, key, timestamp); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#deleteTuple(java.lang.String, java.lang.String) */ @Override public EmptyResultFuture deleteTuple(final String table, final String key) throws BBoxDBException { final long timestamp = MicroSecondTimestampProvider.getNewTimestamp(); return deleteTuple(table, key, timestamp); } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#listTables() */ @Override public SSTableNameListFuture listTables() { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedSStableNameFuture("listTables called, but connection not ready: " + this); } final SSTableNameListFuture clientOperationFuture = new SSTableNameListFuture(1); final ListTablesRequest requestPackage = new ListTablesRequest(getNextSequenceNumber()); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#createDistributionGroup(java.lang.String, short) */ @Override public EmptyResultFuture createDistributionGroup(final String distributionGroup, final DistributionGroupConfiguration distributionGroupConfiguration) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedEmptyResultFuture("listTables called, but connection not ready: " + this); } final EmptyResultFuture clientOperationFuture = new EmptyResultFuture(1); final CreateDistributionGroupRequest requestPackage = new CreateDistributionGroupRequest( getNextSequenceNumber(), distributionGroup, distributionGroupConfiguration); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#deleteDistributionGroup(java.lang.String) */ @Override public EmptyResultFuture deleteDistributionGroup(final String distributionGroup) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedEmptyResultFuture("delete distribution group called, but connection not ready: " + this); } final EmptyResultFuture clientOperationFuture = new EmptyResultFuture(1); final DeleteDistributionGroupRequest requestPackage = new DeleteDistributionGroupRequest( getNextSequenceNumber(), distributionGroup); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#queryKey(java.lang.String, java.lang.String) */ @Override public TupleListFuture queryKey(final String table, final String key) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedTupleListFuture("queryKey called, but connection not ready: " + this, table); } try { final RoutingHeader routingHeader = RoutingHeaderHelper.getRoutingHeaderForLocalSystem( table, BoundingBox.EMPTY_BOX, true, serverAddress); final DuplicateResolver<Tuple> duplicateResolver = TupleStoreConfigurationCache.getInstance().getDuplicateResolverForTupleStore(table); final TupleListFuture clientOperationFuture = new TupleListFuture(1, duplicateResolver, table); final QueryKeyRequest requestPackage = new QueryKeyRequest(getNextSequenceNumber(), routingHeader, table, key, pagingEnabled, tuplesPerPage); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); // Send query immediately flushPendingCompressionPackages(); return clientOperationFuture; } catch (BBoxDBException | ZookeeperException e) { // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for systems list"); Thread.currentThread().interrupt(); // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#queryBoundingBox(java.lang.String, org.bboxdb.storage.entity.BoundingBox) */ @Override public TupleListFuture queryBoundingBox(final String table, final BoundingBox boundingBox) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedTupleListFuture("queryBoundingBox called, but connection not ready: " + this, table); } try { final RoutingHeader routingHeader = RoutingHeaderHelper.getRoutingHeaderForLocalSystem( table, boundingBox, false, serverAddress); final TupleListFuture clientOperationFuture = new TupleListFuture(1, new DoNothingDuplicateResolver(), table); final QueryBoundingBoxRequest requestPackage = new QueryBoundingBoxRequest(getNextSequenceNumber(), routingHeader, table, boundingBox, pagingEnabled, tuplesPerPage); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); // Send query immediately flushPendingCompressionPackages(); return clientOperationFuture; } catch (BBoxDBException | ZookeeperException e) { // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for systems list"); Thread.currentThread().interrupt(); // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } } /** * Execute a continuous bounding box query * */ @Override public TupleListFuture queryBoundingBoxContinuous(final String table, final BoundingBox boundingBox) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedTupleListFuture("queryBoundingBoxContinuous called, but connection not ready: " + this, table); } try { final RoutingHeader routingHeader = RoutingHeaderHelper.getRoutingHeaderForLocalSystem( table, boundingBox, false, serverAddress); final TupleListFuture clientOperationFuture = new TupleListFuture(1, new DoNothingDuplicateResolver(), table); final QueryBoundingBoxContinuousRequest requestPackage = new QueryBoundingBoxContinuousRequest(getNextSequenceNumber(), routingHeader, table, boundingBox); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); // Send query immediately flushPendingCompressionPackages(); return clientOperationFuture; } catch (BBoxDBException | ZookeeperException e) { // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for systems list"); Thread.currentThread().interrupt(); // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#queryBoundingBoxAndTime(java.lang.String, org.bboxdb.storage.entity.BoundingBox) */ @Override public TupleListFuture queryBoundingBoxAndTime(final String table, final BoundingBox boundingBox, final long timestamp) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedTupleListFuture("queryBoundingBox called, but connection not ready: " + this, table); } try { final RoutingHeader routingHeader = RoutingHeaderHelper.getRoutingHeaderForLocalSystem( table, boundingBox, false, serverAddress); final TupleListFuture clientOperationFuture = new TupleListFuture(1, new DoNothingDuplicateResolver(), table); final QueryBoundingBoxTimeRequest requestPackage = new QueryBoundingBoxTimeRequest(getNextSequenceNumber(), routingHeader, table, boundingBox, timestamp, pagingEnabled, tuplesPerPage); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); // Send query immediately flushPendingCompressionPackages(); return clientOperationFuture; } catch (BBoxDBException | ZookeeperException e) { // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for systems list"); Thread.currentThread().interrupt(); // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#queryTime(java.lang.String, long) */ @Override public TupleListFuture queryVersionTime(final String table, final long timestamp) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedTupleListFuture("queryTime called, but connection not ready: " + this, table); } try { final RoutingHeader routingHeader = RoutingHeaderHelper.getRoutingHeaderForLocalSystem( table, BoundingBox.EMPTY_BOX, true, serverAddress); final TupleListFuture clientOperationFuture = new TupleListFuture(1, new DoNothingDuplicateResolver(), table); final QueryVersionTimeRequest requestPackage = new QueryVersionTimeRequest(getNextSequenceNumber(), routingHeader, table, timestamp, pagingEnabled, tuplesPerPage); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); // Send query immediately flushPendingCompressionPackages(); return clientOperationFuture; } catch (BBoxDBException | ZookeeperException e) { // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for systems list"); Thread.currentThread().interrupt(); // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#queryTime(java.lang.String, long) */ @Override public TupleListFuture queryInsertedTime(final String table, final long timestamp) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedTupleListFuture("queryTime called, but connection not ready: " + this, table); } try { final RoutingHeader routingHeader = RoutingHeaderHelper.getRoutingHeaderForLocalSystem( table, BoundingBox.EMPTY_BOX, true, serverAddress); final TupleListFuture clientOperationFuture = new TupleListFuture(1, new DoNothingDuplicateResolver(), table); final QueryInsertTimeRequest requestPackage = new QueryInsertTimeRequest(getNextSequenceNumber(), routingHeader, table, timestamp, pagingEnabled, tuplesPerPage); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); // Send query immediately flushPendingCompressionPackages(); return clientOperationFuture; } catch (BBoxDBException | ZookeeperException e) { // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for systems list"); Thread.currentThread().interrupt(); // Return after exception return FutureHelper.getFailedTupleListFuture(e.getMessage(), table); } } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#queryJoin */ @Override public JoinedTupleListFuture queryJoin(final List<String> tableNames, final BoundingBox boundingBox) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedJoinedTupleListFuture("queryTime called, but connection not ready: " + this); } try { final RoutingHeader routingHeader = RoutingHeaderHelper.getRoutingHeaderForLocalSystem( tableNames.get(0), boundingBox, true, serverAddress); final JoinedTupleListFuture clientOperationFuture = new JoinedTupleListFuture(1); final List<TupleStoreName> tupleStoreNames = tableNames .stream() .map(t -> new TupleStoreName(t)) .collect(Collectors.toList()); final QueryJoinRequest requestPackage = new QueryJoinRequest(getNextSequenceNumber(), routingHeader, tupleStoreNames, boundingBox, pagingEnabled, tuplesPerPage); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); // Send query immediately flushPendingCompressionPackages(); return clientOperationFuture; } catch (BBoxDBException | ZookeeperException e) { // Return after exception return FutureHelper.getFailedJoinedTupleListFuture(e.getMessage()); } catch (InterruptedException e) { logger.warn("Interrupted while waiting for systems list"); Thread.currentThread().interrupt(); // Return after exception return FutureHelper.getFailedJoinedTupleListFuture(e.getMessage()); } } /** * Send a keep alive package to the server, to keep the TCP connection open. * @return */ public EmptyResultFuture sendKeepAlivePackage() { return sendKeepAlivePackage("", new ArrayList<>()); } /** * Send a keep alive package with some gossip * @param tablename * @param tuples * @return */ public EmptyResultFuture sendKeepAlivePackage(final String tablename, final List<Tuple> tuples) { if(! connectionState.isInRunningState()) { return FutureHelper.getFailedEmptyResultFuture("sendKeepAlivePackage called, but connection not ready: " + this); } final EmptyResultFuture clientOperationFuture = new EmptyResultFuture(1); final KeepAliveRequest requestPackage = new KeepAliveRequest(getNextSequenceNumber(), tablename, tuples); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /** * Get the next page for a given query * @param queryPackageId * @return */ public OperationFuture getNextPage(final short queryPackageId) { if(! getResultBuffer().containsKey(queryPackageId)) { final String errorMessage = "Query package " + queryPackageId + " not found in the result buffer"; logger.error(errorMessage); return FutureHelper.getFailedTupleListFuture(errorMessage, ""); } final TupleListFuture clientOperationFuture = new TupleListFuture(1, new DoNothingDuplicateResolver(), ""); final NextPageRequest requestPackage = new NextPageRequest( getNextSequenceNumber(), queryPackageId); registerPackageCallback(requestPackage, clientOperationFuture); sendPackageToServer(requestPackage, clientOperationFuture); // Send query immediately flushPendingCompressionPackages(); return clientOperationFuture; } /** * Cancel the given query on the server * @param queryPackageId * @return */ public EmptyResultFuture cancelQuery(final short queryPackageId) { final EmptyResultFuture clientOperationFuture = new EmptyResultFuture(1); final CancelQueryRequest requestPackage = new CancelQueryRequest(getNextSequenceNumber(), queryPackageId); sendPackageToServer(requestPackage, clientOperationFuture); return clientOperationFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#isConnected() */ @Override public boolean isConnected() { if(clientSocket != null) { return ! clientSocket.isClosed(); } return false; } /** * Get the state of the connection */ public ServiceState getConnectionState() { return connectionState; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#getInFlightCalls() */ @Override public int getInFlightCalls() { synchronized (pendingCalls) { return pendingCalls.size(); } } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#getMaxInFlightCalls() */ @Override public short getMaxInFlightCalls() { return maxInFlightCalls; } /* (non-Javadoc) * @see org.bboxdb.network.client.BBoxDB#setMaxInFlightCalls(short) */ @Override public void setMaxInFlightCalls(short maxInFlightCalls) { this.maxInFlightCalls = (short) Math.min(maxInFlightCalls, MAX_IN_FLIGHT_CALLS); } /** * Send a request package to the server * @param responsePackage * @return * @throws IOException */ protected void sendPackageToServer(final NetworkRequestPackage requestPackage, final OperationFuture future) { future.setConnection(0, this); final boolean result = recalculateRoutingHeader(requestPackage, future); // Package don't need to be send if(result == false) { return; } final short sequenceNumber = requestPackage.getSequenceNumber(); if(! networkOperationRetryer.isPackageIdKnown(sequenceNumber)) { networkOperationRetryer.registerOperation(sequenceNumber, requestPackage, future); } try { synchronized (pendingCalls) { // Ensure that not more then maxInFlightCalls are active while(pendingCalls.size() > maxInFlightCalls) { pendingCalls.wait(); } } } catch(InterruptedException e) { logger.warn("Got an exception while waiting for pending requests", e); Thread.currentThread().interrupt(); return; } if(connectionCapabilities.hasGZipCompression()) { writePackageWithCompression(requestPackage, future); } else { writePackageUncompressed(requestPackage, future); } } /** * Recalculate the routing header and handle the exceptions * @param requestPackage * @param future * @return */ private boolean recalculateRoutingHeader(final NetworkRequestPackage requestPackage, final OperationFuture future) { try { requestPackage.recalculateRoutingHeaderIfSupported(); // Check if package needs to be send final RoutingHeader routingHeader = requestPackage.getRoutingHeader(); if(routingHeader.isRoutedPackage()) { if(routingHeader.getHopCount() == 0) { future.setMessage(0, "No distribution regions in next hop, not sending to server"); future.fireCompleteEvent(); return false; } } } catch (PackageEncodeException e) { final String message = "Got a exception during package encoding"; logger.error(message); future.setMessage(0, message); future.setFailedState(); future.fireCompleteEvent(); return false; } return true; } /** * Write a package uncompresssed to the socket * @param requestPackage * @param future */ protected void writePackageUncompressed(final NetworkRequestPackage requestPackage, final OperationFuture future) { try { writePackageToSocket(requestPackage); } catch (IOException | PackageEncodeException e) { logger.warn("Got an exception while sending package to server", e); future.setFailedState(); future.fireCompleteEvent(); terminateConnection(); } } /** * Handle compression and package chunking * @param requestPackage * @param future */ protected void writePackageWithCompression(NetworkRequestPackage requestPackage, OperationFuture future) { boolean queueFull = false; synchronized (pendingCompressionPackages) { pendingCompressionPackages.add(requestPackage); queueFull = pendingCompressionPackages.size() >= Const.MAX_UNCOMPRESSED_QUEUE_SIZE; } if(queueFull) { flushPendingCompressionPackages(); } } /** * Write all pending compression packages to server, called by the maintainance thread * */ protected void flushPendingCompressionPackages() { final List<NetworkRequestPackage> packagesToWrite = new ArrayList<>(); synchronized (pendingCompressionPackages) { if(pendingCompressionPackages.isEmpty()) { return; } packagesToWrite.addAll(pendingCompressionPackages); pendingCompressionPackages.clear(); } if(logger.isDebugEnabled()) { logger.debug("Chunk size is: {}", packagesToWrite.size()); } final NetworkRequestPackage compressionEnvelopeRequest = new CompressionEnvelopeRequest(NetworkConst.COMPRESSION_TYPE_GZIP, packagesToWrite); try { writePackageToSocket(compressionEnvelopeRequest); } catch (PackageEncodeException | IOException e) { logger.error("Got an exception while write pending compression packages to server", e); terminateConnection(); } } /** * Write the package onto the socket * @param requestPackage * @throws PackageEncodeException * @throws IOException */ protected void writePackageToSocket(final NetworkRequestPackage requestPackage) throws PackageEncodeException, IOException { synchronized (outputStream) { requestPackage.writeToOutputStream(outputStream); outputStream.flush(); } // Could be null during handshake if(mainteinanceHandler != null) { mainteinanceHandler.updateLastDataSendTimestamp(); } } /** * Register a new package callback * @param requestPackage * @param future * @return */ protected short registerPackageCallback(final NetworkRequestPackage requestPackage, final OperationFuture future) { final short sequenceNumber = requestPackage.getSequenceNumber(); future.setRequestId(0, sequenceNumber); synchronized (pendingCalls) { assert (! pendingCalls.containsKey(sequenceNumber)) : "Old call exists: " + pendingCalls.get(sequenceNumber); pendingCalls.put(sequenceNumber, future); } return sequenceNumber; } /** * Handle the next result package * @param packageHeader * @throws PackageEncodeException */ protected void handleResultPackage(final ByteBuffer encodedPackage) throws PackageEncodeException { final short sequenceNumber = NetworkPackageDecoder.getRequestIDFromResponsePackage(encodedPackage); final short packageType = NetworkPackageDecoder.getPackageTypeFromResponse(encodedPackage); OperationFuture future = null; synchronized (pendingCalls) { future = pendingCalls.get(Short.valueOf(sequenceNumber)); } if(! serverResponseHandler.containsKey(packageType)) { logger.error("Unknown respose package type: " + packageType); if(future != null) { future.setFailedState(); future.fireCompleteEvent(); } } else { final ServerResponseHandler handler = serverResponseHandler.get(packageType); final boolean removeFuture = handler.handleServerResult(this, encodedPackage, future); // Remove pending call if(removeFuture) { synchronized (pendingCalls) { sequenceNumberGenerator.releaseNumber(sequenceNumber); pendingCalls.remove(Short.valueOf(sequenceNumber)); pendingCalls.notifyAll(); } } } } /** * Read the full package * @param packageHeader * @param inputStream2 * @return * @throws IOException */ protected ByteBuffer readFullPackage(final ByteBuffer packageHeader, final InputStream inputStream) throws IOException { final int bodyLength = (int) NetworkPackageDecoder.getBodyLengthFromResponsePackage(packageHeader); final int headerLength = packageHeader.limit(); final ByteBuffer encodedPackage = ByteBuffer.allocate(headerLength + bodyLength); //System.out.println("Trying to read: " + bodyLength + " avail " + inputStream.available()); encodedPackage.put(packageHeader.array()); ByteStreams.readFully(inputStream, encodedPackage.array(), encodedPackage.position(), bodyLength); return encodedPackage; } @Override public String toString() { return "BBoxDBClient [serverHostname=" + serverAddress.getHostString() + ", serverPort=" + serverAddress.getPort() + ", pendingCalls=" + pendingCalls.size() + ", connectionState=" + connectionState + "]"; } /** * Get the capabilities (e.g. gzip compression) of the client */ public PeerCapabilities getConnectionCapabilities() { return connectionCapabilities; } /** * Get the capabilities of the client * @return */ public PeerCapabilities getClientCapabilities() { return clientCapabilities; } /** * Is the paging for queries enables * @return */ public boolean isPagingEnabled() { return pagingEnabled; } /** * Enable or disable paging * @param pagingEnabled */ public void setPagingEnabled(final boolean pagingEnabled) { this.pagingEnabled = pagingEnabled; } /** * Get the amount of tuples per page * @return */ public short getTuplesPerPage() { return tuplesPerPage; } /** * Set the tuples per page * @param tuplesPerPage */ public void setTuplesPerPage(final short tuplesPerPage) { this.tuplesPerPage = tuplesPerPage; } /** * Get the result buffer * @return */ public Map<Short, List<PagedTransferableEntity>> getResultBuffer() { return resultBuffer; } /** * Get the network operation retryer * @return */ public NetworkOperationRetryer getNetworkOperationRetryer() { return networkOperationRetryer; } /** * Get the server response reader * @return */ public ServerResponseReader getServerResponseReader() { return serverResponseReader; } /** * The tuple store manager registry * @return */ public TupleStoreManagerRegistry getTupleStoreManagerRegistry() { return tupleStoreManagerRegistry; } /** * The tuple store manager registry * @param tupleStoreManagerRegistry */ public void setTupleStoreManagerRegistry(final TupleStoreManagerRegistry tupleStoreManagerRegistry) { this.tupleStoreManagerRegistry = tupleStoreManagerRegistry; } }
Release sequence number when package is not send
bboxdb-server/src/main/java/org/bboxdb/network/client/BBoxDBClient.java
Release sequence number when package is not send
<ide><path>boxdb-server/src/main/java/org/bboxdb/network/client/BBoxDBClient.java <ide> final OperationFuture future) { <ide> <ide> future.setConnection(0, this); <del> <add> <add> final short sequenceNumber = requestPackage.getSequenceNumber(); <ide> final boolean result = recalculateRoutingHeader(requestPackage, future); <ide> <ide> // Package don't need to be send <ide> if(result == false) { <add> sequenceNumberGenerator.releaseNumber(sequenceNumber); <ide> return; <ide> } <ide> <del> final short sequenceNumber = requestPackage.getSequenceNumber(); <ide> if(! networkOperationRetryer.isPackageIdKnown(sequenceNumber)) { <ide> networkOperationRetryer.registerOperation(sequenceNumber, <ide> requestPackage, future); <ide> <ide> synchronized (pendingCalls) { <ide> assert (! pendingCalls.containsKey(sequenceNumber)) <del> : "Old call exists: " + pendingCalls.get(sequenceNumber); <add> : "Old call exists: " + pendingCalls.get(sequenceNumber); <ide> <ide> pendingCalls.put(sequenceNumber, future); <ide> } <ide> } <ide> <ide> if(! serverResponseHandler.containsKey(packageType)) { <del> logger.error("Unknown respose package type: " + packageType); <add> logger.error("Unknown respose package type: {}", packageType); <add> sequenceNumberGenerator.releaseNumber(sequenceNumber); <ide> <ide> if(future != null) { <ide> future.setFailedState();
Java
apache-2.0
15ced983759265fcc298b1c7ee6cf29c7ad43215
0
synyx/urlaubsverwaltung,synyx/urlaubsverwaltung,synyx/urlaubsverwaltung,synyx/urlaubsverwaltung
package org.synyx.urlaubsverwaltung.api; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.synyx.urlaubsverwaltung.workingtime.NoValidWorkingTimeException; import static org.springframework.http.HttpStatus.BAD_REQUEST; import static org.springframework.http.HttpStatus.NO_CONTENT; /** * Handles exceptions and redirects to error page. */ @RestControllerAdvice public class ApiExceptionHandlerControllerAdvice { @ResponseStatus(NO_CONTENT) @ExceptionHandler({NoValidWorkingTimeException.class}) @ResponseBody public ErrorResponse handleException(IllegalStateException exception) { return new ErrorResponse(NO_CONTENT, exception); } @ResponseStatus(BAD_REQUEST) @ExceptionHandler({NumberFormatException.class, IllegalArgumentException.class}) @ResponseBody public ErrorResponse handleException(IllegalArgumentException exception) { return new ErrorResponse(BAD_REQUEST, exception); } @ResponseStatus(BAD_REQUEST) @ExceptionHandler(MethodArgumentTypeMismatchException.class) @ResponseBody public ErrorResponse handleException(MethodArgumentTypeMismatchException exception) { return new ErrorResponse(BAD_REQUEST, exception); } @ResponseStatus(BAD_REQUEST) @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseBody public ErrorResponse handleException(MissingServletRequestParameterException exception) { return new ErrorResponse(BAD_REQUEST, exception); } @ResponseStatus(HttpStatus.FORBIDDEN) @ExceptionHandler(AccessDeniedException.class) @ResponseBody public ErrorResponse handleException(AccessDeniedException exception) { return new ErrorResponse(HttpStatus.FORBIDDEN, exception); } @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(Exception.class) @ResponseBody public ErrorResponse handleException(Exception exception) { return new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, exception); } }
src/main/java/org/synyx/urlaubsverwaltung/api/ApiExceptionHandlerControllerAdvice.java
package org.synyx.urlaubsverwaltung.api; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.synyx.urlaubsverwaltung.workingtime.NoValidWorkingTimeException; import static org.springframework.http.HttpStatus.BAD_REQUEST; import static org.springframework.http.HttpStatus.NO_CONTENT; /** * Handles exceptions and redirects to error page. */ @ControllerAdvice(annotations = RestController.class) public class ApiExceptionHandlerControllerAdvice { @ResponseStatus(NO_CONTENT) @ExceptionHandler({NoValidWorkingTimeException.class}) @ResponseBody public ErrorResponse handleException(IllegalStateException exception) { return new ErrorResponse(NO_CONTENT, exception); } @ResponseStatus(BAD_REQUEST) @ExceptionHandler({NumberFormatException.class, IllegalArgumentException.class}) @ResponseBody public ErrorResponse handleException(IllegalArgumentException exception) { return new ErrorResponse(BAD_REQUEST, exception); } @ResponseStatus(BAD_REQUEST) @ExceptionHandler(MethodArgumentTypeMismatchException.class) @ResponseBody public ErrorResponse handleException(MethodArgumentTypeMismatchException exception) { return new ErrorResponse(BAD_REQUEST, exception); } @ResponseStatus(BAD_REQUEST) @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseBody public ErrorResponse handleException(MissingServletRequestParameterException exception) { return new ErrorResponse(BAD_REQUEST, exception); } @ResponseStatus(HttpStatus.FORBIDDEN) @ExceptionHandler(AccessDeniedException.class) @ResponseBody public ErrorResponse handleException(AccessDeniedException exception) { return new ErrorResponse(HttpStatus.FORBIDDEN, exception); } @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(Exception.class) @ResponseBody public ErrorResponse handleException(Exception exception) { return new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, exception); } }
Use @RestControllerAdvice
src/main/java/org/synyx/urlaubsverwaltung/api/ApiExceptionHandlerControllerAdvice.java
Use @RestControllerAdvice
<ide><path>rc/main/java/org/synyx/urlaubsverwaltung/api/ApiExceptionHandlerControllerAdvice.java <ide> import org.springframework.http.HttpStatus; <ide> import org.springframework.security.access.AccessDeniedException; <ide> import org.springframework.web.bind.MissingServletRequestParameterException; <del>import org.springframework.web.bind.annotation.ControllerAdvice; <ide> import org.springframework.web.bind.annotation.ExceptionHandler; <ide> import org.springframework.web.bind.annotation.ResponseBody; <ide> import org.springframework.web.bind.annotation.ResponseStatus; <del>import org.springframework.web.bind.annotation.RestController; <add>import org.springframework.web.bind.annotation.RestControllerAdvice; <ide> import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; <ide> import org.synyx.urlaubsverwaltung.workingtime.NoValidWorkingTimeException; <ide> <ide> /** <ide> * Handles exceptions and redirects to error page. <ide> */ <del>@ControllerAdvice(annotations = RestController.class) <add>@RestControllerAdvice <ide> public class ApiExceptionHandlerControllerAdvice { <ide> <ide> @ResponseStatus(NO_CONTENT)
Java
apache-2.0
33a38e3a84e6a21f9ef6f4f38b3afe4bafa7454c
0
sannies/mp4parser,olegloa/mp4parser
package com.googlecode.mp4parser.authoring.samples; import com.coremedia.iso.IsoFile; import com.coremedia.iso.boxes.Box; import com.coremedia.iso.boxes.Container; import com.coremedia.iso.boxes.TrackBox; import com.coremedia.iso.boxes.fragment.*; import com.googlecode.mp4parser.authoring.Sample; import com.googlecode.mp4parser.util.Path; import java.io.IOException; import java.lang.ref.SoftReference; import java.lang.reflect.Array; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.util.*; import static com.googlecode.mp4parser.util.CastUtils.l2i; /** * Created by sannies on 25.05.13. */ public class FragmentedMp4SampleList extends AbstractList<Sample> { Container topLevel; IsoFile[] fragments; TrackBox trackBox = null; TrackExtendsBox trex = null; private SoftReference<Sample> sampleCache[]; private List<TrackFragmentBox> allTrafs; private Map<TrackRunBox, SoftReference<ByteBuffer>> trunDataCache = new HashMap<TrackRunBox, SoftReference<ByteBuffer>>(); private int firstSamples[]; private int size_ = -1; public FragmentedMp4SampleList(long track, Container topLevel, IsoFile... fragments) { this.topLevel = topLevel; this.fragments = fragments; List<TrackBox> tbs = Path.getPaths(topLevel, "moov[0]/trak"); for (TrackBox tb : tbs) { if (tb.getTrackHeaderBox().getTrackId() == track) { trackBox = tb; } } if (trackBox == null) { throw new RuntimeException("This MP4 does not contain track " + track); } List<TrackExtendsBox> trexs = Path.getPaths(topLevel, "moov[0]/mvex[0]/trex"); for (TrackExtendsBox box : trexs) { if (box.getTrackId() == trackBox.getTrackHeaderBox().getTrackId()) { trex = box; } } sampleCache = (SoftReference<Sample>[]) Array.newInstance(SoftReference.class, size()); initAllFragments(); } private List<TrackFragmentBox> initAllFragments() { if (allTrafs != null) { return allTrafs; } List<TrackFragmentBox> trafs = new ArrayList<TrackFragmentBox>(); for (MovieFragmentBox moof : topLevel.getBoxes(MovieFragmentBox.class)) { for (TrackFragmentBox trackFragmentBox : moof.getBoxes(TrackFragmentBox.class)) { if (trackFragmentBox.getTrackFragmentHeaderBox().getTrackId() == trackBox.getTrackHeaderBox().getTrackId()) { trafs.add(trackFragmentBox); } } } if (fragments != null) { for (IsoFile fragment : fragments) { for (MovieFragmentBox moof : fragment.getBoxes(MovieFragmentBox.class)) { for (TrackFragmentBox trackFragmentBox : moof.getBoxes(TrackFragmentBox.class)) { if (trackFragmentBox.getTrackFragmentHeaderBox().getTrackId() == trackBox.getTrackHeaderBox().getTrackId()) { trafs.add(trackFragmentBox); } } } } } allTrafs = trafs; int firstSample = 1; firstSamples = new int[allTrafs.size()]; for (int i = 0; i < allTrafs.size(); i++) { firstSamples[i] = firstSample; firstSample += getTrafSize(allTrafs.get(i)); } return trafs; } private int getTrafSize(TrackFragmentBox traf) { List<Box> boxes = traf.getBoxes(); int size = 0; for (int i = 0; i < boxes.size(); i++) { Box b = boxes.get(i); if (b instanceof TrackRunBox) { size += l2i(((TrackRunBox) b).getSampleCount()); } } return size; } @Override public Sample get(int index) { Sample cachedSample; if (sampleCache[index] != null && (cachedSample = sampleCache[index].get()) != null) { return cachedSample; } int targetIndex = index + 1; int j = firstSamples.length - 1; while (targetIndex - firstSamples[j] < 0) { j--; } TrackFragmentBox trackFragmentBox = allTrafs.get(j); // we got the correct traf. int sampleIndexWithInTraf = targetIndex - firstSamples[j]; int previousTrunsSize = 0; MovieFragmentBox moof = ((MovieFragmentBox) trackFragmentBox.getParent()); for (Box box : trackFragmentBox.getBoxes()) { if (box instanceof TrackRunBox) { TrackRunBox trun = (TrackRunBox) box; if (trun.getEntries().size() <= (sampleIndexWithInTraf - previousTrunsSize)) { previousTrunsSize += trun.getEntries().size(); } else { // we are in correct trun box List<TrackRunBox.Entry> trackRunEntries = trun.getEntries(); TrackFragmentHeaderBox tfhd = trackFragmentBox.getTrackFragmentHeaderBox(); boolean sampleSizePresent = trun.isSampleSizePresent(); boolean hasDefaultSampleSize = tfhd.hasDefaultSampleSize(); long defaultSampleSize = 0; if (!sampleSizePresent) { if (hasDefaultSampleSize) { defaultSampleSize = tfhd.getDefaultSampleSize(); } else { if (trex == null) { throw new RuntimeException("File doesn't contain trex box but track fragments aren't fully self contained. Cannot determine sample size."); } defaultSampleSize = trex.getDefaultSampleSize(); } } final SoftReference<ByteBuffer> trunDataRef = trunDataCache.get(trun); ByteBuffer trunData = trunDataRef != null ? trunDataRef.get() : null; if (trunData == null) { long offset = 0; Container base; if (tfhd.hasBaseDataOffset()) { offset += tfhd.getBaseDataOffset(); base = moof.getParent(); } else { base = moof; } if (trun.isDataOffsetPresent()) { offset += trun.getDataOffset(); } int size = 0; for (TrackRunBox.Entry e : trackRunEntries) { if (sampleSizePresent) { size += e.getSampleSize(); } else { size += defaultSampleSize; } } try { //System.err.println("Mapped trun - offset: " + offset + " - size: " + size); trunData = base.getByteBuffer(offset, size); trunDataCache.put(trun, new SoftReference<ByteBuffer>(trunData)); } catch (IOException e) { throw new RuntimeException(e); } } int offset = 0; for (int i = 0; i < (sampleIndexWithInTraf - previousTrunsSize); i++) { if (sampleSizePresent) { offset += trackRunEntries.get(i).getSampleSize(); } else { offset += defaultSampleSize; } } final long sampleSize; if (sampleSizePresent) { sampleSize = trackRunEntries.get(sampleIndexWithInTraf- previousTrunsSize).getSampleSize(); } else { sampleSize = defaultSampleSize; } final ByteBuffer finalTrunData = trunData; final int finalOffset = offset; // System.err.println("sNo. " + index + " offset: " + finalOffset + " size: " + sampleSize); Sample sample = new Sample() { public void writeTo(WritableByteChannel channel) throws IOException { channel.write(asByteBuffer()); } public long getSize() { return sampleSize; } public ByteBuffer asByteBuffer() { return (ByteBuffer) ((ByteBuffer)finalTrunData.position(finalOffset)).slice().limit(l2i(sampleSize)); } }; sampleCache[index] = new SoftReference<Sample>(sample); return sample; } } } throw new RuntimeException("Couldn't find sample in the traf I was looking"); } @Override public int size() { if (size_ != -1) { return size_; } int i = 0; for (MovieFragmentBox moof : topLevel.getBoxes(MovieFragmentBox.class)) { for (TrackFragmentBox trackFragmentBox : moof.getBoxes(TrackFragmentBox.class)) { if (trackFragmentBox.getTrackFragmentHeaderBox().getTrackId() == trackBox.getTrackHeaderBox().getTrackId()) { for (TrackRunBox trackRunBox : trackFragmentBox.getBoxes(TrackRunBox.class)) { i += trackRunBox.getSampleCount(); } } } } for (IsoFile fragment : fragments) { for (MovieFragmentBox moof : fragment.getBoxes(MovieFragmentBox.class)) { for (TrackFragmentBox trackFragmentBox : moof.getBoxes(TrackFragmentBox.class)) { if (trackFragmentBox.getTrackFragmentHeaderBox().getTrackId() == trackBox.getTrackHeaderBox().getTrackId()) { for (TrackRunBox trackRunBox : trackFragmentBox.getBoxes(TrackRunBox.class)) { i += trackRunBox.getSampleCount(); } } } } } size_ = i; return i; } }
isoparser/src/main/java/com/googlecode/mp4parser/authoring/samples/FragmentedMp4SampleList.java
package com.googlecode.mp4parser.authoring.samples; import com.coremedia.iso.IsoFile; import com.coremedia.iso.boxes.Box; import com.coremedia.iso.boxes.Container; import com.coremedia.iso.boxes.TrackBox; import com.coremedia.iso.boxes.fragment.*; import com.googlecode.mp4parser.authoring.Sample; import com.googlecode.mp4parser.util.Path; import java.io.IOException; import java.lang.ref.SoftReference; import java.lang.reflect.Array; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.util.*; import static com.googlecode.mp4parser.util.CastUtils.l2i; /** * Created by sannies on 25.05.13. */ public class FragmentedMp4SampleList extends AbstractList<Sample> { Container topLevel; IsoFile[] fragments; TrackBox trackBox = null; TrackExtendsBox trex = null; private SoftReference<Sample> sampleCache[]; private List<TrackFragmentBox> allTrafs; private Map<TrackRunBox, SoftReference<ByteBuffer>> trunDataCache = new HashMap<TrackRunBox, SoftReference<ByteBuffer>>(); private int firstSamples[]; private int size_ = -1; public FragmentedMp4SampleList(long track, Container topLevel, IsoFile... fragments) { this.topLevel = topLevel; this.fragments = fragments; List<TrackBox> tbs = Path.getPaths(topLevel, "moov[0]/trak"); for (TrackBox tb : tbs) { if (tb.getTrackHeaderBox().getTrackId() == track) { trackBox = tb; } } if (trackBox == null) { throw new RuntimeException("This MP4 does not contain track " + track); } List<TrackExtendsBox> trexs = Path.getPaths(topLevel, "moov[0]/mvex[0]/trex"); for (TrackExtendsBox box : trexs) { if (box.getTrackId() == trackBox.getTrackHeaderBox().getTrackId()) { trex = box; } } sampleCache = (SoftReference<Sample>[]) Array.newInstance(SoftReference.class, size()); initAllFragments(); } private List<TrackFragmentBox> initAllFragments() { if (allTrafs != null) { return allTrafs; } List<TrackFragmentBox> trafs = new ArrayList<TrackFragmentBox>(); for (MovieFragmentBox moof : topLevel.getBoxes(MovieFragmentBox.class)) { for (TrackFragmentBox trackFragmentBox : moof.getBoxes(TrackFragmentBox.class)) { if (trackFragmentBox.getTrackFragmentHeaderBox().getTrackId() == trackBox.getTrackHeaderBox().getTrackId()) { trafs.add(trackFragmentBox); } } } if (fragments != null) { for (IsoFile fragment : fragments) { for (MovieFragmentBox moof : fragment.getBoxes(MovieFragmentBox.class)) { for (TrackFragmentBox trackFragmentBox : moof.getBoxes(TrackFragmentBox.class)) { if (trackFragmentBox.getTrackFragmentHeaderBox().getTrackId() == trackBox.getTrackHeaderBox().getTrackId()) { trafs.add(trackFragmentBox); } } } } } allTrafs = trafs; int firstSample = 1; firstSamples = new int[allTrafs.size()]; for (int i = 0; i < allTrafs.size(); i++) { firstSamples[i] = firstSample; firstSample += getTrafSize(allTrafs.get(i)); } return trafs; } private int getTrafSize(TrackFragmentBox traf) { List<Box> boxes = traf.getBoxes(); int size = 0; for (int i = 0; i < boxes.size(); i++) { Box b = boxes.get(i); if (b instanceof TrackRunBox) { size += l2i(((TrackRunBox) b).getSampleCount()); } } return size; } @Override public Sample get(int index) { Sample cachedSample; if (sampleCache[index] != null && (cachedSample = sampleCache[index].get()) != null) { return cachedSample; } int targetIndex = index + 1; int j = firstSamples.length - 1; while (targetIndex - firstSamples[j] < 0) { j--; } TrackFragmentBox trackFragmentBox = allTrafs.get(j); // we got the correct traf. int sampleIndexWithInTraf = targetIndex - firstSamples[j]; int previousTrunsSize = 0; MovieFragmentBox moof = ((MovieFragmentBox) trackFragmentBox.getParent()); for (Box box : trackFragmentBox.getBoxes()) { if (box instanceof TrackRunBox) { TrackRunBox trun = (TrackRunBox) box; if (trun.getEntries().size() <= (sampleIndexWithInTraf - previousTrunsSize)) { previousTrunsSize += trun.getEntries().size(); } else { // we are in correct trun box List<TrackRunBox.Entry> trackRunEntries = trun.getEntries(); TrackFragmentHeaderBox tfhd = trackFragmentBox.getTrackFragmentHeaderBox(); boolean sampleSizePresent = trun.isSampleSizePresent(); boolean hasDefaultSampleSize = tfhd.hasDefaultSampleSize(); long defaultSampleSize = 0; if (!sampleSizePresent) { if (hasDefaultSampleSize) { defaultSampleSize = tfhd.getDefaultSampleSize(); } else { if (trex == null) { throw new RuntimeException("File doesn't contain trex box but track fragments aren't fully self contained. Cannot determine sample size."); } defaultSampleSize = trex.getDefaultSampleSize(); } } final SoftReference<ByteBuffer> trunDataRef = trunDataCache.get(trun); ByteBuffer trunData = trunDataRef != null ? trunDataRef.get() : null; if (trunData == null) { long offset = 0; Container base; if (tfhd.hasBaseDataOffset()) { offset += tfhd.getBaseDataOffset(); base = moof.getParent(); } else { base = moof; } if (trun.isDataOffsetPresent()) { offset += trun.getDataOffset(); } int size = 0; for (TrackRunBox.Entry e : trackRunEntries) { if (sampleSizePresent) { size += e.getSampleSize(); } else { size += defaultSampleSize; } } try { System.err.println("Mapped trun - offset: " + offset + " - size: " + size); trunData = base.getByteBuffer(offset, size); trunDataCache.put(trun, new SoftReference<ByteBuffer>(trunData)); } catch (IOException e) { throw new RuntimeException(e); } } int offset = 0; for (int i = 0; i < (sampleIndexWithInTraf - previousTrunsSize); i++) { if (sampleSizePresent) { offset += trackRunEntries.get(i).getSampleSize(); } else { offset += defaultSampleSize; } } final long sampleSize; if (sampleSizePresent) { sampleSize = trackRunEntries.get(sampleIndexWithInTraf- previousTrunsSize).getSampleSize(); } else { sampleSize = defaultSampleSize; } final ByteBuffer finalTrunData = trunData; final int finalOffset = offset; System.err.println("sNo. " + index + " offset: " + finalOffset + " size: " + sampleSize); Sample sample = new Sample() { public void writeTo(WritableByteChannel channel) throws IOException { channel.write(asByteBuffer()); } public long getSize() { return sampleSize; } public ByteBuffer asByteBuffer() { return (ByteBuffer) ((ByteBuffer)finalTrunData.position(finalOffset)).slice().limit(l2i(sampleSize)); } }; // todo: enabled cache|remove comment // sampleCache[index] = new SoftReference<Sample>(sample); return sample; } } } throw new RuntimeException("Couldn't find sample in the traf I was looking"); } @Override public int size() { if (size_ != -1) { return size_; } int i = 0; for (MovieFragmentBox moof : topLevel.getBoxes(MovieFragmentBox.class)) { for (TrackFragmentBox trackFragmentBox : moof.getBoxes(TrackFragmentBox.class)) { if (trackFragmentBox.getTrackFragmentHeaderBox().getTrackId() == trackBox.getTrackHeaderBox().getTrackId()) { for (TrackRunBox trackRunBox : trackFragmentBox.getBoxes(TrackRunBox.class)) { i += trackRunBox.getSampleCount(); } } } } for (IsoFile fragment : fragments) { for (MovieFragmentBox moof : fragment.getBoxes(MovieFragmentBox.class)) { for (TrackFragmentBox trackFragmentBox : moof.getBoxes(TrackFragmentBox.class)) { if (trackFragmentBox.getTrackFragmentHeaderBox().getTrackId() == trackBox.getTrackHeaderBox().getTrackId()) { for (TrackRunBox trackRunBox : trackFragmentBox.getBoxes(TrackRunBox.class)) { i += trackRunBox.getSampleCount(); } } } } } size_ = i; return i; } }
removed debug output, enable sample cache
isoparser/src/main/java/com/googlecode/mp4parser/authoring/samples/FragmentedMp4SampleList.java
removed debug output, enable sample cache
<ide><path>soparser/src/main/java/com/googlecode/mp4parser/authoring/samples/FragmentedMp4SampleList.java <ide> } <ide> } <ide> try { <del> System.err.println("Mapped trun - offset: " + offset + " - size: " + size); <add> //System.err.println("Mapped trun - offset: " + offset + " - size: " + size); <ide> trunData = base.getByteBuffer(offset, size); <ide> trunDataCache.put(trun, new SoftReference<ByteBuffer>(trunData)); <ide> } catch (IOException e) { <ide> <ide> final ByteBuffer finalTrunData = trunData; <ide> final int finalOffset = offset; <del> System.err.println("sNo. " + index + " offset: " + finalOffset + " size: " + sampleSize); <add> // System.err.println("sNo. " + index + " offset: " + finalOffset + " size: " + sampleSize); <ide> Sample sample = new Sample() { <ide> public void writeTo(WritableByteChannel channel) throws IOException { <ide> channel.write(asByteBuffer()); <ide> return (ByteBuffer) ((ByteBuffer)finalTrunData.position(finalOffset)).slice().limit(l2i(sampleSize)); <ide> } <ide> }; <del> // todo: enabled cache|remove comment <del> // sampleCache[index] = new SoftReference<Sample>(sample); <add> sampleCache[index] = new SoftReference<Sample>(sample); <ide> return sample; <ide> } <ide> }
Java
apache-2.0
ef9505b0c0814507e9598a055e92838bf38ce797
0
SyncFree/SwiftCloud,SyncFree/SwiftCloud,SyncFree/SwiftCloud,SyncFree/SwiftCloud
/***************************************************************************** * Copyright 2011-2012 INRIA * Copyright 2011-2012 Universidade Nova de Lisboa * * 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 swift.dc; import static sys.net.api.Networking.Networking; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.logging.Level; import java.util.logging.Logger; import swift.clocks.CausalityClock; import swift.clocks.CausalityClock.CMP_CLOCK; import swift.clocks.ClockFactory; import swift.clocks.Timestamp; import swift.crdt.core.CRDT; import swift.crdt.core.CRDTIdentifier; import swift.crdt.core.CRDTObjectUpdatesGroup; import swift.crdt.core.ManagedCRDT; import swift.proto.BatchCommitUpdatesReply; import swift.proto.BatchCommitUpdatesRequest; import swift.proto.BatchFetchObjectVersionReply; import swift.proto.BatchFetchObjectVersionReply.FetchStatus; import swift.proto.BatchFetchObjectVersionRequest; import swift.proto.ClientRequest; import swift.proto.CommitTSReply; import swift.proto.CommitTSRequest; import swift.proto.CommitUpdatesReply; import swift.proto.CommitUpdatesReply.CommitStatus; import swift.proto.CommitUpdatesRequest; import swift.proto.GenerateDCTimestampReply; import swift.proto.GenerateDCTimestampRequest; import swift.proto.LatestKnownClockReply; import swift.proto.LatestKnownClockRequest; import swift.proto.PingReply; import swift.proto.PingRequest; import swift.proto.SeqCommitUpdatesRequest; import swift.proto.SwiftProtocolHandler; import swift.pubsub.BatchUpdatesNotification; import swift.pubsub.SurrogatePubSubService; import swift.pubsub.SwiftSubscriber; import swift.pubsub.UpdateNotification; import swift.utils.FutureResultHandler; import swift.utils.SafeLog; import swift.utils.SafeLog.ReportType; import sys.Sys; import sys.dht.DHT_Node; import sys.net.api.Endpoint; import sys.net.api.rpc.RpcEndpoint; import sys.net.api.rpc.RpcHandle; import sys.pubsub.PubSubNotification; import sys.pubsub.RemoteSubscriber; import sys.pubsub.impl.AbstractSubscriber; import sys.scheduler.PeriodicTask; //import swift.client.proto.FastRecentUpdatesReply; //import swift.client.proto.FastRecentUpdatesReply.ObjectSubscriptionInfo; //import swift.client.proto.FastRecentUpdatesReply.SubscriptionStatus; //import swift.client.proto.FastRecentUpdatesRequest; /** * Class to handle the requests from clients. * * @author preguica */ final public class DCSurrogate extends SwiftProtocolHandler { public static final boolean FAKE_PRACTI_DEPOT_VECTORS = false; public static final boolean OPTIMIZED_VECTORS_IN_BATCH = false; static Logger logger = Logger.getLogger(DCSurrogate.class.getName()); String siteId; String surrogateId; RpcEndpoint srvEndpoint4Clients; RpcEndpoint srvEndpoint4Sequencer; Endpoint sequencerServerEndpoint; RpcEndpoint cltEndpoint4Sequencer; DCDataServer dataServer; CausalityClock estimatedDCVersion; // estimate of current DC state CausalityClock estimatedDCStableVersion; // estimate of current DC state AtomicReference<CausalityClock> estimatedDCVersionShadow; // read only // estimate of // current DC // state AtomicReference<CausalityClock> estimatedDCStableVersionShadow; // read // only // estimate // of // current // DC // state final public SurrogatePubSubService suPubSub; public int pubsubPort; final ThreadPoolExecutor crdtExecutor; final ThreadPoolExecutor generalExecutor; private final int notificationPeriodMillis; DCSurrogate(String siteId, int port4Clients, int port4Sequencers, Endpoint sequencerEndpoint, Properties props) { this.siteId = siteId; this.surrogateId = "s" + System.nanoTime(); this.pubsubPort = port4Clients + 1; this.sequencerServerEndpoint = sequencerEndpoint; this.cltEndpoint4Sequencer = Networking.rpcConnect().toDefaultService(); this.srvEndpoint4Clients = Networking.rpcBind(port4Clients).toDefaultService(); this.srvEndpoint4Sequencer = Networking.rpcBind(port4Sequencers).toDefaultService(); srvEndpoint4Clients.setHandler(this); srvEndpoint4Sequencer.setHandler(this); srvEndpoint4Clients.getFactory().setExecutor(Executors.newCachedThreadPool()); srvEndpoint4Sequencer.getFactory().setExecutor(Executors.newFixedThreadPool(2)); ArrayBlockingQueue<Runnable> crdtWorkQueue = new ArrayBlockingQueue<Runnable>(512); crdtExecutor = new ThreadPoolExecutor(4, 8, 3, TimeUnit.SECONDS, crdtWorkQueue); crdtExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); ArrayBlockingQueue<Runnable> generalWorkQueue = new ArrayBlockingQueue<Runnable>(512); generalExecutor = new ThreadPoolExecutor(4, 8, 3, TimeUnit.SECONDS, generalWorkQueue); generalExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); suPubSub = new SurrogatePubSubService(generalExecutor, this); dataServer = new DCDataServer(this, props, suPubSub, port4Clients + 2); final String notificationPeriodString = props.getProperty(DCConstants.NOTIFICATION_PERIOD_PROPERTY); if (notificationPeriodString != null) { notificationPeriodMillis = Integer.valueOf(notificationPeriodString); } else { notificationPeriodMillis = DCConstants.DEFAULT_NOTIFICATION_PERIOD_MS; } initData(props); if (logger.isLoggable(Level.INFO)) { logger.info("Server ready..."); } DHT_Node.init(siteId, "surrogates", srvEndpoint4Clients.localEndpoint()); new PeriodicTask(0.0, 0.1) { public void run() { updateEstimatedDCVersion(); } }; } private void initData(Properties props) { estimatedDCVersion = ClockFactory.newClock(); estimatedDCStableVersion = ClockFactory.newClock(); // HACK HACK CausalityClock clk = (CausalityClock) dataServer.dbServer.readSysData("SYS_TABLE", "CURRENT_CLK"); if (clk != null) { logger.info("SURROGATE CLK:" + clk); estimatedDCVersion.merge(clk); estimatedDCStableVersion.merge(clk); } estimatedDCVersionShadow = new AtomicReference<CausalityClock>(estimatedDCVersion.clone()); estimatedDCStableVersionShadow = new AtomicReference<CausalityClock>(estimatedDCStableVersion.clone()); logger.info("EstimatedDCVersion: " + estimatedDCVersion); } public String getId() { return surrogateId; } public CausalityClock getEstimatedDCVersionCopy() { return estimatedDCVersionShadow.get().clone(); } CausalityClock getEstimatedDCStableVersionCopy() { return estimatedDCStableVersionShadow.get().clone(); } public void updateEstimatedDCVersion(CausalityClock cc) { synchronized (estimatedDCVersion) { estimatedDCVersion.merge(cc); estimatedDCVersionShadow.set(estimatedDCVersion.clone()); } } public void updateEstimatedDCStableVersion(CausalityClock cc) { synchronized (estimatedDCStableVersion) { estimatedDCStableVersion.merge(cc); estimatedDCStableVersionShadow.set(estimatedDCStableVersion.clone()); } } /******************************************************************************************** * Methods related with notifications from clients *******************************************************************************************/ <V extends CRDT<V>> ExecCRDTResult execCRDT(CRDTObjectUpdatesGroup<V> grp, CausalityClock snapshotVersion, CausalityClock trxVersion, Timestamp txTs, Timestamp cltTs, Timestamp prvCltTs, CausalityClock curDCVersion) { return dataServer.execCRDT(grp, snapshotVersion, trxVersion, txTs, cltTs, prvCltTs, curDCVersion); } private void updateEstimatedDCVersion() { cltEndpoint4Sequencer.send(sequencerServerEndpoint, new LatestKnownClockRequest("surrogate", false), this, 0); } public void onReceive(RpcHandle conn, LatestKnownClockReply reply) { if (logger.isLoggable(Level.INFO)) { logger.info("LatestKnownClockReply: clk:" + reply.getClock()); } updateEstimatedDCVersion(reply.getClock()); updateEstimatedDCStableVersion(reply.getDistasterDurableClock()); } public void onReceive(RpcHandle conn, final BatchFetchObjectVersionRequest request) { if (logger.isLoggable(Level.INFO)) { logger.info("BatchFetchObjectVersionRequest client = " + request.getClientId() + "; crdt id = " + request.getUids()); } // LWWStringMapRegisterCRDT initialCheckpoint = new // LWWStringMapRegisterCRDT(request.getUid()); // FAKE_INIT_UPDATE.applyTo(initialCheckpoint); // conn.reply(new FetchObjectVersionReply(FetchStatus.OK, new // ManagedCRDT<LWWStringMapRegisterCRDT>(request // .getUid(), initialCheckpoint, request.getVersion(), true), // request.getVersion(), request.getVersion())); // return; // conn.reply(new FetchObjectVersionReply(FetchStatus.OK, new // ManagedCRDT<PutOnlyLWWStringMapCRDT>(request // .getUid(), new PutOnlyLWWStringMapCRDT(request.getUid()), // request.getVersion(), true), request // .getVersion(), request.getVersion())); // return; if (request.hasSubscription()) { for (final CRDTIdentifier id : request.getUids()) { getSession(request).subscribe(id); } } final ClientSession session = getSession(request); final Timestamp cltLastSeqNo = session.getLastSeqNo(); CMP_CLOCK cmp = CMP_CLOCK.CMP_EQUALS; CausalityClock estimatedDCVersionCopy = getEstimatedDCVersionCopy(); cmp = request.getVersion() == null ? CMP_CLOCK.CMP_EQUALS : estimatedDCVersionCopy.compareTo(request .getVersion()); if (cmp == CMP_CLOCK.CMP_ISDOMINATED || cmp == CMP_CLOCK.CMP_CONCURRENT) { updateEstimatedDCVersion(); estimatedDCVersionCopy = getEstimatedDCVersionCopy(); cmp = estimatedDCVersionCopy.compareTo(request.getVersion()); } final CMP_CLOCK finalCmpClk = cmp; final CausalityClock finalEstimatedDCVersionCopy = estimatedDCVersionCopy; CausalityClock estimatedDCStableVersionCopy = getEstimatedDCStableVersionCopy(); final CausalityClock disasterSafeVVReply = request.isSendDCVector() ? estimatedDCStableVersionCopy.clone() : null; if (disasterSafeVVReply != null) { disasterSafeVVReply.intersect(estimatedDCVersionCopy); } // TODO: for nodes !request.isDisasterSafe() send it less // frequently (it's for pruning only) final CausalityClock vvReply = !request.isDisasterSafeSession() && request.isSendDCVector() ? estimatedDCVersionCopy .clone() : null; final BatchFetchObjectVersionReply reply = new BatchFetchObjectVersionReply(request.getBatchSize(), vvReply, disasterSafeVVReply); final Semaphore sem = new Semaphore(0); for (int i = 0; i < request.getBatchSize(); i++) { final int finalIdx = i; dataServer.getCRDT(request.getUid(i), request.getKnownVersion(), request.getVersion(), request.getClientId(), request.isSendMoreRecentUpdates(), request.hasSubscription(), new FutureResultHandler<ManagedCRDT>() { @Override public void onResult(ManagedCRDT crdt) { try { adaptGetReplyToFetchReply(request, finalIdx, cltLastSeqNo, finalCmpClk, finalEstimatedDCVersionCopy, reply, crdt); } finally { sem.release(); } } }); } sem.acquireUninterruptibly(request.getBatchSize()); if (request.getBatchSize() > 1 && !request.isSendMoreRecentUpdates()) { final CausalityClock commonPruneClock = request.getVersion().clone(); final CausalityClock commonClock = commonPruneClock.clone(); if (cltLastSeqNo != null) { commonClock.recordAllUntil(cltLastSeqNo); } reply.compressAllOKReplies(commonPruneClock, commonClock); } conn.reply(reply); } private void adaptGetReplyToFetchReply(final BatchFetchObjectVersionRequest request, int idxInBatch, final Timestamp cltLastSeqNo, final CMP_CLOCK versionToDcCmpClock, final CausalityClock estimatedDCVersionClock, final BatchFetchObjectVersionReply reply, ManagedCRDT crdt) { if (crdt == null) { if (request.getKnownVersion() == null) { if (logger.isLoggable(Level.INFO)) { logger.info("BatchFetchObjectVersionRequest not found:" + request.getUid(idxInBatch)); } reply.setReply(idxInBatch, BatchFetchObjectVersionReply.FetchStatus.OBJECT_NOT_FOUND, null); } else { reply.setReply(idxInBatch, FetchStatus.UP_TO_DATE, null); } } else { synchronized (crdt) { crdt.augmentWithDCClockWithoutMappings(estimatedDCVersionClock); if (cltLastSeqNo != null) crdt.augmentWithScoutClockWithoutMappings(cltLastSeqNo); // TODO: move it to data nodes if (!request.isSendMoreRecentUpdates()) { CausalityClock restriction = (CausalityClock) request.getVersion().copy(); if (cltLastSeqNo != null) { restriction.recordAllUntil(cltLastSeqNo); } crdt.discardRecentUpdates(restriction); } final BatchFetchObjectVersionReply.FetchStatus status; if (versionToDcCmpClock.is(CMP_CLOCK.CMP_ISDOMINATED, CMP_CLOCK.CMP_CONCURRENT)) { logger.warning("Requested version " + request.getVersion() + " of object " + request.getUid(idxInBatch) + " missing; local version: " + estimatedDCVersionClock + " pruned as of " + crdt.getPruneClock()); status = FetchStatus.VERSION_MISSING; } else if (crdt.getPruneClock().compareTo(request.getVersion()) .is(CMP_CLOCK.CMP_DOMINATES, CMP_CLOCK.CMP_CONCURRENT)) { logger.warning("Requested version " + request.getVersion() + " of object " + request.getUid(idxInBatch) + " is pruned; local version: " + estimatedDCVersionClock + " pruned as of " + crdt.getPruneClock()); status = FetchStatus.VERSION_PRUNED; } else { status = FetchStatus.OK; } if (logger.isLoggable(Level.INFO)) { logger.info("BatchFetchObjectVersionRequest clock = " + crdt.getClock() + "/" + request.getUid(idxInBatch)); } reply.setReply(idxInBatch, status, crdt); } } } @Override public void onReceive(final RpcHandle conn, final CommitUpdatesRequest request) { if (logger.isLoggable(Level.INFO)) { logger.info("CommitUpdatesRequest client = " + request.getClientId() + ":ts=" + request.getCltTimestamp() + ":nops=" + request.getObjectUpdateGroups().size()); } final ClientSession session = getSession(request); if (logger.isLoggable(Level.INFO)) { logger.info("CommitUpdatesRequest ... lastSeqNo=" + session.getLastSeqNo()); } Timestamp cltTs = session.getLastSeqNo(); if (cltTs != null && cltTs.getCounter() >= request.getCltTimestamp().getCounter()) conn.reply(new CommitUpdatesReply(getEstimatedDCVersionCopy())); else prepareAndDoCommit(session, request, new FutureResultHandler<CommitUpdatesReply>() { @Override public void onResult(CommitUpdatesReply result) { conn.reply(result); } }); } private void prepareAndDoCommit(final ClientSession session, final CommitUpdatesRequest req, final FutureResultHandler<CommitUpdatesReply> resHandler) { final List<CRDTObjectUpdatesGroup<?>> ops = req.getObjectUpdateGroups(); final CausalityClock dependenciesClock = ops.size() > 0 ? req.getDependencyClock() : ClockFactory.newClock(); GenerateDCTimestampReply tsReply = cltEndpoint4Sequencer.request(sequencerServerEndpoint, new GenerateDCTimestampRequest(req.getClientId(), req.isDisasterSafeSession(), req.getCltTimestamp(), dependenciesClock)); req.setTimestamp(tsReply.getTimestamp()); // req.setDisasterSafe(); // FOR SOSP EVALUATION... doOneCommit(session, req, dependenciesClock, resHandler); } private void doOneCommit(final ClientSession session, final CommitUpdatesRequest req, final CausalityClock snapshotClock, final FutureResultHandler<CommitUpdatesReply> resHandler) { // 0) updates.addSystemTimestamp(timestampService.allocateTimestamp()) // 1) let int clientTxs = // clientTxClockService.getAndLockNumberOfCommitedTxs(clientId) // 2) for all modified objects: // crdt.augumentWithScoutClock(new Timestamp(clientId, clientTxs)) // // ensures that execute() has enough information to ensure tx // idempotence // crdt.execute(updates...) // crdt.discardScoutClock(clientId) // critical to not polute all data // nodes and objects with big vectors, unless we want to do it until // pruning // 3) clientTxClockService.unlock(clientId) if (logger.isLoggable(Level.INFO)) { logger.info("CommitUpdatesRequest: doProcessOneCommit: client = " + req.getClientId() + ":ts=" + req.getCltTimestamp() + ":nops=" + req.getObjectUpdateGroups().size()); } final List<CRDTObjectUpdatesGroup<?>> ops = req.getObjectUpdateGroups(); final Timestamp txTs = req.getTimestamp(); final Timestamp cltTs = req.getCltTimestamp(); final Timestamp prvCltTs = session.getLastSeqNo(); for (CRDTObjectUpdatesGroup<?> o : ops) o.addSystemTimestamp(txTs); final CausalityClock trxClock = snapshotClock.clone(); trxClock.record(txTs); final CausalityClock estimatedDCVersionCopy = getEstimatedDCVersionCopy(); int pos = 0; final AtomicBoolean txnOK = new AtomicBoolean(true); final AtomicReferenceArray<ExecCRDTResult> results = new AtomicReferenceArray<ExecCRDTResult>(ops.size()); if (ops.size() > 2) { // do multiple execCRDTs in parallel final Semaphore s = new Semaphore(0); for (final CRDTObjectUpdatesGroup<?> i : ops) { final int j = pos++; crdtExecutor.execute(new Runnable() { public void run() { try { results.set(j, execCRDT(i, snapshotClock, trxClock, txTs, cltTs, prvCltTs, estimatedDCVersionCopy)); txnOK.compareAndSet(true, results.get(j).isResult()); updateEstimatedDCVersion(i.getDependency()); } finally { s.release(); } } }); } s.acquireUninterruptibly(ops.size()); } else { for (final CRDTObjectUpdatesGroup<?> i : ops) { results.set(pos, execCRDT(i, snapshotClock, trxClock, txTs, cltTs, prvCltTs, estimatedDCVersionCopy)); txnOK.compareAndSet(true, results.get(pos).isResult()); updateEstimatedDCVersion(i.getDependency()); pos++; } } // TODO: handle failure session.setLastSeqNo(cltTs); srvEndpoint4Sequencer.send(sequencerServerEndpoint, new CommitTSRequest(txTs, cltTs, prvCltTs, estimatedDCVersionCopy, txnOK.get(), ops, req.disasterSafe(), session.clientId), new SwiftProtocolHandler() { public void onReceive(CommitTSReply reply) { if (logger.isLoggable(Level.INFO)) { logger.info("Commit: received CommitTSRequest:old vrs:" + estimatedDCVersionCopy + "; new vrs=" + reply.getCurrVersion() + ";ts = " + txTs + ";cltts = " + cltTs); } estimatedDCVersionCopy.record(txTs); updateEstimatedDCVersion(reply.getCurrVersion()); dataServer.dbServer.writeSysData("SYS_TABLE", "CURRENT_CLK", getEstimatedDCVersionCopy()); updateEstimatedDCStableVersion(reply.getStableVersion()); dataServer.dbServer.writeSysData("SYS_TABLE", "STABLE_CLK", getEstimatedDCStableVersionCopy()); if (txnOK.get() && reply.getStatus() == CommitTSReply.CommitTSStatus.OK) { if (logger.isLoggable(Level.INFO)) { logger.info("Commit: for publish DC version: SENDING ; on tx:" + txTs); } resHandler.onResult(new CommitUpdatesReply(txTs)); // return new CommitUpdatesReply(txTs); } else { // FIXME: CommitTSStatus.FAILED if not well // documented. How comes it can fail? logger.warning("Commit: failed for request " + req); resHandler.onResult(new CommitUpdatesReply()); } } }, 0); // if (reply == null) // logger.severe(String.format("------------>REPLY FROM SEQUENCER NULL for: %s, who:%s\n", // txTs, // session.clientId)); // // } while (reply == null); // // if (reply != null) { // // } // return new CommitUpdatesReply(); } @Override public void onReceive(final RpcHandle conn, final BatchCommitUpdatesRequest request) { if (logger.isLoggable(Level.INFO)) { logger.info("BatchCommitUpdatesRequest client = " + request.getClientId() + ":batch size=" + request.getCommitRequests().size()); } final ClientSession session = getSession(request); if (logger.isLoggable(Level.INFO)) { logger.info("BatchCommitUpdatesRequest ... lastSeqNo=" + session.getLastSeqNo()); } final List<Timestamp> tsLst = new LinkedList<Timestamp>(); final List<CommitUpdatesReply> reply = new LinkedList<CommitUpdatesReply>(); for (CommitUpdatesRequest r : request.getCommitRequests()) { if (session.getLastSeqNo() != null && session.getLastSeqNo().getCounter() >= r.getCltTimestamp().getCounter()) { reply.add(new CommitUpdatesReply(getEstimatedDCVersionCopy())); // FIXME: unless the timestamp is stable andpruned, we need to // send a precise mapping to the client! // Also, non-stable clock should appear in internal dependencies // in the batch. } else { // FIXME: is it required to respect internal dependencies in the // batch? Order in the local DC is respected already. // r.addTimestampsToDeps(tsLst); final Semaphore sem = new Semaphore(0); prepareAndDoCommit(session, r, new FutureResultHandler<CommitUpdatesReply>() { @Override public void onResult(CommitUpdatesReply repOne) { if (repOne.getStatus() == CommitStatus.COMMITTED_WITH_KNOWN_TIMESTAMPS) { List<Timestamp> tsLstOne = repOne.getCommitTimestamps(); if (tsLstOne != null) tsLst.addAll(tsLstOne); } reply.add(repOne); sem.release(); } }); sem.acquireUninterruptibly(); } } conn.reply(new BatchCommitUpdatesReply(reply)); } @Override public void onReceive(final RpcHandle conn, final SeqCommitUpdatesRequest request) { if (logger.isLoggable(Level.INFO)) { logger.info("SeqCommitUpdatesRequest timestamp = " + request.getTimestamp() + ";clt=" + request.getCltTimestamp()); } ClientSession session = getSession(request.getCltTimestamp().getIdentifier(), false); List<CRDTObjectUpdatesGroup<?>> ops = request.getObjectUpdateGroups(); CausalityClock snapshotClock = ops.size() > 0 ? ops.get(0).getDependency() : ClockFactory.newClock(); doOneCommit(session, request, snapshotClock, new FutureResultHandler<CommitUpdatesReply>() { @Override public void onResult(CommitUpdatesReply result) { conn.reply(result); } }); } @Override public void onReceive(final RpcHandle conn, LatestKnownClockRequest request) { if (logger.isLoggable(Level.INFO)) { logger.info("LatestKnownClockRequest client = " + request.getClientId()); } cltEndpoint4Sequencer.send(sequencerServerEndpoint, request, new SwiftProtocolHandler() { public void onReceive(RpcHandle conn2, LatestKnownClockReply reply) { if (logger.isLoggable(Level.INFO)) { logger.info("LatestKnownClockRequest: forwarding reply:" + reply.getClock()); } updateEstimatedDCVersion(reply.getClock()); updateEstimatedDCStableVersion(reply.getDistasterDurableClock()); conn.reply(reply); } }, 0); } @Override public void onReceive(final RpcHandle conn, PingRequest request) { PingReply reply = new PingReply(request.getTimeAtSender(), System.currentTimeMillis()); conn.reply(reply); } public class ClientSession extends AbstractSubscriber<CRDTIdentifier> implements SwiftSubscriber { final String clientId; boolean disasterSafe; volatile Timestamp lastSeqNo; private CausalityClock clientFakeVectorKnowledge; private CausalityClock lastSnapshotVector; private RemoteSubscriber<CRDTIdentifier> remoteClient; private PeriodicTask notificationsTask; ClientSession(String clientId, boolean disasterSafe) { super(clientId); this.clientId = clientId; this.disasterSafe = disasterSafe; if (FAKE_PRACTI_DEPOT_VECTORS) { clientFakeVectorKnowledge = ClockFactory.newClock(); } if (OPTIMIZED_VECTORS_IN_BATCH) { lastSnapshotVector = ClockFactory.newClock(); } } // idempotent public synchronized void initNotifications() { if (notificationsTask != null) { return; } notificationsTask = new PeriodicTask(0.5, notificationPeriodMillis * 0.001) { public void run() { tryFireClientNotification(); } }; } public CausalityClock getMinVV() { return suPubSub.minDcVersion(); } public ClientSession setClientEndpoint(Endpoint remote) { remoteClient = new RemoteSubscriber<CRDTIdentifier>(clientId, suPubSub.endpoint(), remote); return this; } Timestamp getLastSeqNo() { return lastSeqNo; } void setLastSeqNo(Timestamp cltTs) { this.lastSeqNo = cltTs; } public void subscribe(CRDTIdentifier key) { suPubSub.subscribe(key, this); } public void unsubscribe(Set<CRDTIdentifier> keys) { suPubSub.unsubscribe(keys, this); } long lastNotification = 0L; List<CRDTObjectUpdatesGroup<?>> pending = new ArrayList<CRDTObjectUpdatesGroup<?>>(); synchronized public void onNotification(final UpdateNotification update) { List<CRDTObjectUpdatesGroup<?>> updates = update.info.getUpdates(); if (updates.isEmpty() || clientId.equals(updates.get(0).getClientTimestamp().getIdentifier())) { // Ignore return; } pending.addAll(update.info.getUpdates()); tryFireClientNotification(); } protected synchronized CausalityClock tryFireClientNotification() { long now = Sys.Sys.timeMillis(); if (now <= (lastNotification + notificationPeriodMillis)) { return null; } final CausalityClock snapshot = suPubSub.minDcVersion(); if (disasterSafe) { snapshot.intersect(getEstimatedDCStableVersionCopy()); } if (OPTIMIZED_VECTORS_IN_BATCH) { for (final String dcId : lastSnapshotVector.getSiteIds()) { if (lastSnapshotVector.includes(snapshot.getLatest(dcId))) { snapshot.drop(dcId); } } lastSnapshotVector.merge(snapshot); } final HashMap<CRDTIdentifier, List<CRDTObjectUpdatesGroup<?>>> objectsUpdates = new HashMap<CRDTIdentifier, List<CRDTObjectUpdatesGroup<?>>>(); final Iterator<CRDTObjectUpdatesGroup<?>> iter = pending.iterator(); while (iter.hasNext()) { final CRDTObjectUpdatesGroup<?> u = iter.next(); if (u.anyTimestampIncluded(snapshot)) { // FIXME: for at-most-once check if any timestamp is // included in the previous clock of the scout List<CRDTObjectUpdatesGroup<?>> objectUpdates = objectsUpdates.get(u.getTargetUID()); if (objectUpdates == null) { objectUpdates = new LinkedList<CRDTObjectUpdatesGroup<?>>(); objectsUpdates.put(u.getTargetUID(), objectUpdates); } objectUpdates.add(u.strippedWithCopiedTimestampMappings()); iter.remove(); } } // TODO: for clients that cannot receive periodical updates (e.g. // mobile in background mode), one could require a transaction to // declare his read set and force refresh the cache before the // transaction if necessary. BatchUpdatesNotification batch; if (FAKE_PRACTI_DEPOT_VECTORS) { final CausalityClock fakeVector = ClockFactory.newClock(); // We compare against the stale vector matchin snapshot, but // these entries // would need to be eventually send anyways. for (final String clientId : dataServer.cltClock.getSiteIds()) { final Timestamp clientTimestamp = dataServer.cltClock.getLatest(clientId); if (!clientFakeVectorKnowledge.includes(clientTimestamp)) { fakeVector.recordAllUntil(clientTimestamp); clientFakeVectorKnowledge.recordAllUntil(clientTimestamp); } } clientFakeVectorKnowledge.merge(fakeVector); batch = new BatchUpdatesNotification(snapshot, disasterSafe, objectsUpdates, fakeVector); } else { batch = new BatchUpdatesNotification(snapshot, disasterSafe, objectsUpdates); } if (remoteClient != null) remoteClient.onNotification(batch.clone(remoteClient.nextSeqN())); lastNotification = now; return snapshot; } @Override public void onNotification(BatchUpdatesNotification evt) { Thread.dumpStack(); } @Override public void onNotification(PubSubNotification<CRDTIdentifier> evt) { Thread.dumpStack(); } } public ClientSession getSession(ClientRequest clientRequest) { return getSession(clientRequest.getClientId(), clientRequest.isDisasterSafeSession()); } public ClientSession getSession(String clientId, boolean disasterSafe) { ClientSession session = sessions.get(clientId), nsession; if (session == null) { session = sessions.putIfAbsent(clientId, nsession = new ClientSession(clientId, disasterSafe)); if (session == null) { session = nsession; session.initNotifications(); } if (ReportType.IDEMPOTENCE_GUARD_SIZE.isEnabled()) { SafeLog.report(ReportType.IDEMPOTENCE_GUARD_SIZE, sessions.size()); } } return session; } private ConcurrentHashMap<String, ClientSession> sessions = new ConcurrentHashMap<String, ClientSession>(); // private static LWWStringMapRegisterUpdate FAKE_INIT_UPDATE = new // LWWStringMapRegisterUpdate(1, // AbstractLWWRegisterCRDT.INIT_TIMESTAMP, new HashMap<String, String>()); // Map<String, Object> evaluateStaleReads(FetchObjectVersionRequest request, // CausalityClock estimatedDCVersionCopy, // CausalityClock estimatedDCStableVersionCopy) { // // Map<String, Object> res = new HashMap<String, Object>(); // // ManagedCRDT mostRecentDCVersion = getCRDT(request.getUid(), // estimatedDCVersionCopy, request.getClientId()); // // ManagedCRDT mostRecentScoutVersion = getCRDT(request.getUid(), // request.getClock(), request.getClientId()); // // if (mostRecentDCVersion != null && mostRecentScoutVersion != null) { // // List<TimestampMapping> diff1 = // mostRecentScoutVersion.getUpdatesTimestampMappingsSince(request // .getDistasterDurableClock()); // // List<TimestampMapping> diff2 = // mostRecentDCVersion.getUpdatesTimestampMappingsSince(request // .getDistasterDurableClock()); // // List<TimestampMapping> diff3 = mostRecentDCVersion // .getUpdatesTimestampMappingsSince(estimatedDCStableVersionCopy); // // res.put("timestamp", request.timestamp); // res.put("Diff1-scout-normal-vs-scout-stable", diff1.size()); // res.put("Diff2-dc-normal-vs-scout-stable", diff2.size()); // res.put("Diff3-dc-normal-vs-dc-stable", diff3.size()); // // res.put("dc-estimatedVersion", estimatedDCVersionCopy); // // res.put("dc-estimatedStableVersion", // // estimatedDCStableVersionCopy); // // res.put("scout-version", request.getVersion()); // // res.put("scout-clock", request.getClock()); // // res.put("scout-stableClock", request.getDistasterDurableClock()); // // res.put("crdt", mostRecentDCVersion.clock); // } // return res; // } }
src-core/swift/dc/DCSurrogate.java
/***************************************************************************** * Copyright 2011-2012 INRIA * Copyright 2011-2012 Universidade Nova de Lisboa * * 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 swift.dc; import static sys.net.api.Networking.Networking; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.logging.Level; import java.util.logging.Logger; import swift.clocks.CausalityClock; import swift.clocks.CausalityClock.CMP_CLOCK; import swift.clocks.ClockFactory; import swift.clocks.Timestamp; import swift.crdt.core.CRDT; import swift.crdt.core.CRDTIdentifier; import swift.crdt.core.CRDTObjectUpdatesGroup; import swift.crdt.core.ManagedCRDT; import swift.proto.BatchCommitUpdatesReply; import swift.proto.BatchCommitUpdatesRequest; import swift.proto.BatchFetchObjectVersionReply; import swift.proto.BatchFetchObjectVersionReply.FetchStatus; import swift.proto.BatchFetchObjectVersionRequest; import swift.proto.ClientRequest; import swift.proto.CommitTSReply; import swift.proto.CommitTSRequest; import swift.proto.CommitUpdatesReply; import swift.proto.CommitUpdatesReply.CommitStatus; import swift.proto.CommitUpdatesRequest; import swift.proto.GenerateDCTimestampReply; import swift.proto.GenerateDCTimestampRequest; import swift.proto.LatestKnownClockReply; import swift.proto.LatestKnownClockRequest; import swift.proto.PingReply; import swift.proto.PingRequest; import swift.proto.SeqCommitUpdatesRequest; import swift.proto.SwiftProtocolHandler; import swift.pubsub.BatchUpdatesNotification; import swift.pubsub.SurrogatePubSubService; import swift.pubsub.SwiftSubscriber; import swift.pubsub.UpdateNotification; import swift.utils.FutureResultHandler; import swift.utils.SafeLog; import swift.utils.SafeLog.ReportType; import sys.Sys; import sys.dht.DHT_Node; import sys.net.api.Endpoint; import sys.net.api.rpc.RpcEndpoint; import sys.net.api.rpc.RpcHandle; import sys.pubsub.PubSubNotification; import sys.pubsub.RemoteSubscriber; import sys.pubsub.impl.AbstractSubscriber; import sys.scheduler.PeriodicTask; //import swift.client.proto.FastRecentUpdatesReply; //import swift.client.proto.FastRecentUpdatesReply.ObjectSubscriptionInfo; //import swift.client.proto.FastRecentUpdatesReply.SubscriptionStatus; //import swift.client.proto.FastRecentUpdatesRequest; /** * Class to handle the requests from clients. * * @author preguica */ final public class DCSurrogate extends SwiftProtocolHandler { public static final boolean FAKE_PRACTI_DEPOT_VECTORS = false; public static final boolean OPTIMIZED_VECTORS_IN_BATCH = false; static Logger logger = Logger.getLogger(DCSurrogate.class.getName()); String siteId; String surrogateId; RpcEndpoint srvEndpoint4Clients; RpcEndpoint srvEndpoint4Sequencer; Endpoint sequencerServerEndpoint; RpcEndpoint cltEndpoint4Sequencer; DCDataServer dataServer; CausalityClock estimatedDCVersion; // estimate of current DC state CausalityClock estimatedDCStableVersion; // estimate of current DC state AtomicReference<CausalityClock> estimatedDCVersionShadow; // read only // estimate of // current DC // state AtomicReference<CausalityClock> estimatedDCStableVersionShadow; // read // only // estimate // of // current // DC // state final public SurrogatePubSubService suPubSub; public int pubsubPort; final ThreadPoolExecutor crdtExecutor; final ThreadPoolExecutor generalExecutor; private final int notificationPeriodMillis; DCSurrogate(String siteId, int port4Clients, int port4Sequencers, Endpoint sequencerEndpoint, Properties props) { this.siteId = siteId; this.surrogateId = "s" + System.nanoTime(); this.pubsubPort = port4Clients + 1; this.sequencerServerEndpoint = sequencerEndpoint; this.cltEndpoint4Sequencer = Networking.rpcConnect().toDefaultService(); this.srvEndpoint4Clients = Networking.rpcBind(port4Clients).toDefaultService(); this.srvEndpoint4Sequencer = Networking.rpcBind(port4Sequencers).toDefaultService(); srvEndpoint4Clients.setHandler(this); srvEndpoint4Sequencer.setHandler(this); srvEndpoint4Clients.getFactory().setExecutor(Executors.newCachedThreadPool()); srvEndpoint4Sequencer.getFactory().setExecutor(Executors.newFixedThreadPool(2)); ArrayBlockingQueue<Runnable> crdtWorkQueue = new ArrayBlockingQueue<Runnable>(512); crdtExecutor = new ThreadPoolExecutor(4, 8, 3, TimeUnit.SECONDS, crdtWorkQueue); crdtExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); ArrayBlockingQueue<Runnable> generalWorkQueue = new ArrayBlockingQueue<Runnable>(512); generalExecutor = new ThreadPoolExecutor(4, 8, 3, TimeUnit.SECONDS, generalWorkQueue); generalExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); suPubSub = new SurrogatePubSubService(generalExecutor, this); dataServer = new DCDataServer(this, props, suPubSub, port4Clients + 2); final String notificationPeriodString = props.getProperty(DCConstants.NOTIFICATION_PERIOD_PROPERTY); if (notificationPeriodString != null) { notificationPeriodMillis = Integer.valueOf(notificationPeriodString); } else { notificationPeriodMillis = DCConstants.DEFAULT_NOTIFICATION_PERIOD_MS; } initData(props); if (logger.isLoggable(Level.INFO)) { logger.info("Server ready..."); } DHT_Node.init(siteId, "surrogates", srvEndpoint4Clients.localEndpoint()); new PeriodicTask(0.0, 0.1) { public void run() { updateEstimatedDCVersion(); } }; } private void initData(Properties props) { estimatedDCVersion = ClockFactory.newClock(); estimatedDCStableVersion = ClockFactory.newClock(); // HACK HACK CausalityClock clk = (CausalityClock) dataServer.dbServer.readSysData("SYS_TABLE", "CURRENT_CLK"); if (clk != null) { logger.info("SURROGATE CLK:" + clk); estimatedDCVersion.merge(clk); estimatedDCStableVersion.merge(clk); } estimatedDCVersionShadow = new AtomicReference<CausalityClock>(estimatedDCVersion.clone()); estimatedDCStableVersionShadow = new AtomicReference<CausalityClock>(estimatedDCStableVersion.clone()); logger.info("EstimatedDCVersion: " + estimatedDCVersion); } public String getId() { return surrogateId; } public CausalityClock getEstimatedDCVersionCopy() { return estimatedDCVersionShadow.get().clone(); } CausalityClock getEstimatedDCStableVersionCopy() { return estimatedDCStableVersionShadow.get().clone(); } public void updateEstimatedDCVersion(CausalityClock cc) { synchronized (estimatedDCVersion) { estimatedDCVersion.merge(cc); estimatedDCVersionShadow.set(estimatedDCVersion.clone()); } } public void updateEstimatedDCStableVersion(CausalityClock cc) { synchronized (estimatedDCStableVersion) { estimatedDCStableVersion.merge(cc); estimatedDCStableVersionShadow.set(estimatedDCStableVersion.clone()); } } /******************************************************************************************** * Methods related with notifications from clients *******************************************************************************************/ <V extends CRDT<V>> ExecCRDTResult execCRDT(CRDTObjectUpdatesGroup<V> grp, CausalityClock snapshotVersion, CausalityClock trxVersion, Timestamp txTs, Timestamp cltTs, Timestamp prvCltTs, CausalityClock curDCVersion) { return dataServer.execCRDT(grp, snapshotVersion, trxVersion, txTs, cltTs, prvCltTs, curDCVersion); } private void updateEstimatedDCVersion() { cltEndpoint4Sequencer.send(sequencerServerEndpoint, new LatestKnownClockRequest("surrogate", false), this, 0); } public void onReceive(RpcHandle conn, LatestKnownClockReply reply) { if (logger.isLoggable(Level.INFO)) { logger.info("LatestKnownClockReply: clk:" + reply.getClock()); } updateEstimatedDCVersion(reply.getClock()); updateEstimatedDCStableVersion(reply.getDistasterDurableClock()); } public void onReceive(RpcHandle conn, final BatchFetchObjectVersionRequest request) { if (logger.isLoggable(Level.INFO)) { logger.info("BatchFetchObjectVersionRequest client = " + request.getClientId() + "; crdt id = " + request.getUids()); } // LWWStringMapRegisterCRDT initialCheckpoint = new // LWWStringMapRegisterCRDT(request.getUid()); // FAKE_INIT_UPDATE.applyTo(initialCheckpoint); // conn.reply(new FetchObjectVersionReply(FetchStatus.OK, new // ManagedCRDT<LWWStringMapRegisterCRDT>(request // .getUid(), initialCheckpoint, request.getVersion(), true), // request.getVersion(), request.getVersion())); // return; // conn.reply(new FetchObjectVersionReply(FetchStatus.OK, new // ManagedCRDT<PutOnlyLWWStringMapCRDT>(request // .getUid(), new PutOnlyLWWStringMapCRDT(request.getUid()), // request.getVersion(), true), request // .getVersion(), request.getVersion())); // return; if (request.hasSubscription()) { for (final CRDTIdentifier id : request.getUids()) { getSession(request).subscribe(id); } } final ClientSession session = getSession(request); final Timestamp cltLastSeqNo = session.getLastSeqNo(); CMP_CLOCK cmp = CMP_CLOCK.CMP_EQUALS; CausalityClock estimatedDCVersionCopy = getEstimatedDCVersionCopy(); cmp = request.getVersion() == null ? CMP_CLOCK.CMP_EQUALS : estimatedDCVersionCopy.compareTo(request .getVersion()); if (cmp == CMP_CLOCK.CMP_ISDOMINATED || cmp == CMP_CLOCK.CMP_CONCURRENT) { updateEstimatedDCVersion(); estimatedDCVersionCopy = getEstimatedDCVersionCopy(); cmp = estimatedDCVersionCopy.compareTo(request.getVersion()); } final CMP_CLOCK finalCmpClk = cmp; final CausalityClock finalEstimatedDCVersionCopy = estimatedDCVersionCopy; CausalityClock estimatedDCStableVersionCopy = getEstimatedDCStableVersionCopy(); final CausalityClock disasterSafeVVReply = request.isSendDCVector() ? estimatedDCStableVersionCopy.clone() : null; if (disasterSafeVVReply != null) { disasterSafeVVReply.intersect(estimatedDCVersionCopy); } // TODO: for nodes !request.isDisasterSafe() send it less // frequently (it's for pruning only) final CausalityClock vvReply = !request.isDisasterSafeSession() && request.isSendDCVector() ? estimatedDCVersionCopy .clone() : null; final BatchFetchObjectVersionReply reply = new BatchFetchObjectVersionReply(request.getBatchSize(), vvReply, disasterSafeVVReply); final Semaphore sem = new Semaphore(0); for (int i = 0; i < request.getBatchSize(); i++) { final int finalIdx = i; dataServer.getCRDT(request.getUid(i), request.getKnownVersion(), request.getVersion(), request.getClientId(), request.isSendMoreRecentUpdates(), request.hasSubscription(), new FutureResultHandler<ManagedCRDT>() { @Override public void onResult(ManagedCRDT crdt) { try { adaptGetReplyToFetchReply(request, finalIdx, cltLastSeqNo, finalCmpClk, finalEstimatedDCVersionCopy, reply, crdt); } finally { sem.release(); } } }); } sem.acquireUninterruptibly(request.getBatchSize()); if (request.getBatchSize() > 1 && !request.isSendMoreRecentUpdates()) { final CausalityClock commonPruneClock = request.getVersion().clone(); final CausalityClock commonClock = commonPruneClock.clone(); if (cltLastSeqNo != null) { commonClock.recordAllUntil(cltLastSeqNo); } reply.compressAllOKReplies(commonPruneClock, commonClock); } conn.reply(reply); } private void adaptGetReplyToFetchReply(final BatchFetchObjectVersionRequest request, int idxInBatch, final Timestamp cltLastSeqNo, final CMP_CLOCK versionToDcCmpClock, final CausalityClock estimatedDCVersionClock, final BatchFetchObjectVersionReply reply, ManagedCRDT crdt) { if (crdt == null) { if (request.getKnownVersion() == null) { if (logger.isLoggable(Level.INFO)) { logger.info("BatchFetchObjectVersionRequest not found:" + request.getUid(idxInBatch)); } reply.setReply(idxInBatch, BatchFetchObjectVersionReply.FetchStatus.OBJECT_NOT_FOUND, null); } else { reply.setReply(idxInBatch, FetchStatus.UP_TO_DATE, null); } } else { synchronized (crdt) { crdt.augmentWithDCClockWithoutMappings(estimatedDCVersionClock); if (cltLastSeqNo != null) crdt.augmentWithScoutClockWithoutMappings(cltLastSeqNo); // TODO: move it to data nodes if (!request.isSendMoreRecentUpdates()) { CausalityClock restriction = (CausalityClock) request.getVersion().copy(); if (cltLastSeqNo != null) { restriction.recordAllUntil(cltLastSeqNo); } crdt.discardRecentUpdates(restriction); } final BatchFetchObjectVersionReply.FetchStatus status; if (versionToDcCmpClock.is(CMP_CLOCK.CMP_ISDOMINATED, CMP_CLOCK.CMP_CONCURRENT)) { logger.warning("Requested version " + request.getVersion() + " of object " + request.getUid(idxInBatch) + " missing; local version: " + estimatedDCVersionClock + " pruned as of " + crdt.getPruneClock()); status = FetchStatus.VERSION_MISSING; } else if (crdt.getPruneClock().compareTo(request.getVersion()) .is(CMP_CLOCK.CMP_DOMINATES, CMP_CLOCK.CMP_CONCURRENT)) { logger.warning("Requested version " + request.getVersion() + " of object " + request.getUid(idxInBatch) + " is pruned; local version: " + estimatedDCVersionClock + " pruned as of " + crdt.getPruneClock()); status = FetchStatus.VERSION_PRUNED; } else { status = FetchStatus.OK; } if (logger.isLoggable(Level.INFO)) { logger.info("BatchFetchObjectVersionRequest clock = " + crdt.getClock() + "/" + request.getUid(idxInBatch)); } reply.setReply(idxInBatch, status, crdt); } } } @Override public void onReceive(final RpcHandle conn, final CommitUpdatesRequest request) { if (logger.isLoggable(Level.INFO)) { logger.info("CommitUpdatesRequest client = " + request.getClientId() + ":ts=" + request.getCltTimestamp() + ":nops=" + request.getObjectUpdateGroups().size()); } final ClientSession session = getSession(request); if (logger.isLoggable(Level.INFO)) { logger.info("CommitUpdatesRequest ... lastSeqNo=" + session.getLastSeqNo()); } Timestamp cltTs = session.getLastSeqNo(); if (cltTs != null && cltTs.getCounter() >= request.getCltTimestamp().getCounter()) conn.reply(new CommitUpdatesReply(getEstimatedDCVersionCopy())); else prepareAndDoCommit(session, request, new FutureResultHandler<CommitUpdatesReply>() { @Override public void onResult(CommitUpdatesReply result) { conn.reply(result); } }); } private void prepareAndDoCommit(final ClientSession session, final CommitUpdatesRequest req, final FutureResultHandler<CommitUpdatesReply> resHandler) { final List<CRDTObjectUpdatesGroup<?>> ops = req.getObjectUpdateGroups(); final CausalityClock dependenciesClock = ops.size() > 0 ? req.getDependencyClock() : ClockFactory.newClock(); GenerateDCTimestampReply tsReply = cltEndpoint4Sequencer.request(sequencerServerEndpoint, new GenerateDCTimestampRequest(req.getClientId(), req.isDisasterSafeSession(), req.getCltTimestamp(), dependenciesClock)); req.setTimestamp(tsReply.getTimestamp()); // req.setDisasterSafe(); // FOR SOSP EVALUATION... doOneCommit(session, req, dependenciesClock, resHandler); } private void doOneCommit(final ClientSession session, final CommitUpdatesRequest req, final CausalityClock snapshotClock, final FutureResultHandler<CommitUpdatesReply> resHandler) { // 0) updates.addSystemTimestamp(timestampService.allocateTimestamp()) // 1) let int clientTxs = // clientTxClockService.getAndLockNumberOfCommitedTxs(clientId) // 2) for all modified objects: // crdt.augumentWithScoutClock(new Timestamp(clientId, clientTxs)) // // ensures that execute() has enough information to ensure tx // idempotence // crdt.execute(updates...) // crdt.discardScoutClock(clientId) // critical to not polute all data // nodes and objects with big vectors, unless we want to do it until // pruning // 3) clientTxClockService.unlock(clientId) if (logger.isLoggable(Level.INFO)) { logger.info("CommitUpdatesRequest: doProcessOneCommit: client = " + req.getClientId() + ":ts=" + req.getCltTimestamp() + ":nops=" + req.getObjectUpdateGroups().size()); } final List<CRDTObjectUpdatesGroup<?>> ops = req.getObjectUpdateGroups(); final Timestamp txTs = req.getTimestamp(); final Timestamp cltTs = req.getCltTimestamp(); final Timestamp prvCltTs = session.getLastSeqNo(); for (CRDTObjectUpdatesGroup<?> o : ops) o.addSystemTimestamp(txTs); final CausalityClock trxClock = snapshotClock.clone(); trxClock.record(txTs); final CausalityClock estimatedDCVersionCopy = getEstimatedDCVersionCopy(); int pos = 0; final AtomicBoolean txnOK = new AtomicBoolean(true); final AtomicReferenceArray<ExecCRDTResult> results = new AtomicReferenceArray<ExecCRDTResult>(ops.size()); if (ops.size() > 2) { // do multiple execCRDTs in parallel final Semaphore s = new Semaphore(0); for (final CRDTObjectUpdatesGroup<?> i : ops) { final int j = pos++; crdtExecutor.execute(new Runnable() { public void run() { try { results.set(j, execCRDT(i, snapshotClock, trxClock, txTs, cltTs, prvCltTs, estimatedDCVersionCopy)); txnOK.compareAndSet(true, results.get(j).isResult()); updateEstimatedDCVersion(i.getDependency()); } finally { s.release(); } } }); } s.acquireUninterruptibly(ops.size()); } else { for (final CRDTObjectUpdatesGroup<?> i : ops) { results.set(pos, execCRDT(i, snapshotClock, trxClock, txTs, cltTs, prvCltTs, estimatedDCVersionCopy)); txnOK.compareAndSet(true, results.get(pos).isResult()); updateEstimatedDCVersion(i.getDependency()); pos++; } } // TODO: handle failure session.setLastSeqNo(cltTs); srvEndpoint4Sequencer.send(sequencerServerEndpoint, new CommitTSRequest(txTs, cltTs, prvCltTs, estimatedDCVersionCopy, txnOK.get(), ops, req.disasterSafe(), session.clientId), new SwiftProtocolHandler() { public void onReceive(CommitTSReply reply) { if (logger.isLoggable(Level.INFO)) { logger.info("Commit: received CommitTSRequest:old vrs:" + estimatedDCVersionCopy + "; new vrs=" + reply.getCurrVersion() + ";ts = " + txTs + ";cltts = " + cltTs); } estimatedDCVersionCopy.record(txTs); updateEstimatedDCVersion(reply.getCurrVersion()); dataServer.dbServer.writeSysData("SYS_TABLE", "CURRENT_CLK", getEstimatedDCVersionCopy()); updateEstimatedDCStableVersion(reply.getStableVersion()); dataServer.dbServer.writeSysData("SYS_TABLE", "STABLE_CLK", getEstimatedDCStableVersionCopy()); if (txnOK.get() && reply.getStatus() == CommitTSReply.CommitTSStatus.OK) { if (logger.isLoggable(Level.INFO)) { logger.info("Commit: for publish DC version: SENDING ; on tx:" + txTs); } resHandler.onResult(new CommitUpdatesReply(txTs)); // return new CommitUpdatesReply(txTs); } else resHandler.onResult(new CommitUpdatesReply()); } }, 0); // if (reply == null) // logger.severe(String.format("------------>REPLY FROM SEQUENCER NULL for: %s, who:%s\n", // txTs, // session.clientId)); // // } while (reply == null); // // if (reply != null) { // // } // return new CommitUpdatesReply(); } @Override public void onReceive(final RpcHandle conn, final BatchCommitUpdatesRequest request) { if (logger.isLoggable(Level.INFO)) { logger.info("BatchCommitUpdatesRequest client = " + request.getClientId() + ":batch size=" + request.getCommitRequests().size()); } final ClientSession session = getSession(request); if (logger.isLoggable(Level.INFO)) { logger.info("BatchCommitUpdatesRequest ... lastSeqNo=" + session.getLastSeqNo()); } final List<Timestamp> tsLst = new LinkedList<Timestamp>(); final List<CommitUpdatesReply> reply = new LinkedList<CommitUpdatesReply>(); for (CommitUpdatesRequest r : request.getCommitRequests()) { if (session.getLastSeqNo() != null && session.getLastSeqNo().getCounter() >= r.getCltTimestamp().getCounter()) { reply.add(new CommitUpdatesReply(getEstimatedDCVersionCopy())); // FIXME: unless the timestamp is stable andpruned, we need to // send a precise mapping to the client! // Also, non-stable clock should appear in internal dependencies // in the batch. } else { // FIXME: is it required to respect internal dependencies in the // batch? Order in the local DC is respected already. // r.addTimestampsToDeps(tsLst); final Semaphore sem = new Semaphore(0); prepareAndDoCommit(session, r, new FutureResultHandler<CommitUpdatesReply>() { @Override public void onResult(CommitUpdatesReply repOne) { if (repOne.getStatus() == CommitStatus.COMMITTED_WITH_KNOWN_TIMESTAMPS) { List<Timestamp> tsLstOne = repOne.getCommitTimestamps(); if (tsLstOne != null) tsLst.addAll(tsLstOne); } reply.add(repOne); sem.release(); } }); sem.acquireUninterruptibly(); } } conn.reply(new BatchCommitUpdatesReply(reply)); } @Override public void onReceive(final RpcHandle conn, final SeqCommitUpdatesRequest request) { if (logger.isLoggable(Level.INFO)) { logger.info("SeqCommitUpdatesRequest timestamp = " + request.getTimestamp() + ";clt=" + request.getCltTimestamp()); } ClientSession session = getSession(request.getCltTimestamp().getIdentifier(), false); List<CRDTObjectUpdatesGroup<?>> ops = request.getObjectUpdateGroups(); CausalityClock snapshotClock = ops.size() > 0 ? ops.get(0).getDependency() : ClockFactory.newClock(); doOneCommit(session, request, snapshotClock, new FutureResultHandler<CommitUpdatesReply>() { @Override public void onResult(CommitUpdatesReply result) { conn.reply(result); } }); } @Override public void onReceive(final RpcHandle conn, LatestKnownClockRequest request) { if (logger.isLoggable(Level.INFO)) { logger.info("LatestKnownClockRequest client = " + request.getClientId()); } cltEndpoint4Sequencer.send(sequencerServerEndpoint, request, new SwiftProtocolHandler() { public void onReceive(RpcHandle conn2, LatestKnownClockReply reply) { if (logger.isLoggable(Level.INFO)) { logger.info("LatestKnownClockRequest: forwarding reply:" + reply.getClock()); } updateEstimatedDCVersion(reply.getClock()); updateEstimatedDCStableVersion(reply.getDistasterDurableClock()); conn.reply(reply); } }, 0); } @Override public void onReceive(final RpcHandle conn, PingRequest request) { PingReply reply = new PingReply(request.getTimeAtSender(), System.currentTimeMillis()); conn.reply(reply); } public class ClientSession extends AbstractSubscriber<CRDTIdentifier> implements SwiftSubscriber { final String clientId; boolean disasterSafe; volatile Timestamp lastSeqNo; private CausalityClock clientFakeVectorKnowledge; private CausalityClock lastSnapshotVector; private RemoteSubscriber<CRDTIdentifier> remoteClient; private PeriodicTask notificationsTask; ClientSession(String clientId, boolean disasterSafe) { super(clientId); this.clientId = clientId; this.disasterSafe = disasterSafe; if (FAKE_PRACTI_DEPOT_VECTORS) { clientFakeVectorKnowledge = ClockFactory.newClock(); } if (OPTIMIZED_VECTORS_IN_BATCH) { lastSnapshotVector = ClockFactory.newClock(); } } // idempotent public synchronized void initNotifications() { if (notificationsTask != null) { return; } notificationsTask = new PeriodicTask(0.5, notificationPeriodMillis * 0.001) { public void run() { tryFireClientNotification(); } }; } public CausalityClock getMinVV() { return suPubSub.minDcVersion(); } public ClientSession setClientEndpoint(Endpoint remote) { remoteClient = new RemoteSubscriber<CRDTIdentifier>(clientId, suPubSub.endpoint(), remote); return this; } Timestamp getLastSeqNo() { return lastSeqNo; } void setLastSeqNo(Timestamp cltTs) { this.lastSeqNo = cltTs; } public void subscribe(CRDTIdentifier key) { suPubSub.subscribe(key, this); } public void unsubscribe(Set<CRDTIdentifier> keys) { suPubSub.unsubscribe(keys, this); } long lastNotification = 0L; List<CRDTObjectUpdatesGroup<?>> pending = new ArrayList<CRDTObjectUpdatesGroup<?>>(); synchronized public void onNotification(final UpdateNotification update) { List<CRDTObjectUpdatesGroup<?>> updates = update.info.getUpdates(); if (updates.isEmpty() || clientId.equals(updates.get(0).getClientTimestamp().getIdentifier())) { // Ignore return; } pending.addAll(update.info.getUpdates()); tryFireClientNotification(); } protected synchronized CausalityClock tryFireClientNotification() { long now = Sys.Sys.timeMillis(); if (now <= (lastNotification + notificationPeriodMillis)) { return null; } final CausalityClock snapshot = suPubSub.minDcVersion(); if (disasterSafe) { snapshot.intersect(getEstimatedDCStableVersionCopy()); } if (OPTIMIZED_VECTORS_IN_BATCH) { for (final String dcId : lastSnapshotVector.getSiteIds()) { if (lastSnapshotVector.includes(snapshot.getLatest(dcId))) { snapshot.drop(dcId); } } lastSnapshotVector.merge(snapshot); } final HashMap<CRDTIdentifier, List<CRDTObjectUpdatesGroup<?>>> objectsUpdates = new HashMap<CRDTIdentifier, List<CRDTObjectUpdatesGroup<?>>>(); final Iterator<CRDTObjectUpdatesGroup<?>> iter = pending.iterator(); while (iter.hasNext()) { final CRDTObjectUpdatesGroup<?> u = iter.next(); if (u.anyTimestampIncluded(snapshot)) { // FIXME: for at-most-once check if any timestamp is // included in the previous clock of the scout List<CRDTObjectUpdatesGroup<?>> objectUpdates = objectsUpdates.get(u.getTargetUID()); if (objectUpdates == null) { objectUpdates = new LinkedList<CRDTObjectUpdatesGroup<?>>(); objectsUpdates.put(u.getTargetUID(), objectUpdates); } objectUpdates.add(u.strippedWithCopiedTimestampMappings()); iter.remove(); } } // TODO: for clients that cannot receive periodical updates (e.g. // mobile in background mode), one could require a transaction to // declare his read set and force refresh the cache before the // transaction if necessary. BatchUpdatesNotification batch; if (FAKE_PRACTI_DEPOT_VECTORS) { final CausalityClock fakeVector = ClockFactory.newClock(); // We compare against the stale vector matchin snapshot, but // these entries // would need to be eventually send anyways. for (final String clientId : dataServer.cltClock.getSiteIds()) { final Timestamp clientTimestamp = dataServer.cltClock.getLatest(clientId); if (!clientFakeVectorKnowledge.includes(clientTimestamp)) { fakeVector.recordAllUntil(clientTimestamp); clientFakeVectorKnowledge.recordAllUntil(clientTimestamp); } } clientFakeVectorKnowledge.merge(fakeVector); batch = new BatchUpdatesNotification(snapshot, disasterSafe, objectsUpdates, fakeVector); } else { batch = new BatchUpdatesNotification(snapshot, disasterSafe, objectsUpdates); } if (remoteClient != null) remoteClient.onNotification(batch.clone(remoteClient.nextSeqN())); lastNotification = now; return snapshot; } @Override public void onNotification(BatchUpdatesNotification evt) { Thread.dumpStack(); } @Override public void onNotification(PubSubNotification<CRDTIdentifier> evt) { Thread.dumpStack(); } } public ClientSession getSession(ClientRequest clientRequest) { return getSession(clientRequest.getClientId(), clientRequest.isDisasterSafeSession()); } public ClientSession getSession(String clientId, boolean disasterSafe) { ClientSession session = sessions.get(clientId), nsession; if (session == null) { session = sessions.putIfAbsent(clientId, nsession = new ClientSession(clientId, disasterSafe)); if (session == null) { session = nsession; session.initNotifications(); } if (ReportType.IDEMPOTENCE_GUARD_SIZE.isEnabled()) { SafeLog.report(ReportType.IDEMPOTENCE_GUARD_SIZE, sessions.size()); } } return session; } private ConcurrentHashMap<String, ClientSession> sessions = new ConcurrentHashMap<String, ClientSession>(); // private static LWWStringMapRegisterUpdate FAKE_INIT_UPDATE = new // LWWStringMapRegisterUpdate(1, // AbstractLWWRegisterCRDT.INIT_TIMESTAMP, new HashMap<String, String>()); // Map<String, Object> evaluateStaleReads(FetchObjectVersionRequest request, // CausalityClock estimatedDCVersionCopy, // CausalityClock estimatedDCStableVersionCopy) { // // Map<String, Object> res = new HashMap<String, Object>(); // // ManagedCRDT mostRecentDCVersion = getCRDT(request.getUid(), // estimatedDCVersionCopy, request.getClientId()); // // ManagedCRDT mostRecentScoutVersion = getCRDT(request.getUid(), // request.getClock(), request.getClientId()); // // if (mostRecentDCVersion != null && mostRecentScoutVersion != null) { // // List<TimestampMapping> diff1 = // mostRecentScoutVersion.getUpdatesTimestampMappingsSince(request // .getDistasterDurableClock()); // // List<TimestampMapping> diff2 = // mostRecentDCVersion.getUpdatesTimestampMappingsSince(request // .getDistasterDurableClock()); // // List<TimestampMapping> diff3 = mostRecentDCVersion // .getUpdatesTimestampMappingsSince(estimatedDCStableVersionCopy); // // res.put("timestamp", request.timestamp); // res.put("Diff1-scout-normal-vs-scout-stable", diff1.size()); // res.put("Diff2-dc-normal-vs-scout-stable", diff2.size()); // res.put("Diff3-dc-normal-vs-dc-stable", diff3.size()); // // res.put("dc-estimatedVersion", estimatedDCVersionCopy); // // res.put("dc-estimatedStableVersion", // // estimatedDCStableVersionCopy); // // res.put("scout-version", request.getVersion()); // // res.put("scout-clock", request.getClock()); // // res.put("scout-stableClock", request.getDistasterDurableClock()); // // res.put("crdt", mostRecentDCVersion.clock); // } // return res; // } }
DCSurrogate: report failure as a warning
src-core/swift/dc/DCSurrogate.java
DCSurrogate: report failure as a warning
<ide><path>rc-core/swift/dc/DCSurrogate.java <ide> } <ide> resHandler.onResult(new CommitUpdatesReply(txTs)); <ide> // return new CommitUpdatesReply(txTs); <del> } else <add> } else { <add> // FIXME: CommitTSStatus.FAILED if not well <add> // documented. How comes it can fail? <add> logger.warning("Commit: failed for request " + req); <ide> resHandler.onResult(new CommitUpdatesReply()); <add> } <ide> } <ide> }, 0); <ide>
Java
epl-1.0
40d412e89b47f2149e0d017090d1d5adf3a71bf8
0
OpenBMP/openbmp-mysql-consumer,OpenBMP/openbmp-mysql-consumer,OpenBMP/openbmp-mysql-consumer
package org.openbmp.handler; /* * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * */ import org.openbmp.processor.ParseLongEmptyAsZero; import org.openbmp.processor.ParseNullAsEmpty; import org.openbmp.processor.ParseTimestamp; import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.ParseBool; import org.supercsv.cellprocessor.ParseInt; import org.supercsv.cellprocessor.ParseLong; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.ift.CellProcessor; /** * Format class for peer parsed messages (openbmp.parsed.peer) * * Schema Version: 1 * */ public class Peer extends Base { /** * Handle the message by parsing it and storing the data in memory. * * @param data */ public Peer(String data) { super(); headerNames = new String [] { "action", "seq", "hash", "router_hash", "name", "remote_bgp_id", "router_ip", "timestamp", "remote_asn", "remote_ip", "peer_rd", "remote_port", "local_asn", "local_ip", "local_port", "local_bgp_id", "info_data", "adv_cap", "recv_cap", "remote_holddown", "adv_holddown", "bmp_reason", "bgp_error_code", "bgp_error_sub_code", "error_text", "isL3VPN", "isPrePolicy", "isIPv4"}; parse(data); } /** * Processors used for each field. * * Order matters and must match the same order as defined in headerNames * * @return array of cell processors */ protected CellProcessor[] getProcessors() { final CellProcessor[] processors = new CellProcessor[] { new NotNull(), // action new ParseLong(), // seq new NotNull(), // hash new NotNull(), // router hash new ParseNullAsEmpty(), // name new NotNull(), // remote_bgp_id new NotNull(), // router_ip new ParseTimestamp(), // Timestamp new ParseLong(), // remote_asn new NotNull(), // remote_ip new ParseNullAsEmpty(), // peer_rd new ParseLongEmptyAsZero(), // remote_port new ParseLongEmptyAsZero(), // local_asn new ParseNullAsEmpty(), // local_ip new ParseLongEmptyAsZero(), // local_port new ParseNullAsEmpty(), // local_bgp_id new ParseNullAsEmpty(), // info_data new ParseNullAsEmpty(), // adv_cap new ParseNullAsEmpty(), // recv_cap, new ParseLongEmptyAsZero(), // remote_holddown new ParseLongEmptyAsZero(), // local_holddown new ParseLongEmptyAsZero(), // bmp_reason new ParseLongEmptyAsZero(), // bgp_error_code new ParseLongEmptyAsZero(), // bgp_error_sub_code new ParseNullAsEmpty(), // error_text new ParseLongEmptyAsZero(), // isL3VPN new ParseLongEmptyAsZero(), // isPrePolicy new ParseLongEmptyAsZero() // isIPv4 }; return processors; } /** * Generate MySQL insert/update statement, sans the values * * @return Two strings are returned * 0 = Insert statement string up to VALUES keyword * 1 = ON DUPLICATE KEY UPDATE ... or empty if not used. */ public String[] genInsertStatement() { String [] stmt = { " REPLACE INTO bgp_peers (hash_id,router_hash_id,peer_rd,isIPv4,peer_addr,name,peer_bgp_id," + "peer_as,state,isL3VPNpeer,timestamp,isPrePolicy,local_ip,local_bgp_id,local_port," + "local_hold_time,local_asn,remote_port,remote_hold_time,sent_capabilities," + "recv_capabilities,bmp_reason,bgp_err_code,bgp_err_subcode,error_text) VALUES ", "" }; return stmt; } /** * Generate bulk values statement for SQL bulk insert. * * @return String in the format of (col1, col2, ...)[,...] */ public String genValuesStatement() { StringBuilder sb = new StringBuilder(); for (int i=0; i < rowMap.size(); i++) { if (i > 0) sb.append(','); sb.append('('); sb.append("'" + rowMap.get(i).get("hash") + "',"); sb.append("'" + rowMap.get(i).get("router_hash") + "',"); sb.append("'" + rowMap.get(i).get("peer_rd") + "',"); sb.append(rowMap.get(i).get("isIPv4") + ","); sb.append("'" + rowMap.get(i).get("remote_ip") + "',"); sb.append("'" + rowMap.get(i).get("name") + "',"); sb.append("'" + rowMap.get(i).get("remote_bgp_id") + "',"); sb.append(rowMap.get(i).get("remote_asn") + ","); sb.append((((String)rowMap.get(i).get("action")).equalsIgnoreCase("up") ? 1 : 0) + ","); sb.append(rowMap.get(i).get("isL3VPN") + ","); sb.append("'" + rowMap.get(i).get("timestamp") + "',"); sb.append(rowMap.get(i).get("isPrePolicy") + ","); sb.append("'" + rowMap.get(i).get("local_ip") + "',"); sb.append("'" + rowMap.get(i).get("local_bgp_id") + "',"); sb.append(rowMap.get(i).get("local_port") + ","); sb.append(rowMap.get(i).get("adv_holddown") + ","); sb.append(rowMap.get(i).get("local_asn") + ","); sb.append(rowMap.get(i).get("remote_port") + ","); sb.append(rowMap.get(i).get("remote_holddown") + ","); sb.append("'" + rowMap.get(i).get("adv_cap") + "',"); sb.append("'" + rowMap.get(i).get("recv_cap") + "',"); sb.append(rowMap.get(i).get("bmp_reason") + ","); sb.append(rowMap.get(i).get("bgp_error_code") + ","); sb.append(rowMap.get(i).get("bgp_error_sub_code") + ","); sb.append("'" + rowMap.get(i).get("error_text") + "'"); sb.append(')'); } return sb.toString(); } /** * Generate MySQL RIB update statement to withdraw all rib entries * * Upon peer up or down, withdraw all RIB entries. When the PEER is up all * RIB entries will get updated. Depending on how long the peer was down, some * entries may not be present anymore, thus they are withdrawn. * * @return Multi statement update is returned, such as update ...; update ...; */ public String genRibPeerUpdate() { StringBuilder sb = new StringBuilder(); sb.append("SET @TRIGGER_DISABLED=TRUE; "); for (int i=0; i < rowMap.size(); i++) { if (i > 0) sb.append(';'); sb.append("UPDATE rib SET isWithdrawn = True WHERE peer_hash_id = '"); sb.append(rowMap.get(i).get("hash")); sb.append("' AND isWithdrawn = False"); sb.append("; UPDATE ls_nodes SET isWithdrawn = True WHERE peer_hash_id = '"); sb.append(rowMap.get(i).get("hash")); sb.append("' AND isWithdrawn = False"); sb.append("; UPDATE ls_links SET isWithdrawn = True WHERE peer_hash_id = '"); sb.append(rowMap.get(i).get("hash")); sb.append("' AND isWithdrawn = False"); sb.append("; UPDATE ls_prefixes SET isWithdrawn = True WHERE peer_hash_id = '"); sb.append(rowMap.get(i).get("hash")); sb.append("' AND isWithdrawn = False"); } sb.append("SET @TRIGGER_DISABLED=FALSE; "); return sb.toString(); } }
src/main/java/org/openbmp/handler/Peer.java
package org.openbmp.handler; /* * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * */ import org.openbmp.processor.ParseLongEmptyAsZero; import org.openbmp.processor.ParseNullAsEmpty; import org.openbmp.processor.ParseTimestamp; import org.supercsv.cellprocessor.Optional; import org.supercsv.cellprocessor.ParseBool; import org.supercsv.cellprocessor.ParseInt; import org.supercsv.cellprocessor.ParseLong; import org.supercsv.cellprocessor.constraint.NotNull; import org.supercsv.cellprocessor.ift.CellProcessor; /** * Format class for peer parsed messages (openbmp.parsed.peer) * * Schema Version: 1 * */ public class Peer extends Base { /** * Handle the message by parsing it and storing the data in memory. * * @param data */ public Peer(String data) { super(); headerNames = new String [] { "action", "seq", "hash", "router_hash", "name", "remote_bgp_id", "router_ip", "timestamp", "remote_asn", "remote_ip", "peer_rd", "remote_port", "local_asn", "local_ip", "local_port", "local_bgp_id", "info_data", "adv_cap", "recv_cap", "remote_holddown", "adv_holddown", "bmp_reason", "bgp_error_code", "bgp_error_sub_code", "error_text", "isL3VPN", "isPrePolicy", "isIPv4"}; parse(data); } /** * Processors used for each field. * * Order matters and must match the same order as defined in headerNames * * @return array of cell processors */ protected CellProcessor[] getProcessors() { final CellProcessor[] processors = new CellProcessor[] { new NotNull(), // action new ParseLong(), // seq new NotNull(), // hash new NotNull(), // router hash new ParseNullAsEmpty(), // name new NotNull(), // remote_bgp_id new NotNull(), // router_ip new ParseTimestamp(), // Timestamp new ParseLong(), // remote_asn new NotNull(), // remote_ip new ParseNullAsEmpty(), // peer_rd new ParseLongEmptyAsZero(), // remote_port new ParseLongEmptyAsZero(), // local_asn new ParseNullAsEmpty(), // local_ip new ParseLongEmptyAsZero(), // local_port new ParseNullAsEmpty(), // local_bgp_id new ParseNullAsEmpty(), // info_data new ParseNullAsEmpty(), // adv_cap new ParseNullAsEmpty(), // recv_cap, new ParseLongEmptyAsZero(), // remote_holddown new ParseLongEmptyAsZero(), // local_holddown new ParseLongEmptyAsZero(), // bmp_reason new ParseLongEmptyAsZero(), // bgp_error_code new ParseLongEmptyAsZero(), // bgp_error_sub_code new ParseNullAsEmpty(), // error_text new ParseLongEmptyAsZero(), // isL3VPN new ParseLongEmptyAsZero(), // isPrePolicy new ParseLongEmptyAsZero() // isIPv4 }; return processors; } /** * Generate MySQL insert/update statement, sans the values * * @return Two strings are returned * 0 = Insert statement string up to VALUES keyword * 1 = ON DUPLICATE KEY UPDATE ... or empty if not used. */ public String[] genInsertStatement() { String [] stmt = { " REPLACE INTO bgp_peers (hash_id,router_hash_id,peer_rd,isIPv4,peer_addr,name,peer_bgp_id," + "peer_as,state,isL3VPNpeer,timestamp,isPrePolicy,local_ip,local_bgp_id,local_port," + "local_hold_time,local_asn,remote_port,remote_hold_time,sent_capabilities," + "recv_capabilities,bmp_reason,bgp_err_code,bgp_err_subcode,error_text) VALUES ", "" }; return stmt; } /** * Generate bulk values statement for SQL bulk insert. * * @return String in the format of (col1, col2, ...)[,...] */ public String genValuesStatement() { StringBuilder sb = new StringBuilder(); for (int i=0; i < rowMap.size(); i++) { if (i > 0) sb.append(','); sb.append('('); sb.append("'" + rowMap.get(i).get("hash") + "',"); sb.append("'" + rowMap.get(i).get("router_hash") + "',"); sb.append("'" + rowMap.get(i).get("peer_rd") + "',"); sb.append(rowMap.get(i).get("isIPv4") + ","); sb.append("'" + rowMap.get(i).get("remote_ip") + "',"); sb.append("'" + rowMap.get(i).get("name") + "',"); sb.append("'" + rowMap.get(i).get("remote_bgp_id") + "',"); sb.append(rowMap.get(i).get("remote_asn") + ","); sb.append((((String)rowMap.get(i).get("action")).equalsIgnoreCase("up") ? 1 : 0) + ","); sb.append(rowMap.get(i).get("isL3VPN") + ","); sb.append("'" + rowMap.get(i).get("timestamp") + "',"); sb.append(rowMap.get(i).get("isPrePolicy") + ","); sb.append("'" + rowMap.get(i).get("local_ip") + "',"); sb.append("'" + rowMap.get(i).get("local_bgp_id") + "',"); sb.append(rowMap.get(i).get("local_port") + ","); sb.append(rowMap.get(i).get("adv_holddown") + ","); sb.append(rowMap.get(i).get("local_asn") + ","); sb.append(rowMap.get(i).get("remote_port") + ","); sb.append(rowMap.get(i).get("remote_holddown") + ","); sb.append("'" + rowMap.get(i).get("adv_cap") + "',"); sb.append("'" + rowMap.get(i).get("recv_cap") + "',"); sb.append(rowMap.get(i).get("bmp_reason") + ","); sb.append(rowMap.get(i).get("bgp_error_code") + ","); sb.append(rowMap.get(i).get("bgp_error_sub_code") + ","); sb.append("'" + rowMap.get(i).get("error_text") + "'"); sb.append(')'); } return sb.toString(); } /** * Generate MySQL RIB update statement to withdraw all rib entries * * Upon peer up or down, withdraw all RIB entries. When the PEER is up all * RIB entries will get updated. Depending on how long the peer was down, some * entries may not be present anymore, thus they are withdrawn. * * @return Multi statement update is returned, such as update ...; update ...; */ public String genRibPeerUpdate() { StringBuilder sb = new StringBuilder(); sb.append("SET @TRIGGER_DISABLED=TRUE; "); for (int i=0; i < rowMap.size(); i++) { if (i > 0) sb.append(';'); sb.append("UPDATE rib SET isWithdrawn = True WHERE peer_hash_id = '"); sb.append(rowMap.get(i).get("hash")); sb.append("' AND isWithdrawn = False"); } sb.append("SET @TRIGGER_DISABLED=FALSE; "); return sb.toString(); } }
Update to have peer up/down set link-state NLRI's to withdrawn. Upon peer down or up, all NLRI's should be marked as withdrawn.
src/main/java/org/openbmp/handler/Peer.java
Update to have peer up/down set link-state NLRI's to withdrawn.
<ide><path>rc/main/java/org/openbmp/handler/Peer.java <ide> sb.append("UPDATE rib SET isWithdrawn = True WHERE peer_hash_id = '"); <ide> sb.append(rowMap.get(i).get("hash")); <ide> sb.append("' AND isWithdrawn = False"); <add> <add> sb.append("; UPDATE ls_nodes SET isWithdrawn = True WHERE peer_hash_id = '"); <add> sb.append(rowMap.get(i).get("hash")); <add> sb.append("' AND isWithdrawn = False"); <add> sb.append("; UPDATE ls_links SET isWithdrawn = True WHERE peer_hash_id = '"); <add> sb.append(rowMap.get(i).get("hash")); <add> sb.append("' AND isWithdrawn = False"); <add> sb.append("; UPDATE ls_prefixes SET isWithdrawn = True WHERE peer_hash_id = '"); <add> sb.append(rowMap.get(i).get("hash")); <add> sb.append("' AND isWithdrawn = False"); <add> <ide> } <ide> <ide> sb.append("SET @TRIGGER_DISABLED=FALSE; ");
Java
mit
d18dd9e2a1122284c803ff7ed26d76d11e13e1ba
0
fhirschmann/clozegen,fhirschmann/clozegen
/* * Copyright (C) 2012 Fabian Hirschmann <[email protected]> * * 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 com.github.fhirschmann.clozegen.lib.frequency; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import nu.xom.*; /** * Base class for all Frequency Distribution Lists. * <p> * This base class allows you to load a list of frequencies from an XML * file. These XML files must be of the following nature: * <pre> * <frequencies> * <frequency value="1234" ... /> * <frequency value="4563" ... /> * </frequencies> * </pre> * The only required XML attribute here is the "value" attribute which indicates * how many times the subject has occurred. You can add as many attributes * as you like and process them in processChild(), so the population * of the frequencies with ValueCount<T> is up to you. * </p> * * @author Fabian Hirschmann <[email protected]> */ public abstract class AbstractFrequencyList<T> { /** The frequency count. */ private final List<ValueCount<T>> frequencies = new ArrayList<ValueCount<T>>(); /** * This method lets you process individual frequency-children in the XML file. * * @param child */ abstract void processChild(Element child); /** * Loads the frequency list from an XML file. * * @param xmlFile * @throws ParsingException * @throws ValidityException * @throws IOException */ public void load(final String xmlFile) throws ParsingException, ValidityException, IOException { final InputStream stream = this.getClass().getClassLoader(). getResourceAsStream(xmlFile); final Builder builder = new Builder(); final Document doc = builder.build(stream); final Element root = doc.getRootElement(); for (int i = 0; i < root.getChildCount(); i++) { final Element child = root.getChildElements().get(i); processChild(child); } Collections.sort(getFrequencies()); } /** * @return the frequencies */ public List<ValueCount<T>> getFrequencies() { return frequencies; } }
lib/src/main/java/com/github/fhirschmann/clozegen/lib/frequency/AbstractFrequencyList.java
/* * Copyright (C) 2012 Fabian Hirschmann <[email protected]> * * 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 com.github.fhirschmann.clozegen.lib.frequency; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import nu.xom.*; /** * Base class for all Frequency Distribution Lists. * <p> * This base class allows you to load a list of frequencies from an XML * file. These XML files must be of the following nature: * <pre> * <frequencies> * <frequency value="1234" ... /> * <frequency value="4563" ... /> * </frequencies> * </pre> * The only required xml attribute here is the "value" attribute which indicates * how many times the subject has occurred. You can add as many attributes * as you like and process them in processChild(), so the population * of the frequencies with ValueCount<T> is up to you. * </p> * * @author Fabian Hirschmann <[email protected]> */ public abstract class AbstractFrequencyList<T> { /** The frequency count. */ private final List<ValueCount<T>> frequencies = new ArrayList<ValueCount<T>>(); /** * This method lets you process individual frequency-children in the XML file. * * @param child */ abstract void processChild(Element child); /** * Loads the frequency list from an XML file. * * @param xmlFile * @throws ParsingException * @throws ValidityException * @throws IOException */ public void load(final String xmlFile) throws ParsingException, ValidityException, IOException { final InputStream stream = this.getClass().getClassLoader(). getResourceAsStream(xmlFile); final Builder builder = new Builder(); final Document doc = builder.build(stream); final Element root = doc.getRootElement(); for (int i = 0; i < root.getChildCount(); i++) { final Element child = root.getChildElements().get(i); processChild(child); } Collections.sort(getFrequencies()); } /** * @return the frequencies */ public List<ValueCount<T>> getFrequencies() { return frequencies; } }
fixed spelling
lib/src/main/java/com/github/fhirschmann/clozegen/lib/frequency/AbstractFrequencyList.java
fixed spelling
<ide><path>ib/src/main/java/com/github/fhirschmann/clozegen/lib/frequency/AbstractFrequencyList.java <ide> * <frequency value="4563" ... /> <ide> * </frequencies> <ide> * </pre> <del> * The only required xml attribute here is the "value" attribute which indicates <add> * The only required XML attribute here is the "value" attribute which indicates <ide> * how many times the subject has occurred. You can add as many attributes <ide> * as you like and process them in processChild(), so the population <ide> * of the frequencies with ValueCount<T> is up to you.
Java
apache-2.0
ebeac25ecb2c9752c2c884f3087798b72398fc6a
0
mapr/hbase,mapr/hbase,mapr/hbase,mapr/hbase,mapr/hbase,mapr/hbase,mapr/hbase,mapr/hbase,mapr/hbase
/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.ipc; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.security.PrivilegedExceptionAction; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import javax.net.SocketFactory; import javax.security.sasl.SaslException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.CellScanner; import org.apache.hadoop.hbase.HBaseIOException; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.codec.Codec; import org.apache.hadoop.hbase.codec.KeyValueCodec; import org.apache.hadoop.hbase.protobuf.ProtobufUtil; import org.apache.hadoop.hbase.protobuf.generated.AuthenticationProtos; import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.CellBlockMeta; import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.ConnectionHeader; import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.ExceptionResponse; import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.RequestHeader; import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.ResponseHeader; import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.UserInformation; import org.apache.hadoop.hbase.protobuf.generated.TracingProtos.RPCTInfo; import org.apache.hadoop.hbase.security.AuthMethod; import org.apache.hadoop.hbase.security.HBaseSaslRpcClient; import org.apache.hadoop.hbase.security.SecurityInfo; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.security.UserProvider; import org.apache.hadoop.hbase.security.token.AuthenticationTokenSelector; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; import org.apache.hadoop.hbase.util.ExceptionUtil; import org.apache.hadoop.hbase.util.Pair; import org.apache.hadoop.hbase.util.PoolMap; import org.apache.hadoop.hbase.util.PoolMap.PoolType; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.ipc.RemoteException; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.SecurityUtil; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.security.token.TokenSelector; import org.cloudera.htrace.Span; import org.cloudera.htrace.Trace; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.BlockingRpcChannel; import com.google.protobuf.Descriptors.MethodDescriptor; import com.google.protobuf.Message; import com.google.protobuf.Message.Builder; import com.google.protobuf.RpcController; import com.google.protobuf.ServiceException; import com.google.protobuf.TextFormat; /** * Does RPC against a cluster. Manages connections per regionserver in the cluster. * <p>See HBaseServer */ @InterfaceAudience.Private public class RpcClient { // The LOG key is intentionally not from this package to avoid ipc logging at DEBUG (all under // o.a.h.hbase is set to DEBUG as default). public static final Log LOG = LogFactory.getLog("org.apache.hadoop.ipc.RpcClient"); protected final PoolMap<ConnectionId, Connection> connections; protected int counter; // counter for call ids protected final AtomicBoolean running = new AtomicBoolean(true); // if client runs final protected Configuration conf; final protected int maxIdleTime; // connections will be culled if it was idle for // maxIdleTime microsecs final protected int maxRetries; //the max. no. of retries for socket connections final protected long failureSleep; // Time to sleep before retry on failure. protected final boolean tcpNoDelay; // if T then disable Nagle's Algorithm protected final boolean tcpKeepAlive; // if T then use keepalives protected int pingInterval; // how often sends ping to the server in msecs protected FailedServers failedServers; private final Codec codec; private final CompressionCodec compressor; private final IPCUtil ipcUtil; protected final SocketFactory socketFactory; // how to create sockets protected String clusterId; protected final SocketAddress localAddr; private final boolean fallbackAllowed; private UserProvider userProvider; final private static String PING_INTERVAL_NAME = "ipc.ping.interval"; final private static String SOCKET_TIMEOUT = "ipc.socket.timeout"; final static int DEFAULT_PING_INTERVAL = 60000; // 1 min final static int DEFAULT_SOCKET_TIMEOUT = 20000; // 20 seconds final static int PING_CALL_ID = -1; public final static String FAILED_SERVER_EXPIRY_KEY = "hbase.ipc.client.failed.servers.expiry"; public final static int FAILED_SERVER_EXPIRY_DEFAULT = 2000; public static final String IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_KEY = "hbase.ipc.client.fallback-to-simple-auth-allowed"; public static final boolean IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_DEFAULT = false; // thread-specific RPC timeout, which may override that of what was passed in. // This is used to change dynamically the timeout (for read only) when retrying: if // the time allowed for the operation is less than the usual socket timeout, then // we lower the timeout. This is subject to race conditions, and should be used with // extreme caution. private static ThreadLocal<Integer> rpcTimeout = new ThreadLocal<Integer>() { @Override protected Integer initialValue() { return HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT; } }; /** * A class to manage a list of servers that failed recently. */ static class FailedServers { private final LinkedList<Pair<Long, String>> failedServers = new LinkedList<Pair<Long, java.lang.String>>(); private final int recheckServersTimeout; FailedServers(Configuration conf) { this.recheckServersTimeout = conf.getInt( FAILED_SERVER_EXPIRY_KEY, FAILED_SERVER_EXPIRY_DEFAULT); } /** * Add an address to the list of the failed servers list. */ public synchronized void addToFailedServers(InetSocketAddress address) { final long expiry = EnvironmentEdgeManager.currentTimeMillis() + recheckServersTimeout; failedServers.addFirst(new Pair<Long, String>(expiry, address.toString())); } /** * Check if the server should be considered as bad. Clean the old entries of the list. * * @return true if the server is in the failed servers list */ public synchronized boolean isFailedServer(final InetSocketAddress address) { if (failedServers.isEmpty()) { return false; } final String lookup = address.toString(); final long now = EnvironmentEdgeManager.currentTimeMillis(); // iterate, looking for the search entry and cleaning expired entries Iterator<Pair<Long, String>> it = failedServers.iterator(); while (it.hasNext()) { Pair<Long, String> cur = it.next(); if (cur.getFirst() < now) { it.remove(); } else { if (lookup.equals(cur.getSecond())) { return true; } } } return false; } } @SuppressWarnings("serial") @InterfaceAudience.Public @InterfaceStability.Evolving // Shouldn't this be a DoNotRetryException? St.Ack 10/2/2013 public static class FailedServerException extends HBaseIOException { public FailedServerException(String s) { super(s); } } /** * set the ping interval value in configuration * * @param conf Configuration * @param pingInterval the ping interval */ // Any reason we couldn't just do tcp keepalive instead of this pingery? // St.Ack 20130121 public static void setPingInterval(Configuration conf, int pingInterval) { conf.setInt(PING_INTERVAL_NAME, pingInterval); } /** * Get the ping interval from configuration; * If not set in the configuration, return the default value. * * @param conf Configuration * @return the ping interval */ static int getPingInterval(Configuration conf) { return conf.getInt(PING_INTERVAL_NAME, DEFAULT_PING_INTERVAL); } /** * Set the socket timeout * @param conf Configuration * @param socketTimeout the socket timeout */ public static void setSocketTimeout(Configuration conf, int socketTimeout) { conf.setInt(SOCKET_TIMEOUT, socketTimeout); } /** * @return the socket timeout */ static int getSocketTimeout(Configuration conf) { return conf.getInt(SOCKET_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); } /** A call waiting for a value. */ protected class Call { final int id; // call id final Message param; // rpc request method param object /** * Optionally has cells when making call. Optionally has cells set on response. Used * passing cells to the rpc and receiving the response. */ CellScanner cells; Message response; // value, null if error // The return type. Used to create shell into which we deserialize the response if any. Message responseDefaultType; IOException error; // exception, null if value boolean done; // true when call is done long startTime; final MethodDescriptor md; protected Call(final MethodDescriptor md, Message param, final CellScanner cells, final Message responseDefaultType) { this.param = param; this.md = md; this.cells = cells; this.startTime = System.currentTimeMillis(); this.responseDefaultType = responseDefaultType; synchronized (RpcClient.this) { this.id = counter++; } } @Override public String toString() { return "callId: " + this.id + " methodName: " + this.md.getName() + " param {" + (this.param != null? ProtobufUtil.getShortTextFormat(this.param): "") + "}"; } /** Indicate when the call is complete and the * value or error are available. Notifies by default. */ protected synchronized void callComplete() { this.done = true; notify(); // notify caller } /** Set the exception when there is an error. * Notify the caller the call is done. * * @param error exception thrown by the call; either local or remote */ public void setException(IOException error) { this.error = error; callComplete(); } /** * Set the return value when there is no error. * Notify the caller the call is done. * * @param response return value of the call. * @param cells Can be null */ public void setResponse(Message response, final CellScanner cells) { this.response = response; this.cells = cells; callComplete(); } public long getStartTime() { return this.startTime; } } protected final static Map<AuthenticationProtos.TokenIdentifier.Kind, TokenSelector<? extends TokenIdentifier>> tokenHandlers = new HashMap<AuthenticationProtos.TokenIdentifier.Kind, TokenSelector<? extends TokenIdentifier>>(); static { tokenHandlers.put(AuthenticationProtos.TokenIdentifier.Kind.HBASE_AUTH_TOKEN, new AuthenticationTokenSelector()); } /** * Creates a connection. Can be overridden by a subclass for testing. * @param remoteId - the ConnectionId to use for the connection creation. */ protected Connection createConnection(ConnectionId remoteId, final Codec codec, final CompressionCodec compressor) throws IOException { return new Connection(remoteId, codec, compressor); } /** Thread that reads responses and notifies callers. Each connection owns a * socket connected to a remote address. Calls are multiplexed through this * socket: responses may be delivered out of order. */ protected class Connection extends Thread { private ConnectionHeader header; // connection header protected ConnectionId remoteId; protected Socket socket = null; // connected socket protected DataInputStream in; protected DataOutputStream out; private InetSocketAddress server; // server ip:port private String serverPrincipal; // server's krb5 principal name private AuthMethod authMethod; // authentication method private boolean useSasl; private Token<? extends TokenIdentifier> token; private HBaseSaslRpcClient saslRpcClient; private int reloginMaxBackoff; // max pause before relogin on sasl failure private final Codec codec; private final CompressionCodec compressor; // currently active calls protected final ConcurrentSkipListMap<Integer, Call> calls = new ConcurrentSkipListMap<Integer, Call>(); protected final AtomicLong lastActivity = new AtomicLong(); // last I/O activity time protected final AtomicBoolean shouldCloseConnection = new AtomicBoolean(); // indicate if the connection is closed protected IOException closeException; // close reason Connection(ConnectionId remoteId, final Codec codec, final CompressionCodec compressor) throws IOException { if (remoteId.getAddress().isUnresolved()) { throw new UnknownHostException("unknown host: " + remoteId.getAddress().getHostName()); } this.server = remoteId.getAddress(); this.codec = codec; this.compressor = compressor; UserGroupInformation ticket = remoteId.getTicket().getUGI(); SecurityInfo securityInfo = SecurityInfo.getInfo(remoteId.getServiceName()); this.useSasl = userProvider.isHBaseSecurityEnabled(); if (useSasl && securityInfo != null) { AuthenticationProtos.TokenIdentifier.Kind tokenKind = securityInfo.getTokenKind(); if (tokenKind != null) { TokenSelector<? extends TokenIdentifier> tokenSelector = tokenHandlers.get(tokenKind); if (tokenSelector != null) { token = tokenSelector.selectToken(new Text(clusterId), ticket.getTokens()); } else if (LOG.isDebugEnabled()) { LOG.debug("No token selector found for type "+tokenKind); } } String serverKey = securityInfo.getServerPrincipal(); if (serverKey == null) { throw new IOException( "Can't obtain server Kerberos config key from SecurityInfo"); } serverPrincipal = SecurityUtil.getServerPrincipal( conf.get(serverKey), server.getAddress().getCanonicalHostName().toLowerCase()); if (LOG.isDebugEnabled()) { LOG.debug("RPC Server Kerberos principal name for service=" + remoteId.getServiceName() + " is " + serverPrincipal); } } if (!useSasl) { authMethod = AuthMethod.SIMPLE; } else if (token != null) { authMethod = AuthMethod.DIGEST; } else { authMethod = AuthMethod.KERBEROS; } if (LOG.isDebugEnabled()) { LOG.debug("Use " + authMethod + " authentication for service " + remoteId.serviceName + ", sasl=" + useSasl); } reloginMaxBackoff = conf.getInt("hbase.security.relogin.maxbackoff", 5000); this.remoteId = remoteId; ConnectionHeader.Builder builder = ConnectionHeader.newBuilder(); builder.setServiceName(remoteId.getServiceName()); UserInformation userInfoPB; if ((userInfoPB = getUserInfo(ticket)) != null) { builder.setUserInfo(userInfoPB); } if (this.codec != null) { builder.setCellBlockCodecClass(this.codec.getClass().getCanonicalName()); } if (this.compressor != null) { builder.setCellBlockCompressorClass(this.compressor.getClass().getCanonicalName()); } this.header = builder.build(); this.setName("IPC Client (" + socketFactory.hashCode() +") connection to " + remoteId.getAddress().toString() + ((ticket==null)?" from an unknown user": (" from " + ticket.getUserName()))); this.setDaemon(true); } private UserInformation getUserInfo(UserGroupInformation ugi) { if (ugi == null || authMethod == AuthMethod.DIGEST) { // Don't send user for token auth return null; } UserInformation.Builder userInfoPB = UserInformation.newBuilder(); if (authMethod == AuthMethod.KERBEROS) { // Send effective user for Kerberos auth userInfoPB.setEffectiveUser(ugi.getUserName()); } else if (authMethod == AuthMethod.SIMPLE) { //Send both effective user and real user for simple auth userInfoPB.setEffectiveUser(ugi.getUserName()); if (ugi.getRealUser() != null) { userInfoPB.setRealUser(ugi.getRealUser().getUserName()); } } return userInfoPB.build(); } /** Update lastActivity with the current time. */ protected void touch() { lastActivity.set(System.currentTimeMillis()); } /** * Add a call to this connection's call queue and notify * a listener; synchronized. If the connection is dead, the call is not added, and the * caller is notified. * This function can return a connection that is already marked as 'shouldCloseConnection' * It is up to the user code to check this status. * @param call to add */ @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="NN_NAKED_NOTIFY", justification="Notify because new call available for processing") protected synchronized void addCall(Call call) { // If the connection is about to close, we manage this as if the call was already added // to the connection calls list. If not, the connection creations are serialized, as // mentioned in HBASE-6364 if (this.shouldCloseConnection.get()) { if (this.closeException == null) { call.setException(new IOException( "Call " + call.id + " not added as the connection " + remoteId + " is closing")); } else { call.setException(this.closeException); } synchronized (call) { call.notifyAll(); } } else { calls.put(call.id, call); synchronized (call) { notify(); } } } /** This class sends a ping to the remote side when timeout on * reading. If no failure is detected, it retries until at least * a byte is read. */ protected class PingInputStream extends FilterInputStream { /* constructor */ protected PingInputStream(InputStream in) { super(in); } /* Process timeout exception * if the connection is not going to be closed, send a ping. * otherwise, throw the timeout exception. */ private void handleTimeout(SocketTimeoutException e) throws IOException { if (shouldCloseConnection.get() || !running.get() || remoteId.rpcTimeout > 0) { throw e; } sendPing(); } /** Read a byte from the stream. * Send a ping if timeout on read. Retries if no failure is detected * until a byte is read. * @throws IOException for any IO problem other than socket timeout */ @Override public int read() throws IOException { do { try { return super.read(); } catch (SocketTimeoutException e) { handleTimeout(e); } } while (true); } /** Read bytes into a buffer starting from offset <code>off</code> * Send a ping if timeout on read. Retries if no failure is detected * until a byte is read. * * @return the total number of bytes read; -1 if the connection is closed. */ @Override public int read(byte[] buf, int off, int len) throws IOException { do { try { return super.read(buf, off, len); } catch (SocketTimeoutException e) { handleTimeout(e); } } while (true); } } protected synchronized void setupConnection() throws IOException { short ioFailures = 0; short timeoutFailures = 0; while (true) { try { this.socket = socketFactory.createSocket(); this.socket.setTcpNoDelay(tcpNoDelay); this.socket.setKeepAlive(tcpKeepAlive); if (localAddr != null) { this.socket.bind(localAddr); } // connection time out is 20s NetUtils.connect(this.socket, remoteId.getAddress(), getSocketTimeout(conf)); if (remoteId.rpcTimeout > 0) { pingInterval = remoteId.rpcTimeout; // overwrite pingInterval } this.socket.setSoTimeout(pingInterval); return; } catch (SocketTimeoutException toe) { /* The max number of retries is 45, * which amounts to 20s*45 = 15 minutes retries. */ handleConnectionFailure(timeoutFailures++, maxRetries, toe); } catch (IOException ie) { handleConnectionFailure(ioFailures++, maxRetries, ie); } } } protected void closeConnection() { if (socket == null) { return; } // close the current connection try { if (socket.getOutputStream() != null) { socket.getOutputStream().close(); } } catch (IOException ignored) { // Can happen if the socket is already closed } try { if (socket.getInputStream() != null) { socket.getInputStream().close(); } } catch (IOException ignored) { // Can happen if the socket is already closed } try { if (socket.getChannel() != null) { socket.getChannel().close(); } } catch (IOException ignored) { // Can happen if the socket is already closed } try { socket.close(); } catch (IOException e) { LOG.warn("Not able to close a socket", e); } // set socket to null so that the next call to setupIOstreams // can start the process of connect all over again. socket = null; } /** * Handle connection failures * * If the current number of retries is equal to the max number of retries, * stop retrying and throw the exception; Otherwise backoff N seconds and * try connecting again. * * This Method is only called from inside setupIOstreams(), which is * synchronized. Hence the sleep is synchronized; the locks will be retained. * * @param curRetries current number of retries * @param maxRetries max number of retries allowed * @param ioe failure reason * @throws IOException if max number of retries is reached */ private void handleConnectionFailure(int curRetries, int maxRetries, IOException ioe) throws IOException { closeConnection(); // throw the exception if the maximum number of retries is reached if (curRetries >= maxRetries || ExceptionUtil.isInterrupt(ioe)) { throw ioe; } // otherwise back off and retry try { Thread.sleep(failureSleep); } catch (InterruptedException ie) { ExceptionUtil.rethrowIfInterrupt(ie); } LOG.info("Retrying connect to server: " + remoteId.getAddress() + " after sleeping " + failureSleep + "ms. Already tried " + curRetries + " time(s)."); } /* wait till someone signals us to start reading RPC response or * it is idle too long, it is marked as to be closed, * or the client is marked as not running. * * Return true if it is time to read a response; false otherwise. */ protected synchronized boolean waitForWork() { if (calls.isEmpty() && !shouldCloseConnection.get() && running.get()) { long timeout = maxIdleTime - (System.currentTimeMillis()-lastActivity.get()); if (timeout>0) { try { wait(timeout); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } } if (!calls.isEmpty() && !shouldCloseConnection.get() && running.get()) { return true; } else if (shouldCloseConnection.get()) { return false; } else if (calls.isEmpty()) { // idle connection closed or stopped markClosed(null); return false; } else { // get stopped but there are still pending requests markClosed((IOException)new IOException().initCause( new InterruptedException())); return false; } } public InetSocketAddress getRemoteAddress() { return remoteId.getAddress(); } /* Send a ping to the server if the time elapsed * since last I/O activity is equal to or greater than the ping interval */ protected synchronized void sendPing() throws IOException { // Can we do tcp keepalive instead of this pinging? long curTime = System.currentTimeMillis(); if ( curTime - lastActivity.get() >= pingInterval) { lastActivity.set(curTime); //noinspection SynchronizeOnNonFinalField synchronized (this.out) { out.writeInt(PING_CALL_ID); out.flush(); } } } @Override public void run() { if (LOG.isDebugEnabled()) { LOG.debug(getName() + ": starting, connections " + connections.size()); } try { while (waitForWork()) { // Wait here for work - read or close connection readResponse(); } } catch (Throwable t) { LOG.warn(getName() + ": unexpected exception receiving call responses", t); markClosed(new IOException("Unexpected exception receiving call responses", t)); } close(); if (LOG.isDebugEnabled()) LOG.debug(getName() + ": stopped, connections " + connections.size()); } private synchronized void disposeSasl() { if (saslRpcClient != null) { try { saslRpcClient.dispose(); saslRpcClient = null; } catch (IOException ioe) { LOG.error("Error disposing of SASL client", ioe); } } } private synchronized boolean shouldAuthenticateOverKrb() throws IOException { UserGroupInformation loginUser = UserGroupInformation.getLoginUser(); UserGroupInformation currentUser = UserGroupInformation.getCurrentUser(); UserGroupInformation realUser = currentUser.getRealUser(); return authMethod == AuthMethod.KERBEROS && loginUser != null && //Make sure user logged in using Kerberos either keytab or TGT loginUser.hasKerberosCredentials() && // relogin only in case it is the login user (e.g. JT) // or superuser (like oozie). (loginUser.equals(currentUser) || loginUser.equals(realUser)); } private synchronized boolean setupSaslConnection(final InputStream in2, final OutputStream out2) throws IOException { saslRpcClient = new HBaseSaslRpcClient(authMethod, token, serverPrincipal, fallbackAllowed); return saslRpcClient.saslConnect(in2, out2); } /** * If multiple clients with the same principal try to connect * to the same server at the same time, the server assumes a * replay attack is in progress. This is a feature of kerberos. * In order to work around this, what is done is that the client * backs off randomly and tries to initiate the connection * again. * The other problem is to do with ticket expiry. To handle that, * a relogin is attempted. * <p> * The retry logic is governed by the {@link #shouldAuthenticateOverKrb} * method. In case when the user doesn't have valid credentials, we don't * need to retry (from cache or ticket). In such cases, it is prudent to * throw a runtime exception when we receive a SaslException from the * underlying authentication implementation, so there is no retry from * other high level (for eg, HCM or HBaseAdmin). * </p> */ private synchronized void handleSaslConnectionFailure( final int currRetries, final int maxRetries, final Exception ex, final Random rand, final UserGroupInformation user) throws IOException, InterruptedException{ user.doAs(new PrivilegedExceptionAction<Object>() { public Object run() throws IOException, InterruptedException { closeConnection(); if (shouldAuthenticateOverKrb()) { if (currRetries < maxRetries) { LOG.debug("Exception encountered while connecting to " + "the server : " + ex); //try re-login if (UserGroupInformation.isLoginKeytabBased()) { UserGroupInformation.getLoginUser().reloginFromKeytab(); } else { UserGroupInformation.getLoginUser().reloginFromTicketCache(); } disposeSasl(); //have granularity of milliseconds //we are sleeping with the Connection lock held but since this //connection instance is being used for connecting to the server //in question, it is okay Thread.sleep((rand.nextInt(reloginMaxBackoff) + 1)); return null; } else { String msg = "Couldn't setup connection for " + UserGroupInformation.getLoginUser().getUserName() + " to " + serverPrincipal; LOG.warn(msg); throw (IOException) new IOException(msg).initCause(ex); } } else { LOG.warn("Exception encountered while connecting to " + "the server : " + ex); } if (ex instanceof RemoteException) { throw (RemoteException)ex; } if (ex instanceof SaslException) { String msg = "SASL authentication failed." + " The most likely cause is missing or invalid credentials." + " Consider 'kinit'."; LOG.fatal(msg, ex); throw new RuntimeException(msg, ex); } throw new IOException(ex); } }); } protected synchronized void setupIOstreams() throws IOException, InterruptedException { if (socket != null || shouldCloseConnection.get()) { return; } if (failedServers.isFailedServer(remoteId.getAddress())) { if (LOG.isDebugEnabled()) { LOG.debug("Not trying to connect to " + server + " this server is in the failed servers list"); } IOException e = new FailedServerException( "This server is in the failed servers list: " + server); markClosed(e); close(); throw e; } try { if (LOG.isDebugEnabled()) { LOG.debug("Connecting to " + server); } short numRetries = 0; final short MAX_RETRIES = 5; Random rand = null; while (true) { setupConnection(); InputStream inStream = NetUtils.getInputStream(socket); // This creates a socket with a write timeout. This timeout cannot be changed, // RpcClient allows to change the timeout dynamically, but we can only // change the read timeout today. OutputStream outStream = NetUtils.getOutputStream(socket, pingInterval); // Write out the preamble -- MAGIC, version, and auth to use. writeConnectionHeaderPreamble(outStream); if (useSasl) { final InputStream in2 = inStream; final OutputStream out2 = outStream; UserGroupInformation ticket = remoteId.getTicket().getUGI(); if (authMethod == AuthMethod.KERBEROS) { if (ticket != null && ticket.getRealUser() != null) { ticket = ticket.getRealUser(); } } boolean continueSasl = false; if (ticket == null) throw new FatalConnectionException("ticket/user is null"); try { continueSasl = ticket.doAs(new PrivilegedExceptionAction<Boolean>() { @Override public Boolean run() throws IOException { return setupSaslConnection(in2, out2); } }); } catch (Exception ex) { if (rand == null) { rand = new Random(); } handleSaslConnectionFailure(numRetries++, MAX_RETRIES, ex, rand, ticket); continue; } if (continueSasl) { // Sasl connect is successful. Let's set up Sasl i/o streams. inStream = saslRpcClient.getInputStream(inStream); outStream = saslRpcClient.getOutputStream(outStream); } else { // fall back to simple auth because server told us so. authMethod = AuthMethod.SIMPLE; useSasl = false; } } this.in = new DataInputStream(new BufferedInputStream(new PingInputStream(inStream))); this.out = new DataOutputStream(new BufferedOutputStream(outStream)); // Now write out the connection header writeConnectionHeader(); // update last activity time touch(); // start the receiver thread after the socket connection has been set up start(); return; } } catch (Throwable t) { failedServers.addToFailedServers(remoteId.address); IOException e = null; if (t instanceof IOException) { e = (IOException)t; markClosed(e); } else { e = new IOException("Could not set up IO Streams", t); markClosed(e); } close(); throw e; } } /** * Write the RPC header: <MAGIC WORD -- 'HBas'> <ONEBYTE_VERSION> <ONEBYTE_AUTH_TYPE> */ private void writeConnectionHeaderPreamble(OutputStream outStream) throws IOException { // Assemble the preamble up in a buffer first and then send it. Writing individual elements, // they are getting sent across piecemeal according to wireshark and then server is messing // up the reading on occasion (the passed in stream is not buffered yet). // Preamble is six bytes -- 'HBas' + VERSION + AUTH_CODE int rpcHeaderLen = HConstants.RPC_HEADER.array().length; byte [] preamble = new byte [rpcHeaderLen + 2]; System.arraycopy(HConstants.RPC_HEADER.array(), 0, preamble, 0, rpcHeaderLen); preamble[rpcHeaderLen] = HConstants.RPC_CURRENT_VERSION; preamble[rpcHeaderLen + 1] = authMethod.code; outStream.write(preamble); outStream.flush(); } /** * Write the connection header. * Out is not synchronized because only the first thread does this. */ private void writeConnectionHeader() throws IOException { synchronized (this.out) { this.out.writeInt(this.header.getSerializedSize()); this.header.writeTo(this.out); this.out.flush(); } } /** Close the connection. */ protected synchronized void close() { if (!shouldCloseConnection.get()) { LOG.error(getName() + ": the connection is not in the closed state"); return; } // release the resources // first thing to do;take the connection out of the connection list synchronized (connections) { connections.removeValue(remoteId, this); } // close the streams and therefore the socket if (this.out != null) { synchronized(this.out) { IOUtils.closeStream(out); this.out = null; } } IOUtils.closeStream(in); this.in = null; disposeSasl(); // clean up all calls if (closeException == null) { if (!calls.isEmpty()) { LOG.warn(getName() + ": connection is closed for no cause and calls are not empty. " + "#Calls: " + calls.size()); // clean up calls anyway closeException = new IOException("Unexpected closed connection"); cleanupCalls(); } } else { // log the info if (LOG.isDebugEnabled()) { LOG.debug(getName() + ": closing ipc connection to " + server + ": " + closeException.getMessage(), closeException); } // cleanup calls cleanupCalls(); } if (LOG.isDebugEnabled()) LOG.debug(getName() + ": closed"); } /** * Initiates a call by sending the parameter to the remote server. * Note: this is not called from the Connection thread, but by other * threads. * @param call * @param priority * @see #readResponse() */ protected void writeRequest(Call call, final int priority) { if (shouldCloseConnection.get()) return; try { RequestHeader.Builder builder = RequestHeader.newBuilder(); builder.setCallId(call.id); if (Trace.isTracing()) { Span s = Trace.currentSpan(); builder.setTraceInfo(RPCTInfo.newBuilder(). setParentId(s.getSpanId()).setTraceId(s.getTraceId())); } builder.setMethodName(call.md.getName()); builder.setRequestParam(call.param != null); ByteBuffer cellBlock = ipcUtil.buildCellBlock(this.codec, this.compressor, call.cells); if (cellBlock != null) { CellBlockMeta.Builder cellBlockBuilder = CellBlockMeta.newBuilder(); cellBlockBuilder.setLength(cellBlock.limit()); builder.setCellBlockMeta(cellBlockBuilder.build()); } // Only pass priority if there one. Let zero be same as no priority. if (priority != 0) builder.setPriority(priority); //noinspection SynchronizeOnNonFinalField RequestHeader header = builder.build(); synchronized (this.out) { // FindBugs IS2_INCONSISTENT_SYNC IPCUtil.write(this.out, header, call.param, cellBlock); } if (LOG.isDebugEnabled()) { LOG.debug(getName() + ": wrote request header " + TextFormat.shortDebugString(header)); } } catch(IOException e) { markClosed(e); } } /* Receive a response. * Because only one receiver, so no synchronization on in. */ protected void readResponse() { if (shouldCloseConnection.get()) return; touch(); int totalSize = -1; try { // See HBaseServer.Call.setResponse for where we write out the response. // Total size of the response. Unused. But have to read it in anyways. totalSize = in.readInt(); // Read the header ResponseHeader responseHeader = ResponseHeader.parseDelimitedFrom(in); int id = responseHeader.getCallId(); if (LOG.isDebugEnabled()) { LOG.debug(getName() + ": got response header " + TextFormat.shortDebugString(responseHeader) + ", totalSize: " + totalSize + " bytes"); } Call call = calls.get(id); if (call == null) { // So we got a response for which we have no corresponding 'call' here on the client-side. // We probably timed out waiting, cleaned up all references, and now the server decides // to return a response. There is nothing we can do w/ the response at this stage. Clean // out the wire of the response so its out of the way and we can get other responses on // this connection. int readSoFar = IPCUtil.getTotalSizeWhenWrittenDelimited(responseHeader); int whatIsLeftToRead = totalSize - readSoFar; LOG.debug("Unknown callId: " + id + ", skipping over this response of " + whatIsLeftToRead + " bytes"); IOUtils.skipFully(in, whatIsLeftToRead); } if (responseHeader.hasException()) { ExceptionResponse exceptionResponse = responseHeader.getException(); RemoteException re = createRemoteException(exceptionResponse); if (isFatalConnectionException(exceptionResponse)) { markClosed(re); } else { if (call != null) call.setException(re); } } else { Message value = null; // Call may be null because it may have timedout and been cleaned up on this side already if (call != null && call.responseDefaultType != null) { Builder builder = call.responseDefaultType.newBuilderForType(); builder.mergeDelimitedFrom(in); value = builder.build(); } CellScanner cellBlockScanner = null; if (responseHeader.hasCellBlockMeta()) { int size = responseHeader.getCellBlockMeta().getLength(); byte [] cellBlock = new byte[size]; IOUtils.readFully(this.in, cellBlock, 0, cellBlock.length); cellBlockScanner = ipcUtil.createCellScanner(this.codec, this.compressor, cellBlock); } // it's possible that this call may have been cleaned up due to a RPC // timeout, so check if it still exists before setting the value. if (call != null) call.setResponse(value, cellBlockScanner); } if (call != null) calls.remove(id); } catch (IOException e) { if (e instanceof SocketTimeoutException && remoteId.rpcTimeout > 0) { // Clean up open calls but don't treat this as a fatal condition, // since we expect certain responses to not make it by the specified // {@link ConnectionId#rpcTimeout}. closeException = e; } else { // Treat this as a fatal condition and close this connection markClosed(e); } } finally { if (remoteId.rpcTimeout > 0) { cleanupCalls(remoteId.rpcTimeout); } } } /** * @param e * @return True if the exception is a fatal connection exception. */ private boolean isFatalConnectionException(final ExceptionResponse e) { return e.getExceptionClassName(). equals(FatalConnectionException.class.getName()); } /** * @param e * @return RemoteException made from passed <code>e</code> */ private RemoteException createRemoteException(final ExceptionResponse e) { String innerExceptionClassName = e.getExceptionClassName(); boolean doNotRetry = e.getDoNotRetry(); return e.hasHostname()? // If a hostname then add it to the RemoteWithExtrasException new RemoteWithExtrasException(innerExceptionClassName, e.getStackTrace(), e.getHostname(), e.getPort(), doNotRetry): new RemoteWithExtrasException(innerExceptionClassName, e.getStackTrace(), doNotRetry); } protected synchronized void markClosed(IOException e) { if (shouldCloseConnection.compareAndSet(false, true)) { closeException = e; notifyAll(); } } /* Cleanup all calls and mark them as done */ protected void cleanupCalls() { cleanupCalls(0); } @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="NN_NAKED_NOTIFY", justification="Notify because timedout") protected void cleanupCalls(long rpcTimeout) { Iterator<Entry<Integer, Call>> itor = calls.entrySet().iterator(); while (itor.hasNext()) { Call c = itor.next().getValue(); long waitTime = System.currentTimeMillis() - c.getStartTime(); if (waitTime >= rpcTimeout) { if (this.closeException == null) { // There may be no exception in the case that there are many calls // being multiplexed over this connection and these are succeeding // fine while this Call object is taking a long time to finish // over on the server; e.g. I just asked the regionserver to bulk // open 3k regions or its a big fat multiput into a heavily-loaded // server (Perhaps this only happens at the extremes?) this.closeException = new CallTimeoutException("Call id=" + c.id + ", waitTime=" + waitTime + ", rpcTimetout=" + rpcTimeout); } c.setException(this.closeException); synchronized (c) { c.notifyAll(); } itor.remove(); } else { break; } } try { if (!calls.isEmpty()) { Call firstCall = calls.get(calls.firstKey()); long maxWaitTime = System.currentTimeMillis() - firstCall.getStartTime(); if (maxWaitTime < rpcTimeout) { rpcTimeout -= maxWaitTime; } } if (!shouldCloseConnection.get()) { closeException = null; setSocketTimeout(socket, (int) rpcTimeout); } } catch (SocketException e) { LOG.debug("Couldn't lower timeout, which may result in longer than expected calls"); } } } @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="IS2_INCONSISTENT_SYNC", justification="Presume sync not needed setting socket timeout") private static void setSocketTimeout(final Socket socket, final int rpcTimeout) throws java.net.SocketException { if (socket == null) return; socket.setSoTimeout(rpcTimeout); } /** * Client-side call timeout */ @SuppressWarnings("serial") @InterfaceAudience.Public @InterfaceStability.Evolving public static class CallTimeoutException extends IOException { public CallTimeoutException(final String msg) { super(msg); } } /** * Construct an IPC cluster client whose values are of the {@link Message} class. * @param conf configuration * @param clusterId * @param factory socket factory */ RpcClient(Configuration conf, String clusterId, SocketFactory factory) { this(conf, clusterId, factory, null); } /** * Construct an IPC cluster client whose values are of the {@link Message} class. * @param conf configuration * @param clusterId * @param factory socket factory * @param localAddr client socket bind address */ RpcClient(Configuration conf, String clusterId, SocketFactory factory, SocketAddress localAddr) { this.maxIdleTime = conf.getInt("hbase.ipc.client.connection.maxidletime", 10000); //10s this.maxRetries = conf.getInt("hbase.ipc.client.connect.max.retries", 0); this.failureSleep = conf.getLong(HConstants.HBASE_CLIENT_PAUSE, HConstants.DEFAULT_HBASE_CLIENT_PAUSE); this.tcpNoDelay = conf.getBoolean("hbase.ipc.client.tcpnodelay", true); this.tcpKeepAlive = conf.getBoolean("hbase.ipc.client.tcpkeepalive", true); this.pingInterval = getPingInterval(conf); this.ipcUtil = new IPCUtil(conf); this.conf = conf; this.codec = getCodec(); this.compressor = getCompressor(conf); this.socketFactory = factory; this.clusterId = clusterId != null ? clusterId : HConstants.CLUSTER_ID_DEFAULT; this.connections = new PoolMap<ConnectionId, Connection>(getPoolType(conf), getPoolSize(conf)); this.failedServers = new FailedServers(conf); this.fallbackAllowed = conf.getBoolean(IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_KEY, IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_DEFAULT); this.localAddr = localAddr; this.userProvider = UserProvider.instantiate(conf); // login the server principal (if using secure Hadoop) if (LOG.isDebugEnabled()) { LOG.debug("Codec=" + this.codec + ", compressor=" + this.compressor + ", tcpKeepAlive=" + this.tcpKeepAlive + ", tcpNoDelay=" + this.tcpNoDelay + ", maxIdleTime=" + this.maxIdleTime + ", maxRetries=" + this.maxRetries + ", fallbackAllowed=" + this.fallbackAllowed + ", ping interval=" + this.pingInterval + "ms" + ", bind address=" + (this.localAddr != null ? this.localAddr : "null")); } } /** * Construct an IPC client for the cluster <code>clusterId</code> with the default SocketFactory * @param conf configuration * @param clusterId */ public RpcClient(Configuration conf, String clusterId) { this(conf, clusterId, NetUtils.getDefaultSocketFactory(conf), null); } /** * Construct an IPC client for the cluster <code>clusterId</code> with the default SocketFactory * @param conf configuration * @param clusterId * @param localAddr client socket bind address. */ public RpcClient(Configuration conf, String clusterId, SocketAddress localAddr) { this(conf, clusterId, NetUtils.getDefaultSocketFactory(conf), localAddr); } /** * Encapsulate the ugly casting and RuntimeException conversion in private method. * @return Codec to use on this client. */ Codec getCodec() { // For NO CODEC, "hbase.client.rpc.codec" must be configured with empty string AND // "hbase.client.default.rpc.codec" also -- because default is to do cell block encoding. String className = conf.get(HConstants.RPC_CODEC_CONF_KEY, getDefaultCodec(this.conf)); if (className == null || className.length() == 0) return null; try { return (Codec)Class.forName(className).newInstance(); } catch (Exception e) { throw new RuntimeException("Failed getting codec " + className, e); } } @VisibleForTesting public static String getDefaultCodec(final Configuration c) { // If "hbase.client.default.rpc.codec" is empty string -- you can't set it to null because // Configuration will complain -- then no default codec (and we'll pb everything). Else // default is KeyValueCodec return c.get("hbase.client.default.rpc.codec", KeyValueCodec.class.getCanonicalName()); } /** * Encapsulate the ugly casting and RuntimeException conversion in private method. * @param conf * @return The compressor to use on this client. */ private static CompressionCodec getCompressor(final Configuration conf) { String className = conf.get("hbase.client.rpc.compressor", null); if (className == null || className.isEmpty()) return null; try { return (CompressionCodec)Class.forName(className).newInstance(); } catch (Exception e) { throw new RuntimeException("Failed getting compressor " + className, e); } } /** * Return the pool type specified in the configuration, which must be set to * either {@link PoolType#RoundRobin} or {@link PoolType#ThreadLocal}, * otherwise default to the former. * * For applications with many user threads, use a small round-robin pool. For * applications with few user threads, you may want to try using a * thread-local pool. In any case, the number of {@link RpcClient} instances * should not exceed the operating system's hard limit on the number of * connections. * * @param config configuration * @return either a {@link PoolType#RoundRobin} or * {@link PoolType#ThreadLocal} */ protected static PoolType getPoolType(Configuration config) { return PoolType.valueOf(config.get(HConstants.HBASE_CLIENT_IPC_POOL_TYPE), PoolType.RoundRobin, PoolType.ThreadLocal); } /** * Return the pool size specified in the configuration, which is applicable only if * the pool type is {@link PoolType#RoundRobin}. * * @param config * @return the maximum pool size */ protected static int getPoolSize(Configuration config) { return config.getInt(HConstants.HBASE_CLIENT_IPC_POOL_SIZE, 1); } /** Return the socket factory of this client * * @return this client's socket factory */ SocketFactory getSocketFactory() { return socketFactory; } /** Stop all threads related to this client. No further calls may be made * using this client. */ public void stop() { if (LOG.isDebugEnabled()) LOG.debug("Stopping rpc client"); if (!running.compareAndSet(true, false)) return; // wake up all connections synchronized (connections) { for (Connection conn : connections.values()) { conn.interrupt(); } } // wait until all connections are closed while (!connections.isEmpty()) { try { Thread.sleep(100); } catch (InterruptedException ignored) { } } } Pair<Message, CellScanner> call(MethodDescriptor md, Message param, CellScanner cells, Message returnType, User ticket, InetSocketAddress addr, int rpcTimeout) throws InterruptedException, IOException { return call(md, param, cells, returnType, ticket, addr, rpcTimeout, HConstants.NORMAL_QOS); } /** Make a call, passing <code>param</code>, to the IPC server running at * <code>address</code> which is servicing the <code>protocol</code> protocol, * with the <code>ticket</code> credentials, returning the value. * Throws exceptions if there are network problems or if the remote code * threw an exception. * @param md * @param param * @param cells * @param addr * @param returnType * @param ticket Be careful which ticket you pass. A new user will mean a new Connection. * {@link UserProvider#getCurrent()} makes a new instance of User each time so will be a * new Connection each time. * @param rpcTimeout * @return A pair with the Message response and the Cell data (if any). * @throws InterruptedException * @throws IOException */ Pair<Message, CellScanner> call(MethodDescriptor md, Message param, CellScanner cells, Message returnType, User ticket, InetSocketAddress addr, int rpcTimeout, int priority) throws InterruptedException, IOException { Call call = new Call(md, param, cells, returnType); Connection connection = getConnection(ticket, call, addr, rpcTimeout, this.codec, this.compressor); connection.writeRequest(call, priority); // send the parameter //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (call) { while (!call.done) { if (connection.shouldCloseConnection.get()) { throw new IOException("Unexpected closed connection"); } call.wait(1000); // wait for the result } if (call.error != null) { if (call.error instanceof RemoteException) { call.error.fillInStackTrace(); throw call.error; } // local exception throw wrapException(addr, call.error); } return new Pair<Message, CellScanner>(call.response, call.cells); } } /** * Take an IOException and the address we were trying to connect to * and return an IOException with the input exception as the cause. * The new exception provides the stack trace of the place where * the exception is thrown and some extra diagnostics information. * If the exception is ConnectException or SocketTimeoutException, * return a new one of the same type; Otherwise return an IOException. * * @param addr target address * @param exception the relevant exception * @return an exception to throw */ protected IOException wrapException(InetSocketAddress addr, IOException exception) { if (exception instanceof ConnectException) { //connection refused; include the host:port in the error return (ConnectException)new ConnectException( "Call to " + addr + " failed on connection exception: " + exception).initCause(exception); } else if (exception instanceof SocketTimeoutException) { return (SocketTimeoutException)new SocketTimeoutException("Call to " + addr + " failed because " + exception).initCause(exception); } else { return (IOException)new IOException("Call to " + addr + " failed on local exception: " + exception).initCause(exception); } } /** * Interrupt the connections to the given ip:port server. This should be called if the server * is known as actually dead. This will not prevent current operation to be retried, and, * depending on their own behavior, they may retry on the same server. This can be a feature, * for example at startup. In any case, they're likely to get connection refused (if the * process died) or no route to host: i.e. there next retries should be faster and with a * safe exception. */ public void cancelConnections(String hostname, int port, IOException ioe) { synchronized (connections) { for (Connection connection : connections.values()) { if (connection.isAlive() && connection.getRemoteAddress().getPort() == port && connection.getRemoteAddress().getHostName().equals(hostname)) { LOG.info("The server on " + hostname + ":" + port + " is dead - stopping the connection " + connection.remoteId); connection.closeConnection(); // We could do a connection.interrupt(), but it's safer not to do it, as the // interrupted exception behavior is not defined nor enforced enough. } } } } /* Get a connection from the pool, or create a new one and add it to the * pool. Connections to a given host/port are reused. */ protected Connection getConnection(User ticket, Call call, InetSocketAddress addr, int rpcTimeout, final Codec codec, final CompressionCodec compressor) throws IOException, InterruptedException { if (!running.get()) throw new StoppedRpcClientException(); Connection connection; ConnectionId remoteId = new ConnectionId(ticket, call.md.getService().getName(), addr, rpcTimeout); synchronized (connections) { connection = connections.get(remoteId); if (connection == null) { connection = createConnection(remoteId, this.codec, this.compressor); connections.put(remoteId, connection); } } connection.addCall(call); //we don't invoke the method below inside "synchronized (connections)" //block above. The reason for that is if the server happens to be slow, //it will take longer to establish a connection and that will slow the //entire system down. //Moreover, if the connection is currently created, there will be many threads // waiting here; as setupIOstreams is synchronized. If the connection fails with a // timeout, they will all fail simultaneously. This is checked in setupIOstreams. connection.setupIOstreams(); return connection; } /** * This class holds the address and the user ticket, etc. The client connections * to servers are uniquely identified by <remoteAddress, ticket, serviceName, rpcTimeout> */ protected static class ConnectionId { final InetSocketAddress address; final User ticket; final int rpcTimeout; private static final int PRIME = 16777619; final String serviceName; ConnectionId(User ticket, String serviceName, InetSocketAddress address, int rpcTimeout) { this.address = address; this.ticket = ticket; this.rpcTimeout = rpcTimeout; this.serviceName = serviceName; } String getServiceName() { return this.serviceName; } InetSocketAddress getAddress() { return address; } User getTicket() { return ticket; } @Override public String toString() { return this.address.toString() + "/" + this.serviceName + "/" + this.ticket + "/" + this.rpcTimeout; } @Override public boolean equals(Object obj) { if (obj instanceof ConnectionId) { ConnectionId id = (ConnectionId) obj; return address.equals(id.address) && ((ticket != null && ticket.equals(id.ticket)) || (ticket == id.ticket)) && rpcTimeout == id.rpcTimeout && this.serviceName == id.serviceName; } return false; } @Override // simply use the default Object#hashcode() ? public int hashCode() { int hashcode = (address.hashCode() + PRIME * (PRIME * this.serviceName.hashCode() ^ (ticket == null ? 0 : ticket.hashCode()) )) ^ rpcTimeout; return hashcode; } } public static void setRpcTimeout(int t) { rpcTimeout.set(t); } public static int getRpcTimeout() { return rpcTimeout.get(); } /** * Returns the lower of the thread-local RPC time from {@link #setRpcTimeout(int)} and the given * default timeout. */ public static int getRpcTimeout(int defaultTimeout) { return Math.min(defaultTimeout, rpcTimeout.get()); } public static void resetRpcTimeout() { rpcTimeout.remove(); } /** * Make a blocking call. Throws exceptions if there are network problems or if the remote code * threw an exception. * @param md * @param controller * @param param * @param returnType * @param isa * @param ticket Be careful which ticket you pass. A new user will mean a new Connection. * {@link UserProvider#getCurrent()} makes a new instance of User each time so will be a * new Connection each time. * @param rpcTimeout * @return A pair with the Message response and the Cell data (if any). * @throws InterruptedException * @throws IOException */ Message callBlockingMethod(MethodDescriptor md, RpcController controller, Message param, Message returnType, final User ticket, final InetSocketAddress isa, final int rpcTimeout) throws ServiceException { long startTime = 0; if (LOG.isTraceEnabled()) { startTime = System.currentTimeMillis(); } PayloadCarryingRpcController pcrc = (PayloadCarryingRpcController)controller; CellScanner cells = null; if (pcrc != null) { cells = pcrc.cellScanner(); // Clear it here so we don't by mistake try and these cells processing results. pcrc.setCellScanner(null); } Pair<Message, CellScanner> val = null; try { val = call(md, param, cells, returnType, ticket, isa, rpcTimeout, pcrc != null? pcrc.getPriority(): HConstants.NORMAL_QOS); if (pcrc != null) { // Shove the results into controller so can be carried across the proxy/pb service void. if (val.getSecond() != null) pcrc.setCellScanner(val.getSecond()); } else if (val.getSecond() != null) { throw new ServiceException("Client dropping data on the floor!"); } if (LOG.isTraceEnabled()) { long callTime = System.currentTimeMillis() - startTime; if (LOG.isTraceEnabled()) { LOG.trace("Call: " + md.getName() + ", callTime: " + callTime + "ms"); } } return val.getFirst(); } catch (Throwable e) { throw new ServiceException(e); } } /** * Creates a "channel" that can be used by a blocking protobuf service. Useful setting up * protobuf blocking stubs. * @param sn * @param ticket * @param rpcTimeout * @return A blocking rpc channel that goes via this rpc client instance. */ public BlockingRpcChannel createBlockingRpcChannel(final ServerName sn, final User ticket, final int rpcTimeout) { return new BlockingRpcChannelImplementation(this, sn, ticket, rpcTimeout); } /** * Blocking rpc channel that goes via hbase rpc. */ // Public so can be subclassed for tests. public static class BlockingRpcChannelImplementation implements BlockingRpcChannel { private final InetSocketAddress isa; private volatile RpcClient rpcClient; private final int rpcTimeout; private final User ticket; protected BlockingRpcChannelImplementation(final RpcClient rpcClient, final ServerName sn, final User ticket, final int rpcTimeout) { this.isa = new InetSocketAddress(sn.getHostname(), sn.getPort()); this.rpcClient = rpcClient; // Set the rpc timeout to be the minimum of configured timeout and whatever the current // thread local setting is. this.rpcTimeout = getRpcTimeout(rpcTimeout); this.ticket = ticket; } @Override public Message callBlockingMethod(MethodDescriptor md, RpcController controller, Message param, Message returnType) throws ServiceException { return this.rpcClient.callBlockingMethod(md, controller, param, returnType, this.ticket, this.isa, this.rpcTimeout); } } }
hbase-client/src/main/java/org/apache/hadoop/hbase/ipc/RpcClient.java
/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.ipc; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.security.PrivilegedExceptionAction; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import javax.net.SocketFactory; import javax.security.sasl.SaslException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.CellScanner; import org.apache.hadoop.hbase.HBaseIOException; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.codec.Codec; import org.apache.hadoop.hbase.codec.KeyValueCodec; import org.apache.hadoop.hbase.protobuf.ProtobufUtil; import org.apache.hadoop.hbase.protobuf.generated.AuthenticationProtos; import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.CellBlockMeta; import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.ConnectionHeader; import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.ExceptionResponse; import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.RequestHeader; import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.ResponseHeader; import org.apache.hadoop.hbase.protobuf.generated.RPCProtos.UserInformation; import org.apache.hadoop.hbase.protobuf.generated.TracingProtos.RPCTInfo; import org.apache.hadoop.hbase.security.AuthMethod; import org.apache.hadoop.hbase.security.HBaseSaslRpcClient; import org.apache.hadoop.hbase.security.SecurityInfo; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.security.UserProvider; import org.apache.hadoop.hbase.security.token.AuthenticationTokenSelector; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; import org.apache.hadoop.hbase.util.ExceptionUtil; import org.apache.hadoop.hbase.util.Pair; import org.apache.hadoop.hbase.util.PoolMap; import org.apache.hadoop.hbase.util.PoolMap.PoolType; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.ipc.RemoteException; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.SecurityUtil; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.security.token.TokenSelector; import org.cloudera.htrace.Span; import org.cloudera.htrace.Trace; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.BlockingRpcChannel; import com.google.protobuf.Descriptors.MethodDescriptor; import com.google.protobuf.Message; import com.google.protobuf.Message.Builder; import com.google.protobuf.RpcController; import com.google.protobuf.ServiceException; import com.google.protobuf.TextFormat; /** * Does RPC against a cluster. Manages connections per regionserver in the cluster. * <p>See HBaseServer */ @InterfaceAudience.Private public class RpcClient { // The LOG key is intentionally not from this package to avoid ipc logging at DEBUG (all under // o.a.h.hbase is set to DEBUG as default). public static final Log LOG = LogFactory.getLog("org.apache.hadoop.ipc.RpcClient"); protected final PoolMap<ConnectionId, Connection> connections; protected int counter; // counter for call ids protected final AtomicBoolean running = new AtomicBoolean(true); // if client runs final protected Configuration conf; final protected int maxIdleTime; // connections will be culled if it was idle for // maxIdleTime microsecs final protected int maxRetries; //the max. no. of retries for socket connections final protected long failureSleep; // Time to sleep before retry on failure. protected final boolean tcpNoDelay; // if T then disable Nagle's Algorithm protected final boolean tcpKeepAlive; // if T then use keepalives protected int pingInterval; // how often sends ping to the server in msecs protected FailedServers failedServers; private final Codec codec; private final CompressionCodec compressor; private final IPCUtil ipcUtil; protected final SocketFactory socketFactory; // how to create sockets protected String clusterId; protected final SocketAddress localAddr; private final boolean fallbackAllowed; private UserProvider userProvider; final private static String PING_INTERVAL_NAME = "ipc.ping.interval"; final private static String SOCKET_TIMEOUT = "ipc.socket.timeout"; final static int DEFAULT_PING_INTERVAL = 60000; // 1 min final static int DEFAULT_SOCKET_TIMEOUT = 20000; // 20 seconds final static int PING_CALL_ID = -1; public final static String FAILED_SERVER_EXPIRY_KEY = "hbase.ipc.client.failed.servers.expiry"; public final static int FAILED_SERVER_EXPIRY_DEFAULT = 2000; public static final String IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_KEY = "hbase.ipc.client.fallback-to-simple-auth-allowed"; public static final boolean IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_DEFAULT = false; // thread-specific RPC timeout, which may override that of what was passed in. // This is used to change dynamically the timeout (for read only) when retrying: if // the time allowed for the operation is less than the usual socket timeout, then // we lower the timeout. This is subject to race conditions, and should be used with // extreme caution. private static ThreadLocal<Integer> rpcTimeout = new ThreadLocal<Integer>() { @Override protected Integer initialValue() { return HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT; } }; /** * A class to manage a list of servers that failed recently. */ static class FailedServers { private final LinkedList<Pair<Long, String>> failedServers = new LinkedList<Pair<Long, java.lang.String>>(); private final int recheckServersTimeout; FailedServers(Configuration conf) { this.recheckServersTimeout = conf.getInt( FAILED_SERVER_EXPIRY_KEY, FAILED_SERVER_EXPIRY_DEFAULT); } /** * Add an address to the list of the failed servers list. */ public synchronized void addToFailedServers(InetSocketAddress address) { final long expiry = EnvironmentEdgeManager.currentTimeMillis() + recheckServersTimeout; failedServers.addFirst(new Pair<Long, String>(expiry, address.toString())); } /** * Check if the server should be considered as bad. Clean the old entries of the list. * * @return true if the server is in the failed servers list */ public synchronized boolean isFailedServer(final InetSocketAddress address) { if (failedServers.isEmpty()) { return false; } final String lookup = address.toString(); final long now = EnvironmentEdgeManager.currentTimeMillis(); // iterate, looking for the search entry and cleaning expired entries Iterator<Pair<Long, String>> it = failedServers.iterator(); while (it.hasNext()) { Pair<Long, String> cur = it.next(); if (cur.getFirst() < now) { it.remove(); } else { if (lookup.equals(cur.getSecond())) { return true; } } } return false; } } @SuppressWarnings("serial") @InterfaceAudience.Public @InterfaceStability.Evolving // Shouldn't this be a DoNotRetryException? St.Ack 10/2/2013 public static class FailedServerException extends HBaseIOException { public FailedServerException(String s) { super(s); } } /** * set the ping interval value in configuration * * @param conf Configuration * @param pingInterval the ping interval */ // Any reason we couldn't just do tcp keepalive instead of this pingery? // St.Ack 20130121 public static void setPingInterval(Configuration conf, int pingInterval) { conf.setInt(PING_INTERVAL_NAME, pingInterval); } /** * Get the ping interval from configuration; * If not set in the configuration, return the default value. * * @param conf Configuration * @return the ping interval */ static int getPingInterval(Configuration conf) { return conf.getInt(PING_INTERVAL_NAME, DEFAULT_PING_INTERVAL); } /** * Set the socket timeout * @param conf Configuration * @param socketTimeout the socket timeout */ public static void setSocketTimeout(Configuration conf, int socketTimeout) { conf.setInt(SOCKET_TIMEOUT, socketTimeout); } /** * @return the socket timeout */ static int getSocketTimeout(Configuration conf) { return conf.getInt(SOCKET_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); } /** A call waiting for a value. */ protected class Call { final int id; // call id final Message param; // rpc request method param object /** * Optionally has cells when making call. Optionally has cells set on response. Used * passing cells to the rpc and receiving the response. */ CellScanner cells; Message response; // value, null if error // The return type. Used to create shell into which we deserialize the response if any. Message responseDefaultType; IOException error; // exception, null if value boolean done; // true when call is done long startTime; final MethodDescriptor md; protected Call(final MethodDescriptor md, Message param, final CellScanner cells, final Message responseDefaultType) { this.param = param; this.md = md; this.cells = cells; this.startTime = System.currentTimeMillis(); this.responseDefaultType = responseDefaultType; synchronized (RpcClient.this) { this.id = counter++; } } @Override public String toString() { return "callId: " + this.id + " methodName: " + this.md.getName() + " param {" + (this.param != null? ProtobufUtil.getShortTextFormat(this.param): "") + "}"; } /** Indicate when the call is complete and the * value or error are available. Notifies by default. */ protected synchronized void callComplete() { this.done = true; notify(); // notify caller } /** Set the exception when there is an error. * Notify the caller the call is done. * * @param error exception thrown by the call; either local or remote */ public void setException(IOException error) { this.error = error; callComplete(); } /** * Set the return value when there is no error. * Notify the caller the call is done. * * @param response return value of the call. * @param cells Can be null */ public void setResponse(Message response, final CellScanner cells) { this.response = response; this.cells = cells; callComplete(); } public long getStartTime() { return this.startTime; } } protected final static Map<AuthenticationProtos.TokenIdentifier.Kind, TokenSelector<? extends TokenIdentifier>> tokenHandlers = new HashMap<AuthenticationProtos.TokenIdentifier.Kind, TokenSelector<? extends TokenIdentifier>>(); static { tokenHandlers.put(AuthenticationProtos.TokenIdentifier.Kind.HBASE_AUTH_TOKEN, new AuthenticationTokenSelector()); } /** * Creates a connection. Can be overridden by a subclass for testing. * @param remoteId - the ConnectionId to use for the connection creation. */ protected Connection createConnection(ConnectionId remoteId, final Codec codec, final CompressionCodec compressor) throws IOException { return new Connection(remoteId, codec, compressor); } /** Thread that reads responses and notifies callers. Each connection owns a * socket connected to a remote address. Calls are multiplexed through this * socket: responses may be delivered out of order. */ protected class Connection extends Thread { private ConnectionHeader header; // connection header protected ConnectionId remoteId; protected Socket socket = null; // connected socket protected DataInputStream in; protected DataOutputStream out; private InetSocketAddress server; // server ip:port private String serverPrincipal; // server's krb5 principal name private AuthMethod authMethod; // authentication method private boolean useSasl; private Token<? extends TokenIdentifier> token; private HBaseSaslRpcClient saslRpcClient; private int reloginMaxBackoff; // max pause before relogin on sasl failure private final Codec codec; private final CompressionCodec compressor; // currently active calls protected final ConcurrentSkipListMap<Integer, Call> calls = new ConcurrentSkipListMap<Integer, Call>(); protected final AtomicLong lastActivity = new AtomicLong(); // last I/O activity time protected final AtomicBoolean shouldCloseConnection = new AtomicBoolean(); // indicate if the connection is closed protected IOException closeException; // close reason Connection(ConnectionId remoteId, final Codec codec, final CompressionCodec compressor) throws IOException { if (remoteId.getAddress().isUnresolved()) { throw new UnknownHostException("unknown host: " + remoteId.getAddress().getHostName()); } this.server = remoteId.getAddress(); this.codec = codec; this.compressor = compressor; UserGroupInformation ticket = remoteId.getTicket().getUGI(); SecurityInfo securityInfo = SecurityInfo.getInfo(remoteId.getServiceName()); this.useSasl = userProvider.isHBaseSecurityEnabled(); if (useSasl && securityInfo != null) { AuthenticationProtos.TokenIdentifier.Kind tokenKind = securityInfo.getTokenKind(); if (tokenKind != null) { TokenSelector<? extends TokenIdentifier> tokenSelector = tokenHandlers.get(tokenKind); if (tokenSelector != null) { token = tokenSelector.selectToken(new Text(clusterId), ticket.getTokens()); } else if (LOG.isDebugEnabled()) { LOG.debug("No token selector found for type "+tokenKind); } } String serverKey = securityInfo.getServerPrincipal(); if (serverKey == null) { throw new IOException( "Can't obtain server Kerberos config key from SecurityInfo"); } serverPrincipal = SecurityUtil.getServerPrincipal( conf.get(serverKey), server.getAddress().getCanonicalHostName().toLowerCase()); if (LOG.isDebugEnabled()) { LOG.debug("RPC Server Kerberos principal name for service=" + remoteId.getServiceName() + " is " + serverPrincipal); } } if (!useSasl) { authMethod = AuthMethod.SIMPLE; } else if (token != null) { authMethod = AuthMethod.DIGEST; } else { authMethod = AuthMethod.KERBEROS; } if (LOG.isDebugEnabled()) { LOG.debug("Use " + authMethod + " authentication for service " + remoteId.serviceName + ", sasl=" + useSasl); } reloginMaxBackoff = conf.getInt("hbase.security.relogin.maxbackoff", 5000); this.remoteId = remoteId; ConnectionHeader.Builder builder = ConnectionHeader.newBuilder(); builder.setServiceName(remoteId.getServiceName()); UserInformation userInfoPB; if ((userInfoPB = getUserInfo(ticket)) != null) { builder.setUserInfo(userInfoPB); } if (this.codec != null) { builder.setCellBlockCodecClass(this.codec.getClass().getCanonicalName()); } if (this.compressor != null) { builder.setCellBlockCompressorClass(this.compressor.getClass().getCanonicalName()); } this.header = builder.build(); this.setName("IPC Client (" + socketFactory.hashCode() +") connection to " + remoteId.getAddress().toString() + ((ticket==null)?" from an unknown user": (" from " + ticket.getUserName()))); this.setDaemon(true); } private UserInformation getUserInfo(UserGroupInformation ugi) { if (ugi == null || authMethod == AuthMethod.DIGEST) { // Don't send user for token auth return null; } UserInformation.Builder userInfoPB = UserInformation.newBuilder(); if (authMethod == AuthMethod.KERBEROS) { // Send effective user for Kerberos auth userInfoPB.setEffectiveUser(ugi.getUserName()); } else if (authMethod == AuthMethod.SIMPLE) { //Send both effective user and real user for simple auth userInfoPB.setEffectiveUser(ugi.getUserName()); if (ugi.getRealUser() != null) { userInfoPB.setRealUser(ugi.getRealUser().getUserName()); } } return userInfoPB.build(); } /** Update lastActivity with the current time. */ protected void touch() { lastActivity.set(System.currentTimeMillis()); } /** * Add a call to this connection's call queue and notify * a listener; synchronized. If the connection is dead, the call is not added, and the * caller is notified. * This function can return a connection that is already marked as 'shouldCloseConnection' * It is up to the user code to check this status. * @param call to add */ @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="NN_NAKED_NOTIFY", justification="Notify because new call available for processing") protected synchronized void addCall(Call call) { // If the connection is about to close, we manage this as if the call was already added // to the connection calls list. If not, the connection creations are serialized, as // mentioned in HBASE-6364 if (this.shouldCloseConnection.get()) { if (this.closeException == null) { call.setException(new IOException( "Call " + call.id + " not added as the connection " + remoteId + " is closing")); } else { call.setException(this.closeException); } synchronized (call) { call.notifyAll(); } } else { calls.put(call.id, call); synchronized (call) { notify(); } } } /** This class sends a ping to the remote side when timeout on * reading. If no failure is detected, it retries until at least * a byte is read. */ protected class PingInputStream extends FilterInputStream { /* constructor */ protected PingInputStream(InputStream in) { super(in); } /* Process timeout exception * if the connection is not going to be closed, send a ping. * otherwise, throw the timeout exception. */ private void handleTimeout(SocketTimeoutException e) throws IOException { if (shouldCloseConnection.get() || !running.get() || remoteId.rpcTimeout > 0) { throw e; } sendPing(); } /** Read a byte from the stream. * Send a ping if timeout on read. Retries if no failure is detected * until a byte is read. * @throws IOException for any IO problem other than socket timeout */ @Override public int read() throws IOException { do { try { return super.read(); } catch (SocketTimeoutException e) { handleTimeout(e); } } while (true); } /** Read bytes into a buffer starting from offset <code>off</code> * Send a ping if timeout on read. Retries if no failure is detected * until a byte is read. * * @return the total number of bytes read; -1 if the connection is closed. */ @Override public int read(byte[] buf, int off, int len) throws IOException { do { try { return super.read(buf, off, len); } catch (SocketTimeoutException e) { handleTimeout(e); } } while (true); } } protected synchronized void setupConnection() throws IOException { short ioFailures = 0; short timeoutFailures = 0; while (true) { try { this.socket = socketFactory.createSocket(); this.socket.setTcpNoDelay(tcpNoDelay); this.socket.setKeepAlive(tcpKeepAlive); if (localAddr != null) { this.socket.bind(localAddr); } // connection time out is 20s NetUtils.connect(this.socket, remoteId.getAddress(), getSocketTimeout(conf)); if (remoteId.rpcTimeout > 0) { pingInterval = remoteId.rpcTimeout; // overwrite pingInterval } this.socket.setSoTimeout(pingInterval); return; } catch (SocketTimeoutException toe) { /* The max number of retries is 45, * which amounts to 20s*45 = 15 minutes retries. */ handleConnectionFailure(timeoutFailures++, maxRetries, toe); } catch (IOException ie) { handleConnectionFailure(ioFailures++, maxRetries, ie); } } } protected void closeConnection() { if (socket == null) { return; } // close the current connection try { if (socket.getOutputStream() != null) { socket.getOutputStream().close(); } } catch (IOException ignored) { // Can happen if the socket is already closed } try { if (socket.getInputStream() != null) { socket.getInputStream().close(); } } catch (IOException ignored) { // Can happen if the socket is already closed } try { if (socket.getChannel() != null) { socket.getChannel().close(); } } catch (IOException ignored) { // Can happen if the socket is already closed } try { socket.close(); } catch (IOException e) { LOG.warn("Not able to close a socket", e); } // set socket to null so that the next call to setupIOstreams // can start the process of connect all over again. socket = null; } /** * Handle connection failures * * If the current number of retries is equal to the max number of retries, * stop retrying and throw the exception; Otherwise backoff N seconds and * try connecting again. * * This Method is only called from inside setupIOstreams(), which is * synchronized. Hence the sleep is synchronized; the locks will be retained. * * @param curRetries current number of retries * @param maxRetries max number of retries allowed * @param ioe failure reason * @throws IOException if max number of retries is reached */ private void handleConnectionFailure(int curRetries, int maxRetries, IOException ioe) throws IOException { closeConnection(); // throw the exception if the maximum number of retries is reached if (curRetries >= maxRetries || ExceptionUtil.isInterrupt(ioe)) { throw ioe; } // otherwise back off and retry try { Thread.sleep(failureSleep); } catch (InterruptedException ie) { ExceptionUtil.rethrowIfInterrupt(ie); } LOG.info("Retrying connect to server: " + remoteId.getAddress() + " after sleeping " + failureSleep + "ms. Already tried " + curRetries + " time(s)."); } /* wait till someone signals us to start reading RPC response or * it is idle too long, it is marked as to be closed, * or the client is marked as not running. * * Return true if it is time to read a response; false otherwise. */ protected synchronized boolean waitForWork() { if (calls.isEmpty() && !shouldCloseConnection.get() && running.get()) { long timeout = maxIdleTime - (System.currentTimeMillis()-lastActivity.get()); if (timeout>0) { try { wait(timeout); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } } if (!calls.isEmpty() && !shouldCloseConnection.get() && running.get()) { return true; } else if (shouldCloseConnection.get()) { return false; } else if (calls.isEmpty()) { // idle connection closed or stopped markClosed(null); return false; } else { // get stopped but there are still pending requests markClosed((IOException)new IOException().initCause( new InterruptedException())); return false; } } public InetSocketAddress getRemoteAddress() { return remoteId.getAddress(); } /* Send a ping to the server if the time elapsed * since last I/O activity is equal to or greater than the ping interval */ protected synchronized void sendPing() throws IOException { // Can we do tcp keepalive instead of this pinging? long curTime = System.currentTimeMillis(); if ( curTime - lastActivity.get() >= pingInterval) { lastActivity.set(curTime); //noinspection SynchronizeOnNonFinalField synchronized (this.out) { out.writeInt(PING_CALL_ID); out.flush(); } } } @Override public void run() { if (LOG.isDebugEnabled()) { LOG.debug(getName() + ": starting, connections " + connections.size()); } try { while (waitForWork()) { // Wait here for work - read or close connection readResponse(); } } catch (Throwable t) { LOG.warn(getName() + ": unexpected exception receiving call responses", t); markClosed(new IOException("Unexpected exception receiving call responses", t)); } close(); if (LOG.isDebugEnabled()) LOG.debug(getName() + ": stopped, connections " + connections.size()); } private synchronized void disposeSasl() { if (saslRpcClient != null) { try { saslRpcClient.dispose(); saslRpcClient = null; } catch (IOException ioe) { LOG.error("Error disposing of SASL client", ioe); } } } private synchronized boolean shouldAuthenticateOverKrb() throws IOException { UserGroupInformation loginUser = UserGroupInformation.getLoginUser(); UserGroupInformation currentUser = UserGroupInformation.getCurrentUser(); UserGroupInformation realUser = currentUser.getRealUser(); return authMethod == AuthMethod.KERBEROS && loginUser != null && //Make sure user logged in using Kerberos either keytab or TGT loginUser.hasKerberosCredentials() && // relogin only in case it is the login user (e.g. JT) // or superuser (like oozie). (loginUser.equals(currentUser) || loginUser.equals(realUser)); } private synchronized boolean setupSaslConnection(final InputStream in2, final OutputStream out2) throws IOException { saslRpcClient = new HBaseSaslRpcClient(authMethod, token, serverPrincipal, fallbackAllowed); return saslRpcClient.saslConnect(in2, out2); } /** * If multiple clients with the same principal try to connect * to the same server at the same time, the server assumes a * replay attack is in progress. This is a feature of kerberos. * In order to work around this, what is done is that the client * backs off randomly and tries to initiate the connection * again. * The other problem is to do with ticket expiry. To handle that, * a relogin is attempted. * <p> * The retry logic is governed by the {@link #shouldAuthenticateOverKrb} * method. In case when the user doesn't have valid credentials, we don't * need to retry (from cache or ticket). In such cases, it is prudent to * throw a runtime exception when we receive a SaslException from the * underlying authentication implementation, so there is no retry from * other high level (for eg, HCM or HBaseAdmin). * </p> */ private synchronized void handleSaslConnectionFailure( final int currRetries, final int maxRetries, final Exception ex, final Random rand, final UserGroupInformation user) throws IOException, InterruptedException{ user.doAs(new PrivilegedExceptionAction<Object>() { public Object run() throws IOException, InterruptedException { closeConnection(); if (shouldAuthenticateOverKrb()) { if (currRetries < maxRetries) { LOG.debug("Exception encountered while connecting to " + "the server : " + ex); //try re-login if (UserGroupInformation.isLoginKeytabBased()) { UserGroupInformation.getLoginUser().reloginFromKeytab(); } else { UserGroupInformation.getLoginUser().reloginFromTicketCache(); } disposeSasl(); //have granularity of milliseconds //we are sleeping with the Connection lock held but since this //connection instance is being used for connecting to the server //in question, it is okay Thread.sleep((rand.nextInt(reloginMaxBackoff) + 1)); return null; } else { String msg = "Couldn't setup connection for " + UserGroupInformation.getLoginUser().getUserName() + " to " + serverPrincipal; LOG.warn(msg); throw (IOException) new IOException(msg).initCause(ex); } } else { LOG.warn("Exception encountered while connecting to " + "the server : " + ex); } if (ex instanceof RemoteException) { throw (RemoteException)ex; } if (ex instanceof SaslException) { String msg = "SASL authentication failed." + " The most likely cause is missing or invalid credentials." + " Consider 'kinit'."; LOG.fatal(msg, ex); throw new RuntimeException(msg, ex); } throw new IOException(ex); } }); } protected synchronized void setupIOstreams() throws IOException, InterruptedException { if (socket != null || shouldCloseConnection.get()) { return; } if (failedServers.isFailedServer(remoteId.getAddress())) { if (LOG.isDebugEnabled()) { LOG.debug("Not trying to connect to " + server + " this server is in the failed servers list"); } IOException e = new FailedServerException( "This server is in the failed servers list: " + server); markClosed(e); close(); throw e; } try { if (LOG.isDebugEnabled()) { LOG.debug("Connecting to " + server); } short numRetries = 0; final short MAX_RETRIES = 5; Random rand = null; while (true) { setupConnection(); InputStream inStream = NetUtils.getInputStream(socket); // This creates a socket with a write timeout. This timeout cannot be changed, // RpcClient allows to change the timeout dynamically, but we can only // change the read timeout today. OutputStream outStream = NetUtils.getOutputStream(socket, pingInterval); // Write out the preamble -- MAGIC, version, and auth to use. writeConnectionHeaderPreamble(outStream); if (useSasl) { final InputStream in2 = inStream; final OutputStream out2 = outStream; UserGroupInformation ticket = remoteId.getTicket().getUGI(); if (authMethod == AuthMethod.KERBEROS) { if (ticket != null && ticket.getRealUser() != null) { ticket = ticket.getRealUser(); } } boolean continueSasl = false; if (ticket == null) throw new FatalConnectionException("ticket/user is null"); try { continueSasl = ticket.doAs(new PrivilegedExceptionAction<Boolean>() { @Override public Boolean run() throws IOException { return setupSaslConnection(in2, out2); } }); } catch (Exception ex) { if (rand == null) { rand = new Random(); } handleSaslConnectionFailure(numRetries++, MAX_RETRIES, ex, rand, ticket); continue; } if (continueSasl) { // Sasl connect is successful. Let's set up Sasl i/o streams. inStream = saslRpcClient.getInputStream(inStream); outStream = saslRpcClient.getOutputStream(outStream); } else { // fall back to simple auth because server told us so. authMethod = AuthMethod.SIMPLE; useSasl = false; } } this.in = new DataInputStream(new BufferedInputStream(new PingInputStream(inStream))); this.out = new DataOutputStream(new BufferedOutputStream(outStream)); // Now write out the connection header writeConnectionHeader(); // update last activity time touch(); // start the receiver thread after the socket connection has been set up start(); return; } } catch (Throwable t) { failedServers.addToFailedServers(remoteId.address); IOException e = null; if (t instanceof IOException) { e = (IOException)t; markClosed(e); } else { e = new IOException("Could not set up IO Streams", t); markClosed(e); } close(); throw e; } } /** * Write the RPC header: <MAGIC WORD -- 'HBas'> <ONEBYTE_VERSION> <ONEBYTE_AUTH_TYPE> */ private void writeConnectionHeaderPreamble(OutputStream outStream) throws IOException { // Assemble the preamble up in a buffer first and then send it. Writing individual elements, // they are getting sent across piecemeal according to wireshark and then server is messing // up the reading on occasion (the passed in stream is not buffered yet). // Preamble is six bytes -- 'HBas' + VERSION + AUTH_CODE int rpcHeaderLen = HConstants.RPC_HEADER.array().length; byte [] preamble = new byte [rpcHeaderLen + 2]; System.arraycopy(HConstants.RPC_HEADER.array(), 0, preamble, 0, rpcHeaderLen); preamble[rpcHeaderLen] = HConstants.RPC_CURRENT_VERSION; preamble[rpcHeaderLen + 1] = authMethod.code; outStream.write(preamble); outStream.flush(); } /** * Write the connection header. * Out is not synchronized because only the first thread does this. */ private void writeConnectionHeader() throws IOException { synchronized (this.out) { this.out.writeInt(this.header.getSerializedSize()); this.header.writeTo(this.out); this.out.flush(); } } /** Close the connection. */ protected synchronized void close() { if (!shouldCloseConnection.get()) { LOG.error(getName() + ": the connection is not in the closed state"); return; } // release the resources // first thing to do;take the connection out of the connection list synchronized (connections) { connections.removeValue(remoteId, this); } // close the streams and therefore the socket if (this.out != null) { synchronized(this.out) { IOUtils.closeStream(out); this.out = null; } } IOUtils.closeStream(in); this.in = null; disposeSasl(); // clean up all calls if (closeException == null) { if (!calls.isEmpty()) { LOG.warn(getName() + ": connection is closed for no cause and calls are not empty. " + "#Calls: " + calls.size()); // clean up calls anyway closeException = new IOException("Unexpected closed connection"); cleanupCalls(); } } else { // log the info if (LOG.isDebugEnabled()) { LOG.debug(getName() + ": closing ipc connection to " + server + ": " + closeException.getMessage(), closeException); } // cleanup calls cleanupCalls(); } if (LOG.isDebugEnabled()) LOG.debug(getName() + ": closed"); } /** * Initiates a call by sending the parameter to the remote server. * Note: this is not called from the Connection thread, but by other * threads. * @param call * @param priority * @see #readResponse() */ protected void writeRequest(Call call, final int priority) { if (shouldCloseConnection.get()) return; try { RequestHeader.Builder builder = RequestHeader.newBuilder(); builder.setCallId(call.id); if (Trace.isTracing()) { Span s = Trace.currentSpan(); builder.setTraceInfo(RPCTInfo.newBuilder(). setParentId(s.getSpanId()).setTraceId(s.getTraceId())); } builder.setMethodName(call.md.getName()); builder.setRequestParam(call.param != null); ByteBuffer cellBlock = ipcUtil.buildCellBlock(this.codec, this.compressor, call.cells); if (cellBlock != null) { CellBlockMeta.Builder cellBlockBuilder = CellBlockMeta.newBuilder(); cellBlockBuilder.setLength(cellBlock.limit()); builder.setCellBlockMeta(cellBlockBuilder.build()); } // Only pass priority if there one. Let zero be same as no priority. if (priority != 0) builder.setPriority(priority); //noinspection SynchronizeOnNonFinalField RequestHeader header = builder.build(); synchronized (this.out) { // FindBugs IS2_INCONSISTENT_SYNC IPCUtil.write(this.out, header, call.param, cellBlock); } if (LOG.isDebugEnabled()) { LOG.debug(getName() + ": wrote request header " + TextFormat.shortDebugString(header)); } } catch(IOException e) { markClosed(e); } } /* Receive a response. * Because only one receiver, so no synchronization on in. */ protected void readResponse() { if (shouldCloseConnection.get()) return; touch(); int totalSize = -1; try { // See HBaseServer.Call.setResponse for where we write out the response. // Total size of the response. Unused. But have to read it in anyways. totalSize = in.readInt(); // Read the header ResponseHeader responseHeader = ResponseHeader.parseDelimitedFrom(in); int id = responseHeader.getCallId(); if (LOG.isDebugEnabled()) { LOG.debug(getName() + ": got response header " + TextFormat.shortDebugString(responseHeader) + ", totalSize: " + totalSize + " bytes"); } Call call = calls.get(id); if (call == null) { // So we got a response for which we have no corresponding 'call' here on the client-side. // We probably timed out waiting, cleaned up all references, and now the server decides // to return a response. There is nothing we can do w/ the response at this stage. Clean // out the wire of the response so its out of the way and we can get other responses on // this connection. int readSoFar = IPCUtil.getTotalSizeWhenWrittenDelimited(responseHeader); int whatIsLeftToRead = totalSize - readSoFar; LOG.debug("Unknown callId: " + id + ", skipping over this response of " + whatIsLeftToRead + " bytes"); IOUtils.skipFully(in, whatIsLeftToRead); } if (responseHeader.hasException()) { ExceptionResponse exceptionResponse = responseHeader.getException(); RemoteException re = createRemoteException(exceptionResponse); if (isFatalConnectionException(exceptionResponse)) { markClosed(re); } else { if (call != null) call.setException(re); } } else { Message value = null; // Call may be null because it may have timedout and been cleaned up on this side already if (call != null && call.responseDefaultType != null) { Builder builder = call.responseDefaultType.newBuilderForType(); builder.mergeDelimitedFrom(in); value = builder.build(); } CellScanner cellBlockScanner = null; if (responseHeader.hasCellBlockMeta()) { int size = responseHeader.getCellBlockMeta().getLength(); byte [] cellBlock = new byte[size]; IOUtils.readFully(this.in, cellBlock, 0, cellBlock.length); cellBlockScanner = ipcUtil.createCellScanner(this.codec, this.compressor, cellBlock); } // it's possible that this call may have been cleaned up due to a RPC // timeout, so check if it still exists before setting the value. if (call != null) call.setResponse(value, cellBlockScanner); } if (call != null) calls.remove(id); } catch (IOException e) { if (e instanceof SocketTimeoutException && remoteId.rpcTimeout > 0) { // Clean up open calls but don't treat this as a fatal condition, // since we expect certain responses to not make it by the specified // {@link ConnectionId#rpcTimeout}. closeException = e; } if (ExceptionUtil.isInterrupt(e)){ } else { // Treat this as a fatal condition and close this connection markClosed(e); } } finally { if (remoteId.rpcTimeout > 0) { cleanupCalls(remoteId.rpcTimeout); } } } /** * @param e * @return True if the exception is a fatal connection exception. */ private boolean isFatalConnectionException(final ExceptionResponse e) { return e.getExceptionClassName(). equals(FatalConnectionException.class.getName()); } /** * @param e * @return RemoteException made from passed <code>e</code> */ private RemoteException createRemoteException(final ExceptionResponse e) { String innerExceptionClassName = e.getExceptionClassName(); boolean doNotRetry = e.getDoNotRetry(); return e.hasHostname()? // If a hostname then add it to the RemoteWithExtrasException new RemoteWithExtrasException(innerExceptionClassName, e.getStackTrace(), e.getHostname(), e.getPort(), doNotRetry): new RemoteWithExtrasException(innerExceptionClassName, e.getStackTrace(), doNotRetry); } protected synchronized void markClosed(IOException e) { if (shouldCloseConnection.compareAndSet(false, true)) { closeException = e; notifyAll(); } } /* Cleanup all calls and mark them as done */ protected void cleanupCalls() { cleanupCalls(0); } @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="NN_NAKED_NOTIFY", justification="Notify because timedout") protected void cleanupCalls(long rpcTimeout) { Iterator<Entry<Integer, Call>> itor = calls.entrySet().iterator(); while (itor.hasNext()) { Call c = itor.next().getValue(); long waitTime = System.currentTimeMillis() - c.getStartTime(); if (waitTime >= rpcTimeout) { if (this.closeException == null) { // There may be no exception in the case that there are many calls // being multiplexed over this connection and these are succeeding // fine while this Call object is taking a long time to finish // over on the server; e.g. I just asked the regionserver to bulk // open 3k regions or its a big fat multiput into a heavily-loaded // server (Perhaps this only happens at the extremes?) this.closeException = new CallTimeoutException("Call id=" + c.id + ", waitTime=" + waitTime + ", rpcTimetout=" + rpcTimeout); } c.setException(this.closeException); synchronized (c) { c.notifyAll(); } itor.remove(); } else { break; } } try { if (!calls.isEmpty()) { Call firstCall = calls.get(calls.firstKey()); long maxWaitTime = System.currentTimeMillis() - firstCall.getStartTime(); if (maxWaitTime < rpcTimeout) { rpcTimeout -= maxWaitTime; } } if (!shouldCloseConnection.get()) { closeException = null; setSocketTimeout(socket, (int) rpcTimeout); } } catch (SocketException e) { LOG.debug("Couldn't lower timeout, which may result in longer than expected calls"); } } } @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="IS2_INCONSISTENT_SYNC", justification="Presume sync not needed setting socket timeout") private static void setSocketTimeout(final Socket socket, final int rpcTimeout) throws java.net.SocketException { if (socket == null) return; socket.setSoTimeout(rpcTimeout); } /** * Client-side call timeout */ @SuppressWarnings("serial") @InterfaceAudience.Public @InterfaceStability.Evolving public static class CallTimeoutException extends IOException { public CallTimeoutException(final String msg) { super(msg); } } /** * Construct an IPC cluster client whose values are of the {@link Message} class. * @param conf configuration * @param clusterId * @param factory socket factory */ RpcClient(Configuration conf, String clusterId, SocketFactory factory) { this(conf, clusterId, factory, null); } /** * Construct an IPC cluster client whose values are of the {@link Message} class. * @param conf configuration * @param clusterId * @param factory socket factory * @param localAddr client socket bind address */ RpcClient(Configuration conf, String clusterId, SocketFactory factory, SocketAddress localAddr) { this.maxIdleTime = conf.getInt("hbase.ipc.client.connection.maxidletime", 10000); //10s this.maxRetries = conf.getInt("hbase.ipc.client.connect.max.retries", 0); this.failureSleep = conf.getLong(HConstants.HBASE_CLIENT_PAUSE, HConstants.DEFAULT_HBASE_CLIENT_PAUSE); this.tcpNoDelay = conf.getBoolean("hbase.ipc.client.tcpnodelay", true); this.tcpKeepAlive = conf.getBoolean("hbase.ipc.client.tcpkeepalive", true); this.pingInterval = getPingInterval(conf); this.ipcUtil = new IPCUtil(conf); this.conf = conf; this.codec = getCodec(); this.compressor = getCompressor(conf); this.socketFactory = factory; this.clusterId = clusterId != null ? clusterId : HConstants.CLUSTER_ID_DEFAULT; this.connections = new PoolMap<ConnectionId, Connection>(getPoolType(conf), getPoolSize(conf)); this.failedServers = new FailedServers(conf); this.fallbackAllowed = conf.getBoolean(IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_KEY, IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_DEFAULT); this.localAddr = localAddr; this.userProvider = UserProvider.instantiate(conf); // login the server principal (if using secure Hadoop) if (LOG.isDebugEnabled()) { LOG.debug("Codec=" + this.codec + ", compressor=" + this.compressor + ", tcpKeepAlive=" + this.tcpKeepAlive + ", tcpNoDelay=" + this.tcpNoDelay + ", maxIdleTime=" + this.maxIdleTime + ", maxRetries=" + this.maxRetries + ", fallbackAllowed=" + this.fallbackAllowed + ", ping interval=" + this.pingInterval + "ms" + ", bind address=" + (this.localAddr != null ? this.localAddr : "null")); } } /** * Construct an IPC client for the cluster <code>clusterId</code> with the default SocketFactory * @param conf configuration * @param clusterId */ public RpcClient(Configuration conf, String clusterId) { this(conf, clusterId, NetUtils.getDefaultSocketFactory(conf), null); } /** * Construct an IPC client for the cluster <code>clusterId</code> with the default SocketFactory * @param conf configuration * @param clusterId * @param localAddr client socket bind address. */ public RpcClient(Configuration conf, String clusterId, SocketAddress localAddr) { this(conf, clusterId, NetUtils.getDefaultSocketFactory(conf), localAddr); } /** * Encapsulate the ugly casting and RuntimeException conversion in private method. * @return Codec to use on this client. */ Codec getCodec() { // For NO CODEC, "hbase.client.rpc.codec" must be configured with empty string AND // "hbase.client.default.rpc.codec" also -- because default is to do cell block encoding. String className = conf.get(HConstants.RPC_CODEC_CONF_KEY, getDefaultCodec(this.conf)); if (className == null || className.length() == 0) return null; try { return (Codec)Class.forName(className).newInstance(); } catch (Exception e) { throw new RuntimeException("Failed getting codec " + className, e); } } @VisibleForTesting public static String getDefaultCodec(final Configuration c) { // If "hbase.client.default.rpc.codec" is empty string -- you can't set it to null because // Configuration will complain -- then no default codec (and we'll pb everything). Else // default is KeyValueCodec return c.get("hbase.client.default.rpc.codec", KeyValueCodec.class.getCanonicalName()); } /** * Encapsulate the ugly casting and RuntimeException conversion in private method. * @param conf * @return The compressor to use on this client. */ private static CompressionCodec getCompressor(final Configuration conf) { String className = conf.get("hbase.client.rpc.compressor", null); if (className == null || className.isEmpty()) return null; try { return (CompressionCodec)Class.forName(className).newInstance(); } catch (Exception e) { throw new RuntimeException("Failed getting compressor " + className, e); } } /** * Return the pool type specified in the configuration, which must be set to * either {@link PoolType#RoundRobin} or {@link PoolType#ThreadLocal}, * otherwise default to the former. * * For applications with many user threads, use a small round-robin pool. For * applications with few user threads, you may want to try using a * thread-local pool. In any case, the number of {@link RpcClient} instances * should not exceed the operating system's hard limit on the number of * connections. * * @param config configuration * @return either a {@link PoolType#RoundRobin} or * {@link PoolType#ThreadLocal} */ protected static PoolType getPoolType(Configuration config) { return PoolType.valueOf(config.get(HConstants.HBASE_CLIENT_IPC_POOL_TYPE), PoolType.RoundRobin, PoolType.ThreadLocal); } /** * Return the pool size specified in the configuration, which is applicable only if * the pool type is {@link PoolType#RoundRobin}. * * @param config * @return the maximum pool size */ protected static int getPoolSize(Configuration config) { return config.getInt(HConstants.HBASE_CLIENT_IPC_POOL_SIZE, 1); } /** Return the socket factory of this client * * @return this client's socket factory */ SocketFactory getSocketFactory() { return socketFactory; } /** Stop all threads related to this client. No further calls may be made * using this client. */ public void stop() { if (LOG.isDebugEnabled()) LOG.debug("Stopping rpc client"); if (!running.compareAndSet(true, false)) return; // wake up all connections synchronized (connections) { for (Connection conn : connections.values()) { conn.interrupt(); } } // wait until all connections are closed while (!connections.isEmpty()) { try { Thread.sleep(100); } catch (InterruptedException ignored) { } } } Pair<Message, CellScanner> call(MethodDescriptor md, Message param, CellScanner cells, Message returnType, User ticket, InetSocketAddress addr, int rpcTimeout) throws InterruptedException, IOException { return call(md, param, cells, returnType, ticket, addr, rpcTimeout, HConstants.NORMAL_QOS); } /** Make a call, passing <code>param</code>, to the IPC server running at * <code>address</code> which is servicing the <code>protocol</code> protocol, * with the <code>ticket</code> credentials, returning the value. * Throws exceptions if there are network problems or if the remote code * threw an exception. * @param md * @param param * @param cells * @param addr * @param returnType * @param ticket Be careful which ticket you pass. A new user will mean a new Connection. * {@link UserProvider#getCurrent()} makes a new instance of User each time so will be a * new Connection each time. * @param rpcTimeout * @return A pair with the Message response and the Cell data (if any). * @throws InterruptedException * @throws IOException */ Pair<Message, CellScanner> call(MethodDescriptor md, Message param, CellScanner cells, Message returnType, User ticket, InetSocketAddress addr, int rpcTimeout, int priority) throws InterruptedException, IOException { Call call = new Call(md, param, cells, returnType); Connection connection = getConnection(ticket, call, addr, rpcTimeout, this.codec, this.compressor); connection.writeRequest(call, priority); // send the parameter //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (call) { while (!call.done) { if (connection.shouldCloseConnection.get()) { throw new IOException("Unexpected closed connection"); } call.wait(1000); // wait for the result } if (call.error != null) { if (call.error instanceof RemoteException) { call.error.fillInStackTrace(); throw call.error; } // local exception throw wrapException(addr, call.error); } return new Pair<Message, CellScanner>(call.response, call.cells); } } /** * Take an IOException and the address we were trying to connect to * and return an IOException with the input exception as the cause. * The new exception provides the stack trace of the place where * the exception is thrown and some extra diagnostics information. * If the exception is ConnectException or SocketTimeoutException, * return a new one of the same type; Otherwise return an IOException. * * @param addr target address * @param exception the relevant exception * @return an exception to throw */ protected IOException wrapException(InetSocketAddress addr, IOException exception) { if (exception instanceof ConnectException) { //connection refused; include the host:port in the error return (ConnectException)new ConnectException( "Call to " + addr + " failed on connection exception: " + exception).initCause(exception); } else if (exception instanceof SocketTimeoutException) { return (SocketTimeoutException)new SocketTimeoutException("Call to " + addr + " failed because " + exception).initCause(exception); } else { return (IOException)new IOException("Call to " + addr + " failed on local exception: " + exception).initCause(exception); } } /** * Interrupt the connections to the given ip:port server. This should be called if the server * is known as actually dead. This will not prevent current operation to be retried, and, * depending on their own behavior, they may retry on the same server. This can be a feature, * for example at startup. In any case, they're likely to get connection refused (if the * process died) or no route to host: i.e. there next retries should be faster and with a * safe exception. */ public void cancelConnections(String hostname, int port, IOException ioe) { synchronized (connections) { for (Connection connection : connections.values()) { if (connection.isAlive() && connection.getRemoteAddress().getPort() == port && connection.getRemoteAddress().getHostName().equals(hostname)) { LOG.info("The server on " + hostname + ":" + port + " is dead - stopping the connection " + connection.remoteId); connection.closeConnection(); // We could do a connection.interrupt(), but it's safer not to do it, as the // interrupted exception behavior is not defined nor enforced enough. } } } } /* Get a connection from the pool, or create a new one and add it to the * pool. Connections to a given host/port are reused. */ protected Connection getConnection(User ticket, Call call, InetSocketAddress addr, int rpcTimeout, final Codec codec, final CompressionCodec compressor) throws IOException, InterruptedException { if (!running.get()) throw new StoppedRpcClientException(); Connection connection; ConnectionId remoteId = new ConnectionId(ticket, call.md.getService().getName(), addr, rpcTimeout); synchronized (connections) { connection = connections.get(remoteId); if (connection == null) { connection = createConnection(remoteId, this.codec, this.compressor); connections.put(remoteId, connection); } } connection.addCall(call); //we don't invoke the method below inside "synchronized (connections)" //block above. The reason for that is if the server happens to be slow, //it will take longer to establish a connection and that will slow the //entire system down. //Moreover, if the connection is currently created, there will be many threads // waiting here; as setupIOstreams is synchronized. If the connection fails with a // timeout, they will all fail simultaneously. This is checked in setupIOstreams. connection.setupIOstreams(); return connection; } /** * This class holds the address and the user ticket, etc. The client connections * to servers are uniquely identified by <remoteAddress, ticket, serviceName, rpcTimeout> */ protected static class ConnectionId { final InetSocketAddress address; final User ticket; final int rpcTimeout; private static final int PRIME = 16777619; final String serviceName; ConnectionId(User ticket, String serviceName, InetSocketAddress address, int rpcTimeout) { this.address = address; this.ticket = ticket; this.rpcTimeout = rpcTimeout; this.serviceName = serviceName; } String getServiceName() { return this.serviceName; } InetSocketAddress getAddress() { return address; } User getTicket() { return ticket; } @Override public String toString() { return this.address.toString() + "/" + this.serviceName + "/" + this.ticket + "/" + this.rpcTimeout; } @Override public boolean equals(Object obj) { if (obj instanceof ConnectionId) { ConnectionId id = (ConnectionId) obj; return address.equals(id.address) && ((ticket != null && ticket.equals(id.ticket)) || (ticket == id.ticket)) && rpcTimeout == id.rpcTimeout && this.serviceName == id.serviceName; } return false; } @Override // simply use the default Object#hashcode() ? public int hashCode() { int hashcode = (address.hashCode() + PRIME * (PRIME * this.serviceName.hashCode() ^ (ticket == null ? 0 : ticket.hashCode()) )) ^ rpcTimeout; return hashcode; } } public static void setRpcTimeout(int t) { rpcTimeout.set(t); } public static int getRpcTimeout() { return rpcTimeout.get(); } /** * Returns the lower of the thread-local RPC time from {@link #setRpcTimeout(int)} and the given * default timeout. */ public static int getRpcTimeout(int defaultTimeout) { return Math.min(defaultTimeout, rpcTimeout.get()); } public static void resetRpcTimeout() { rpcTimeout.remove(); } /** * Make a blocking call. Throws exceptions if there are network problems or if the remote code * threw an exception. * @param md * @param controller * @param param * @param returnType * @param isa * @param ticket Be careful which ticket you pass. A new user will mean a new Connection. * {@link UserProvider#getCurrent()} makes a new instance of User each time so will be a * new Connection each time. * @param rpcTimeout * @return A pair with the Message response and the Cell data (if any). * @throws InterruptedException * @throws IOException */ Message callBlockingMethod(MethodDescriptor md, RpcController controller, Message param, Message returnType, final User ticket, final InetSocketAddress isa, final int rpcTimeout) throws ServiceException { long startTime = 0; if (LOG.isTraceEnabled()) { startTime = System.currentTimeMillis(); } PayloadCarryingRpcController pcrc = (PayloadCarryingRpcController)controller; CellScanner cells = null; if (pcrc != null) { cells = pcrc.cellScanner(); // Clear it here so we don't by mistake try and these cells processing results. pcrc.setCellScanner(null); } Pair<Message, CellScanner> val = null; try { val = call(md, param, cells, returnType, ticket, isa, rpcTimeout, pcrc != null? pcrc.getPriority(): HConstants.NORMAL_QOS); if (pcrc != null) { // Shove the results into controller so can be carried across the proxy/pb service void. if (val.getSecond() != null) pcrc.setCellScanner(val.getSecond()); } else if (val.getSecond() != null) { throw new ServiceException("Client dropping data on the floor!"); } if (LOG.isTraceEnabled()) { long callTime = System.currentTimeMillis() - startTime; if (LOG.isTraceEnabled()) { LOG.trace("Call: " + md.getName() + ", callTime: " + callTime + "ms"); } } return val.getFirst(); } catch (Throwable e) { throw new ServiceException(e); } } /** * Creates a "channel" that can be used by a blocking protobuf service. Useful setting up * protobuf blocking stubs. * @param sn * @param ticket * @param rpcTimeout * @return A blocking rpc channel that goes via this rpc client instance. */ public BlockingRpcChannel createBlockingRpcChannel(final ServerName sn, final User ticket, final int rpcTimeout) { return new BlockingRpcChannelImplementation(this, sn, ticket, rpcTimeout); } /** * Blocking rpc channel that goes via hbase rpc. */ // Public so can be subclassed for tests. public static class BlockingRpcChannelImplementation implements BlockingRpcChannel { private final InetSocketAddress isa; private volatile RpcClient rpcClient; private final int rpcTimeout; private final User ticket; protected BlockingRpcChannelImplementation(final RpcClient rpcClient, final ServerName sn, final User ticket, final int rpcTimeout) { this.isa = new InetSocketAddress(sn.getHostname(), sn.getPort()); this.rpcClient = rpcClient; // Set the rpc timeout to be the minimum of configured timeout and whatever the current // thread local setting is. this.rpcTimeout = getRpcTimeout(rpcTimeout); this.ticket = ticket; } @Override public Message callBlockingMethod(MethodDescriptor md, RpcController controller, Message param, Message returnType) throws ServiceException { return this.rpcClient.callBlockingMethod(md, controller, param, returnType, this.ticket, this.isa, this.rpcTimeout); } } }
HBASE-10477 Regression from HBASE-10337 git-svn-id: eacefbb430aa6993bec52677de2e7e10bea24366@1565366 13f79535-47bb-0310-9956-ffa450edef68
hbase-client/src/main/java/org/apache/hadoop/hbase/ipc/RpcClient.java
HBASE-10477 Regression from HBASE-10337
<ide><path>base-client/src/main/java/org/apache/hadoop/hbase/ipc/RpcClient.java <ide> // since we expect certain responses to not make it by the specified <ide> // {@link ConnectionId#rpcTimeout}. <ide> closeException = e; <del> } if (ExceptionUtil.isInterrupt(e)){ <del> <ide> } else { <ide> // Treat this as a fatal condition and close this connection <ide> markClosed(e);
JavaScript
mit
be08377bd318b11872166e241a557c29495ff790
0
fauvel/CM,njam/CM,njam/CM,cargomedia/CM,fauvel/CM,vogdb/cm,cargomedia/CM,cargomedia/CM,vogdb/cm,njam/CM,njam/CM,fauvel/CM,fauvel/CM,fauvel/CM,njam/CM,vogdb/cm,vogdb/cm,vogdb/cm,cargomedia/CM
/** * @class CM_View_Abstract * @extends Backbone.View */ var CM_View_Abstract = Backbone.View.extend({ _class: 'CM_View_Abstract', /** @type CM_View_Abstract[] **/ _children: [], /** * @param {Object} [options] */ constructor: function(options) { this.options = options || {}; Backbone.View.apply(this, arguments); }, initialize: function() { this._children = []; if (this.getParent()) { this.getParent().registerChild(this); } this.events = this.collectEvents(); if (this.actions) { this._bindActions(this.actions); } if (this.streams) { this._bindStreams(this.streams); } if (this.childrenEvents) { this._bindChildrenEvents(this.childrenEvents); } if (this.appEvents) { this._bindAppEvents(this.appEvents); } this.on('all', function(eventName, data) { cm.viewEvents.trigger.apply(cm.viewEvents, [this].concat(_.toArray(arguments))); }); }, collectEvents: function() { var eventsObjects = [], currentConstructor = this.constructor, currentProto = currentConstructor.prototype; do { if (currentProto.hasOwnProperty('events')) { eventsObjects.unshift(currentProto.events); } } while (currentConstructor = ( currentProto = currentConstructor.__super__ ) && currentProto.constructor); eventsObjects.unshift({}); return _.extend.apply(_, eventsObjects); }, ready: function() { }, _ready: function() { this.ready(); _.each(this.getChildren(), function(child) { child._ready(); }); this.trigger('ready'); }, /** * @param {CM_View_Abstract} child */ registerChild: function(child) { this._children.push(child); child.options.parent = this; }, /** * @param {String|Null} [className] * @return CM_View_Abstract[] */ getChildren: function(className) { if (!className) { return this._children; } return _.filter(this._children, function(child) { return child.hasClass(className); }); }, /** * @param {String} className * @return CM_View_Abstract|null */ findChild: function(className) { return _.find(this.getChildren(), function(child) { return child.hasClass(className); }) || null; }, /** * @param {String} className * @returns {CM_View_Abstract} */ getChild: function(className) { var child = this.findChild(className); if (!child) { throw new Error('Failed to retrieve `' + className + '` child view of `' + this.getClass() + '`.'); } return child; }, /** * @return CM_View_Abstract|null */ getParent: function() { if (this.options.parent) { return this.options.parent; } return null; }, /** * @param {String} className * @return CM_View_Abstract|null */ findParent: function(className) { var parent = this.getParent(); if (!parent) { return null; } if (parent.hasClass(className)) { return parent; } return parent.findParent(className); }, /** * @return CM_View_Abstract|null */ getComponent: function() { if (this.hasClass('CM_Component_Abstract')) { return this; } return this.findParent('CM_Component_Abstract'); }, /** * @returns {{CM_Component_Abstract: Object|null, CM_View_Abstract: Object}} */ getViewInfoList: function() { var viewInfoList = { CM_Component_Abstract: null, CM_View_Abstract: this._getArray() }; var component = this.getComponent(); if (component) { viewInfoList.CM_Component_Abstract = component._getArray(); } return viewInfoList; }, /** * @return String */ getAutoId: function() { if (!this.el.id) { this.el.id = cm.getUuid(); } return this.el.id; }, /** * @return Object */ getParams: function() { return this.options.params || {}; }, /** * @return string[] */ getClasses: function() { var classes = [this.getClass()]; if ('CM_View_Abstract' != this.getClass()) { classes = classes.concat(this.constructor.__super__.getClasses()); } return classes; }, /** * @return String */ getClass: function() { return this._class; }, /** * @param {String} className * @returns Boolean */ hasClass: function(className) { return _.contains(this.getClasses(), className); }, remove: function() { this.trigger('destruct'); this.$el.detach(); // Detach from DOM to prevent reflows when removing children _.each(_.clone(this.getChildren()), function(child) { child.remove(); }); if (this.getParent()) { var siblings = this.getParent().getChildren(); for (var i = 0, sibling; sibling = siblings[i]; i++) { if (sibling.getAutoId() == this.getAutoId()) { siblings.splice(i, 1); } } } delete cm.views[this.getAutoId()]; this.$el.remove(); this.stopListening(); }, /** * @param {jQuery} $html */ replaceWithHtml: function($html) { var parent = this.el.parentNode; parent.replaceChild($html[0], this.el); this.remove(); }, disable: function() { this.$().disable(); }, enable: function() { this.$().enable(); }, /** * @param {String} functionName * @param {Object|Null} [params] * @param {Object|Null} [options] * @return Promise */ ajax: function(functionName, params, options) { options = _.defaults(options || {}, { 'modal': false, 'view': this }); params = params || {}; var handler = this; if (options.modal) { this.disable(); } var promise = cm.ajax('ajax', {viewInfoList: options.view.getViewInfoList(), method: functionName, params: params}) .then(function(response) { if (response.exec) { new Function(response.exec).call(handler); } return response.data; }) .finally(function() { if (options.modal) { handler.enable(); } }); this.on('destruct', function() { promise.cancel(); }); return promise; }, /** * @param {String} functionName * @param {Object|Null} [params] * @param {Object|Null} [options] * @return Promise */ ajaxModal: function(functionName, params, options) { options = _.defaults(options || {}, { 'modal': true }); return this.ajax(functionName, params, options); }, /** * @param {String} className * @param {Object|Null} [params] * @param {Object|Null} [options] * @return Promise */ loadComponent: function(className, params, options) { options = _.defaults(options || {}, { 'modal': true, 'method': 'loadComponent' }); params = params || {}; params.className = className; var self = this; return this.ajax(options.method, params, options) .then(function(response) { return self._injectView(response); }); }, /** * @param {String} className * @param {Object|Null} [params] * @param {Object|Null} [options] * @return Promise */ prepareComponent: function(className, params, options) { return this.loadComponent(className, params, options) .then(function(component) { component._ready(); return component; }); }, /** * @param {String} className * @param {Object|Null} [params] * @param {Object|Null} [options] * @return Promise */ popOutComponent: function(className, params, options) { return this.prepareComponent(className, params, options) .then(function(component) { component.popOut({}, true); return component; }); }, /** * @param {int} actionVerb * @param {int} actionType * @param {String} [channelKey] * @param {Number} [channelType] * @param {Function} callback fn(CM_Action_Abstract action, CM_Model_Abstract model, array data) */ bindAction: function(actionVerb, actionType, channelKey, channelType, callback) { if (!channelKey && !channelType) { if (!cm.options.stream.channel) { return; } channelKey = cm.options.stream.channel.key; channelType = cm.options.stream.channel.type; } var callbackResponse = function(response) { callback.call(this, response.action, response.model, response.data); }; cm.action.bind(actionVerb, actionType, channelKey, channelType, callbackResponse, this); this.on('destruct', function() { cm.action.unbind(actionVerb, actionType, channelKey, channelType, callbackResponse, this); }); }, /** * @param {String} channelKey * @param {Number} channelType * @param {String} event * @param {Function} callback fn(array data) * @param {Boolean} [allowClientMessage] */ bindStream: function(channelKey, channelType, event, callback, allowClientMessage) { cm.stream.bind(channelKey, channelType, event, callback, this, allowClientMessage); this.on('destruct', function() { cm.stream.unbind(channelKey, channelType, event, callback, this); }, this); }, /** * @param {String} channelKey * @param {Number} channelType * @param {String} [event] * @param {Function} [callback] */ unbindStream: function(channelKey, channelType, event, callback) { cm.stream.unbind(channelKey, channelType, event, callback, this); }, /** * @param {String} viewClassName * @param {String} event * @param {Function} callback fn(CM_View_Abstract view, array data) */ bindChildrenEvent: function(viewClassName, event, callback) { cm.viewEvents.bind(this, viewClassName, event, callback, this); this.on('destruct', function() { cm.viewEvents.unbind(this, viewClassName, event, callback, this); }); }, /** * @param {String} event * @param {Function} callback fn(Object data) */ bindAppEvent: function(event, callback) { cm.event.bind(event, callback, this); this.on('destruct', function() { cm.event.unbind(event, callback, this); }); }, /** * @param {Function} callback * @param {Number} interval * @return {Number} */ setInterval: function(callback, interval) { var self = this; var id = window.setInterval(function() { callback.call(self); }, interval); this.on('destruct', function() { window.clearInterval(id); }); return id; }, /** * @param {Function} callback * @param {Number} timeout * @return {Number} */ setTimeout: function(callback, timeout) { var self = this; var id = window.setTimeout(function() { callback.call(self); }, timeout); this.on('destruct', function() { window.clearTimeout(id); }); return id; }, /** * @param {Function} fn * @return {String} */ createGlobalFunction: function(fn) { var self = this; var functionName = 'cm_global_' + cm.getUuid().replace(/-/g, '_'); window[functionName] = function() { fn.apply(self, arguments); }; this.on('destruct', function() { delete window[functionName]; }); return functionName; }, /** * @param {jQuery} $element * @param {String} event * @param {Function} callback */ bindJquery: function($element, event, callback) { var self = this; var callbackWithContext = function() { callback.apply(self, arguments); }; $element.on(event, callbackWithContext); this.on('destruct', function() { $element.off(event, callbackWithContext); }); }, /** * @param {String} key * @param {*} value */ storageSet: function(key, value) { cm.storage.set(this.getClass() + ':' + key, value); }, /** * @param {String} key * @return * */ storageGet: function(key) { return cm.storage.get(this.getClass() + ':' + key); }, /** * @param {String} key */ storageDelete: function(key) { cm.storage.del(this.getClass() + ':' + key); }, /** * @param {String} key * @param {Function} getter * @return {*} */ cacheGet: function(key, getter) { return cm.cache.get(this.getClass() + ':' + key, getter, this); }, /** * @param {String} name * @param {Object} variables * @return {jQuery} */ renderTemplate: function(name, variables) { var template = this.cacheGet('template-' + name, function() { var $template = this.$('> script[type="text/template"].' + name); if (!$template.length) { throw new CM_Exception('Template `' + name + '` does not exist in `' + this.getClass() + '`'); } return $template.html(); }); return cm.template.render(template, variables); }, /** * @param {Function} callback * @returns {Promise} */ try: function(callback) { return Promise.try(callback.bind(this)).bind(this); }, /** * @param {Number} milliseconds * @returns {Promise} */ delay: function(milliseconds) { return Promise.delay(milliseconds).bind(this); }, /** * @param {String} eventName * @param {*} [obj] * @returns {Promise} */ wait: function(eventName, obj) { var observer = new cm.lib.Observer(); var target = obj || this; var promise = new Promise(function(resolve) { observer.listenTo(target, eventName, resolve); }); return promise.finally(function() { observer.stopListening(); observer = null; }); }, /** * @param {Function} callback * @param {String} eventName * @param {*} [obj] */ cancellable: function(callback, eventName, obj) { var target = obj || this; var observer = new cm.lib.Observer(); var promise = null; observer.listenTo(target, eventName, function() { if (promise) { promise.cancel(); } }); promise = callback.apply(this); return promise.finally(function() { observer.stopListening(); observer = null; }); }, /** * @param {Object} actions * @param {String} [channelKey] * @param {Number} [channelType] */ _bindActions: function(actions, channelKey, channelType) { _.each(actions, function(callback, key) { var match = key.match(/^(\S+)\s+(.+)$/); var actionType = cm.action.types[match[1]]; var actionNames = match[2].split(/\s*,\s*/); _.each(actionNames, function(actionVerbName) { this.bindAction(actionVerbName, actionType, channelKey, channelType, callback); }, this); }, this); }, /** * @param {Object} streams */ _bindStreams: function(streams) { if (!cm.options.stream.channel) { return; } _.each(streams, function(callback, key) { this.bindStream(cm.options.stream.channel.key, cm.options.stream.channel.type, this.getClass() + ':' + key, callback); }, this); }, /** * @param {Object} events */ _bindChildrenEvents: function(events) { _.each(events, function(callback, key) { var match = key.match(/^(\S+)\s+(.+)$/); var viewName = match[1]; var eventNames = match[2].split(/\s*,\s*/); _.each(eventNames, function(eventName) { this.bindChildrenEvent(viewName, eventName, callback); }, this); }, this); }, /** * @param {Object} events */ _bindAppEvents: function(events) { _.each(events, function(callback, eventNameStr) { var eventNameList = eventNameStr.split(/[\s]+/); _.each(eventNameList, function(eventName) { this.bindAppEvent(eventName, callback); }, this); }, this); }, /** * @return Object */ _getArray: function() { return { className: this.getClass(), id: this.getAutoId(), params: this.getParams(), parentId: this.getParent() ? this.getParent().getAutoId() : null }; }, /** * @param {Object} response * @return CM_Abstract_View */ _injectView: function(response) { cm.window.appendHidden(response.html); new Function(response.js).call(this); var view = cm.views[response.autoId]; this.registerChild(view); return view; } });
library/CM/View/Abstract.js
/** * @class CM_View_Abstract * @extends Backbone.View */ var CM_View_Abstract = Backbone.View.extend({ _class: 'CM_View_Abstract', /** @type CM_View_Abstract[] **/ _children: [], /** * @param {Object} [options] */ constructor: function(options) { this.options = options || {}; Backbone.View.apply(this, arguments); }, initialize: function() { this._children = []; if (this.getParent()) { this.getParent().registerChild(this); } this.events = this.collectEvents(); if (this.actions) { this._bindActions(this.actions); } if (this.streams) { this._bindStreams(this.streams); } if (this.childrenEvents) { this._bindChildrenEvents(this.childrenEvents); } if (this.appEvents) { this._bindAppEvents(this.appEvents); } this.on('all', function(eventName, data) { cm.viewEvents.trigger.apply(cm.viewEvents, [this].concat(_.toArray(arguments))); }); }, collectEvents: function() { var eventsObjects = [], currentConstructor = this.constructor, currentProto = currentConstructor.prototype; do { if (currentProto.hasOwnProperty('events')) { eventsObjects.unshift(currentProto.events); } } while (currentConstructor = ( currentProto = currentConstructor.__super__ ) && currentProto.constructor); eventsObjects.unshift({}); return _.extend.apply(_, eventsObjects); }, ready: function() { }, _ready: function() { this.ready(); _.each(this.getChildren(), function(child) { child._ready(); }); this.trigger('ready'); }, /** * @param {CM_View_Abstract} child */ registerChild: function(child) { this._children.push(child); child.options.parent = this; }, /** * @param {String|Null} [className] * @return CM_View_Abstract[] */ getChildren: function(className) { if (!className) { return this._children; } return _.filter(this._children, function(child) { return child.hasClass(className); }); }, /** * @param {String} className * @return CM_View_Abstract|null */ findChild: function(className) { return _.find(this.getChildren(), function(child) { return child.hasClass(className); }) || null; }, /** * @param {String} className * @returns {CM_View_Abstract} */ getChild: function(className) { var child = this.findChild(className); if (!child) { throw new Error('Failed to retrieve `' + className + '` child view of `' + this.getClass() + '`.'); } return child; }, /** * @return CM_View_Abstract|null */ getParent: function() { if (this.options.parent) { return this.options.parent; } return null; }, /** * @param {String} className * @return CM_View_Abstract|null */ findParent: function(className) { var parent = this.getParent(); if (!parent) { return null; } if (parent.hasClass(className)) { return parent; } return parent.findParent(className); }, /** * @return CM_View_Abstract|null */ getComponent: function() { if (this.hasClass('CM_Component_Abstract')) { return this; } return this.findParent('CM_Component_Abstract'); }, /** * @returns {{CM_Component_Abstract: Object|null, CM_View_Abstract: Object}} */ getViewInfoList: function() { var viewInfoList = { CM_Component_Abstract: null, CM_View_Abstract: this._getArray() }; var component = this.getComponent(); if (component) { viewInfoList.CM_Component_Abstract = component._getArray(); } return viewInfoList; }, /** * @return String */ getAutoId: function() { if (!this.el.id) { this.el.id = cm.getUuid(); } return this.el.id; }, /** * @return Object */ getParams: function() { return this.options.params || {}; }, /** * @return string[] */ getClasses: function() { var classes = [this.getClass()]; if ('CM_View_Abstract' != this.getClass()) { classes = classes.concat(this.constructor.__super__.getClasses()); } return classes; }, /** * @return String */ getClass: function() { return this._class; }, /** * @param {String} className * @returns Boolean */ hasClass: function(className) { return _.contains(this.getClasses(), className); }, remove: function() { this.trigger('destruct'); this.$el.detach(); // Detach from DOM to prevent reflows when removing children _.each(_.clone(this.getChildren()), function(child) { child.remove(); }); if (this.getParent()) { var siblings = this.getParent().getChildren(); for (var i = 0, sibling; sibling = siblings[i]; i++) { if (sibling.getAutoId() == this.getAutoId()) { siblings.splice(i, 1); } } } delete cm.views[this.getAutoId()]; this.$el.remove(); this.stopListening(); }, /** * @param {jQuery} $html */ replaceWithHtml: function($html) { var $parent = this.$el.parent(); var $next = this.$el.next(); cm.window.appendHidden(this.$el); if ($next.length) { $next.before($html); } else { $parent.append($html); } this.remove(); }, disable: function() { this.$().disable(); }, enable: function() { this.$().enable(); }, /** * @param {String} functionName * @param {Object|Null} [params] * @param {Object|Null} [options] * @return Promise */ ajax: function(functionName, params, options) { options = _.defaults(options || {}, { 'modal': false, 'view': this }); params = params || {}; var handler = this; if (options.modal) { this.disable(); } var promise = cm.ajax('ajax', {viewInfoList: options.view.getViewInfoList(), method: functionName, params: params}) .then(function(response) { if (response.exec) { new Function(response.exec).call(handler); } return response.data; }) .finally(function() { if (options.modal) { handler.enable(); } }); this.on('destruct', function() { promise.cancel(); }); return promise; }, /** * @param {String} functionName * @param {Object|Null} [params] * @param {Object|Null} [options] * @return Promise */ ajaxModal: function(functionName, params, options) { options = _.defaults(options || {}, { 'modal': true }); return this.ajax(functionName, params, options); }, /** * @param {String} className * @param {Object|Null} [params] * @param {Object|Null} [options] * @return Promise */ loadComponent: function(className, params, options) { options = _.defaults(options || {}, { 'modal': true, 'method': 'loadComponent' }); params = params || {}; params.className = className; var self = this; return this.ajax(options.method, params, options) .then(function(response) { return self._injectView(response); }); }, /** * @param {String} className * @param {Object|Null} [params] * @param {Object|Null} [options] * @return Promise */ prepareComponent: function(className, params, options) { return this.loadComponent(className, params, options) .then(function(component) { component._ready(); return component; }); }, /** * @param {String} className * @param {Object|Null} [params] * @param {Object|Null} [options] * @return Promise */ popOutComponent: function(className, params, options) { return this.prepareComponent(className, params, options) .then(function(component) { component.popOut({}, true); return component; }); }, /** * @param {int} actionVerb * @param {int} actionType * @param {String} [channelKey] * @param {Number} [channelType] * @param {Function} callback fn(CM_Action_Abstract action, CM_Model_Abstract model, array data) */ bindAction: function(actionVerb, actionType, channelKey, channelType, callback) { if (!channelKey && !channelType) { if (!cm.options.stream.channel) { return; } channelKey = cm.options.stream.channel.key; channelType = cm.options.stream.channel.type; } var callbackResponse = function(response) { callback.call(this, response.action, response.model, response.data); }; cm.action.bind(actionVerb, actionType, channelKey, channelType, callbackResponse, this); this.on('destruct', function() { cm.action.unbind(actionVerb, actionType, channelKey, channelType, callbackResponse, this); }); }, /** * @param {String} channelKey * @param {Number} channelType * @param {String} event * @param {Function} callback fn(array data) * @param {Boolean} [allowClientMessage] */ bindStream: function(channelKey, channelType, event, callback, allowClientMessage) { cm.stream.bind(channelKey, channelType, event, callback, this, allowClientMessage); this.on('destruct', function() { cm.stream.unbind(channelKey, channelType, event, callback, this); }, this); }, /** * @param {String} channelKey * @param {Number} channelType * @param {String} [event] * @param {Function} [callback] */ unbindStream: function(channelKey, channelType, event, callback) { cm.stream.unbind(channelKey, channelType, event, callback, this); }, /** * @param {String} viewClassName * @param {String} event * @param {Function} callback fn(CM_View_Abstract view, array data) */ bindChildrenEvent: function(viewClassName, event, callback) { cm.viewEvents.bind(this, viewClassName, event, callback, this); this.on('destruct', function() { cm.viewEvents.unbind(this, viewClassName, event, callback, this); }); }, /** * @param {String} event * @param {Function} callback fn(Object data) */ bindAppEvent: function(event, callback) { cm.event.bind(event, callback, this); this.on('destruct', function() { cm.event.unbind(event, callback, this); }); }, /** * @param {Function} callback * @param {Number} interval * @return {Number} */ setInterval: function(callback, interval) { var self = this; var id = window.setInterval(function() { callback.call(self); }, interval); this.on('destruct', function() { window.clearInterval(id); }); return id; }, /** * @param {Function} callback * @param {Number} timeout * @return {Number} */ setTimeout: function(callback, timeout) { var self = this; var id = window.setTimeout(function() { callback.call(self); }, timeout); this.on('destruct', function() { window.clearTimeout(id); }); return id; }, /** * @param {Function} fn * @return {String} */ createGlobalFunction: function(fn) { var self = this; var functionName = 'cm_global_' + cm.getUuid().replace(/-/g, '_'); window[functionName] = function() { fn.apply(self, arguments); }; this.on('destruct', function() { delete window[functionName]; }); return functionName; }, /** * @param {jQuery} $element * @param {String} event * @param {Function} callback */ bindJquery: function($element, event, callback) { var self = this; var callbackWithContext = function() { callback.apply(self, arguments); }; $element.on(event, callbackWithContext); this.on('destruct', function() { $element.off(event, callbackWithContext); }); }, /** * @param {String} key * @param {*} value */ storageSet: function(key, value) { cm.storage.set(this.getClass() + ':' + key, value); }, /** * @param {String} key * @return * */ storageGet: function(key) { return cm.storage.get(this.getClass() + ':' + key); }, /** * @param {String} key */ storageDelete: function(key) { cm.storage.del(this.getClass() + ':' + key); }, /** * @param {String} key * @param {Function} getter * @return {*} */ cacheGet: function(key, getter) { return cm.cache.get(this.getClass() + ':' + key, getter, this); }, /** * @param {String} name * @param {Object} variables * @return {jQuery} */ renderTemplate: function(name, variables) { var template = this.cacheGet('template-' + name, function() { var $template = this.$('> script[type="text/template"].' + name); if (!$template.length) { throw new CM_Exception('Template `' + name + '` does not exist in `' + this.getClass() + '`'); } return $template.html(); }); return cm.template.render(template, variables); }, /** * @param {Function} callback * @returns {Promise} */ try: function(callback) { return Promise.try(callback.bind(this)).bind(this); }, /** * @param {Number} milliseconds * @returns {Promise} */ delay: function(milliseconds) { return Promise.delay(milliseconds).bind(this); }, /** * @param {String} eventName * @param {*} [obj] * @returns {Promise} */ wait: function(eventName, obj) { var observer = new cm.lib.Observer(); var target = obj || this; var promise = new Promise(function(resolve) { observer.listenTo(target, eventName, resolve); }); return promise.finally(function() { observer.stopListening(); observer = null; }); }, /** * @param {Function} callback * @param {String} eventName * @param {*} [obj] */ cancellable: function(callback, eventName, obj) { var target = obj || this; var observer = new cm.lib.Observer(); var promise = null; observer.listenTo(target, eventName, function() { if (promise) { promise.cancel(); } }); promise = callback.apply(this); return promise.finally(function() { observer.stopListening(); observer = null; }); }, /** * @param {Object} actions * @param {String} [channelKey] * @param {Number} [channelType] */ _bindActions: function(actions, channelKey, channelType) { _.each(actions, function(callback, key) { var match = key.match(/^(\S+)\s+(.+)$/); var actionType = cm.action.types[match[1]]; var actionNames = match[2].split(/\s*,\s*/); _.each(actionNames, function(actionVerbName) { this.bindAction(actionVerbName, actionType, channelKey, channelType, callback); }, this); }, this); }, /** * @param {Object} streams */ _bindStreams: function(streams) { if (!cm.options.stream.channel) { return; } _.each(streams, function(callback, key) { this.bindStream(cm.options.stream.channel.key, cm.options.stream.channel.type, this.getClass() + ':' + key, callback); }, this); }, /** * @param {Object} events */ _bindChildrenEvents: function(events) { _.each(events, function(callback, key) { var match = key.match(/^(\S+)\s+(.+)$/); var viewName = match[1]; var eventNames = match[2].split(/\s*,\s*/); _.each(eventNames, function(eventName) { this.bindChildrenEvent(viewName, eventName, callback); }, this); }, this); }, /** * @param {Object} events */ _bindAppEvents: function(events) { _.each(events, function(callback, eventNameStr) { var eventNameList = eventNameStr.split(/[\s]+/); _.each(eventNameList, function(eventName) { this.bindAppEvent(eventName, callback); }, this); }, this); }, /** * @return Object */ _getArray: function() { return { className: this.getClass(), id: this.getAutoId(), params: this.getParams(), parentId: this.getParent() ? this.getParent().getAutoId() : null }; }, /** * @param {Object} response * @return CM_Abstract_View */ _injectView: function(response) { cm.window.appendHidden(response.html); new Function(response.js).call(this); var view = cm.views[response.autoId]; this.registerChild(view); return view; } });
Use Node.replaceChild in CM_View_Abstract.replaceWithHtml
library/CM/View/Abstract.js
Use Node.replaceChild in CM_View_Abstract.replaceWithHtml
<ide><path>ibrary/CM/View/Abstract.js <ide> * @param {jQuery} $html <ide> */ <ide> replaceWithHtml: function($html) { <del> var $parent = this.$el.parent(); <del> var $next = this.$el.next(); <del> cm.window.appendHidden(this.$el); <del> if ($next.length) { <del> $next.before($html); <del> } else { <del> $parent.append($html); <del> } <add> var parent = this.el.parentNode; <add> parent.replaceChild($html[0], this.el); <ide> this.remove(); <ide> }, <ide>
JavaScript
mit
67f8264433889f2f49e4f23502fa70f3cc62afc2
0
kmerhi/artifactoid
#!/usr/bin/env node const open = require('open'); const yargs = require('yargs'); /* istanbul ignore next */ yargs.version() .usage('Usage: artifactoid <command> [options]') .command(['get <uri>', 'g', '*'], 'Get latest download URI for given path', require('./cmds/get')) // .command(['upload <uri>', 'push'], 'Upload the latest download URI for given path', require('./cmds/push')) .command(['docs'], 'Go to the documentation at github.com/kmerhi/artifactoid', {}, () => open('https://github.com/kmerhi/artifactoid#readme')) .demandCommand(1, 'You need at least one command before moving on') .help('h') .alias('h', 'help') .options({ 'u': { alias: 'user', describe: 'User to connect to Artifactory repo', type: 'string' }, 'p': { alias: 'pass', describe: 'Password (or API key) for basic auth', type: 'string' }, 's': { alias: 'snip', describe: 'Return relative path', type: 'boolean' }, }) .epilogue('For more information, go to https://github.com/kmerhi/artifactoid') .argv;
src/cli.js
#!/usr/bin/env node const open = require('open'); const yargs = require('yargs'); /* istanbul ignore next */ yargs.version() .usage('Usage: artifactoid <command> [options]') .command(['get <uri>', 'g', '*'], 'Get latest download URI for given path', require('./cmds/get')) // .command(['upload <uri>', 'push'], 'Upload the latest download URI for given path', require('./cmds/push')) .command(['docs'], 'Go to the documentation at github.com/kmerhi/artifactoid', {}, () => open('https://github.com/kmerhi/artifactoid#readme')) .demandCommand(1, 'You need at least one command before moving on') .help('h') .alias('h', 'help') .describe('u', 'User to connect to Artifactory repo') .alias('u', 'user') .describe('p', 'Password (or API key) for basic auth') .alias('p', 'pass') .epilogue('For more information, go to https://github.com/kmerhi/artifactoid') .argv;
clean up options
src/cli.js
clean up options
<ide><path>rc/cli.js <ide> .demandCommand(1, 'You need at least one command before moving on') <ide> .help('h') <ide> .alias('h', 'help') <del> .describe('u', 'User to connect to Artifactory repo') <del> .alias('u', 'user') <del> .describe('p', 'Password (or API key) for basic auth') <del> .alias('p', 'pass') <add> .options({ <add> 'u': { <add> alias: 'user', <add> describe: 'User to connect to Artifactory repo', <add> type: 'string' <add> }, <add> 'p': { <add> alias: 'pass', <add> describe: 'Password (or API key) for basic auth', <add> type: 'string' <add> }, <add> 's': { <add> alias: 'snip', <add> describe: 'Return relative path', <add> type: 'boolean' <add> }, <add> }) <ide> .epilogue('For more information, go to https://github.com/kmerhi/artifactoid') <ide> .argv;
Java
epl-1.0
5e9f1a8ba0ad6df8f23410dca06aaaf49a2733bd
0
opendaylight/netvirt,opendaylight/netvirt,opendaylight/netvirt,opendaylight/netvirt,opendaylight/netvirt
/* * Copyright (c) 2016, 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.netvirt.neutronvpn; import com.google.common.base.Optional; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Singleton; import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.genius.datastoreutils.AsyncDataTreeChangeListenerBase; import org.opendaylight.genius.mdsalutil.MDSALUtil; import org.opendaylight.netvirt.elanmanager.api.IElanService; import org.opendaylight.netvirt.neutronvpn.api.utils.NeutronUtils; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeBase; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegmentsBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ProviderTypes; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeBase; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeFlat; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeVlan; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeVxlan; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.Networks; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.NetworkProviderExtension; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.neutron.networks.network.Segments; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class NeutronNetworkChangeListener extends AsyncDataTreeChangeListenerBase<Network, NeutronNetworkChangeListener> { private static final Logger LOG = LoggerFactory.getLogger(NeutronNetworkChangeListener.class); private final DataBroker dataBroker; private final NeutronvpnManager nvpnManager; private final NeutronvpnNatManager nvpnNatManager; private final IElanService elanService; private final NeutronvpnUtils neutronvpnUtils; @Inject public NeutronNetworkChangeListener(final DataBroker dataBroker, final NeutronvpnManager neutronvpnManager, final NeutronvpnNatManager neutronvpnNatManager, final IElanService elanService, final NeutronvpnUtils neutronvpnUtils) { super(Network.class, NeutronNetworkChangeListener.class); this.dataBroker = dataBroker; nvpnManager = neutronvpnManager; nvpnNatManager = neutronvpnNatManager; this.elanService = elanService; this.neutronvpnUtils = neutronvpnUtils; } @Override @PostConstruct public void init() { LOG.info("{} init", getClass().getSimpleName()); registerListener(LogicalDatastoreType.CONFIGURATION, dataBroker); } @Override protected InstanceIdentifier<Network> getWildCardPath() { return InstanceIdentifier.create(Neutron.class).child(Networks.class).child(Network.class); } @Override protected NeutronNetworkChangeListener getDataTreeChangeListener() { return NeutronNetworkChangeListener.this; } @Override protected void add(InstanceIdentifier<Network> identifier, Network input) { LOG.trace("Adding Network : key: {}, value={}", identifier, input); String networkId = input.getUuid().getValue(); if (!NeutronvpnUtils.isNetworkTypeSupported(input)) { LOG.error("Neutronvpn doesn't support the provider type for given network {}", networkId); return; } Class<? extends NetworkTypeBase> networkType = input.getAugmentation(NetworkProviderExtension.class) .getNetworkType(); if (NeutronvpnUtils.isVlanOrVxlanNetwork(networkType) && NeutronUtils.getSegmentationIdFromNeutronNetwork(input, networkType) == null) { LOG.error("Segmentation ID is null for configured provider network {} of type {}. Abandoning any further " + "processing for the network", input.getUuid().getValue(), networkType); return; } neutronvpnUtils.addToNetworkCache(input); // Create ELAN instance for this network ElanInstance elanInstance = createElanInstance(input); if (NeutronvpnUtils.getIsExternal(input)) { // Create ELAN interface and IETF interfaces for the physical network elanService.createExternalElanNetwork(elanInstance); ProviderTypes providerNwType = NeutronvpnUtils.getProviderNetworkType(input); if (providerNwType == null) { LOG.error("Unable to get Network Provider Type for network {}", networkId); return; } LOG.trace("External Network Provider Type for network {} is {}", networkId, providerNwType.getName()); nvpnNatManager.addExternalNetwork(input); if (NeutronvpnUtils.isFlatOrVlanNetwork(input)) { nvpnManager.createL3InternalVpn(input.getUuid(), null, null, null, null, null, null, null); nvpnManager.createExternalVpnInterfaces(input.getUuid()); } } } @Override protected void remove(InstanceIdentifier<Network> identifier, Network input) { LOG.trace("Removing Network : key: {}, value={}", identifier, input); if (NeutronvpnUtils.getIsExternal(input)) { if (NeutronvpnUtils.isFlatOrVlanNetwork(input)) { nvpnManager.removeExternalVpnInterfaces(input.getUuid()); nvpnManager.removeVpn(input.getUuid()); } nvpnNatManager.removeExternalNetwork(input); } //Delete ELAN instance for this network String elanInstanceName = input.getUuid().getValue(); ElanInstance elanInstance = elanService.getElanInstance(elanInstanceName); if (elanInstance != null) { elanService.deleteExternalElanNetwork(elanInstance); deleteElanInstance(elanInstanceName); } neutronvpnUtils.removeFromNetworkCache(input); } @Override protected void update(InstanceIdentifier<Network> identifier, Network original, Network update) { LOG.trace("Updating Network : key: {}, original value={}, update value={}", identifier, original, update); neutronvpnUtils.addToNetworkCache(update); String elanInstanceName = original.getUuid().getValue(); Class<? extends SegmentTypeBase> origSegmentType = NeutronvpnUtils.getSegmentTypeFromNeutronNetwork(original); String origSegmentationId = NeutronvpnUtils.getSegmentationIdFromNeutronNetwork(original); String origPhysicalNetwork = NeutronvpnUtils.getPhysicalNetworkName(original); Class<? extends SegmentTypeBase> updateSegmentType = NeutronvpnUtils.getSegmentTypeFromNeutronNetwork(update); String updateSegmentationId = NeutronvpnUtils.getSegmentationIdFromNeutronNetwork(update); String updatePhysicalNetwork = NeutronvpnUtils.getPhysicalNetworkName(update); Boolean origExternal = NeutronvpnUtils.getIsExternal(original); Boolean updateExternal = NeutronvpnUtils.getIsExternal(update); Boolean origIsFlatOrVlanNetwork = NeutronvpnUtils.isFlatOrVlanNetwork(original); Boolean updateIsFlatOrVlanNetwork = NeutronvpnUtils.isFlatOrVlanNetwork(update); if (!Objects.equals(origSegmentType, updateSegmentType) || !Objects.equals(origSegmentationId, updateSegmentationId) || !Objects.equals(origPhysicalNetwork, updatePhysicalNetwork) || !Objects.equals(origExternal, updateExternal)) { if (origExternal && origIsFlatOrVlanNetwork && (!updateExternal || !updateIsFlatOrVlanNetwork)) { nvpnManager.removeExternalVpnInterfaces(original.getUuid()); nvpnManager.removeVpn(original.getUuid()); nvpnNatManager.removeExternalNetwork(original); } ElanInstance elanInstance = elanService.getElanInstance(elanInstanceName); if (elanInstance != null) { elanService.deleteExternalElanNetwork(elanInstance); elanInstance = updateElanInstance(elanInstanceName, updateSegmentType, updateSegmentationId, updatePhysicalNetwork, update); if (updateExternal) { elanService.updateExternalElanNetwork(elanInstance); } } if (updateExternal && updateIsFlatOrVlanNetwork && !origExternal) { nvpnNatManager.addExternalNetwork(update); nvpnManager.createL3InternalVpn(update.getUuid(), null, null, null, null, null, null, null); nvpnManager.createExternalVpnInterfaces(update.getUuid()); } } } @Nonnull private List<ElanSegments> buildSegments(Network input) { NetworkProviderExtension providerExtension = input.getAugmentation(NetworkProviderExtension.class); if (providerExtension == null || providerExtension.getSegments() == null) { return Collections.emptyList(); } return providerExtension.getSegments().stream() .map(segment -> new ElanSegmentsBuilder() .setSegmentationIndex(segment.getSegmentationIndex()) .setSegmentationId(getSegmentationId(input, segment)) .setSegmentType(elanSegmentTypeFromNetworkType(segment.getNetworkType())) .build()) .collect(Collectors.toList()); } private Long getSegmentationId(Network network, Segments segment) { try { if (segment.getSegmentationId() != null) { return Long.valueOf(segment.getSegmentationId()); } } catch (NumberFormatException error) { LOG.error("Failed to get the segment id for network {}", network); } return 0L; } private Class<? extends SegmentTypeBase> elanSegmentTypeFromNetworkType( Class<? extends NetworkTypeBase> networkType) { if (networkType == null) { return null; } if (networkType.isAssignableFrom(NetworkTypeVxlan.class)) { return SegmentTypeVxlan.class; } else if (networkType.isAssignableFrom(NetworkTypeVlan.class)) { return SegmentTypeVlan.class; } else if (networkType.isAssignableFrom(NetworkTypeFlat.class)) { return SegmentTypeFlat.class; } return null; } private ElanInstance createElanInstance(Network input) { String elanInstanceName = input.getUuid().getValue(); InstanceIdentifier<ElanInstance> id = createElanInstanceIdentifier(elanInstanceName); Optional<ElanInstance> existingElanInstance = MDSALUtil.read(dataBroker, LogicalDatastoreType.CONFIGURATION, id); if (existingElanInstance.isPresent()) { return existingElanInstance.get(); } Class<? extends SegmentTypeBase> segmentType = NeutronvpnUtils.getSegmentTypeFromNeutronNetwork(input); String segmentationId = NeutronvpnUtils.getSegmentationIdFromNeutronNetwork(input); String physicalNetworkName = NeutronvpnUtils.getPhysicalNetworkName(input); long elanTag = elanService.retrieveNewElanTag(elanInstanceName); ElanInstance elanInstance = createElanInstanceBuilder(elanInstanceName, segmentType, segmentationId, physicalNetworkName, input).setElanTag(elanTag).build(); MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION, id, elanInstance); LOG.debug("ELANInstance {} created with elan tag {} and segmentation ID {}", elanInstanceName, elanTag, segmentationId); return elanInstance; } private ElanInstanceBuilder createElanInstanceBuilder(String elanInstanceName, Class<? extends SegmentTypeBase> segmentType, String segmentationId, String physicalNetworkName, Network network) { Boolean isExternal = NeutronvpnUtils.getIsExternal(network); List<ElanSegments> segments = buildSegments(network); ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName); if (segmentType != null) { elanInstanceBuilder.setSegmentType(segmentType); if (segmentationId != null) { elanInstanceBuilder.setSegmentationId(Long.valueOf(segmentationId)); } if (physicalNetworkName != null) { elanInstanceBuilder.setPhysicalNetworkName(physicalNetworkName); } } elanInstanceBuilder.setElanSegments(segments); elanInstanceBuilder.setExternal(isExternal); elanInstanceBuilder.setKey(new ElanInstanceKey(elanInstanceName)); return elanInstanceBuilder; } private void deleteElanInstance(String elanInstanceName) { InstanceIdentifier<ElanInstance> id = createElanInstanceIdentifier(elanInstanceName); MDSALUtil.syncDelete(dataBroker, LogicalDatastoreType.CONFIGURATION, id); LOG.debug("ELANInstance {} deleted", elanInstanceName); } private ElanInstance updateElanInstance(String elanInstanceName, Class<? extends SegmentTypeBase> segmentType, String segmentationId, String physicalNetworkName, Network network) { ElanInstance elanInstance = createElanInstanceBuilder(elanInstanceName, segmentType, segmentationId, physicalNetworkName, network).build(); InstanceIdentifier<ElanInstance> id = createElanInstanceIdentifier(elanInstanceName); MDSALUtil.syncUpdate(dataBroker, LogicalDatastoreType.CONFIGURATION, id, elanInstance); return elanInstance; } private InstanceIdentifier<ElanInstance> createElanInstanceIdentifier(String elanInstanceName) { InstanceIdentifier<ElanInstance> id = InstanceIdentifier.builder(ElanInstances.class) .child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build(); return id; } }
neutronvpn/impl/src/main/java/org/opendaylight/netvirt/neutronvpn/NeutronNetworkChangeListener.java
/* * Copyright (c) 2016, 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.netvirt.neutronvpn; import com.google.common.base.Optional; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Singleton; import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.genius.datastoreutils.AsyncDataTreeChangeListenerBase; import org.opendaylight.genius.mdsalutil.MDSALUtil; import org.opendaylight.netvirt.elanmanager.api.IElanService; import org.opendaylight.netvirt.neutronvpn.api.utils.NeutronUtils; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.ElanInstances; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeBase; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeFlat; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVlan; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.SegmentTypeVxlan; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstance; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.ElanInstanceKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegments; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.elan.rev150602.elan.instances.elan.instance.ElanSegmentsBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ProviderTypes; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeBase; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeFlat; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeVlan; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeVxlan; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.Networks; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.NetworkProviderExtension; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class NeutronNetworkChangeListener extends AsyncDataTreeChangeListenerBase<Network, NeutronNetworkChangeListener> { private static final Logger LOG = LoggerFactory.getLogger(NeutronNetworkChangeListener.class); private final DataBroker dataBroker; private final NeutronvpnManager nvpnManager; private final NeutronvpnNatManager nvpnNatManager; private final IElanService elanService; private final NeutronvpnUtils neutronvpnUtils; @Inject public NeutronNetworkChangeListener(final DataBroker dataBroker, final NeutronvpnManager neutronvpnManager, final NeutronvpnNatManager neutronvpnNatManager, final IElanService elanService, final NeutronvpnUtils neutronvpnUtils) { super(Network.class, NeutronNetworkChangeListener.class); this.dataBroker = dataBroker; nvpnManager = neutronvpnManager; nvpnNatManager = neutronvpnNatManager; this.elanService = elanService; this.neutronvpnUtils = neutronvpnUtils; } @Override @PostConstruct public void init() { LOG.info("{} init", getClass().getSimpleName()); registerListener(LogicalDatastoreType.CONFIGURATION, dataBroker); } @Override protected InstanceIdentifier<Network> getWildCardPath() { return InstanceIdentifier.create(Neutron.class).child(Networks.class).child(Network.class); } @Override protected NeutronNetworkChangeListener getDataTreeChangeListener() { return NeutronNetworkChangeListener.this; } @Override protected void add(InstanceIdentifier<Network> identifier, Network input) { LOG.trace("Adding Network : key: {}, value={}", identifier, input); String networkId = input.getUuid().getValue(); if (!NeutronvpnUtils.isNetworkTypeSupported(input)) { LOG.error("Neutronvpn doesn't support the provider type for given network {}", networkId); return; } Class<? extends NetworkTypeBase> networkType = input.getAugmentation(NetworkProviderExtension.class) .getNetworkType(); if (NeutronvpnUtils.isVlanOrVxlanNetwork(networkType) && NeutronUtils.getSegmentationIdFromNeutronNetwork(input, networkType) == null) { LOG.error("Segmentation ID is null for configured provider network {} of type {}. Abandoning any further " + "processing for the network", input.getUuid().getValue(), networkType); return; } neutronvpnUtils.addToNetworkCache(input); // Create ELAN instance for this network ElanInstance elanInstance = createElanInstance(input); if (NeutronvpnUtils.getIsExternal(input)) { // Create ELAN interface and IETF interfaces for the physical network elanService.createExternalElanNetwork(elanInstance); ProviderTypes providerNwType = NeutronvpnUtils.getProviderNetworkType(input); if (providerNwType == null) { LOG.error("Unable to get Network Provider Type for network {}", networkId); return; } LOG.trace("External Network Provider Type for network {} is {}", networkId, providerNwType.getName()); nvpnNatManager.addExternalNetwork(input); if (NeutronvpnUtils.isFlatOrVlanNetwork(input)) { nvpnManager.createL3InternalVpn(input.getUuid(), null, null, null, null, null, null, null); nvpnManager.createExternalVpnInterfaces(input.getUuid()); } } } @Override protected void remove(InstanceIdentifier<Network> identifier, Network input) { LOG.trace("Removing Network : key: {}, value={}", identifier, input); if (NeutronvpnUtils.getIsExternal(input)) { if (NeutronvpnUtils.isFlatOrVlanNetwork(input)) { nvpnManager.removeExternalVpnInterfaces(input.getUuid()); nvpnManager.removeVpn(input.getUuid()); } nvpnNatManager.removeExternalNetwork(input); } //Delete ELAN instance for this network String elanInstanceName = input.getUuid().getValue(); ElanInstance elanInstance = elanService.getElanInstance(elanInstanceName); if (elanInstance != null) { elanService.deleteExternalElanNetwork(elanInstance); deleteElanInstance(elanInstanceName); } neutronvpnUtils.removeFromNetworkCache(input); } @Override protected void update(InstanceIdentifier<Network> identifier, Network original, Network update) { LOG.trace("Updating Network : key: {}, original value={}, update value={}", identifier, original, update); neutronvpnUtils.addToNetworkCache(update); String elanInstanceName = original.getUuid().getValue(); Class<? extends SegmentTypeBase> origSegmentType = NeutronvpnUtils.getSegmentTypeFromNeutronNetwork(original); String origSegmentationId = NeutronvpnUtils.getSegmentationIdFromNeutronNetwork(original); String origPhysicalNetwork = NeutronvpnUtils.getPhysicalNetworkName(original); Class<? extends SegmentTypeBase> updateSegmentType = NeutronvpnUtils.getSegmentTypeFromNeutronNetwork(update); String updateSegmentationId = NeutronvpnUtils.getSegmentationIdFromNeutronNetwork(update); String updatePhysicalNetwork = NeutronvpnUtils.getPhysicalNetworkName(update); Boolean origExternal = NeutronvpnUtils.getIsExternal(original); Boolean updateExternal = NeutronvpnUtils.getIsExternal(update); Boolean origIsFlatOrVlanNetwork = NeutronvpnUtils.isFlatOrVlanNetwork(original); Boolean updateIsFlatOrVlanNetwork = NeutronvpnUtils.isFlatOrVlanNetwork(update); if (!Objects.equals(origSegmentType, updateSegmentType) || !Objects.equals(origSegmentationId, updateSegmentationId) || !Objects.equals(origPhysicalNetwork, updatePhysicalNetwork) || !Objects.equals(origExternal, updateExternal)) { if (origExternal && origIsFlatOrVlanNetwork && (!updateExternal || !updateIsFlatOrVlanNetwork)) { nvpnManager.removeExternalVpnInterfaces(original.getUuid()); nvpnManager.removeVpn(original.getUuid()); nvpnNatManager.removeExternalNetwork(original); } ElanInstance elanInstance = elanService.getElanInstance(elanInstanceName); if (elanInstance != null) { elanService.deleteExternalElanNetwork(elanInstance); elanInstance = updateElanInstance(elanInstanceName, updateSegmentType, updateSegmentationId, updatePhysicalNetwork, update); if (updateExternal) { elanService.updateExternalElanNetwork(elanInstance); } } if (updateExternal && updateIsFlatOrVlanNetwork && !origExternal) { nvpnNatManager.addExternalNetwork(update); nvpnManager.createL3InternalVpn(update.getUuid(), null, null, null, null, null, null, null); nvpnManager.createExternalVpnInterfaces(update.getUuid()); } } } @Nonnull private List<ElanSegments> buildSegments(Network input) { Long numSegments = NeutronUtils.getNumberSegmentsFromNeutronNetwork(input); List<ElanSegments> segments = new ArrayList<>(); for (long index = 1L; index <= numSegments; index++) { ElanSegmentsBuilder elanSegmentsBuilder = new ElanSegmentsBuilder(); elanSegmentsBuilder.setSegmentationId(0L); if (NeutronUtils.getSegmentationIdFromNeutronNetworkSegment(input, index) != null) { try { elanSegmentsBuilder.setSegmentationId( Long.valueOf(NeutronUtils.getSegmentationIdFromNeutronNetworkSegment(input, index))); } catch (NumberFormatException error) { LOG.error("Failed to get the segment id for network {}", input); } } if (NeutronUtils.isNetworkSegmentType(input, index, NetworkTypeVxlan.class)) { elanSegmentsBuilder.setSegmentType(SegmentTypeVxlan.class); } else if (NeutronUtils.isNetworkSegmentType(input, index, NetworkTypeVlan.class)) { elanSegmentsBuilder.setSegmentType(SegmentTypeVlan.class); } else if (NeutronUtils.isNetworkSegmentType(input, index, NetworkTypeFlat.class)) { elanSegmentsBuilder.setSegmentType(SegmentTypeFlat.class); } elanSegmentsBuilder.setSegmentationIndex(index); segments.add(elanSegmentsBuilder.build()); LOG.debug("Added segment {} to ELANInstance", segments.get((int) index - 1)); } return segments; } private ElanInstance createElanInstance(Network input) { String elanInstanceName = input.getUuid().getValue(); InstanceIdentifier<ElanInstance> id = createElanInstanceIdentifier(elanInstanceName); Optional<ElanInstance> existingElanInstance = MDSALUtil.read(dataBroker, LogicalDatastoreType.CONFIGURATION, id); if (existingElanInstance.isPresent()) { return existingElanInstance.get(); } Class<? extends SegmentTypeBase> segmentType = NeutronvpnUtils.getSegmentTypeFromNeutronNetwork(input); String segmentationId = NeutronvpnUtils.getSegmentationIdFromNeutronNetwork(input); String physicalNetworkName = NeutronvpnUtils.getPhysicalNetworkName(input); long elanTag = elanService.retrieveNewElanTag(elanInstanceName); ElanInstance elanInstance = createElanInstanceBuilder(elanInstanceName, segmentType, segmentationId, physicalNetworkName, input).setElanTag(elanTag).build(); MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION, id, elanInstance); LOG.debug("ELANInstance {} created with elan tag {} and segmentation ID {}", elanInstanceName, elanTag, segmentationId); return elanInstance; } private ElanInstanceBuilder createElanInstanceBuilder(String elanInstanceName, Class<? extends SegmentTypeBase> segmentType, String segmentationId, String physicalNetworkName, Network network) { Boolean isExternal = NeutronvpnUtils.getIsExternal(network); List<ElanSegments> segments = buildSegments(network); ElanInstanceBuilder elanInstanceBuilder = new ElanInstanceBuilder().setElanInstanceName(elanInstanceName); if (segmentType != null) { elanInstanceBuilder.setSegmentType(segmentType); if (segmentationId != null) { elanInstanceBuilder.setSegmentationId(Long.valueOf(segmentationId)); } if (physicalNetworkName != null) { elanInstanceBuilder.setPhysicalNetworkName(physicalNetworkName); } } elanInstanceBuilder.setElanSegments(segments); elanInstanceBuilder.setExternal(isExternal); elanInstanceBuilder.setKey(new ElanInstanceKey(elanInstanceName)); return elanInstanceBuilder; } private void deleteElanInstance(String elanInstanceName) { InstanceIdentifier<ElanInstance> id = createElanInstanceIdentifier(elanInstanceName); MDSALUtil.syncDelete(dataBroker, LogicalDatastoreType.CONFIGURATION, id); LOG.debug("ELANInstance {} deleted", elanInstanceName); } private ElanInstance updateElanInstance(String elanInstanceName, Class<? extends SegmentTypeBase> segmentType, String segmentationId, String physicalNetworkName, Network network) { ElanInstance elanInstance = createElanInstanceBuilder(elanInstanceName, segmentType, segmentationId, physicalNetworkName, network).build(); InstanceIdentifier<ElanInstance> id = createElanInstanceIdentifier(elanInstanceName); MDSALUtil.syncUpdate(dataBroker, LogicalDatastoreType.CONFIGURATION, id, elanInstance); return elanInstance; } private InstanceIdentifier<ElanInstance> createElanInstanceIdentifier(String elanInstanceName) { InstanceIdentifier<ElanInstance> id = InstanceIdentifier.builder(ElanInstances.class) .child(ElanInstance.class, new ElanInstanceKey(elanInstanceName)).build(); return id; } }
NETVIRT-1227 : Refactoring segment creation For multisegment network , the code is unnecessarly using multiple loops and varibles , increasing the probability of NP and ArrayIndexOutOfBoundExceptions. Hence refactoring the code. Change-Id: I6022813925096d9b02f5cb14fb92918445dd04db Signed-off-by: eaksahu <[email protected]>
neutronvpn/impl/src/main/java/org/opendaylight/netvirt/neutronvpn/NeutronNetworkChangeListener.java
NETVIRT-1227 : Refactoring segment creation
<ide><path>eutronvpn/impl/src/main/java/org/opendaylight/netvirt/neutronvpn/NeutronNetworkChangeListener.java <ide> package org.opendaylight.netvirt.neutronvpn; <ide> <ide> import com.google.common.base.Optional; <del>import java.util.ArrayList; <add>import java.util.Collections; <ide> import java.util.List; <ide> import java.util.Objects; <add>import java.util.stream.Collectors; <ide> import javax.annotation.Nonnull; <ide> import javax.annotation.PostConstruct; <ide> import javax.inject.Inject; <ide> import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.Networks; <ide> import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network; <ide> import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.NetworkProviderExtension; <add>import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.neutron.networks.network.Segments; <ide> import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron; <ide> import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; <ide> import org.slf4j.Logger; <ide> <ide> @Nonnull <ide> private List<ElanSegments> buildSegments(Network input) { <del> Long numSegments = NeutronUtils.getNumberSegmentsFromNeutronNetwork(input); <del> List<ElanSegments> segments = new ArrayList<>(); <del> <del> for (long index = 1L; index <= numSegments; index++) { <del> ElanSegmentsBuilder elanSegmentsBuilder = new ElanSegmentsBuilder(); <del> elanSegmentsBuilder.setSegmentationId(0L); <del> if (NeutronUtils.getSegmentationIdFromNeutronNetworkSegment(input, index) != null) { <del> try { <del> elanSegmentsBuilder.setSegmentationId( <del> Long.valueOf(NeutronUtils.getSegmentationIdFromNeutronNetworkSegment(input, index))); <del> } catch (NumberFormatException error) { <del> LOG.error("Failed to get the segment id for network {}", input); <del> } <del> } <del> if (NeutronUtils.isNetworkSegmentType(input, index, NetworkTypeVxlan.class)) { <del> elanSegmentsBuilder.setSegmentType(SegmentTypeVxlan.class); <del> } else if (NeutronUtils.isNetworkSegmentType(input, index, NetworkTypeVlan.class)) { <del> elanSegmentsBuilder.setSegmentType(SegmentTypeVlan.class); <del> } else if (NeutronUtils.isNetworkSegmentType(input, index, NetworkTypeFlat.class)) { <del> elanSegmentsBuilder.setSegmentType(SegmentTypeFlat.class); <del> } <del> elanSegmentsBuilder.setSegmentationIndex(index); <del> segments.add(elanSegmentsBuilder.build()); <del> LOG.debug("Added segment {} to ELANInstance", segments.get((int) index - 1)); <del> } <del> return segments; <add> NetworkProviderExtension providerExtension = input.getAugmentation(NetworkProviderExtension.class); <add> if (providerExtension == null || providerExtension.getSegments() == null) { <add> return Collections.emptyList(); <add> } <add> return providerExtension.getSegments().stream() <add> .map(segment -> new ElanSegmentsBuilder() <add> .setSegmentationIndex(segment.getSegmentationIndex()) <add> .setSegmentationId(getSegmentationId(input, segment)) <add> .setSegmentType(elanSegmentTypeFromNetworkType(segment.getNetworkType())) <add> .build()) <add> .collect(Collectors.toList()); <add> } <add> <add> private Long getSegmentationId(Network network, Segments segment) { <add> try { <add> if (segment.getSegmentationId() != null) { <add> return Long.valueOf(segment.getSegmentationId()); <add> } <add> } catch (NumberFormatException error) { <add> LOG.error("Failed to get the segment id for network {}", network); <add> } <add> return 0L; <add> } <add> <add> private Class<? extends SegmentTypeBase> elanSegmentTypeFromNetworkType( <add> Class<? extends NetworkTypeBase> networkType) { <add> if (networkType == null) { <add> return null; <add> } <add> if (networkType.isAssignableFrom(NetworkTypeVxlan.class)) { <add> return SegmentTypeVxlan.class; <add> } else if (networkType.isAssignableFrom(NetworkTypeVlan.class)) { <add> return SegmentTypeVlan.class; <add> } else if (networkType.isAssignableFrom(NetworkTypeFlat.class)) { <add> return SegmentTypeFlat.class; <add> } <add> return null; <ide> } <ide> <ide> private ElanInstance createElanInstance(Network input) {
Java
apache-2.0
d829dea2445f45930d122101fe7e335ae69bfc9e
0
google/tsunami-security-scanner-plugins,google/tsunami-security-scanner-plugins,google/tsunami-security-scanner-plugins
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.tsunami.plugins.detectors.grafana; import static com.google.common.truth.Truth.assertThat; import static com.google.tsunami.common.data.NetworkEndpointUtils.forHostnameAndPort; import com.google.common.collect.ImmutableList; import com.google.inject.Guice; import com.google.protobuf.util.Timestamps; import com.google.tsunami.common.net.http.HttpClientModule; import com.google.tsunami.common.net.http.HttpStatus; import com.google.tsunami.common.time.testing.FakeUtcClock; import com.google.tsunami.common.time.testing.FakeUtcClockModule; import com.google.tsunami.proto.AdditionalDetail; import com.google.tsunami.proto.DetectionReport; import com.google.tsunami.proto.DetectionReportList; import com.google.tsunami.proto.DetectionStatus; import com.google.tsunami.proto.NetworkService; import com.google.tsunami.proto.Severity; import com.google.tsunami.proto.Software; import com.google.tsunami.proto.TargetInfo; import com.google.tsunami.proto.TextData; import com.google.tsunami.proto.TransportProtocol; import com.google.tsunami.proto.Vulnerability; import com.google.tsunami.proto.VulnerabilityId; import java.io.IOException; import java.time.Instant; import javax.inject.Inject; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link GrafanaArbitraryFileReadingDetector}. */ @RunWith(JUnit4.class) public final class GrafanaArbitraryFileReadingDetectorTest { private final FakeUtcClock fakeUtcClock = FakeUtcClock.create().setNow(Instant.parse("2020-01-01T00:00:00.00Z")); @Inject private GrafanaArbitraryFileReadingDetector detector; private MockWebServer mockWebServer; private NetworkService grafanaService; @Before public void setUp() { mockWebServer = new MockWebServer(); grafanaService = NetworkService.newBuilder() .setNetworkEndpoint( forHostnameAndPort(mockWebServer.getHostName(), mockWebServer.getPort())) .setTransportProtocol(TransportProtocol.TCP) .setSoftware(Software.newBuilder().setName("Grafana")) .setServiceName("http") .build(); Guice.createInjector( new FakeUtcClockModule(fakeUtcClock), new HttpClientModule.Builder().build(), new GrafanaArbitraryFileReadingDetectorBootstrapModule()) .injectMembers(this); } @After public void tearDown() throws IOException { mockWebServer.shutdown(); } @Test public void detect_whenVulnerable_returnsVulnerability() { mockWebServer.setDispatcher(new VulnerableEndpointDispatcher()); DetectionReportList detectionReports = detector.detect(TargetInfo.getDefaultInstance(), ImmutableList.of(grafanaService)); assertThat(detectionReports.getDetectionReportsList()) .containsExactly( DetectionReport.newBuilder() .setTargetInfo(TargetInfo.getDefaultInstance()) .setNetworkService(grafanaService) .setDetectionTimestamp( Timestamps.fromMillis(Instant.now(fakeUtcClock).toEpochMilli())) .setDetectionStatus(DetectionStatus.VULNERABILITY_VERIFIED) .setVulnerability( Vulnerability.newBuilder() .setMainId( VulnerabilityId.newBuilder().setPublisher("TSUNAMI_COMMUNITY") .setValue("CVE_2021_43798")) .setSeverity(Severity.HIGH) .setTitle("Grafana Pre-Auth Arbitrary File Reading vulnerability") .setDescription( "In Grafana 8.0.0 to 8.3.0, there is an endpoint that can be " + "accessed without authentication. This endpoint has a directory " + "traversal vulnerability, and any user can read any file on the " + "server without authentication, causing information leakage.") .setRecommendation("Update to 8.3.1 version or later.") .addAdditionalDetails( AdditionalDetail.newBuilder() .setTextData( TextData.newBuilder() .setText( "Vulnerable target:\n" + mockWebServer.url("/") + "public/plugins/grafana-clock-panel/..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2Fetc%2Fpasswd\n\n" + "Response:\n" + "200 Ok\n" + "Content-Length: 259\n\n" + "root:x:0:0:root:/root:/bin/ash\n" + "bin:x:1:1:bin:/bin:/sbin/nologin\n" + "daemon:x:2:2:daemon:/sbin:/sbin/nologin\n" + "adm:x:3:4:adm:/var/adm:/sbin/nologin\n" + "lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n" + "sync:x:5:0:sync:/sbin:/bin/sync\n" + "shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\n" ))) ) .build()); assertThat(mockWebServer.getRequestCount()).isEqualTo(1); } @Test public void detect_whenNoVulnerable_returnsNoFinding() { mockWebServer.setDispatcher(new SafeEndpointDispatcher()); DetectionReportList detectionReports = detector.detect(TargetInfo.getDefaultInstance(), ImmutableList.of(grafanaService)); assertThat(detectionReports.getDetectionReportsList()).isEmpty(); assertThat(mockWebServer.getRequestCount()).isEqualTo(19); } private static final class VulnerableEndpointDispatcher extends Dispatcher { @Override public MockResponse dispatch(RecordedRequest recordedRequest) { return new MockResponse().setResponseCode(HttpStatus.OK.code()) .setBody("root:x:0:0:root:/root:/bin/ash\n" + "bin:x:1:1:bin:/bin:/sbin/nologin\n" + "daemon:x:2:2:daemon:/sbin:/sbin/nologin\n" + "adm:x:3:4:adm:/var/adm:/sbin/nologin\n" + "lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n" + "sync:x:5:0:sync:/sbin:/bin/sync\n" + "shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\n"); } } private static final class SafeEndpointDispatcher extends Dispatcher { @Override public MockResponse dispatch(RecordedRequest recordedRequest) { return new MockResponse().setResponseCode(HttpStatus.NOT_FOUND.code()); } } }
community/detectors/grafana_arbitrary_file_reading/src/test/java/com/google/tsunami/plugins/detectors/grafana/GrafanaArbitraryFileReadingDetectorTest.java
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.tsunami.plugins.detectors.grafana; import static com.google.common.truth.Truth.assertThat; import static com.google.tsunami.common.data.NetworkEndpointUtils.forHostnameAndPort; import com.google.common.collect.ImmutableList; import com.google.inject.Guice; import com.google.protobuf.util.Timestamps; import com.google.tsunami.common.net.http.HttpClientModule; import com.google.tsunami.common.net.http.HttpStatus; import com.google.tsunami.common.time.testing.FakeUtcClock; import com.google.tsunami.common.time.testing.FakeUtcClockModule; import com.google.tsunami.proto.AdditionalDetail; import com.google.tsunami.proto.DetectionReport; import com.google.tsunami.proto.DetectionReportList; import com.google.tsunami.proto.DetectionStatus; import com.google.tsunami.proto.NetworkService; import com.google.tsunami.proto.Severity; import com.google.tsunami.proto.Software; import com.google.tsunami.proto.TargetInfo; import com.google.tsunami.proto.TextData; import com.google.tsunami.proto.TransportProtocol; import com.google.tsunami.proto.Vulnerability; import com.google.tsunami.proto.VulnerabilityId; import java.io.IOException; import java.time.Instant; import javax.inject.Inject; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link GrafanaArbitraryFileReadingDetector}. */ @RunWith(JUnit4.class) public final class GrafanaArbitraryFileReadingDetectorTest { private final FakeUtcClock fakeUtcClock = FakeUtcClock.create().setNow(Instant.parse("2020-01-01T00:00:00.00Z")); @Inject private GrafanaArbitraryFileReadingDetector detector; private MockWebServer mockWebServer; private NetworkService grafanaService; @Before public void setUp() { mockWebServer = new MockWebServer(); grafanaService = NetworkService.newBuilder() .setNetworkEndpoint( forHostnameAndPort(mockWebServer.getHostName(), mockWebServer.getPort())) .setTransportProtocol(TransportProtocol.TCP) .setSoftware(Software.newBuilder().setName("Grafana")) .setServiceName("http") .build(); Guice.createInjector( new FakeUtcClockModule(fakeUtcClock), new HttpClientModule.Builder().build(), new GrafanaArbitraryFileReadingDetectorBootstrapModule()) .injectMembers(this); } @After public void tearDown() throws IOException { mockWebServer.shutdown(); } @Test public void detect_whenVulnerable_returnsVulnerability() { mockWebServer.setDispatcher(new VulnerableEndpointDispatcher()); DetectionReportList detectionReports = detector.detect(TargetInfo.getDefaultInstance(), ImmutableList.of(grafanaService)); assertThat(detectionReports.getDetectionReportsList()) .containsExactly( DetectionReport.newBuilder() .setTargetInfo(TargetInfo.getDefaultInstance()) .setNetworkService(grafanaService) .setDetectionTimestamp( Timestamps.fromMillis(Instant.now(fakeUtcClock).toEpochMilli())) .setDetectionStatus(DetectionStatus.VULNERABILITY_VERIFIED) .setVulnerability( Vulnerability.newBuilder() .setMainId( VulnerabilityId.newBuilder().setPublisher("TSUNAMI_COMMUNITY") .setValue("GRAFANA_ARBITRARY_FILE_READING")) .setSeverity(Severity.HIGH) .setTitle("Grafana Pre-Auth Arbitrary File Reading vulnerability") .setDescription( "In Grafana 8.0.0 to 8.3.0, there is an endpoint that can be " + "accessed without authentication. This endpoint has a directory " + "traversal vulnerability, and any user can read any file on the " + "server without authentication, causing information leakage.") .setRecommendation("The application should be deployed on the internal " + "network as much as possible, do not open the endpoint to the " + "external network, or use the Nginx gateway for reverse proxy.") .addAdditionalDetails( AdditionalDetail.newBuilder() .setTextData( TextData.newBuilder() .setText( "Vulnerable target:\n" + mockWebServer.url("/") + "public/plugins/grafana-clock-panel/..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F.." + "%2F..%2F..%2F..%2Fetc%2Fpasswd\n\n" + "Response:\n" + "200 Ok\n" + "Content-Length: 259\n\n" + "root:x:0:0:root:/root:/bin/ash\n" + "bin:x:1:1:bin:/bin:/sbin/nologin\n" + "daemon:x:2:2:daemon:/sbin:/sbin/nologin\n" + "adm:x:3:4:adm:/var/adm:/sbin/nologin\n" + "lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n" + "sync:x:5:0:sync:/sbin:/bin/sync\n" + "shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\n" ))) ) .build()); assertThat(mockWebServer.getRequestCount()).isEqualTo(1); } @Test public void detect_whenNoVulnerable_returnsNoFinding() { mockWebServer.setDispatcher(new SafeEndpointDispatcher()); DetectionReportList detectionReports = detector.detect(TargetInfo.getDefaultInstance(), ImmutableList.of(grafanaService)); assertThat(detectionReports.getDetectionReportsList()).isEmpty(); assertThat(mockWebServer.getRequestCount()).isEqualTo(19); } private static final class VulnerableEndpointDispatcher extends Dispatcher { @Override public MockResponse dispatch(RecordedRequest recordedRequest) { return new MockResponse().setResponseCode(HttpStatus.OK.code()) .setBody("root:x:0:0:root:/root:/bin/ash\n" + "bin:x:1:1:bin:/bin:/sbin/nologin\n" + "daemon:x:2:2:daemon:/sbin:/sbin/nologin\n" + "adm:x:3:4:adm:/var/adm:/sbin/nologin\n" + "lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n" + "sync:x:5:0:sync:/sbin:/bin/sync\n" + "shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\n"); } } private static final class SafeEndpointDispatcher extends Dispatcher { @Override public MockResponse dispatch(RecordedRequest recordedRequest) { return new MockResponse().setResponseCode(HttpStatus.NOT_FOUND.code()); } } }
Update GrafanaArbitraryFileReadingDetectorTest.java fix test.
community/detectors/grafana_arbitrary_file_reading/src/test/java/com/google/tsunami/plugins/detectors/grafana/GrafanaArbitraryFileReadingDetectorTest.java
Update GrafanaArbitraryFileReadingDetectorTest.java
<ide><path>ommunity/detectors/grafana_arbitrary_file_reading/src/test/java/com/google/tsunami/plugins/detectors/grafana/GrafanaArbitraryFileReadingDetectorTest.java <ide> Vulnerability.newBuilder() <ide> .setMainId( <ide> VulnerabilityId.newBuilder().setPublisher("TSUNAMI_COMMUNITY") <del> .setValue("GRAFANA_ARBITRARY_FILE_READING")) <add> .setValue("CVE_2021_43798")) <ide> .setSeverity(Severity.HIGH) <ide> .setTitle("Grafana Pre-Auth Arbitrary File Reading vulnerability") <ide> .setDescription( <ide> + "accessed without authentication. This endpoint has a directory " <ide> + "traversal vulnerability, and any user can read any file on the " <ide> + "server without authentication, causing information leakage.") <del> .setRecommendation("The application should be deployed on the internal " <del> + "network as much as possible, do not open the endpoint to the " <del> + "external network, or use the Nginx gateway for reverse proxy.") <add> .setRecommendation("Update to 8.3.1 version or later.") <ide> .addAdditionalDetails( <ide> AdditionalDetail.newBuilder() <ide> .setTextData(
Java
mpl-2.0
c59a4dade3136120a6c87898e386603e9a339a36
0
GUBotDev/XBeeJavaLibrary,brucetsao/XBeeJavaLibrary,digidotcom/XBeeJavaLibrary
/** * Copyright (c) 2014 Digi International Inc., * All rights not expressly granted are 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/. * * Digi International Inc. 11001 Bren Road East, Minnetonka, MN 55343 * ======================================================================= */ package com.digi.xbee.api; import java.io.IOException; import java.util.ArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.digi.xbee.api.connection.IConnectionInterface; import com.digi.xbee.api.connection.DataReader; import com.digi.xbee.api.connection.serial.SerialPortParameters; import com.digi.xbee.api.exceptions.ATCommandException; import com.digi.xbee.api.exceptions.InterfaceAlreadyOpenException; import com.digi.xbee.api.exceptions.InterfaceNotOpenException; import com.digi.xbee.api.exceptions.InvalidOperatingModeException; import com.digi.xbee.api.exceptions.OperationNotSupportedException; import com.digi.xbee.api.exceptions.TimeoutException; import com.digi.xbee.api.exceptions.TransmitException; import com.digi.xbee.api.exceptions.XBeeException; import com.digi.xbee.api.io.IOLine; import com.digi.xbee.api.io.IOMode; import com.digi.xbee.api.io.IOSample; import com.digi.xbee.api.io.IOValue; import com.digi.xbee.api.listeners.IPacketReceiveListener; import com.digi.xbee.api.listeners.ISerialDataReceiveListener; import com.digi.xbee.api.models.ATCommand; import com.digi.xbee.api.models.ATCommandResponse; import com.digi.xbee.api.models.ATCommandStatus; import com.digi.xbee.api.models.XBee16BitAddress; import com.digi.xbee.api.models.XBee64BitAddress; import com.digi.xbee.api.models.OperatingMode; import com.digi.xbee.api.models.XBeeProtocol; import com.digi.xbee.api.models.XBeeTransmitOptions; import com.digi.xbee.api.models.XBeeTransmitStatus; import com.digi.xbee.api.packet.XBeeAPIPacket; import com.digi.xbee.api.packet.APIFrameType; import com.digi.xbee.api.packet.XBeePacket; import com.digi.xbee.api.packet.common.ATCommandPacket; import com.digi.xbee.api.packet.common.ATCommandResponsePacket; import com.digi.xbee.api.packet.common.IODataSampleRxIndicatorPacket; import com.digi.xbee.api.packet.common.RemoteATCommandPacket; import com.digi.xbee.api.packet.common.RemoteATCommandResponsePacket; import com.digi.xbee.api.packet.common.TransmitPacket; import com.digi.xbee.api.packet.common.TransmitStatusPacket; import com.digi.xbee.api.packet.raw.RX16IOPacket; import com.digi.xbee.api.packet.raw.RX64IOPacket; import com.digi.xbee.api.packet.raw.TX16Packet; import com.digi.xbee.api.packet.raw.TX64Packet; import com.digi.xbee.api.packet.raw.TXStatusPacket; import com.digi.xbee.api.utils.ByteUtils; import com.digi.xbee.api.utils.HexUtils; public class XBeeDevice { // Constants. protected static int DEFAULT_RECEIVE_TIMETOUT = 2000; // 2.0 seconds of timeout to receive packet and command responses. protected static int TIMEOUT_BEFORE_COMMAND_MODE = 1200; protected static int TIMEOUT_ENTER_COMMAND_MODE = 1500; private static String COMMAND_MODE_CHAR = "+"; private static String COMMAND_MODE_OK = "OK\r"; // Variables. protected IConnectionInterface connectionInterface; protected DataReader dataReader = null; protected XBeeProtocol xbeeProtocol = XBeeProtocol.UNKNOWN; protected OperatingMode operatingMode = OperatingMode.UNKNOWN; protected XBee64BitAddress xbee64BitAddress; protected int currentFrameID = 0xFF; protected int receiveTimeout = DEFAULT_RECEIVE_TIMETOUT; private Logger logger; private XBeeDevice localXBeeDevice; private Object ioLock = new Object(); private boolean ioPacketReceived = false; private byte[] ioPacketPayload; /** * Class constructor. Instantiates a new {@code XBeeDevice} object in the * given port name and baud rate. * * @param port Serial port name where XBee device is attached to. * @param baudRate Serial port baud rate to communicate with the device. * Other connection parameters will be set as default (8 * data bits, 1 stop bit, no parity, no flow control). * * @throws NullPointerException if {@code port == null}. * @throws IllegalArgumentException if {@code baudRate < 0}. */ public XBeeDevice(String port, int baudRate) { this(XBee.createConnectiontionInterface(port, baudRate)); } /** * Class constructor. Instantiates a new {@code XBeeDevice} object in the * given serial port name and settings. * * @param port Serial port name where XBee device is attached to. * @param baudRate Serial port baud rate to communicate with the device. * @param dataBits Serial port data bits. * @param stopBits Serial port data bits. * @param parity Serial port data bits. * @param flowControl Serial port data bits. * * @throws NullPointerException if {@code port == null}. * @throws IllegalArgumentException if {@code baudRate < 0} or * if {@code dataBits < 0} or * if {@code stopBits < 0} or * if {@code parity < 0} or * if {@code flowControl < 0}. */ public XBeeDevice(String port, int baudRate, int dataBits, int stopBits, int parity, int flowControl) { this(port, new SerialPortParameters(baudRate, dataBits, stopBits, parity, flowControl)); } /** * Class constructor. Instantiates a new {@code XBeeDevice} object in the * given serial port name and parameters. * * @param port Serial port name where XBee device is attached to. * @param serialPortParameters Object containing the serial port parameters. * * @throws NullPointerException if {@code port == null} or * if {@code serialPortParameters == null}. * * @see SerialPortParameters */ public XBeeDevice(String port, SerialPortParameters serialPortParameters) { this(XBee.createConnectiontionInterface(port, serialPortParameters)); } /** * Class constructor. Instantiates a new {@code XBeeDevice} object with the * given connection interface. * * @param connectionInterface The connection interface with the physical * XBee device. * * @throws NullPointerException if {@code connectionInterface == null}. * * @see IConnectionInterface */ public XBeeDevice(IConnectionInterface connectionInterface) { if (connectionInterface == null) throw new NullPointerException("ConnectionInterface cannot be null."); this.connectionInterface = connectionInterface; this.logger = LoggerFactory.getLogger(XBeeDevice.class); logger.debug(toString() + "Using the connection interface {}.", connectionInterface.getClass().getSimpleName(), connectionInterface.toString()); } /** * Class constructor. Instantiates a new remote {@code XBeeDevice} object * with the given local {@code XBeeDevice} which contains the connection * interface to be used. * * @param localXBeeDevice The local XBee device that will behave as * connection interface to communicate with this * remote XBee device. * @param xbee64BitAddress The 64-bit address to identify this remote XBee * device. * @throws NullPointerException if {@code localXBeeDevice == null} or * if {@code xbee64BitAddress == null}. * * @see XBee64BitAddress */ public XBeeDevice(XBeeDevice localXBeeDevice, XBee64BitAddress xbee64BitAddress) { if (localXBeeDevice == null) throw new NullPointerException("Local XBee device cannot be null."); if (xbee64BitAddress == null) throw new NullPointerException("XBee 64 bit address of the remote device cannot be null."); if (localXBeeDevice.isRemote()) throw new IllegalArgumentException("The given local XBee device is remote."); this.localXBeeDevice = localXBeeDevice; this.connectionInterface = localXBeeDevice.getConnectionInterface(); this.xbee64BitAddress = xbee64BitAddress; this.logger = LoggerFactory.getLogger(XBeeDevice.class); logger.debug(toString() + "Using the connection interface {}.", connectionInterface.getClass().getSimpleName(), connectionInterface.toString()); } /** * Opens the connection interface associated with this XBee device. * * @throws XBeeException if there is any problem opening the device. * @throws InterfaceAlreadyOpenException if the device is already open. * * @see #isOpen() * @see #close() */ public void open() throws XBeeException { logger.info(toString() + "Opening the connection interface..."); // First, verify that the connection is not already open. if (connectionInterface.isOpen()) throw new InterfaceAlreadyOpenException(); // Connect the interface. connectionInterface.open(); logger.info(toString() + "Connection interface open."); // Data reader initialization and determining operating mode should be only // done for local XBee devices. if (isRemote()) return; // Initialize the data reader. dataReader = new DataReader(connectionInterface, operatingMode); dataReader.start(); // Determine the operating mode of the XBee device if it is unknown. if (operatingMode == OperatingMode.UNKNOWN) operatingMode = determineOperatingMode(); // Check if the operating mode is a valid and supported one. if (operatingMode == OperatingMode.UNKNOWN) { close(); throw new InvalidOperatingModeException("Could not determine operating mode."); } else if (operatingMode == OperatingMode.AT) { close(); throw new InvalidOperatingModeException(operatingMode); } } /** * Closes the connection interface associated with this XBee device. * * @see #isOpen() * @see #open() */ public void close() { // Stop XBee reader. if (dataReader != null && dataReader.isRunning()) dataReader.stopReader(); // Close interface. connectionInterface.close(); logger.info(toString() + "Connection interface closed."); } /** * Retrieves whether or not the connection interface associated to the * device is open. * * @return {@code true} if the interface is open, {@code false} otherwise. * * @see #open() * @see #close() */ public boolean isOpen() { if (connectionInterface != null) return connectionInterface.isOpen(); return false; } /** * Retrieves the connection interface associated to this XBee device. * * @return XBee device's connection interface. * * @see IConnectionInterface */ public IConnectionInterface getConnectionInterface() { return connectionInterface; } /** * Retrieves whether or not the XBee device is a remote device. * * @return {@code true} if the XBee device is a remote device, * {@code false} otherwise. */ public boolean isRemote() { return localXBeeDevice != null; } /** * Determines the operating mode of the XBee device. * * @return The operating mode of the XBee device. * * @throws OperationNotSupportedException if the packet is being sent from * a remote device. * @throws InterfaceNotOpenException if the device is not open. * * @see OperatingMode */ protected OperatingMode determineOperatingMode() throws OperationNotSupportedException { try { // Check if device is in API or API Escaped operating modes. operatingMode = OperatingMode.API; dataReader.setXBeeReaderMode(operatingMode); ATCommandResponse response = sendATCommand(new ATCommand("AP")); if (response.getResponse() != null && response.getResponse().length > 0) { if (response.getResponse()[0] != OperatingMode.API.getID()) operatingMode = OperatingMode.API_ESCAPE; logger.debug(toString() + "Using {}.", operatingMode.getName()); return operatingMode; } } catch (TimeoutException e) { // Check if device is in AT operating mode. operatingMode = OperatingMode.AT; dataReader.setXBeeReaderMode(operatingMode); try { // It is necessary to wait at least 1 second to enter in command mode after // sending any data to the device. Thread.sleep(TIMEOUT_BEFORE_COMMAND_MODE); // Try to enter in AT command mode, if so the module is in AT mode. boolean success = enterATCommandMode(); if (success) return OperatingMode.AT; } catch (TimeoutException e1) { logger.error(e1.getMessage(), e1); } catch (InvalidOperatingModeException e1) { logger.error(e1.getMessage(), e1); } catch (InterruptedException e1) { logger.error(e1.getMessage(), e1); } } catch (InvalidOperatingModeException e) { logger.error("Invalid operating mode", e); } catch (IOException e) { logger.error(e.getMessage(), e); } return OperatingMode.UNKNOWN; } /** * Attempts to put the device in AT Command mode. Only valid if device is * working in AT mode. * * @return {@code true} if the device entered in AT command mode, * {@code false} otherwise. * * @throws InvalidOperatingModeException if the operating mode cannot be * determined or is not supported. * @throws TimeoutException if the configured time expires. * @throws InterfaceNotOpenException if the device is not open. */ public boolean enterATCommandMode() throws InvalidOperatingModeException, TimeoutException { if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); if (operatingMode != OperatingMode.AT) throw new InvalidOperatingModeException("Invalid mode. Command mode can be only accessed while in AT mode."); // Enter in AT command mode (send '+++'). The process waits 1,5 seconds for the 'OK\n'. byte[] readData = new byte[256]; try { // Send the command mode sequence. connectionInterface.writeData(COMMAND_MODE_CHAR.getBytes()); connectionInterface.writeData(COMMAND_MODE_CHAR.getBytes()); connectionInterface.writeData(COMMAND_MODE_CHAR.getBytes()); // Wait some time to let the module generate a response. Thread.sleep(TIMEOUT_ENTER_COMMAND_MODE); // Read data from the device (it should answer with 'OK\r'). int readBytes = connectionInterface.readData(readData); if (readBytes < COMMAND_MODE_OK.length()) throw new TimeoutException(); // Check if the read data is 'OK\r'. String readString = new String(readData, 0, readBytes); if (!readString.contains(COMMAND_MODE_OK)) return false; // Read data was 'OK\r'. return true; } catch (IOException e) { logger.error(e.getMessage(), e); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } return false; } /** * Retrieves the 64-bit address of the XBee device. * * @return The 64-bit address of the XBee device. * * @see XBee64BitAddress */ public XBee64BitAddress get64BitAddress() { return xbee64BitAddress; } /** * Retrieves the Operating mode (AT, API or API escaped) of the XBee device. * * @return The operating mode of the XBee device. * * @see OperatingMode */ public OperatingMode getOperatingMode() { return operatingMode; } /** * Retrieves the XBee Protocol of the XBee device. * * @return The XBee device protocol. * * @see XBeeProtocol * @see #setXBeeProtocol(XBeeProtocol) */ public XBeeProtocol getXBeeProtocol() { return xbeeProtocol; } /** * Sets the XBee protocol of the XBee device. * * @param xbeeProtocol The XBee protocol to set. * * @see XBeeProtocol * @see #getXBeeProtocol() */ protected void setXBeeProtocol(XBeeProtocol xbeeProtocol) { this.xbeeProtocol = xbeeProtocol; } /** * Sends the given AT command and waits for answer or until the configured * receive timeout expires. * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * @param command AT command to be sent. * @return An {@code ATCommandResponse} object containing the response of * the command or {@code null} if there is no response. * * @throws InvalidOperatingModeException if the operating mode is different than {@link OperatingMode#API} and * {@link OperatingMode#API_ESCAPE}. * @throws TimeoutException if the configured time expires while waiting * for the command reply. * @throws OperationNotSupportedException if the packet is being sent from * a remote device. * @throws IOException if an I/O error occurs while sending the AT command. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code command == null}. * * @see ATCommand * @see ATCommandResponse * @see #setReceiveTimeout(int) * @see #getReceiveTimeout() */ public ATCommandResponse sendATCommand(ATCommand command) throws InvalidOperatingModeException, TimeoutException, OperationNotSupportedException, IOException { // Check if command is null. if (command == null) throw new NullPointerException("AT command cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); ATCommandResponse response = null; OperatingMode operatingMode = getOperatingMode(); switch (operatingMode) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(operatingMode); case API: case API_ESCAPE: // Create AT command packet XBeePacket packet; if (isRemote()) packet = new RemoteATCommandPacket(getNextFrameID(), get64BitAddress(), XBee16BitAddress.UNKNOWN_ADDRESS, XBeeTransmitOptions.NONE, command.getCommand(), command.getParameter()); else packet = new ATCommandPacket(getNextFrameID(), command.getCommand(), command.getParameter()); if (command.getParameter() == null) logger.debug(toString() + "Sending AT command '{}'.", command.getCommand()); else logger.debug(toString() + "Sending AT command '{} {}'.", command.getCommand(), HexUtils.prettyHexString(command.getParameter())); try { // Send the packet and build response. XBeePacket answerPacket = sendXBeePacket(packet, true); if (answerPacket instanceof ATCommandResponsePacket) response = new ATCommandResponse(command, ((ATCommandResponsePacket)answerPacket).getCommandValue(), ((ATCommandResponsePacket)answerPacket).getStatus()); else if (answerPacket instanceof RemoteATCommandResponsePacket) response = new ATCommandResponse(command, ((RemoteATCommandResponsePacket)answerPacket).getCommandValue(), ((RemoteATCommandResponsePacket)answerPacket).getStatus()); if (response.getResponse() != null) logger.debug(toString() + "AT command response: {}.", HexUtils.prettyHexString(response.getResponse())); else logger.debug(toString() + "AT command response: null."); } catch (ClassCastException e) { logger.error("Received an invalid packet type after sending an AT command packet." + e); } } return response; } /** * Sends the given XBee packet synchronously and blocks until the response * is received or the configured receive timeout expires. * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>Use {@link #sendXBeePacketAsync(XBeePacket)} for non-blocking * operations.</p> * * @param packet XBee packet to be sent. * * @return An {@code XBeePacket} object containing the response of the sent * packet or {@code null} if there is no response. * * @throws XBeeException if there is any error sending the XBee packet. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * * @see XBeePacket * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) * @see #sendXBeePacketAsync(XBeePacket) * @see #setReceiveTimeout(int) * @see #getReceiveTimeout() */ public XBeePacket sendXBeePacket(XBeePacket packet) throws XBeeException { try { return sendXBeePacket(packet, isRemote()); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } } /** * Sends the given XBee packet synchronously and blocks until response is * received or receive timeout is reached. * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>Use {@link #sendXBeePacketAsync(XBeePacket, boolean)} for non-blocking * operations.</p> * * @param packet XBee packet to be sent. * @param sentFromLocalDevice Indicates whether or not the packet was sent * from a local device. * @return An {@code XBeePacket} containing the response of the sent packet * or {@code null} if there is no response. * * @throws InvalidOperatingModeException if the operating mode is different than {@link OperatingMode#API} and * {@link OperatingMode#API_ESCAPE}. * @throws TimeoutException if the configured time expires while waiting for the packet reply. * @throws OperationNotSupportedException if the packet is being sent from a remote device. * @throws IOException if an I/O error occurs while sending the XBee packet. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * * @see XBeePacket * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener, boolean) * @see #sendXBeePacketAsync(XBeePacket) * @see #sendXBeePacketAsync(XBeePacket, boolean) * @see #setReceiveTimeout(int) * @see #getReceiveTimeout() */ private XBeePacket sendXBeePacket(final XBeePacket packet, boolean sentFromLocalDevice) throws InvalidOperatingModeException, TimeoutException, OperationNotSupportedException, IOException { // Check if the packet to send is null. if (packet == null) throw new NullPointerException("XBee packet cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if the packet is being sent from a remote device. if (!sentFromLocalDevice) throw new OperationNotSupportedException("Remote devices cannot send data to other remote devices."); OperatingMode operatingMode = getOperatingMode(); switch (operatingMode) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(operatingMode); case API: case API_ESCAPE: // Build response container. ArrayList<XBeePacket> responseList = new ArrayList<XBeePacket>(); // If the packet does not need frame ID, send it async. and return null. if (packet instanceof XBeeAPIPacket) { if (!((XBeeAPIPacket)packet).needsAPIFrameID()) { sendXBeePacketAsync(packet, sentFromLocalDevice); return null; } } else { sendXBeePacketAsync(packet, sentFromLocalDevice); return null; } // Add the required frame ID to the packet if necessary. insertFrameID(packet); // Generate a packet received listener for the packet to be sent. IPacketReceiveListener packetReceiveListener = createPacketReceivedListener(packet, responseList); // Add the packet listener to the data reader. dataReader.addPacketReceiveListener(packetReceiveListener); // Write the packet data. writePacket(packet); try { // Wait for response or timeout. synchronized (responseList) { try { responseList.wait(receiveTimeout); } catch (InterruptedException e) {} } // After the wait check if we received any response, if not throw timeout exception. if (responseList.size() < 1) throw new TimeoutException(); // Return the received packet. return responseList.get(0); } finally { // Always remove the packet listener from the list. dataReader.removePacketReceiveListener(packetReceiveListener); } } } /** * Insert (if possible) the next frame ID stored in the device to the * provided packet. * * @param xbeePacket The packet to add the frame ID. * * @see XBeePacket */ private void insertFrameID(XBeePacket xbeePacket) { if (xbeePacket instanceof XBeeAPIPacket) return; if (((XBeeAPIPacket)xbeePacket).needsAPIFrameID() && ((XBeeAPIPacket)xbeePacket).getFrameID() == XBeeAPIPacket.NO_FRAME_ID) ((XBeeAPIPacket)xbeePacket).setFrameID(getNextFrameID()); } /** * Retrieves the packet listener corresponding to the provided sent packet. * * <p>The listener will filter those packets matching with the Frame ID of * the sent packet storing them in the provided responseList array.</p> * * @param sentPacket The packet sent. * @param responseList List of packets received that correspond to the * frame ID of the packet sent. * * @return A packet receive listener that will filter the packets received * corresponding to the sent one. * * @see IPacketReceiveListener * @see XBeePacket */ private IPacketReceiveListener createPacketReceivedListener(final XBeePacket sentPacket, final ArrayList<XBeePacket> responseList) { IPacketReceiveListener packetReceiveListener = new IPacketReceiveListener() { /* * (non-Javadoc) * @see com.digi.xbee.api.listeners.IPacketReceiveListener#packetReceived(com.digi.xbee.api.packet.XBeePacket) */ @Override public void packetReceived(XBeePacket receivedPacket) { // Check if it is the packet we are waiting for. if (((XBeeAPIPacket)receivedPacket).checkFrameID((((XBeeAPIPacket)sentPacket).getFrameID()))) { // Security check to avoid class cast exceptions. It has been observed that parallel processes // using the same connection but with different frame index may collide and cause this exception at some point. if (sentPacket instanceof XBeeAPIPacket && receivedPacket instanceof XBeeAPIPacket) { XBeeAPIPacket sentAPIPacket = (XBeeAPIPacket)sentPacket; XBeeAPIPacket receivedAPIPacket = (XBeeAPIPacket)receivedPacket; // If the packet sent is an AT command, verify that the received one is an AT command response and // the command matches in both packets. if (sentAPIPacket.getFrameType() == APIFrameType.AT_COMMAND) { if (receivedAPIPacket.getFrameType() != APIFrameType.AT_COMMAND_RESPONSE) return; if (!((ATCommandPacket)sentAPIPacket).getCommand().equalsIgnoreCase(((ATCommandResponsePacket)receivedPacket).getCommand())) return; } // If the packet sent is a remote AT command, verify that the received one is a remote AT command response and // the command matches in both packets. if (sentAPIPacket.getFrameType() == APIFrameType.REMOTE_AT_COMMAND_REQUEST) { if (receivedAPIPacket.getFrameType() != APIFrameType.REMOTE_AT_COMMAND_RESPONSE) return; if (!((RemoteATCommandPacket)sentAPIPacket).getCommand().equalsIgnoreCase(((RemoteATCommandResponsePacket)receivedPacket).getCommand())) return; } } // Verify that the sent packet is not the received one! This can happen when the echo mode is enabled in the // serial port. if (!isSamePacket(sentPacket, receivedPacket)) { responseList.add(receivedPacket); synchronized (responseList) { responseList.notify(); } } } } }; return packetReceiveListener; } /** * Retrieves whether or not the sent packet is the same than the received one. * * @param sentPacket The packet sent. * @param receivedPacket The packet received. * * @return {@code true} if the sent packet is the same than the received * one, {@code false} otherwise. * * @see XBeePacket */ private boolean isSamePacket(XBeePacket sentPacket, XBeePacket receivedPacket) { // TODO Should not we implement the {@code equals} method in the XBeePacket?? if (HexUtils.byteArrayToHexString(sentPacket.generateByteArray()).equals(HexUtils.byteArrayToHexString(receivedPacket.generateByteArray()))) return true; return false; } /** * Sends the given XBee packet asynchronously and registers the given packet * listener (if not {@code null}) to wait for an answer. * * @param packet XBee packet to be sent. * @param packetReceiveListener Listener for the operation, {@code null} * not to be notified when the answer arrives. * * @throws InvalidOperatingModeException if the operating mode is different than {@link OperatingMode#API} and * {@link OperatingMode#API_ESCAPE}. * @throws OperationNotSupportedException if the packet is being sent from a remote device. * @throws IOException if an I/O error occurs while sending the XBee packet. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * * @see XBeePacket * @see IPacketReceiveListener * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacket(XBeePacket, boolean) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) * @see #sendXBeePacketAsync(XBeePacket) * @see #sendXBeePacketAsync(XBeePacket, boolean) */ private void sendXBeePacket(XBeePacket packet, IPacketReceiveListener packetReceiveListener, boolean sentFromLocalDevice) throws InvalidOperatingModeException, OperationNotSupportedException, IOException { // Check if the packet to send is null. if (packet == null) throw new NullPointerException("XBee packet cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if the packet is being sent from a remote device. if (!sentFromLocalDevice) throw new OperationNotSupportedException("Remote devices cannot send data to other remote devices."); OperatingMode operatingMode = getOperatingMode(); switch (operatingMode) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(operatingMode); case API: case API_ESCAPE: // Add the required frame ID and subscribe listener if given. if (packet instanceof XBeeAPIPacket) { if (((XBeeAPIPacket)packet).needsAPIFrameID()) { if (((XBeeAPIPacket)packet).getFrameID() == XBeeAPIPacket.NO_FRAME_ID) ((XBeeAPIPacket)packet).setFrameID(getNextFrameID()); if (packetReceiveListener != null) dataReader.addPacketReceiveListener(packetReceiveListener, ((XBeeAPIPacket)packet).getFrameID()); } else if (packetReceiveListener != null) dataReader.addPacketReceiveListener(packetReceiveListener); } // Write packet data. writePacket(packet); break; } } /** * Sends the given XBee packet asynchronously. * * <p>To be notified when the answer is received, use * {@link #sendXBeePacket(XBeePacket, IPacketReceiveListener)}.</p> * * @param packet XBee packet to be sent asynchronously. * * @throws InvalidOperatingModeException if the operating mode is different than {@link OperatingMode#API} and * {@link OperatingMode#API_ESCAPE}. * @throws OperationNotSupportedException if the packet is being sent from a remote device. * @throws IOException if an I/O error occurs while sending the XBee packet. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * * @see XBeePacket * @see #sendXBeePacketAsync(XBeePacket) * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacket(XBeePacket, boolean) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener, boolean) */ private void sendXBeePacketAsync(XBeePacket packet, boolean sentFromLocalDevice) throws InvalidOperatingModeException, OperationNotSupportedException, IOException { sendXBeePacket(packet, null, sentFromLocalDevice); } /** * Sends the given XBee packet and registers the given packet listener * (if not {@code null}) to wait for an answer. * * @param packet XBee packet to be sent. * @param packetReceiveListener Listener for the operation, {@code null} * not to be notified when the answer arrives. * * @throws XBeeException if there is any error sending the XBee packet. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * * @see XBeePacket * @see IPacketReceiveListener * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacketAsync(XBeePacket) */ public void sendXBeePacket(XBeePacket packet, IPacketReceiveListener packetReceiveListener) throws XBeeException { try { sendXBeePacket(packet, packetReceiveListener, isRemote()); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } } /** * Sends the given XBee packet asynchronously. * * <p>To be notified when the answer is received, use * {@link #sendXBeePacket(XBeePacket, IPacketReceiveListener)}.</p> * * @param packet XBee packet to be sent asynchronously. * * @throws XBeeException if there is any error sending the XBee packet. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * * @see XBeePacket * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) */ public void sendXBeePacketAsync(XBeePacket packet) throws IOException, XBeeException { try { sendXBeePacket(packet, null, isRemote()); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } } /** * Writes the given XBee packet in the connection interface. * * @param packet XBee packet to be written. * * @throws IOException if an I/O error occurs while writing the XBee packet * in the connection interface. */ protected void writePacket(XBeePacket packet) throws IOException { logger.debug(toString() + "Sending XBee packet: \n{}", packet.toPrettyString()); // Write bytes with the required escaping mode. switch (operatingMode) { case API: default: connectionInterface.writeData(packet.generateByteArray()); break; case API_ESCAPE: connectionInterface.writeData(packet.generateByteArrayEscaped()); break; } } /** * Retrieves the next Frame ID of the XBee protocol. * * @return The next Frame ID. */ public int getNextFrameID() { if (currentFrameID == 0xff) { // Reset counter. currentFrameID = 1; } else currentFrameID ++; return currentFrameID; } /** * Retrieves the configured timeout for receiving packets in synchronous * operations. * * @return The current receive timeout in milliseconds. * * @see #setReceiveTimeout(int) */ public int getReceiveTimeout() { return receiveTimeout; } /** * Configures the timeout in milliseconds for receiving packets in * synchronous operations. * * @param receiveTimeout The new receive timeout in milliseconds. * * @throws IllegalArgumentException if {@code receiveTimeout < 0}. * * @see #getReceiveTimeout() */ public void setReceiveTimeout(int receiveTimeout) { if (receiveTimeout < 0) throw new IllegalArgumentException("Receive timeout cannot be less than 0."); this.receiveTimeout = receiveTimeout; } /** * Starts listening for packets in the provided packets listener. * * <p>The provided listener is added to the list of listeners to be notified * when new packets are received. If the listener has been already * included, this method does nothing.</p> * * @param listener Listener to be notified when new packets are received. * * @see IPacketReceiveListener * @see #stopListeningForPackets(IPacketReceiveListener) */ public void startListeningForPackets(IPacketReceiveListener listener) { if (dataReader == null) return; dataReader.addPacketReceiveListener(listener); } /** * Stops listening for packets in the provided packets listener. * * <p>The provided listener is removed from the list of packets listeners. * If the listener was not in the list this method does nothing.</p> * * @param listener Listener to be removed from the list of listeners. * * @see IPacketReceiveListener * @see #startListeningForPackets(IPacketReceiveListener) */ public void stopListeningForPackets(IPacketReceiveListener listener) { if (dataReader == null) return; dataReader.removePacketReceiveListener(listener); } /** * Starts listening for serial data in the provided serial data listener. * * <p>The provided listener is added to the list of listeners to be notified * when new serial data is received. If the listener has been already * included this method does nothing.</p> * * @param listener Listener to be notified when new serial data is received. * * @see ISerialDataReceiveListener * @see #stopListeningForSerialData(ISerialDataReceiveListener) */ public void startListeningForSerialData(ISerialDataReceiveListener listener) { if (dataReader == null) return; dataReader.addSerialDatatReceiveListener(listener); } /** * Stops listening for serial data in the provided serial data listener. * * <p>The provided listener is removed from the list of serial data * listeners. If the listener was not in the list this method does nothing.</p> * * @param listener Listener to be removed from the list of listeners. * * @see ISerialDataReceiveListener * @see #startListeningForSerialData(ISerialDataReceiveListener) */ public void stopListeningForSerialData(ISerialDataReceiveListener listener) { if (dataReader == null) return; dataReader.removeSerialDataReceiveListener(listener); } /** * Sends the provided data to the XBee device of the network corresponding * to the given 64-bit address asynchronously. * * <p>Asynchronous transmissions do not wait for answer from the remote * device or for transmit status packet.</p> * * @param address The 64-bit address of the XBee that will receive the data. * @param data Byte array containing data to be sent. * * @throws XBeeException if there is any XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code address == null} or * if {@code data == null}. * * @see XBee64BitAddress * @see #sendSerialDataAsync(XBee16BitAddress, byte[]) * @see #sendSerialDataAsync(XBeeDevice, byte[]) * @see #sendSerialData(XBee16BitAddress, byte[]) * @see #sendSerialData(XBee64BitAddress, byte[]) * @see #sendSerialData(XBeeDevice, byte[]) */ public void sendSerialDataAsync(XBee64BitAddress address, byte[] data) throws XBeeException { // Verify the parameters are not null, if they are null, throw an exception. if (address == null) throw new NullPointerException("Address cannot be null"); if (data == null) throw new NullPointerException("Data cannot be null"); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if device is remote. if (isRemote()) throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device."); logger.info(toString() + "Sending serial data asynchronously to {} >> {}.", address, HexUtils.prettyHexString(data)); // Depending on the protocol of the XBee device, the packet to send may vary. XBeePacket xbeePacket; switch (getXBeeProtocol()) { case RAW_802_15_4: // Generate and send the Tx64 packet. xbeePacket = new TX64Packet(getNextFrameID(), address, XBeeTransmitOptions.NONE, data); break; default: // Generate and send the Transmit packet. xbeePacket = new TransmitPacket(getNextFrameID(), address, XBee16BitAddress.UNKNOWN_ADDRESS, 0, XBeeTransmitOptions.NONE, data); } sendAndCheckXBeePacket(xbeePacket, true); } /** * Sends the provided data to the XBee device of the network corresponding * to the given 16-bit address asynchronously. * * <p>Asynchronous transmissions do not wait for answer from the remote * device or for transmit status packet.</p> * * @param address The 16-bit address of the XBee that will receive the data. * @param data Byte array containing data to be sent. * * @throws XBeeException if there is any XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code address == null} or * if {@code data == null}. * * @see XBee16BitAddress * @see #sendSerialDataAsync(XBee64BitAddress, byte[]) * @see #sendSerialDataAsync(XBeeDevice, byte[]) * @see #sendSerialData(XBee16BitAddress, byte[]) * @see #sendSerialData(XBee64BitAddress, byte[]) * @see #sendSerialData(XBeeDevice, byte[]) */ public void sendSerialDataAsync(XBee16BitAddress address, byte[] data) throws XBeeException { // Verify the parameters are not null, if they are null, throw an exception. if (address == null) throw new NullPointerException("Address cannot be null"); if (data == null) throw new NullPointerException("Data cannot be null"); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if device is remote. if (isRemote()) throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device."); logger.info(toString() + "Sending serial data asynchronously to {} >> {}.", address, HexUtils.prettyHexString(data)); // Depending on the protocol of the XBee device, the packet to send may vary. XBeePacket xbeePacket; switch (getXBeeProtocol()) { case RAW_802_15_4: // Generate and send the Tx16 packet. xbeePacket = new TX16Packet(getNextFrameID(), address, XBeeTransmitOptions.NONE, data); break; default: // Generate and send the Transmit packet. xbeePacket = new TransmitPacket(getNextFrameID(), XBee64BitAddress.UNKNOWN_ADDRESS, address, 0, XBeeTransmitOptions.NONE, data); } sendAndCheckXBeePacket(xbeePacket, true); } /** * Sends the provided data to the XBee device of the network corresponding * to the given 64-Bit/16-Bit address asynchronously. * * <p>Asynchronous transmissions do not wait for answer from the remote * device or for transmit status packet.</p> * * @param address64Bit The 64-bit address of the XBee that will receive the * data. * @param address16bit The 16-bit address of the XBee that will receive the * data. If it is unknown the * {@code XBee16BitAddress.UNKNOWN_ADDRESS} must be used. * @param data Byte array containing data to be sent. * * @throws XBeeException if a remote device is trying to send serial data or * if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code address64Bit == null} or * if {@code address16bit == null} or * if {@code data == null}. * * @see XBee64BitAddress * @see XBee16BitAddress * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) * @see #sendSerialData(XBee64BitAddress, byte[]) * @see #sendSerialData(XBee16BitAddress, byte[]) * @see #sendSerialData(XBee64BitAddress, XBee16BitAddress, byte[]) * @see #sendSerialData(XBeeDevice, byte[]) * @see #sendSerialDataAsync(XBee64BitAddress, byte[]) * @see #sendSerialDataAsync(XBee16BitAddress, byte[]) * @see #sendSerialDataAsync(XBeeDevice, byte[]) */ public void sendSerialDataAsync(XBee64BitAddress address64Bit, XBee16BitAddress address16bit, byte[] data) throws XBeeException { // Verify the parameters are not null, if they are null, throw an exception. if (address64Bit == null) throw new NullPointerException("64-bit address cannot be null"); if (address16bit == null) throw new NullPointerException("16-bit address cannot be null"); if (data == null) throw new NullPointerException("Data cannot be null"); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if device is remote. if (isRemote()) throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device."); logger.info(toString() + "Sending serial data asynchronously to {}[{}] >> {}.", address64Bit, address16bit, HexUtils.prettyHexString(data)); // Depending on the protocol of the XBee device, the packet to send may vary. XBeePacket xbeePacket; switch (getXBeeProtocol()) { case RAW_802_15_4: // TODO We don't know which address should be used: 16-bit/64-bit. // For the moment we are going to use 64-bit address by default. xbeePacket = new TX64Packet(getNextFrameID(), address64Bit, XBeeTransmitOptions.NONE, data); break; default: // Generate and send the Transmit packet. xbeePacket = new TransmitPacket(getNextFrameID(), address64Bit, address16bit, 0, XBeeTransmitOptions.NONE, data); } sendAndCheckXBeePacket(xbeePacket, true); } /** * Sends the provided data to the provided XBee device asynchronously. * * <p>Asynchronous transmissions do not wait for answer from the remote * device or for transmit status packet.</p> * * @param xbeeDevice The XBee device of the network that will receive the data. * @param data Byte array containing data to be sent. * * @throws XBeeException if there is any XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code xbeeDevice == null} or * if {@code data == null}. * * @see #sendSerialDataAsync(XBee64BitAddress, byte[]) * @see #sendSerialDataAsync(XBee16BitAddress, byte[]) * @see #sendSerialData(XBee64BitAddress, byte[]) * @see #sendSerialData(XBee16BitAddress, byte[]) * @see #sendSerialData(XBeeDevice, byte[]) */ public void sendSerialDataAsync(XBeeDevice xbeeDevice, byte[] data) throws XBeeException { if (xbeeDevice == null) throw new NullPointerException("XBee device cannot be null"); sendSerialDataAsync(xbeeDevice.get64BitAddress(), data); } /** * Sends the provided data to the XBee device of the network corresponding * to the given 64-bit address. * * <p>This method blocks till a success or error response arrives or the * configured receive timeout expires.</p> * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>For non-blocking operations use the method * {@link #sendSerialData(XBee64BitAddress, byte[])}.</p> * * @param address The 64-bit address of the XBee that will receive the data. * @param data Byte array containing data to be sent. * * @throws TimeoutException if there is a timeout sending the serial data. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code address == null} or * if {@code data == null}. * * @see XBee64BitAddress * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) * @see #sendSerialData(XBee16BitAddress, byte[]) * @see #sendSerialData(XBeeDevice, byte[]) * @see #sendSerialDataAsync(XBee64BitAddress, byte[]) * @see #sendSerialDataAsync(XBee16BitAddress, byte[]) * @see #sendSerialDataAsync(XBeeDevice, byte[]) */ public void sendSerialData(XBee64BitAddress address, byte[] data) throws TimeoutException, XBeeException { // Verify the parameters are not null, if they are null, throw an exception. if (address == null) throw new NullPointerException("Address cannot be null"); if (data == null) throw new NullPointerException("Data cannot be null"); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if device is remote. if (isRemote()) throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device."); logger.info(toString() + "Sending serial data to {} >> {}.", address, HexUtils.prettyHexString(data)); // Depending on the protocol of the XBee device, the packet to send may vary. XBeePacket xbeePacket; switch (getXBeeProtocol()) { case RAW_802_15_4: // Generate and send the Tx64 packet. xbeePacket = new TX64Packet(getNextFrameID(), address, XBeeTransmitOptions.NONE, data); break; default: // Generate and send the Transmit packet. xbeePacket = new TransmitPacket(getNextFrameID(), address, XBee16BitAddress.UNKNOWN_ADDRESS, 0, XBeeTransmitOptions.NONE, data); } sendAndCheckXBeePacket(xbeePacket, false); } /** * Sends the provided data to the XBee device of the network corresponding * to the given 16-bit address. * * <p>This method blocks till a success or error response arrives or the * configured receive timeout expires.</p> * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>For non-blocking operations use the method * {@link #sendSerialData(XBee16BitAddress, byte[])}.</p> * * @param address The 16-bit address of the XBee that will receive the data. * @param data Byte array containing data to be sent. * * @throws TimeoutException if there is a timeout sending the serial data. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code address == null} or * if {@code data == null}. * * @see XBee16BitAddress * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) * @see #sendSerialData(XBee64BitAddress, byte[]) * @see #sendSerialData(XBeeDevice, byte[]) * @see #sendSerialDataAsync(XBee64BitAddress, byte[]) * @see #sendSerialDataAsync(XBee16BitAddress, byte[]) * @see #sendSerialDataAsync(XBeeDevice, byte[]) */ public void sendSerialData(XBee16BitAddress address, byte[] data) throws TimeoutException, XBeeException { // Verify the parameters are not null, if they are null, throw an exception. if (address == null) throw new NullPointerException("Address cannot be null"); if (data == null) throw new NullPointerException("Data cannot be null"); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if device is remote. if (isRemote()) throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device."); logger.info(toString() + "Sending serial data to {} >> {}.", address, HexUtils.prettyHexString(data)); // Depending on the protocol of the XBee device, the packet to send may vary. XBeePacket xbeePacket; switch (getXBeeProtocol()) { case RAW_802_15_4: // Generate and send the Tx16 packet. xbeePacket = new TX16Packet(getNextFrameID(), address, XBeeTransmitOptions.NONE, data); break; default: // Generate and send the Transmit packet. xbeePacket = new TransmitPacket(getNextFrameID(), XBee64BitAddress.UNKNOWN_ADDRESS, address, 0, XBeeTransmitOptions.NONE, data); } sendAndCheckXBeePacket(xbeePacket, false); } /** * Sends the provided data to the XBee device of the network corresponding * to the given 64-Bit/16-Bit address. * * <p>This method blocks till a success or error response arrives or the * configured receive timeout expires.</p> * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>For non-blocking operations use the method * {@link #sendSerialData(XBee16BitAddress, byte[])}.</p> * * @param address64Bit The 64-bit address of the XBee that will receive the * data. * @param address16bit The 16-bit address of the XBee that will receive the * data. If it is unknown the * {@code XBee16BitAddress.UNKNOWN_ADDRESS} must be used. * @param data Byte array containing data to be sent. * * @throws TimeoutException if there is a timeout sending the serial data. * @throws XBeeException if a remote device is trying to send serial data or * if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code address64Bit == null} or * if {@code address16bit == null} or * if {@code data == null}. * * @see XBee64BitAddress * @see XBee16BitAddress * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) * @see #sendSerialData(XBee64BitAddress, byte[]) * @see #sendSerialData(XBee16BitAddress, byte[]) * @see #sendSerialData(XBeeDevice, byte[]) * @see #sendSerialDataAsync(XBee64BitAddress, byte[]) * @see #sendSerialDataAsync(XBee16BitAddress, byte[]) * @see #sendSerialDataAsync(XBee64BitAddress, XBee16BitAddress, byte[]) * @see #sendSerialDataAsync(XBeeDevice, byte[]) */ public void sendSerialData(XBee64BitAddress address64Bit, XBee16BitAddress address16bit, byte[] data) throws TimeoutException, XBeeException { // Verify the parameters are not null, if they are null, throw an exception. if (address64Bit == null) throw new NullPointerException("64-bit address cannot be null"); if (address16bit == null) throw new NullPointerException("16-bit address cannot be null"); if (data == null) throw new NullPointerException("Data cannot be null"); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if device is remote. if (isRemote()) throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device."); logger.info(toString() + "Sending serial data to {}[{}] >> {}.", address64Bit, address16bit, HexUtils.prettyHexString(data)); // Depending on the protocol of the XBee device, the packet to send may vary. XBeePacket xbeePacket; switch (getXBeeProtocol()) { case RAW_802_15_4: // TODO We don't know which address should be used: 16-bit/64-bit. // For the moment we are going to use 64-bit address by default. xbeePacket = new TX64Packet(getNextFrameID(), address64Bit, XBeeTransmitOptions.NONE, data); break; default: // Generate and send the Transmit packet. xbeePacket = new TransmitPacket(getNextFrameID(), address64Bit, address16bit, 0, XBeeTransmitOptions.NONE, data); } sendAndCheckXBeePacket(xbeePacket, false); } /** * Sends the provided data to the given XBee device. * * <p>This method blocks till a success or error response arrives or the * configured receive timeout expires.</p> * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>For non-blocking operations use the method * {@link #sendSerialDataAsync(XBeeDevice, byte[])}.</p> * * @param xbeeDevice The XBee device of the network that will receive the data. * @param data Byte array containing data to be sent. * * @throws TimeoutException if there is a timeout sending the serial data. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code xbeeDevice == null} or * if {@code data == null}. * * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) * @see #sendSerialData(XBee64BitAddress, byte[]) * @see #sendSerialData(XBee16BitAddress, byte[]) * @see #sendSerialDataAsync(XBee64BitAddress, byte[]) * @see #sendSerialDataAsync(XBee16BitAddress, byte[]) * @see #sendSerialDataAsync(XBeeDevice, byte[]) */ public void sendSerialData(XBeeDevice xbeeDevice, byte[] data) throws TimeoutException, XBeeException { if (xbeeDevice == null) throw new NullPointerException("XBee device cannot be null"); sendSerialData(xbeeDevice.get64BitAddress(), data); } /** * Sends the provided {@code XBeePacket} and determines if the transmission * status is success for synchronous transmissions. If the status is not * success, an {@code TransmitException} is thrown. * * @param packet The {@code XBeePacket} to be sent. * @param asyncTransmission Determines whether or not the transmission * should be made asynchronously. * * @throws TransmitException if {@code packet} is not an instance of {@code TransmitStatusPacket} or * if {@code packet} is not an instance of {@code TXStatusPacket} or * if its transmit status is different than {@code XBeeTransmitStatus.SUCCESS}. * @throws XBeeException if there is any other XBee related error. * * @see XBeePacket */ private void sendAndCheckXBeePacket(XBeePacket packet, boolean asyncTransmission) throws TransmitException, XBeeException { XBeePacket receivedPacket = null; // Send the XBee packet. try { if (asyncTransmission) sendXBeePacketAsync(packet, true); else receivedPacket = sendXBeePacket(packet, true); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // If the transmission is async. we are done. if (asyncTransmission) return; // Check if the packet received is a valid transmit status packet. if (receivedPacket == null) throw new TransmitException(null); if (receivedPacket instanceof TransmitStatusPacket) { if (((TransmitStatusPacket)receivedPacket).getTransmitStatus() == null) throw new TransmitException(null); else if (((TransmitStatusPacket)receivedPacket).getTransmitStatus() != XBeeTransmitStatus.SUCCESS) throw new TransmitException(((TransmitStatusPacket)receivedPacket).getTransmitStatus()); } else if (receivedPacket instanceof TXStatusPacket) { if (((TXStatusPacket)receivedPacket).getTransmitStatus() == null) throw new TransmitException(null); else if (((TXStatusPacket)receivedPacket).getTransmitStatus() != XBeeTransmitStatus.SUCCESS) throw new TransmitException(((TXStatusPacket)receivedPacket).getTransmitStatus()); } else throw new TransmitException(null); } /** * Sets the configuration of the given IO line. * * @param ioLine The IO line to configure. * @param mode The IO mode to set to the IO line. * * @throws TimeoutException if there is a timeout sending the set * configuration command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code ioLine == null} or * if {@code ioMode == null}. * * @see IOLine * @see IOMode * @see #getIOConfiguration(IOLine) */ public void setIOConfiguration(IOLine ioLine, IOMode ioMode) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); if (ioMode == null) throw new NullPointerException("IO mode cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Create and send the AT Command. String atCommand = ioLine.getConfigurationATCommand(); ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(atCommand, new byte[]{(byte)ioMode.getID()})); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); } /** * Retrieves the configuration mode of the provided IO line. * * @param ioLine The IO line to get its configuration. * * @return The IO mode (configuration) of the provided IO line. * * @throws TimeoutException if there is a timeout sending the get * configuration command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code ioLine == null}. * * @see IOLine * @see IOMode * @see #setIOConfiguration(IOLine, IOMode) */ public IOMode getIOConfiguration(IOLine ioLine) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("DIO pin cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Create and send the AT Command. ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(ioLine.getConfigurationATCommand())); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); // Check if the response contains the configuration value. if (response.getResponse() == null || response.getResponse().length == 0) throw new OperationNotSupportedException("Answer does not conain the configuration value."); // Check if the received configuration mode is valid. int ioModeValue = response.getResponse()[0]; IOMode dioMode = IOMode.getIOMode(ioModeValue, ioLine); if (dioMode == null) throw new OperationNotSupportedException("Received configuration mode '" + HexUtils.integerToHexString(ioModeValue, 1) + "' is not valid."); // Return the configuration mode. return dioMode; } /** * Sets the digital value (high or low) to the provided IO line. * * @param ioLine The IO line to set its value. * @param value The IOValue to set to the IO line ({@code HIGH} or * {@code LOW}). * * @throws TimeoutException if there is a timeout sending the set DIO * command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code ioLine == null} or * if {@code ioValue == null}. * * @see IOLine * @see IOValue * @see IOMode#DIGITAL_OUT_HIGH * @see IOMode#DIGITAL_OUT_LOW * @see #getIOConfiguration(IOLine) * @see #setIOConfiguration(IOLine, IOMode) */ public void setDIOValue(IOLine ioLine, IOValue ioValue) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Check IO value. if (ioValue == null) throw new NullPointerException("IO value cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Create and send the AT Command. String atCommand = ioLine.getConfigurationATCommand(); byte[] valueByte = new byte[]{(byte)ioValue.getID()}; ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(atCommand, valueByte)); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); } /** * Retrieves the digital value of the provided IO line (must be configured * as digital I/O). * * @param ioLine The IO line to get its digital value. * * @return The digital value corresponding to the provided IO line. * * @throws TimeoutException if there is a timeout sending the get IO values * command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code ioLine == null}. * * @see IOLine * @see IOMode#DIGITAL_IN * @see IOMode#DIGITAL_OUT_HIGH * @see IOMode#DIGITAL_OUT_LOW * @see #getIOConfiguration(IOLine) * @see #setIOConfiguration(IOLine, IOMode) */ public IOValue getDIOValue(IOLine ioLine) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Create and send the AT Command. ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(ioLine.getReadIOATCommand())); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); IOSample ioSample; byte[] samplePayload = null; // If the protocol is 802.15.4 we need to receive an Rx16 or Rx64 IO packet if (getXBeeProtocol() == XBeeProtocol.RAW_802_15_4) { samplePayload = receiveIOPacket(); if (samplePayload == null) throw new TimeoutException("Timeout waiting for the IO response packet."); } else samplePayload = response.getResponse(); // Try to build an IO Sample from the sample payload. try { ioSample = new IOSample(samplePayload); } catch (IllegalArgumentException e) { throw new XBeeException("Couldn't create the IO sample.", e); } catch (NullPointerException e) { throw new XBeeException("Couldn't create the IO sample.", e); } // Check if the IO sample contains the expected IO line and value. if (!ioSample.hasDigitalValues() || !ioSample.getDigitalValues().containsKey(ioLine)) throw new OperationNotSupportedException("Answer does not conain digital data for " + ioLine.getName() + "."); // Return the digital value. return ioSample.getDigitalValues().get(ioLine); } /** * Sets the duty cycle (in %) of the provided IO line. * * <p>IO line must be PWM capable({@code hasPWMCapability()}) and * it must be configured as PWM Output ({@code IOMode.PWM}).</p> * * @param ioLine The IO line to set its duty cycle value. * @param value The duty cycle of the PWM. * * @throws TimeoutException if there is a timeout sending the set PWM duty * cycle command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws IllegalArgumentException if {@code ioLine.hasPWMCapability() == false} or * if {@code value < 0} or * if {@code value > 1023}. * @throws NullPointerException if {@code ioLine == null}. * * @see IOLine * @see IOMode#PWM * @see #getPWMDutyCycle(IOLine) * @see #getIOConfiguration(IOLine) * @see #setIOConfiguration(IOLine, IOMode) */ public void setPWMDutyCycle(IOLine ioLine, double dutyCycle) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Check if the IO line has PWM capability. if (!ioLine.hasPWMCapability()) throw new IllegalArgumentException("Provided IO line does not have PWM capability."); // Check duty cycle limits. if (dutyCycle < 0 || dutyCycle > 100) throw new IllegalArgumentException("Duty Cycle must be between 0% and 100%."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Convert the value. int finaldutyCycle = (int)(dutyCycle * 1023.0/100.0); // Create and send the AT Command. String atCommand = ioLine.getPWMDutyCycleATCommand(); ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(atCommand, ByteUtils.intToByteArray(finaldutyCycle))); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); } /** * Gets the PWM duty cycle (in %) corresponding to the provided IO line. * * <p>IO line must be PWM capable ({@code hasPWMCapability()}) and * it must be configured as PWM Output ({@code IOMode.PWM}).</p> * * @param ioLine The IO line to get its PWM duty cycle. * * @return The PWM duty cycle value corresponding to the provided IO line * (0% - 100%). * * @throws TimeoutException if there is a timeout sending the get PWM duty * cycle command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws IllegalArgumentException if {@code ioLine.hasPWMCapability() == false}. * @throws NullPointerException if {@code ioLine == null}. * * @see IOLine * @see IOMode#PWM * @see #setPWMDutyCycle(IOLine, double) * @see #getIOConfiguration(IOLine) * @see #setIOConfiguration(IOLine, IOMode) */ public double getPWMDutyCycle(IOLine ioLine) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Check if the IO line has PWM capability. if (!ioLine.hasPWMCapability()) throw new IllegalArgumentException("Provided IO line does not have PWM capability."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Create and send the AT Command. ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(ioLine.getPWMDutyCycleATCommand())); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); // Check if the response contains the PWM value. if (response.getResponse() == null || response.getResponse().length == 0) throw new OperationNotSupportedException("Answer does not conain PWM duty cycle value."); // Return the PWM duty cycle value. int readValue = ByteUtils.byteArrayToInt(response.getResponse()); return Math.round((readValue * 100.0/1023.0) * 100.0) / 100.0; } /** * Retrieves the analog value of the provided IO line (must be configured * as ADC). * * @param ioLine The IO line to get its analog value. * * @return The analog value corresponding to the provided IO line. * * @throws TimeoutException if there is a timeout sending the get IO values * command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code ioLine == null}. * * @see IOLine * @see IOMode#ADC * @see #getIOConfiguration(IOLine) * @see #setIOConfiguration(IOLine, IOMode) */ public int getADCValue(IOLine ioLine) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Create and send the AT Command. ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(ioLine.getReadIOATCommand())); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); IOSample ioSample; byte[] samplePayload = null; // If the protocol is 802.15.4 we need to receive an Rx16 or Rx64 IO packet if (getXBeeProtocol() == XBeeProtocol.RAW_802_15_4) { samplePayload = receiveIOPacket(); if (samplePayload == null) throw new TimeoutException("Timeout waiting for the IO response packet."); } else samplePayload = response.getResponse(); // Try to build an IO Sample from the sample payload. try { ioSample = new IOSample(samplePayload); } catch (IllegalArgumentException e) { throw new XBeeException("Couldn't create the IO sample.", e); } catch (NullPointerException e) { throw new XBeeException("Couldn't create the IO sample.", e); } // Check if the IO sample contains the expected IO line and value. if (!ioSample.hasAnalogValues() || !ioSample.getAnalogValues().containsKey(ioLine)) throw new OperationNotSupportedException("Answer does not conain analog data for " + ioLine.getName() + "."); // Return the analog value. return ioSample.getAnalogValues().get(ioLine); } /** * Checks if the provided {@code ATCommandResponse} is valid throwing an * {@code ATCommandException} in case it is not. * * @param response The {@code ATCommandResponse} to check. * * @throws ATCommandException if {@code response == null} or * if {@code response.getResponseStatus() != ATCommandStatus.OK}. */ private void checkATCommandResponseIsValid(ATCommandResponse response) throws ATCommandException { if (response == null || response.getResponseStatus() == null) throw new ATCommandException(null); else if (response.getResponseStatus() != ATCommandStatus.OK) throw new ATCommandException(response.getResponseStatus()); } /** * Retrieves the latest IO packet and returns its value. * * @return The value of the latest received IO packet. */ private byte[] receiveIOPacket() { ioPacketReceived = false; ioPacketPayload = null; startListeningForPackets(IOPacketReceiveListener); synchronized (ioLock) { try { ioLock.wait(receiveTimeout); } catch (InterruptedException e) { } } stopListeningForPackets(IOPacketReceiveListener); if (ioPacketReceived) return ioPacketPayload; return null; } /** * Custom listener for IO packets. It will try to receive an IO sample packet. * * <p>When an IO sample packet is received, it saves its payload and notifies * the object that was waiting for the reception.</p> */ private IPacketReceiveListener IOPacketReceiveListener = new IPacketReceiveListener() { /* * (non-Javadoc) * @see com.digi.xbee.api.listeners.IPacketReceiveListener#packetReceived(com.digi.xbee.api.packet.XBeePacket) */ public void packetReceived(XBeePacket receivedPacket) { // Discard non API packets. if (!(receivedPacket instanceof XBeeAPIPacket)) return; // If we already have received an IO packet, ignore this packet. if (ioPacketReceived) return; // Save the packet value (IO sample payload) switch (((XBeeAPIPacket)receivedPacket).getFrameType()) { case IO_DATA_SAMPLE_RX_INDICATOR: ioPacketPayload = ((IODataSampleRxIndicatorPacket)receivedPacket).getReceivedData(); break; case RX_IO_16: ioPacketPayload = ((RX16IOPacket)receivedPacket).getReceivedData(); break; case RX_IO_64: ioPacketPayload = ((RX64IOPacket)receivedPacket).getReceivedData(); break; default: return; } // Set the IO packet received flag. ioPacketReceived = true; // Continue execution by notifying the lock object. synchronized (ioLock) { ioLock.notify(); } } }; /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return connectionInterface.toString(); } }
src/com/digi/xbee/api/XBeeDevice.java
/** * Copyright (c) 2014 Digi International Inc., * All rights not expressly granted are 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/. * * Digi International Inc. 11001 Bren Road East, Minnetonka, MN 55343 * ======================================================================= */ package com.digi.xbee.api; import java.io.IOException; import java.util.ArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.digi.xbee.api.connection.IConnectionInterface; import com.digi.xbee.api.connection.DataReader; import com.digi.xbee.api.connection.serial.SerialPortParameters; import com.digi.xbee.api.exceptions.ATCommandException; import com.digi.xbee.api.exceptions.InterfaceAlreadyOpenException; import com.digi.xbee.api.exceptions.InterfaceNotOpenException; import com.digi.xbee.api.exceptions.InvalidOperatingModeException; import com.digi.xbee.api.exceptions.OperationNotSupportedException; import com.digi.xbee.api.exceptions.TimeoutException; import com.digi.xbee.api.exceptions.TransmitException; import com.digi.xbee.api.exceptions.XBeeException; import com.digi.xbee.api.io.IOLine; import com.digi.xbee.api.io.IOMode; import com.digi.xbee.api.io.IOSample; import com.digi.xbee.api.io.IOValue; import com.digi.xbee.api.listeners.IPacketReceiveListener; import com.digi.xbee.api.listeners.ISerialDataReceiveListener; import com.digi.xbee.api.models.ATCommand; import com.digi.xbee.api.models.ATCommandResponse; import com.digi.xbee.api.models.ATCommandStatus; import com.digi.xbee.api.models.XBee16BitAddress; import com.digi.xbee.api.models.XBee64BitAddress; import com.digi.xbee.api.models.OperatingMode; import com.digi.xbee.api.models.XBeeProtocol; import com.digi.xbee.api.models.XBeeTransmitOptions; import com.digi.xbee.api.models.XBeeTransmitStatus; import com.digi.xbee.api.packet.XBeeAPIPacket; import com.digi.xbee.api.packet.APIFrameType; import com.digi.xbee.api.packet.XBeePacket; import com.digi.xbee.api.packet.common.ATCommandPacket; import com.digi.xbee.api.packet.common.ATCommandResponsePacket; import com.digi.xbee.api.packet.common.IODataSampleRxIndicatorPacket; import com.digi.xbee.api.packet.common.RemoteATCommandPacket; import com.digi.xbee.api.packet.common.RemoteATCommandResponsePacket; import com.digi.xbee.api.packet.common.TransmitPacket; import com.digi.xbee.api.packet.common.TransmitStatusPacket; import com.digi.xbee.api.packet.raw.RX16IOPacket; import com.digi.xbee.api.packet.raw.RX64IOPacket; import com.digi.xbee.api.packet.raw.TX16Packet; import com.digi.xbee.api.packet.raw.TX64Packet; import com.digi.xbee.api.packet.raw.TXStatusPacket; import com.digi.xbee.api.utils.ByteUtils; import com.digi.xbee.api.utils.HexUtils; public class XBeeDevice { // Constants. protected static int DEFAULT_RECEIVE_TIMETOUT = 2000; // 2.0 seconds of timeout to receive packet and command responses. protected static int TIMEOUT_BEFORE_COMMAND_MODE = 1200; protected static int TIMEOUT_ENTER_COMMAND_MODE = 1500; private static String COMMAND_MODE_CHAR = "+"; private static String COMMAND_MODE_OK = "OK\r"; // Variables. protected IConnectionInterface connectionInterface; protected DataReader dataReader = null; protected XBeeProtocol xbeeProtocol = XBeeProtocol.UNKNOWN; protected OperatingMode operatingMode = OperatingMode.UNKNOWN; protected XBee64BitAddress xbee64BitAddress; protected int currentFrameID = 0xFF; protected int receiveTimeout = DEFAULT_RECEIVE_TIMETOUT; private Logger logger; private XBeeDevice localXBeeDevice; private Object ioLock = new Object(); private boolean ioPacketReceived = false; private byte[] ioPacketPayload; /** * Class constructor. Instantiates a new {@code XBeeDevice} object in the * given port name and baud rate. * * @param port Serial port name where XBee device is attached to. * @param baudRate Serial port baud rate to communicate with the device. * Other connection parameters will be set as default (8 * data bits, 1 stop bit, no parity, no flow control). * * @throws NullPointerException if {@code port == null}. * @throws IllegalArgumentException if {@code baudRate < 0}. */ public XBeeDevice(String port, int baudRate) { this(XBee.createConnectiontionInterface(port, baudRate)); } /** * Class constructor. Instantiates a new {@code XBeeDevice} object in the * given serial port name and settings. * * @param port Serial port name where XBee device is attached to. * @param baudRate Serial port baud rate to communicate with the device. * @param dataBits Serial port data bits. * @param stopBits Serial port data bits. * @param parity Serial port data bits. * @param flowControl Serial port data bits. * * @throws NullPointerException if {@code port == null}. * @throws IllegalArgumentException if {@code baudRate < 0} or * if {@code dataBits < 0} or * if {@code stopBits < 0} or * if {@code parity < 0} or * if {@code flowControl < 0}. */ public XBeeDevice(String port, int baudRate, int dataBits, int stopBits, int parity, int flowControl) { this(port, new SerialPortParameters(baudRate, dataBits, stopBits, parity, flowControl)); } /** * Class constructor. Instantiates a new {@code XBeeDevice} object in the * given serial port name and parameters. * * @param port Serial port name where XBee device is attached to. * @param serialPortParameters Object containing the serial port parameters. * * @throws NullPointerException if {@code port == null} or * if {@code serialPortParameters == null}. * * @see SerialPortParameters */ public XBeeDevice(String port, SerialPortParameters serialPortParameters) { this(XBee.createConnectiontionInterface(port, serialPortParameters)); } /** * Class constructor. Instantiates a new {@code XBeeDevice} object with the * given connection interface. * * @param connectionInterface The connection interface with the physical * XBee device. * * @throws NullPointerException if {@code connectionInterface == null} * * @see IConnectionInterface */ public XBeeDevice(IConnectionInterface connectionInterface) { if (connectionInterface == null) throw new NullPointerException("ConnectionInterface cannot be null."); this.connectionInterface = connectionInterface; this.logger = LoggerFactory.getLogger(XBeeDevice.class); logger.debug(toString() + "Using the connection interface {}.", connectionInterface.getClass().getSimpleName(), connectionInterface.toString()); } /** * Class constructor. Instantiates a new remote {@code XBeeDevice} object * with the given local {@code XBeeDevice} which contains the connection * interface to be used. * * @param localXBeeDevice The local XBee device that will behave as * connection interface to communicate with this * remote XBee device * @param xbee64BitAddress The 64-bit address to identify this remote XBee * device. * @throws NullPointerException if {@code localXBeeDevice == null} or * if {@code xbee64BitAddress == null}. * * @see XBee64BitAddress */ public XBeeDevice(XBeeDevice localXBeeDevice, XBee64BitAddress xbee64BitAddress) { if (localXBeeDevice == null) throw new NullPointerException("Local XBee device cannot be null."); if (xbee64BitAddress == null) throw new NullPointerException("XBee 64 bit address of the remote device cannot be null."); if (localXBeeDevice.isRemote()) throw new IllegalArgumentException("The given local XBee device is remote."); this.localXBeeDevice = localXBeeDevice; this.connectionInterface = localXBeeDevice.getConnectionInterface(); this.xbee64BitAddress = xbee64BitAddress; this.logger = LoggerFactory.getLogger(XBeeDevice.class); logger.debug(toString() + "Using the connection interface {}.", connectionInterface.getClass().getSimpleName(), connectionInterface.toString()); } /** * Opens the connection interface associated with this XBee device. * * @throws XBeeException if there is any problem opening the device. * @throws InterfaceAlreadyOpenException if the device is already open. * * @see #isOpen() * @see #close() */ public void open() throws XBeeException { logger.info(toString() + "Opening the connection interface..."); // First, verify that the connection is not already open. if (connectionInterface.isOpen()) throw new InterfaceAlreadyOpenException(); // Connect the interface. connectionInterface.open(); logger.info(toString() + "Connection interface open."); // Data reader initialization and determining operating mode should be only // done for local XBee devices. if (isRemote()) return; // Initialize the data reader. dataReader = new DataReader(connectionInterface, operatingMode); dataReader.start(); // Determine the operating mode of the XBee device if it is unknown. if (operatingMode == OperatingMode.UNKNOWN) operatingMode = determineOperatingMode(); // Check if the operating mode is a valid and supported one. if (operatingMode == OperatingMode.UNKNOWN) { close(); throw new InvalidOperatingModeException("Could not determine operating mode."); } else if (operatingMode == OperatingMode.AT) { close(); throw new InvalidOperatingModeException(operatingMode); } } /** * Closes the connection interface associated with this XBee device. * * @see #isOpen() * @see #open() */ public void close() { // Stop XBee reader. if (dataReader != null && dataReader.isRunning()) dataReader.stopReader(); // Close interface. connectionInterface.close(); logger.info(toString() + "Connection interface closed."); } /** * Retrieves whether or not the connection interface associated to the * device is open. * * @return {@code true} if the interface is open, {@code false} otherwise. * * @see #open() * @see #close() */ public boolean isOpen() { if (connectionInterface != null) return connectionInterface.isOpen(); return false; } /** * Retrieves the connection interface associated to this XBee device. * * @return XBee device's connection interface. * * @see IConnectionInterface */ public IConnectionInterface getConnectionInterface() { return connectionInterface; } /** * Retrieves whether or not the XBee device is a remote device. * * @return {@code true} if the XBee device is a remote device, * {@code false} otherwise. */ public boolean isRemote() { return localXBeeDevice != null; } /** * Determines the operating mode of the XBee device. * * @return The operating mode of the XBee device. * * @throws OperationNotSupportedException if the packet is being sent from * a remote device. * @throws InterfaceNotOpenException if the device is not open. * * @see OperatingMode */ protected OperatingMode determineOperatingMode() throws OperationNotSupportedException { try { // Check if device is in API or API Escaped operating modes. operatingMode = OperatingMode.API; dataReader.setXBeeReaderMode(operatingMode); ATCommandResponse response = sendATCommand(new ATCommand("AP")); if (response.getResponse() != null && response.getResponse().length > 0) { if (response.getResponse()[0] != OperatingMode.API.getID()) operatingMode = OperatingMode.API_ESCAPE; logger.debug(toString() + "Using {}.", operatingMode.getName()); return operatingMode; } } catch (TimeoutException e) { // Check if device is in AT operating mode. operatingMode = OperatingMode.AT; dataReader.setXBeeReaderMode(operatingMode); try { // It is necessary to wait at least 1 second to enter in command mode after // sending any data to the device. Thread.sleep(TIMEOUT_BEFORE_COMMAND_MODE); // Try to enter in AT command mode, if so the module is in AT mode. boolean success = enterATCommandMode(); if (success) return OperatingMode.AT; } catch (TimeoutException e1) { logger.error(e1.getMessage(), e1); } catch (InvalidOperatingModeException e1) { logger.error(e1.getMessage(), e1); } catch (InterruptedException e1) { logger.error(e1.getMessage(), e1); } } catch (InvalidOperatingModeException e) { logger.error("Invalid operating mode", e); } catch (IOException e) { logger.error(e.getMessage(), e); } return OperatingMode.UNKNOWN; } /** * Attempts to put the device in AT Command mode. Only valid if device is * working in AT mode. * * @return {@code true} if the device entered in AT command mode, * {@code false} otherwise. * * @throws InvalidOperatingModeException if the operating mode cannot be * determined or is not supported. * @throws TimeoutException if the configured time expires. * @throws InterfaceNotOpenException if the device is not open. */ public boolean enterATCommandMode() throws InvalidOperatingModeException, TimeoutException { if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); if (operatingMode != OperatingMode.AT) throw new InvalidOperatingModeException("Invalid mode. Command mode can be only accessed while in AT mode."); // Enter in AT command mode (send '+++'). The process waits 1,5 seconds for the 'OK\n'. byte[] readData = new byte[256]; try { // Send the command mode sequence. connectionInterface.writeData(COMMAND_MODE_CHAR.getBytes()); connectionInterface.writeData(COMMAND_MODE_CHAR.getBytes()); connectionInterface.writeData(COMMAND_MODE_CHAR.getBytes()); // Wait some time to let the module generate a response. Thread.sleep(TIMEOUT_ENTER_COMMAND_MODE); // Read data from the device (it should answer with 'OK\r'). int readBytes = connectionInterface.readData(readData); if (readBytes < COMMAND_MODE_OK.length()) throw new TimeoutException(); // Check if the read data is 'OK\r'. String readString = new String(readData, 0, readBytes); if (!readString.contains(COMMAND_MODE_OK)) return false; // Read data was 'OK\r'. return true; } catch (IOException e) { logger.error(e.getMessage(), e); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } return false; } /** * Retrieves the 64-bit address of the XBee device. * * @return The 64-bit address of the XBee device. * * @see XBee64BitAddress */ public XBee64BitAddress get64BitAddress() { return xbee64BitAddress; } /** * Retrieves the Operating mode (AT, API or API escaped) of the XBee device. * * @return The operating mode of the XBee device. * * @see OperatingMode */ public OperatingMode getOperatingMode() { return operatingMode; } /** * Retrieves the XBee Protocol of the XBee device. * * @return The XBee device protocol. * * @see XBeeProtocol * @see #setXBeeProtocol(XBeeProtocol) */ public XBeeProtocol getXBeeProtocol() { return xbeeProtocol; } /** * Sets the XBee protocol of the XBee device. * * @param xbeeProtocol The XBee protocol to set. * * @see XBeeProtocol * @see #getXBeeProtocol() */ protected void setXBeeProtocol(XBeeProtocol xbeeProtocol) { this.xbeeProtocol = xbeeProtocol; } /** * Sends the given AT command and waits for answer or until the configured * receive timeout expires. * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * @param command AT command to be sent. * @return An {@code ATCommandResponse} object containing the response of * the command or {@code null} if there is no response. * * @throws InvalidOperatingModeException if the operating mode is different than {@link OperatingMode#API} and * {@link OperatingMode#API_ESCAPE}. * @throws TimeoutException if the configured time expires while waiting * for the command reply. * @throws OperationNotSupportedException if the packet is being sent from * a remote device. * @throws IOException if an I/O error occurs while sending the AT command. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code command == null}. * * @see ATCommand * @see ATCommandResponse * @see #setReceiveTimeout(int) * @see #getReceiveTimeout() */ public ATCommandResponse sendATCommand(ATCommand command) throws InvalidOperatingModeException, TimeoutException, OperationNotSupportedException, IOException { // Check if command is null. if (command == null) throw new NullPointerException("AT command cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); ATCommandResponse response = null; OperatingMode operatingMode = getOperatingMode(); switch (operatingMode) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(operatingMode); case API: case API_ESCAPE: // Create AT command packet XBeePacket packet; if (isRemote()) packet = new RemoteATCommandPacket(getNextFrameID(), get64BitAddress(), XBee16BitAddress.UNKNOWN_ADDRESS, XBeeTransmitOptions.NONE, command.getCommand(), command.getParameter()); else packet = new ATCommandPacket(getNextFrameID(), command.getCommand(), command.getParameter()); if (command.getParameter() == null) logger.debug(toString() + "Sending AT command '{}'.", command.getCommand()); else logger.debug(toString() + "Sending AT command '{} {}'.", command.getCommand(), HexUtils.prettyHexString(command.getParameter())); try { // Send the packet and build response. XBeePacket answerPacket = sendXBeePacket(packet, true); if (answerPacket instanceof ATCommandResponsePacket) response = new ATCommandResponse(command, ((ATCommandResponsePacket)answerPacket).getCommandValue(), ((ATCommandResponsePacket)answerPacket).getStatus()); else if (answerPacket instanceof RemoteATCommandResponsePacket) response = new ATCommandResponse(command, ((RemoteATCommandResponsePacket)answerPacket).getCommandValue(), ((RemoteATCommandResponsePacket)answerPacket).getStatus()); if (response.getResponse() != null) logger.debug(toString() + "AT command response: {}.", HexUtils.prettyHexString(response.getResponse())); else logger.debug(toString() + "AT command response: null."); } catch (ClassCastException e) { logger.error("Received an invalid packet type after sending an AT command packet." + e); } } return response; } /** * Sends the given XBee packet synchronously and blocks until the response * is received or the configured receive timeout expires. * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>Use {@link #sendXBeePacketAsync(XBeePacket)} for non-blocking * operations.</p> * * @param packet XBee packet to be sent. * * @return An {@code XBeePacket} object containing the response of the sent * packet or {@code null} if there is no response. * * @throws XBeeException if there is any error sending the XBee packet. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * * @see XBeePacket * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) * @see #sendXBeePacketAsync(XBeePacket) * @see #setReceiveTimeout(int) * @see #getReceiveTimeout() */ public XBeePacket sendXBeePacket(XBeePacket packet) throws XBeeException { try { return sendXBeePacket(packet, isRemote()); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } } /** * Sends the given XBee packet synchronously and blocks until response is * received or receive timeout is reached. * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>Use {@link #sendXBeePacketAsync(XBeePacket, boolean)} for non-blocking * operations.</p> * * @param packet XBee packet to be sent. * @param sentFromLocalDevice Indicates whether or not the packet was sent * from a local device. * @return An {@code XBeePacket} containing the response of the sent packet * or {@code null} if there is no response. * * @throws InvalidOperatingModeException if the operating mode is different than {@link OperatingMode#API} and * {@link OperatingMode#API_ESCAPE}. * @throws TimeoutException if the configured time expires while waiting for the packet reply. * @throws OperationNotSupportedException if the packet is being sent from a remote device. * @throws IOException if an I/O error occurs while sending the XBee packet. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * * @see XBeePacket * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener, boolean) * @see #sendXBeePacketAsync(XBeePacket) * @see #sendXBeePacketAsync(XBeePacket, boolean) * @see #setReceiveTimeout(int) * @see #getReceiveTimeout() */ private XBeePacket sendXBeePacket(final XBeePacket packet, boolean sentFromLocalDevice) throws InvalidOperatingModeException, TimeoutException, OperationNotSupportedException, IOException { // Check if the packet to send is null. if (packet == null) throw new NullPointerException("XBee packet cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if the packet is being sent from a remote device. if (!sentFromLocalDevice) throw new OperationNotSupportedException("Remote devices cannot send data to other remote devices."); OperatingMode operatingMode = getOperatingMode(); switch (operatingMode) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(operatingMode); case API: case API_ESCAPE: // Build response container. ArrayList<XBeePacket> responseList = new ArrayList<XBeePacket>(); // If the packet does not need frame ID, send it async. and return null. if (packet instanceof XBeeAPIPacket) { if (!((XBeeAPIPacket)packet).needsAPIFrameID()) { sendXBeePacketAsync(packet, sentFromLocalDevice); return null; } } else { sendXBeePacketAsync(packet, sentFromLocalDevice); return null; } // Add the required frame ID to the packet if necessary. insertFrameID(packet); // Generate a packet received listener for the packet to be sent. IPacketReceiveListener packetReceiveListener = createPacketReceivedListener(packet, responseList); // Add the packet listener to the data reader. dataReader.addPacketReceiveListener(packetReceiveListener); // Write the packet data. writePacket(packet); try { // Wait for response or timeout. synchronized (responseList) { try { responseList.wait(receiveTimeout); } catch (InterruptedException e) {} } // After the wait check if we received any response, if not throw timeout exception. if (responseList.size() < 1) throw new TimeoutException(); // Return the received packet. return responseList.get(0); } finally { // Always remove the packet listener from the list. dataReader.removePacketReceiveListener(packetReceiveListener); } } } /** * Insert (if possible) the next frame ID stored in the device to the * provided packet. * * @param xbeePacket The packet to add the frame ID. * * @see XBeePacket */ private void insertFrameID(XBeePacket xbeePacket) { if (xbeePacket instanceof XBeeAPIPacket) return; if (((XBeeAPIPacket)xbeePacket).needsAPIFrameID() && ((XBeeAPIPacket)xbeePacket).getFrameID() == XBeeAPIPacket.NO_FRAME_ID) ((XBeeAPIPacket)xbeePacket).setFrameID(getNextFrameID()); } /** * Retrieves the packet listener corresponding to the provided sent packet. * * <p>The listener will filter those packets matching with the Frame ID of * the sent packet storing them in the provided responseList array.</p> * * @param sentPacket The packet sent. * @param responseList List of packets received that correspond to the * frame ID of the packet sent. * * @return A packet receive listener that will filter the packets received * corresponding to the sent one. * * @see IPacketReceiveListener * @see XBeePacket */ private IPacketReceiveListener createPacketReceivedListener(final XBeePacket sentPacket, final ArrayList<XBeePacket> responseList) { IPacketReceiveListener packetReceiveListener = new IPacketReceiveListener() { /* * (non-Javadoc) * @see com.digi.xbee.api.listeners.IPacketReceiveListener#packetReceived(com.digi.xbee.api.packet.XBeePacket) */ @Override public void packetReceived(XBeePacket receivedPacket) { // Check if it is the packet we are waiting for. if (((XBeeAPIPacket)receivedPacket).checkFrameID((((XBeeAPIPacket)sentPacket).getFrameID()))) { // Security check to avoid class cast exceptions. It has been observed that parallel processes // using the same connection but with different frame index may collide and cause this exception at some point. if (sentPacket instanceof XBeeAPIPacket && receivedPacket instanceof XBeeAPIPacket) { XBeeAPIPacket sentAPIPacket = (XBeeAPIPacket)sentPacket; XBeeAPIPacket receivedAPIPacket = (XBeeAPIPacket)receivedPacket; // If the packet sent is an AT command, verify that the received one is an AT command response and // the command matches in both packets. if (sentAPIPacket.getFrameType() == APIFrameType.AT_COMMAND) { if (receivedAPIPacket.getFrameType() != APIFrameType.AT_COMMAND_RESPONSE) return; if (!((ATCommandPacket)sentAPIPacket).getCommand().equalsIgnoreCase(((ATCommandResponsePacket)receivedPacket).getCommand())) return; } // If the packet sent is a remote AT command, verify that the received one is a remote AT command response and // the command matches in both packets. if (sentAPIPacket.getFrameType() == APIFrameType.REMOTE_AT_COMMAND_REQUEST) { if (receivedAPIPacket.getFrameType() != APIFrameType.REMOTE_AT_COMMAND_RESPONSE) return; if (!((RemoteATCommandPacket)sentAPIPacket).getCommand().equalsIgnoreCase(((RemoteATCommandResponsePacket)receivedPacket).getCommand())) return; } } // Verify that the sent packet is not the received one! This can happen when the echo mode is enabled in the // serial port. if (!isSamePacket(sentPacket, receivedPacket)) { responseList.add(receivedPacket); synchronized (responseList) { responseList.notify(); } } } } }; return packetReceiveListener; } /** * Retrieves whether or not the sent packet is the same than the received one. * * @param sentPacket The packet sent. * @param receivedPacket The packet received. * * @return {@code true} if the sent packet is the same than the received * one, {@code false} otherwise. * * @see XBeePacket */ private boolean isSamePacket(XBeePacket sentPacket, XBeePacket receivedPacket) { // TODO Should not we implement the {@code equals} method in the XBeePacket?? if (HexUtils.byteArrayToHexString(sentPacket.generateByteArray()).equals(HexUtils.byteArrayToHexString(receivedPacket.generateByteArray()))) return true; return false; } /** * Sends the given XBee packet asynchronously and registers the given packet * listener (if not {@code null}) to wait for an answer. * * @param packet XBee packet to be sent. * @param packetReceiveListener Listener for the operation, {@code null} * not to be notified when the answer arrives. * * @throws InvalidOperatingModeException if the operating mode is different than {@link OperatingMode#API} and * {@link OperatingMode#API_ESCAPE}. * @throws OperationNotSupportedException if the packet is being sent from a remote device. * @throws IOException if an I/O error occurs while sending the XBee packet. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * * @see XBeePacket * @see IPacketReceiveListener * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacket(XBeePacket, boolean) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) * @see #sendXBeePacketAsync(XBeePacket) * @see #sendXBeePacketAsync(XBeePacket, boolean) */ private void sendXBeePacket(XBeePacket packet, IPacketReceiveListener packetReceiveListener, boolean sentFromLocalDevice) throws InvalidOperatingModeException, OperationNotSupportedException, IOException { // Check if the packet to send is null. if (packet == null) throw new NullPointerException("XBee packet cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if the packet is being sent from a remote device. if (!sentFromLocalDevice) throw new OperationNotSupportedException("Remote devices cannot send data to other remote devices."); OperatingMode operatingMode = getOperatingMode(); switch (operatingMode) { case AT: case UNKNOWN: default: throw new InvalidOperatingModeException(operatingMode); case API: case API_ESCAPE: // Add the required frame ID and subscribe listener if given. if (packet instanceof XBeeAPIPacket) { if (((XBeeAPIPacket)packet).needsAPIFrameID()) { if (((XBeeAPIPacket)packet).getFrameID() == XBeeAPIPacket.NO_FRAME_ID) ((XBeeAPIPacket)packet).setFrameID(getNextFrameID()); if (packetReceiveListener != null) dataReader.addPacketReceiveListener(packetReceiveListener, ((XBeeAPIPacket)packet).getFrameID()); } else if (packetReceiveListener != null) dataReader.addPacketReceiveListener(packetReceiveListener); } // Write packet data. writePacket(packet); break; } } /** * Sends the given XBee packet asynchronously. * * <p>To be notified when the answer is received, use * {@link #sendXBeePacket(XBeePacket, IPacketReceiveListener)}.</p> * * @param packet XBee packet to be sent asynchronously. * * @throws InvalidOperatingModeException if the operating mode is different than {@link OperatingMode#API} and * {@link OperatingMode#API_ESCAPE}. * @throws OperationNotSupportedException if the packet is being sent from a remote device. * @throws IOException if an I/O error occurs while sending the XBee packet. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * * @see XBeePacket * @see #sendXBeePacketAsync(XBeePacket) * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacket(XBeePacket, boolean) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener, boolean) */ private void sendXBeePacketAsync(XBeePacket packet, boolean sentFromLocalDevice) throws InvalidOperatingModeException, OperationNotSupportedException, IOException { sendXBeePacket(packet, null, sentFromLocalDevice); } /** * Sends the given XBee packet and registers the given packet listener * (if not {@code null}) to wait for an answer. * * @param packet XBee packet to be sent. * @param packetReceiveListener Listener for the operation, {@code null} * not to be notified when the answer arrives. * * @throws XBeeException if there is any error sending the XBee packet. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * * @see XBeePacket * @see IPacketReceiveListener * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacketAsync(XBeePacket) */ public void sendXBeePacket(XBeePacket packet, IPacketReceiveListener packetReceiveListener) throws XBeeException { try { sendXBeePacket(packet, packetReceiveListener, isRemote()); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } } /** * Sends the given XBee packet asynchronously. * * <p>To be notified when the answer is received, use * {@link #sendXBeePacket(XBeePacket, IPacketReceiveListener)}.</p> * * @param packet XBee packet to be sent asynchronously. * * @throws XBeeException if there is any error sending the XBee packet. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code packet == null}. * * @see XBeePacket * @see #sendXBeePacket(XBeePacket) * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener) */ public void sendXBeePacketAsync(XBeePacket packet) throws IOException, XBeeException { try { sendXBeePacket(packet, null, isRemote()); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } } /** * Writes the given XBee packet in the connection interface. * * @param packet XBee packet to be written. * * @throws IOException if an I/O error occurs while writing the XBee packet * in the connection interface. */ protected void writePacket(XBeePacket packet) throws IOException { logger.debug(toString() + "Sending XBee packet: \n{}", packet.toPrettyString()); // Write bytes with the required escaping mode. switch (operatingMode) { case API: default: connectionInterface.writeData(packet.generateByteArray()); break; case API_ESCAPE: connectionInterface.writeData(packet.generateByteArrayEscaped()); break; } } /** * Retrieves the next Frame ID of the XBee protocol. * * @return The next Frame ID. */ public int getNextFrameID() { if (currentFrameID == 0xff) { // Reset counter. currentFrameID = 1; } else currentFrameID ++; return currentFrameID; } /** * Retrieves the configured timeout for receiving packets in synchronous * operations. * * @return The current receive timeout in milliseconds. * * @see #setReceiveTimeout(int) */ public int getReceiveTimeout() { return receiveTimeout; } /** * Configures the timeout in milliseconds for receiving packets in * synchronous operations. * * @param receiveTimeout The new receive timeout in milliseconds. * * @throws IllegalArgumentException if {@code receiveTimeout < 0}. * * @see #getReceiveTimeout() */ public void setReceiveTimeout(int receiveTimeout) { if (receiveTimeout < 0) throw new IllegalArgumentException("Receive timeout cannot be less than 0."); this.receiveTimeout = receiveTimeout; } /** * Starts listening for packets in the provided packets listener. * * <p>The provided listener is added to the list of listeners to be notified * when new packets are received. If the listener has been already * included, this method does nothing.</p> * * @param listener Listener to be notified when new packets are received. * * @see IPacketReceiveListener * @see #stopListeningForPackets(IPacketReceiveListener) */ public void startListeningForPackets(IPacketReceiveListener listener) { if (dataReader == null) return; dataReader.addPacketReceiveListener(listener); } /** * Stops listening for packets in the provided packets listener. * * <p>The provided listener is removed from the list of packets listeners. * If the listener was not in the list this method does nothing.</p> * * @param listener Listener to be removed from the list of listeners. * * @see IPacketReceiveListener * @see #startListeningForPackets(IPacketReceiveListener) */ public void stopListeningForPackets(IPacketReceiveListener listener) { if (dataReader == null) return; dataReader.removePacketReceiveListener(listener); } /** * Starts listening for serial data in the provided serial data listener. * * <p>The provided listener is added to the list of listeners to be notified * when new serial data is received. If the listener has been already * included this method does nothing.</p> * * @param listener Listener to be notified when new serial data is received. * * @see ISerialDataReceiveListener * @see #stopListeningForSerialData(ISerialDataReceiveListener) */ public void startListeningForSerialData(ISerialDataReceiveListener listener) { if (dataReader == null) return; dataReader.addSerialDatatReceiveListener(listener); } /** * Stops listening for serial data in the provided serial data listener. * * <p>The provided listener is removed from the list of serial data * listeners. If the listener was not in the list this method does nothing.</p> * * @param listener Listener to be removed from the list of listeners. * * @see ISerialDataReceiveListener * @see #startListeningForSerialData(ISerialDataReceiveListener) */ public void stopListeningForSerialData(ISerialDataReceiveListener listener) { if (dataReader == null) return; dataReader.removeSerialDataReceiveListener(listener); } /** * Sends the provided data to the XBee device of the network corresponding * to the given 64-bit address asynchronously. * * <p>Asynchronous transmissions do not wait for answer from the remote * device or for transmit status packet</p> * * @param address The 64-bit address of the XBee that will receive the data. * @param data Byte array containing data to be sent. * * @throws XBeeException if there is any XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code address == null} or * if {@code data == null}. * * @see XBee64BitAddress * @see #sendSerialDataAsync(XBee16BitAddress, byte[]) * @see #sendSerialDataAsync(XBeeDevice, byte[]) * @see #sendSerialData(XBee16BitAddress, byte[]) * @see #sendSerialData(XBee64BitAddress, byte[]) * @see #sendSerialData(XBeeDevice, byte[]) */ public void sendSerialDataAsync(XBee64BitAddress address, byte[] data) throws XBeeException { // Verify the parameters are not null, if they are null, throw an exception. if (address == null) throw new NullPointerException("Address cannot be null"); if (data == null) throw new NullPointerException("Data cannot be null"); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if device is remote. if (isRemote()) throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device."); logger.info(toString() + "Sending serial data asynchronously to {} >> {}.", address, HexUtils.prettyHexString(data)); // Depending on the protocol of the XBee device, the packet to send may vary. XBeePacket xbeePacket; switch (getXBeeProtocol()) { case RAW_802_15_4: // Generate and send the Tx64 packet. xbeePacket = new TX64Packet(getNextFrameID(), address, XBeeTransmitOptions.NONE, data); break; default: // Generate and send the Transmit packet. xbeePacket = new TransmitPacket(getNextFrameID(), address, XBee16BitAddress.UNKNOWN_ADDRESS, 0, XBeeTransmitOptions.NONE, data); } sendAndCheckXBeePacket(xbeePacket, true); } /** * Sends the provided data to the XBee device of the network corresponding * to the given 16-bit address asynchronously. * * <p>Asynchronous transmissions do not wait for answer from the remote * device or for transmit status packet</p> * * @param address The 16-bit address of the XBee that will receive the data. * @param data Byte array containing data to be sent. * * @throws XBeeException if there is any XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code address == null} or * if {@code data == null}. * * @see XBee16BitAddress * @see #sendSerialDataAsync(XBee64BitAddress, byte[]) * @see #sendSerialDataAsync(XBeeDevice, byte[]) * @see #sendSerialData(XBee16BitAddress, byte[]) * @see #sendSerialData(XBee64BitAddress, byte[]) * @see #sendSerialData(XBeeDevice, byte[]) */ public void sendSerialDataAsync(XBee16BitAddress address, byte[] data) throws XBeeException { // Verify the parameters are not null, if they are null, throw an exception. if (address == null) throw new NullPointerException("Address cannot be null"); if (data == null) throw new NullPointerException("Data cannot be null"); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if device is remote. if (isRemote()) throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device."); logger.info(toString() + "Sending serial data asynchronously to {} >> {}.", address, HexUtils.prettyHexString(data)); // Depending on the protocol of the XBee device, the packet to send may vary. XBeePacket xbeePacket; switch (getXBeeProtocol()) { case RAW_802_15_4: // Generate and send the Tx16 packet. xbeePacket = new TX16Packet(getNextFrameID(), address, XBeeTransmitOptions.NONE, data); break; default: // Generate and send the Transmit packet. xbeePacket = new TransmitPacket(getNextFrameID(), XBee64BitAddress.UNKNOWN_ADDRESS, address, 0, XBeeTransmitOptions.NONE, data); } sendAndCheckXBeePacket(xbeePacket, true); } /** * Sends the provided data to the XBee device of the network corresponding * to the given 64-Bit/16-Bit address asynchronously. * * <p>Asynchronous transmissions do not wait for answer from the remote * device or for transmit status packet.</p> * * @param address64Bit The 64-bit address of the XBee that will receive the * data. * @param address16bit The 16-bit address of the XBee that will receive the * data. If it is unknown the * {@code XBee16BitAddress.UNKNOWN_ADDRESS} must be used. * @param data Byte array containing data to be sent. * * @throws XBeeException if a remote device is trying to send serial data or * if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code address64Bit == null} or * if {@code address16bit == null} or * if {@code data == null}. * * @see XBee64BitAddress * @see XBee16BitAddress * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) * @see #sendSerialData(XBee64BitAddress, byte[]) * @see #sendSerialData(XBee16BitAddress, byte[]) * @see #sendSerialData(XBee64BitAddress, XBee16BitAddress, byte[]) * @see #sendSerialData(XBeeDevice, byte[]) * @see #sendSerialDataAsync(XBee64BitAddress, byte[]) * @see #sendSerialDataAsync(XBee16BitAddress, byte[]) * @see #sendSerialDataAsync(XBeeDevice, byte[]) */ public void sendSerialDataAsync(XBee64BitAddress address64Bit, XBee16BitAddress address16bit, byte[] data) throws XBeeException { // Verify the parameters are not null, if they are null, throw an exception. if (address64Bit == null) throw new NullPointerException("64-bit address cannot be null"); if (address16bit == null) throw new NullPointerException("16-bit address cannot be null"); if (data == null) throw new NullPointerException("Data cannot be null"); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if device is remote. if (isRemote()) throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device."); logger.info(toString() + "Sending serial data asynchronously to {}[{}] >> {}.", address64Bit, address16bit, HexUtils.prettyHexString(data)); // Depending on the protocol of the XBee device, the packet to send may vary. XBeePacket xbeePacket; switch (getXBeeProtocol()) { case RAW_802_15_4: // TODO We don't know which address should be used: 16-bit/64-bit. // For the moment we are going to use 64-bit address by default. xbeePacket = new TX64Packet(getNextFrameID(), address64Bit, XBeeTransmitOptions.NONE, data); break; default: // Generate and send the Transmit packet. xbeePacket = new TransmitPacket(getNextFrameID(), address64Bit, address16bit, 0, XBeeTransmitOptions.NONE, data); } sendAndCheckXBeePacket(xbeePacket, true); } /** * Sends the provided data to the provided XBee device asynchronously. * * <p>Asynchronous transmissions do not wait for answer from the remote * device or for transmit status packet</p> * * @param xbeeDevice The XBee device of the network that will receive the data. * @param data Byte array containing data to be sent. * * @throws XBeeException if there is any XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code xbeeDevice == null} or * if {@code data == null}. * * @see #sendSerialDataAsync(XBee64BitAddress, byte[]) * @see #sendSerialDataAsync(XBee16BitAddress, byte[]) * @see #sendSerialData(XBee64BitAddress, byte[]) * @see #sendSerialData(XBee16BitAddress, byte[]) * @see #sendSerialData(XBeeDevice, byte[]) */ public void sendSerialDataAsync(XBeeDevice xbeeDevice, byte[] data) throws XBeeException { if (xbeeDevice == null) throw new NullPointerException("XBee device cannot be null"); sendSerialDataAsync(xbeeDevice.get64BitAddress(), data); } /** * Sends the provided data to the XBee device of the network corresponding * to the given 64-bit address. * * <p>This method blocks till a success or error response arrives or the * configured receive timeout expires.</p> * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>For non-blocking operations use the method * {@link #sendSerialData(XBee64BitAddress, byte[])}.</p> * * @param address The 64-bit address of the XBee that will receive the data. * @param data Byte array containing data to be sent. * * @throws TimeoutException if there is a timeout sending the serial data. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code address == null} or * if {@code data == null}. * * @see XBee64BitAddress * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) * @see #sendSerialData(XBee16BitAddress, byte[]) * @see #sendSerialData(XBeeDevice, byte[]) * @see #sendSerialDataAsync(XBee64BitAddress, byte[]) * @see #sendSerialDataAsync(XBee16BitAddress, byte[]) * @see #sendSerialDataAsync(XBeeDevice, byte[]) */ public void sendSerialData(XBee64BitAddress address, byte[] data) throws TimeoutException, XBeeException { // Verify the parameters are not null, if they are null, throw an exception. if (address == null) throw new NullPointerException("Address cannot be null"); if (data == null) throw new NullPointerException("Data cannot be null"); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if device is remote. if (isRemote()) throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device."); logger.info(toString() + "Sending serial data to {} >> {}.", address, HexUtils.prettyHexString(data)); // Depending on the protocol of the XBee device, the packet to send may vary. XBeePacket xbeePacket; switch (getXBeeProtocol()) { case RAW_802_15_4: // Generate and send the Tx64 packet. xbeePacket = new TX64Packet(getNextFrameID(), address, XBeeTransmitOptions.NONE, data); break; default: // Generate and send the Transmit packet. xbeePacket = new TransmitPacket(getNextFrameID(), address, XBee16BitAddress.UNKNOWN_ADDRESS, 0, XBeeTransmitOptions.NONE, data); } sendAndCheckXBeePacket(xbeePacket, false); } /** * Sends the provided data to the XBee device of the network corresponding * to the given 16-bit address. * * <p>This method blocks till a success or error response arrives or the * configured receive timeout expires.</p> * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>For non-blocking operations use the method * {@link #sendSerialData(XBee16BitAddress, byte[])}.</p> * * @param address The 16-bit address of the XBee that will receive the data. * @param data Byte array containing data to be sent. * * @throws TimeoutException if there is a timeout sending the serial data. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code address == null} or * if {@code data == null}. * * @see XBee16BitAddress * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) * @see #sendSerialData(XBee64BitAddress, byte[]) * @see #sendSerialData(XBeeDevice, byte[]) * @see #sendSerialDataAsync(XBee64BitAddress, byte[]) * @see #sendSerialDataAsync(XBee16BitAddress, byte[]) * @see #sendSerialDataAsync(XBeeDevice, byte[]) */ public void sendSerialData(XBee16BitAddress address, byte[] data) throws TimeoutException, XBeeException { // Verify the parameters are not null, if they are null, throw an exception. if (address == null) throw new NullPointerException("Address cannot be null"); if (data == null) throw new NullPointerException("Data cannot be null"); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if device is remote. if (isRemote()) throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device."); logger.info(toString() + "Sending serial data to {} >> {}.", address, HexUtils.prettyHexString(data)); // Depending on the protocol of the XBee device, the packet to send may vary. XBeePacket xbeePacket; switch (getXBeeProtocol()) { case RAW_802_15_4: // Generate and send the Tx16 packet. xbeePacket = new TX16Packet(getNextFrameID(), address, XBeeTransmitOptions.NONE, data); break; default: // Generate and send the Transmit packet. xbeePacket = new TransmitPacket(getNextFrameID(), XBee64BitAddress.UNKNOWN_ADDRESS, address, 0, XBeeTransmitOptions.NONE, data); } sendAndCheckXBeePacket(xbeePacket, false); } /** * Sends the provided data to the XBee device of the network corresponding * to the given 64-Bit/16-Bit address. * * <p>This method blocks till a success or error response arrives or the * configured receive timeout expires.</p> * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>For non-blocking operations use the method * {@link #sendSerialData(XBee16BitAddress, byte[])}.</p> * * @param address64Bit The 64-bit address of the XBee that will receive the * data. * @param address16bit The 16-bit address of the XBee that will receive the * data. If it is unknown the * {@code XBee16BitAddress.UNKNOWN_ADDRESS} must be used. * @param data Byte array containing data to be sent. * * @throws TimeoutException if there is a timeout sending the serial data. * @throws XBeeException if a remote device is trying to send serial data or * if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code address64Bit == null} or * if {@code address16bit == null} or * if {@code data == null}. * * @see XBee64BitAddress * @see XBee16BitAddress * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) * @see #sendSerialData(XBee64BitAddress, byte[]) * @see #sendSerialData(XBee16BitAddress, byte[]) * @see #sendSerialData(XBeeDevice, byte[]) * @see #sendSerialDataAsync(XBee64BitAddress, byte[]) * @see #sendSerialDataAsync(XBee16BitAddress, byte[]) * @see #sendSerialDataAsync(XBee64BitAddress, XBee16BitAddress, byte[]) * @see #sendSerialDataAsync(XBeeDevice, byte[]) */ public void sendSerialData(XBee64BitAddress address64Bit, XBee16BitAddress address16bit, byte[] data) throws TimeoutException, XBeeException { // Verify the parameters are not null, if they are null, throw an exception. if (address64Bit == null) throw new NullPointerException("64-bit address cannot be null"); if (address16bit == null) throw new NullPointerException("16-bit address cannot be null"); if (data == null) throw new NullPointerException("Data cannot be null"); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Check if device is remote. if (isRemote()) throw new OperationNotSupportedException("Cannot send data to a remote device from a remote device."); logger.info(toString() + "Sending serial data to {}[{}] >> {}.", address64Bit, address16bit, HexUtils.prettyHexString(data)); // Depending on the protocol of the XBee device, the packet to send may vary. XBeePacket xbeePacket; switch (getXBeeProtocol()) { case RAW_802_15_4: // TODO We don't know which address should be used: 16-bit/64-bit. // For the moment we are going to use 64-bit address by default. xbeePacket = new TX64Packet(getNextFrameID(), address64Bit, XBeeTransmitOptions.NONE, data); break; default: // Generate and send the Transmit packet. xbeePacket = new TransmitPacket(getNextFrameID(), address64Bit, address16bit, 0, XBeeTransmitOptions.NONE, data); } sendAndCheckXBeePacket(xbeePacket, false); } /** * Sends the provided data to the given XBee device. * * <p>This method blocks till a success or error response arrives or the * configured receive timeout expires.</p> * * <p>The received timeout is configured using the {@code setReceiveTimeout} * method and can be consulted with {@code getReceiveTimeout} method.</p> * * <p>For non-blocking operations use the method * {@link #sendSerialDataAsync(XBeeDevice, byte[])}.</p> * * @param xbeeDevice The XBee device of the network that will receive the data. * @param data Byte array containing data to be sent. * * @throws TimeoutException if there is a timeout sending the serial data. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code xbeeDevice == null} or * if {@code data == null}. * * @see #getReceiveTimeout() * @see #setReceiveTimeout(int) * @see #sendSerialData(XBee64BitAddress, byte[]) * @see #sendSerialData(XBee16BitAddress, byte[]) * @see #sendSerialDataAsync(XBee64BitAddress, byte[]) * @see #sendSerialDataAsync(XBee16BitAddress, byte[]) * @see #sendSerialDataAsync(XBeeDevice, byte[]) */ public void sendSerialData(XBeeDevice xbeeDevice, byte[] data) throws TimeoutException, XBeeException { if (xbeeDevice == null) throw new NullPointerException("XBee device cannot be null"); sendSerialData(xbeeDevice.get64BitAddress(), data); } /** * Sends the provided {@code XBeePacket} and determines if the transmission * status is success for synchronous transmissions. If the status is not * success, an {@code TransmitException} is thrown. * * @param packet The {@code XBeePacket} to be sent. * @param asyncTransmission Determines whether or not the transmission * should be made asynchronously. * * @throws TransmitException if {@code packet} is not an instance of {@code TransmitStatusPacket} or * if {@code packet} is not an instance of {@code TXStatusPacket} or * if its transmit status is different than {@code XBeeTransmitStatus.SUCCESS}. * @throws XBeeException if there is any other XBee related error. * * @see XBeePacket */ private void sendAndCheckXBeePacket(XBeePacket packet, boolean asyncTransmission) throws TransmitException, XBeeException { XBeePacket receivedPacket = null; // Send the XBee packet. try { if (asyncTransmission) sendXBeePacketAsync(packet, true); else receivedPacket = sendXBeePacket(packet, true); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // If the transmission is async. we are done. if (asyncTransmission) return; // Check if the packet received is a valid transmit status packet. if (receivedPacket == null) throw new TransmitException(null); if (receivedPacket instanceof TransmitStatusPacket) { if (((TransmitStatusPacket)receivedPacket).getTransmitStatus() == null) throw new TransmitException(null); else if (((TransmitStatusPacket)receivedPacket).getTransmitStatus() != XBeeTransmitStatus.SUCCESS) throw new TransmitException(((TransmitStatusPacket)receivedPacket).getTransmitStatus()); } else if (receivedPacket instanceof TXStatusPacket) { if (((TXStatusPacket)receivedPacket).getTransmitStatus() == null) throw new TransmitException(null); else if (((TXStatusPacket)receivedPacket).getTransmitStatus() != XBeeTransmitStatus.SUCCESS) throw new TransmitException(((TXStatusPacket)receivedPacket).getTransmitStatus()); } else throw new TransmitException(null); } /** * Sets the configuration of the given IO line. * * @param ioLine The IO line to configure. * @param mode The IO mode to set to the IO line. * * @throws TimeoutException if there is a timeout sending the set * configuration command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code ioLine == null} or * if {@code ioMode == null}. * * @see IOLine * @see IOMode * @see #getIOConfiguration(IOLine) */ public void setIOConfiguration(IOLine ioLine, IOMode ioMode) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); if (ioMode == null) throw new NullPointerException("IO mode cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Create and send the AT Command. String atCommand = ioLine.getConfigurationATCommand(); ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(atCommand, new byte[]{(byte)ioMode.getID()})); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); } /** * Retrieves the configuration mode of the provided IO line. * * @param ioLine The IO line to get its configuration. * * @return The IO mode (configuration) of the provided IO line. * * @throws TimeoutException if there is a timeout sending the get * configuration command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code ioLine == null}. * * @see IOLine * @see IOMode * @see #setIOConfiguration(IOLine, IOMode) */ public IOMode getIOConfiguration(IOLine ioLine) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("DIO pin cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Create and send the AT Command. ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(ioLine.getConfigurationATCommand())); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); // Check if the response contains the configuration value. if (response.getResponse() == null || response.getResponse().length == 0) throw new OperationNotSupportedException("Answer does not conain the configuration value."); // Check if the received configuration mode is valid. int ioModeValue = response.getResponse()[0]; IOMode dioMode = IOMode.getIOMode(ioModeValue, ioLine); if (dioMode == null) throw new OperationNotSupportedException("Received configuration mode '" + HexUtils.integerToHexString(ioModeValue, 1) + "' is not valid."); // Return the configuration mode. return dioMode; } /** * Sets the digital value (high or low) to the provided IO line. * * @param ioLine The IO line to set its value. * @param value The IOValue to set to the IO line ({@code HIGH} or * {@code LOW}). * * @throws TimeoutException if there is a timeout sending the set DIO * command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code ioLine == null} or * if {@code ioValue == null}. * * @see IOLine * @see IOValue * @see IOMode#DIGITAL_OUT_HIGH * @see IOMode#DIGITAL_OUT_LOW * @see #getIOConfiguration(IOLine) * @see #setIOConfiguration(IOLine, IOMode) */ public void setDIOValue(IOLine ioLine, IOValue ioValue) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Check IO value. if (ioValue == null) throw new NullPointerException("IO value cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Create and send the AT Command. String atCommand = ioLine.getConfigurationATCommand(); byte[] valueByte = new byte[]{(byte)ioValue.getID()}; ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(atCommand, valueByte)); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); } /** * Retrieves the digital value of the provided IO line (must be configured * as digital I/O). * * @param ioLine The IO line to get its digital value. * * @return The digital value corresponding to the provided IO line. * * @throws TimeoutException if there is a timeout sending the get IO values * command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code ioLine == null}. * * @see IOLine * @see IOMode#DIGITAL_IN * @see IOMode#DIGITAL_OUT_HIGH * @see IOMode#DIGITAL_OUT_LOW * @see #getIOConfiguration(IOLine) * @see #setIOConfiguration(IOLine, IOMode) */ public IOValue getDIOValue(IOLine ioLine) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Create and send the AT Command. ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(ioLine.getReadIOATCommand())); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); IOSample ioSample; byte[] samplePayload = null; // If the protocol is 802.15.4 we need to receive an Rx16 or Rx64 IO packet if (getXBeeProtocol() == XBeeProtocol.RAW_802_15_4) { samplePayload = receiveIOPacket(); if (samplePayload == null) throw new TimeoutException("Timeout waiting for the IO response packet."); } else samplePayload = response.getResponse(); // Try to build an IO Sample from the sample payload. try { ioSample = new IOSample(samplePayload); } catch (IllegalArgumentException e) { throw new XBeeException("Couldn't create the IO sample.", e); } catch (NullPointerException e) { throw new XBeeException("Couldn't create the IO sample.", e); } // Check if the IO sample contains the expected IO line and value. if (!ioSample.hasDigitalValues() || !ioSample.getDigitalValues().containsKey(ioLine)) throw new OperationNotSupportedException("Answer does not conain digital data for " + ioLine.getName() + "."); // Return the digital value. return ioSample.getDigitalValues().get(ioLine); } /** * Sets the duty cycle (in %) of the provided IO line. * * <p>IO line must be PWM capable({@code hasPWMCapability()}) and * it must be configured as PWM Output ({@code IOMode.PWM}).</p> * * @param ioLine The IO line to set its duty cycle value. * @param value The duty cycle of the PWM. * * @throws TimeoutException if there is a timeout sending the set PWM duty * cycle command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws IllegalArgumentException if {@code ioLine.hasPWMCapability() == false} or * if {@code value < 0} or * if {@code value > 1023}. * @throws NullPointerException if {@code ioLine == null}. * * @see IOLine * @see IOMode#PWM * @see #getPWMDutyCycle(IOLine) * @see #getIOConfiguration(IOLine) * @see #setIOConfiguration(IOLine, IOMode) */ public void setPWMDutyCycle(IOLine ioLine, double dutyCycle) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Check if the IO line has PWM capability. if (!ioLine.hasPWMCapability()) throw new IllegalArgumentException("Provided IO line does not have PWM capability."); // Check duty cycle limits. if (dutyCycle < 0 || dutyCycle > 100) throw new IllegalArgumentException("Duty Cycle must be between 0% and 100%."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Convert the value. int finaldutyCycle = (int)(dutyCycle * 1023.0/100.0); // Create and send the AT Command. String atCommand = ioLine.getPWMDutyCycleATCommand(); ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(atCommand, ByteUtils.intToByteArray(finaldutyCycle))); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); } /** * Gets the PWM duty cycle (in %) corresponding to the provided IO line. * * <p>IO line must be PWM capable ({@code hasPWMCapability()}) and * it must be configured as PWM Output ({@code IOMode.PWM}).</p> * * @param ioLine The IO line to get its PWM duty cycle. * * @return The PWM duty cycle value corresponding to the provided IO line * (0% - 100%). * * @throws TimeoutException if there is a timeout sending the get PWM duty * cycle command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws IllegalArgumentException if {@code ioLine.hasPWMCapability() == false}. * @throws NullPointerException if {@code ioLine == null}. * * @see IOLine * @see IOMode#PWM * @see #setPWMDutyCycle(IOLine, double) * @see #getIOConfiguration(IOLine) * @see #setIOConfiguration(IOLine, IOMode) */ public double getPWMDutyCycle(IOLine ioLine) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Check if the IO line has PWM capability. if (!ioLine.hasPWMCapability()) throw new IllegalArgumentException("Provided IO line does not have PWM capability."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Create and send the AT Command. ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(ioLine.getPWMDutyCycleATCommand())); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); // Check if the response contains the PWM value. if (response.getResponse() == null || response.getResponse().length == 0) throw new OperationNotSupportedException("Answer does not conain PWM duty cycle value."); // Return the PWM duty cycle value. int readValue = ByteUtils.byteArrayToInt(response.getResponse()); return Math.round((readValue * 100.0/1023.0) * 100.0) / 100.0; } /** * Retrieves the analog value of the provided IO line (must be configured * as ADC). * * @param ioLine The IO line to get its analog value. * * @return The analog value corresponding to the provided IO line. * * @throws TimeoutException if there is a timeout sending the get IO values * command. * @throws XBeeException if there is any other XBee related exception. * @throws InterfaceNotOpenException if the device is not open. * @throws NullPointerException if {@code ioLine == null}. * * @see IOLine * @see IOMode#ADC * @see #getIOConfiguration(IOLine) * @see #setIOConfiguration(IOLine, IOMode) */ public int getADCValue(IOLine ioLine) throws TimeoutException, XBeeException { // Check IO line. if (ioLine == null) throw new NullPointerException("IO line cannot be null."); // Check connection. if (!connectionInterface.isOpen()) throw new InterfaceNotOpenException(); // Create and send the AT Command. ATCommandResponse response = null; try { response = sendATCommand(new ATCommand(ioLine.getReadIOATCommand())); } catch (IOException e) { throw new XBeeException("Error writing in the communication interface.", e); } // Check if AT Command response is valid. checkATCommandResponseIsValid(response); IOSample ioSample; byte[] samplePayload = null; // If the protocol is 802.15.4 we need to receive an Rx16 or Rx64 IO packet if (getXBeeProtocol() == XBeeProtocol.RAW_802_15_4) { samplePayload = receiveIOPacket(); if (samplePayload == null) throw new TimeoutException("Timeout waiting for the IO response packet."); } else samplePayload = response.getResponse(); // Try to build an IO Sample from the sample payload. try { ioSample = new IOSample(samplePayload); } catch (IllegalArgumentException e) { throw new XBeeException("Couldn't create the IO sample.", e); } catch (NullPointerException e) { throw new XBeeException("Couldn't create the IO sample.", e); } // Check if the IO sample contains the expected IO line and value. if (!ioSample.hasAnalogValues() || !ioSample.getAnalogValues().containsKey(ioLine)) throw new OperationNotSupportedException("Answer does not conain analog data for " + ioLine.getName() + "."); // Return the analog value. return ioSample.getAnalogValues().get(ioLine); } /** * Checks if the provided {@code ATCommandResponse} is valid throwing an * {@code ATCommandException} in case it is not. * * @param response The {@code ATCommandResponse} to check. * * @throws ATCommandException if {@code response == null} or * if {@code response.getResponseStatus() != ATCommandStatus.OK}. */ private void checkATCommandResponseIsValid(ATCommandResponse response) throws ATCommandException { if (response == null || response.getResponseStatus() == null) throw new ATCommandException(null); else if (response.getResponseStatus() != ATCommandStatus.OK) throw new ATCommandException(response.getResponseStatus()); } /** * Retrieves the latest IO packet and returns its value. * * @return The value of the latest received IO packet. */ private byte[] receiveIOPacket() { ioPacketReceived = false; ioPacketPayload = null; startListeningForPackets(IOPacketReceiveListener); synchronized (ioLock) { try { ioLock.wait(receiveTimeout); } catch (InterruptedException e) { } } stopListeningForPackets(IOPacketReceiveListener); if (ioPacketReceived) return ioPacketPayload; return null; } /** * Custom listener for IO packets. It will try to receive an IO sample packet. * * <p>When an IO sample packet is received, it saves its payload and notifies * the object that was waiting for the reception.</p> */ private IPacketReceiveListener IOPacketReceiveListener = new IPacketReceiveListener() { /* * (non-Javadoc) * @see com.digi.xbee.api.listeners.IPacketReceiveListener#packetReceived(com.digi.xbee.api.packet.XBeePacket) */ public void packetReceived(XBeePacket receivedPacket) { // Discard non API packets. if (!(receivedPacket instanceof XBeeAPIPacket)) return; // If we already have received an IO packet, ignore this packet. if (ioPacketReceived) return; // Save the packet value (IO sample payload) switch (((XBeeAPIPacket)receivedPacket).getFrameType()) { case IO_DATA_SAMPLE_RX_INDICATOR: ioPacketPayload = ((IODataSampleRxIndicatorPacket)receivedPacket).getReceivedData(); break; case RX_IO_16: ioPacketPayload = ((RX16IOPacket)receivedPacket).getReceivedData(); break; case RX_IO_64: ioPacketPayload = ((RX64IOPacket)receivedPacket).getReceivedData(); break; default: return; } // Set the IO packet received flag. ioPacketReceived = true; // Continue execution by notifying the lock object. synchronized (ioLock) { ioLock.notify(); } } }; /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return connectionInterface.toString(); } }
Little cosmetic changes. Signed-off-by: Diego Escalona <[email protected]>
src/com/digi/xbee/api/XBeeDevice.java
Little cosmetic changes.
<ide><path>rc/com/digi/xbee/api/XBeeDevice.java <ide> * @param connectionInterface The connection interface with the physical <ide> * XBee device. <ide> * <del> * @throws NullPointerException if {@code connectionInterface == null} <add> * @throws NullPointerException if {@code connectionInterface == null}. <ide> * <ide> * @see IConnectionInterface <ide> */ <ide> * <ide> * @param localXBeeDevice The local XBee device that will behave as <ide> * connection interface to communicate with this <del> * remote XBee device <add> * remote XBee device. <ide> * @param xbee64BitAddress The 64-bit address to identify this remote XBee <ide> * device. <ide> * @throws NullPointerException if {@code localXBeeDevice == null} or <ide> return operatingMode; <ide> } <ide> } catch (TimeoutException e) { <del> // Check if device is in AT operating mode. <del> operatingMode = OperatingMode.AT; <del> dataReader.setXBeeReaderMode(operatingMode); <del> <del> try { <del> // It is necessary to wait at least 1 second to enter in command mode after <del> // sending any data to the device. <del> Thread.sleep(TIMEOUT_BEFORE_COMMAND_MODE); <del> // Try to enter in AT command mode, if so the module is in AT mode. <del> boolean success = enterATCommandMode(); <del> if (success) <del> return OperatingMode.AT; <del> } catch (TimeoutException e1) { <del> logger.error(e1.getMessage(), e1); <del> } catch (InvalidOperatingModeException e1) { <del> logger.error(e1.getMessage(), e1); <del> } catch (InterruptedException e1) { <del> logger.error(e1.getMessage(), e1); <del> } <add> // Check if device is in AT operating mode. <add> operatingMode = OperatingMode.AT; <add> dataReader.setXBeeReaderMode(operatingMode); <add> <add> try { <add> // It is necessary to wait at least 1 second to enter in command mode after <add> // sending any data to the device. <add> Thread.sleep(TIMEOUT_BEFORE_COMMAND_MODE); <add> // Try to enter in AT command mode, if so the module is in AT mode. <add> boolean success = enterATCommandMode(); <add> if (success) <add> return OperatingMode.AT; <add> } catch (TimeoutException e1) { <add> logger.error(e1.getMessage(), e1); <add> } catch (InvalidOperatingModeException e1) { <add> logger.error(e1.getMessage(), e1); <add> } catch (InterruptedException e1) { <add> logger.error(e1.getMessage(), e1); <add> } <ide> } catch (InvalidOperatingModeException e) { <ide> logger.error("Invalid operating mode", e); <ide> } catch (IOException e) { <ide> * to the given 64-bit address asynchronously. <ide> * <ide> * <p>Asynchronous transmissions do not wait for answer from the remote <del> * device or for transmit status packet</p> <add> * device or for transmit status packet.</p> <ide> * <ide> * @param address The 64-bit address of the XBee that will receive the data. <ide> * @param data Byte array containing data to be sent. <ide> * to the given 16-bit address asynchronously. <ide> * <ide> * <p>Asynchronous transmissions do not wait for answer from the remote <del> * device or for transmit status packet</p> <add> * device or for transmit status packet.</p> <ide> * <ide> * @param address The 16-bit address of the XBee that will receive the data. <ide> * @param data Byte array containing data to be sent. <ide> * Sends the provided data to the provided XBee device asynchronously. <ide> * <ide> * <p>Asynchronous transmissions do not wait for answer from the remote <del> * device or for transmit status packet</p> <add> * device or for transmit status packet.</p> <ide> * <ide> * @param xbeeDevice The XBee device of the network that will receive the data. <ide> * @param data Byte array containing data to be sent. <ide> * <ide> * @throws XBeeException if there is any XBee related exception. <del> * @throws InterfaceNotOpenException if the device is not open. <add> * @throws InterfaceNotOpenException if the device is not open. <ide> * @throws NullPointerException if {@code xbeeDevice == null} or <ide> * if {@code data == null}. <ide> *
Java
apache-2.0
06155e12a41d2c4959d34d42eea28c21b1169494
0
kzubrinic/oop
package hr.unidu.oop.p01; /** * Prvi Java program. */ public class DobarDan{ public static void main(String[] args){ System.out.println("Dobar dan!"); } }
oop/src/hr/unidu/oop/p01/DobarDan.java
package hr.unidu.oop.p01; /** * Prvi program. */ public class DobarDan{ public static void main(String[] args){ System.out.println("Dobar dan!"); } }
Izmjena komentara u prvom programu
oop/src/hr/unidu/oop/p01/DobarDan.java
Izmjena komentara u prvom programu
<ide><path>op/src/hr/unidu/oop/p01/DobarDan.java <ide> package hr.unidu.oop.p01; <ide> <ide> /** <del> * Prvi program. <add> * Prvi Java program. <ide> */ <ide> public class DobarDan{ <ide> public static void main(String[] args){
Java
apache-2.0
b7ffb88426881507ca14ca73b5ac8f19173da2c6
0
Pardus-Engerek/engerek,PetrGasparik/midpoint,Pardus-Engerek/engerek,PetrGasparik/midpoint,PetrGasparik/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,Pardus-Engerek/engerek,Pardus-Engerek/engerek,arnost-starosta/midpoint,PetrGasparik/midpoint
/* * Copyright (c) 2013-2016 Evolveum * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.evolveum.midpoint.model.impl; import java.net.URI; import java.util.Collection; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import javax.xml.namespace.QName; import com.evolveum.midpoint.model.api.ModelInteractionService; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.apache.commons.lang.Validate; import org.apache.cxf.jaxrs.ext.MessageContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.evolveum.midpoint.audit.api.AuditEventRecord; import com.evolveum.midpoint.audit.api.AuditEventStage; import com.evolveum.midpoint.audit.api.AuditEventType; import com.evolveum.midpoint.audit.api.AuditService; import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.model.api.PolicyViolationException; import com.evolveum.midpoint.model.impl.rest.PATCH; import com.evolveum.midpoint.model.impl.security.SecurityHelper; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.query.QueryJaxbConvertor; import com.evolveum.midpoint.schema.DeltaConvertor; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.security.api.ConnectionEnvironment; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.TaskManager; import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.exception.CommunicationException; import com.evolveum.midpoint.util.exception.ConfigurationException; import com.evolveum.midpoint.util.exception.ConsistencyViolationException; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SecurityViolationException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectListType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectModificationType; import com.evolveum.prism.xml.ns._public.query_3.QueryType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; /** * @author katkav * @author semancik */ @Service @Produces({"application/xml", "application/json"}) public class ModelRestService { public static final String CLASS_DOT = ModelRestService.class.getName() + "."; public static final String OPERATION_REST_SERVICE = CLASS_DOT + "restService"; public static final String OPERATION_GET = CLASS_DOT + "get"; public static final String OPERATION_ADD_OBJECT = CLASS_DOT + "addObject"; public static final String OPERATION_DELETE_OBJECT = CLASS_DOT + "deleteObject"; public static final String OPERATION_MODIFY_OBJECT = CLASS_DOT + "modifyObject"; public static final String OPERATION_NOTIFY_CHANGE = CLASS_DOT + "notifyChange"; public static final String OPERATION_FIND_SHADOW_OWNER = CLASS_DOT + "findShadowOwner"; public static final String OPERATION_SEARCH_OBJECTS = CLASS_DOT + "searchObjects"; public static final String OPERATION_IMPORT_FROM_RESOURCE = CLASS_DOT + "importFromResource"; public static final String OPERATION_TEST_RESOURCE = CLASS_DOT + "testResource"; public static final String OPERATION_SUSPEND_TASKS = CLASS_DOT + "suspendTasks"; public static final String OPERATION_SUSPEND_AND_DELETE_TASKS = CLASS_DOT + "suspendAndDeleteTasks"; public static final String OPERATION_RESUME_TASKS = CLASS_DOT + "resumeTasks"; public static final String OPERATION_SCHEDULE_TASKS_NOW = CLASS_DOT + "scheduleTasksNow"; @Autowired(required=true) private ModelCrudService model; @Autowired(required=true) private ModelInteractionService modelInteraction; @Autowired(required=true) private PrismContext prismContext; @Autowired(required=true) private SecurityHelper securityHelper; private static final Trace LOGGER = TraceManager.getTrace(ModelRestService.class); public static final long WAIT_FOR_TASK_STOP = 2000L; private static final String QUERY_PARAMETER_OPTIONS = "options"; public static final String MESSAGE_PROPERTY_TASK_NAME = "task"; public ModelRestService() { // nothing to do } @GET @Path("/users/{id}/policy") public Response getValuePolicyForUser(@PathParam("id") String oid, @Context MessageContext mc) { LOGGER.info("getValuePolicyForUser start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_GET); Response response; try { Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(GetOperationOptions.createRaw()); PrismObject<UserType> user = model.getObject(UserType.class, oid, options, task, parentResult); CredentialsPolicyType policy = modelInteraction.getCredentialsPolicy(user, task, parentResult); ResponseBuilder builder = Response.ok(); builder.entity(policy); response = builder.build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); LOGGER.info("getValuePolicyForUser finish"); return response; } private Response handleException(Exception ex) { if (ex instanceof ObjectNotFoundException) { return buildErrorResponse(Status.NOT_FOUND, ex); } if (ex instanceof CommunicationException) { return buildErrorResponse(Status.GATEWAY_TIMEOUT, ex); } if (ex instanceof SecurityViolationException) { return buildErrorResponse(Status.FORBIDDEN, ex); } if (ex instanceof ConfigurationException) { return buildErrorResponse(Status.BAD_GATEWAY, ex); } if (ex instanceof SchemaException || ex instanceof PolicyViolationException || ex instanceof ConsistencyViolationException || ex instanceof ObjectAlreadyExistsException) { return buildErrorResponse(Status.CONFLICT, ex); } return buildErrorResponse(Status.INTERNAL_SERVER_ERROR, ex); } private Response buildErrorResponse(Status status, Exception ex) { return buildErrorResponse(status, ex.getMessage()); } private Response buildErrorResponse(Status status, String message) { return Response.status(status).entity(message).type(MediaType.TEXT_PLAIN).build(); } @GET @Path("/{type}/{id}") public <T extends ObjectType> Response getObject(@PathParam("type") String type, @PathParam("id") String id, @Context MessageContext mc){ LOGGER.info("model rest service for get operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_GET); Class<T> clazz = ObjectTypes.getClassFromRestType(type); Response response; try { PrismObject<T> object = model.getObject(clazz, id, null, task, parentResult); ResponseBuilder builder = Response.ok(); builder.entity(object); response = builder.build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @POST @Path("/{type}") // @Produces({"text/html", "application/xml"}) @Consumes({"application/xml", "application/json"}) public <T extends ObjectType> Response addObject(@PathParam("type") String type, PrismObject<T> object, @QueryParam("options") List<String> options, @Context UriInfo uriInfo, @Context MessageContext mc) { LOGGER.info("model rest service for add operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_ADD_OBJECT); Class clazz = ObjectTypes.getClassFromRestType(type); if (!object.getCompileTimeClass().equals(clazz)){ finishRequest(task); return buildErrorResponse(Status.BAD_REQUEST, "Request to add object of type " + object.getCompileTimeClass().getSimpleName() + " to the collection of " + type); } ModelExecuteOptions modelExecuteOptions = ModelExecuteOptions.fromRestOptions(options); String oid; Response response; try { oid = model.addObject(object, modelExecuteOptions, task, parentResult); LOGGER.info("returned oid : {}", oid ); ResponseBuilder builder; if (oid != null) { URI resourceURI = uriInfo.getAbsolutePathBuilder().path(oid).build(oid); builder = clazz.isAssignableFrom(TaskType.class) ? Response.accepted().location(resourceURI) : Response.created(resourceURI); } else { // OID might be null e.g. if the object creation is a subject of workflow approval builder = Response.accepted(); // TODO is this ok ? } response = builder.build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @PUT @Path("/{type}/{id}") // @Produces({"text/html", "application/xml"}) public <T extends ObjectType> Response addObject(@PathParam("type") String type, @PathParam("id") String id, PrismObject<T> object, @QueryParam("options") List<String> options, @Context UriInfo uriInfo, @Context Request request, @Context MessageContext mc){ LOGGER.info("model rest service for add operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_ADD_OBJECT); Class clazz = ObjectTypes.getClassFromRestType(type); if (!object.getCompileTimeClass().equals(clazz)){ finishRequest(task); return buildErrorResponse(Status.BAD_REQUEST, "Request to add object of type " + object.getCompileTimeClass().getSimpleName() + " to the collection of " + type); } ModelExecuteOptions modelExecuteOptions = ModelExecuteOptions.fromRestOptions(options); if (modelExecuteOptions == null) { modelExecuteOptions = ModelExecuteOptions.createOverwrite(); } else if (!ModelExecuteOptions.isOverwrite(modelExecuteOptions)){ modelExecuteOptions.setOverwrite(Boolean.TRUE); } String oid; Response response; try { oid = model.addObject(object, modelExecuteOptions, task, parentResult); LOGGER.info("returned oid : {}", oid ); URI resourceURI = uriInfo.getAbsolutePathBuilder().path(oid).build(oid); ResponseBuilder builder = clazz.isAssignableFrom(TaskType.class) ? Response.accepted().location(resourceURI) : Response.created(resourceURI); response = builder.build(); } catch (ObjectAlreadyExistsException e) { response = Response.serverError().entity(e.getMessage()).build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @DELETE @Path("/{type}/{id}") // @Produces({"text/html", "application/xml"}) public Response deleteObject(@PathParam("type") String type, @PathParam("id") String id, @QueryParam("options") List<String> options, @Context MessageContext mc){ LOGGER.info("model rest service for delete operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_DELETE_OBJECT); Class clazz = ObjectTypes.getClassFromRestType(type); Response response; try { if (clazz.isAssignableFrom(TaskType.class)){ model.suspendAndDeleteTasks(MiscUtil.createCollection(id), WAIT_FOR_TASK_STOP, true, parentResult); parentResult.computeStatus(); finishRequest(task); if (parentResult.isSuccess()){ return Response.noContent().build(); } return Response.serverError().entity(parentResult.getMessage()).build(); } ModelExecuteOptions modelExecuteOptions = ModelExecuteOptions.fromRestOptions(options); model.deleteObject(clazz, id, modelExecuteOptions, task, parentResult); response = Response.noContent().build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @POST @Path("/{type}/{oid}") public <T extends ObjectType> Response modifyObjectPost(@PathParam("type") String type, @PathParam("oid") String oid, ObjectModificationType modificationType, @QueryParam("options") List<String> options, @Context MessageContext mc) { return modifyObjectPatch(type, oid, modificationType, options, mc); } @PATCH @Path("/{type}/{oid}") // @Produces({"text/html", "application/xml"}) public <T extends ObjectType> Response modifyObjectPatch(@PathParam("type") String type, @PathParam("oid") String oid, ObjectModificationType modificationType, @QueryParam("options") List<String> options, @Context MessageContext mc) { LOGGER.info("model rest service for modify operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_MODIFY_OBJECT); Class clazz = ObjectTypes.getClassFromRestType(type); Response response; try { ModelExecuteOptions modelExecuteOptions = ModelExecuteOptions.fromRestOptions(options); Collection<? extends ItemDelta> modifications = DeltaConvertor.toModifications(modificationType, clazz, prismContext); model.modifyObject(clazz, oid, modifications, modelExecuteOptions, task, parentResult); response = Response.noContent().build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @POST @Path("/notifyChange") public Response notifyChange(ResourceObjectShadowChangeDescriptionType changeDescription, @Context UriInfo uriInfo, @Context MessageContext mc) { LOGGER.info("model rest service for notify change operation start"); Validate.notNull(changeDescription, "Chnage description must not be null"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_NOTIFY_CHANGE); Response response; try { model.notifyChange(changeDescription, parentResult, task); return Response.ok().build(); // String oldShadowOid = changeDescription.getOldShadowOid(); // if (oldShadowOid != null){ // URI resourceURI = uriInfo.getAbsolutePathBuilder().path(oldShadowOid).build(oldShadowOid); // return Response.accepted().location(resourceURI).build(); // } else { // changeDescription.get // } // response = Response.seeOther((uriInfo.getBaseUriBuilder().path(this.getClass(), "getObject").build(ObjectTypes.TASK.getRestType(), task.getOid()))).build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @GET @Path("/shadows/{oid}/owner") // @Produces({"text/html", "application/xml"}) public Response findShadowOwner(@PathParam("oid") String shadowOid, @Context MessageContext mc){ LOGGER.info("model rest service for find shadow owner operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_FIND_SHADOW_OWNER); Response response; try { PrismObject<UserType> user = model.findShadowOwner(shadowOid, task, parentResult); response = Response.ok().entity(user).build(); } catch (ConfigurationException e) { response = buildErrorResponse(Status.INTERNAL_SERVER_ERROR, e.getMessage()); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @POST @Path("/{type}/search") // @Produces({"text/html", "application/xml"}) public Response searchObjects(@PathParam("type") String type, QueryType queryType, @Context MessageContext mc){ LOGGER.info("model rest service for find shadow owner operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_SEARCH_OBJECTS); Class clazz = ObjectTypes.getClassFromRestType(type); Response response; try { ObjectQuery query = QueryJaxbConvertor.createObjectQuery(clazz, queryType, prismContext); List<PrismObject<? extends ShadowType>> objects = model.searchObjects(clazz, query, null, task, parentResult); ObjectListType listType = new ObjectListType(); for (PrismObject<? extends ObjectType> o : objects) { listType.getObject().add(o.asObjectable()); } response = Response.ok().entity(listType).build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @POST @Path("/resources/{resourceOid}/import/{objectClass}") // @Produces({"text/html", "application/xml"}) public Response importFromResource(@PathParam("resourceOid") String resourceOid, @PathParam("objectClass") String objectClass, @Context MessageContext mc, @Context UriInfo uriInfo) { LOGGER.info("model rest service for import from resource operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_IMPORT_FROM_RESOURCE); QName objClass = new QName(MidPointConstants.NS_RI, objectClass); Response response; try { model.importFromResource(resourceOid, objClass, task, parentResult); response = Response.seeOther((uriInfo.getBaseUriBuilder().path(this.getClass(), "getObject") .build(ObjectTypes.TASK.getRestType(), task.getOid()))).build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @POST @Path("/resources/{resourceOid}/test") // @Produces({"text/html", "application/xml"}) public Response testResource(@PathParam("resourceOid") String resourceOid, @Context MessageContext mc) { LOGGER.info("model rest service for test resource operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_TEST_RESOURCE); Response response; OperationResult testResult = null; try { testResult = model.testResource(resourceOid, task); response = Response.ok(testResult).build(); } catch (Exception ex) { response = handleException(ex); } if (testResult != null) { parentResult.getSubresults().add(testResult); } finishRequest(task); return response; } @POST @Path("/tasks/{oid}/suspend") public Response suspendTasks(@PathParam("oid") String taskOid, @Context MessageContext mc) { Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_SUSPEND_TASKS); Response response; Collection<String> taskOids = MiscUtil.createCollection(taskOid); try { model.suspendTasks(taskOids, WAIT_FOR_TASK_STOP, parentResult); parentResult.computeStatus(); if (parentResult.isSuccess()){ response = Response.noContent().build(); } else { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(parentResult.getMessage()).build(); } } catch (Exception ex) { response = handleException(ex); } finishRequest(task); return response; } // @DELETE // @Path("tasks/{oid}/suspend") public Response suspendAndDeleteTasks(@PathParam("oid") String taskOid, @Context MessageContext mc) { Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_SUSPEND_AND_DELETE_TASKS); Response response; Collection<String> taskOids = MiscUtil.createCollection(taskOid); try { model.suspendAndDeleteTasks(taskOids, WAIT_FOR_TASK_STOP, true, parentResult); parentResult.computeStatus(); if (parentResult.isSuccess()) { response = Response.accepted().build(); } else { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(parentResult.getMessage()).build(); } } catch (Exception ex) { response = handleException(ex); } finishRequest(task); return response; } @POST @Path("/tasks/{oid}/resume") public Response resumeTasks(@PathParam("oid") String taskOid, @Context MessageContext mc) { Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_RESUME_TASKS); Response response; Collection<String> taskOids = MiscUtil.createCollection(taskOid); try { model.resumeTasks(taskOids, parentResult); parentResult.computeStatus(); if (parentResult.isSuccess()) { response = Response.accepted().build(); } else { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(parentResult.getMessage()).build(); } } catch (Exception ex) { response = handleException(ex); } finishRequest(task); return response; } @POST @Path("tasks/{oid}/run") public Response scheduleTasksNow(@PathParam("oid") String taskOid, @Context MessageContext mc) { Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_SCHEDULE_TASKS_NOW); Collection<String> taskOids = MiscUtil.createCollection(taskOid); Response response; try { model.scheduleTasksNow(taskOids, parentResult); parentResult.computeStatus(); if (parentResult.isSuccess()) { response = Response.accepted().build(); } else { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(parentResult.getMessage()).build(); } } catch (Exception ex) { response = handleException(ex); } finishRequest(task); return response; } // @GET // @Path("tasks/{oid}") // public Response getTaskByIdentifier(@PathParam("oid") String identifier) throws SchemaException, ObjectNotFoundException { // OperationResult parentResult = new OperationResult("getTaskByIdentifier"); // PrismObject<TaskType> task = model.getTaskByIdentifier(identifier, null, parentResult); // // return Response.ok(task).build(); // } // // // public boolean deactivateServiceThreads(long timeToWait, OperationResult parentResult) { // return model.deactivateServiceThreads(timeToWait, parentResult); // } // // public void reactivateServiceThreads(OperationResult parentResult) { // model.reactivateServiceThreads(parentResult); // } // // public boolean getServiceThreadsActivationState() { // return model.getServiceThreadsActivationState(); // } // // public void stopSchedulers(Collection<String> nodeIdentifiers, OperationResult parentResult) { // model.stopSchedulers(nodeIdentifiers, parentResult); // } // // public boolean stopSchedulersAndTasks(Collection<String> nodeIdentifiers, long waitTime, OperationResult parentResult) { // return model.stopSchedulersAndTasks(nodeIdentifiers, waitTime, parentResult); // } // // public void startSchedulers(Collection<String> nodeIdentifiers, OperationResult parentResult) { // model.startSchedulers(nodeIdentifiers, parentResult); // } // // public void synchronizeTasks(OperationResult parentResult) { // model.synchronizeTasks(parentResult); // } private ModelExecuteOptions getOptions(UriInfo uriInfo){ List<String> options = uriInfo.getQueryParameters().get(QUERY_PARAMETER_OPTIONS); return ModelExecuteOptions.fromRestOptions(options); } private Task initRequest(MessageContext mc) { Task task = (Task) mc.get(MESSAGE_PROPERTY_TASK_NAME); // No need to audit login. it was already audited during authentication return task; } private void finishRequest(Task task) { task.getResult().computeStatus(); ConnectionEnvironment connEnv = new ConnectionEnvironment(); connEnv.setChannel(SchemaConstants.CHANNEL_REST_URI); connEnv.setSessionId(task.getTaskIdentifier()); securityHelper.auditLogout(connEnv, task); } }
model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelRestService.java
/* * Copyright (c) 2013-2016 Evolveum * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.evolveum.midpoint.model.impl; import java.net.URI; import java.util.Collection; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import javax.xml.namespace.QName; import com.evolveum.midpoint.model.api.ModelInteractionService; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.apache.commons.lang.Validate; import org.apache.cxf.jaxrs.ext.MessageContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.evolveum.midpoint.audit.api.AuditEventRecord; import com.evolveum.midpoint.audit.api.AuditEventStage; import com.evolveum.midpoint.audit.api.AuditEventType; import com.evolveum.midpoint.audit.api.AuditService; import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.model.api.PolicyViolationException; import com.evolveum.midpoint.model.impl.rest.PATCH; import com.evolveum.midpoint.model.impl.security.SecurityHelper; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.query.QueryJaxbConvertor; import com.evolveum.midpoint.schema.DeltaConvertor; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.security.api.ConnectionEnvironment; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.TaskManager; import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.exception.CommunicationException; import com.evolveum.midpoint.util.exception.ConfigurationException; import com.evolveum.midpoint.util.exception.ConsistencyViolationException; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SecurityViolationException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectListType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectModificationType; import com.evolveum.prism.xml.ns._public.query_3.QueryType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; /** * @author katkav * @author semancik */ @Service @Produces({"application/xml", "application/json"}) public class ModelRestService { public static final String CLASS_DOT = ModelRestService.class.getName() + "."; public static final String OPERATION_REST_SERVICE = CLASS_DOT + "restService"; public static final String OPERATION_GET = CLASS_DOT + "get"; public static final String OPERATION_ADD_OBJECT = CLASS_DOT + "addObject"; public static final String OPERATION_DELETE_OBJECT = CLASS_DOT + "deleteObject"; public static final String OPERATION_MODIFY_OBJECT = CLASS_DOT + "modifyObject"; public static final String OPERATION_NOTIFY_CHANGE = CLASS_DOT + "notifyChange"; public static final String OPERATION_FIND_SHADOW_OWNER = CLASS_DOT + "findShadowOwner"; public static final String OPERATION_SEARCH_OBJECTS = CLASS_DOT + "searchObjects"; public static final String OPERATION_IMPORT_FROM_RESOURCE = CLASS_DOT + "importFromResource"; public static final String OPERATION_TEST_RESOURCE = CLASS_DOT + "testResource"; public static final String OPERATION_SUSPEND_TASKS = CLASS_DOT + "suspendTasks"; public static final String OPERATION_SUSPEND_AND_DELETE_TASKS = CLASS_DOT + "suspendAndDeleteTasks"; public static final String OPERATION_RESUME_TASKS = CLASS_DOT + "resumeTasks"; public static final String OPERATION_SCHEDULE_TASKS_NOW = CLASS_DOT + "scheduleTasksNow"; @Autowired(required=true) private ModelCrudService model; @Autowired(required=true) private ModelInteractionService modelInteraction; @Autowired(required=true) private PrismContext prismContext; @Autowired(required=true) private SecurityHelper securityHelper; private static final Trace LOGGER = TraceManager.getTrace(ModelRestService.class); public static final long WAIT_FOR_TASK_STOP = 2000L; private static final String QUERY_PARAMETER_OPTIONS = "options"; public static final String MESSAGE_PROPERTY_TASK_NAME = "task"; public ModelRestService() { // nothing to do } @GET @Path("/users/{id}/policy") public Response getValuePolicyForUser(@PathParam("id") String oid, @Context MessageContext mc) { LOGGER.info("getValuePolicyForUser start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_GET); Response response; try { Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(GetOperationOptions.createRaw()); PrismObject<UserType> user = model.getObject(UserType.class, oid, options, task, parentResult); CredentialsPolicyType policy = modelInteraction.getCredentialsPolicy(user, task, parentResult); ResponseBuilder builder = Response.ok(); builder.entity(policy); response = builder.build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); LOGGER.info("getValuePolicyForUser finish"); return response; } private Response handleException(Exception ex) { if (ex instanceof ObjectNotFoundException) { return buildErrorResponse(Status.NOT_FOUND, ex); } if (ex instanceof CommunicationException) { return buildErrorResponse(Status.GATEWAY_TIMEOUT, ex); } if (ex instanceof SecurityViolationException) { return buildErrorResponse(Status.FORBIDDEN, ex); } if (ex instanceof ConfigurationException) { return buildErrorResponse(Status.BAD_GATEWAY, ex); } if (ex instanceof SchemaException || ex instanceof PolicyViolationException || ex instanceof ConsistencyViolationException || ex instanceof ObjectAlreadyExistsException) { return buildErrorResponse(Status.CONFLICT, ex); } return buildErrorResponse(Status.INTERNAL_SERVER_ERROR, ex); } private Response buildErrorResponse(Status status, Exception ex) { return buildErrorResponse(status, ex.getMessage()); } private Response buildErrorResponse(Status status, String message) { return Response.status(status).entity(message).type(MediaType.TEXT_PLAIN).build(); } @GET @Path("/{type}/{id}") public <T extends ObjectType> Response getObject(@PathParam("type") String type, @PathParam("id") String id, @Context MessageContext mc){ LOGGER.info("model rest service for get operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_GET); Class<T> clazz = ObjectTypes.getClassFromRestType(type); Response response; try { PrismObject<T> object = model.getObject(clazz, id, null, task, parentResult); ResponseBuilder builder = Response.ok(); builder.entity(object); response = builder.build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @POST @Path("/{type}") // @Produces({"text/html", "application/xml"}) @Consumes({"application/xml", "application/json"}) public <T extends ObjectType> Response addObject(@PathParam("type") String type, PrismObject<T> object, @QueryParam("options") List<String> options, @Context UriInfo uriInfo, @Context MessageContext mc) { LOGGER.info("model rest service for add operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_ADD_OBJECT); Class clazz = ObjectTypes.getClassFromRestType(type); if (!object.getCompileTimeClass().equals(clazz)){ finishRequest(task); return buildErrorResponse(Status.BAD_REQUEST, "Request to add object of type " + object.getCompileTimeClass().getSimpleName() + " to the collection of " + type); } ModelExecuteOptions modelExecuteOptions = ModelExecuteOptions.fromRestOptions(options); String oid; Response response; try { oid = model.addObject(object, modelExecuteOptions, task, parentResult); LOGGER.info("returned oid : {}", oid ); ResponseBuilder builder; if (oid != null) { URI resourceURI = uriInfo.getAbsolutePathBuilder().path(oid).build(oid); builder = clazz.isAssignableFrom(TaskType.class) ? Response.accepted().location(resourceURI) : Response.created(resourceURI); } else { // OID might be null e.g. if the object creation is a subject of workflow approval builder = Response.accepted(); // TODO is this ok ? } response = builder.build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @PUT @Path("/{type}/{id}") // @Produces({"text/html", "application/xml"}) public <T extends ObjectType> Response addObject(@PathParam("type") String type, @PathParam("id") String id, PrismObject<T> object, @QueryParam("options") List<String> options, @Context UriInfo uriInfo, @Context Request request, @Context MessageContext mc){ LOGGER.info("model rest service for add operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_ADD_OBJECT); Class clazz = ObjectTypes.getClassFromRestType(type); if (!object.getCompileTimeClass().equals(clazz)){ finishRequest(task); return buildErrorResponse(Status.BAD_REQUEST, "Request to add object of type " + object.getCompileTimeClass().getSimpleName() + " to the collection of " + type); } ModelExecuteOptions modelExecuteOptions = ModelExecuteOptions.fromRestOptions(options); if (modelExecuteOptions == null || !ModelExecuteOptions.isOverwrite(modelExecuteOptions)){ modelExecuteOptions = ModelExecuteOptions.createOverwrite(); } String oid; Response response; try { oid = model.addObject(object, modelExecuteOptions, task, parentResult); LOGGER.info("returned oid : {}", oid ); URI resourceURI = uriInfo.getAbsolutePathBuilder().path(oid).build(oid); ResponseBuilder builder = clazz.isAssignableFrom(TaskType.class) ? Response.accepted().location(resourceURI) : Response.created(resourceURI); response = builder.build(); } catch (ObjectAlreadyExistsException e) { response = Response.serverError().entity(e.getMessage()).build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @DELETE @Path("/{type}/{id}") // @Produces({"text/html", "application/xml"}) public Response deleteObject(@PathParam("type") String type, @PathParam("id") String id, @QueryParam("options") List<String> options, @Context MessageContext mc){ LOGGER.info("model rest service for delete operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_DELETE_OBJECT); Class clazz = ObjectTypes.getClassFromRestType(type); Response response; try { if (clazz.isAssignableFrom(TaskType.class)){ model.suspendAndDeleteTasks(MiscUtil.createCollection(id), WAIT_FOR_TASK_STOP, true, parentResult); parentResult.computeStatus(); finishRequest(task); if (parentResult.isSuccess()){ return Response.noContent().build(); } return Response.serverError().entity(parentResult.getMessage()).build(); } ModelExecuteOptions modelExecuteOptions = ModelExecuteOptions.fromRestOptions(options); model.deleteObject(clazz, id, modelExecuteOptions, task, parentResult); response = Response.noContent().build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @POST @Path("/{type}/{oid}") public <T extends ObjectType> Response modifyObjectPost(@PathParam("type") String type, @PathParam("oid") String oid, ObjectModificationType modificationType, @QueryParam("options") List<String> options, @Context MessageContext mc) { return modifyObjectPatch(type, oid, modificationType, options, mc); } @PATCH @Path("/{type}/{oid}") // @Produces({"text/html", "application/xml"}) public <T extends ObjectType> Response modifyObjectPatch(@PathParam("type") String type, @PathParam("oid") String oid, ObjectModificationType modificationType, @QueryParam("options") List<String> options, @Context MessageContext mc) { LOGGER.info("model rest service for modify operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_MODIFY_OBJECT); Class clazz = ObjectTypes.getClassFromRestType(type); Response response; try { ModelExecuteOptions modelExecuteOptions = ModelExecuteOptions.fromRestOptions(options); Collection<? extends ItemDelta> modifications = DeltaConvertor.toModifications(modificationType, clazz, prismContext); model.modifyObject(clazz, oid, modifications, modelExecuteOptions, task, parentResult); response = Response.noContent().build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @POST @Path("/notifyChange") public Response notifyChange(ResourceObjectShadowChangeDescriptionType changeDescription, @Context UriInfo uriInfo, @Context MessageContext mc) { LOGGER.info("model rest service for notify change operation start"); Validate.notNull(changeDescription, "Chnage description must not be null"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_NOTIFY_CHANGE); Response response; try { model.notifyChange(changeDescription, parentResult, task); return Response.ok().build(); // String oldShadowOid = changeDescription.getOldShadowOid(); // if (oldShadowOid != null){ // URI resourceURI = uriInfo.getAbsolutePathBuilder().path(oldShadowOid).build(oldShadowOid); // return Response.accepted().location(resourceURI).build(); // } else { // changeDescription.get // } // response = Response.seeOther((uriInfo.getBaseUriBuilder().path(this.getClass(), "getObject").build(ObjectTypes.TASK.getRestType(), task.getOid()))).build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @GET @Path("/shadows/{oid}/owner") // @Produces({"text/html", "application/xml"}) public Response findShadowOwner(@PathParam("oid") String shadowOid, @Context MessageContext mc){ LOGGER.info("model rest service for find shadow owner operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_FIND_SHADOW_OWNER); Response response; try { PrismObject<UserType> user = model.findShadowOwner(shadowOid, task, parentResult); response = Response.ok().entity(user).build(); } catch (ConfigurationException e) { response = buildErrorResponse(Status.INTERNAL_SERVER_ERROR, e.getMessage()); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @POST @Path("/{type}/search") // @Produces({"text/html", "application/xml"}) public Response searchObjects(@PathParam("type") String type, QueryType queryType, @Context MessageContext mc){ LOGGER.info("model rest service for find shadow owner operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_SEARCH_OBJECTS); Class clazz = ObjectTypes.getClassFromRestType(type); Response response; try { ObjectQuery query = QueryJaxbConvertor.createObjectQuery(clazz, queryType, prismContext); List<PrismObject<? extends ShadowType>> objects = model.searchObjects(clazz, query, null, task, parentResult); ObjectListType listType = new ObjectListType(); for (PrismObject<? extends ObjectType> o : objects) { listType.getObject().add(o.asObjectable()); } response = Response.ok().entity(listType).build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @POST @Path("/resources/{resourceOid}/import/{objectClass}") // @Produces({"text/html", "application/xml"}) public Response importFromResource(@PathParam("resourceOid") String resourceOid, @PathParam("objectClass") String objectClass, @Context MessageContext mc, @Context UriInfo uriInfo) { LOGGER.info("model rest service for import from resource operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_IMPORT_FROM_RESOURCE); QName objClass = new QName(MidPointConstants.NS_RI, objectClass); Response response; try { model.importFromResource(resourceOid, objClass, task, parentResult); response = Response.seeOther((uriInfo.getBaseUriBuilder().path(this.getClass(), "getObject") .build(ObjectTypes.TASK.getRestType(), task.getOid()))).build(); } catch (Exception ex) { response = handleException(ex); } parentResult.computeStatus(); finishRequest(task); return response; } @POST @Path("/resources/{resourceOid}/test") // @Produces({"text/html", "application/xml"}) public Response testResource(@PathParam("resourceOid") String resourceOid, @Context MessageContext mc) { LOGGER.info("model rest service for test resource operation start"); Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_TEST_RESOURCE); Response response; OperationResult testResult = null; try { testResult = model.testResource(resourceOid, task); response = Response.ok(testResult).build(); } catch (Exception ex) { response = handleException(ex); } if (testResult != null) { parentResult.getSubresults().add(testResult); } finishRequest(task); return response; } @POST @Path("/tasks/{oid}/suspend") public Response suspendTasks(@PathParam("oid") String taskOid, @Context MessageContext mc) { Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_SUSPEND_TASKS); Response response; Collection<String> taskOids = MiscUtil.createCollection(taskOid); try { model.suspendTasks(taskOids, WAIT_FOR_TASK_STOP, parentResult); parentResult.computeStatus(); if (parentResult.isSuccess()){ response = Response.noContent().build(); } else { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(parentResult.getMessage()).build(); } } catch (Exception ex) { response = handleException(ex); } finishRequest(task); return response; } // @DELETE // @Path("tasks/{oid}/suspend") public Response suspendAndDeleteTasks(@PathParam("oid") String taskOid, @Context MessageContext mc) { Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_SUSPEND_AND_DELETE_TASKS); Response response; Collection<String> taskOids = MiscUtil.createCollection(taskOid); try { model.suspendAndDeleteTasks(taskOids, WAIT_FOR_TASK_STOP, true, parentResult); parentResult.computeStatus(); if (parentResult.isSuccess()) { response = Response.accepted().build(); } else { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(parentResult.getMessage()).build(); } } catch (Exception ex) { response = handleException(ex); } finishRequest(task); return response; } @POST @Path("/tasks/{oid}/resume") public Response resumeTasks(@PathParam("oid") String taskOid, @Context MessageContext mc) { Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_RESUME_TASKS); Response response; Collection<String> taskOids = MiscUtil.createCollection(taskOid); try { model.resumeTasks(taskOids, parentResult); parentResult.computeStatus(); if (parentResult.isSuccess()) { response = Response.accepted().build(); } else { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(parentResult.getMessage()).build(); } } catch (Exception ex) { response = handleException(ex); } finishRequest(task); return response; } @POST @Path("tasks/{oid}/run") public Response scheduleTasksNow(@PathParam("oid") String taskOid, @Context MessageContext mc) { Task task = initRequest(mc); OperationResult parentResult = task.getResult().createSubresult(OPERATION_SCHEDULE_TASKS_NOW); Collection<String> taskOids = MiscUtil.createCollection(taskOid); Response response; try { model.scheduleTasksNow(taskOids, parentResult); parentResult.computeStatus(); if (parentResult.isSuccess()) { response = Response.accepted().build(); } else { response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(parentResult.getMessage()).build(); } } catch (Exception ex) { response = handleException(ex); } finishRequest(task); return response; } // @GET // @Path("tasks/{oid}") // public Response getTaskByIdentifier(@PathParam("oid") String identifier) throws SchemaException, ObjectNotFoundException { // OperationResult parentResult = new OperationResult("getTaskByIdentifier"); // PrismObject<TaskType> task = model.getTaskByIdentifier(identifier, null, parentResult); // // return Response.ok(task).build(); // } // // // public boolean deactivateServiceThreads(long timeToWait, OperationResult parentResult) { // return model.deactivateServiceThreads(timeToWait, parentResult); // } // // public void reactivateServiceThreads(OperationResult parentResult) { // model.reactivateServiceThreads(parentResult); // } // // public boolean getServiceThreadsActivationState() { // return model.getServiceThreadsActivationState(); // } // // public void stopSchedulers(Collection<String> nodeIdentifiers, OperationResult parentResult) { // model.stopSchedulers(nodeIdentifiers, parentResult); // } // // public boolean stopSchedulersAndTasks(Collection<String> nodeIdentifiers, long waitTime, OperationResult parentResult) { // return model.stopSchedulersAndTasks(nodeIdentifiers, waitTime, parentResult); // } // // public void startSchedulers(Collection<String> nodeIdentifiers, OperationResult parentResult) { // model.startSchedulers(nodeIdentifiers, parentResult); // } // // public void synchronizeTasks(OperationResult parentResult) { // model.synchronizeTasks(parentResult); // } private ModelExecuteOptions getOptions(UriInfo uriInfo){ List<String> options = uriInfo.getQueryParameters().get(QUERY_PARAMETER_OPTIONS); return ModelExecuteOptions.fromRestOptions(options); } private Task initRequest(MessageContext mc) { Task task = (Task) mc.get(MESSAGE_PROPERTY_TASK_NAME); // No need to audit login. it was already audited during authentication return task; } private void finishRequest(Task task) { task.getResult().computeStatus(); ConnectionEnvironment connEnv = new ConnectionEnvironment(); connEnv.setChannel(SchemaConstants.CHANNEL_REST_URI); connEnv.setSessionId(task.getTaskIdentifier()); securityHelper.auditLogout(connEnv, task); } }
fixing MID-2637
model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelRestService.java
fixing MID-2637
<ide><path>odel/model-impl/src/main/java/com/evolveum/midpoint/model/impl/ModelRestService.java <ide> } <ide> <ide> ModelExecuteOptions modelExecuteOptions = ModelExecuteOptions.fromRestOptions(options); <del> if (modelExecuteOptions == null || !ModelExecuteOptions.isOverwrite(modelExecuteOptions)){ <add> if (modelExecuteOptions == null) { <ide> modelExecuteOptions = ModelExecuteOptions.createOverwrite(); <add> } else if (!ModelExecuteOptions.isOverwrite(modelExecuteOptions)){ <add> modelExecuteOptions.setOverwrite(Boolean.TRUE); <ide> } <ide> <ide> String oid;
Java
apache-2.0
85163523b6c6c53af0d3aecaf25783d7b142aa2e
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.run; import com.intellij.execution.Location; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.actions.ConfigurationFromContext; import com.intellij.execution.actions.LazyRunConfigurationProducer; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.testFramework.LightVirtualFile; import com.jetbrains.python.PythonFileType; import com.jetbrains.python.PythonLanguage; import com.jetbrains.python.psi.types.TypeEvalContext; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; /** * @author yole */ public final class PythonRunConfigurationProducer extends LazyRunConfigurationProducer<PythonRunConfiguration> { @NotNull @Override public ConfigurationFactory getConfigurationFactory() { return PythonConfigurationType.getInstance().getFactory(); } @Override protected boolean setupConfigurationFromContext(@NotNull PythonRunConfiguration configuration, @NotNull ConfigurationContext context, @NotNull Ref<PsiElement> sourceElement) { final Location location = context.getLocation(); if (location == null) return false; final PsiFile script = location.getPsiElement().getContainingFile(); if (!isAvailable(location, script)) return false; final VirtualFile vFile = script.getVirtualFile(); if (vFile == null) return false; configuration.setScriptName(vFile.getPath()); final VirtualFile parent = vFile.getParent(); if (parent != null && StringUtil.isEmpty(configuration.getWorkingDirectory())) { configuration.setWorkingDirectory(parent.getPath()); } final Module module = ModuleUtilCore.findModuleForPsiElement(script); if (module != null) { configuration.setUseModuleSdk(true); configuration.setModule(module); } configuration.setGeneratedName(); return true; } @Override public boolean isConfigurationFromContext(@NotNull PythonRunConfiguration configuration, @NotNull ConfigurationContext context) { final Location location = context.getLocation(); if (location == null) return false; final PsiFile script = location.getPsiElement().getContainingFile(); if (!isAvailable(location, script)) return false; final VirtualFile virtualFile = script.getVirtualFile(); if (virtualFile == null) return false; if (virtualFile instanceof LightVirtualFile) return false; final String workingDirectory = configuration.getWorkingDirectory(); final String scriptName = configuration.getScriptName(); final String path = virtualFile.getPath(); return scriptName.equals(path) || path.equals(new File(workingDirectory, scriptName).getAbsolutePath()); } private static boolean isAvailable(@NotNull final Location location, @Nullable final PsiFile script) { if (script == null || script.getFileType() != PythonFileType.INSTANCE || !script.getViewProvider().getBaseLanguage().isKindOf(PythonLanguage.INSTANCE)) { return false; } final Module module = ModuleUtilCore.findModuleForPsiElement(script); if (module != null) { for (RunnableScriptFilter f : RunnableScriptFilter.EP_NAME.getExtensionList()) { // Configuration producers always called by user if (f.isRunnableScript(script, module, location, TypeEvalContext.userInitiated(location.getProject(), null))) { return false; } } } return true; } // Only prefer over other regular config @Override public boolean isPreferredConfiguration(ConfigurationFromContext self, ConfigurationFromContext other) { return other.isProducedBy(PythonRunConfigurationProducer.class); } }
python/src/com/jetbrains/python/run/PythonRunConfigurationProducer.java
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.run; import com.intellij.execution.Location; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.actions.ConfigurationFromContext; import com.intellij.execution.actions.LazyRunConfigurationProducer; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.testFramework.LightVirtualFile; import com.jetbrains.python.PythonFileType; import com.jetbrains.python.PythonLanguage; import com.jetbrains.python.psi.types.TypeEvalContext; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; /** * @author yole */ public final class PythonRunConfigurationProducer extends LazyRunConfigurationProducer<PythonRunConfiguration> { @NotNull @Override public ConfigurationFactory getConfigurationFactory() { return PythonConfigurationType.getInstance().getFactory(); } @Override protected boolean setupConfigurationFromContext(@NotNull PythonRunConfiguration configuration, @NotNull ConfigurationContext context, @NotNull Ref<PsiElement> sourceElement) { final Location location = context.getLocation(); if (location == null) return false; final PsiFile script = location.getPsiElement().getContainingFile(); if (!isAvailable(location, script)) return false; final VirtualFile vFile = script.getVirtualFile(); if (vFile == null) return false; configuration.setScriptName(vFile.getPath()); final VirtualFile parent = vFile.getParent(); if (parent != null && StringUtil.isEmpty(configuration.getWorkingDirectory())) { configuration.setWorkingDirectory(parent.getPath()); } final Module module = ModuleUtilCore.findModuleForPsiElement(script); if (module != null) { configuration.setUseModuleSdk(true); configuration.setModule(module); } configuration.setName(configuration.suggestedName()); return true; } @Override public boolean isConfigurationFromContext(@NotNull PythonRunConfiguration configuration, @NotNull ConfigurationContext context) { final Location location = context.getLocation(); if (location == null) return false; final PsiFile script = location.getPsiElement().getContainingFile(); if (!isAvailable(location, script)) return false; final VirtualFile virtualFile = script.getVirtualFile(); if (virtualFile == null) return false; if (virtualFile instanceof LightVirtualFile) return false; final String workingDirectory = configuration.getWorkingDirectory(); final String scriptName = configuration.getScriptName(); final String path = virtualFile.getPath(); return scriptName.equals(path) || path.equals(new File(workingDirectory, scriptName).getAbsolutePath()); } private static boolean isAvailable(@NotNull final Location location, @Nullable final PsiFile script) { if (script == null || script.getFileType() != PythonFileType.INSTANCE || !script.getViewProvider().getBaseLanguage().isKindOf(PythonLanguage.INSTANCE)) { return false; } final Module module = ModuleUtilCore.findModuleForPsiElement(script); if (module != null) { for (RunnableScriptFilter f : RunnableScriptFilter.EP_NAME.getExtensionList()) { // Configuration producers always called by user if (f.isRunnableScript(script, module, location, TypeEvalContext.userInitiated(location.getProject(), null))) { return false; } } } return true; } // Only prefer over other regular config @Override public boolean isPreferredConfiguration(ConfigurationFromContext self, ConfigurationFromContext other) { return other.isProducedBy(PythonRunConfigurationProducer.class); } }
PY-12516 Enable automatic renaming of generated run configurations on module refactoring It didn't work because we forgot to set isGeneratedName flag for such run configurations by initializing suggested name manually instead of using the standard LocatableConfigurationBase#setGeneratedName() method. GitOrigin-RevId: 6f0eb6b3e53f52e6a7647298cc143a2d0f573e93
python/src/com/jetbrains/python/run/PythonRunConfigurationProducer.java
PY-12516 Enable automatic renaming of generated run configurations on module refactoring
<ide><path>ython/src/com/jetbrains/python/run/PythonRunConfigurationProducer.java <ide> configuration.setUseModuleSdk(true); <ide> configuration.setModule(module); <ide> } <del> configuration.setName(configuration.suggestedName()); <add> configuration.setGeneratedName(); <ide> return true; <ide> } <ide>
Java
apache-2.0
4a663936575051ace985584c46d333185e2a5202
0
bither/bither-android,neurocis/bither-android,leerduo/bither-android,CryptArc/templecoin-bither
/* * Copyright 2014 http://Bither.net * * 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 net.bither.db; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import net.bither.BitherApplication; import net.bither.bitherj.core.In; import net.bither.bitherj.core.Out; import net.bither.bitherj.core.Tx; import net.bither.bitherj.db.AbstractDb; import net.bither.bitherj.db.ITxProvider; import net.bither.bitherj.exception.AddressFormatException; import net.bither.bitherj.utils.Base58; import net.bither.bitherj.utils.Sha256Hash; import net.bither.bitherj.utils.Utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class TxProvider implements ITxProvider { private static TxProvider txProvider = new TxProvider(BitherApplication.mDbHelper); public static TxProvider getInstance() { return txProvider; } private SQLiteOpenHelper mDb; public TxProvider(SQLiteOpenHelper db) { this.mDb = db; } // public List<Tx> getTxByAddress(String address) { // List<Tx> txItemList = new ArrayList<Tx>(); // String sql = "select b.* from addresses_txs a, txs b where a.tx_hash=b.tx_hash and a.address='" + // address + "' order by b.block_no"; // SQLiteDatabase db = this.mDb.getReadableDatabase(); // Cursor c = db.rawQuery(sql, null); // try { // while (c.moveToNext()) { // txItemList.add(applyCursor(c)); // } // } catch (Exception e) { // e.printStackTrace(); // } // c.close(); // return txItemList; // } public List<Tx> getTxAndDetailByAddress(String address) { List<Tx> txItemList = new ArrayList<Tx>(); HashMap<Sha256Hash, Tx> txDict = new HashMap<Sha256Hash, Tx>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); try { String sql = "select b.* from addresses_txs a, txs b where a.tx_hash=b.tx_hash and a.address='" + address + "' order by b.block_no "; Cursor c = db.rawQuery(sql, null); while (c.moveToNext()) { Tx txItem = applyCursor(c); txItem.setIns(new ArrayList<In>()); txItem.setOuts(new ArrayList<Out>()); txItemList.add(txItem); txDict.put(new Sha256Hash(txItem.getTxHash()), txItem); } c.close(); sql = "select b.* from addresses_txs a, ins b where a.tx_hash=b.tx_hash and a.address=? " + "order by b.tx_hash ,b.in_sn"; c = db.rawQuery(sql, new String[]{address}); while (c.moveToNext()) { In inItem = applyCursorIn(c); Tx tx = txDict.get(new Sha256Hash(inItem.getTxHash())); if (tx != null) tx.getIns().add(inItem); } c.close(); sql = "select b.* from addresses_txs a, outs b where a.tx_hash=b.tx_hash and a.address=? " + "order by b.tx_hash,b.out_sn"; c = db.rawQuery(sql, new String[]{address}); while (c.moveToNext()) { Out out = applyCursorOut(c); Tx tx = txDict.get(new Sha256Hash(out.getTxHash())); if (tx != null) tx.getOuts().add(out); } c.close(); } catch (AddressFormatException e) { e.printStackTrace(); } return txItemList; } public List<Tx> getPublishedTxs() { List<Tx> txItemList = new ArrayList<Tx>(); HashMap<Sha256Hash, Tx> txDict = new HashMap<Sha256Hash, Tx>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select * from txs where block_no is null or block_no = ?"; try { Cursor c = db.rawQuery(sql, new String[]{Integer.toString(Tx.TX_UNCONFIRMED)}); while (c.moveToNext()) { Tx txItem = applyCursor(c); txItem.setIns(new ArrayList<In>()); txItem.setOuts(new ArrayList<Out>()); txItemList.add(txItem); txDict.put(new Sha256Hash(txItem.getTxHash()), txItem); } c.close(); sql = "select b.* from txs a, ins b where a.tx_hash=b.tx_hash and ( a.block_no is null or a.block_no = ? ) " + "order by b.tx_hash ,b.in_sn"; c = db.rawQuery(sql, new String[]{Integer.toString(Tx.TX_UNCONFIRMED)}); while (c.moveToNext()) { In inItem = applyCursorIn(c); Tx tx = txDict.get(new Sha256Hash(inItem.getTxHash())); tx.getIns().add(inItem); } c.close(); sql = "select b.* from txs a, outs b where a.tx_hash=b.tx_hash and ( a.block_no is null or a.block_no = ? ) " + "order by b.tx_hash,b.out_sn"; c = db.rawQuery(sql, new String[]{Integer.toString(Tx.TX_UNCONFIRMED)}); while (c.moveToNext()) { Out out = applyCursorOut(c); Tx tx = txDict.get(new Sha256Hash(out.getTxHash())); tx.getOuts().add(out); } c.close(); } catch (AddressFormatException e) { e.printStackTrace(); } finally { } return txItemList; } public Tx getTxDetailByTxHash(byte[] txHash) { Tx txItem = null; String txHashStr = Base58.encode(txHash); SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select * from txs where tx_hash='" + txHashStr + "'"; Cursor c = db.rawQuery(sql, null); try { if (c.moveToNext()) { txItem = applyCursor(c); } if (txItem != null) { addInsAndOuts(db, txItem); } } catch (AddressFormatException e) { e.printStackTrace(); } finally { c.close(); } return txItem; } private void addInsAndOuts(SQLiteDatabase db, Tx txItem) throws AddressFormatException { String txHashStr = Base58.encode(txItem.getTxHash()); txItem.setOuts(new ArrayList<Out>()); txItem.setIns(new ArrayList<In>()); String sql = "select * from ins where tx_hash='" + txHashStr + "' order by in_sn"; Cursor c = db.rawQuery(sql, null); while (c.moveToNext()) { In inItem = applyCursorIn(c); inItem.setTx(txItem); txItem.getIns().add(inItem); } c.close(); sql = "select * from outs where tx_hash='" + txHashStr + "' order by out_sn"; c = db.rawQuery(sql, null); while (c.moveToNext()) { Out outItem = applyCursorOut(c); outItem.setTx(txItem); txItem.getOuts().add(outItem); } c.close(); } public boolean isExist(byte[] txHash) { boolean result = false; SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select count(0) from txs where tx_hash='" + Base58.encode(txHash) + "'"; Cursor c = db.rawQuery(sql, null); if (c.moveToNext()) { result = c.getInt(0) > 0; } c.close(); return result; } public void add(Tx txItem) { SQLiteDatabase db = this.mDb.getWritableDatabase(); db.beginTransaction(); addTxToDb(db, txItem); db.setTransactionSuccessful(); db.endTransaction(); } public void addTxs(List<Tx> txItems) { SQLiteDatabase db = this.mDb.getReadableDatabase(); List<Tx> addTxItems = new ArrayList<Tx>(); String existSql = "select count(0) cnt from txs where tx_hash="; Cursor c; for (Tx txItem : txItems) { c = db.rawQuery(existSql + "'" + Base58.encode(txItem.getTxHash()) + "'", null); int cnt = 0; if (c.moveToNext()) { int idColumn = c.getColumnIndex("cnt"); if (idColumn != -1) { cnt = c.getInt(idColumn); } } if (cnt == 0) { addTxItems.add(txItem); } c.close(); } if (addTxItems.size() > 0) { db = this.mDb.getWritableDatabase(); db.beginTransaction(); for (Tx txItem : addTxItems) { //LogUtil.d("txDb", Base58.encode(txItem.getTxHash()) + "," + Utils.bytesToHexString(txItem.getTxHash())); addTxToDb(db, txItem); //List<Tx> txList = getTxAndDetailByAddress("1B5XuAJNTN2Upi7AXs7tJCxvFGjhPna6Q5"); } db.setTransactionSuccessful(); db.endTransaction(); } } private void addTxToDb(SQLiteDatabase db, Tx txItem) { ContentValues cv = new ContentValues(); applyContentValues(txItem, cv); db.insert(AbstractDb.Tables.TXS, null, cv); Cursor c; String sql; List<Object[]> addressesTxsRels = new ArrayList<Object[]>(); try { for (In inItem : txItem.getIns()) { sql = "select out_address from outs where tx_hash='" + Base58.encode(inItem.getPrevTxHash()) + "' and out_sn=" + inItem.getPrevOutSn(); c = db.rawQuery(sql, null); while (c.moveToNext()) { int idColumn = c.getColumnIndex("out_address"); if (idColumn != -1) { addressesTxsRels.add(new Object[]{c.getString(idColumn), txItem.getTxHash()}); } } c.close(); cv = new ContentValues(); applyContentValues(inItem, cv); db.insert(AbstractDb.Tables.INS, null, cv); sql = "update outs set out_status=" + Out.OutStatus.spent.getValue() + " where tx_hash='" + Base58.encode(inItem.getPrevTxHash()) + "' and out_sn=" + inItem.getPrevOutSn(); db.execSQL(sql); } for (Out outItem : txItem.getOuts()) { cv = new ContentValues(); applyContentValues(outItem, cv); db.insert(AbstractDb.Tables.OUTS, null, cv); if (!Utils.isEmpty(outItem.getOutAddress())) { addressesTxsRels.add(new Object[]{outItem.getOutAddress(), txItem.getTxHash()}); } sql = "select tx_hash from ins where prev_tx_hash='" + Base58.encode(txItem.getTxHash()) + "' and prev_out_sn=" + outItem.getOutSn(); c = db.rawQuery(sql, null); boolean isSpentByExistTx = false; if (c.moveToNext()) { int idColumn = c.getColumnIndex("tx_hash"); if (idColumn != -1) { addressesTxsRels.add(new Object[]{outItem.getOutAddress(), Base58.decode(c.getString(idColumn))}); } isSpentByExistTx = true; } c.close(); if (isSpentByExistTx) { sql = "update outs set out_status=" + Out.OutStatus.spent.getValue() + " where tx_hash='" + Base58.encode(txItem.getTxHash()) + "' and out_sn=" + outItem.getOutSn(); db.execSQL(sql); } } for (Object[] array : addressesTxsRels) { sql = "insert or ignore into addresses_txs(address, tx_hash) values('" + array[0] + "','" + Base58.encode((byte[]) array[1]) + "')"; db.execSQL(sql); } } catch (AddressFormatException e) { e.printStackTrace(); } } public void remove(byte[] txHash) { String txHashStr = Base58.encode(txHash); List<String> txHashes = new ArrayList<String>(); List<String> needRemoveTxHashes = new ArrayList<String>(); txHashes.add(txHashStr); while (txHashes.size() > 0) { String thisHash = txHashes.get(0); txHashes.remove(0); needRemoveTxHashes.add(thisHash); List<String> temp = getRelayTx(thisHash); txHashes.addAll(temp); } SQLiteDatabase db = this.mDb.getWritableDatabase(); db.beginTransaction(); for (String str : needRemoveTxHashes) { removeSingleTx(db, str); } db.setTransactionSuccessful(); db.endTransaction(); } private void removeSingleTx(SQLiteDatabase db, String tx) { String deleteTx = "delete from txs where tx_hash='" + tx + "'"; String deleteIn = "delete from ins where tx_hash='" + tx + "'"; String deleteOut = "delete from outs where tx_hash='" + tx + "'"; String deleteAddressesTx = "delete from addresses_txs where tx_hash='" + tx + "'"; String inSql = "select prev_tx_hash,prev_out_sn from ins where tx_hash='" + tx + "'"; String existOtherIn = "select count(0) cnt from ins where prev_tx_hash=? and prev_out_sn=?"; String updatePrevOut = "update outs set out_status=%d where tx_hash=%s and out_sn=%d"; Cursor c = db.rawQuery(inSql, new String[]{tx}); List<Object[]> needUpdateOuts = new ArrayList<Object[]>(); while (c.moveToNext()) { int idColumn = c.getColumnIndex(AbstractDb.InsColumns.PREV_TX_HASH); String prevTxHash = null; int prevOutSn = 0; if (idColumn != -1) { prevTxHash = c.getString(idColumn); } idColumn = c.getColumnIndex(AbstractDb.InsColumns.PREV_OUT_SN); if (idColumn != -1) { prevOutSn = c.getInt(idColumn); } needUpdateOuts.add(new Object[]{prevTxHash, prevOutSn}); } c.close(); db.execSQL(deleteAddressesTx); db.execSQL(deleteOut); db.execSQL(deleteIn); db.execSQL(deleteTx); for (Object[] array : needUpdateOuts) { c = db.rawQuery(existOtherIn, new String[]{array[0].toString(), array[1].toString()}); while (c.moveToNext()) { if (c.getInt(0) == 0) { String updateSql = Utils.format(updatePrevOut, Out.OutStatus.unspent.getValue(), array[0].toString(), Integer.valueOf(array[1].toString())); db.execSQL(updateSql); } } c.close(); } } private List<String> getRelayTx(String txHash) { List<String> relayTxHashes = new ArrayList<String>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); String relayTx = "select distinct tx_hash from ins where prev_tx_hash='" + txHash + "'"; Cursor c = db.rawQuery(relayTx, null); while (c.moveToNext()) { relayTxHashes.add(c.getString(0)); } c.close(); return relayTxHashes; } public boolean isAddressContainsTx(String address, Tx txItem) { boolean result = false; String sql = "select count(0) from ins a, txs b where a.tx_hash=b.tx_hash and" + " b.block_no is not null and a.prev_tx_hash=? and a.prev_out_sn=?"; SQLiteDatabase db = this.mDb.getReadableDatabase(); Cursor c; for (In inItem : txItem.getIns()) { c = db.rawQuery(sql, new String[]{Base58.encode(inItem.getPrevTxHash()), Integer.toString(inItem.getPrevOutSn())}); if (c.moveToNext()) { if (c.getInt(0) > 0) { c.close(); return false; } } c.close(); } sql = "select count(0) from addresses_txs where tx_hash=? and address=?"; c = db.rawQuery(sql, new String[]{ Base58.encode(txItem.getTxHash()), address }); int count = 0; if (c.moveToNext()) { count = c.getInt(0); } c.close(); if (count > 0) { return true; } sql = "select count(0) from outs where tx_hash=? and out_sn=? and out_address=?"; for (In inItem : txItem.getIns()) { c = db.rawQuery(sql, new String[]{Base58.encode(inItem.getPrevTxHash()) , Integer.toString(inItem.getPrevOutSn()), address}); count = 0; if (c.moveToNext()) { count = c.getInt(0); } c.close(); if (count > 0) { return true; } } return result; } public boolean isTxDoubleSpendWithConfirmedTx(Tx tx) { String sql = "select count(0) from ins a, txs b where a.tx_hash=b.tx_hash and" + " b.block_no is not null and a.prev_tx_hash=? and a.prev_out_sn=?"; SQLiteDatabase db = this.mDb.getReadableDatabase(); Cursor c; for (In inItem : tx.getIns()) { c = db.rawQuery(sql, new String[]{Base58.encode(inItem.getPrevTxHash()), Integer.toString(inItem.getPrevOutSn())}); if (c.moveToNext()) { if (c.getInt(0) > 0) { c.close(); return true; } } c.close(); } return false; } public List<String> getInAddresses(Tx tx) { List<String> result = new ArrayList<String>(); String sql = "select out_address from outs where tx_hash=? and out_sn=?"; SQLiteDatabase db = this.mDb.getReadableDatabase(); Cursor c; for (In inItem : tx.getIns()) { c = db.rawQuery(sql, new String[]{Base58.encode(inItem.getPrevTxHash()) , Integer.toString(inItem.getPrevOutSn())}); if (c.moveToNext()) { if (!c.isNull(0)) { result.add(c.getString(0)); } } c.close(); } return result; } public void confirmTx(int blockNo, List<byte[]> txHashes) { if (blockNo == Tx.TX_UNCONFIRMED || txHashes == null) { return; } String sql = "update txs set block_no=%d where tx_hash='%s'"; String existSql = "select count(0) from txs where block_no=? and tx_hash=?"; String doubleSpendSql = "select a.tx_hash from ins a, ins b where a.prev_tx_hash=b.prev_tx_hash " + "and a.prev_out_sn=b.prev_out_sn and a.tx_hash<>b.tx_hash and b.tx_hash=?"; String blockTimeSql = "select block_time from blocks where block_no=?"; String updateTxTimeThatMoreThanBlockTime = "update txs set tx_time=%d where block_no=%d and tx_time>%d"; SQLiteDatabase db = this.mDb.getWritableDatabase(); db.beginTransaction(); Cursor c; for (byte[] txHash : txHashes) { c = db.rawQuery(existSql, new String[]{Integer.toString(blockNo), Base58.encode(txHash)}); if (c.moveToNext()) { int cnt = c.getInt(0); c.close(); if (cnt > 0) { continue; } } else { c.close(); } String updateSql = Utils.format(sql, blockNo, Base58.encode(txHash)); db.execSQL(updateSql); c = db.rawQuery(doubleSpendSql, new String[]{Base58.encode(txHash)}); List<String> txHashes1 = new ArrayList<String>(); while (c.moveToNext()) { int idColumn = c.getColumnIndex("tx_hash"); if (idColumn != -1) { txHashes1.add(c.getString(idColumn)); } } c.close(); List<String> needRemoveTxHashes = new ArrayList<String>(); while (txHashes1.size() > 0) { String thisHash = txHashes1.get(0); txHashes1.remove(0); needRemoveTxHashes.add(thisHash); List<String> temp = getRelayTx(thisHash); txHashes1.addAll(temp); } for (String each : needRemoveTxHashes) { removeSingleTx(db, each); } } c = db.rawQuery(blockTimeSql, new String[]{Integer.toString(blockNo)}); if (c.moveToNext()) { int idColumn = c.getColumnIndex("block_time"); if (idColumn != -1) { int blockTime = c.getInt(idColumn); c.close(); String sqlTemp = Utils.format(updateTxTimeThatMoreThanBlockTime, blockTime, blockNo, blockTime); db.execSQL(sqlTemp); } } else { c.close(); } db.setTransactionSuccessful(); db.endTransaction(); } public void unConfirmTxByBlockNo(int blockNo) { SQLiteDatabase db = this.mDb.getWritableDatabase(); String sql = "update txs set block_no=null where block_no>=" + blockNo; db.execSQL(sql); } public List<Tx> getUnspendTxWithAddress(String address) { String unspendOutSql = "select a.*,b.tx_ver,b.tx_locktime,b.tx_time,b.block_no,b.source,ifnull(b.block_no,0)*a.out_value coin_depth " + "from outs a,txs b where a.tx_hash=b.tx_hash" + " and a.out_address=? and a.out_status=?"; List<Tx> txItemList = new ArrayList<Tx>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); Cursor c = db.rawQuery(unspendOutSql, new String[]{address, Integer.toString(Out.OutStatus.unspent.getValue())}); try { while (c.moveToNext()) { int idColumn = c.getColumnIndex("coin_depth"); Tx txItem = applyCursor(c); Out outItem = applyCursorOut(c); if (idColumn != -1) { outItem.setCoinDepth(c.getLong(idColumn)); } outItem.setTx(txItem); txItem.setOuts(new ArrayList<Out>()); txItem.getOuts().add(outItem); txItemList.add(txItem); } c.close(); } catch (AddressFormatException e) { e.printStackTrace(); } return txItemList; } public List<Out> getUnspendOutWithAddress(String address) { List<Out> outItems = new ArrayList<Out>(); String unspendOutSql = "select a.* from outs a,txs b where a.tx_hash=b.tx_hash " + "and b.block_no is null and a.out_address=? and a.out_status=?"; SQLiteDatabase db = this.mDb.getReadableDatabase(); Cursor c = db.rawQuery(unspendOutSql, new String[]{address, Integer.toString(Out.OutStatus.unspent.getValue())}); try { while (c.moveToNext()) { outItems.add(applyCursorOut(c)); } c.close(); } catch (AddressFormatException e) { e.printStackTrace(); } return outItems; } public List<Out> getUnSpendOutCanSpendWithAddress(String address) { List<Out> outItems = new ArrayList<Out>(); String confirmedOutSql = "select a.*,b.block_no*a.out_value coin_depth from outs a,txs b" + " where a.tx_hash=b.tx_hash and b.block_no is not null and a.out_address=? and a.out_status=?"; String selfOutSql = "select a.* from outs a,txs b where a.tx_hash=b.tx_hash and b.block_no" + " is null and a.out_address=? and a.out_status=? and b.source>=?"; SQLiteDatabase db = this.mDb.getReadableDatabase(); Cursor c = db.rawQuery(confirmedOutSql, new String[]{address, Integer.toString(Out.OutStatus.unspent.getValue())}); try { while (c.moveToNext()) { Out outItem = applyCursorOut(c); int idColumn = c.getColumnIndex("coin_depth"); if (idColumn != -1) { outItem.setCoinDepth(c.getLong(idColumn)); } outItems.add(outItem); } c.close(); c = db.rawQuery(selfOutSql, new String[]{address, Integer.toString(Out.OutStatus.unspent.getValue()), "1"}); while (c.moveToNext()) { outItems.add(applyCursorOut(c)); } c.close(); } catch (AddressFormatException e) { e.printStackTrace(); } return outItems; } public List<Out> getUnSpendOutButNotConfirmWithAddress(String address) { List<Out> outItems = new ArrayList<Out>(); String selfOutSql = "select a.* from outs a,txs b where a.tx_hash=b.tx_hash and b.block_no" + " is null and a.out_address=? and a.out_status=? and b.source=?"; SQLiteDatabase db = this.mDb.getReadableDatabase(); Cursor c = db.rawQuery(selfOutSql, new String[]{address, Integer.toString(Out.OutStatus.unspent.getValue()), "0"}); try { while (c.moveToNext()) { outItems.add(applyCursorOut(c)); } } catch (AddressFormatException e) { e.printStackTrace(); } finally { c.close(); } return outItems; } public int txCount(String address) { int result = 0; SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select count(*) from addresses_txs where address='" + address + "'"; Cursor c = db.rawQuery(sql, null); if (c.moveToNext()) { result = c.getInt(0); } c.close(); return result; } public void txSentBySelfHasSaw(byte[] txHash) { SQLiteDatabase db = this.mDb.getWritableDatabase(); String sql = "update txs set source=source+1 where tx_hash='" + Base58.encode(txHash) + "' and source>=1"; db.execSQL(sql); } public List<Out> getOuts() { List<Out> outItemList = new ArrayList<Out>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select * from outs "; Cursor c = db.rawQuery(sql, null); try { while (c.moveToNext()) { outItemList.add(applyCursorOut(c)); } } catch (AddressFormatException e) { e.printStackTrace(); } finally { c.close(); } return outItemList; } public List<Out> getUnSpentOuts() { List<Out> outItemList = new ArrayList<Out>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select * from outs where out_status=?"; Cursor c = db.rawQuery(sql, new String[]{"0"}); try { while (c.moveToNext()) { outItemList.add(applyCursorOut(c)); } } catch (AddressFormatException e) { e.printStackTrace(); } finally { c.close(); } return outItemList; } public List<In> getRelatedIn(String address){ List<In> list = new ArrayList<In>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select ins.* from ins,addresses_txs " + "where ins.tx_hash=addresses_txs.tx_hash and addresses_txs.address=? "; Cursor c = db.rawQuery(sql, new String[] {address}); try { while (c.moveToNext()) { list.add(applyCursorIn(c)); } } catch (AddressFormatException e) { e.printStackTrace(); } finally { c.close(); } return list; } public List<Tx> getRecentlyTxsByAddress(String address, int greateThanBlockNo, int limit) { List<Tx> txItemList = new ArrayList<Tx>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select b.* from addresses_txs a, txs b where a.tx_hash=b.tx_hash and a.address='%s' " + "and ((b.block_no is null) or (b.block_no is not null and b.block_no>%d)) " + "order by ifnull(b.block_no,4294967295) desc, b.tx_time desc " + "limit %d "; sql = Utils.format(sql, address, greateThanBlockNo, limit); Cursor c = db.rawQuery(sql, null); try { while (c.moveToNext()) { Tx txItem = applyCursor(c); txItemList.add(txItem); } for (Tx item : txItemList) { addInsAndOuts(db, item); } } catch (AddressFormatException e) { e.printStackTrace(); } finally { c.close(); } return txItemList; } public List<Long> txInValues(byte[] txHash) { List<Long> inValues = new ArrayList<Long>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select b.out_value " + "from ins a left outer join outs b on a.prev_tx_hash=b.tx_hash and a.prev_out_sn=b.out_sn " + "where a.tx_hash='" + Base58.encode(txHash) + "'"; Cursor c = db.rawQuery(sql, null); while (c.moveToNext()) { int idColumn = c.getColumnIndex("out_value"); if (idColumn != -1) { inValues.add(c.getLong(idColumn)); } else { inValues.add(null); } } c.close(); return inValues; } public HashMap<Sha256Hash, Tx> getTxDependencies(Tx txItem) { HashMap<Sha256Hash, Tx> result = new HashMap<Sha256Hash, Tx>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); try { for (In inItem : txItem.getIns()) { Tx tx; String txHashStr = Base58.encode(inItem.getTxHash()); String sql = "select * from txs where tx_hash='" + txHashStr + "'"; Cursor c = db.rawQuery(sql, null); if (c.moveToNext()) { tx = applyCursor(c); c.close(); } else { c.close(); continue; } addInsAndOuts(db, tx); result.put(new Sha256Hash(tx.getTxHash()), tx); } } catch (AddressFormatException e) { e.printStackTrace(); } return result; } public void clearAllTx() { SQLiteDatabase db = this.mDb.getWritableDatabase(); db.beginTransaction(); db.delete(AbstractDb.Tables.TXS, "", new String[0]); db.delete(AbstractDb.Tables.OUTS, "", new String[0]); db.delete(AbstractDb.Tables.INS, "", new String[0]); db.delete(AbstractDb.Tables.ADDRESSES_TXS, "", new String[0]); db.setTransactionSuccessful(); db.endTransaction(); } public void completeInSignature(List<In> ins) { SQLiteDatabase db = this.mDb.getWritableDatabase(); db.beginTransaction(); String sql = "update ins set in_signature=? where tx_hash=? and in_sn=? and in_signature is null"; for (In in : ins) { db.execSQL(sql, new String[]{Base58.encode(in.getInSignature()) , Base58.encode(in.getTxHash()), Integer.toString(in.getInSn())}); } db.setTransactionSuccessful(); db.endTransaction(); } public int needCompleteInSignature(String address) { int result = 0; SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select max(txs.block_no) from outs,ins,txs where outs.out_address=? " + "and ins.prev_tx_hash=outs.tx_hash and ins.prev_out_sn=outs.out_sn " + "and ifnull(ins.in_signature,'')='' and txs.tx_hash=ins.tx_hash"; // String sql = "select max(txs.block_no) from addresses_txs,ins,txs " + // "where addresses_txs.tx_hash=ins.tx_hash and addresses_txs.address=? " + // "and ins.in_signature is null and txs.tx_hash=ins.tx_hash"; Cursor c = db.rawQuery(sql, new String[] {address}); if (c.moveToNext()) { result = c.getInt(0); } c.close(); return result; } private void applyContentValues(Tx txItem, ContentValues cv) { if (txItem.getBlockNo() != Tx.TX_UNCONFIRMED) { cv.put(AbstractDb.TxsColumns.BLOCK_NO, txItem.getBlockNo()); } cv.put(AbstractDb.TxsColumns.TX_HASH, Base58.encode(txItem.getTxHash())); cv.put(AbstractDb.TxsColumns.SOURCE, txItem.getSource()); cv.put(AbstractDb.TxsColumns.TX_TIME, txItem.getTxTime()); cv.put(AbstractDb.TxsColumns.TX_VER, txItem.getTxVer()); cv.put(AbstractDb.TxsColumns.TX_LOCKTIME, txItem.getTxLockTime()); } private void applyContentValues(In inItem, ContentValues cv) { cv.put(AbstractDb.InsColumns.TX_HASH, Base58.encode(inItem.getTxHash())); cv.put(AbstractDb.InsColumns.IN_SN, inItem.getInSn()); cv.put(AbstractDb.InsColumns.PREV_TX_HASH, Base58.encode(inItem.getPrevTxHash())); cv.put(AbstractDb.InsColumns.PREV_OUT_SN, inItem.getPrevOutSn()); if (inItem.getInSignature() != null) { cv.put(AbstractDb.InsColumns.IN_SIGNATURE, Base58.encode(inItem.getInSignature())); } cv.put(AbstractDb.InsColumns.IN_SEQUENCE, inItem.getInSequence()); } private void applyContentValues(Out outItem, ContentValues cv) { cv.put(AbstractDb.OutsColumns.TX_HASH, Base58.encode(outItem.getTxHash())); cv.put(AbstractDb.OutsColumns.OUT_SN, outItem.getOutSn()); cv.put(AbstractDb.OutsColumns.OUT_SCRIPT, Base58.encode(outItem.getOutScript())); cv.put(AbstractDb.OutsColumns.OUT_VALUE, outItem.getOutValue()); cv.put(AbstractDb.OutsColumns.OUT_STATUS, outItem.getOutStatus().getValue()); if (!Utils.isEmpty(outItem.getOutAddress())) { cv.put(AbstractDb.OutsColumns.OUT_ADDRESS, outItem.getOutAddress()); } } private Tx applyCursor(Cursor c) throws AddressFormatException { Tx txItem = new Tx(); int idColumn = c.getColumnIndex(AbstractDb.TxsColumns.BLOCK_NO); if (!c.isNull(idColumn)) { txItem.setBlockNo(c.getInt(idColumn)); } else { txItem.setBlockNo(Tx.TX_UNCONFIRMED); } idColumn = c.getColumnIndex(AbstractDb.TxsColumns.TX_HASH); if (idColumn != -1) { txItem.setTxHash(Base58.decode(c.getString(idColumn))); } idColumn = c.getColumnIndex(AbstractDb.TxsColumns.SOURCE); if (idColumn != -1) { txItem.setSource(c.getInt(idColumn)); } if (txItem.getSource() >= 1) { txItem.setSawByPeerCnt(txItem.getSource() - 1); txItem.setSource(1); } else { txItem.setSawByPeerCnt(0); txItem.setSource(0); } idColumn = c.getColumnIndex(AbstractDb.TxsColumns.TX_TIME); if (idColumn != -1) { txItem.setTxTime(c.getInt(idColumn)); } idColumn = c.getColumnIndex(AbstractDb.TxsColumns.TX_VER); if (idColumn != -1) { txItem.setTxVer(c.getInt(idColumn)); } idColumn = c.getColumnIndex(AbstractDb.TxsColumns.TX_LOCKTIME); if (idColumn != -1) { txItem.setTxLockTime(c.getInt(idColumn)); } return txItem; } private In applyCursorIn(Cursor c) throws AddressFormatException { In inItem = new In(); int idColumn = c.getColumnIndex(AbstractDb.InsColumns.TX_HASH); if (idColumn != -1) { inItem.setTxHash(Base58.decode(c.getString(idColumn))); } idColumn = c.getColumnIndex(AbstractDb.InsColumns.IN_SN); if (idColumn != -1) { inItem.setInSn(c.getInt(idColumn)); } idColumn = c.getColumnIndex(AbstractDb.InsColumns.PREV_TX_HASH); if (idColumn != -1) { inItem.setPrevTxHash(Base58.decode(c.getString(idColumn))); } idColumn = c.getColumnIndex(AbstractDb.InsColumns.PREV_OUT_SN); if (idColumn != -1) { inItem.setPrevOutSn(c.getInt(idColumn)); } idColumn = c.getColumnIndex(AbstractDb.InsColumns.IN_SIGNATURE); if (idColumn != -1) { String inSignature = c.getString(idColumn); if (!Utils.isEmpty(inSignature)) { inItem.setInSignature(Base58.decode(c.getString(idColumn))); } } idColumn = c.getColumnIndex(AbstractDb.InsColumns.IN_SEQUENCE); if (idColumn != -1) { inItem.setInSequence(c.getInt(idColumn)); } return inItem; } private Out applyCursorOut(Cursor c) throws AddressFormatException { Out outItem = new Out(); int idColumn = c.getColumnIndex(AbstractDb.OutsColumns.TX_HASH); if (idColumn != -1) { outItem.setTxHash(Base58.decode(c.getString(idColumn))); } idColumn = c.getColumnIndex(AbstractDb.OutsColumns.OUT_SN); if (idColumn != -1) { outItem.setOutSn(c.getInt(idColumn)); } idColumn = c.getColumnIndex(AbstractDb.OutsColumns.OUT_SCRIPT); if (idColumn != -1) { outItem.setOutScript(Base58.decode(c.getString(idColumn))); } idColumn = c.getColumnIndex(AbstractDb.OutsColumns.OUT_VALUE); if (idColumn != -1) { outItem.setOutValue(c.getLong(idColumn)); } idColumn = c.getColumnIndex(AbstractDb.OutsColumns.OUT_STATUS); if (idColumn != -1) { outItem.setOutStatus(Out.getOutStatus(c.getInt(idColumn))); } idColumn = c.getColumnIndex(AbstractDb.OutsColumns.OUT_ADDRESS); if (idColumn != -1) { outItem.setOutAddress(c.getString(idColumn)); } return outItem; } }
bither-android/src/net/bither/db/TxProvider.java
/* * Copyright 2014 http://Bither.net * * 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 net.bither.db; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import net.bither.BitherApplication; import net.bither.bitherj.core.In; import net.bither.bitherj.core.Out; import net.bither.bitherj.core.Tx; import net.bither.bitherj.db.AbstractDb; import net.bither.bitherj.db.ITxProvider; import net.bither.bitherj.exception.AddressFormatException; import net.bither.bitherj.utils.Base58; import net.bither.bitherj.utils.Sha256Hash; import net.bither.bitherj.utils.Utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class TxProvider implements ITxProvider { private static TxProvider txProvider = new TxProvider(BitherApplication.mDbHelper); public static TxProvider getInstance() { return txProvider; } private SQLiteOpenHelper mDb; public TxProvider(SQLiteOpenHelper db) { this.mDb = db; } // public List<Tx> getTxByAddress(String address) { // List<Tx> txItemList = new ArrayList<Tx>(); // String sql = "select b.* from addresses_txs a, txs b where a.tx_hash=b.tx_hash and a.address='" + // address + "' order by b.block_no"; // SQLiteDatabase db = this.mDb.getReadableDatabase(); // Cursor c = db.rawQuery(sql, null); // try { // while (c.moveToNext()) { // txItemList.add(applyCursor(c)); // } // } catch (Exception e) { // e.printStackTrace(); // } // c.close(); // return txItemList; // } public List<Tx> getTxAndDetailByAddress(String address) { List<Tx> txItemList = new ArrayList<Tx>(); HashMap<Sha256Hash, Tx> txDict = new HashMap<Sha256Hash, Tx>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); try { String sql = "select b.* from addresses_txs a, txs b where a.tx_hash=b.tx_hash and a.address='" + address + "' order by b.block_no "; Cursor c = db.rawQuery(sql, null); while (c.moveToNext()) { Tx txItem = applyCursor(c); txItem.setIns(new ArrayList<In>()); txItem.setOuts(new ArrayList<Out>()); txItemList.add(txItem); txDict.put(new Sha256Hash(txItem.getTxHash()), txItem); } c.close(); sql = "select b.* from addresses_txs a, ins b where a.tx_hash=b.tx_hash and a.address=? " + "order by b.tx_hash ,b.in_sn"; c = db.rawQuery(sql, new String[]{address}); while (c.moveToNext()) { In inItem = applyCursorIn(c); Tx tx = txDict.get(new Sha256Hash(inItem.getTxHash())); if (tx != null) tx.getIns().add(inItem); } c.close(); sql = "select b.* from addresses_txs a, outs b where a.tx_hash=b.tx_hash and a.address=? " + "order by b.tx_hash,b.out_sn"; c = db.rawQuery(sql, new String[]{address}); while (c.moveToNext()) { Out out = applyCursorOut(c); Tx tx = txDict.get(new Sha256Hash(out.getTxHash())); if (tx != null) tx.getOuts().add(out); } c.close(); } catch (AddressFormatException e) { e.printStackTrace(); } return txItemList; } public List<Tx> getPublishedTxs() { List<Tx> txItemList = new ArrayList<Tx>(); HashMap<Sha256Hash, Tx> txDict = new HashMap<Sha256Hash, Tx>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select * from txs where block_no is null or block_no = ?"; try { Cursor c = db.rawQuery(sql, new String[]{Integer.toString(Tx.TX_UNCONFIRMED)}); while (c.moveToNext()) { Tx txItem = applyCursor(c); txItem.setIns(new ArrayList<In>()); txItem.setOuts(new ArrayList<Out>()); txItemList.add(txItem); txDict.put(new Sha256Hash(txItem.getTxHash()), txItem); } c.close(); sql = "select b.* from txs a, ins b where a.tx_hash=b.tx_hash and ( a.block_no is null or a.block_no = ? ) " + "order by b.tx_hash ,b.in_sn"; c = db.rawQuery(sql, new String[]{Integer.toString(Tx.TX_UNCONFIRMED)}); while (c.moveToNext()) { In inItem = applyCursorIn(c); Tx tx = txDict.get(new Sha256Hash(inItem.getTxHash())); tx.getIns().add(inItem); } c.close(); sql = "select b.* from txs a, outs b where a.tx_hash=b.tx_hash and ( a.block_no is null or a.block_no = ? ) " + "order by b.tx_hash,b.out_sn"; c = db.rawQuery(sql, new String[]{Integer.toString(Tx.TX_UNCONFIRMED)}); while (c.moveToNext()) { Out out = applyCursorOut(c); Tx tx = txDict.get(new Sha256Hash(out.getTxHash())); tx.getOuts().add(out); } c.close(); } catch (AddressFormatException e) { e.printStackTrace(); } finally { } return txItemList; } public Tx getTxDetailByTxHash(byte[] txHash) { Tx txItem = null; String txHashStr = Base58.encode(txHash); SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select * from txs where tx_hash='" + txHashStr + "'"; Cursor c = db.rawQuery(sql, null); try { if (c.moveToNext()) { txItem = applyCursor(c); } if (txItem != null) { addInsAndOuts(db, txItem); } } catch (AddressFormatException e) { e.printStackTrace(); } finally { c.close(); } return txItem; } private void addInsAndOuts(SQLiteDatabase db, Tx txItem) throws AddressFormatException { String txHashStr = Base58.encode(txItem.getTxHash()); txItem.setOuts(new ArrayList<Out>()); txItem.setIns(new ArrayList<In>()); String sql = "select * from ins where tx_hash='" + txHashStr + "' order by in_sn"; Cursor c = db.rawQuery(sql, null); while (c.moveToNext()) { In inItem = applyCursorIn(c); inItem.setTx(txItem); txItem.getIns().add(inItem); } c.close(); sql = "select * from outs where tx_hash='" + txHashStr + "' order by out_sn"; c = db.rawQuery(sql, null); while (c.moveToNext()) { Out outItem = applyCursorOut(c); outItem.setTx(txItem); txItem.getOuts().add(outItem); } c.close(); } public boolean isExist(byte[] txHash) { boolean result = false; SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select count(0) from txs where tx_hash='" + Base58.encode(txHash) + "'"; Cursor c = db.rawQuery(sql, null); if (c.moveToNext()) { result = c.getInt(0) > 0; } c.close(); return result; } public void add(Tx txItem) { SQLiteDatabase db = this.mDb.getWritableDatabase(); db.beginTransaction(); addTxToDb(db, txItem); db.setTransactionSuccessful(); db.endTransaction(); } public void addTxs(List<Tx> txItems) { SQLiteDatabase db = this.mDb.getReadableDatabase(); List<Tx> addTxItems = new ArrayList<Tx>(); String existSql = "select count(0) cnt from txs where tx_hash="; Cursor c; for (Tx txItem : txItems) { c = db.rawQuery(existSql + "'" + Base58.encode(txItem.getTxHash()) + "'", null); int cnt = 0; if (c.moveToNext()) { int idColumn = c.getColumnIndex("cnt"); if (idColumn != -1) { cnt = c.getInt(idColumn); } } if (cnt == 0) { addTxItems.add(txItem); } c.close(); } if (addTxItems.size() > 0) { db = this.mDb.getWritableDatabase(); db.beginTransaction(); for (Tx txItem : addTxItems) { //LogUtil.d("txDb", Base58.encode(txItem.getTxHash()) + "," + Utils.bytesToHexString(txItem.getTxHash())); addTxToDb(db, txItem); //List<Tx> txList = getTxAndDetailByAddress("1B5XuAJNTN2Upi7AXs7tJCxvFGjhPna6Q5"); } db.setTransactionSuccessful(); db.endTransaction(); } } private void addTxToDb(SQLiteDatabase db, Tx txItem) { ContentValues cv = new ContentValues(); applyContentValues(txItem, cv); db.insert(AbstractDb.Tables.TXS, null, cv); Cursor c; String sql; List<Object[]> addressesTxsRels = new ArrayList<Object[]>(); try { for (In inItem : txItem.getIns()) { sql = "select out_address from outs where tx_hash='" + Base58.encode(inItem.getPrevTxHash()) + "' and out_sn=" + inItem.getPrevOutSn(); c = db.rawQuery(sql, null); while (c.moveToNext()) { int idColumn = c.getColumnIndex("out_address"); if (idColumn != -1) { addressesTxsRels.add(new Object[]{c.getString(idColumn), txItem.getTxHash()}); } } c.close(); cv = new ContentValues(); applyContentValues(inItem, cv); db.insert(AbstractDb.Tables.INS, null, cv); sql = "update outs set out_status=" + Out.OutStatus.spent.getValue() + " where tx_hash='" + Base58.encode(inItem.getPrevTxHash()) + "' and out_sn=" + inItem.getPrevOutSn(); db.execSQL(sql); } for (Out outItem : txItem.getOuts()) { cv = new ContentValues(); applyContentValues(outItem, cv); db.insert(AbstractDb.Tables.OUTS, null, cv); if (!Utils.isEmpty(outItem.getOutAddress())) { addressesTxsRels.add(new Object[]{outItem.getOutAddress(), txItem.getTxHash()}); } sql = "select tx_hash from ins where prev_tx_hash='" + Base58.encode(txItem.getTxHash()) + "' and prev_out_sn=" + outItem.getOutSn(); c = db.rawQuery(sql, null); boolean isSpentByExistTx = false; if (c.moveToNext()) { int idColumn = c.getColumnIndex("tx_hash"); if (idColumn != -1) { addressesTxsRels.add(new Object[]{outItem.getOutAddress(), Base58.decode(c.getString(idColumn))}); } isSpentByExistTx = true; } c.close(); if (isSpentByExistTx) { sql = "update outs set out_status=" + Out.OutStatus.spent.getValue() + " where tx_hash='" + Base58.encode(txItem.getTxHash()) + "' and out_sn=" + outItem.getOutSn(); db.execSQL(sql); } } for (Object[] array : addressesTxsRels) { sql = "insert or ignore into addresses_txs(address, tx_hash) values('" + array[0] + "','" + Base58.encode((byte[]) array[1]) + "')"; db.execSQL(sql); } } catch (AddressFormatException e) { e.printStackTrace(); } } public void remove(byte[] txHash) { String txHashStr = Base58.encode(txHash); List<String> txHashes = new ArrayList<String>(); List<String> needRemoveTxHashes = new ArrayList<String>(); txHashes.add(txHashStr); while (txHashes.size() > 0) { String thisHash = txHashes.get(0); txHashes.remove(0); needRemoveTxHashes.add(thisHash); List<String> temp = getRelayTx(thisHash); txHashes.addAll(temp); } SQLiteDatabase db = this.mDb.getWritableDatabase(); db.beginTransaction(); for (String str : needRemoveTxHashes) { removeSingleTx(db, str); } db.setTransactionSuccessful(); db.endTransaction(); } private void removeSingleTx(SQLiteDatabase db, String tx) { String deleteTx = "delete from txs where tx_hash='" + tx + "'"; String deleteIn = "delete from ins where tx_hash='" + tx + "'"; String deleteOut = "delete from outs where tx_hash='" + tx + "'"; String deleteAddressesTx = "delete from addresses_txs where tx_hash='" + tx + "'"; String inSql = "select prev_tx_hash,prev_out_sn from ins where tx_hash='" + tx + "'"; String existOtherIn = "select count(0) cnt from ins where prev_tx_hash=? and prev_out_sn=?"; String updatePrevOut = "update outs set out_status=%d where tx_hash=%s and out_sn=%d"; Cursor c = db.rawQuery(inSql, new String[]{tx}); List<Object[]> needUpdateOuts = new ArrayList<Object[]>(); while (c.moveToNext()) { int idColumn = c.getColumnIndex(AbstractDb.InsColumns.PREV_TX_HASH); String prevTxHash = null; int prevOutSn = 0; if (idColumn != -1) { prevTxHash = c.getString(idColumn); } idColumn = c.getColumnIndex(AbstractDb.InsColumns.PREV_OUT_SN); if (idColumn != -1) { prevOutSn = c.getInt(idColumn); } needUpdateOuts.add(new Object[]{prevTxHash, prevOutSn}); } c.close(); db.execSQL(deleteAddressesTx); db.execSQL(deleteOut); db.execSQL(deleteIn); db.execSQL(deleteTx); for (Object[] array : needUpdateOuts) { c = db.rawQuery(existOtherIn, new String[]{array[0].toString(), array[1].toString()}); while (c.moveToNext()) { if (c.getInt(0) == 0) { String updateSql = Utils.format(updatePrevOut, Out.OutStatus.unspent.getValue(), array[0].toString(), Integer.valueOf(array[1].toString())); db.execSQL(updateSql); } } c.close(); } } private List<String> getRelayTx(String txHash) { List<String> relayTxHashes = new ArrayList<String>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); String relayTx = "select distinct tx_hash from ins where prev_tx_hash='" + txHash + "'"; Cursor c = db.rawQuery(relayTx, null); while (c.moveToNext()) { relayTxHashes.add(c.getString(0)); } c.close(); return relayTxHashes; } public boolean isAddressContainsTx(String address, Tx txItem) { boolean result = false; String sql = "select count(0) from ins a, txs b where a.tx_hash=b.tx_hash and" + " b.block_no is not null and a.prev_tx_hash=? and a.prev_out_sn=?"; SQLiteDatabase db = this.mDb.getReadableDatabase(); Cursor c; for (In inItem : txItem.getIns()) { c = db.rawQuery(sql, new String[]{Base58.encode(inItem.getPrevTxHash()), Integer.toString(inItem.getPrevOutSn())}); if (c.moveToNext()) { if (c.getInt(0) > 0) { c.close(); return false; } } c.close(); } sql = "select count(0) from addresses_txs where tx_hash=? and address=?"; c = db.rawQuery(sql, new String[]{ Base58.encode(txItem.getTxHash()), address }); int count = 0; if (c.moveToNext()) { count = c.getInt(0); } c.close(); if (count > 0) { return true; } sql = "select count(0) from outs where tx_hash=? and out_sn=? and out_address=?"; for (In inItem : txItem.getIns()) { c = db.rawQuery(sql, new String[]{Base58.encode(inItem.getPrevTxHash()) , Integer.toString(inItem.getPrevOutSn()), address}); count = 0; if (c.moveToNext()) { count = c.getInt(0); } c.close(); if (count > 0) { return true; } } return result; } public boolean isTxDoubleSpendWithConfirmedTx(Tx tx) { String sql = "select count(0) from ins a, txs b where a.tx_hash=b.tx_hash and" + " b.block_no is not null and a.prev_tx_hash=? and a.prev_out_sn=?"; SQLiteDatabase db = this.mDb.getReadableDatabase(); Cursor c; for (In inItem : tx.getIns()) { c = db.rawQuery(sql, new String[]{Base58.encode(inItem.getPrevTxHash()), Integer.toString(inItem.getPrevOutSn())}); if (c.moveToNext()) { if (c.getInt(0) > 0) { c.close(); return true; } } c.close(); } return false; } public List<String> getInAddresses(Tx tx) { List<String> result = new ArrayList<String>(); String sql = "select out_address from outs where tx_hash=? and out_sn=?"; SQLiteDatabase db = this.mDb.getReadableDatabase(); Cursor c; for (In inItem : tx.getIns()) { c = db.rawQuery(sql, new String[]{Base58.encode(inItem.getPrevTxHash()) , Integer.toString(inItem.getPrevOutSn())}); if (c.moveToNext()) { if (!c.isNull(0)) { result.add(c.getString(0)); } } c.close(); } return result; } public void confirmTx(int blockNo, List<byte[]> txHashes) { if (blockNo == Tx.TX_UNCONFIRMED || txHashes == null) { return; } String sql = "update txs set block_no=%d where tx_hash='%s'"; String existSql = "select count(0) from txs where block_no=? and tx_hash=?"; String doubleSpendSql = "select a.tx_hash from ins a, ins b where a.prev_tx_hash=b.prev_tx_hash " + "and a.prev_out_sn=b.prev_out_sn and a.tx_hash<>b.tx_hash and b.tx_hash=?"; String blockTimeSql = "select block_time from blocks where block_no=?"; String updateTxTimeThatMoreThanBlockTime = "update txs set tx_time=%d where block_no=%d and tx_time>%d"; SQLiteDatabase db = this.mDb.getWritableDatabase(); db.beginTransaction(); Cursor c; for (byte[] txHash : txHashes) { c = db.rawQuery(existSql, new String[]{Integer.toString(blockNo), Base58.encode(txHash)}); if (c.moveToNext()) { int cnt = c.getInt(0); c.close(); if (cnt > 0) { continue; } } else { c.close(); } String updateSql = Utils.format(sql, blockNo, Base58.encode(txHash)); db.execSQL(updateSql); c = db.rawQuery(doubleSpendSql, new String[]{Base58.encode(txHash)}); List<String> txHashes1 = new ArrayList<String>(); while (c.moveToNext()) { int idColumn = c.getColumnIndex("tx_hash"); if (idColumn != -1) { txHashes1.add(c.getString(idColumn)); } } c.close(); List<String> needRemoveTxHashes = new ArrayList<String>(); while (txHashes1.size() > 0) { String thisHash = txHashes1.get(0); txHashes1.remove(0); needRemoveTxHashes.add(thisHash); List<String> temp = getRelayTx(thisHash); txHashes1.addAll(temp); } for (String each : needRemoveTxHashes) { removeSingleTx(db, each); } } c = db.rawQuery(blockTimeSql, new String[]{Integer.toString(blockNo)}); if (c.moveToNext()) { int idColumn = c.getColumnIndex("block_time"); if (idColumn != -1) { int blockTime = c.getInt(idColumn); c.close(); String sqlTemp = Utils.format(updateTxTimeThatMoreThanBlockTime, blockTime, blockNo, blockTime); db.execSQL(sqlTemp); } } else { c.close(); } db.setTransactionSuccessful(); db.endTransaction(); } public void unConfirmTxByBlockNo(int blockNo) { SQLiteDatabase db = this.mDb.getWritableDatabase(); String sql = "update txs set block_no=null where block_no>=" + blockNo; db.execSQL(sql); } public List<Tx> getUnspendTxWithAddress(String address) { String unspendOutSql = "select a.*,b.tx_ver,b.tx_locktime,b.tx_time,b.block_no,b.source,ifnull(b.block_no,0)*a.out_value coin_depth " + "from outs a,txs b where a.tx_hash=b.tx_hash" + " and a.out_address=? and a.out_status=?"; List<Tx> txItemList = new ArrayList<Tx>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); Cursor c = db.rawQuery(unspendOutSql, new String[]{address, Integer.toString(Out.OutStatus.unspent.getValue())}); try { while (c.moveToNext()) { int idColumn = c.getColumnIndex("coin_depth"); Tx txItem = applyCursor(c); Out outItem = applyCursorOut(c); if (idColumn != -1) { outItem.setCoinDepth(c.getLong(idColumn)); } outItem.setTx(txItem); txItem.setOuts(new ArrayList<Out>()); txItem.getOuts().add(outItem); txItemList.add(txItem); } c.close(); } catch (AddressFormatException e) { e.printStackTrace(); } return txItemList; } public List<Out> getUnspendOutWithAddress(String address) { List<Out> outItems = new ArrayList<Out>(); String unspendOutSql = "select a.* from outs a,txs b where a.tx_hash=b.tx_hash " + "and b.block_no is null and a.out_address=? and a.out_status=?"; SQLiteDatabase db = this.mDb.getReadableDatabase(); Cursor c = db.rawQuery(unspendOutSql, new String[]{address, Integer.toString(Out.OutStatus.unspent.getValue())}); try { while (c.moveToNext()) { outItems.add(applyCursorOut(c)); } c.close(); } catch (AddressFormatException e) { e.printStackTrace(); } return outItems; } public List<Out> getUnSpendOutCanSpendWithAddress(String address) { List<Out> outItems = new ArrayList<Out>(); String confirmedOutSql = "select a.*,b.block_no*a.out_value coin_depth from outs a,txs b" + " where a.tx_hash=b.tx_hash and b.block_no is not null and a.out_address=? and a.out_status=?"; String selfOutSql = "select a.* from outs a,txs b where a.tx_hash=b.tx_hash and b.block_no" + " is null and a.out_address=? and a.out_status=? and b.source>=?"; SQLiteDatabase db = this.mDb.getReadableDatabase(); Cursor c = db.rawQuery(confirmedOutSql, new String[]{address, Integer.toString(Out.OutStatus.unspent.getValue())}); try { while (c.moveToNext()) { Out outItem = applyCursorOut(c); int idColumn = c.getColumnIndex("coin_depth"); if (idColumn != -1) { outItem.setCoinDepth(c.getLong(idColumn)); } outItems.add(outItem); } c.close(); c = db.rawQuery(selfOutSql, new String[]{address, Integer.toString(Out.OutStatus.unspent.getValue()), "1"}); while (c.moveToNext()) { outItems.add(applyCursorOut(c)); } c.close(); } catch (AddressFormatException e) { e.printStackTrace(); } return outItems; } public List<Out> getUnSpendOutButNotConfirmWithAddress(String address) { List<Out> outItems = new ArrayList<Out>(); String selfOutSql = "select a.* from outs a,txs b where a.tx_hash=b.tx_hash and b.block_no" + " is null and a.out_address=? and a.out_status=? and b.source=?"; SQLiteDatabase db = this.mDb.getReadableDatabase(); Cursor c = db.rawQuery(selfOutSql, new String[]{address, Integer.toString(Out.OutStatus.unspent.getValue()), "0"}); try { while (c.moveToNext()) { outItems.add(applyCursorOut(c)); } } catch (AddressFormatException e) { e.printStackTrace(); } finally { c.close(); } return outItems; } public int txCount(String address) { int result = 0; SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select count(*) from addresses_txs where address='" + address + "'"; Cursor c = db.rawQuery(sql, null); if (c.moveToNext()) { result = c.getInt(0); } c.close(); return result; } public void txSentBySelfHasSaw(byte[] txHash) { SQLiteDatabase db = this.mDb.getWritableDatabase(); String sql = "update txs set source=source+1 where tx_hash='" + Base58.encode(txHash) + "' and source>=1"; db.execSQL(sql); } public List<Out> getOuts() { List<Out> outItemList = new ArrayList<Out>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select * from outs "; Cursor c = db.rawQuery(sql, null); try { while (c.moveToNext()) { outItemList.add(applyCursorOut(c)); } } catch (AddressFormatException e) { e.printStackTrace(); } finally { c.close(); } return outItemList; } public List<Out> getUnSpentOuts() { List<Out> outItemList = new ArrayList<Out>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select * from outs where out_status=?"; Cursor c = db.rawQuery(sql, new String[]{"0"}); try { while (c.moveToNext()) { outItemList.add(applyCursorOut(c)); } } catch (AddressFormatException e) { e.printStackTrace(); } finally { c.close(); } return outItemList; } public List<In> getRelatedIn(String address){ List<In> list = new ArrayList<In>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select ins.* from ins,addresses_txs " + "where ins.tx_hash=addresses_txs.tx_hash and addresses_txs.address=? "; Cursor c = db.rawQuery(sql, new String[] {address}); try { while (c.moveToNext()) { list.add(applyCursorIn(c)); } } catch (AddressFormatException e) { e.printStackTrace(); } finally { c.close(); } return list; } public List<Tx> getRecentlyTxsByAddress(String address, int greateThanBlockNo, int limit) { List<Tx> txItemList = new ArrayList<Tx>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select b.* from addresses_txs a, txs b where a.tx_hash=b.tx_hash and a.address='%s' " + "and ((b.block_no is null) or (b.block_no is not null and b.block_no>%d)) " + "order by ifnull(b.block_no,4294967295) desc, b.tx_time desc " + "limit %d "; sql = Utils.format(sql, address, greateThanBlockNo, limit); Cursor c = db.rawQuery(sql, null); try { while (c.moveToNext()) { Tx txItem = applyCursor(c); txItemList.add(txItem); } for (Tx item : txItemList) { addInsAndOuts(db, item); } } catch (AddressFormatException e) { e.printStackTrace(); } finally { c.close(); } return txItemList; } public List<Long> txInValues(byte[] txHash) { List<Long> inValues = new ArrayList<Long>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select b.out_value " + "from ins a left outer join outs b on a.prev_tx_hash=b.tx_hash and a.prev_out_sn=b.out_sn " + "where a.tx_hash='" + Base58.encode(txHash) + "'"; Cursor c = db.rawQuery(sql, null); while (c.moveToNext()) { int idColumn = c.getColumnIndex("out_value"); if (idColumn != -1) { inValues.add(c.getLong(idColumn)); } else { inValues.add(null); } } c.close(); return inValues; } public HashMap<Sha256Hash, Tx> getTxDependencies(Tx txItem) { HashMap<Sha256Hash, Tx> result = new HashMap<Sha256Hash, Tx>(); SQLiteDatabase db = this.mDb.getReadableDatabase(); try { for (In inItem : txItem.getIns()) { Tx tx; String txHashStr = Base58.encode(inItem.getTxHash()); String sql = "select * from txs where tx_hash='" + txHashStr + "'"; Cursor c = db.rawQuery(sql, null); if (c.moveToNext()) { tx = applyCursor(c); c.close(); } else { c.close(); continue; } addInsAndOuts(db, tx); result.put(new Sha256Hash(tx.getTxHash()), tx); } } catch (AddressFormatException e) { e.printStackTrace(); } return result; } public void clearAllTx() { SQLiteDatabase db = this.mDb.getWritableDatabase(); db.beginTransaction(); db.delete(AbstractDb.Tables.TXS, "", new String[0]); db.delete(AbstractDb.Tables.OUTS, "", new String[0]); db.delete(AbstractDb.Tables.INS, "", new String[0]); db.delete(AbstractDb.Tables.ADDRESSES_TXS, "", new String[0]); db.setTransactionSuccessful(); db.endTransaction(); } public void completeInSignature(List<In> ins) { SQLiteDatabase db = this.mDb.getWritableDatabase(); db.beginTransaction(); String sql = "update ins set in_signature=? where tx_hash=? and in_sn=? and in_signature is null"; for (In in : ins) { db.execSQL(sql, new String[]{Base58.encode(in.getInSignature()) , Base58.encode(in.getTxHash()), Integer.toString(in.getInSn())}); } db.setTransactionSuccessful(); db.endTransaction(); } public int needCompleteInSignature(String address) { int result = 0; SQLiteDatabase db = this.mDb.getReadableDatabase(); String sql = "select max(txs.block_no) from outs,ins,txs where outs.out_address=? " + "and ins.prev_tx_hash=outs.tx_hash and ins.prev_out_sn=outs.out_sn " + "and ins.in_signature is null and txs.tx_hash=ins.tx_hash"; // String sql = "select max(txs.block_no) from addresses_txs,ins,txs " + // "where addresses_txs.tx_hash=ins.tx_hash and addresses_txs.address=? " + // "and ins.in_signature is null and txs.tx_hash=ins.tx_hash"; Cursor c = db.rawQuery(sql, new String[] {address}); if (c.moveToNext()) { result = c.getInt(0); } c.close(); return result; } private void applyContentValues(Tx txItem, ContentValues cv) { if (txItem.getBlockNo() != Tx.TX_UNCONFIRMED) { cv.put(AbstractDb.TxsColumns.BLOCK_NO, txItem.getBlockNo()); } cv.put(AbstractDb.TxsColumns.TX_HASH, Base58.encode(txItem.getTxHash())); cv.put(AbstractDb.TxsColumns.SOURCE, txItem.getSource()); cv.put(AbstractDb.TxsColumns.TX_TIME, txItem.getTxTime()); cv.put(AbstractDb.TxsColumns.TX_VER, txItem.getTxVer()); cv.put(AbstractDb.TxsColumns.TX_LOCKTIME, txItem.getTxLockTime()); } private void applyContentValues(In inItem, ContentValues cv) { cv.put(AbstractDb.InsColumns.TX_HASH, Base58.encode(inItem.getTxHash())); cv.put(AbstractDb.InsColumns.IN_SN, inItem.getInSn()); cv.put(AbstractDb.InsColumns.PREV_TX_HASH, Base58.encode(inItem.getPrevTxHash())); cv.put(AbstractDb.InsColumns.PREV_OUT_SN, inItem.getPrevOutSn()); if (inItem.getInSignature() != null) { cv.put(AbstractDb.InsColumns.IN_SIGNATURE, Base58.encode(inItem.getInSignature())); } cv.put(AbstractDb.InsColumns.IN_SEQUENCE, inItem.getInSequence()); } private void applyContentValues(Out outItem, ContentValues cv) { cv.put(AbstractDb.OutsColumns.TX_HASH, Base58.encode(outItem.getTxHash())); cv.put(AbstractDb.OutsColumns.OUT_SN, outItem.getOutSn()); cv.put(AbstractDb.OutsColumns.OUT_SCRIPT, Base58.encode(outItem.getOutScript())); cv.put(AbstractDb.OutsColumns.OUT_VALUE, outItem.getOutValue()); cv.put(AbstractDb.OutsColumns.OUT_STATUS, outItem.getOutStatus().getValue()); if (!Utils.isEmpty(outItem.getOutAddress())) { cv.put(AbstractDb.OutsColumns.OUT_ADDRESS, outItem.getOutAddress()); } } private Tx applyCursor(Cursor c) throws AddressFormatException { Tx txItem = new Tx(); int idColumn = c.getColumnIndex(AbstractDb.TxsColumns.BLOCK_NO); if (!c.isNull(idColumn)) { txItem.setBlockNo(c.getInt(idColumn)); } else { txItem.setBlockNo(Tx.TX_UNCONFIRMED); } idColumn = c.getColumnIndex(AbstractDb.TxsColumns.TX_HASH); if (idColumn != -1) { txItem.setTxHash(Base58.decode(c.getString(idColumn))); } idColumn = c.getColumnIndex(AbstractDb.TxsColumns.SOURCE); if (idColumn != -1) { txItem.setSource(c.getInt(idColumn)); } if (txItem.getSource() >= 1) { txItem.setSawByPeerCnt(txItem.getSource() - 1); txItem.setSource(1); } else { txItem.setSawByPeerCnt(0); txItem.setSource(0); } idColumn = c.getColumnIndex(AbstractDb.TxsColumns.TX_TIME); if (idColumn != -1) { txItem.setTxTime(c.getInt(idColumn)); } idColumn = c.getColumnIndex(AbstractDb.TxsColumns.TX_VER); if (idColumn != -1) { txItem.setTxVer(c.getInt(idColumn)); } idColumn = c.getColumnIndex(AbstractDb.TxsColumns.TX_LOCKTIME); if (idColumn != -1) { txItem.setTxLockTime(c.getInt(idColumn)); } return txItem; } private In applyCursorIn(Cursor c) throws AddressFormatException { In inItem = new In(); int idColumn = c.getColumnIndex(AbstractDb.InsColumns.TX_HASH); if (idColumn != -1) { inItem.setTxHash(Base58.decode(c.getString(idColumn))); } idColumn = c.getColumnIndex(AbstractDb.InsColumns.IN_SN); if (idColumn != -1) { inItem.setInSn(c.getInt(idColumn)); } idColumn = c.getColumnIndex(AbstractDb.InsColumns.PREV_TX_HASH); if (idColumn != -1) { inItem.setPrevTxHash(Base58.decode(c.getString(idColumn))); } idColumn = c.getColumnIndex(AbstractDb.InsColumns.PREV_OUT_SN); if (idColumn != -1) { inItem.setPrevOutSn(c.getInt(idColumn)); } idColumn = c.getColumnIndex(AbstractDb.InsColumns.IN_SIGNATURE); if (idColumn != -1) { String inSignature = c.getString(idColumn); if (!Utils.isEmpty(inSignature)) { inItem.setInSignature(Base58.decode(c.getString(idColumn))); } } idColumn = c.getColumnIndex(AbstractDb.InsColumns.IN_SEQUENCE); if (idColumn != -1) { inItem.setInSequence(c.getInt(idColumn)); } return inItem; } private Out applyCursorOut(Cursor c) throws AddressFormatException { Out outItem = new Out(); int idColumn = c.getColumnIndex(AbstractDb.OutsColumns.TX_HASH); if (idColumn != -1) { outItem.setTxHash(Base58.decode(c.getString(idColumn))); } idColumn = c.getColumnIndex(AbstractDb.OutsColumns.OUT_SN); if (idColumn != -1) { outItem.setOutSn(c.getInt(idColumn)); } idColumn = c.getColumnIndex(AbstractDb.OutsColumns.OUT_SCRIPT); if (idColumn != -1) { outItem.setOutScript(Base58.decode(c.getString(idColumn))); } idColumn = c.getColumnIndex(AbstractDb.OutsColumns.OUT_VALUE); if (idColumn != -1) { outItem.setOutValue(c.getLong(idColumn)); } idColumn = c.getColumnIndex(AbstractDb.OutsColumns.OUT_STATUS); if (idColumn != -1) { outItem.setOutStatus(Out.getOutStatus(c.getInt(idColumn))); } idColumn = c.getColumnIndex(AbstractDb.OutsColumns.OUT_ADDRESS); if (idColumn != -1) { outItem.setOutAddress(c.getString(idColumn)); } return outItem; } }
check r
bither-android/src/net/bither/db/TxProvider.java
check r
<ide><path>ither-android/src/net/bither/db/TxProvider.java <ide> SQLiteDatabase db = this.mDb.getReadableDatabase(); <ide> String sql = "select max(txs.block_no) from outs,ins,txs where outs.out_address=? " + <ide> "and ins.prev_tx_hash=outs.tx_hash and ins.prev_out_sn=outs.out_sn " + <del> "and ins.in_signature is null and txs.tx_hash=ins.tx_hash"; <add> "and ifnull(ins.in_signature,'')='' and txs.tx_hash=ins.tx_hash"; <ide> // String sql = "select max(txs.block_no) from addresses_txs,ins,txs " + <ide> // "where addresses_txs.tx_hash=ins.tx_hash and addresses_txs.address=? " + <ide> // "and ins.in_signature is null and txs.tx_hash=ins.tx_hash";
Java
apache-2.0
bd56eea49a9c6a84ce194ba3f2a186a47e7d50bc
0
apache/tomcat,apache/tomcat,apache/tomcat,apache/tomcat,Nickname0806/Test_Q4,Nickname0806/Test_Q4,Nickname0806/Test_Q4,apache/tomcat,Nickname0806/Test_Q4
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.webresources; import java.net.URL; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class TomcatURLStreamHandlerFactory implements URLStreamHandlerFactory { private static final String WAR_PROTOCOL = "war"; // Singleton instance private static volatile TomcatURLStreamHandlerFactory instance = null; /** * Obtain a reference to the singleton instance. It is recommended that * callers check the value of {@link #isRegistered()} before using the * returned instance. */ public static TomcatURLStreamHandlerFactory getInstance() { getInstanceInternal(true); return instance; } private static TomcatURLStreamHandlerFactory getInstanceInternal(boolean register) { // Double checked locking. OK because instance is volatile. if (instance == null) { synchronized (TomcatURLStreamHandlerFactory.class) { if (instance == null) { instance = new TomcatURLStreamHandlerFactory(register); } } } return instance; } private final boolean registered; // List of factories for application defined stream handler factories. private List<URLStreamHandlerFactory> userFactories = new CopyOnWriteArrayList<>(); /** * Register this factory with the JVM. May be called more than once. The * implementation ensures that registration only occurs once. * * @returns <code>true</code> if the factory is already registered with the * JVM or was successfully registered as a result of this call. * <code>false</code> if the factory was disabled prior to this * call. */ public static boolean register() { return getInstanceInternal(true).isRegistered(); } /** * Prevent this this factory from registering with the JVM. May be called * more than once. * * @returns <code>true</code> if the factory is already disabled or was * successfully disabled as a result of this call. * <code>false</code> if the factory was already registered prior * to this call. */ public static boolean disable() { return !getInstanceInternal(false).isRegistered(); } /** * Release references to any user provided factories that have been loaded * using the provided class loader. Called during web application stop to * prevent memory leaks. */ public static void release(ClassLoader classLoader) { Iterator<URLStreamHandlerFactory> iter = instance.userFactories.iterator(); while (iter.hasNext()) { ClassLoader factoryLoader = iter.next().getClass().getClassLoader(); while (factoryLoader != null) { if (classLoader.equals(factoryLoader)) { iter.remove(); break; } factoryLoader = factoryLoader.getParent(); } } } private TomcatURLStreamHandlerFactory(boolean register) { // Hide default constructor // Singleton pattern to ensure there is only one instance of this // factory this.registered = register; if (register) { URL.setURLStreamHandlerFactory(this); } } public boolean isRegistered() { return registered; } /** * Since the JVM only allows a single call to * {@link URL#setURLStreamHandlerFactory(URLStreamHandlerFactory)} and * Tomcat needs to register a handler, provide a mechanism to allow * applications to register their own handlers. */ public void addUserFactory(URLStreamHandlerFactory factory) { userFactories.add(factory); } @Override public URLStreamHandler createURLStreamHandler(String protocol) { // Tomcat's handler always takes priority so applications can't override // it. if (WAR_PROTOCOL.equals(protocol)) { return new WarURLStreamHandler(); } // Application handlers for (URLStreamHandlerFactory factory : userFactories) { URLStreamHandler handler = factory.createURLStreamHandler(protocol); if (handler != null) { return handler; } } // Unknown protocol return null; } }
java/org/apache/catalina/webresources/TomcatURLStreamHandlerFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.webresources; import java.net.URL; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; // TODO Add hook to enable user registered factories to be unloaded on web // application stop. public class TomcatURLStreamHandlerFactory implements URLStreamHandlerFactory{ private static final String WAR_PROTOCOL = "war"; // Singleton instance private static TomcatURLStreamHandlerFactory instance = new TomcatURLStreamHandlerFactory(); /** * Obtain a reference to the singleton instance, */ public static TomcatURLStreamHandlerFactory getInstance() { return instance; } // List of factories for application defined stream handler factories. private List<URLStreamHandlerFactory> userFactories = new CopyOnWriteArrayList<>(); /** * Register this factory with the JVM. May be called more than once. The * implementation ensures that registration only occurs once. */ public static void register() { // Calling this method loads this class which in turn triggers all the // necessary registration. } /** * Since the JVM only allows a single call to * {@link URL#setURLStreamHandlerFactory(URLStreamHandlerFactory)} and * Tomcat needs to register a handler, provide a mechanism to allow * applications to register their own handlers. */ public static void addUserFactory(URLStreamHandlerFactory factory) { instance.userFactories.add(factory); } /** * Release references to any user provided factories that have been loaded * using the provided class loader. Called during web application stop to * prevent memory leaks. */ public static void release(ClassLoader classLoader) { Iterator<URLStreamHandlerFactory> iter = instance.userFactories.iterator(); while (iter.hasNext()) { ClassLoader factoryLoader = iter.next().getClass().getClassLoader(); while (factoryLoader != null) { if (classLoader.equals(factoryLoader)) { iter.remove(); break; } factoryLoader = factoryLoader.getParent(); } } } private TomcatURLStreamHandlerFactory() { // Hide default constructor // Singleton pattern to ensure there is only one instance of this // factory URL.setURLStreamHandlerFactory(this); } @Override public URLStreamHandler createURLStreamHandler(String protocol) { // Tomcat's handler always takes priority so applications can't override // it. if (WAR_PROTOCOL.equals(protocol)) { return new WarURLStreamHandler(); } // Application handlers for (URLStreamHandlerFactory factory : userFactories) { URLStreamHandler handler = factory.createURLStreamHandler(protocol); if (handler != null) { return handler; } } // Unknown protocol return null; } }
Fix https://issues.apache.org/bugzilla/show_bug.cgi?id=55630 Provide a way to disable the custom URLStreamHandlerFactory git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1530025 13f79535-47bb-0310-9956-ffa450edef68
java/org/apache/catalina/webresources/TomcatURLStreamHandlerFactory.java
Fix https://issues.apache.org/bugzilla/show_bug.cgi?id=55630 Provide a way to disable the custom URLStreamHandlerFactory
<ide><path>ava/org/apache/catalina/webresources/TomcatURLStreamHandlerFactory.java <ide> import java.util.List; <ide> import java.util.concurrent.CopyOnWriteArrayList; <ide> <del>// TODO Add hook to enable user registered factories to be unloaded on web <del>// application stop. <del>public class TomcatURLStreamHandlerFactory implements URLStreamHandlerFactory{ <add>public class TomcatURLStreamHandlerFactory implements URLStreamHandlerFactory { <ide> <ide> private static final String WAR_PROTOCOL = "war"; <ide> <ide> // Singleton instance <del> private static TomcatURLStreamHandlerFactory instance = <del> new TomcatURLStreamHandlerFactory(); <add> private static volatile TomcatURLStreamHandlerFactory instance = null; <ide> <ide> /** <del> * Obtain a reference to the singleton instance, <add> * Obtain a reference to the singleton instance. It is recommended that <add> * callers check the value of {@link #isRegistered()} before using the <add> * returned instance. <ide> */ <ide> public static TomcatURLStreamHandlerFactory getInstance() { <add> getInstanceInternal(true); <ide> return instance; <ide> } <ide> <add> <add> private static TomcatURLStreamHandlerFactory getInstanceInternal(boolean register) { <add> // Double checked locking. OK because instance is volatile. <add> if (instance == null) { <add> synchronized (TomcatURLStreamHandlerFactory.class) { <add> if (instance == null) { <add> instance = new TomcatURLStreamHandlerFactory(register); <add> } <add> } <add> } <add> return instance; <add> } <add> <add> <add> private final boolean registered; <ide> <ide> // List of factories for application defined stream handler factories. <ide> private List<URLStreamHandlerFactory> userFactories = <ide> new CopyOnWriteArrayList<>(); <ide> <del> <ide> /** <ide> * Register this factory with the JVM. May be called more than once. The <ide> * implementation ensures that registration only occurs once. <add> * <add> * @returns <code>true</code> if the factory is already registered with the <add> * JVM or was successfully registered as a result of this call. <add> * <code>false</code> if the factory was disabled prior to this <add> * call. <ide> */ <del> public static void register() { <del> // Calling this method loads this class which in turn triggers all the <del> // necessary registration. <add> public static boolean register() { <add> return getInstanceInternal(true).isRegistered(); <ide> } <ide> <ide> <ide> /** <del> * Since the JVM only allows a single call to <del> * {@link URL#setURLStreamHandlerFactory(URLStreamHandlerFactory)} and <del> * Tomcat needs to register a handler, provide a mechanism to allow <del> * applications to register their own handlers. <add> * Prevent this this factory from registering with the JVM. May be called <add> * more than once. <add> * <add> * @returns <code>true</code> if the factory is already disabled or was <add> * successfully disabled as a result of this call. <add> * <code>false</code> if the factory was already registered prior <add> * to this call. <add> <ide> */ <del> public static void addUserFactory(URLStreamHandlerFactory factory) { <del> instance.userFactories.add(factory); <add> public static boolean disable() { <add> return !getInstanceInternal(false).isRegistered(); <ide> } <ide> <ide> <ide> } <ide> <ide> <del> private TomcatURLStreamHandlerFactory() { <add> private TomcatURLStreamHandlerFactory(boolean register) { <ide> // Hide default constructor <ide> // Singleton pattern to ensure there is only one instance of this <ide> // factory <del> URL.setURLStreamHandlerFactory(this); <add> this.registered = register; <add> if (register) { <add> URL.setURLStreamHandlerFactory(this); <add> } <add> } <add> <add> <add> public boolean isRegistered() { <add> return registered; <add> } <add> <add> <add> /** <add> * Since the JVM only allows a single call to <add> * {@link URL#setURLStreamHandlerFactory(URLStreamHandlerFactory)} and <add> * Tomcat needs to register a handler, provide a mechanism to allow <add> * applications to register their own handlers. <add> */ <add> public void addUserFactory(URLStreamHandlerFactory factory) { <add> userFactories.add(factory); <ide> } <ide> <ide>
Java
apache-2.0
14b8957713b05974caaf527bceb5de534871a256
0
chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.jms.BytesMessage; import javax.jms.Connection; import javax.jms.DeliveryMode; import javax.jms.InvalidDestinationException; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TemporaryQueue; import javax.jms.TextMessage; import junit.framework.TestCase; /** * @version */ public class JmsTempDestinationTest extends TestCase { private Connection connection; private ActiveMQConnectionFactory factory; protected List<Connection> connections = Collections.synchronizedList(new ArrayList<Connection>()); protected void setUp() throws Exception { factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); factory.setUseAsyncSend(false); connection = factory.createConnection(); connections.add(connection); } /** * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { for (Iterator iter = connections.iterator(); iter.hasNext();) { Connection conn = (Connection)iter.next(); try { conn.close(); } catch (Throwable e) { } iter.remove(); } } /** * Make sure Temp destination can only be consumed by local connection * * @throws JMSException */ public void testTempDestOnlyConsumedByLocalConn() throws JMSException { connection.start(); Session tempSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue queue = tempSession.createTemporaryQueue(); MessageProducer producer = tempSession.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); TextMessage message = tempSession.createTextMessage("First"); producer.send(message); // temp destination should not be consume when using another connection Connection otherConnection = factory.createConnection(); connections.add(otherConnection); Session otherSession = otherConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue otherQueue = otherSession.createTemporaryQueue(); MessageConsumer consumer = otherSession.createConsumer(otherQueue); Message msg = consumer.receive(3000); assertNull(msg); // should throw InvalidDestinationException when consuming a temp // destination from another connection try { consumer = otherSession.createConsumer(queue); fail("Send should fail since temp destination should be used from another connection"); } catch (InvalidDestinationException e) { assertTrue("failed to throw an exception", true); } // should be able to consume temp destination from the same connection consumer = tempSession.createConsumer(queue); msg = consumer.receive(3000); assertNotNull(msg); } /** * Make sure that a temp queue does not drop message if there is an active * consumers. * * @throws JMSException */ public void testTempQueueHoldsMessagesWithConsumers() throws JMSException { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createTemporaryQueue(); MessageConsumer consumer = session.createConsumer(queue); connection.start(); MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); TextMessage message = session.createTextMessage("Hello"); producer.send(message); Message message2 = consumer.receive(1000); assertNotNull(message2); assertTrue("Expected message to be a TextMessage", message2 instanceof TextMessage); assertTrue("Expected message to be a '" + message.getText() + "'", ((TextMessage)message2).getText().equals(message.getText())); } /** * Make sure that a temp queue does not drop message if there are no active * consumers. * * @throws JMSException */ public void testTempQueueHoldsMessagesWithoutConsumers() throws JMSException { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createTemporaryQueue(); MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); TextMessage message = session.createTextMessage("Hello"); producer.send(message); connection.start(); MessageConsumer consumer = session.createConsumer(queue); Message message2 = consumer.receive(3000); assertNotNull(message2); assertTrue("Expected message to be a TextMessage", message2 instanceof TextMessage); assertTrue("Expected message to be a '" + message.getText() + "'", ((TextMessage)message2).getText().equals(message.getText())); } /** * Test temp queue works under load * * @throws JMSException */ public void testTmpQueueWorksUnderLoad() throws JMSException { int count = 500; int dataSize = 1024; ArrayList list = new ArrayList(count); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createTemporaryQueue(); MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); byte[] data = new byte[dataSize]; for (int i = 0; i < count; i++) { BytesMessage message = session.createBytesMessage(); message.writeBytes(data); message.setIntProperty("c", i); producer.send(message); list.add(message); } connection.start(); MessageConsumer consumer = session.createConsumer(queue); for (int i = 0; i < count; i++) { Message message2 = consumer.receive(2000); assertTrue(message2 != null); assertEquals(i, message2.getIntProperty("c")); assertTrue(message2.equals(list.get(i))); } } /** * Make sure you cannot publish to a temp destination that does not exist * anymore. * * @throws JMSException * @throws InterruptedException * @throws URISyntaxException */ public void testPublishFailsForClosedConnection() throws JMSException, InterruptedException, URISyntaxException { Connection tempConnection = factory.createConnection(); connections.add(tempConnection); Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue queue = tempSession.createTemporaryQueue(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); connection.start(); // This message delivery should work since the temp connection is still // open. MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); TextMessage message = session.createTextMessage("First"); producer.send(message); // Closing the connection should destroy the temp queue that was // created. tempConnection.close(); Thread.sleep(2000); // Wait a little bit to let the delete take effect. // This message delivery NOT should work since the temp connection is // now closed. try { message = session.createTextMessage("Hello"); producer.send(message); fail("Send should fail since temp destination should not exist anymore."); } catch (JMSException e) { } } /** * Make sure you cannot publish to a temp destination that does not exist * anymore. * * @throws JMSException * @throws InterruptedException */ public void testPublishFailsForDestoryedTempDestination() throws JMSException, InterruptedException { Connection tempConnection = factory.createConnection(); connections.add(tempConnection); Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue queue = tempSession.createTemporaryQueue(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); connection.start(); // This message delivery should work since the temp connection is still // open. MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); TextMessage message = session.createTextMessage("First"); producer.send(message); // deleting the Queue will cause sends to fail queue.delete(); Thread.sleep(1000); // Wait a little bit to let the delete take effect. // This message delivery NOT should work since the temp connection is // now closed. try { message = session.createTextMessage("Hello"); producer.send(message); fail("Send should fail since temp destination should not exist anymore."); } catch (JMSException e) { assertTrue("failed to throw an exception", true); } } /** * Test you can't delete a Destination with Active Subscribers * * @throws JMSException */ public void testDeleteDestinationWithSubscribersFails() throws JMSException { Connection connection = factory.createConnection(); connections.add(connection); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue queue = session.createTemporaryQueue(); connection.start(); session.createConsumer(queue); // This message delivery should NOT work since the temp connection is // now closed. try { queue.delete(); fail("Should fail as Subscribers are active"); } catch (JMSException e) { assertTrue("failed to throw an exception", true); } } }
activemq-core/src/test/java/org/apache/activemq/JmsTempDestinationTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq; import java.util.ArrayList; import javax.jms.BytesMessage; import javax.jms.Connection; import javax.jms.DeliveryMode; import javax.jms.InvalidDestinationException; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TemporaryQueue; import javax.jms.TextMessage; import junit.framework.TestCase; /** * @version */ public class JmsTempDestinationTest extends TestCase { private Connection connection; private ActiveMQConnectionFactory factory; protected void setUp() throws Exception { factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); factory.setUseAsyncSend(false); connection = factory.createConnection(); } /** * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { if (connection != null) { connection.close(); connection = null; } } /** * Make sure Temp destination can only be consumed by local connection * * @throws JMSException */ public void testTempDestOnlyConsumedByLocalConn() throws JMSException { connection.start(); Session tempSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue queue = tempSession.createTemporaryQueue(); MessageProducer producer = tempSession.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); TextMessage message = tempSession.createTextMessage("First"); producer.send(message); // temp destination should not be consume when using another connection Connection otherConnection = factory.createConnection(); Session otherSession = otherConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue otherQueue = otherSession.createTemporaryQueue(); MessageConsumer consumer = otherSession.createConsumer(otherQueue); Message msg = consumer.receive(3000); assertNull(msg); // should throw InvalidDestinationException when consuming a temp // destination from another connection try { consumer = otherSession.createConsumer(queue); fail("Send should fail since temp destination should be used from another connection"); } catch (InvalidDestinationException e) { assertTrue("failed to throw an exception", true); } // should be able to consume temp destination from the same connection consumer = tempSession.createConsumer(queue); msg = consumer.receive(3000); assertNotNull(msg); } /** * Make sure that a temp queue does not drop message if there is an active * consumers. * * @throws JMSException */ public void testTempQueueHoldsMessagesWithConsumers() throws JMSException { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createTemporaryQueue(); MessageConsumer consumer = session.createConsumer(queue); connection.start(); MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); TextMessage message = session.createTextMessage("Hello"); producer.send(message); Message message2 = consumer.receive(1000); assertNotNull(message2); assertTrue("Expected message to be a TextMessage", message2 instanceof TextMessage); assertTrue("Expected message to be a '" + message.getText() + "'", ((TextMessage)message2).getText().equals(message.getText())); } /** * Make sure that a temp queue does not drop message if there are no active * consumers. * * @throws JMSException */ public void testTempQueueHoldsMessagesWithoutConsumers() throws JMSException { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createTemporaryQueue(); MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); TextMessage message = session.createTextMessage("Hello"); producer.send(message); connection.start(); MessageConsumer consumer = session.createConsumer(queue); Message message2 = consumer.receive(3000); assertNotNull(message2); assertTrue("Expected message to be a TextMessage", message2 instanceof TextMessage); assertTrue("Expected message to be a '" + message.getText() + "'", ((TextMessage)message2).getText().equals(message.getText())); } /** * Test temp queue works under load * * @throws JMSException */ public void testTmpQueueWorksUnderLoad() throws JMSException { int count = 500; int dataSize = 1024; ArrayList list = new ArrayList(count); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createTemporaryQueue(); MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); byte[] data = new byte[dataSize]; for (int i = 0; i < count; i++) { BytesMessage message = session.createBytesMessage(); message.writeBytes(data); producer.send(message); list.add(message); } connection.start(); MessageConsumer consumer = session.createConsumer(queue); for (int i = 0; i < count; i++) { Message message2 = consumer.receive(2000); assertTrue(message2 != null); assertTrue(message2.equals(list.get(i))); } } /** * Make sure you cannot publish to a temp destination that does not exist * anymore. * * @throws JMSException * @throws InterruptedException */ public void testPublishFailsForClosedConnection() throws JMSException, InterruptedException { Connection tempConnection = factory.createConnection(); Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue queue = tempSession.createTemporaryQueue(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); connection.start(); // This message delivery should work since the temp connection is still // open. MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); TextMessage message = session.createTextMessage("First"); producer.send(message); // Closing the connection should destroy the temp queue that was // created. tempConnection.close(); Thread.sleep(2000); // Wait a little bit to let the delete take effect. // This message delivery NOT should work since the temp connection is // now closed. try { message = session.createTextMessage("Hello"); producer.send(message); fail("Send should fail since temp destination should not exist anymore."); } catch (JMSException e) { assertTrue("failed to throw an exception", true); } } /** * Make sure you cannot publish to a temp destination that does not exist * anymore. * * @throws JMSException * @throws InterruptedException */ public void testPublishFailsForDestoryedTempDestination() throws JMSException, InterruptedException { Connection tempConnection = factory.createConnection(); Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue queue = tempSession.createTemporaryQueue(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); connection.start(); // This message delivery should work since the temp connection is still // open. MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); TextMessage message = session.createTextMessage("First"); producer.send(message); // deleting the Queue will cause sends to fail queue.delete(); Thread.sleep(1000); // Wait a little bit to let the delete take effect. // This message delivery NOT should work since the temp connection is // now closed. try { message = session.createTextMessage("Hello"); producer.send(message); fail("Send should fail since temp destination should not exist anymore."); } catch (JMSException e) { assertTrue("failed to throw an exception", true); } } /** * Test you can't delete a Destination with Active Subscribers * * @throws JMSException */ public void testDeleteDestinationWithSubscribersFails() throws JMSException { Connection connection = factory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue queue = session.createTemporaryQueue(); connection.start(); session.createConsumer(queue); // This message delivery should NOT work since the temp connection is // now closed. try { queue.delete(); fail("Should fail as Subscribers are active"); } catch (JMSException e) { assertTrue("failed to throw an exception", true); } } }
Shutdown all connections opened in the testcase so that the broker shutdown between cases. Fixes failures that happened ocasionally git-svn-id: d2a93f579bd4835921162e9a69396c846e49961c@641890 13f79535-47bb-0310-9956-ffa450edef68
activemq-core/src/test/java/org/apache/activemq/JmsTempDestinationTest.java
Shutdown all connections opened in the testcase so that the broker shutdown between cases. Fixes failures that happened ocasionally
<ide><path>ctivemq-core/src/test/java/org/apache/activemq/JmsTempDestinationTest.java <ide> */ <ide> package org.apache.activemq; <ide> <add>import java.net.URI; <add>import java.net.URISyntaxException; <ide> import java.util.ArrayList; <add>import java.util.Collections; <add>import java.util.Date; <add>import java.util.Iterator; <add>import java.util.List; <ide> <ide> import javax.jms.BytesMessage; <ide> import javax.jms.Connection; <ide> <ide> private Connection connection; <ide> private ActiveMQConnectionFactory factory; <add> protected List<Connection> connections = Collections.synchronizedList(new ArrayList<Connection>()); <ide> <ide> protected void setUp() throws Exception { <ide> factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); <ide> factory.setUseAsyncSend(false); <ide> connection = factory.createConnection(); <add> connections.add(connection); <ide> } <ide> <ide> /** <ide> * @see junit.framework.TestCase#tearDown() <ide> */ <ide> protected void tearDown() throws Exception { <del> if (connection != null) { <del> connection.close(); <del> connection = null; <del> } <del> } <del> <add> for (Iterator iter = connections.iterator(); iter.hasNext();) { <add> Connection conn = (Connection)iter.next(); <add> try { <add> conn.close(); <add> } catch (Throwable e) { <add> } <add> iter.remove(); <add> } <add> } <add> <ide> /** <ide> * Make sure Temp destination can only be consumed by local connection <ide> * <ide> <ide> // temp destination should not be consume when using another connection <ide> Connection otherConnection = factory.createConnection(); <add> connections.add(otherConnection); <ide> Session otherSession = otherConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); <ide> TemporaryQueue otherQueue = otherSession.createTemporaryQueue(); <ide> MessageConsumer consumer = otherSession.createConsumer(otherQueue); <ide> for (int i = 0; i < count; i++) { <ide> BytesMessage message = session.createBytesMessage(); <ide> message.writeBytes(data); <add> message.setIntProperty("c", i); <ide> producer.send(message); <ide> list.add(message); <ide> } <ide> MessageConsumer consumer = session.createConsumer(queue); <ide> for (int i = 0; i < count; i++) { <ide> Message message2 = consumer.receive(2000); <del> <ide> assertTrue(message2 != null); <add> assertEquals(i, message2.getIntProperty("c")); <ide> assertTrue(message2.equals(list.get(i))); <ide> } <ide> } <ide> * <ide> * @throws JMSException <ide> * @throws InterruptedException <del> */ <del> public void testPublishFailsForClosedConnection() throws JMSException, InterruptedException { <del> <add> * @throws URISyntaxException <add> */ <add> public void testPublishFailsForClosedConnection() throws JMSException, InterruptedException, URISyntaxException { <add> <ide> Connection tempConnection = factory.createConnection(); <add> connections.add(tempConnection); <ide> Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); <ide> TemporaryQueue queue = tempSession.createTemporaryQueue(); <ide> <ide> // created. <ide> tempConnection.close(); <ide> Thread.sleep(2000); // Wait a little bit to let the delete take effect. <add> <add> // This message delivery NOT should work since the temp connection is <add> // now closed. <add> try { <add> message = session.createTextMessage("Hello"); <add> producer.send(message); <add> fail("Send should fail since temp destination should not exist anymore."); <add> } catch (JMSException e) { <add> } <add> } <add> <add> /** <add> * Make sure you cannot publish to a temp destination that does not exist <add> * anymore. <add> * <add> * @throws JMSException <add> * @throws InterruptedException <add> */ <add> public void testPublishFailsForDestoryedTempDestination() throws JMSException, InterruptedException { <add> <add> Connection tempConnection = factory.createConnection(); <add> connections.add(tempConnection); <add> Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); <add> TemporaryQueue queue = tempSession.createTemporaryQueue(); <add> <add> Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); <add> connection.start(); <add> <add> // This message delivery should work since the temp connection is still <add> // open. <add> MessageProducer producer = session.createProducer(queue); <add> producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); <add> TextMessage message = session.createTextMessage("First"); <add> producer.send(message); <add> <add> // deleting the Queue will cause sends to fail <add> queue.delete(); <add> Thread.sleep(1000); // Wait a little bit to let the delete take effect. <ide> <ide> // This message delivery NOT should work since the temp connection is <ide> // now closed. <ide> } <ide> <ide> /** <del> * Make sure you cannot publish to a temp destination that does not exist <del> * anymore. <del> * <del> * @throws JMSException <del> * @throws InterruptedException <del> */ <del> public void testPublishFailsForDestoryedTempDestination() throws JMSException, InterruptedException { <del> <del> Connection tempConnection = factory.createConnection(); <del> Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); <del> TemporaryQueue queue = tempSession.createTemporaryQueue(); <del> <del> Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); <del> connection.start(); <del> <del> // This message delivery should work since the temp connection is still <del> // open. <del> MessageProducer producer = session.createProducer(queue); <del> producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); <del> TextMessage message = session.createTextMessage("First"); <del> producer.send(message); <del> <del> // deleting the Queue will cause sends to fail <del> queue.delete(); <del> Thread.sleep(1000); // Wait a little bit to let the delete take effect. <del> <del> // This message delivery NOT should work since the temp connection is <del> // now closed. <del> try { <del> message = session.createTextMessage("Hello"); <del> producer.send(message); <del> fail("Send should fail since temp destination should not exist anymore."); <del> } catch (JMSException e) { <del> assertTrue("failed to throw an exception", true); <del> } <del> } <del> <del> /** <ide> * Test you can't delete a Destination with Active Subscribers <ide> * <ide> * @throws JMSException <ide> */ <ide> public void testDeleteDestinationWithSubscribersFails() throws JMSException { <ide> Connection connection = factory.createConnection(); <add> connections.add(connection); <ide> Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); <ide> TemporaryQueue queue = session.createTemporaryQueue(); <ide>
Java
mit
1ed92caf8fa796c0c1fa8da114dd9bc9ce5f33d9
0
Lexine/rootbeer1,Lexine/rootbeer1,yarenty/rootbeer1,yarenty/rootbeer1,Lexine/rootbeer1,Lexine/rootbeer1,yarenty/rootbeer1,yarenty/rootbeer1,yarenty/rootbeer1
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.metzingen.thorstenkiefer; import edu.syr.pcpratts.rootbeer.runtime.Kernel; import edu.syr.pcpratts.rootbeer.runtime.Rootbeer; import edu.syr.pcpratts.rootbeer.runtime.util.Stopwatch; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author thorsten */ public class RayGenerator { private static Rootbeer rb = new Rootbeer(); private static class MyThread extends Thread { public boolean compute = false; public MyKernel kernel = null; public int y; public int w; @Override public void run() { while (true) { while (!compute) { try { sleep(1000); } catch (InterruptedException ex) { } } for (int x = 0; x < w; ++x) { kernel.gpuMethod(x, y); } compute = false; } } } private static MyThread[] threads = new MyThread[16]; public static void generateGPU( int w, int h, double minx, double maxx, double miny, double maxy, int[] pixels, double[][] spheres, double[] light, double[] observer, double radius, double[] vx, double[] vy, int numDimensions) { st.start(); rb.setThreadConfig(w, h); MyKernel myKernel = new MyKernel(pixels, minx, maxx, miny, maxy, w, h, spheres, light, observer, vx, vy, radius, numDimensions); rb.runAll(myKernel); st.stop(); System.out.println(st.elapsedTimeMillis()); System.out.println(rb.getStats().size()); } private static Stopwatch st = new Stopwatch(); public static void generateCPU( int w, int h, double minx, double maxx, double miny, double maxy, int[] pixels, double[][] spheres, double[] light, double[] observer, double radius, double[] vx, double[] vy, int numDimensions) { st.start(); for (int i = 0; i < threads.length; ++i) { threads[i] = new MyThread(); threads[i].kernel = new MyKernel(pixels, minx, maxx, miny, maxy, w, h, spheres, light, observer, vx, vy, radius, numDimensions); threads[i].w = w; threads[i].start(); } for (int y = 0; y < h; ++y) { boolean found = false; while (!found) { for (MyThread mt : threads) { if (!mt.compute) { found = true; mt.y = y; mt.compute = true; mt.interrupt(); break; } } } } st.stop(); System.out.println(st.elapsedTimeMillis()); } }
gtc2013/MultiDimRay2/raylib/src/de/metzingen/thorstenkiefer/RayGenerator.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.metzingen.thorstenkiefer; import com.sun.jmx.snmp.tasks.ThreadService; import edu.syr.pcpratts.rootbeer.runtime.Kernel; import edu.syr.pcpratts.rootbeer.runtime.Rootbeer; import edu.syr.pcpratts.rootbeer.runtime.util.Stopwatch; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author thorsten */ public class RayGenerator { private static Rootbeer rb = new Rootbeer(); private static class MyThread extends Thread { public boolean compute = false; public MyKernel kernel = null; public int y; public int w; @Override public void run() { while (true) { while (!compute) { try { sleep(1000); } catch (InterruptedException ex) { } } for (int x = 0; x < w; ++x) { kernel.gpuMethod(x, y); } compute = false; } } } private static MyThread[] threads = new MyThread[16]; public static void generateGPU( int w, int h, double minx, double maxx, double miny, double maxy, int[] pixels, double[][] spheres, double[] light, double[] observer, double radius, double[] vx, double[] vy, int numDimensions) { st.start(); rb.setThreadConfig(w, h); MyKernel myKernel = new MyKernel(pixels, minx, maxx, miny, maxy, w, h, spheres, light, observer, vx, vy, radius, numDimensions); rb.runAll(myKernel); st.stop(); System.out.println(st.elapsedTimeMillis()); System.out.println(rb.getStats().size()); } private static Stopwatch st = new Stopwatch(); public static void generateCPU( int w, int h, double minx, double maxx, double miny, double maxy, int[] pixels, double[][] spheres, double[] light, double[] observer, double radius, double[] vx, double[] vy, int numDimensions) { st.start(); for (int i = 0; i < threads.length; ++i) { threads[i] = new MyThread(); threads[i].kernel = new MyKernel(pixels, minx, maxx, miny, maxy, w, h, spheres, light, observer, vx, vy, radius, numDimensions); threads[i].w = w; threads[i].start(); } for (int y = 0; y < h; ++y) { boolean found = false; while (!found) { for (MyThread mt : threads) { if (!mt.compute) { found = true; mt.y = y; mt.compute = true; mt.interrupt(); break; } } } } st.stop(); System.out.println(st.elapsedTimeMillis()); } }
Making raylib compile on a system without ThreadService
gtc2013/MultiDimRay2/raylib/src/de/metzingen/thorstenkiefer/RayGenerator.java
Making raylib compile on a system without ThreadService
<ide><path>tc2013/MultiDimRay2/raylib/src/de/metzingen/thorstenkiefer/RayGenerator.java <ide> */ <ide> package de.metzingen.thorstenkiefer; <ide> <del>import com.sun.jmx.snmp.tasks.ThreadService; <ide> import edu.syr.pcpratts.rootbeer.runtime.Kernel; <ide> import edu.syr.pcpratts.rootbeer.runtime.Rootbeer; <ide> import edu.syr.pcpratts.rootbeer.runtime.util.Stopwatch;
JavaScript
bsd-2-clause
e69f0606251b465960bc3809adc8c4025ffd8c36
0
sandflow/imscJS,sandflow/imscJS,sandflow/imscJS,sandflow/imscJS
/* * Copyright (c) 2016, Pierre-Anthony Lemieux <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @module imscHTML */ ; (function (imscHTML, imscNames, imscStyles) { /** * Function that maps <pre>smpte:background</pre> URIs to URLs resolving to image resource * @callback IMGResolver * @param {string} <pre>smpte:background</pre> URI * @return {string} PNG resource URL */ /** * Renders an ISD object (returned by <pre>generateISD()</pre>) into a * parent element, that must be attached to the DOM. The ISD will be rendered * into a child <pre>div</pre> * with heigh and width equal to the clientHeight and clientWidth of the element, * unless explicitly specified otherwise by the caller. Images URIs specified * by <pre>smpte:background</pre> attributes are mapped to image resource URLs * by an <pre>imgResolver</pre> function. The latter takes the value of <code>smpte:background</code> * attribute and an <code>img</code> DOM element as input, and is expected to * set the <code>src</code> attribute of the <code>img</code> to the absolute URI of the image. * <pre>displayForcedOnlyMode</pre> sets the (boolean) * value of the IMSC1 displayForcedOnlyMode parameter. The function returns * an opaque object that should passed in <code>previousISDState</code> when this function * is called for the next ISD, otherwise <code>previousISDState</code> should be set to * <code>null</code>. * * @param {Object} isd ISD to be rendered * @param {Object} element Element into which the ISD is rendered * @param {?IMGResolver} imgResolver Resolve <pre>smpte:background</pre> URIs into URLs. * @param {?number} eheight Height (in pixel) of the child <div>div</div> or null * to use clientHeight of the parent element * @param {?number} ewidth Width (in pixel) of the child <div>div</div> or null * to use clientWidth of the parent element * @param {?boolean} displayForcedOnlyMode Value of the IMSC1 displayForcedOnlyMode parameter, * or false if null * @param {?module:imscUtils.ErrorHandler} errorHandler Error callback * @param {Object} previousISDState State saved during processing of the previous ISD, or null if initial call * @param {?boolean} enableRollUp Enables roll-up animations (see CEA 708) * @return {Object} ISD state to be provided when this funtion is called for the next ISD */ imscHTML.render = function (isd, element, imgResolver, eheight, ewidth, displayForcedOnlyMode, errorHandler, previousISDState, enableRollUp ) { /* maintain aspect ratio if specified */ var height = eheight || element.clientHeight; var width = ewidth || element.clientWidth; if (isd.aspectRatio !== null) { var twidth = height * isd.aspectRatio; if (twidth > width) { height = Math.round(width / isd.aspectRatio); } else { width = twidth; } } var rootcontainer = document.createElement("div"); rootcontainer.style.position = "relative"; rootcontainer.style.width = width + "px"; rootcontainer.style.height = height + "px"; rootcontainer.style.margin = "auto"; rootcontainer.style.top = 0; rootcontainer.style.bottom = 0; rootcontainer.style.left = 0; rootcontainer.style.right = 0; rootcontainer.style.zIndex = 0; var context = { h: height, w: width, regionH: null, regionW: null, imgResolver: imgResolver, displayForcedOnlyMode: displayForcedOnlyMode || false, isd: isd, errorHandler: errorHandler, previousISDState: previousISDState, enableRollUp: enableRollUp || false, currentISDState: {}, flg: null, /* current fillLineGap value if active, null otherwise */ lp: null, /* current linePadding value if active, null otherwise */ mra: null, /* current multiRowAlign value if active, null otherwise */ ipd: null, /* inline progression direction (lr, rl, tb) */ bpd: null, /* block progression direction (lr, rl, tb) */ ruby: null, /* is ruby present in a <p> */ textEmphasis: null, /* is textEmphasis present in a <p> */ rubyReserve: null /* is rubyReserve applicable to a <p> */ }; element.appendChild(rootcontainer); for (var i in isd.contents) { processElement(context, rootcontainer, isd.contents[i]); } return context.currentISDState; }; function processElement(context, dom_parent, isd_element) { var e; if (isd_element.kind === 'region') { e = document.createElement("div"); e.style.position = "absolute"; } else if (isd_element.kind === 'body') { e = document.createElement("div"); } else if (isd_element.kind === 'div') { e = document.createElement("div"); } else if (isd_element.kind === 'image') { e = document.createElement("img"); if (context.imgResolver !== null && isd_element.src !== null) { var uri = context.imgResolver(isd_element.src, e); if (uri) e.src = uri; e.height = context.regionH; e.width = context.regionW; } } else if (isd_element.kind === 'p') { e = document.createElement("p"); } else if (isd_element.kind === 'span') { if (isd_element.styleAttrs[imscStyles.byName.ruby.qname] === "container") { e = document.createElement("ruby"); context.ruby = true; } else if (isd_element.styleAttrs[imscStyles.byName.ruby.qname] === "base") { e = document.createElement("rb"); } else if (isd_element.styleAttrs[imscStyles.byName.ruby.qname] === "text") { e = document.createElement("rt"); } else if (isd_element.styleAttrs[imscStyles.byName.ruby.qname] === "baseContainer") { e = document.createElement("rbc"); } else if (isd_element.styleAttrs[imscStyles.byName.ruby.qname] === "textContainer") { e = document.createElement("rtc"); } else if (isd_element.styleAttrs[imscStyles.byName.ruby.qname] === "delimiter") { /* ignore rp */ return; } else { e = document.createElement("span"); } var te = isd_element.styleAttrs[imscStyles.byName.textEmphasis.qname]; if (te && te.style !== "none") { context.textEmphasis = true; } //e.textContent = isd_element.text; } else if (isd_element.kind === 'br') { e = document.createElement("br"); } if (!e) { reportError(context.errorHandler, "Error processing ISD element kind: " + isd_element.kind); return; } /* add to parent */ dom_parent.appendChild(e); /* override UA default margin */ /* TODO: should apply to <p> only */ e.style.margin = "0"; /* tranform TTML styles to CSS styles */ for (var i in STYLING_MAP_DEFS) { var sm = STYLING_MAP_DEFS[i]; var attr = isd_element.styleAttrs[sm.qname]; if (attr !== undefined && sm.map !== null) { sm.map(context, e, isd_element, attr); } } var proc_e = e; /* remember writing direction */ if (isd_element.kind === "region") { var wdir = isd_element.styleAttrs[imscStyles.byName.writingMode.qname]; if (wdir === "lrtb" || wdir === "lr") { context.ipd = "lr"; context.bpd = "tb"; } else if (wdir === "rltb" || wdir === "rl") { context.ipd = "rl"; context.bpd = "tb"; } else if (wdir === "tblr") { context.ipd = "tb"; context.bpd = "lr"; } else if (wdir === "tbrl" || wdir === "tb") { context.ipd = "tb"; context.bpd = "rl"; } } /* do we have linePadding ? */ var lp = isd_element.styleAttrs[imscStyles.byName.linePadding.qname]; if (lp && (! lp.isZero())) { var plength = lp.toUsedLength(context.w, context.h); if (plength > 0) { /* apply padding to the <p> so that line padding does not cause line wraps */ var padmeasure = Math.ceil(plength) + "px"; if (context.bpd === "tb") { proc_e.style.paddingLeft = padmeasure; proc_e.style.paddingRight = padmeasure; } else { proc_e.style.paddingTop = padmeasure; proc_e.style.paddingBottom = padmeasure; } context.lp = lp; } } // do we have multiRowAlign? var mra = isd_element.styleAttrs[imscStyles.byName.multiRowAlign.qname]; if (mra && mra !== "auto") { /* create inline block to handle multirowAlign */ var s = document.createElement("span"); s.style.display = "inline-block"; s.style.textAlign = mra; e.appendChild(s); proc_e = s; context.mra = mra; } /* do we have rubyReserve? */ var rr = isd_element.styleAttrs[imscStyles.byName.rubyReserve.qname]; if (rr && rr[0] !== "none") { context.rubyReserve = rr; } /* remember we are filling line gaps */ if (isd_element.styleAttrs[imscStyles.byName.fillLineGap.qname]) { context.flg = true; } if (isd_element.kind === "span" && isd_element.text) { if (imscStyles.byName.textCombine.qname in isd_element.styleAttrs && isd_element.styleAttrs[imscStyles.byName.textCombine.qname][0] === "all") { /* ignore tate-chu-yoku since line break cannot happen within */ e.textContent = isd_element.text; } else { // wrap characters in spans to find the line wrap locations var cbuf = ''; for (var j = 0; j < isd_element.text.length; j++) { cbuf += isd_element.text.charAt(j); var cc = isd_element.text.charCodeAt(j); if (cc < 0xD800 || cc > 0xDBFF || j === isd_element.text.length) { /* wrap the character(s) in a span unless it is a high surrogate */ var span = document.createElement("span"); span.textContent = cbuf; e.appendChild(span); cbuf = ''; } } } } /* process the children of the ISD element */ for (var k in isd_element.contents) { processElement(context, proc_e, isd_element.contents[k]); } /* list of lines */ var linelist = []; /* paragraph processing */ /* TODO: linePadding only supported for horizontal scripts */ if ((context.lp || context.mra || context.flg || context.ruby || context.textEmphasis || context.rubyReserve) && isd_element.kind === "p") { constructLineList(context, proc_e, linelist, null); /* apply rubyReserve */ if (context.rubyReserve) { applyRubyReserve(linelist, context); context.rubyReserve = null; } /* apply tts:rubyPosition="outside" */ if (context.ruby || context.rubyReserve) { applyRubyPosition(linelist, context); context.ruby = null; } /* apply text emphasis "outside" position */ if (context.textEmphasis) { applyTextEmphasis(linelist, context); context.textEmphasis = null; } /* insert line breaks for multirowalign */ if (context.mra) { applyMultiRowAlign(linelist); context.mra = null; } /* add linepadding */ if (context.lp) { applyLinePadding(linelist, context.lp.toUsedLength(context.w, context.h), context); context.lp = null; } /* fill line gaps linepadding */ if (context.flg) { var par_edges = rect2edges(proc_e.getBoundingClientRect(), context); applyFillLineGap(linelist, par_edges.before, par_edges.after, context); context.flg = null; } } /* region processing */ if (isd_element.kind === "region") { /* build line list */ constructLineList(context, proc_e, linelist); /* perform roll up if needed */ if ((context.bpd === "tb") && context.enableRollUp && isd_element.contents.length > 0 && isd_element.styleAttrs[imscStyles.byName.displayAlign.qname] === 'after') { /* horrible hack, perhaps default region id should be underscore everywhere? */ var rid = isd_element.id === '' ? '_' : isd_element.id; var rb = new RegionPBuffer(rid, linelist); context.currentISDState[rb.id] = rb; if (context.previousISDState && rb.id in context.previousISDState && context.previousISDState[rb.id].plist.length > 0 && rb.plist.length > 1 && rb.plist[rb.plist.length - 2].text === context.previousISDState[rb.id].plist[context.previousISDState[rb.id].plist.length - 1].text) { var body_elem = e.firstElementChild; var h = rb.plist[rb.plist.length - 1].after - rb.plist[rb.plist.length - 1].before; body_elem.style.bottom = "-" + h + "px"; body_elem.style.transition = "transform 0.4s"; body_elem.style.position = "relative"; body_elem.style.transform = "translateY(-" + h + "px)"; } } /* TODO: clean-up the spans ? */ } } function applyLinePadding(lineList, lp, context) { for (var i in lineList) { var l = lineList[i].elements.length; var se = lineList[i].elements[lineList[i].start_elem]; var ee = lineList[i].elements[lineList[i].end_elem]; var pospadpxlen = Math.ceil(lp) + "px"; var negpadpxlen = "-" + Math.ceil(lp) + "px"; if (l !== 0) { if (context.ipd === "lr") { se.node.style.borderLeftColor = se.bgcolor || "#00000000"; se.node.style.borderLeftStyle = "solid"; se.node.style.borderLeftWidth = pospadpxlen; se.node.style.marginLeft = negpadpxlen; } else if (context.ipd === "rl") { se.node.style.borderRightColor = se.bgcolor || "#00000000"; se.node.style.borderRightStyle = "solid"; se.node.style.borderRightWidth = pospadpxlen; se.node.style.marginRight = negpadpxlen; } else if (context.ipd === "tb") { se.node.style.borderTopColor = se.bgcolor || "#00000000"; se.node.style.borderTopStyle = "solid"; se.node.style.borderTopWidth = pospadpxlen; se.node.style.marginTop = negpadpxlen; } if (context.ipd === "lr") { ee.node.style.borderRightColor = ee.bgcolor || "#00000000"; ee.node.style.borderRightStyle = "solid"; ee.node.style.borderRightWidth = pospadpxlen; ee.node.style.marginRight = negpadpxlen; } else if (context.ipd === "rl") { ee.node.style.borderLeftColor = ee.bgcolor || "#00000000"; ee.node.style.borderLeftStyle = "solid"; ee.node.style.borderLeftWidth = pospadpxlen; ee.node.style.marginLeft = negpadpxlen; } else if (context.ipd === "tb") { ee.node.style.borderBottomColor = ee.bgcolor || "#00000000"; ee.node.style.borderBottomStyle = "solid"; ee.node.style.borderBottomWidth = pospadpxlen; ee.node.style.marginBottom = negpadpxlen; } } } } function applyMultiRowAlign(lineList) { /* apply an explicit br to all but the last line */ for (var i = 0; i < lineList.length - 1; i++) { var l = lineList[i].elements.length; if (l !== 0 && lineList[i].br === false) { var br = document.createElement("br"); var lastnode = lineList[i].elements[l - 1].node; lastnode.parentElement.insertBefore(br, lastnode.nextSibling); } } } function applyTextEmphasis(lineList, context) { /* supports "outside" only */ for (var i = 0; i < lineList.length; i++) { for (var j = 0; j < lineList[i].te.length; j++) { /* skip if position already set */ if (lineList[i].te[j].style[TEXTEMPHASISPOSITION_PROP] && lineList[i].te[j].style[TEXTEMPHASISPOSITION_PROP] !== "none") continue; var pos; if (context.bpd === "tb") { pos = (i === 0) ? "left over" : "left under"; } else { if (context.bpd === "rl") { pos = (i === 0) ? "right under" : "left under"; } else { pos = (i === 0) ? "left under" : "right under"; } } lineList[i].te[j].style[TEXTEMPHASISPOSITION_PROP] = pos; } } } function applyRubyPosition(lineList, context) { for (var i = 0; i < lineList.length; i++) { for (var j = 0; j < lineList[i].rbc.length; j++) { /* skip if ruby-position already set */ if (lineList[i].rbc[j].style[RUBYPOSITION_PROP]) continue; var pos; if (RUBYPOSITION_ISWK) { /* WebKit exception */ pos = (i === 0) ? "before" : "after"; } else if (context.bpd === "tb") { pos = (i === 0) ? "over" : "under"; } else { if (context.bpd === "rl") { pos = (i === 0) ? "over" : "under"; } else { pos = (i === 0) ? "under" : "over"; } } lineList[i].rbc[j].style[RUBYPOSITION_PROP] = pos; } } } function applyRubyReserve(lineList, context) { for (var i = 0; i < lineList.length; i++) { var ruby = document.createElement("ruby"); var rb = document.createElement("rb"); rb.textContent = "\u200B"; ruby.appendChild(rb); var rt1; var rt2; var fs = context.rubyReserve[1].toUsedLength(context.w, context.h) + "px"; if (context.rubyReserve[0] === "both" || (context.rubyReserve[0] === "outside" && lineList.length == 1)) { rt1 = document.createElement("rtc"); rt1.style[RUBYPOSITION_PROP] = RUBYPOSITION_ISWK ? "after" : "under"; rt1.textContent = "\u200B"; rt1.style.fontSize = fs; rt2 = document.createElement("rtc"); rt2.style[RUBYPOSITION_PROP] = RUBYPOSITION_ISWK ? "before" : "over"; rt2.textContent = "\u200B"; rt2.style.fontSize = fs; ruby.appendChild(rt1); ruby.appendChild(rt2); } else { rt1 = document.createElement("rtc"); rt1.textContent = "\u200B"; rt1.style.fontSize = fs; var pos; if (context.rubyReserve[0] === "after" || (context.rubyReserve[0] === "outside" && i > 0)) { pos = RUBYPOSITION_ISWK ? "after" : ((context.bpd === "tb" || context.bpd === "rl") ? "under" : "over"); } else { pos = RUBYPOSITION_ISWK ? "before" : ((context.bpd === "tb" || context.bpd === "rl") ? "over" : "under"); } rt1.style[RUBYPOSITION_PROP] = pos; ruby.appendChild(rt1); } /* add in front of the first ruby element of the line, if it exists */ var sib = null; for (var j = 0; j < lineList[i].rbc.length; j++) { if (lineList[i].rbc[j].localName === 'ruby') { sib = lineList[i].rbc[j]; /* copy specified style properties from the sibling ruby container */ for(var k = 0; k < sib.style.length; k++) { ruby.style.setProperty(sib.style.item(k), sib.style.getPropertyValue(sib.style.item(k))); } break; } } /* otherwise add before first span */ sib = sib || lineList[i].elements[0].node; sib.parentElement.insertBefore(ruby, sib); } } function applyFillLineGap(lineList, par_before, par_after, context) { /* positive for BPD = lr and tb, negative for BPD = rl */ var s = Math.sign(par_after - par_before); for (var i = 0; i <= lineList.length; i++) { /* compute frontier between lines */ var frontier; if (i === 0) { frontier = par_before; } else if (i === lineList.length) { frontier = par_after; } else { frontier = (lineList[i].before + lineList[i - 1].after) / 2; } /* padding amount */ var pad; /* current element */ var e; /* before line */ if (i > 0) { for (var j = 0; j < lineList[i - 1].elements.length; j++) { if (lineList[i - 1].elements[j].bgcolor === null) continue; e = lineList[i - 1].elements[j]; if (s * (e.after - frontier) < 0) { pad = Math.ceil(Math.abs(frontier - e.after)) + "px"; e.node.style.backgroundColor = e.bgcolor; if (context.bpd === "lr") { e.node.style.paddingRight = pad; } else if (context.bpd === "rl") { e.node.style.paddingLeft = pad; } else if (context.bpd === "tb") { e.node.style.paddingBottom = pad; } } } } /* after line */ if (i < lineList.length) { for (var k = 0; k < lineList[i].elements.length; k++) { e = lineList[i].elements[k]; if (e.bgcolor === null) continue; if (s * (e.before - frontier) > 0) { pad = Math.ceil(Math.abs(e.before - frontier)) + "px"; e.node.style.backgroundColor = e.bgcolor; if (context.bpd === "lr") { e.node.style.paddingLeft = pad; } else if (context.bpd === "rl") { e.node.style.paddingRight = pad; } else if (context.bpd === "tb") { e.node.style.paddingTop = pad; } } } } } } function RegionPBuffer(id, lineList) { this.id = id; this.plist = lineList; } function rect2edges(rect, context) { var edges = {before: null, after: null, start: null, end: null}; if (context.bpd === "tb") { edges.before = rect.top; edges.after = rect.bottom; if (context.ipd === "lr") { edges.start = rect.left; edges.end = rect.right; } else { edges.start = rect.right; edges.end = rect.left; } } else if (context.bpd === "lr") { edges.before = rect.left; edges.after = rect.right; edges.start = rect.top; edges.end = rect.bottom; } else if (context.bpd === "rl") { edges.before = rect.right; edges.after = rect.left; edges.start = rect.top; edges.end = rect.bottom; } return edges; } function constructLineList(context, element, llist, bgcolor) { if (element.localName === "rt" || element.localName === "rtc") { /* skip ruby annotations */ return; } var curbgcolor = element.style.backgroundColor || bgcolor; if (element.childElementCount === 0) { if (element.localName === 'span' || element.localName === 'rb') { var r = element.getBoundingClientRect(); /* skip if span is not displayed */ if (r.height === 0 || r.width === 0) return; var edges = rect2edges(r, context); if (llist.length === 0 || (!isSameLine(edges.before, edges.after, llist[llist.length - 1].before, llist[llist.length - 1].after)) ) { llist.push({ before: edges.before, after: edges.after, start: edges.start, end: edges.end, start_elem: 0, end_elem: 0, elements: [], rbc: [], te: [], text: "", br: false }); } else { /* positive for BPD = lr and tb, negative for BPD = rl */ var bpd_dir = Math.sign(edges.after - edges.before); /* positive for IPD = lr and tb, negative for IPD = rl */ var ipd_dir = Math.sign(edges.end - edges.start); /* check if the line height has increased */ if (bpd_dir * (edges.before - llist[llist.length - 1].before) < 0) { llist[llist.length - 1].before = edges.before; } if (bpd_dir * (edges.after - llist[llist.length - 1].after) > 0) { llist[llist.length - 1].after = edges.after; } if (ipd_dir * (edges.start - llist[llist.length - 1].start) < 0) { llist[llist.length - 1].start = edges.start; llist[llist.length - 1].start_elem = llist[llist.length - 1].elements.length; } if (ipd_dir * (edges.end - llist[llist.length - 1].end) > 0) { llist[llist.length - 1].end = edges.end; llist[llist.length - 1].end_elem = llist[llist.length - 1].elements.length; } } llist[llist.length - 1].text += element.textContent; llist[llist.length - 1].elements.push( { node: element, bgcolor: curbgcolor, before: edges.before, after: edges.after } ); } else if (element.localName === 'br' && llist.length !== 0) { llist[llist.length - 1].br = true; } } else { var child = element.firstChild; while (child) { if (child.nodeType === Node.ELEMENT_NODE) { constructLineList(context, child, llist, curbgcolor); if (child.localName === 'ruby' || child.localName === 'rtc') { /* remember non-empty ruby and rtc elements so that tts:rubyPosition can be applied */ if (llist.length > 0) { llist[llist.length - 1].rbc.push(child); } } else if (child.localName === 'span' && child.style[TEXTEMPHASISSTYLE_PROP] && child.style[TEXTEMPHASISSTYLE_PROP] !== "none") { /* remember non-empty span elements with textEmphasis */ if (llist.length > 0) { llist[llist.length - 1].te.push(child); } } } child = child.nextSibling; } } } function isSameLine(before1, after1, before2, after2) { return ((after1 < after2) && (before1 > before2)) || ((after2 <= after1) && (before2 >= before1)); } function HTMLStylingMapDefintion(qName, mapFunc) { this.qname = qName; this.map = mapFunc; } var STYLING_MAP_DEFS = [ new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling backgroundColor", function (context, dom_element, isd_element, attr) { /* skip if transparent */ if (attr[3] === 0) return; dom_element.style.backgroundColor = "rgba(" + attr[0].toString() + "," + attr[1].toString() + "," + attr[2].toString() + "," + (attr[3] / 255).toString() + ")"; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling color", function (context, dom_element, isd_element, attr) { dom_element.style.color = "rgba(" + attr[0].toString() + "," + attr[1].toString() + "," + attr[2].toString() + "," + (attr[3] / 255).toString() + ")"; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling direction", function (context, dom_element, isd_element, attr) { dom_element.style.direction = attr; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling display", function (context, dom_element, isd_element, attr) {} ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling displayAlign", function (context, dom_element, isd_element, attr) { /* see https://css-tricks.com/snippets/css/a-guide-to-flexbox/ */ /* TODO: is this affected by writing direction? */ dom_element.style.display = "flex"; dom_element.style.flexDirection = "column"; if (attr === "before") { dom_element.style.justifyContent = "flex-start"; } else if (attr === "center") { dom_element.style.justifyContent = "center"; } else if (attr === "after") { dom_element.style.justifyContent = "flex-end"; } } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling extent", function (context, dom_element, isd_element, attr) { /* TODO: this is super ugly */ context.regionH = attr.h.toUsedLength(context.w, context.h); context.regionW = attr.w.toUsedLength(context.w, context.h); /* * CSS height/width are measured against the content rectangle, * whereas TTML height/width include padding */ var hdelta = 0; var wdelta = 0; var p = isd_element.styleAttrs["http://www.w3.org/ns/ttml#styling padding"]; if (!p) { /* error */ } else { hdelta = p[0].toUsedLength(context.w, context.h) + p[2].toUsedLength(context.w, context.h); wdelta = p[1].toUsedLength(context.w, context.h) + p[3].toUsedLength(context.w, context.h); } dom_element.style.height = (context.regionH - hdelta) + "px"; dom_element.style.width = (context.regionW - wdelta) + "px"; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling fontFamily", function (context, dom_element, isd_element, attr) { var rslt = []; /* per IMSC1 */ for (var i in attr) { if (attr[i] === "monospaceSerif") { rslt.push("Courier New"); rslt.push('"Liberation Mono"'); rslt.push("Courier"); rslt.push("monospace"); } else if (attr[i] === "proportionalSansSerif") { rslt.push("Arial"); rslt.push("Helvetica"); rslt.push('"Liberation Sans"'); rslt.push("sans-serif"); } else if (attr[i] === "monospace") { rslt.push("monospace"); } else if (attr[i] === "sansSerif") { rslt.push("sans-serif"); } else if (attr[i] === "serif") { rslt.push("serif"); } else if (attr[i] === "monospaceSansSerif") { rslt.push("Consolas"); rslt.push("monospace"); } else if (attr[i] === "proportionalSerif") { rslt.push("serif"); } else { rslt.push(attr[i]); } } dom_element.style.fontFamily = rslt.join(","); } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling shear", function (context, dom_element, isd_element, attr) { /* return immediately if tts:shear is 0% since CSS transforms are not inherited*/ if (attr === 0) return; var angle = attr * -0.9; /* context.writingMode is needed since writing mode is not inherited and sets the inline progression */ if (context.bpd === "tb") { dom_element.style.transform = "skewX(" + angle + "deg)"; } else { dom_element.style.transform = "skewY(" + angle + "deg)"; } } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling fontSize", function (context, dom_element, isd_element, attr) { dom_element.style.fontSize = attr.toUsedLength(context.w, context.h) + "px"; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling fontStyle", function (context, dom_element, isd_element, attr) { dom_element.style.fontStyle = attr; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling fontWeight", function (context, dom_element, isd_element, attr) { dom_element.style.fontWeight = attr; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling lineHeight", function (context, dom_element, isd_element, attr) { if (attr === "normal") { dom_element.style.lineHeight = "normal"; } else { dom_element.style.lineHeight = attr.toUsedLength(context.w, context.h) + "px"; } } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling opacity", function (context, dom_element, isd_element, attr) { dom_element.style.opacity = attr; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling origin", function (context, dom_element, isd_element, attr) { dom_element.style.top = attr.h.toUsedLength(context.w, context.h) + "px"; dom_element.style.left = attr.w.toUsedLength(context.w, context.h) + "px"; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling overflow", function (context, dom_element, isd_element, attr) { dom_element.style.overflow = attr; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling padding", function (context, dom_element, isd_element, attr) { /* attr: top,left,bottom,right*/ /* style: top right bottom left*/ var rslt = []; rslt[0] = attr[0].toUsedLength(context.w, context.h) + "px"; rslt[1] = attr[3].toUsedLength(context.w, context.h) + "px"; rslt[2] = attr[2].toUsedLength(context.w, context.h) + "px"; rslt[3] = attr[1].toUsedLength(context.w, context.h) + "px"; dom_element.style.padding = rslt.join(" "); } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling position", function (context, dom_element, isd_element, attr) { dom_element.style.top = attr.h.toUsedLength(context.w, context.h) + "px"; dom_element.style.left = attr.w.toUsedLength(context.w, context.h) + "px"; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling rubyAlign", function (context, dom_element, isd_element, attr) { dom_element.style.rubyAlign = attr; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling rubyPosition", function (context, dom_element, isd_element, attr) { /* skip if "outside", which is handled by applyRubyPosition() */ if (attr === "before" || attr === "after") { var pos; if (RUBYPOSITION_ISWK) { /* WebKit exception */ pos = attr; } else if (context.bpd === "tb") { pos = (attr === "before") ? "over" : "under"; } else { if (context.bpd === "rl") { pos = (attr === "before") ? "over" : "under"; } else { pos = (attr === "before") ? "under" : "over"; } } /* apply position to the parent dom_element, i.e. ruby or rtc */ dom_element.parentElement.style[RUBYPOSITION_PROP] = pos; } } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling showBackground", null ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling textAlign", function (context, dom_element, isd_element, attr) { var ta; var dir = isd_element.styleAttrs[imscStyles.byName.direction.qname]; /* handle UAs that do not understand start or end */ if (attr === "start") { ta = (dir === "rtl") ? "right" : "left"; } else if (attr === "end") { ta = (dir === "rtl") ? "left" : "right"; } else { ta = attr; } dom_element.style.textAlign = ta; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling textDecoration", function (context, dom_element, isd_element, attr) { dom_element.style.textDecoration = attr.join(" ").replace("lineThrough", "line-through"); } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling textOutline", function (context, dom_element, isd_element, attr) { /* defer to tts:textShadow */ } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling textShadow", function (context, dom_element, isd_element, attr) { var txto = isd_element.styleAttrs[imscStyles.byName.textOutline.qname]; if (attr === "none" && txto === "none") { dom_element.style.textShadow = ""; } else { var s = []; if (txto !== "none") { /* emulate text outline */ var to_color = "rgba(" + txto.color[0].toString() + "," + txto.color[1].toString() + "," + txto.color[2].toString() + "," + (txto.color[3] / 255).toString() + ")"; s.push( "1px 1px 1px " + to_color); s.push( "-1px 1px 1px " + to_color); s.push( "1px -1px 1px " + to_color); s.push( "-1px -1px 1px " + to_color); } /* add text shadow */ if (attr !== "none") { for (var i in attr) { s.push(attr[i].x_off.toUsedLength(context.w, context.h) + "px " + attr[i].y_off.toUsedLength(context.w, context.h) + "px " + attr[i].b_radius.toUsedLength(context.w, context.h) + "px " + "rgba(" + attr[i].color[0].toString() + "," + attr[i].color[1].toString() + "," + attr[i].color[2].toString() + "," + (attr[i].color[3] / 255).toString() + ")" ); } } dom_element.style.textShadow = s.join(","); } } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling textCombine", function (context, dom_element, isd_element, attr) { dom_element.style.textCombineUpright = attr.join(" "); } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling textEmphasis", function (context, dom_element, isd_element, attr) { /* ignore color (not used in IMSC 1.1) */ if (attr.style === "none") { dom_element.style[TEXTEMPHASISSTYLE_PROP] = "none"; /* no need to set position, so return */ return; } else if (attr.style === "auto") { dom_element.style[TEXTEMPHASISSTYLE_PROP] = "filled"; } else { dom_element.style[TEXTEMPHASISSTYLE_PROP] = attr.style + " " + attr.symbol; } /* ignore "outside" position (set in postprocessing) */ if (attr.position === "before" || attr.position === "after") { var pos; if (context.bpd === "tb") { pos = (attr.position === "before") ? "left over" : "left under"; } else { if (context.bpd === "rl") { pos = (attr.position === "before") ? "right under" : "left under"; } else { pos = (attr.position === "before") ? "left under" : "right under"; } } dom_element.style[TEXTEMPHASISPOSITION_PROP] = pos; } } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling unicodeBidi", function (context, dom_element, isd_element, attr) { var ub; if (attr === 'bidiOverride') { ub = "bidi-override"; } else { ub = attr; } dom_element.style.unicodeBidi = ub; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling visibility", function (context, dom_element, isd_element, attr) { dom_element.style.visibility = attr; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling wrapOption", function (context, dom_element, isd_element, attr) { if (attr === "wrap") { if (isd_element.space === "preserve") { dom_element.style.whiteSpace = "pre-wrap"; } else { dom_element.style.whiteSpace = "normal"; } } else { if (isd_element.space === "preserve") { dom_element.style.whiteSpace = "pre"; } else { dom_element.style.whiteSpace = "noWrap"; } } } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling writingMode", function (context, dom_element, isd_element, attr) { if (attr === "lrtb" || attr === "lr") { context.writingMode = "horizontal-tb"; } else if (attr === "rltb" || attr === "rl") { context.writingMode = "horizontal-tb"; } else if (attr === "tblr") { context.writingMode = "vertical-lr"; } else if (attr === "tbrl" || attr === "tb") { context.writingMode = "vertical-rl"; } dom_element.style.writingMode = context.writingMode; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling zIndex", function (context, dom_element, isd_element, attr) { dom_element.style.zIndex = attr; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml/profile/imsc1#styling forcedDisplay", function (context, dom_element, isd_element, attr) { if (context.displayForcedOnlyMode && attr === false) { dom_element.style.visibility = "hidden"; } } ) ]; var STYLMAP_BY_QNAME = {}; for (var i in STYLING_MAP_DEFS) { STYLMAP_BY_QNAME[STYLING_MAP_DEFS[i].qname] = STYLING_MAP_DEFS[i]; } /* CSS property names */ var RUBYPOSITION_ISWK = "webkitRubyPosition" in window.getComputedStyle(document.documentElement); var RUBYPOSITION_PROP = RUBYPOSITION_ISWK ? "webkitRubyPosition" : "rubyPosition"; var TEXTEMPHASISSTYLE_PROP = "webkitTextEmphasisStyle" in window.getComputedStyle(document.documentElement) ? "webkitTextEmphasisStyle" : "textEmphasisStyle"; var TEXTEMPHASISPOSITION_PROP = "webkitTextEmphasisPosition" in window.getComputedStyle(document.documentElement) ? "webkitTextEmphasisPosition" : "textEmphasisPosition"; /* error utilities */ function reportError(errorHandler, msg) { if (errorHandler && errorHandler.error && errorHandler.error(msg)) throw msg; } })(typeof exports === 'undefined' ? this.imscHTML = {} : exports, typeof imscNames === 'undefined' ? require("./names") : imscNames, typeof imscStyles === 'undefined' ? require("./styles") : imscStyles, typeof imscUtils === 'undefined' ? require("./utils") : imscUtils);
src/main/js/html.js
/* * Copyright (c) 2016, Pierre-Anthony Lemieux <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @module imscHTML */ ; (function (imscHTML, imscNames, imscStyles) { /** * Function that maps <pre>smpte:background</pre> URIs to URLs resolving to image resource * @callback IMGResolver * @param {string} <pre>smpte:background</pre> URI * @return {string} PNG resource URL */ /** * Renders an ISD object (returned by <pre>generateISD()</pre>) into a * parent element, that must be attached to the DOM. The ISD will be rendered * into a child <pre>div</pre> * with heigh and width equal to the clientHeight and clientWidth of the element, * unless explicitly specified otherwise by the caller. Images URIs specified * by <pre>smpte:background</pre> attributes are mapped to image resource URLs * by an <pre>imgResolver</pre> function. The latter takes the value of <code>smpte:background</code> * attribute and an <code>img</code> DOM element as input, and is expected to * set the <code>src</code> attribute of the <code>img</code> to the absolute URI of the image. * <pre>displayForcedOnlyMode</pre> sets the (boolean) * value of the IMSC1 displayForcedOnlyMode parameter. The function returns * an opaque object that should passed in <code>previousISDState</code> when this function * is called for the next ISD, otherwise <code>previousISDState</code> should be set to * <code>null</code>. * * @param {Object} isd ISD to be rendered * @param {Object} element Element into which the ISD is rendered * @param {?IMGResolver} imgResolver Resolve <pre>smpte:background</pre> URIs into URLs. * @param {?number} eheight Height (in pixel) of the child <div>div</div> or null * to use clientHeight of the parent element * @param {?number} ewidth Width (in pixel) of the child <div>div</div> or null * to use clientWidth of the parent element * @param {?boolean} displayForcedOnlyMode Value of the IMSC1 displayForcedOnlyMode parameter, * or false if null * @param {?module:imscUtils.ErrorHandler} errorHandler Error callback * @param {Object} previousISDState State saved during processing of the previous ISD, or null if initial call * @param {?boolean} enableRollUp Enables roll-up animations (see CEA 708) * @return {Object} ISD state to be provided when this funtion is called for the next ISD */ imscHTML.render = function (isd, element, imgResolver, eheight, ewidth, displayForcedOnlyMode, errorHandler, previousISDState, enableRollUp ) { /* maintain aspect ratio if specified */ var height = eheight || element.clientHeight; var width = ewidth || element.clientWidth; if (isd.aspectRatio !== null) { var twidth = height * isd.aspectRatio; if (twidth > width) { height = Math.round(width / isd.aspectRatio); } else { width = twidth; } } var rootcontainer = document.createElement("div"); rootcontainer.style.position = "relative"; rootcontainer.style.width = width + "px"; rootcontainer.style.height = height + "px"; rootcontainer.style.margin = "auto"; rootcontainer.style.top = 0; rootcontainer.style.bottom = 0; rootcontainer.style.left = 0; rootcontainer.style.right = 0; rootcontainer.style.zIndex = 0; var context = { h: height, w: width, regionH: null, regionW: null, imgResolver: imgResolver, displayForcedOnlyMode: displayForcedOnlyMode || false, isd: isd, errorHandler: errorHandler, previousISDState: previousISDState, enableRollUp: enableRollUp || false, currentISDState: {}, flg: null, /* current fillLineGap value if active, null otherwise */ lp: null, /* current linePadding value if active, null otherwise */ mra: null, /* current multiRowAlign value if active, null otherwise */ ipd: null, /* inline progression direction (lr, rl, tb) */ bpd: null, /* block progression direction (lr, rl, tb) */ ruby: null, /* is ruby present in a <p> */ textEmphasis: null, /* is textEmphasis present in a <p> */ rubyReserve: null /* is rubyReserve applicable to a <p> */ }; element.appendChild(rootcontainer); for (var i in isd.contents) { processElement(context, rootcontainer, isd.contents[i]); } return context.currentISDState; }; function processElement(context, dom_parent, isd_element) { var e; if (isd_element.kind === 'region') { e = document.createElement("div"); e.style.position = "absolute"; } else if (isd_element.kind === 'body') { e = document.createElement("div"); } else if (isd_element.kind === 'div') { e = document.createElement("div"); } else if (isd_element.kind === 'image') { e = document.createElement("img"); if (context.imgResolver !== null && isd_element.src !== null) { var uri = context.imgResolver(isd_element.src, e); if (uri) e.src = uri; e.height = context.regionH; e.width = context.regionW; } } else if (isd_element.kind === 'p') { e = document.createElement("p"); } else if (isd_element.kind === 'span') { if (isd_element.styleAttrs[imscStyles.byName.ruby.qname] === "container") { e = document.createElement("ruby"); context.ruby = true; } else if (isd_element.styleAttrs[imscStyles.byName.ruby.qname] === "base") { e = document.createElement("rb"); } else if (isd_element.styleAttrs[imscStyles.byName.ruby.qname] === "text") { e = document.createElement("rt"); } else if (isd_element.styleAttrs[imscStyles.byName.ruby.qname] === "baseContainer") { e = document.createElement("rbc"); } else if (isd_element.styleAttrs[imscStyles.byName.ruby.qname] === "textContainer") { e = document.createElement("rtc"); } else if (isd_element.styleAttrs[imscStyles.byName.ruby.qname] === "delimiter") { /* ignore rp */ return; } else { e = document.createElement("span"); } var te = isd_element.styleAttrs[imscStyles.byName.textEmphasis.qname]; if (te && te.style !== "none") { context.textEmphasis = true; } //e.textContent = isd_element.text; } else if (isd_element.kind === 'br') { e = document.createElement("br"); } if (!e) { reportError(context.errorHandler, "Error processing ISD element kind: " + isd_element.kind); return; } /* add to parent */ dom_parent.appendChild(e); /* override UA default margin */ /* TODO: should apply to <p> only */ e.style.margin = "0"; /* tranform TTML styles to CSS styles */ for (var i in STYLING_MAP_DEFS) { var sm = STYLING_MAP_DEFS[i]; var attr = isd_element.styleAttrs[sm.qname]; if (attr !== undefined && sm.map !== null) { sm.map(context, e, isd_element, attr); } } var proc_e = e; /* remember writing direction */ if (isd_element.kind === "region") { var wdir = isd_element.styleAttrs[imscStyles.byName.writingMode.qname]; if (wdir === "lrtb" || wdir === "lr") { context.ipd = "lr"; context.bpd = "tb"; } else if (wdir === "rltb" || wdir === "rl") { context.ipd = "rl"; context.bpd = "tb"; } else if (wdir === "tblr") { context.ipd = "tb"; context.bpd = "lr"; } else if (wdir === "tbrl" || wdir === "tb") { context.ipd = "tb"; context.bpd = "rl"; } } /* do we have linePadding ? */ var lp = isd_element.styleAttrs[imscStyles.byName.linePadding.qname]; if (lp && (! lp.isZero())) { var plength = lp.toUsedLength(context.w, context.h); if (plength > 0) { /* apply padding to the <p> so that line padding does not cause line wraps */ var padmeasure = Math.ceil(plength) + "px"; if (context.bpd === "tb") { proc_e.style.paddingLeft = padmeasure; proc_e.style.paddingRight = padmeasure; } else { proc_e.style.paddingTop = padmeasure; proc_e.style.paddingBottom = padmeasure; } context.lp = lp; } } // do we have multiRowAlign? var mra = isd_element.styleAttrs[imscStyles.byName.multiRowAlign.qname]; if (mra && mra !== "auto") { /* create inline block to handle multirowAlign */ var s = document.createElement("span"); s.style.display = "inline-block"; s.style.textAlign = mra; e.appendChild(s); proc_e = s; context.mra = mra; } /* do we have rubyReserve? */ var rr = isd_element.styleAttrs[imscStyles.byName.rubyReserve.qname]; if (rr && rr[0] !== "none") { context.rubyReserve = rr; } /* remember we are filling line gaps */ if (isd_element.styleAttrs[imscStyles.byName.fillLineGap.qname]) { context.flg = true; } if (isd_element.kind === "span" && isd_element.text) { if (imscStyles.byName.textCombine.qname in isd_element.styleAttrs && isd_element.styleAttrs[imscStyles.byName.textCombine.qname][0] === "all") { /* ignore tate-chu-yoku since line break cannot happen within */ e.textContent = isd_element.text; } else { // wrap characters in spans to find the line wrap locations var cbuf = ''; for (var j = 0; j < isd_element.text.length; j++) { cbuf += isd_element.text.charAt(j); var cc = isd_element.text.charCodeAt(j); if (cc < 0xD800 || cc > 0xDBFF || j === isd_element.text.length) { /* wrap the character(s) in a span unless it is a high surrogate */ var span = document.createElement("span"); span.textContent = cbuf; e.appendChild(span); cbuf = ''; } } } } /* process the children of the ISD element */ for (var k in isd_element.contents) { processElement(context, proc_e, isd_element.contents[k]); } /* list of lines */ var linelist = []; /* paragraph processing */ /* TODO: linePadding only supported for horizontal scripts */ if ((context.lp || context.mra || context.flg || context.ruby || context.textEmphasis || context.rubyReserve) && isd_element.kind === "p") { constructLineList(context, proc_e, linelist, null); /* apply rubyReserve */ if (context.rubyReserve) { applyRubyReserve(linelist, context); context.rubyReserve = null; } /* apply tts:rubyPosition="outside" */ if (context.ruby || context.rubyReserve) { applyRubyPosition(linelist, context); context.ruby = null; } /* apply text emphasis "outside" position */ if (context.textEmphasis) { applyTextEmphasis(linelist, context); context.textEmphasis = null; } /* insert line breaks for multirowalign */ if (context.mra) { applyMultiRowAlign(linelist); context.mra = null; } /* add linepadding */ if (context.lp) { applyLinePadding(linelist, context.lp.toUsedLength(context.w, context.h), context); context.lp = null; } /* fill line gaps linepadding */ if (context.flg) { var par_edges = rect2edges(proc_e.getBoundingClientRect(), context); applyFillLineGap(linelist, par_edges.before, par_edges.after, context); context.flg = null; } } /* region processing */ if (isd_element.kind === "region") { /* build line list */ constructLineList(context, proc_e, linelist); /* perform roll up if needed */ if ((context.bpd === "tb") && context.enableRollUp && isd_element.contents.length > 0 && isd_element.styleAttrs[imscStyles.byName.displayAlign.qname] === 'after') { /* horrible hack, perhaps default region id should be underscore everywhere? */ var rid = isd_element.id === '' ? '_' : isd_element.id; var rb = new RegionPBuffer(rid, linelist); context.currentISDState[rb.id] = rb; if (context.previousISDState && rb.id in context.previousISDState && context.previousISDState[rb.id].plist.length > 0 && rb.plist.length > 1 && rb.plist[rb.plist.length - 2].text === context.previousISDState[rb.id].plist[context.previousISDState[rb.id].plist.length - 1].text) { var body_elem = e.firstElementChild; var h = rb.plist[rb.plist.length - 1].after - rb.plist[rb.plist.length - 1].before; body_elem.style.bottom = "-" + h + "px"; body_elem.style.transition = "transform 0.4s"; body_elem.style.position = "relative"; body_elem.style.transform = "translateY(-" + h + "px)"; } } /* TODO: clean-up the spans ? */ } } function applyLinePadding(lineList, lp, context) { for (var i in lineList) { var l = lineList[i].elements.length; var se = lineList[i].elements[lineList[i].start_elem]; var ee = lineList[i].elements[lineList[i].end_elem]; var pospadpxlen = Math.ceil(lp) + "px"; var negpadpxlen = "-" + Math.ceil(lp) + "px"; if (l !== 0) { if (context.ipd === "lr") { se.node.style.borderLeftColor = se.bgcolor || "#00000000"; se.node.style.borderLeftStyle = "solid"; se.node.style.borderLeftWidth = pospadpxlen; se.node.style.marginLeft = negpadpxlen; } else if (context.ipd === "rl") { se.node.style.borderRightColor = se.bgcolor || "#00000000"; se.node.style.borderRightStyle = "solid"; se.node.style.borderRightWidth = pospadpxlen; se.node.style.marginRight = negpadpxlen; } else if (context.ipd === "tb") { se.node.style.borderTopColor = se.bgcolor || "#00000000"; se.node.style.borderTopStyle = "solid"; se.node.style.borderTopWidth = pospadpxlen; se.node.style.marginTop = negpadpxlen; } if (context.ipd === "lr") { ee.node.style.borderRightColor = ee.bgcolor || "#00000000"; ee.node.style.borderRightStyle = "solid"; ee.node.style.borderRightWidth = pospadpxlen; ee.node.style.marginRight = negpadpxlen; } else if (context.ipd === "rl") { ee.node.style.borderLeftColor = ee.bgcolor || "#00000000"; ee.node.style.borderLeftStyle = "solid"; ee.node.style.borderLeftWidth = pospadpxlen; ee.node.style.marginLeft = negpadpxlen; } else if (context.ipd === "tb") { ee.node.style.borderBottomColor = ee.bgcolor || "#00000000"; ee.node.style.borderBottomStyle = "solid"; ee.node.style.borderBottomWidth = pospadpxlen; ee.node.style.marginBottom = negpadpxlen; } } } } function applyMultiRowAlign(lineList) { /* apply an explicit br to all but the last line */ for (var i = 0; i < lineList.length - 1; i++) { var l = lineList[i].elements.length; if (l !== 0 && lineList[i].br === false) { var br = document.createElement("br"); var lastnode = lineList[i].elements[l - 1].node; lastnode.parentElement.insertBefore(br, lastnode.nextSibling); } } } function applyTextEmphasis(lineList, context) { /* supports "outside" only */ for (var i = 0; i < lineList.length; i++) { for (var j = 0; j < lineList[i].te.length; j++) { /* skip if position already set */ if (lineList[i].te[j].style[TEXTEMPHASISPOSITION_PROP] && lineList[i].te[j].style[TEXTEMPHASISPOSITION_PROP] !== "none") continue; var pos; if (context.bpd === "tb") { pos = (i === 0) ? "left over" : "left under"; } else { if (context.bpd === "rl") { pos = (i === 0) ? "right under" : "left under"; } else { pos = (i === 0) ? "left under" : "right under"; } } lineList[i].te[j].style[TEXTEMPHASISPOSITION_PROP] = pos; } } } function applyRubyPosition(lineList, context) { for (var i = 0; i < lineList.length; i++) { for (var j = 0; j < lineList[i].rbc.length; j++) { /* skip if ruby-position already set */ if (lineList[i].rbc[j].style[RUBYPOSITION_PROP]) continue; var pos; if (RUBYPOSITION_ISWK) { /* WebKit exception */ pos = (i === 0) ? "before" : "after"; } else if (context.bpd === "tb") { pos = (i === 0) ? "over" : "under"; } else { if (context.bpd === "rl") { pos = (i === 0) ? "over" : "under"; } else { pos = (i === 0) ? "under" : "over"; } } lineList[i].rbc[j].style[RUBYPOSITION_PROP] = pos; } } } function applyRubyReserve(lineList, context) { for (var i = 0; i < lineList.length; i++) { var ruby = document.createElement("ruby"); var rb = document.createElement("rb"); rb.textContent = "\u200B"; ruby.appendChild(rb); var rt1; var rt2; var fs = context.rubyReserve[1].toUsedLength(context.w, context.h) + "px"; if (context.rubyReserve[0] === "both" || (context.rubyReserve[0] === "outside" && lineList.length == 1)) { rt1 = document.createElement("rtc"); rt1.style[RUBYPOSITION_PROP] = RUBYPOSITION_ISWK ? "after" : "under"; rt1.textContent = "\u200B"; rt1.style.fontSize = fs; rt2 = document.createElement("rtc"); rt2.style[RUBYPOSITION_PROP] = RUBYPOSITION_ISWK ? "before" : "over"; rt2.textContent = "\u200B"; rt2.style.fontSize = fs; ruby.appendChild(rt1); ruby.appendChild(rt2); } else { rt1 = document.createElement("rtc"); rt1.textContent = "\u200B"; rt1.style.fontSize = fs; var pos; if (context.rubyReserve[0] === "after" || (context.rubyReserve[0] === "outside" && i > 0)) { pos = RUBYPOSITION_ISWK ? "after" : ((context.bpd === "tb" || context.bpd === "rl") ? "under" : "over"); } else { pos = RUBYPOSITION_ISWK ? "before" : ((context.bpd === "tb" || context.bpd === "rl") ? "over" : "under"); } rt1.style[RUBYPOSITION_PROP] = pos; ruby.appendChild(rt1); } var e = lineList[i].elements[0].node.parentElement.insertBefore( ruby, lineList[i].elements[0].node ); } } function applyFillLineGap(lineList, par_before, par_after, context) { /* positive for BPD = lr and tb, negative for BPD = rl */ var s = Math.sign(par_after - par_before); for (var i = 0; i <= lineList.length; i++) { /* compute frontier between lines */ var frontier; if (i === 0) { frontier = par_before; } else if (i === lineList.length) { frontier = par_after; } else { frontier = (lineList[i].before + lineList[i - 1].after) / 2; } /* padding amount */ var pad; /* current element */ var e; /* before line */ if (i > 0) { for (var j = 0; j < lineList[i - 1].elements.length; j++) { if (lineList[i - 1].elements[j].bgcolor === null) continue; e = lineList[i - 1].elements[j]; if (s * (e.after - frontier) < 0) { pad = Math.ceil(Math.abs(frontier - e.after)) + "px"; e.node.style.backgroundColor = e.bgcolor; if (context.bpd === "lr") { e.node.style.paddingRight = pad; } else if (context.bpd === "rl") { e.node.style.paddingLeft = pad; } else if (context.bpd === "tb") { e.node.style.paddingBottom = pad; } } } } /* after line */ if (i < lineList.length) { for (var k = 0; k < lineList[i].elements.length; k++) { e = lineList[i].elements[k]; if (e.bgcolor === null) continue; if (s * (e.before - frontier) > 0) { pad = Math.ceil(Math.abs(e.before - frontier)) + "px"; e.node.style.backgroundColor = e.bgcolor; if (context.bpd === "lr") { e.node.style.paddingLeft = pad; } else if (context.bpd === "rl") { e.node.style.paddingRight = pad; } else if (context.bpd === "tb") { e.node.style.paddingTop = pad; } } } } } } function RegionPBuffer(id, lineList) { this.id = id; this.plist = lineList; } function rect2edges(rect, context) { var edges = {before: null, after: null, start: null, end: null}; if (context.bpd === "tb") { edges.before = rect.top; edges.after = rect.bottom; if (context.ipd === "lr") { edges.start = rect.left; edges.end = rect.right; } else { edges.start = rect.right; edges.end = rect.left; } } else if (context.bpd === "lr") { edges.before = rect.left; edges.after = rect.right; edges.start = rect.top; edges.end = rect.bottom; } else if (context.bpd === "rl") { edges.before = rect.right; edges.after = rect.left; edges.start = rect.top; edges.end = rect.bottom; } return edges; } function constructLineList(context, element, llist, bgcolor) { if (element.localName === "rt" || element.localName === "rtc") { /* skip ruby annotations */ return; } var curbgcolor = element.style.backgroundColor || bgcolor; if (element.childElementCount === 0) { if (element.localName === 'span' || element.localName === 'rb') { var r = element.getBoundingClientRect(); /* skip if span is not displayed */ if (r.height === 0 || r.width === 0) return; var edges = rect2edges(r, context); if (llist.length === 0 || (!isSameLine(edges.before, edges.after, llist[llist.length - 1].before, llist[llist.length - 1].after)) ) { llist.push({ before: edges.before, after: edges.after, start: edges.start, end: edges.end, start_elem: 0, end_elem: 0, elements: [], rbc: [], te: [], text: "", br: false }); } else { /* positive for BPD = lr and tb, negative for BPD = rl */ var bpd_dir = Math.sign(edges.after - edges.before); /* positive for IPD = lr and tb, negative for IPD = rl */ var ipd_dir = Math.sign(edges.end - edges.start); /* check if the line height has increased */ if (bpd_dir * (edges.before - llist[llist.length - 1].before) < 0) { llist[llist.length - 1].before = edges.before; } if (bpd_dir * (edges.after - llist[llist.length - 1].after) > 0) { llist[llist.length - 1].after = edges.after; } if (ipd_dir * (edges.start - llist[llist.length - 1].start) < 0) { llist[llist.length - 1].start = edges.start; llist[llist.length - 1].start_elem = llist[llist.length - 1].elements.length; } if (ipd_dir * (edges.end - llist[llist.length - 1].end) > 0) { llist[llist.length - 1].end = edges.end; llist[llist.length - 1].end_elem = llist[llist.length - 1].elements.length; } } llist[llist.length - 1].text += element.textContent; llist[llist.length - 1].elements.push( { node: element, bgcolor: curbgcolor, before: edges.before, after: edges.after } ); } else if (element.localName === 'br' && llist.length !== 0) { llist[llist.length - 1].br = true; } } else { var child = element.firstChild; while (child) { if (child.nodeType === Node.ELEMENT_NODE) { constructLineList(context, child, llist, curbgcolor); if (child.localName === 'ruby' || child.localName === 'rtc') { /* remember non-empty ruby and rtc elements so that tts:rubyPosition can be applied */ if (llist.length > 0) { llist[llist.length - 1].rbc.push(child); } } else if (child.localName === 'span' && child.style[TEXTEMPHASISSTYLE_PROP] && child.style[TEXTEMPHASISSTYLE_PROP] !== "none") { /* remember non-empty span elements with textEmphasis */ if (llist.length > 0) { llist[llist.length - 1].te.push(child); } } } child = child.nextSibling; } } } function isSameLine(before1, after1, before2, after2) { return ((after1 < after2) && (before1 > before2)) || ((after2 <= after1) && (before2 >= before1)); } function HTMLStylingMapDefintion(qName, mapFunc) { this.qname = qName; this.map = mapFunc; } var STYLING_MAP_DEFS = [ new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling backgroundColor", function (context, dom_element, isd_element, attr) { /* skip if transparent */ if (attr[3] === 0) return; dom_element.style.backgroundColor = "rgba(" + attr[0].toString() + "," + attr[1].toString() + "," + attr[2].toString() + "," + (attr[3] / 255).toString() + ")"; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling color", function (context, dom_element, isd_element, attr) { dom_element.style.color = "rgba(" + attr[0].toString() + "," + attr[1].toString() + "," + attr[2].toString() + "," + (attr[3] / 255).toString() + ")"; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling direction", function (context, dom_element, isd_element, attr) { dom_element.style.direction = attr; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling display", function (context, dom_element, isd_element, attr) {} ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling displayAlign", function (context, dom_element, isd_element, attr) { /* see https://css-tricks.com/snippets/css/a-guide-to-flexbox/ */ /* TODO: is this affected by writing direction? */ dom_element.style.display = "flex"; dom_element.style.flexDirection = "column"; if (attr === "before") { dom_element.style.justifyContent = "flex-start"; } else if (attr === "center") { dom_element.style.justifyContent = "center"; } else if (attr === "after") { dom_element.style.justifyContent = "flex-end"; } } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling extent", function (context, dom_element, isd_element, attr) { /* TODO: this is super ugly */ context.regionH = attr.h.toUsedLength(context.w, context.h); context.regionW = attr.w.toUsedLength(context.w, context.h); /* * CSS height/width are measured against the content rectangle, * whereas TTML height/width include padding */ var hdelta = 0; var wdelta = 0; var p = isd_element.styleAttrs["http://www.w3.org/ns/ttml#styling padding"]; if (!p) { /* error */ } else { hdelta = p[0].toUsedLength(context.w, context.h) + p[2].toUsedLength(context.w, context.h); wdelta = p[1].toUsedLength(context.w, context.h) + p[3].toUsedLength(context.w, context.h); } dom_element.style.height = (context.regionH - hdelta) + "px"; dom_element.style.width = (context.regionW - wdelta) + "px"; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling fontFamily", function (context, dom_element, isd_element, attr) { var rslt = []; /* per IMSC1 */ for (var i in attr) { if (attr[i] === "monospaceSerif") { rslt.push("Courier New"); rslt.push('"Liberation Mono"'); rslt.push("Courier"); rslt.push("monospace"); } else if (attr[i] === "proportionalSansSerif") { rslt.push("Arial"); rslt.push("Helvetica"); rslt.push('"Liberation Sans"'); rslt.push("sans-serif"); } else if (attr[i] === "monospace") { rslt.push("monospace"); } else if (attr[i] === "sansSerif") { rslt.push("sans-serif"); } else if (attr[i] === "serif") { rslt.push("serif"); } else if (attr[i] === "monospaceSansSerif") { rslt.push("Consolas"); rslt.push("monospace"); } else if (attr[i] === "proportionalSerif") { rslt.push("serif"); } else { rslt.push(attr[i]); } } dom_element.style.fontFamily = rslt.join(","); } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling shear", function (context, dom_element, isd_element, attr) { /* return immediately if tts:shear is 0% since CSS transforms are not inherited*/ if (attr === 0) return; var angle = attr * -0.9; /* context.writingMode is needed since writing mode is not inherited and sets the inline progression */ if (context.bpd === "tb") { dom_element.style.transform = "skewX(" + angle + "deg)"; } else { dom_element.style.transform = "skewY(" + angle + "deg)"; } } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling fontSize", function (context, dom_element, isd_element, attr) { dom_element.style.fontSize = attr.toUsedLength(context.w, context.h) + "px"; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling fontStyle", function (context, dom_element, isd_element, attr) { dom_element.style.fontStyle = attr; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling fontWeight", function (context, dom_element, isd_element, attr) { dom_element.style.fontWeight = attr; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling lineHeight", function (context, dom_element, isd_element, attr) { if (attr === "normal") { dom_element.style.lineHeight = "normal"; } else { dom_element.style.lineHeight = attr.toUsedLength(context.w, context.h) + "px"; } } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling opacity", function (context, dom_element, isd_element, attr) { dom_element.style.opacity = attr; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling origin", function (context, dom_element, isd_element, attr) { dom_element.style.top = attr.h.toUsedLength(context.w, context.h) + "px"; dom_element.style.left = attr.w.toUsedLength(context.w, context.h) + "px"; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling overflow", function (context, dom_element, isd_element, attr) { dom_element.style.overflow = attr; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling padding", function (context, dom_element, isd_element, attr) { /* attr: top,left,bottom,right*/ /* style: top right bottom left*/ var rslt = []; rslt[0] = attr[0].toUsedLength(context.w, context.h) + "px"; rslt[1] = attr[3].toUsedLength(context.w, context.h) + "px"; rslt[2] = attr[2].toUsedLength(context.w, context.h) + "px"; rslt[3] = attr[1].toUsedLength(context.w, context.h) + "px"; dom_element.style.padding = rslt.join(" "); } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling position", function (context, dom_element, isd_element, attr) { dom_element.style.top = attr.h.toUsedLength(context.w, context.h) + "px"; dom_element.style.left = attr.w.toUsedLength(context.w, context.h) + "px"; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling rubyAlign", function (context, dom_element, isd_element, attr) { dom_element.style.rubyAlign = attr; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling rubyPosition", function (context, dom_element, isd_element, attr) { /* skip if "outside", which is handled by applyRubyPosition() */ if (attr === "before" || attr === "after") { var pos; if (RUBYPOSITION_ISWK) { /* WebKit exception */ pos = attr; } else if (context.bpd === "tb") { pos = (attr === "before") ? "over" : "under"; } else { if (context.bpd === "rl") { pos = (attr === "before") ? "over" : "under"; } else { pos = (attr === "before") ? "under" : "over"; } } /* apply position to the parent dom_element, i.e. ruby or rtc */ dom_element.parentElement.style[RUBYPOSITION_PROP] = pos; } } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling showBackground", null ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling textAlign", function (context, dom_element, isd_element, attr) { var ta; var dir = isd_element.styleAttrs[imscStyles.byName.direction.qname]; /* handle UAs that do not understand start or end */ if (attr === "start") { ta = (dir === "rtl") ? "right" : "left"; } else if (attr === "end") { ta = (dir === "rtl") ? "left" : "right"; } else { ta = attr; } dom_element.style.textAlign = ta; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling textDecoration", function (context, dom_element, isd_element, attr) { dom_element.style.textDecoration = attr.join(" ").replace("lineThrough", "line-through"); } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling textOutline", function (context, dom_element, isd_element, attr) { /* defer to tts:textShadow */ } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling textShadow", function (context, dom_element, isd_element, attr) { var txto = isd_element.styleAttrs[imscStyles.byName.textOutline.qname]; if (attr === "none" && txto === "none") { dom_element.style.textShadow = ""; } else { var s = []; if (txto !== "none") { /* emulate text outline */ var to_color = "rgba(" + txto.color[0].toString() + "," + txto.color[1].toString() + "," + txto.color[2].toString() + "," + (txto.color[3] / 255).toString() + ")"; s.push( "1px 1px 1px " + to_color); s.push( "-1px 1px 1px " + to_color); s.push( "1px -1px 1px " + to_color); s.push( "-1px -1px 1px " + to_color); } /* add text shadow */ if (attr !== "none") { for (var i in attr) { s.push(attr[i].x_off.toUsedLength(context.w, context.h) + "px " + attr[i].y_off.toUsedLength(context.w, context.h) + "px " + attr[i].b_radius.toUsedLength(context.w, context.h) + "px " + "rgba(" + attr[i].color[0].toString() + "," + attr[i].color[1].toString() + "," + attr[i].color[2].toString() + "," + (attr[i].color[3] / 255).toString() + ")" ); } } dom_element.style.textShadow = s.join(","); } } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling textCombine", function (context, dom_element, isd_element, attr) { dom_element.style.textCombineUpright = attr.join(" "); } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling textEmphasis", function (context, dom_element, isd_element, attr) { /* ignore color (not used in IMSC 1.1) */ if (attr.style === "none") { dom_element.style[TEXTEMPHASISSTYLE_PROP] = "none"; /* no need to set position, so return */ return; } else if (attr.style === "auto") { dom_element.style[TEXTEMPHASISSTYLE_PROP] = "filled"; } else { dom_element.style[TEXTEMPHASISSTYLE_PROP] = attr.style + " " + attr.symbol; } /* ignore "outside" position (set in postprocessing) */ if (attr.position === "before" || attr.position === "after") { var pos; if (context.bpd === "tb") { pos = (attr.position === "before") ? "left over" : "left under"; } else { if (context.bpd === "rl") { pos = (attr.position === "before") ? "right under" : "left under"; } else { pos = (attr.position === "before") ? "left under" : "right under"; } } dom_element.style[TEXTEMPHASISPOSITION_PROP] = pos; } } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling unicodeBidi", function (context, dom_element, isd_element, attr) { var ub; if (attr === 'bidiOverride') { ub = "bidi-override"; } else { ub = attr; } dom_element.style.unicodeBidi = ub; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling visibility", function (context, dom_element, isd_element, attr) { dom_element.style.visibility = attr; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling wrapOption", function (context, dom_element, isd_element, attr) { if (attr === "wrap") { if (isd_element.space === "preserve") { dom_element.style.whiteSpace = "pre-wrap"; } else { dom_element.style.whiteSpace = "normal"; } } else { if (isd_element.space === "preserve") { dom_element.style.whiteSpace = "pre"; } else { dom_element.style.whiteSpace = "noWrap"; } } } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling writingMode", function (context, dom_element, isd_element, attr) { if (attr === "lrtb" || attr === "lr") { context.writingMode = "horizontal-tb"; } else if (attr === "rltb" || attr === "rl") { context.writingMode = "horizontal-tb"; } else if (attr === "tblr") { context.writingMode = "vertical-lr"; } else if (attr === "tbrl" || attr === "tb") { context.writingMode = "vertical-rl"; } dom_element.style.writingMode = context.writingMode; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml#styling zIndex", function (context, dom_element, isd_element, attr) { dom_element.style.zIndex = attr; } ), new HTMLStylingMapDefintion( "http://www.w3.org/ns/ttml/profile/imsc1#styling forcedDisplay", function (context, dom_element, isd_element, attr) { if (context.displayForcedOnlyMode && attr === false) { dom_element.style.visibility = "hidden"; } } ) ]; var STYLMAP_BY_QNAME = {}; for (var i in STYLING_MAP_DEFS) { STYLMAP_BY_QNAME[STYLING_MAP_DEFS[i].qname] = STYLING_MAP_DEFS[i]; } /* CSS property names */ var RUBYPOSITION_ISWK = "webkitRubyPosition" in window.getComputedStyle(document.documentElement); var RUBYPOSITION_PROP = RUBYPOSITION_ISWK ? "webkitRubyPosition" : "rubyPosition"; var TEXTEMPHASISSTYLE_PROP = "webkitTextEmphasisStyle" in window.getComputedStyle(document.documentElement) ? "webkitTextEmphasisStyle" : "textEmphasisStyle"; var TEXTEMPHASISPOSITION_PROP = "webkitTextEmphasisPosition" in window.getComputedStyle(document.documentElement) ? "webkitTextEmphasisPosition" : "textEmphasisPosition"; /* error utilities */ function reportError(errorHandler, msg) { if (errorHandler && errorHandler.error && errorHandler.error(msg)) throw msg; } })(typeof exports === 'undefined' ? this.imscHTML = {} : exports, typeof imscNames === 'undefined' ? require("./names") : imscNames, typeof imscStyles === 'undefined' ? require("./styles") : imscStyles, typeof imscUtils === 'undefined' ? require("./utils") : imscUtils);
Fixed tts:rubyReserve on lines starting with a ruby container (#184)
src/main/js/html.js
Fixed tts:rubyReserve on lines starting with a ruby container (#184)
<ide><path>rc/main/js/html.js <ide> <ide> } <ide> <del> var e = lineList[i].elements[0].node.parentElement.insertBefore( <del> ruby, <del> lineList[i].elements[0].node <del> ); <add> /* add in front of the first ruby element of the line, if it exists */ <add> <add> var sib = null; <add> <add> for (var j = 0; j < lineList[i].rbc.length; j++) { <add> <add> if (lineList[i].rbc[j].localName === 'ruby') { <add> <add> sib = lineList[i].rbc[j]; <add> <add> /* copy specified style properties from the sibling ruby container */ <add> <add> for(var k = 0; k < sib.style.length; k++) { <add> <add> ruby.style.setProperty(sib.style.item(k), sib.style.getPropertyValue(sib.style.item(k))); <add> <add> } <add> <add> break; <add> } <add> <add> } <add> <add> /* otherwise add before first span */ <add> <add> sib = sib || lineList[i].elements[0].node; <add> <add> sib.parentElement.insertBefore(ruby, sib); <ide> <ide> } <ide>
JavaScript
mit
27e04ccc87f823f5c69f5d73537d085d19998fc3
0
bullcitydave/petviner
//Build the Model var Vine = Backbone.Model.extend ({ defaults: function(){ return { postId: '', created: '', videoUrl: '', username: '', permalinkUrl:'' }; }, idAttribute: "postId" }); //Instantiate the Model var vine = new Vine(); var VineCollection = Backbone.Collection.extend ({ model: Vine, // url: 'https://api.vineapp.com/timelines/tags/cat', url: 'http://www.mocky.io/v2/53cb43667313bbe4019ef820', parse: function(results) { return results.data.records; }, sync: function(method, model, options) { var that = this; var params = _.extend({ type: 'GET', dataType: 'jsonp', url: that.url, processData: false }, options); return $.ajax(params); } }); //Instantiate the Collection var vineCollection = new VineCollection({ }); //View for our vine collection var VineListView = Backbone.View.extend ({ className : 'list', initialize:function(){ var self = this; this.collection.fetch({ success: function(){ console.log('Yay!'); console.log(this.collection); } }).done(function(){ self.render(); }); }, render: function () { var source = $('#vine-list-template').html(); var template = Handlebars.compile(source); var rendered = template({vineCollection: this.collection.toJSON()}); this.$el.html(rendered); console.log('Collection rendered to page') return this; } }); //Instantiate the Vine List view var vineListView = new VineListView ({ collection: vineCollection }); var VineSingleView = Backbone.View.extend({ initialize: function(){ console.log('Initializing single vine view'); }, render: function(id){ var source = $('#vine-single-template').html(); var template = Handlebars.compile(source); console.log('Attempting to render model id' + id); // var rendered = template({vine: vineCollection.get(id).toJSON()}); // this.$el.html(rendered); var m = vineCollection.get(id); this.$el.html(template(m.toJSON())); // .done(function(){ return this; // }); } }); var vineSingleView = new VineSingleView ({ className : 'vine-single' });
app/scripts/main.js
//Build the Model var Vine = Backbone.Model.extend ({ defaults: function(){ return { postId: '', created: '', videoUrl: '', username: '', permalinkUrl:'' }; }, idAttribute: "postId" }); //Instantiate the Model var vine = new Vine(); var VineCollection = Backbone.Collection.extend ({ model: Vine, // url: 'https://api.vineapp.com/timelines/tags/cat', url: 'http://www.mocky.io/v2/53cb43667313bbe4019ef820', parse: function(results) { return results.data.records; }, sync: function(method, model, options) { var that = this; var params = _.extend({ type: 'GET', dataType: 'jsonp', url: that.url, processData: false }, options); return $.ajax(params); } }); //Instantiate the Collection var vineCollection = new VineCollection({ }); //View for our vine collection var VineListView = Backbone.View.extend ({ className : 'list', initialize:function(){ var self = this; this.collection.fetch({ success: function(){ console.log('Yay!'); console.log(this.collection); } }).done(function(){ self.render(); }); }, render: function () { var source = $('#vine-list-template').html(); var template = Handlebars.compile(source); var rendered = template({vineCollection: this.collection.toJSON()}); this.$el.html(rendered); console.log('Collection rendered to page') return this; } }); //Instantiate the Vine List view var vineListView = new VineListView ({ collection: vineCollection }); var VineSingleView = Backbone.View.extend({ initialize: function(){ console.log('Initializing single vine view'); }, render: function(id){ var source = $('#vine-single-template').html(); var template = Handlebars.compile(source); var rendered = template({vine: vineCollection.get(id).toJSON()}); this.$el.html(rendered); return this; } }); var vineSingleView = new VineSingleView ({ className : 'vine-single' });
Single view is rendering after getting singleview render template function syntax and parameters fixed
app/scripts/main.js
Single view is rendering after getting singleview render template function syntax and parameters fixed
<ide><path>pp/scripts/main.js <ide> render: function(id){ <ide> var source = $('#vine-single-template').html(); <ide> var template = Handlebars.compile(source); <del> var rendered = template({vine: vineCollection.get(id).toJSON()}); <del> this.$el.html(rendered); <del> return this; <add> console.log('Attempting to render model id' + id); <add> // var rendered = template({vine: vineCollection.get(id).toJSON()}); <add> // this.$el.html(rendered); <add> var m = vineCollection.get(id); <add> this.$el.html(template(m.toJSON())); <add> // .done(function(){ <add> return this; <add> // }); <ide> } <ide> <ide>
Java
apache-2.0
799997b0605583974c584acab31667cad1e33943
0
francisliu/hbase_namespace,francisliu/hbase_namespace,francisliu/hbase_namespace,francisliu/hbase_namespace,francisliu/hbase_namespace,francisliu/hbase_namespace,francisliu/hbase_namespace,francisliu/hbase_namespace,francisliu/hbase_namespace
/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.master; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Chore; import org.apache.hadoop.hbase.ClusterStatus; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; import org.apache.hadoop.hbase.util.Pair; import org.apache.hadoop.hbase.util.Threads; import org.apache.hadoop.hbase.util.VersionInfo; import org.jboss.netty.bootstrap.ConnectionlessBootstrap; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelUpstreamHandler; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.DatagramChannel; import org.jboss.netty.channel.socket.DatagramChannelFactory; import org.jboss.netty.channel.socket.oio.OioDatagramChannelFactory; import org.jboss.netty.handler.codec.protobuf.ProtobufEncoder; import java.io.Closeable; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Class to publish the cluster status to the client. This allows them to know immediately * the dead region servers, hence to cut the connection they have with them, eventually stop * waiting on the socket. This improves the mean time to recover, and as well allows to increase * on the client the different timeouts, as the dead servers will be detected separately. */ @InterfaceAudience.Private public class ClusterStatusPublisher extends Chore { /** * The implementation class used to publish the status. Default is null (no publish). * Use org.apache.hadoop.hbase.master.ClusterStatusPublisher.MulticastPublisher to multicast the * status. */ public static final String STATUS_PUBLISHER_CLASS = "hbase.status.publisher.class"; public static final Class<? extends ClusterStatusPublisher.Publisher> DEFAULT_STATUS_PUBLISHER_CLASS = null; /** * The minimum time between two status messages, in milliseconds. */ public static final String STATUS_PUBLISH_PERIOD = "hbase.status.publish.period"; public static final int DEFAULT_STATUS_PUBLISH_PERIOD = 10000; private long lastMessageTime = 0; private final HMaster master; private final int messagePeriod; // time between two message private final ConcurrentMap<ServerName, Integer> lastSent = new ConcurrentHashMap<ServerName, Integer>(); private Publisher publisher; private boolean connected = false; /** * We want to limit the size of the protobuf message sent, do fit into a single packet. * a reasonable size for ip / ethernet is less than 1Kb. */ public static int MAX_SERVER_PER_MESSAGE = 10; /** * If a server dies, we're sending the information multiple times in case a receiver misses the * message. */ public static int NB_SEND = 5; public ClusterStatusPublisher(HMaster master, Configuration conf, Class<? extends Publisher> publisherClass) throws IOException { super("HBase clusterStatusPublisher for " + master.getName(), conf.getInt(STATUS_PUBLISH_PERIOD, DEFAULT_STATUS_PUBLISH_PERIOD), master); this.master = master; this.messagePeriod = conf.getInt(STATUS_PUBLISH_PERIOD, DEFAULT_STATUS_PUBLISH_PERIOD); try { this.publisher = publisherClass.newInstance(); } catch (InstantiationException e) { throw new IOException("Can't create publisher " + publisherClass.getName(), e); } catch (IllegalAccessException e) { throw new IOException("Can't create publisher " + publisherClass.getName(), e); } this.publisher.connect(conf); connected = true; } // For tests only protected ClusterStatusPublisher() { master = null; messagePeriod = 0; } @Override protected void chore() { if (!connected) { return; } List<ServerName> sns = generateDeadServersListToSend(); if (sns.isEmpty()) { // Nothing to send. Done. return; } final long curTime = EnvironmentEdgeManager.currentTimeMillis(); if (lastMessageTime > curTime - messagePeriod) { // We already sent something less than 10 second ago. Done. return; } // Ok, we're going to send something then. lastMessageTime = curTime; // We're reusing an existing protobuf message, but we don't send everything. // This could be extended in the future, for example if we want to send stuff like the // META server name. ClusterStatus cs = new ClusterStatus(VersionInfo.getVersion(), master.getMasterFileSystem().getClusterId().toString(), null, sns, master.getServerName(), null, null, null, null); publisher.publish(cs); } protected void cleanup() { connected = false; publisher.close(); } /** * Create the dead server to send. A dead server is sent NB_SEND times. We send at max * MAX_SERVER_PER_MESSAGE at a time. if there are too many dead servers, we send the newly * dead first. */ protected List<ServerName> generateDeadServersListToSend() { // We're getting the message sent since last time, and add them to the list long since = EnvironmentEdgeManager.currentTimeMillis() - messagePeriod * 2; for (Pair<ServerName, Long> dead : getDeadServers(since)) { lastSent.putIfAbsent(dead.getFirst(), 0); } // We're sending the new deads first. List<Map.Entry<ServerName, Integer>> entries = new ArrayList<Map.Entry<ServerName, Integer>>(); entries.addAll(lastSent.entrySet()); Collections.sort(entries, new Comparator<Map.Entry<ServerName, Integer>>() { @Override public int compare(Map.Entry<ServerName, Integer> o1, Map.Entry<ServerName, Integer> o2) { return o1.getValue().compareTo(o2.getValue()); } }); // With a limit of MAX_SERVER_PER_MESSAGE int max = entries.size() > MAX_SERVER_PER_MESSAGE ? MAX_SERVER_PER_MESSAGE : entries.size(); List<ServerName> res = new ArrayList<ServerName>(max); for (int i = 0; i < max; i++) { Map.Entry<ServerName, Integer> toSend = entries.get(i); if (toSend.getValue() >= (NB_SEND - 1)) { lastSent.remove(toSend.getKey()); } else { lastSent.replace(toSend.getKey(), toSend.getValue(), toSend.getValue() + 1); } res.add(toSend.getKey()); } return res; } /** * Get the servers which died since a given timestamp. * protected because it can be subclassed by the tests. */ protected List<Pair<ServerName, Long>> getDeadServers(long since) { if (master.getServerManager() == null) { return Collections.emptyList(); } return master.getServerManager().getDeadServers().copyDeadServersSince(since); } public static interface Publisher extends Closeable { public void connect(Configuration conf) throws IOException; public void publish(ClusterStatus cs); @Override public void close(); } public static class MulticastPublisher implements Publisher { private DatagramChannel channel; private final ExecutorService service = Executors.newSingleThreadExecutor( Threads.newDaemonThreadFactory("hbase-master-clusterStatus-worker")); public MulticastPublisher() { } @Override public void connect(Configuration conf) throws IOException { String mcAddress = conf.get(HConstants.STATUS_MULTICAST_ADDRESS, HConstants.DEFAULT_STATUS_MULTICAST_ADDRESS); int port = conf.getInt(HConstants.STATUS_MULTICAST_PORT, HConstants.DEFAULT_STATUS_MULTICAST_PORT); // Can't be NiO with Netty today => not implemented in Netty. DatagramChannelFactory f = new OioDatagramChannelFactory(service); ConnectionlessBootstrap b = new ConnectionlessBootstrap(f); b.setPipeline(Channels.pipeline(new ProtobufEncoder(), new ChannelUpstreamHandler() { @Override public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { // We're just writing here. Discard any incoming data. See HBASE-8466. } })); channel = (DatagramChannel) b.bind(new InetSocketAddress(0)); channel.getConfig().setReuseAddress(true); InetAddress ina; try { ina = InetAddress.getByName(mcAddress); } catch (UnknownHostException e) { throw new IOException("Can't connect to " + mcAddress, e); } channel.joinGroup(ina); channel.connect(new InetSocketAddress(mcAddress, port)); } @Override public void publish(ClusterStatus cs) { ClusterStatusProtos.ClusterStatus csp = cs.convert(); channel.write(csp); } @Override public void close() { if (channel != null) { channel.close(); } service.shutdown(); } } }
hbase-server/src/main/java/org/apache/hadoop/hbase/master/ClusterStatusPublisher.java
/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.master; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Chore; import org.apache.hadoop.hbase.ClusterStatus; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; import org.apache.hadoop.hbase.util.Pair; import org.apache.hadoop.hbase.util.Threads; import org.apache.hadoop.hbase.util.VersionInfo; import org.jboss.netty.bootstrap.ConnectionlessBootstrap; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.DatagramChannel; import org.jboss.netty.channel.socket.DatagramChannelFactory; import org.jboss.netty.channel.socket.oio.OioDatagramChannelFactory; import org.jboss.netty.handler.codec.protobuf.ProtobufEncoder; import java.io.Closeable; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Class to publish the cluster status to the client. This allows them to know immediately * the dead region servers, hence to cut the connection they have with them, eventually stop * waiting on the socket. This improves the mean time to recover, and as well allows to increase * on the client the different timeouts, as the dead servers will be detected separately. */ @InterfaceAudience.Private public class ClusterStatusPublisher extends Chore { /** * The implementation class used to publish the status. Default is null (no publish). * Use org.apache.hadoop.hbase.master.ClusterStatusPublisher.MulticastPublisher to multicast the * status. */ public static final String STATUS_PUBLISHER_CLASS = "hbase.status.publisher.class"; public static final Class<? extends ClusterStatusPublisher.Publisher> DEFAULT_STATUS_PUBLISHER_CLASS = null; /** * The minimum time between two status messages, in milliseconds. */ public static final String STATUS_PUBLISH_PERIOD = "hbase.status.publish.period"; public static final int DEFAULT_STATUS_PUBLISH_PERIOD = 10000; private long lastMessageTime = 0; private final HMaster master; private final int messagePeriod; // time between two message private final ConcurrentMap<ServerName, Integer> lastSent = new ConcurrentHashMap<ServerName, Integer>(); private Publisher publisher; private boolean connected = false; /** * We want to limit the size of the protobuf message sent, do fit into a single packet. * a reasonable size for ip / ethernet is less than 1Kb. */ public static int MAX_SERVER_PER_MESSAGE = 10; /** * If a server dies, we're sending the information multiple times in case a receiver misses the * message. */ public static int NB_SEND = 5; public ClusterStatusPublisher(HMaster master, Configuration conf, Class<? extends Publisher> publisherClass) throws IOException { super("HBase clusterStatusPublisher for " + master.getName(), conf.getInt(STATUS_PUBLISH_PERIOD, DEFAULT_STATUS_PUBLISH_PERIOD), master); this.master = master; this.messagePeriod = conf.getInt(STATUS_PUBLISH_PERIOD, DEFAULT_STATUS_PUBLISH_PERIOD); try { this.publisher = publisherClass.newInstance(); } catch (InstantiationException e) { throw new IOException("Can't create publisher " + publisherClass.getName(), e); } catch (IllegalAccessException e) { throw new IOException("Can't create publisher " + publisherClass.getName(), e); } this.publisher.connect(conf); connected = true; } // For tests only protected ClusterStatusPublisher() { master = null; messagePeriod = 0; } @Override protected void chore() { if (!connected) { return; } List<ServerName> sns = generateDeadServersListToSend(); if (sns.isEmpty()) { // Nothing to send. Done. return; } final long curTime = EnvironmentEdgeManager.currentTimeMillis(); if (lastMessageTime > curTime - messagePeriod) { // We already sent something less than 10 second ago. Done. return; } // Ok, we're going to send something then. lastMessageTime = curTime; // We're reusing an existing protobuf message, but we don't send everything. // This could be extended in the future, for example if we want to send stuff like the // META server name. ClusterStatus cs = new ClusterStatus(VersionInfo.getVersion(), master.getMasterFileSystem().getClusterId().toString(), null, sns, master.getServerName(), null, null, null, null); publisher.publish(cs); } protected void cleanup() { connected = false; publisher.close(); } /** * Create the dead server to send. A dead server is sent NB_SEND times. We send at max * MAX_SERVER_PER_MESSAGE at a time. if there are too many dead servers, we send the newly * dead first. */ protected List<ServerName> generateDeadServersListToSend() { // We're getting the message sent since last time, and add them to the list long since = EnvironmentEdgeManager.currentTimeMillis() - messagePeriod * 2; for (Pair<ServerName, Long> dead : getDeadServers(since)) { lastSent.putIfAbsent(dead.getFirst(), 0); } // We're sending the new deads first. List<Map.Entry<ServerName, Integer>> entries = new ArrayList<Map.Entry<ServerName, Integer>>(); entries.addAll(lastSent.entrySet()); Collections.sort(entries, new Comparator<Map.Entry<ServerName, Integer>>() { @Override public int compare(Map.Entry<ServerName, Integer> o1, Map.Entry<ServerName, Integer> o2) { return o1.getValue().compareTo(o2.getValue()); } }); // With a limit of MAX_SERVER_PER_MESSAGE int max = entries.size() > MAX_SERVER_PER_MESSAGE ? MAX_SERVER_PER_MESSAGE : entries.size(); List<ServerName> res = new ArrayList<ServerName>(max); for (int i = 0; i < max; i++) { Map.Entry<ServerName, Integer> toSend = entries.get(i); if (toSend.getValue() >= (NB_SEND - 1)) { lastSent.remove(toSend.getKey()); } else { lastSent.replace(toSend.getKey(), toSend.getValue(), toSend.getValue() + 1); } res.add(toSend.getKey()); } return res; } /** * Get the servers which died since a given timestamp. * protected because it can be subclassed by the tests. */ protected List<Pair<ServerName, Long>> getDeadServers(long since) { if (master.getServerManager() == null) { return Collections.emptyList(); } return master.getServerManager().getDeadServers().copyDeadServersSince(since); } public static interface Publisher extends Closeable { public void connect(Configuration conf) throws IOException; public void publish(ClusterStatus cs); @Override public void close(); } public static class MulticastPublisher implements Publisher { private DatagramChannel channel; private final ExecutorService service = Executors.newSingleThreadExecutor( Threads.newDaemonThreadFactory("hbase-master-clusterStatus-worker")); public MulticastPublisher() { } @Override public void connect(Configuration conf) throws IOException { String mcAddress = conf.get(HConstants.STATUS_MULTICAST_ADDRESS, HConstants.DEFAULT_STATUS_MULTICAST_ADDRESS); int port = conf.getInt(HConstants.STATUS_MULTICAST_PORT, HConstants.DEFAULT_STATUS_MULTICAST_PORT); // Can't be NiO with Netty today => not implemented in Netty. DatagramChannelFactory f = new OioDatagramChannelFactory(service); ConnectionlessBootstrap b = new ConnectionlessBootstrap(f); b.setPipeline(Channels.pipeline(new ProtobufEncoder())); channel = (DatagramChannel) b.bind(new InetSocketAddress(0)); channel.getConfig().setReuseAddress(true); InetAddress ina; try { ina = InetAddress.getByName(mcAddress); } catch (UnknownHostException e) { throw new IOException("Can't connect to " + mcAddress, e); } channel.joinGroup(ina); channel.connect(new InetSocketAddress(mcAddress, port)); } @Override public void publish(ClusterStatus cs) { ClusterStatusProtos.ClusterStatus csp = cs.convert(); channel.write(csp); } @Override public void close() { if (channel != null) { channel.close(); } service.shutdown(); } } }
HBASE-8466 Netty messages in the logs git-svn-id: 949c06ec81f1cb709fd2be51dd530a930344d7b3@1478664 13f79535-47bb-0310-9956-ffa450edef68
hbase-server/src/main/java/org/apache/hadoop/hbase/master/ClusterStatusPublisher.java
HBASE-8466 Netty messages in the logs
<ide><path>base-server/src/main/java/org/apache/hadoop/hbase/master/ClusterStatusPublisher.java <ide> import org.apache.hadoop.hbase.util.Threads; <ide> import org.apache.hadoop.hbase.util.VersionInfo; <ide> import org.jboss.netty.bootstrap.ConnectionlessBootstrap; <add>import org.jboss.netty.channel.ChannelEvent; <add>import org.jboss.netty.channel.ChannelHandlerContext; <add>import org.jboss.netty.channel.ChannelUpstreamHandler; <ide> import org.jboss.netty.channel.Channels; <ide> import org.jboss.netty.channel.socket.DatagramChannel; <ide> import org.jboss.netty.channel.socket.DatagramChannelFactory; <ide> DatagramChannelFactory f = new OioDatagramChannelFactory(service); <ide> <ide> ConnectionlessBootstrap b = new ConnectionlessBootstrap(f); <del> b.setPipeline(Channels.pipeline(new ProtobufEncoder())); <add> b.setPipeline(Channels.pipeline(new ProtobufEncoder(), <add> new ChannelUpstreamHandler() { <add> @Override <add> public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) <add> throws Exception { <add> // We're just writing here. Discard any incoming data. See HBASE-8466. <add> } <add> })); <ide> <ide> <ide> channel = (DatagramChannel) b.bind(new InetSocketAddress(0));
Java
agpl-3.0
180ce761d952c9fea7331c9a6367dbc9588b584d
0
itsjeyd/ODE,itsjeyd/ODE,itsjeyd/ODE,itsjeyd/ODE
import org.junit.*; import play.test.*; import play.libs.F.*; import static play.test.Helpers.*; import static org.fest.assertions.Assertions.*; public class IntegrationTest { /** * Add your integration tests here. * In this example we just check if the home page is being shown. */ @Test public void test() { running( testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, new Callback<TestBrowser>() { public void invoke(TestBrowser browser) { browser.goTo("http://localhost:3333"); assertThat( browser.pageSource()).contains("Hi! This is Ode."); } }); } }
ode/test/IntegrationTest.java
import org.junit.*; import play.test.*; import play.libs.F.*; import static play.test.Helpers.*; import static org.fest.assertions.Assertions.*; public class IntegrationTest { /** * add your integration test here * in this example we just check if the welcome page is being shown */ @Test public void test() { running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, new Callback<TestBrowser>() { public void invoke(TestBrowser browser) { browser.goTo("http://localhost:3333"); assertThat(browser.pageSource()).contains("Your new application is ready."); } }); } }
Make example integration test pass.
ode/test/IntegrationTest.java
Make example integration test pass.
<ide><path>de/test/IntegrationTest.java <ide> public class IntegrationTest { <ide> <ide> /** <del> * add your integration test here <del> * in this example we just check if the welcome page is being shown <add> * Add your integration tests here. <add> * In this example we just check if the home page is being shown. <ide> */ <ide> @Test <ide> public void test() { <del> running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, new Callback<TestBrowser>() { <add> running( <add> testServer(3333, fakeApplication(inMemoryDatabase())), <add> HTMLUNIT, new Callback<TestBrowser>() { <ide> public void invoke(TestBrowser browser) { <ide> browser.goTo("http://localhost:3333"); <del> assertThat(browser.pageSource()).contains("Your new application is ready."); <add> assertThat( <add> browser.pageSource()).contains("Hi! This is Ode."); <ide> } <ide> }); <ide> }
JavaScript
isc
3e9daa9f71da8bc5c3aad2cbde08f0eabd667aeb
0
xdv/ripplecharts-frontend,shekenahglory/ripplecharts-frontend,xdv/ripplecharts-frontend,bankonme/ripplecharts-frontend,ripple/ripplecharts-frontend,ripple/ripplecharts-frontend,shekenahglory/ripplecharts-frontend,bankonme/ripplecharts-frontend
(function() { ripple.currencyDropdown = function(gateways, old, fixed) { var event = d3.dispatch("change"); var select; var loaded = false; function dropdown(selection) { if (old) selection.call(oldDropdowns, fixed); else selection.call(loadDropdowns); } dropdown.selected = function(_) { return arguments.length ? (select = _, dropdown) : select; }; function loadDropdowns(selection) { selection.html(""); var theme = store.get("theme") || store.session.get("theme") || "light"; var selectionId; if (selection.attr("id") === "quote") selectionId = "trade"; else selectionId = selection.attr("id"); var currencies = gateways.getCurrencies(); var currencySelect = selection.append("select").attr("class", "currency").attr("id", selectionId+"_currency"); var gatewaySelect = selection.append("select").attr("class","gateway").attr("id", selectionId+"_gateway"); //format currnecies for dropdowns var i = currencies.length; while (i--) { if (!currencies[i].include) { currencies.splice(i, 1); } else { currencies[i] = { text : ripple.Currency.from_json(currencies[i].currency).to_human().substring(0,3), value : i, currency : currencies[i].currency, imageSrc : currencies[i].icon }; if (select.currency === currencies[i].currency) currencies[i].selected = true; } } $("#"+selectionId+"_currency").ddslick({ data: currencies, imagePosition: "left", width: "120px", onSelected: function (data) { if (!loaded) { changeCurrency(data.selectedData.currency); } else if (data.selectedData.currency !== select.currency) { changeCurrency(data.selectedData.currency); } } }); editList(selectionId, 'gateway'); editList(selectionId, 'currency'); function checkThemeLogo(issuer) { if (theme == 'dark') { issuer.imageSrc = issuer.assets['logo.grayscale.svg']; } else if (theme == 'light') { issuer.imageSrc = issuer.assets['logo.svg']; } } function changeCurrency(selected){ $("#"+selectionId+"_gateway").ddslick("destroy"); var issuers; var issuer; var picked = false; var disable = false; issuers = gateways.getIssuers(selected); if (selected === "XRP" || issuers.length === 0) { issuers = [{}]; disable = true; } var i = issuers.length; while (i--) { issuer = issuers[i]; if (disable !== true && !issuers[i].include) { issuers.splice(i, 1); } else { issuer.text = issuer.name; if (disable !== true && !issuer.custom) { checkThemeLogo(issuer); } issuer.value = i; if (select.issuer === issuer.account) { issuer.selected = true; } else issuer.selected = false; } } //Special edge case for custom issuer being duplicate of featured for (i=0; i<issuers.length; i++) { if (issuers[i].selected && !picked) picked = true; else if (issuers[i].selected && picked) issuers[i].selected = false; } $("#"+selectionId+"_gateway").ddslick({ data: issuers, imagePosition: "left", onSelected: function (data) { var different_issuer = data.selectedData.account !== select.issuer; var different_currency = selected !== select.currency; if (different_currency || different_issuer) { changeGateway(selected, data.selectedData.account, selectionId); } } }); d3.select("#"+selectionId+"currency").classed("currency", true); d3.select("#"+selectionId+"_gateway").classed("gateway", true); if (disable === true) { d3.select("#"+selectionId+"_gateway").classed("disabledDropdown", true); } } function changeGateway(currency, issuer, selectionId) { if ($("#"+selectionId+"_gateway").find('li.edit_list.gateway').length < 1) { editList(selectionId, 'gateway'); } select = issuer ? {currency: currency, issuer: issuer} : {currency:currency} event.change(select); } } //append edit list option to dropdowns function editList( selectionId, selectionSuffix ) { $('#'+ selectionId + '_' + selectionSuffix + ' ul.dd-options').append( '<a onClick=ga("send", "event", "Manage", "Edit button"); class="edit_list" href="#/manage-' + selectionSuffix +'?'+ selectionId +'"><li ui-route="/manage-' + selectionSuffix + '" ng-class="{active:$uiRoute !== false}" class="edit_list ' + selectionSuffix + '"><span class="plus">+</span> Edit</li></a>'); } function oldDropdowns(selection, fixed) { var currencies = gateways.getCurrencies(fixed); var currencySelect = selection.append("select").attr("class","currency").on("change", changeCurrency); var gateway = gateways.getName(select.currency, select.issuer); var selectedCurrency = select ? select.currency : null; var gatewaySelect = selection.append("select").attr("class","gateway").on("change", changeGateway); var option = currencySelect.selectAll("option") .data(currencies) .enter().append("option") .attr("class", function(d){ return d.currency }) .property("selected", function(d) { return selectedCurrency && d.currency === selectedCurrency; }) .text(function(d){ return d.currency }); changeCurrency(); function changeCurrency() { var currency = currencySelect.node().value; var list = currency == 'XRP' ? [""] : gateways.getIssuers(currency, fixed).map(function(d){ return d.name; }); var option = gatewaySelect.selectAll("option").data(list, String); option.enter().append("option").text(function(d){return d}); option.exit().remove(); if (currency=="XRP") gatewaySelect.attr("disabled", "true"); else gatewaySelect.attr('disabled', null); if (select) { option.property("selected", function(d) { return d === gateway }); } changeGateway(); } function changeGateway() { var gateway = gatewaySelect.node().value, currency = currencySelect.node().value, accounts = gateways.getIssuers(currency, fixed), account = accounts && accounts.filter(function(d) { return d.name === gateway; })[0]; issuer = account ? account.account : null; event.change(issuer ? {currency:currency, issuer:issuer} : {currency:currency}); } } return d3.rebind(dropdown, event, "on"); }; })();
src/common/dropdowns.js
(function() { ripple.currencyDropdown = function(gateways, old, fixed) { var event = d3.dispatch("change"); var select; var loaded = false; function dropdown(selection) { if (old) selection.call(oldDropdowns, fixed); else selection.call(loadDropdowns); } dropdown.selected = function(_) { return arguments.length ? (select = _, dropdown) : select; }; function loadDropdowns(selection) { selection.html(""); var theme = store.get("theme") || store.session.get("theme") || "light"; var selectionId; if (selection.attr("id") === "quote") selectionId = "trade"; else selectionId = selection.attr("id"); var currencies = gateways.getCurrencies(); var currencySelect = selection.append("select").attr("class", "currency").attr("id", selectionId+"_currency"); var gatewaySelect = selection.append("select").attr("class","gateway").attr("id", selectionId+"_gateway"); //format currnecies for dropdowns var i = currencies.length; while (i--) { if (!currencies[i].include) { currencies.splice(i, 1); } else { currencies[i] = { text : ripple.Currency.from_json(currencies[i].currency).to_human().substring(0,3), value : i, currency : currencies[i].currency, imageSrc : currencies[i].icon }; if (select.currency === currencies[i].currency) currencies[i].selected = true; } } $("#"+selectionId+"_currency").ddslick({ data: currencies, imagePosition: "left", width: "120px", onSelected: function (data) { if (!loaded) { changeCurrency(data.selectedData.currency); } else if (data.selectedData.currency !== select.currency) { changeCurrency(data.selectedData.currency); } } }); editList(selectionId, 'gateway'); editList(selectionId, 'currency'); function checkThemeLogo(issuer) { if (theme == 'dark') { issuer.imageSrc = issuer.assets['logo.grayscale.svg']; } else if (theme == 'light') { issuer.imageSrc = issuer.assets['logo.svg']; } } function changeCurrency(selected){ $("#"+selectionId+"_gateway").ddslick("destroy"); var issuers; var issuer; var picked = false; var disable = false; issuers = gateways.getIssuers(selected); if (selected === "XRP" || issuers.length === 0) { issuers = [{}]; disable = true; } var i = issuers.length; while (i--) { issuer = issuers[i]; if (disable !== true && !issuers[i].include) { issuers.splice(i, 1); } else { issuer.text = issuer.name; if (disable !== true && !issuer.custom) { checkThemeLogo(issuer); } issuer.value = i; if (select.issuer === issuer.account) { issuer.selected = true; } else issuer.selected = false; } } //Special edge case for custom issuer being duplicate of featured for (i=0; i<issuers.length; i++) { if (issuers[i].selected && !picked) picked = true; else if (issuers[i].selected && picked) issuers[i].selected = false; } $("#"+selectionId+"_gateway").ddslick({ data: issuers, imagePosition: "left", onSelected: function (data) { var different_issuer = data.selectedData.account !== select.issuer; var different_currency = selected !== select.currency; if (different_currency || different_issuer) { changeGateway(selected, data.selectedData.account, selectionId); } } }); d3.select("#"+selectionId+"currency").classed("currency", true); d3.select("#"+selectionId+"_gateway").classed("gateway", true); if (disable === true) { d3.select("#"+selectionId+"_gateway").classed("disabledDropdown", true); } } function changeGateway(currency, issuer, selectionId) { if ($("#"+selectionId+"_gateway").find('li.edit_list.gateway').length < 1) { editList(selectionId, 'gateway'); } select = issuer ? {currency: currency, issuer: issuer} : {currency:currency} event.change(select); } } //append edit list option to dropdowns function editList( selectionId, selectionSuffix ) { $('#'+ selectionId + '_' + selectionSuffix + ' ul.dd-options').append('<a class="edit_list" href="#/manage-' + selectionSuffix +'?'+ selectionId +'"><li ui-route="/manage-' + selectionSuffix + '" ng-class="{active:$uiRoute !== false}" class="edit_list ' + selectionSuffix + '"><span class="plus">+</span> Edit</li></a>'); } function oldDropdowns(selection, fixed) { var currencies = gateways.getCurrencies(fixed); var currencySelect = selection.append("select").attr("class","currency").on("change", changeCurrency); var gateway = gateways.getName(select.currency, select.issuer); var selectedCurrency = select ? select.currency : null; var gatewaySelect = selection.append("select").attr("class","gateway").on("change", changeGateway); var option = currencySelect.selectAll("option") .data(currencies) .enter().append("option") .attr("class", function(d){ return d.currency }) .property("selected", function(d) { return selectedCurrency && d.currency === selectedCurrency; }) .text(function(d){ return d.currency }); changeCurrency(); function changeCurrency() { var currency = currencySelect.node().value; var list = currency == 'XRP' ? [""] : gateways.getIssuers(currency, fixed).map(function(d){ return d.name; }); var option = gatewaySelect.selectAll("option").data(list, String); option.enter().append("option").text(function(d){return d}); option.exit().remove(); if (currency=="XRP") gatewaySelect.attr("disabled", "true"); else gatewaySelect.attr('disabled', null); if (select) { option.property("selected", function(d) { return d === gateway }); } changeGateway(); } function changeGateway() { var gateway = gatewaySelect.node().value, currency = currencySelect.node().value, accounts = gateways.getIssuers(currency, fixed), account = accounts && accounts.filter(function(d) { return d.name === gateway; })[0]; issuer = account ? account.account : null; event.change(issuer ? {currency:currency, issuer:issuer} : {currency:currency}); } } return d3.rebind(dropdown, event, "on"); }; })();
event tracking for edit button
src/common/dropdowns.js
event tracking for edit button
<ide><path>rc/common/dropdowns.js <ide> <ide> //append edit list option to dropdowns <ide> function editList( selectionId, selectionSuffix ) { <del> $('#'+ selectionId + '_' + selectionSuffix + ' ul.dd-options').append('<a class="edit_list" href="#/manage-' + selectionSuffix +'?'+ selectionId +'"><li ui-route="/manage-' + selectionSuffix + '" ng-class="{active:$uiRoute !== false}" class="edit_list ' + selectionSuffix + '"><span class="plus">+</span> Edit</li></a>'); <del> } <add> $('#'+ selectionId + '_' + selectionSuffix + ' ul.dd-options').append( '<a onClick=ga("send", "event", "Manage", "Edit button"); class="edit_list" href="#/manage-' + selectionSuffix +'?'+ selectionId +'"><li ui-route="/manage-' + selectionSuffix + '" ng-class="{active:$uiRoute !== false}" class="edit_list ' + selectionSuffix + '"><span class="plus">+</span> Edit</li></a>'); <add> } <ide> <ide> function oldDropdowns(selection, fixed) { <ide> var currencies = gateways.getCurrencies(fixed);
Java
mit
3fa36d4186922d1a328cdbdf46c250aa1fab4905
0
gabelew/SimCity201
package atHome.city; import java.awt.Graphics2D; import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.imageio.ImageIO; import restaurant.RoleOrder; import restaurant.gui.FoodIcon; import city.PersonAgent; import city.gui.Gui; import city.gui.SimCityGui; import city.roles.AtHomeRole; public class AtHomeGui implements Gui{ private PersonAgent agent = null; private AtHomeRole role = null; private boolean isPresent = false; private static BufferedImage personImg = null; private int xPos, yPos; private int xDestination, yDestination; private int xHomePosition = 20; private int yHomePosition = 30; private int xFRIDGE_POSITION = 0; private int yFRIDGE_POSITION = 0; private int xGRILL_POSITION = 0; private int yGRILL_POSITION = 0; private int xTABLE_POS = 57; private int yTABLE_POS = 70; private int xKITCHEN_COUNTER_POSITION = 0; private int yKITCHEN_COUNTER_POSITION = 0; static final int yTABLE_OFFSET = 300; static final int xKITCHEN_OFFSET = 217; static final int xFOOD_OFFSET = 10; static final int yFOOD_OFFSET = 4; static final int yKITCHEN_COUNTER_OFFSET = 30; static final int yGRILL_RIGHT_OFFSET = 30; static final int xGRILL_RIGHT_OFFSET = 52; static final int yFIDGE_OFFSET = 15; static final int xFIDGE_OFFSET = 100; static final int yAPT_OFFSET = 310; static final int xAPT_OFFSET = 30; static final int HOUSE_TABLEPOS = 150; static final int COOKING_OFFSET = 20; static final int KITCHEN_OFFSET = 15; List<MyFood> foods = Collections.synchronizedList(new ArrayList<MyFood>()); private enum Command {noCommand, GoHome, GoToFridge, GoToGrill, GoToCounter, GoToRestPost, EatFood, LeaveHome, GetFoodFromCounter, GetFoodFromGrill}; private enum FoodState{PutFoodOnGrill, PutFoodOnCounter, FoodOnGrill, FoodOnCounter, PickUpFromGrill, PickUpFromCounter, PutOnPickUpTable, OnPickUpTable, WaiterPickedUp}; Command command = Command.noCommand; public AtHomeGui(PersonAgent c, AtHomeRole r) { try { StringBuilder path = new StringBuilder("imgs/"); personImg = ImageIO.read(new File(path.toString() + "customer_v1.png")); } catch (IOException e) {} this.agent = c; this.role = r; if(agent.myHome instanceof Apartment) { int aptnum = ((Apartment)agent.myHome).renters.indexOf(agent); //System.out.println("MY APT NUMBER IS: " + aptnum); if(aptnum < 4)//top 4 apartments { xKITCHEN_COUNTER_POSITION = xHomePosition + aptnum*xKITCHEN_OFFSET; yKITCHEN_COUNTER_POSITION = yHomePosition - yKITCHEN_COUNTER_OFFSET + KITCHEN_OFFSET; xFRIDGE_POSITION = xHomePosition + xFIDGE_OFFSET + aptnum*xKITCHEN_OFFSET; yFRIDGE_POSITION = yHomePosition + yFIDGE_OFFSET- KITCHEN_OFFSET; xGRILL_POSITION = xHomePosition + xGRILL_RIGHT_OFFSET + aptnum*xKITCHEN_OFFSET; yGRILL_POSITION = yHomePosition -yGRILL_RIGHT_OFFSET+ KITCHEN_OFFSET; xTABLE_POS += xKITCHEN_OFFSET*aptnum; xHomePosition = xHomePosition + aptnum*xKITCHEN_OFFSET; //xDestination = xHomePosition; //yDestination = yHomePosition; } else //bottom 4 apartments { xKITCHEN_COUNTER_POSITION = xAPT_OFFSET + xHomePosition + (aptnum-4)*xKITCHEN_OFFSET; yKITCHEN_COUNTER_POSITION = yHomePosition - yKITCHEN_COUNTER_OFFSET + yAPT_OFFSET+ KITCHEN_OFFSET; xFRIDGE_POSITION = xAPT_OFFSET + xHomePosition + xFIDGE_OFFSET + (aptnum-4)*xKITCHEN_OFFSET; yFRIDGE_POSITION = yHomePosition + yFIDGE_OFFSET + yAPT_OFFSET- KITCHEN_OFFSET; xGRILL_POSITION = xAPT_OFFSET + xHomePosition + xGRILL_RIGHT_OFFSET + (aptnum-4)*xKITCHEN_OFFSET; yGRILL_POSITION = yHomePosition -yGRILL_RIGHT_OFFSET + yAPT_OFFSET+ KITCHEN_OFFSET; xTABLE_POS = xAPT_OFFSET*2 + xKITCHEN_OFFSET*(aptnum-4); yTABLE_POS += yTABLE_OFFSET; xHomePosition = xHomePosition + (aptnum-4)*xKITCHEN_OFFSET; yHomePosition = yHomePosition + yAPT_OFFSET; //xDestination = xHomePosition; //yDestination = yHomePosition; } } if(agent.myHome instanceof Home) { xHomePosition = 50; yHomePosition = 50; xKITCHEN_COUNTER_POSITION = xHomePosition; yKITCHEN_COUNTER_POSITION = yHomePosition - yKITCHEN_COUNTER_OFFSET; xFRIDGE_POSITION = xHomePosition + xFIDGE_OFFSET; yFRIDGE_POSITION = yHomePosition + yFIDGE_OFFSET; xGRILL_POSITION = xHomePosition + xGRILL_RIGHT_OFFSET; yGRILL_POSITION = yHomePosition -yGRILL_RIGHT_OFFSET; xTABLE_POS = HOUSE_TABLEPOS; yTABLE_POS = HOUSE_TABLEPOS; } xPos = 0; yPos = 200; } @Override public void updatePosition() { //moving within house if(agent.myHome instanceof Home) { if(command == Command.LeaveHome) { if (yPos < yDestination) yPos++; else if (yPos > yDestination) yPos--; if(yPos == yDestination) { if (xPos < xDestination) xPos++; else if (xPos > xDestination) xPos--; } } else { if (yPos < yDestination) yPos++; else if (yPos > yDestination) yPos--; if (xPos < xDestination) xPos++; else if (xPos > xDestination) xPos--; } } else //moving within apt { if(command == Command.LeaveHome) { if (yPos < yDestination) yPos++; else if (yPos > yDestination) yPos--; if(yPos == yDestination) { if (xPos < xDestination) xPos++; else if (xPos > xDestination) xPos--; } } else { if (xPos < xDestination) xPos++; else if (xPos > xDestination) xPos--; else if (yPos < yDestination) yPos++; else if (yPos > yDestination) yPos--; } } if (xPos == xDestination && yPos == yDestination) { if(command == Command.GoHome || command == Command.GoToFridge) { command = Command.noCommand; role.msgAnimationFinshed(); xDestination = xHomePosition; yDestination = yHomePosition; } else if(command == Command.GoToGrill || command == Command.GoToCounter) { command = Command.noCommand; role.msgAnimationFinshed(); xDestination = xHomePosition; yDestination = yHomePosition; for(MyFood f: foods) { if(f.food != null) { if(f.state == FoodState.PutFoodOnGrill) { f.state = FoodState.FoodOnGrill; f.CookingPoint = new Point(xGRILL_POSITION + COOKING_OFFSET, yGRILL_POSITION + 0*COOKING_OFFSET); } else if (f.state == FoodState.PutFoodOnCounter) { f.state = FoodState.FoodOnCounter; f.CookingPoint = new Point(xKITCHEN_COUNTER_POSITION + COOKING_OFFSET,yKITCHEN_COUNTER_POSITION + 0*COOKING_OFFSET); } } } } else if(command == command.GetFoodFromGrill || command == command.GetFoodFromCounter) { command = Command.noCommand; role.msgAnimationFinshed(); for(MyFood f : foods) { if(f.state == FoodState.FoodOnGrill) { f.state = FoodState.PickUpFromGrill; } else if (f.state == FoodState.FoodOnCounter) { f.state = FoodState.PickUpFromCounter; } } } else if(command == Command.EatFood || command == Command.LeaveHome) { command = Command.noCommand; role.msgAnimationFinshed(); } } } public void doEnterHome() { command = Command.GoHome; xDestination = xHomePosition; yDestination = yHomePosition; } @Override public boolean isPresent() { return isPresent; } public void setPresent(boolean p) { isPresent = p; } public void draw(Graphics2D g) { g.drawImage(personImg, xPos, yPos, null); drawFood(g); } public void drawFood(Graphics2D g) { synchronized(foods) { for(MyFood f: foods) { if(f.food != null) { if(f.state == FoodState.PutFoodOnGrill || f.state == FoodState.PutFoodOnCounter || f.state == FoodState.PickUpFromCounter || f.state == FoodState.PickUpFromGrill) { g.drawImage(f.food.iconImg, xPos+f.point.x, yPos+f.point.y, null); } else if(f.state == FoodState.FoodOnGrill || f.state == FoodState.FoodOnCounter) { g.drawImage(f.food.iconImg, f.CookingPoint.x, f.CookingPoint.y, null); } } } } } public void DoLeaveHome() { command = Command.LeaveHome; xDestination = -20; yDestination = 200; } /*********************************** * Cooking at home animation calls **********************************/ public void DoGoToFridge() { xDestination = xFRIDGE_POSITION; yDestination = yFRIDGE_POSITION; command = Command.GoToFridge; } public void DoCookFood(String choice) { // Grab food from fidge(already at fidge // if burger,steak,chicken put on grill and set timer // if salad or cookie, put on right if(choice.equalsIgnoreCase("steak") || choice.equalsIgnoreCase("chicken")){ foods.add(new MyFood(new FoodIcon(choice+"g"), new Point(xFOOD_OFFSET, yFOOD_OFFSET),choice)); xDestination = xGRILL_POSITION; yDestination = yGRILL_POSITION; command = Command.GoToGrill; }else{ foods.add(new MyFood(new FoodIcon(choice+"g"), new Point(xFOOD_OFFSET, yFOOD_OFFSET),choice)); xDestination = xKITCHEN_COUNTER_POSITION; yDestination = yKITCHEN_COUNTER_POSITION; command = Command.GoToCounter; } } public void SitDownAndEatFood() { command = Command.EatFood; xDestination = xTABLE_POS; yDestination = yTABLE_POS; } public void PlateFood() { for(MyFood f: foods) { if(f.food != null) { if(f.state == FoodState.FoodOnGrill) { command = Command.GetFoodFromGrill; xDestination = xGRILL_POSITION; yDestination = yGRILL_POSITION; } if (f.state == FoodState.FoodOnCounter) { command = Command.GetFoodFromCounter; xDestination = xKITCHEN_COUNTER_POSITION; yDestination = yKITCHEN_COUNTER_POSITION; } } } } public void DoneEating() { foods.clear(); } /***************** * Utility Class ****************/ class MyFood { FoodIcon food; Point point; Point CookingPoint; FoodState state; String choice; MyFood(FoodIcon f, Point p, String c){ this.food = f; this.point = p; this.choice = c; if(choice.equalsIgnoreCase("steak") || choice.equalsIgnoreCase("chicken")) { state = FoodState.PutFoodOnGrill; } else { state = FoodState.PutFoodOnCounter; } } } }
src/atHome/city/AtHomeGui.java
package atHome.city; import java.awt.Graphics2D; import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.imageio.ImageIO; import restaurant.RoleOrder; import restaurant.gui.FoodIcon; import city.PersonAgent; import city.gui.Gui; import city.gui.SimCityGui; import city.roles.AtHomeRole; public class AtHomeGui implements Gui{ private PersonAgent agent = null; private AtHomeRole role = null; private boolean isPresent = false; private static BufferedImage personImg = null; private int xPos, yPos; private int xDestination, yDestination; private int xHomePosition = 20; private int yHomePosition = 30; private int xFRIDGE_POSITION = 0; private int yFRIDGE_POSITION = 0; private int xGRILL_POSITION = 0; private int yGRILL_POSITION = 0; private int xTABLE_POS = 57; private int yTABLE_POS = 70; private int xKITCHEN_COUNTER_POSITION = 0; private int yKITCHEN_COUNTER_POSITION = 0; static final int yTABLE_OFFSET = 300; static final int xKITCHEN_OFFSET = 217; static final int xFOOD_OFFSET = 10; static final int yFOOD_OFFSET = 4; static final int yKITCHEN_COUNTER_OFFSET = 30; static final int yGRILL_RIGHT_OFFSET = 30; static final int xGRILL_RIGHT_OFFSET = 52; static final int yFIDGE_OFFSET = 15; static final int xFIDGE_OFFSET = 100; static final int yAPT_OFFSET = 310; static final int xAPT_OFFSET = 30; static final int HOUSE_TABLEPOS = 150; static final int COOKING_OFFSET = 0; static final int KITCHEN_OFFSET = 15; List<MyFood> foods = Collections.synchronizedList(new ArrayList<MyFood>()); private enum Command {noCommand, GoHome, GoToFridge, GoToGrill, GoToCounter, GoToRestPost, EatFood, LeaveHome, GetFoodFromCounter, GetFoodFromGrill}; private enum FoodState{PutFoodOnGrill, PutFoodOnCounter, FoodOnGrill, FoodOnCounter, PickUpFromGrill, PickUpFromCounter, PutOnPickUpTable, OnPickUpTable, WaiterPickedUp}; Command command = Command.noCommand; public AtHomeGui(PersonAgent c, AtHomeRole r) { try { StringBuilder path = new StringBuilder("imgs/"); personImg = ImageIO.read(new File(path.toString() + "customer_v1.png")); } catch (IOException e) {} this.agent = c; this.role = r; if(agent.myHome instanceof Apartment) { int aptnum = ((Apartment)agent.myHome).renters.indexOf(agent); //System.out.println("MY APT NUMBER IS: " + aptnum); if(aptnum < 4)//top 4 apartments { xKITCHEN_COUNTER_POSITION = xHomePosition + aptnum*xKITCHEN_OFFSET; yKITCHEN_COUNTER_POSITION = yHomePosition - yKITCHEN_COUNTER_OFFSET + KITCHEN_OFFSET; xFRIDGE_POSITION = xHomePosition + xFIDGE_OFFSET + aptnum*xKITCHEN_OFFSET; yFRIDGE_POSITION = yHomePosition + yFIDGE_OFFSET- KITCHEN_OFFSET; xGRILL_POSITION = xHomePosition + xGRILL_RIGHT_OFFSET + aptnum*xKITCHEN_OFFSET; yGRILL_POSITION = yHomePosition -yGRILL_RIGHT_OFFSET+ KITCHEN_OFFSET; xTABLE_POS += xKITCHEN_OFFSET*aptnum; xHomePosition = xHomePosition + aptnum*xKITCHEN_OFFSET; //xDestination = xHomePosition; //yDestination = yHomePosition; } else //bottom 4 apartments { xKITCHEN_COUNTER_POSITION = xAPT_OFFSET + xHomePosition + (aptnum-4)*xKITCHEN_OFFSET; yKITCHEN_COUNTER_POSITION = yHomePosition - yKITCHEN_COUNTER_OFFSET + yAPT_OFFSET+ KITCHEN_OFFSET; xFRIDGE_POSITION = xAPT_OFFSET + xHomePosition + xFIDGE_OFFSET + (aptnum-4)*xKITCHEN_OFFSET; yFRIDGE_POSITION = yHomePosition + yFIDGE_OFFSET + yAPT_OFFSET- KITCHEN_OFFSET; xGRILL_POSITION = xAPT_OFFSET + xHomePosition + xGRILL_RIGHT_OFFSET + (aptnum-4)*xKITCHEN_OFFSET; yGRILL_POSITION = yHomePosition -yGRILL_RIGHT_OFFSET + yAPT_OFFSET+ KITCHEN_OFFSET; xTABLE_POS = xAPT_OFFSET*2 + xKITCHEN_OFFSET*(aptnum-4); yTABLE_POS += yTABLE_OFFSET; xHomePosition = xHomePosition + (aptnum-4)*xKITCHEN_OFFSET; yHomePosition = yHomePosition + yAPT_OFFSET; //xDestination = xHomePosition; //yDestination = yHomePosition; } } if(agent.myHome instanceof Home) { xHomePosition = 50; yHomePosition = 50; xKITCHEN_COUNTER_POSITION = xHomePosition; yKITCHEN_COUNTER_POSITION = yHomePosition - yKITCHEN_COUNTER_OFFSET; xFRIDGE_POSITION = xHomePosition + xFIDGE_OFFSET; yFRIDGE_POSITION = yHomePosition + yFIDGE_OFFSET; xGRILL_POSITION = xHomePosition + xGRILL_RIGHT_OFFSET; yGRILL_POSITION = yHomePosition -yGRILL_RIGHT_OFFSET; xTABLE_POS = HOUSE_TABLEPOS; yTABLE_POS = HOUSE_TABLEPOS; } xPos = 0; yPos = 200; } @Override public void updatePosition() { //moving within house if(agent.myHome instanceof Home) { if(command == Command.LeaveHome) { if (yPos < yDestination) yPos++; else if (yPos > yDestination) yPos--; if(yPos == yDestination) { if (xPos < xDestination) xPos++; else if (xPos > xDestination) xPos--; } } else { if (yPos < yDestination) yPos++; else if (yPos > yDestination) yPos--; if (xPos < xDestination) xPos++; else if (xPos > xDestination) xPos--; } } else //moving within apt { if(command == Command.LeaveHome) { if (yPos < yDestination) yPos++; else if (yPos > yDestination) yPos--; if(yPos == yDestination) { if (xPos < xDestination) xPos++; else if (xPos > xDestination) xPos--; } } else { if (xPos < xDestination) xPos++; else if (xPos > xDestination) xPos--; else if (yPos < yDestination) yPos++; else if (yPos > yDestination) yPos--; } } if (xPos == xDestination && yPos == yDestination) { if(command == Command.GoHome || command == Command.GoToFridge) { command = Command.noCommand; role.msgAnimationFinshed(); xDestination = xHomePosition; yDestination = yHomePosition; } else if(command == Command.GoToGrill || command == Command.GoToCounter) { command = Command.noCommand; role.msgAnimationFinshed(); xDestination = xHomePosition; yDestination = yHomePosition; for(MyFood f: foods) { if(f.food != null) { if(f.state == FoodState.PutFoodOnGrill) { f.state = FoodState.FoodOnGrill; f.CookingPoint = new Point(xGRILL_POSITION + COOKING_OFFSET, yGRILL_POSITION + COOKING_OFFSET); } else if (f.state == FoodState.PutFoodOnCounter) { f.state = FoodState.FoodOnCounter; f.CookingPoint = new Point(xKITCHEN_COUNTER_POSITION + COOKING_OFFSET,yKITCHEN_COUNTER_POSITION + COOKING_OFFSET); } } } } else if(command == command.GetFoodFromGrill || command == command.GetFoodFromCounter) { command = Command.noCommand; role.msgAnimationFinshed(); for(MyFood f : foods) { if(f.state == FoodState.FoodOnGrill) { f.state = FoodState.PickUpFromGrill; } else if (f.state == FoodState.FoodOnCounter) { f.state = FoodState.PickUpFromCounter; } } } else if(command == Command.EatFood || command == Command.LeaveHome) { command = Command.noCommand; role.msgAnimationFinshed(); } } } public void doEnterHome() { command = Command.GoHome; xDestination = xHomePosition; yDestination = yHomePosition; } @Override public boolean isPresent() { return isPresent; } public void setPresent(boolean p) { isPresent = p; } public void draw(Graphics2D g) { g.drawImage(personImg, xPos, yPos, null); drawFood(g); } public void drawFood(Graphics2D g) { synchronized(foods) { for(MyFood f: foods) { if(f.food != null) { if(f.state == FoodState.PutFoodOnGrill || f.state == FoodState.PutFoodOnCounter || f.state == FoodState.PickUpFromCounter || f.state == FoodState.PickUpFromGrill) { g.drawImage(f.food.iconImg, xPos+f.point.x, yPos+f.point.y, null); } else if(f.state == FoodState.FoodOnGrill || f.state == FoodState.FoodOnCounter) { g.drawImage(f.food.iconImg, f.CookingPoint.x, f.CookingPoint.y, null); } } } } } public void DoLeaveHome() { command = Command.LeaveHome; xDestination = -20; yDestination = 200; } /*********************************** * Cooking at home animation calls **********************************/ public void DoGoToFridge() { xDestination = xFRIDGE_POSITION; yDestination = yFRIDGE_POSITION; command = Command.GoToFridge; } public void DoCookFood(String choice) { // Grab food from fidge(already at fidge // if burger,steak,chicken put on grill and set timer // if salad or cookie, put on right if(choice.equalsIgnoreCase("steak") || choice.equalsIgnoreCase("chicken")){ foods.add(new MyFood(new FoodIcon(choice+"g"), new Point(xFOOD_OFFSET, yFOOD_OFFSET),choice)); xDestination = xGRILL_POSITION; yDestination = yGRILL_POSITION; command = Command.GoToGrill; }else{ foods.add(new MyFood(new FoodIcon(choice+"g"), new Point(xFOOD_OFFSET, yFOOD_OFFSET),choice)); xDestination = xKITCHEN_COUNTER_POSITION; yDestination = yKITCHEN_COUNTER_POSITION; command = Command.GoToCounter; } } public void SitDownAndEatFood() { command = Command.EatFood; xDestination = xTABLE_POS; yDestination = yTABLE_POS; } public void PlateFood() { for(MyFood f: foods) { if(f.food != null) { if(f.state == FoodState.FoodOnGrill) { command = Command.GetFoodFromGrill; xDestination = xGRILL_POSITION; yDestination = yGRILL_POSITION; } if (f.state == FoodState.FoodOnCounter) { command = Command.GetFoodFromCounter; xDestination = xKITCHEN_COUNTER_POSITION; yDestination = yKITCHEN_COUNTER_POSITION; } } } } public void DoneEating() { foods.clear(); } /***************** * Utility Class ****************/ class MyFood { FoodIcon food; Point point; Point CookingPoint; FoodState state; String choice; MyFood(FoodIcon f, Point p, String c){ this.food = f; this.point = p; this.choice = c; if(choice.equalsIgnoreCase("steak") || choice.equalsIgnoreCase("chicken")) { state = FoodState.PutFoodOnGrill; } else { state = FoodState.PutFoodOnCounter; } } } }
Updated Bank Animation Panel
src/atHome/city/AtHomeGui.java
Updated Bank Animation Panel
<ide><path>rc/atHome/city/AtHomeGui.java <ide> static final int yAPT_OFFSET = 310; <ide> static final int xAPT_OFFSET = 30; <ide> static final int HOUSE_TABLEPOS = 150; <del> static final int COOKING_OFFSET = 0; <add> static final int COOKING_OFFSET = 20; <ide> static final int KITCHEN_OFFSET = 15; <ide> List<MyFood> foods = Collections.synchronizedList(new ArrayList<MyFood>()); <ide> private enum Command {noCommand, GoHome, GoToFridge, GoToGrill, GoToCounter, GoToRestPost, EatFood, LeaveHome, GetFoodFromCounter, GetFoodFromGrill}; <ide> if(f.state == FoodState.PutFoodOnGrill) <ide> { <ide> f.state = FoodState.FoodOnGrill; <del> f.CookingPoint = new Point(xGRILL_POSITION + COOKING_OFFSET, yGRILL_POSITION + COOKING_OFFSET); <add> f.CookingPoint = new Point(xGRILL_POSITION + COOKING_OFFSET, yGRILL_POSITION + 0*COOKING_OFFSET); <ide> } <ide> else if (f.state == FoodState.PutFoodOnCounter) <ide> { <ide> f.state = FoodState.FoodOnCounter; <del> f.CookingPoint = new Point(xKITCHEN_COUNTER_POSITION + COOKING_OFFSET,yKITCHEN_COUNTER_POSITION + COOKING_OFFSET); <add> f.CookingPoint = new Point(xKITCHEN_COUNTER_POSITION + COOKING_OFFSET,yKITCHEN_COUNTER_POSITION + 0*COOKING_OFFSET); <ide> } <ide> } <ide> }
Java
mit
6ba8664a9866208f30b2304f65c00ea96a0218f5
0
BWeng20/thrift-parser
/* Copyright (c) 2015 Bernd Wengenroth * Licensed under the MIT License. * See LICENSE file for details. */ package bweng.thrift.parser; import bweng.thrift.parser.model.*; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.FileSystem; import java.nio.file.FileSystemNotFoundException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.antlr.runtime.ANTLRReaderStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.TokenStream; import org.antlr.runtime.tree.CommonTree; /** * Generates our Data model from Antlr parser results. */ public final class ThriftModelGenerator { ThriftDocument doc_; // Current package [DAI Extension] ThriftPackage current_package_; // All types not resolved so far public Map<String, ThriftType> global_types_; // All services not resolved so far public Map<String, ThriftService> global_services_; ThriftCommentTokenSource tokensource_; ThriftParser parser_; TokenStream tokens_; Map<String,ThriftDocument> loaded_; Pattern version_pattern_ = Pattern.compile("@version\\s+([0-9\\.]+)", Pattern.CASE_INSENSITIVE); class UnknownType extends ThriftType { ThriftPackage used_in_package; String name; List<Object> usedin; } public synchronized void loadIncludes( ThriftDocument doc ) { loaded_ = new HashMap<>(); loadIncludesInternal( doc ); loaded_.clear(); global_types_ = new HashMap<>(); global_services_= new HashMap<>(); collect_references( doc ); resolve_all( doc ); } private void collect_references( ThriftDocument doc ) { if ( doc != null ) { for (int i=0 ; i<doc.includes_.size() ; ++i) collect_references( doc.includes_.get(i).doc_ ); for ( ThriftType tp : doc.all_types_.values() ) { if ( tp instanceof ThriftTypeRef ) { ThriftTypeRef tpr = (ThriftTypeRef)tp; if ( null == tpr.resolvedType_ ) { doc.unresolved_types_.put( tpr.declaredName_, tpr); } } else { global_types_.put( tp.name_fully_qualified_, tp); } } for ( ThriftService sv : doc.all_services_ ) { if ( sv.extended_service_ != null && sv.extended_service_.resolvedService_ == null ) { doc.unresolved_services_.put( sv.extended_service_.declaredName_, sv.extended_service_ ); } global_services_.put( sv.name_fully_qualified_, sv); } } } private void resolve_all( ThriftDocument doc ) { if ( doc != null ) { for (int i=0 ; i<doc.includes_.size() ; ++i) resolve_all( doc.includes_.get(i).doc_ ); Iterator<ThriftTypeRef> it = doc.unresolved_types_.values().iterator(); while ( it.hasNext() ) { ThriftTypeRef tpr = it.next(); if ( null == tpr.resolvedType_ ) { // Initial scope where the type was used. ThriftPackage scopePackage = tpr.package_; // Go up the hierarchy and try to find the type in global registry. while ( tpr.resolvedType_ == null && scopePackage != null ) { tpr.resolvedType_ = global_types_.get( scopePackage.name_fully_qualified_+"."+tpr.declaredName_ ); scopePackage = scopePackage.parent_; } // if still not found, try as fully qualified type if ( null == tpr.resolvedType_) tpr.resolvedType_ = global_types_.get( tpr.declaredName_ ); if ( null != tpr.resolvedType_) { tpr.package_ = tpr.resolvedType_.package_; tpr.name_ = tpr.resolvedType_.name_; tpr.name_fully_qualified_ = tpr.resolvedType_.name_fully_qualified_; it.remove(); } } } Iterator<ThriftServiceRef> itServ = doc.unresolved_services_.values().iterator(); while ( itServ.hasNext() ) { ThriftServiceRef svr = itServ.next(); if ( null == svr.resolvedService_ ) { svr.resolvedService_ = global_services_.get(svr.declaredName_ ); if ( null != svr.resolvedService_) { itServ.remove(); } } } } } private void loadIncludesInternal( ThriftDocument doc ) { Path docFile = doc.ospath_; for (int i=0 ; i<doc.includes_.size() ; ++i) { ThriftInclude ic = doc.includes_.get(i); if ( null == ic.doc_ ) { try { Path bf = docFile.getParent(); final String icSubPath = ic.path_.replace('\\', File.separatorChar); while ( null != bf) { Path f = bf.resolve( icSubPath ); if ( Files.exists(f) ) { ic.ospath_ = f; final String uriS = ic.ospath_.toUri().toString(); ic.doc_ = loaded_.get(uriS); if ( ic.doc_ == null ) { ic.doc_ = loadDocument( ic.ospath_ ); loaded_.put(uriS, ic.doc_ ); } break; } bf = bf.getParent(); } } catch (IOException ex) { ex.printStackTrace(); } } } for (int i=0 ; i<doc.includes_.size() ; ++i) { ThriftInclude ic = doc.includes_.get(i); if ( null != ic.doc_ ) { loadIncludesInternal( ic.doc_ ); } } } // Gets the name of the document from the file path. public static String getDocumentName( String ospath ) { File f = new File(ospath); String name = f.getName(); int sepidx = name.indexOf('.'); if ( sepidx >= 0 ) name = name.substring(0, sepidx ); return name; } static public Path getPath( String ospath ) { URI uri = null; try { uri = new URI(ospath); } catch (URISyntaxException uriex) { } if ( uri != null && "jar".equalsIgnoreCase( uri.getScheme() )) { FileSystem fs=null; int si = ospath.indexOf("!"); String arc = ospath.substring(0,si); try { URI fsuri = new URI( arc ); try { fs = FileSystems.getFileSystem(fsuri); } catch ( FileSystemNotFoundException fsnf) { fs = FileSystems.newFileSystem(fsuri, new HashMap<String, Object>()); } return fs.getPath(ospath.substring(si+1)); } catch (Exception ex2) { } } return FileSystems.getDefault().getPath(ospath); } public synchronized ThriftDocument loadDocument( Path ospath ) throws IOException { ThriftDocument doc = null; String name = getDocumentName( ospath.toString() ); doc = generateModel(name, new ThriftLexer(new ANTLRReaderStream(Files.newBufferedReader(ospath)))); if ( doc != null ) { doc.ospath_ = ospath; } return doc; } public synchronized ThriftDocument generateModel( String name, ThriftLexer lex ) { tokensource_ = new ThriftCommentTokenSource( lex, ThriftLexer.DEFAULT_TOKEN_CHANNEL, ThriftLexer.COMMENT ); tokens_ = new CommonTokenStream(tokensource_); parser_ = new ThriftParser(tokens_); ThriftDocument d = null; doc_ = null; try { d = gen_document( name, (CommonTree)parser_.document().getTree() ); } catch (RecognitionException ex) { ex.printStackTrace(); } tokens_ = null; tokensource_ = null; return d; } private ThriftDocument gen_document( String name, CommonTree dt ) { ThriftDocument d = new ThriftDocument(); current_package_ = null; doc_ = d; d.column_ = 0; d.line_ = 0; d.name_ = name; d.name_fully_qualified_ = name; d.services_ = new ArrayList<>(); d.all_services_ = new ArrayList<>(); d.all_services_byname_= new HashMap<>(); d.all_packages_ = new ArrayList<>(); d.includes_ = new ArrayList<>(); d.unresolved_types_= new HashMap<>(); d.unresolved_services_= new HashMap<>(); d.types_ = new ArrayList<>(); d.all_types_ = new HashMap<String, ThriftType>(); // Add all default types to list d.all_types_.put(ThriftType.VOID .name_fully_qualified_, ThriftType.VOID ); d.all_types_.put(ThriftType.BOOL .name_fully_qualified_, ThriftType.BOOL ); d.all_types_.put(ThriftType.INT8 .name_fully_qualified_, ThriftType.INT8 ); d.all_types_.put(ThriftType.INT16 .name_fully_qualified_, ThriftType.INT16 ); d.all_types_.put(ThriftType.INT32 .name_fully_qualified_, ThriftType.INT32 ); d.all_types_.put(ThriftType.INT64 .name_fully_qualified_, ThriftType.INT64 ); d.all_types_.put(ThriftType.DOUBLE.name_fully_qualified_, ThriftType.DOUBLE ); d.all_types_.put(ThriftType.STRING.name_fully_qualified_, ThriftType.STRING ); d.all_types_.put(ThriftType.BINARY.name_fully_qualified_, ThriftType.BINARY ); parse_body( dt, 0 ); // Local reference resolution // Types Iterator<ThriftTypeRef> it = doc_.unresolved_types_.values().iterator(); while ( it.hasNext() ) { ThriftTypeRef tpr = it.next(); if ( null == tpr.resolvedType_ ) { // Try to find it in qualified names tpr.resolvedType_ = resolve_type(tpr.declaredName_ ); if ( null == tpr.resolvedType_ && null != tpr.package_) { // Try to find it in original scope tpr.resolvedType_ = tpr.package_.findTypeInPackage( tpr.declaredName_ ); } if ( null != tpr.resolvedType_) { tpr.package_ = tpr.resolvedType_.package_; tpr.name_ = tpr.resolvedType_.name_; tpr.name_fully_qualified_ = tpr.resolvedType_.name_fully_qualified_; it.remove(); } } } // Service references Iterator<ThriftServiceRef> itSv = doc_.unresolved_services_.values().iterator(); while ( itSv.hasNext() ) { ThriftServiceRef svr = itSv.next(); if ( null == svr.resolvedService_ ) { // Try to find it in qualified names svr.resolvedService_ = doc_.all_services_byname_.get( svr.declaredName_ ); if ( null == svr.resolvedService_ && null != svr.declarationPackage_) { // Try to find it in original scope svr.resolvedService_ = svr.declarationPackage_.findServiceInPackage( svr.declaredName_ ); } if ( null != svr.resolvedService_) { itSv.remove(); } } } doc_ = null; return d; } private void add_type_to_scope( ThriftType typ ) { typ.setDocument(doc_); doc_.all_types_.put( typ.name_fully_qualified_, typ ); if ( null != current_package_) current_package_.types_.add(typ); else doc_.types_.add(typ); } private void add_comment( CommonTree dt, ThriftObject obj ) { obj.comment_ = tokensource_.collectComment( dt.getLine()-1 ); // Try to locate version information if ( obj.comment_ != null ) { Matcher m = version_pattern_.matcher(obj.comment_); if ( m.find() && m.groupCount()>0 ) { obj.version_ = m.group(1); } // Try to locate @deprecated if ( obj.comment_.contains( "@deprecated" ) ) { obj.deprecated_ = true; } } } private ThriftType resolve_type( String name ) { ThriftType tp = doc_.all_types_.get( name ); if ( null != tp ) return tp; // Go up the package hierachy ThriftPackage p = current_package_; while( p != null ) { String fqname = get_fully_qualifiedname(p, name); tp = doc_.all_types_.get( fqname ); if ( null != tp ) return tp; p = p.parent_; } return null; } private ThriftType find_type( String name ) { ThriftType tp = resolve_type(name); if ( null == tp ) { tp = doc_.unresolved_types_.get( name ); if ( null == tp ) { ThriftTypeRef tpr = new ThriftTypeRef(); tpr.setDocument(doc_); tpr.declaredName_ = name; tpr.package_ = current_package_; doc_.unresolved_types_.put( name , tpr); tp = tpr; } } return tp; } private int get_integer( CommonTree dt ) { if ( null != dt ) { try { switch (dt.getType() ) { case ThriftParser.INTEGER: return Integer.parseInt( dt.getText() ); case ThriftParser.FIELD_ID_: if ( dt.getChildCount() > 0) return get_integer( (CommonTree)dt.getChild(0) ); break; case ThriftParser.HEX_INTEGER: String hx = dt.getText(); if ( hx.startsWith( "0x" )) hx = hx.substring(2); return Integer.parseInt( hx , 16 ); } } catch (NumberFormatException nfe ) { } } return Integer.MIN_VALUE; } private ThriftFunctionMode get_function_mode( CommonTree dt) { if ( dt.getChildCount() > 3 ) { // If a function mode was declared, it was re-written to child #3 CommonTree ct = (CommonTree)dt.getChild(3); switch (ct.getType()) { case ThriftParser.EVENT: return ThriftFunctionMode.EVENT; case ThriftParser.ONEWAY: return ThriftFunctionMode.ONEWAY; case ThriftParser.ASYNC: return ThriftFunctionMode.ASYNC; case ThriftParser.DEFERRED: return ThriftFunctionMode.DEFERRED; default: return ThriftFunctionMode.NONE; } } return ThriftFunctionMode.NONE; } private String get_identifier( CommonTree dt ) { CommonTree idT = (CommonTree)dt.getFirstChildWithType(ThriftParser.IDENTIFIER); return ( null != idT ) ? idT.getText() : ""; } private ThriftInclude gen_include( CommonTree dt ) { ThriftInclude i = new ThriftInclude(); CommonTree lt = (CommonTree)dt.getFirstChildWithType(ThriftParser.LITERAL); if ( null != lt ) i.path_ = lt.getText(); else i.path_ = ""; return i; } private ThriftPackage gen_package( CommonTree dt ) { ThriftPackage p = new ThriftPackage(); p.setDocument(doc_); p.parent_ = current_package_; p.name_ = get_identifier( dt ); p.name_fully_qualified_ = ((null != current_package_)?current_package_.name_fully_qualified_+"." : "") +p.name_; p.line_ = dt.getLine() -1 ; p.column_= dt.getCharPositionInLine(); add_comment( dt, p ); current_package_ = p; parse_body(dt,1); current_package_ = current_package_.parent_; return p; } private void parse_body( CommonTree dt, int startIndex ) { for (int i = startIndex ; i<dt.getChildCount() ; ++i ) { CommonTree ct = (CommonTree)dt.getChild(i); switch ( ct.getType() ) { case ThriftParser.PACKAGE: ThriftPackage np = gen_package(ct); if ( null != current_package_ ) current_package_.subpackages_.add( np ); doc_.all_packages_.add( np ); break; case ThriftParser.SERVICE: ThriftService serv = gen_service( ct ); if ( null != current_package_ ) current_package_.services_.add(serv); else doc_.services_.add(serv); doc_.all_services_.add(serv); doc_.all_services_byname_.put(serv.name_fully_qualified_, serv); break; case ThriftParser.ENUM: gen_enum( ct ); break; case ThriftParser.STRUCT: gen_struct( ct ); break; case ThriftParser.TYPEDEF: gen_typedef( ct ); break; case ThriftParser.INCLUDE: doc_.includes_.add(gen_include( ct )); break; } } } private String get_fully_qualifiedname( ThriftPackage p, String name ) { StringBuilder sb = new StringBuilder(100); if ( null != p) // [DAI Extension]: "packages" are used as parent namespace sb.append( p.name_fully_qualified_); else // All content is identified by document name. sb.append( doc_.name_ ); if ( 0 < sb.length() ) sb.append('.'); sb.append(name); return sb.toString(); } private String get_fully_qualifiedname( String name ) { return get_fully_qualifiedname( current_package_, name ); } private void add_typeheaderinfo( CommonTree dt, ThriftType tp ) { tp.name_ = get_identifier(dt); tp.name_fully_qualified_ = get_fully_qualifiedname( tp.name_ ); tp.package_ = current_package_; tp.line_ = dt.getLine() - 1; tp.column_= dt.getCharPositionInLine(); add_comment(dt, tp); } private ThriftListType gen_listtype( CommonTree dt ) { ThriftListType lt = new ThriftListType(); lt.setDocument(doc_); if ( 0 < dt.getChildCount() ) lt.value_type_ = gen_fieldtype( (CommonTree)dt.getChild(0) ); return lt; } private ThriftMapType gen_maptype( CommonTree dt ) { ThriftMapType lt = new ThriftMapType(); lt.setDocument(doc_); if ( 1 < dt.getChildCount() ) { lt.key_type_ = gen_fieldtype( (CommonTree)dt.getChild(0) ); lt.value_type_ = gen_fieldtype( (CommonTree)dt.getChild(1) ); } return lt; } private ThriftSetType gen_settype( CommonTree dt ) { ThriftSetType lt = new ThriftSetType(); lt.setDocument(doc_); if ( 0 < dt.getChildCount() ) { lt.value_type_ = gen_fieldtype( (CommonTree)dt.getChild(1) ); } return lt; } private void gen_typedef(CommonTree dt ) { ThriftTypedef td = new ThriftTypedef(); add_typeheaderinfo(dt, td); add_type_to_scope( td ); if ( 1 < dt.getChildCount() ) td.reftype_ = gen_fieldtype( (CommonTree)dt.getChild(1)); } private void gen_enum( CommonTree dt ) { ThriftEnum en = new ThriftEnum(); en.values_ = new ArrayList<>(); add_typeheaderinfo( dt, en ); int autoVal = 0; for (int i = 1 ; i<dt.getChildCount() ; ++i ) { CommonTree ct = (CommonTree)dt.getChild(i); switch ( ct.getType() ) { case ThriftParser.IDENTIFIER: ThriftEnumValue env = new ThriftEnumValue(); env.name_ = ct.getText(); if ( 0 < ct.getChildCount() ) { int vi = get_integer((CommonTree)ct.getChild(0)); if ( vi != Integer.MIN_VALUE) autoVal = vi; } env.value_ = autoVal++; en.values_.add(env); break; } } add_type_to_scope( en ); } private void gen_struct( CommonTree dt ) { ThriftStructType s = new ThriftStructType(); add_typeheaderinfo( dt, s ); s.fields_ = new ArrayList<>(); add_type_to_scope(s); for (int i = 1 ; i<dt.getChildCount() ; ++i ) { CommonTree ct = (CommonTree)dt.getChild(i); switch ( ct.getType() ) { case ThriftParser.FIELD_: s.fields_.add( gen_field( ct )); break; } } } private ThriftField gen_field( CommonTree dt ) { ThriftField f = new ThriftField(); f.setDocument(doc_); f.name_ = get_identifier( dt ); add_comment( dt, f ); if ( 2 <= dt.getChildCount() ) f.type_ = gen_fieldtype( (CommonTree)dt.getChild(1) ); f.id_ = get_integer( (CommonTree)dt.getFirstChildWithType( ThriftParser.FIELD_ID_ ) ); return f; } private ThriftType gen_fieldtype( CommonTree dt ) { ThriftType type = null; switch ( dt.getType() ) { case ThriftParser.VOID: return ThriftType.VOID; case ThriftParser.TYPE_BOOL: return ThriftType.BOOL; case ThriftParser.TYPE_BYTE: return ThriftType.INT8; case ThriftParser.TYPE_I16: return ThriftType.INT16; case ThriftParser.TYPE_I32: return ThriftType.INT32; case ThriftParser.TYPE_I64: return ThriftType.INT64; case ThriftParser.TYPE_DOUBLE: return ThriftType.DOUBLE; case ThriftParser.TYPE_STRING: return ThriftType.STRING; case ThriftParser.TYPE_BINARY: return ThriftType.BINARY; case ThriftParser.SERVICE_PTR_TYPE: return ThriftType.SERVICE; case ThriftParser.LIST: return gen_listtype(dt); case ThriftParser.MAP: return gen_maptype(dt); case ThriftParser.SET: return gen_settype(dt); case ThriftParser.IDENTIFIER: return find_type( dt.getText() ); } return type; } private ThriftService gen_service( CommonTree dt ) { ThriftService s = new ThriftService(); s.setDocument(doc_); s.name_ = get_identifier( dt ); s.name_fully_qualified_ = get_fully_qualifiedname( s.name_ ) ; s.package_ = current_package_; s.line_ = dt.getLine() - 1 ; s.column_ = dt.getCharPositionInLine(); add_comment( dt, s ); CommonTree dtExtends = (CommonTree)dt.getChild(1); if ( dtExtends.getChildCount() > 0 ) { ThriftServiceRef sref = new ThriftServiceRef(); sref.line_ = dtExtends.getLine() - 1 ; sref.column_ = dtExtends.getCharPositionInLine(); sref.declaredName_ = get_identifier(dtExtends); sref.declarationPackage_ = current_package_; s.extended_service_ = sref; } for (int i = 2 ; i<dt.getChildCount() ; ++i ) { CommonTree dtF = (CommonTree)dt.getChild(i); switch ( dtF.getType() ) { case ThriftParser.METHOD_: ThriftFunction f = gen_function(dtF); s.functions_.add(f); f.service_ = s; break; } } return s; } private List<ThriftField> gen_parameters(CommonTree dt ) { ArrayList<ThriftField> p = new ArrayList<>(); for (int i = 0 ; i<dt.getChildCount() ; ++i ) { CommonTree dtP = (CommonTree)dt.getChild(i); switch ( dtP.getType() ) { case ThriftParser.FIELD_: p.add(gen_field(dtP)); break; } } return p; } private ThriftFunction gen_function( CommonTree dt ) { ThriftFunction f = new ThriftFunction(); f.setDocument(doc_); f.mode_ = get_function_mode(dt); f.name_ = get_identifier(dt); f.parameters_ = new ArrayList<>(); f.line_ = dt.getLine() - 1; f.column_= dt.getCharPositionInLine(); if ( 1 < dt.getChildCount() ) f.return_type_ = gen_fieldtype((CommonTree)dt.getChild(1)); add_comment( dt, f ); f.parameters_ = gen_parameters((CommonTree)dt.getFirstChildWithType(ThriftParser.ARGS_)); return f; } }
ThriftParser/src/bweng/thrift/parser/ThriftModelGenerator.java
/* Copyright (c) 2015 Bernd Wengenroth * Licensed under the MIT License. * See LICENSE file for details. */ package bweng.thrift.parser; import bweng.thrift.parser.model.*; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.FileSystem; import java.nio.file.FileSystemNotFoundException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.antlr.runtime.ANTLRReaderStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.TokenStream; import org.antlr.runtime.tree.CommonTree; /** * Generates our Data model from Antlr parser results. */ public final class ThriftModelGenerator { ThriftDocument doc_; // Current package [DAI Extension] ThriftPackage current_package_; // All types not resolved so far public Map<String, ThriftType> global_types_; // All services not resolved so far public Map<String, ThriftService> global_services_; ThriftCommentTokenSource tokensource_; ThriftParser parser_; TokenStream tokens_; Map<String,ThriftDocument> loaded_; Pattern version_pattern_ = Pattern.compile("@version\\s+([0-9\\.]+)", Pattern.CASE_INSENSITIVE); class UnknownType extends ThriftType { ThriftPackage used_in_package; String name; List<Object> usedin; } public synchronized void loadIncludes( ThriftDocument doc ) { loaded_ = new HashMap<>(); loadIncludesInternal( doc ); loaded_.clear(); global_types_ = new HashMap<>(); global_services_= new HashMap<>(); collect_references( doc ); resolve_all( doc ); } private void collect_references( ThriftDocument doc ) { if ( doc != null ) { for (int i=0 ; i<doc.includes_.size() ; ++i) collect_references( doc.includes_.get(i).doc_ ); for ( ThriftType tp : doc.all_types_.values() ) { if ( tp instanceof ThriftTypeRef ) { ThriftTypeRef tpr = (ThriftTypeRef)tp; if ( null == tpr.resolvedType_ ) { doc.unresolved_types_.put( tpr.declaredName_, tpr); } } else { global_types_.put( tp.name_fully_qualified_, tp); } } for ( ThriftService sv : doc.all_services_ ) { if ( sv.extended_service_ != null && sv.extended_service_.resolvedService_ == null ) { doc.unresolved_services_.put( sv.extended_service_.declaredName_, sv.extended_service_ ); } global_services_.put( sv.name_fully_qualified_, sv); } } } private void resolve_all( ThriftDocument doc ) { if ( doc != null ) { for (int i=0 ; i<doc.includes_.size() ; ++i) resolve_all( doc.includes_.get(i).doc_ ); Iterator<ThriftTypeRef> it = doc.unresolved_types_.values().iterator(); while ( it.hasNext() ) { ThriftTypeRef tpr = it.next(); if ( null == tpr.resolvedType_ ) { // Initial scope where the type was used. ThriftPackage scopePackage = tpr.package_; // Go up the hierarchy and try to find the type in global registry. while ( tpr.resolvedType_ == null && scopePackage != null ) { tpr.resolvedType_ = global_types_.get( scopePackage.name_fully_qualified_+"."+tpr.declaredName_ ); scopePackage = scopePackage.parent_; } // if still not found, try as fully qualified type if ( null == tpr.resolvedType_) tpr.resolvedType_ = global_types_.get( tpr.declaredName_ ); if ( null != tpr.resolvedType_) { tpr.package_ = tpr.resolvedType_.package_; tpr.name_ = tpr.resolvedType_.name_; tpr.name_fully_qualified_ = tpr.resolvedType_.name_fully_qualified_; it.remove(); } } } Iterator<ThriftServiceRef> itServ = doc.unresolved_services_.values().iterator(); while ( itServ.hasNext() ) { ThriftServiceRef svr = itServ.next(); if ( null == svr.resolvedService_ ) { svr.resolvedService_ = global_services_.get(svr.declaredName_ ); if ( null != svr.resolvedService_) { itServ.remove(); } } } } } private void loadIncludesInternal( ThriftDocument doc ) { Path docFile = doc.ospath_; for (int i=0 ; i<doc.includes_.size() ; ++i) { ThriftInclude ic = doc.includes_.get(i); if ( null == ic.doc_ ) { try { Path bf = docFile.getParent(); while ( null != bf) { Path f = bf.resolve( ic.path_ ); if ( Files.exists(f) ) { ic.ospath_ = f; final String uriS = ic.ospath_.toUri().toString(); ic.doc_ = loaded_.get(uriS); if ( ic.doc_ == null ) { ic.doc_ = loadDocument( ic.ospath_ ); loaded_.put(uriS, ic.doc_ ); } break; } bf = bf.getParent(); } } catch (IOException ex) { ex.printStackTrace(); } } } for (int i=0 ; i<doc.includes_.size() ; ++i) { ThriftInclude ic = doc.includes_.get(i); if ( null != ic.doc_ ) { loadIncludesInternal( ic.doc_ ); } } } // Gets the name of the document from the file path. public static String getDocumentName( String ospath ) { File f = new File(ospath); String name = f.getName(); int sepidx = name.indexOf('.'); if ( sepidx >= 0 ) name = name.substring(0, sepidx ); return name; } static public Path getPath( String ospath ) { URI uri = null; try { uri = new URI(ospath); } catch (URISyntaxException uriex) { } if ( uri != null && "jar".equalsIgnoreCase( uri.getScheme() )) { FileSystem fs=null; int si = ospath.indexOf("!"); String arc = ospath.substring(0,si); try { URI fsuri = new URI( arc ); try { fs = FileSystems.getFileSystem(fsuri); } catch ( FileSystemNotFoundException fsnf) { fs = FileSystems.newFileSystem(fsuri, new HashMap<String, Object>()); } return fs.getPath(ospath.substring(si+1)); } catch (Exception ex2) { } } return FileSystems.getDefault().getPath(ospath); } public synchronized ThriftDocument loadDocument( Path ospath ) throws IOException { ThriftDocument doc = null; String name = getDocumentName( ospath.toString() ); doc = generateModel(name, new ThriftLexer(new ANTLRReaderStream(Files.newBufferedReader(ospath)))); if ( doc != null ) { doc.ospath_ = ospath; } return doc; } public synchronized ThriftDocument generateModel( String name, ThriftLexer lex ) { tokensource_ = new ThriftCommentTokenSource( lex, ThriftLexer.DEFAULT_TOKEN_CHANNEL, ThriftLexer.COMMENT ); tokens_ = new CommonTokenStream(tokensource_); parser_ = new ThriftParser(tokens_); ThriftDocument d = null; doc_ = null; try { d = gen_document( name, (CommonTree)parser_.document().getTree() ); } catch (RecognitionException ex) { ex.printStackTrace(); } tokens_ = null; tokensource_ = null; return d; } private ThriftDocument gen_document( String name, CommonTree dt ) { ThriftDocument d = new ThriftDocument(); current_package_ = null; doc_ = d; d.column_ = 0; d.line_ = 0; d.name_ = name; d.name_fully_qualified_ = name; d.services_ = new ArrayList<>(); d.all_services_ = new ArrayList<>(); d.all_services_byname_= new HashMap<>(); d.all_packages_ = new ArrayList<>(); d.includes_ = new ArrayList<>(); d.unresolved_types_= new HashMap<>(); d.unresolved_services_= new HashMap<>(); d.types_ = new ArrayList<>(); d.all_types_ = new HashMap<String, ThriftType>(); // Add all default types to list d.all_types_.put(ThriftType.VOID .name_fully_qualified_, ThriftType.VOID ); d.all_types_.put(ThriftType.BOOL .name_fully_qualified_, ThriftType.BOOL ); d.all_types_.put(ThriftType.INT8 .name_fully_qualified_, ThriftType.INT8 ); d.all_types_.put(ThriftType.INT16 .name_fully_qualified_, ThriftType.INT16 ); d.all_types_.put(ThriftType.INT32 .name_fully_qualified_, ThriftType.INT32 ); d.all_types_.put(ThriftType.INT64 .name_fully_qualified_, ThriftType.INT64 ); d.all_types_.put(ThriftType.DOUBLE.name_fully_qualified_, ThriftType.DOUBLE ); d.all_types_.put(ThriftType.STRING.name_fully_qualified_, ThriftType.STRING ); d.all_types_.put(ThriftType.BINARY.name_fully_qualified_, ThriftType.BINARY ); parse_body( dt, 0 ); // Local reference resolution // Types Iterator<ThriftTypeRef> it = doc_.unresolved_types_.values().iterator(); while ( it.hasNext() ) { ThriftTypeRef tpr = it.next(); if ( null == tpr.resolvedType_ ) { // Try to find it in qualified names tpr.resolvedType_ = resolve_type(tpr.declaredName_ ); if ( null == tpr.resolvedType_ && null != tpr.package_) { // Try to find it in original scope tpr.resolvedType_ = tpr.package_.findTypeInPackage( tpr.declaredName_ ); } if ( null != tpr.resolvedType_) { tpr.package_ = tpr.resolvedType_.package_; tpr.name_ = tpr.resolvedType_.name_; tpr.name_fully_qualified_ = tpr.resolvedType_.name_fully_qualified_; it.remove(); } } } // Service references Iterator<ThriftServiceRef> itSv = doc_.unresolved_services_.values().iterator(); while ( itSv.hasNext() ) { ThriftServiceRef svr = itSv.next(); if ( null == svr.resolvedService_ ) { // Try to find it in qualified names svr.resolvedService_ = doc_.all_services_byname_.get( svr.declaredName_ ); if ( null == svr.resolvedService_ && null != svr.declarationPackage_) { // Try to find it in original scope svr.resolvedService_ = svr.declarationPackage_.findServiceInPackage( svr.declaredName_ ); } if ( null != svr.resolvedService_) { itSv.remove(); } } } doc_ = null; return d; } private void add_type_to_scope( ThriftType typ ) { typ.setDocument(doc_); doc_.all_types_.put( typ.name_fully_qualified_, typ ); if ( null != current_package_) current_package_.types_.add(typ); else doc_.types_.add(typ); } private void add_comment( CommonTree dt, ThriftObject obj ) { obj.comment_ = tokensource_.collectComment( dt.getLine()-1 ); // Try to locate version information if ( obj.comment_ != null ) { Matcher m = version_pattern_.matcher(obj.comment_); if ( m.find() && m.groupCount()>0 ) { obj.version_ = m.group(1); } // Try to locate @deprecated if ( obj.comment_.contains( "@deprecated" ) ) { obj.deprecated_ = true; } } } private ThriftType resolve_type( String name ) { ThriftType tp = doc_.all_types_.get( name ); if ( null != tp ) return tp; // Go up the package hierachy ThriftPackage p = current_package_; while( p != null ) { String fqname = get_fully_qualifiedname(p, name); tp = doc_.all_types_.get( fqname ); if ( null != tp ) return tp; p = p.parent_; } return null; } private ThriftType find_type( String name ) { ThriftType tp = resolve_type(name); if ( null == tp ) { tp = doc_.unresolved_types_.get( name ); if ( null == tp ) { ThriftTypeRef tpr = new ThriftTypeRef(); tpr.setDocument(doc_); tpr.declaredName_ = name; tpr.package_ = current_package_; doc_.unresolved_types_.put( name , tpr); tp = tpr; } } return tp; } private int get_integer( CommonTree dt ) { if ( null != dt ) { try { switch (dt.getType() ) { case ThriftParser.INTEGER: return Integer.parseInt( dt.getText() ); case ThriftParser.FIELD_ID_: if ( dt.getChildCount() > 0) return get_integer( (CommonTree)dt.getChild(0) ); break; case ThriftParser.HEX_INTEGER: String hx = dt.getText(); if ( hx.startsWith( "0x" )) hx = hx.substring(2); return Integer.parseInt( hx , 16 ); } } catch (NumberFormatException nfe ) { } } return Integer.MIN_VALUE; } private ThriftFunctionMode get_function_mode( CommonTree dt) { if ( dt.getChildCount() > 3 ) { // If a function mode was declared, it was re-written to child #3 CommonTree ct = (CommonTree)dt.getChild(3); switch (ct.getType()) { case ThriftParser.EVENT: return ThriftFunctionMode.EVENT; case ThriftParser.ONEWAY: return ThriftFunctionMode.ONEWAY; case ThriftParser.ASYNC: return ThriftFunctionMode.ASYNC; case ThriftParser.DEFERRED: return ThriftFunctionMode.DEFERRED; default: return ThriftFunctionMode.NONE; } } return ThriftFunctionMode.NONE; } private String get_identifier( CommonTree dt ) { CommonTree idT = (CommonTree)dt.getFirstChildWithType(ThriftParser.IDENTIFIER); return ( null != idT ) ? idT.getText() : ""; } private ThriftInclude gen_include( CommonTree dt ) { ThriftInclude i = new ThriftInclude(); CommonTree lt = (CommonTree)dt.getFirstChildWithType(ThriftParser.LITERAL); if ( null != lt ) i.path_ = lt.getText(); else i.path_ = ""; return i; } private ThriftPackage gen_package( CommonTree dt ) { ThriftPackage p = new ThriftPackage(); p.setDocument(doc_); p.parent_ = current_package_; p.name_ = get_identifier( dt ); p.name_fully_qualified_ = ((null != current_package_)?current_package_.name_fully_qualified_+"." : "") +p.name_; p.line_ = dt.getLine() -1 ; p.column_= dt.getCharPositionInLine(); add_comment( dt, p ); current_package_ = p; parse_body(dt,1); current_package_ = current_package_.parent_; return p; } private void parse_body( CommonTree dt, int startIndex ) { for (int i = startIndex ; i<dt.getChildCount() ; ++i ) { CommonTree ct = (CommonTree)dt.getChild(i); switch ( ct.getType() ) { case ThriftParser.PACKAGE: ThriftPackage np = gen_package(ct); if ( null != current_package_ ) current_package_.subpackages_.add( np ); doc_.all_packages_.add( np ); break; case ThriftParser.SERVICE: ThriftService serv = gen_service( ct ); if ( null != current_package_ ) current_package_.services_.add(serv); else doc_.services_.add(serv); doc_.all_services_.add(serv); doc_.all_services_byname_.put(serv.name_fully_qualified_, serv); break; case ThriftParser.ENUM: gen_enum( ct ); break; case ThriftParser.STRUCT: gen_struct( ct ); break; case ThriftParser.TYPEDEF: gen_typedef( ct ); break; case ThriftParser.INCLUDE: doc_.includes_.add(gen_include( ct )); break; } } } private String get_fully_qualifiedname( ThriftPackage p, String name ) { StringBuilder sb = new StringBuilder(100); if ( null != p) // [DAI Extension]: "packages" are used as parent namespace sb.append( p.name_fully_qualified_); else // All content is identified by document name. sb.append( doc_.name_ ); if ( 0 < sb.length() ) sb.append('.'); sb.append(name); return sb.toString(); } private String get_fully_qualifiedname( String name ) { return get_fully_qualifiedname( current_package_, name ); } private void add_typeheaderinfo( CommonTree dt, ThriftType tp ) { tp.name_ = get_identifier(dt); tp.name_fully_qualified_ = get_fully_qualifiedname( tp.name_ ); tp.package_ = current_package_; tp.line_ = dt.getLine() - 1; tp.column_= dt.getCharPositionInLine(); add_comment(dt, tp); } private ThriftListType gen_listtype( CommonTree dt ) { ThriftListType lt = new ThriftListType(); lt.setDocument(doc_); if ( 0 < dt.getChildCount() ) lt.value_type_ = gen_fieldtype( (CommonTree)dt.getChild(0) ); return lt; } private ThriftMapType gen_maptype( CommonTree dt ) { ThriftMapType lt = new ThriftMapType(); lt.setDocument(doc_); if ( 1 < dt.getChildCount() ) { lt.key_type_ = gen_fieldtype( (CommonTree)dt.getChild(0) ); lt.value_type_ = gen_fieldtype( (CommonTree)dt.getChild(1) ); } return lt; } private ThriftSetType gen_settype( CommonTree dt ) { ThriftSetType lt = new ThriftSetType(); lt.setDocument(doc_); if ( 0 < dt.getChildCount() ) { lt.value_type_ = gen_fieldtype( (CommonTree)dt.getChild(1) ); } return lt; } private void gen_typedef(CommonTree dt ) { ThriftTypedef td = new ThriftTypedef(); add_typeheaderinfo(dt, td); add_type_to_scope( td ); if ( 1 < dt.getChildCount() ) td.reftype_ = gen_fieldtype( (CommonTree)dt.getChild(1)); } private void gen_enum( CommonTree dt ) { ThriftEnum en = new ThriftEnum(); en.values_ = new ArrayList<>(); add_typeheaderinfo( dt, en ); int autoVal = 0; for (int i = 1 ; i<dt.getChildCount() ; ++i ) { CommonTree ct = (CommonTree)dt.getChild(i); switch ( ct.getType() ) { case ThriftParser.IDENTIFIER: ThriftEnumValue env = new ThriftEnumValue(); env.name_ = ct.getText(); if ( 0 < ct.getChildCount() ) { int vi = get_integer((CommonTree)ct.getChild(0)); if ( vi != Integer.MIN_VALUE) autoVal = vi; } env.value_ = autoVal++; en.values_.add(env); break; } } add_type_to_scope( en ); } private void gen_struct( CommonTree dt ) { ThriftStructType s = new ThriftStructType(); add_typeheaderinfo( dt, s ); s.fields_ = new ArrayList<>(); add_type_to_scope(s); for (int i = 1 ; i<dt.getChildCount() ; ++i ) { CommonTree ct = (CommonTree)dt.getChild(i); switch ( ct.getType() ) { case ThriftParser.FIELD_: s.fields_.add( gen_field( ct )); break; } } } private ThriftField gen_field( CommonTree dt ) { ThriftField f = new ThriftField(); f.setDocument(doc_); f.name_ = get_identifier( dt ); add_comment( dt, f ); if ( 2 <= dt.getChildCount() ) f.type_ = gen_fieldtype( (CommonTree)dt.getChild(1) ); f.id_ = get_integer( (CommonTree)dt.getFirstChildWithType( ThriftParser.FIELD_ID_ ) ); return f; } private ThriftType gen_fieldtype( CommonTree dt ) { ThriftType type = null; switch ( dt.getType() ) { case ThriftParser.VOID: return ThriftType.VOID; case ThriftParser.TYPE_BOOL: return ThriftType.BOOL; case ThriftParser.TYPE_BYTE: return ThriftType.INT8; case ThriftParser.TYPE_I16: return ThriftType.INT16; case ThriftParser.TYPE_I32: return ThriftType.INT32; case ThriftParser.TYPE_I64: return ThriftType.INT64; case ThriftParser.TYPE_DOUBLE: return ThriftType.DOUBLE; case ThriftParser.TYPE_STRING: return ThriftType.STRING; case ThriftParser.TYPE_BINARY: return ThriftType.BINARY; case ThriftParser.SERVICE_PTR_TYPE: return ThriftType.SERVICE; case ThriftParser.LIST: return gen_listtype(dt); case ThriftParser.MAP: return gen_maptype(dt); case ThriftParser.SET: return gen_settype(dt); case ThriftParser.IDENTIFIER: return find_type( dt.getText() ); } return type; } private ThriftService gen_service( CommonTree dt ) { ThriftService s = new ThriftService(); s.setDocument(doc_); s.name_ = get_identifier( dt ); s.name_fully_qualified_ = get_fully_qualifiedname( s.name_ ) ; s.package_ = current_package_; s.line_ = dt.getLine() - 1 ; s.column_ = dt.getCharPositionInLine(); add_comment( dt, s ); CommonTree dtExtends = (CommonTree)dt.getChild(1); if ( dtExtends.getChildCount() > 0 ) { ThriftServiceRef sref = new ThriftServiceRef(); sref.line_ = dtExtends.getLine() - 1 ; sref.column_ = dtExtends.getCharPositionInLine(); sref.declaredName_ = get_identifier(dtExtends); sref.declarationPackage_ = current_package_; s.extended_service_ = sref; } for (int i = 2 ; i<dt.getChildCount() ; ++i ) { CommonTree dtF = (CommonTree)dt.getChild(i); switch ( dtF.getType() ) { case ThriftParser.METHOD_: ThriftFunction f = gen_function(dtF); s.functions_.add(f); f.service_ = s; break; } } return s; } private List<ThriftField> gen_parameters(CommonTree dt ) { ArrayList<ThriftField> p = new ArrayList<>(); for (int i = 0 ; i<dt.getChildCount() ; ++i ) { CommonTree dtP = (CommonTree)dt.getChild(i); switch ( dtP.getType() ) { case ThriftParser.FIELD_: p.add(gen_field(dtP)); break; } } return p; } private ThriftFunction gen_function( CommonTree dt ) { ThriftFunction f = new ThriftFunction(); f.setDocument(doc_); f.mode_ = get_function_mode(dt); f.name_ = get_identifier(dt); f.parameters_ = new ArrayList<>(); f.line_ = dt.getLine() - 1; f.column_= dt.getCharPositionInLine(); if ( 1 < dt.getChildCount() ) f.return_type_ = gen_fieldtype((CommonTree)dt.getChild(1)); add_comment( dt, f ); f.parameters_ = gen_parameters((CommonTree)dt.getFirstChildWithType(ThriftParser.ARGS_)); return f; } }
Fixed include via normal file path.
ThriftParser/src/bweng/thrift/parser/ThriftModelGenerator.java
Fixed include via normal file path.
<ide><path>hriftParser/src/bweng/thrift/parser/ThriftModelGenerator.java <ide> { <ide> try { <ide> Path bf = docFile.getParent(); <add> final String icSubPath = ic.path_.replace('\\', File.separatorChar); <ide> <ide> while ( null != bf) <ide> { <del> Path f = bf.resolve( ic.path_ ); <add> Path f = bf.resolve( icSubPath ); <ide> if ( Files.exists(f) ) <ide> { <ide> ic.ospath_ = f;
Java
mit
7d3dd28813ea3b5b9e84a754969951ba92230136
0
openforis/collect,openforis/collect,openforis/collect,openforis/collect
package org.openforis.collect.designer.component; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.Stack; import org.zkoss.zul.DefaultTreeModel; import org.zkoss.zul.DefaultTreeNode; import org.zkoss.zul.TreeNode; /** * * @author S. Ricci * */ public abstract class AbstractTreeModel<T> extends DefaultTreeModel<T> { private static final long serialVersionUID = 1L; AbstractTreeModel(AbstractTreeNode<T> root) { super(root); } public void deselect() { Collection<AbstractTreeNode<T>> emptySelection = Collections.emptyList(); setSelection(emptySelection); } public Collection<TreeNode<T>> getAllItems() { Collection<TreeNode<T>> result = new ArrayList<TreeNode<T>>(); Stack<TreeNode<T>> stack = new Stack<TreeNode<T>>(); stack.push(getRoot()); while ( ! stack.isEmpty() ) { TreeNode<T> treeNode = stack.pop(); result.add(treeNode); List<TreeNode<T>> children = treeNode.getChildren(); if ( children != null && ! children.isEmpty() ) { stack.addAll(children); } } return result; } public void openAllItems() { Collection<TreeNode<T>> allItems = getAllItems(); setOpenObjects(allItems); } public void removeSelectedNode() { int[] selectionPath = getSelectionPath(); if ( selectionPath != null ) { AbstractTreeNode<T> treeNode = (AbstractTreeNode<T>) getChild(selectionPath); AbstractTreeNode<T> parentTreeNode = (AbstractTreeNode<T>) treeNode.getParent(); parentTreeNode.remove(treeNode); } } @SuppressWarnings("unchecked") public void appendNodeToSelected(T data) { AbstractTreeNode<T> parentNode = getSelectedNode(); if( parentNode == null ) { parentNode = (AbstractTreeNode<T>) getRoot(); } else if ( parentNode.isLeaf() ) { parentNode = recreateNode(parentNode); } AbstractTreeNode<T> node = getNode(data); if ( node == null ) { node = createNode(data); parentNode.add(node); } addOpenObject(parentNode); setSelection(Arrays.asList(node)); } protected AbstractTreeNode<T> getSelectedNode() { int[] selectionPath = getSelectionPath(); return selectionPath != null ? (AbstractTreeNode<T>) getChild(selectionPath): null; } protected AbstractTreeNode<T> getParentNode(T item) { AbstractTreeNode<T> node = getNode(item); AbstractTreeNode<T> parent = (AbstractTreeNode<T>) node.getParent(); return parent; } protected int[] toArray(List<Integer> temp) { int[] result = new int[temp.size()]; for (int i = 0; i < temp.size(); i++) { int value = temp.get(i).intValue(); result[i] = value; } return result; } @SuppressWarnings("unchecked") public void select(T data) { Collection<? extends TreeNode<T>> selection; if ( data == null ) { selection = Collections.emptyList(); } else { AbstractTreeNode<T> treeNode = getNode(data); selection = Arrays.asList(treeNode); } setSelection(selection); } protected AbstractTreeNode<T> getNode(T data) { if ( data == null ) { return null; } else { int[] path = getNodePath(data); if ( path == null ) { return null; } else { return (AbstractTreeNode<T>) getChild(path); } } } protected int[] getNodePath(T data) { TreeNode<T> treeNode = getTreeNode(data); if ( treeNode == null ) { return null; } else { int[] result = getPath(treeNode); return result; } } protected TreeNode<T> getTreeNode(T data) { TreeNode<T> root = getRoot(); Stack<TreeNode<T>> treeNodesStack = new Stack<TreeNode<T>>(); treeNodesStack.push(root); while ( ! treeNodesStack.isEmpty() ) { TreeNode<T> treeNode = treeNodesStack.pop(); T treeNodeData = treeNode.getData(); if ( treeNodeData != null && treeNodeData.equals(data) ) { return treeNode; } List<TreeNode<T>> children = treeNode.getChildren(); if ( children != null && children.size() > 0 ) { treeNodesStack.addAll(children); } } return null; } protected AbstractTreeNode<T> recreateNode(AbstractTreeNode<T> node) { AbstractTreeNode<T> parent = (AbstractTreeNode<T>) node.getParent(); T data = node.getData(); AbstractTreeNode<T> newNode = createNode(data, true); parent.replace(node, newNode); return newNode; } protected AbstractTreeNode<T> createNode(T data) { return createNode(data, false); } protected abstract AbstractTreeNode<T> createNode( T data, boolean defineEmptyChildrenForLeaves); public void moveSelectedNode(int toIndex) { int[] selectionPath = getSelectionPath(); AbstractTreeNode<T> treeNode = (AbstractTreeNode<T>) getChild(selectionPath); AbstractTreeNode<T> parentTreeNode = (AbstractTreeNode<T>) treeNode.getParent(); Set<TreeNode<T>> openObjects = getOpenObjects(); parentTreeNode.insert(treeNode, toIndex); setOpenObjects(openObjects); @SuppressWarnings("unchecked") List<AbstractTreeNode<T>> selection = Arrays.asList(treeNode); setSelection(selection); } static abstract class AbstractTreeNode<T> extends DefaultTreeNode<T> { private static final long serialVersionUID = 1L; AbstractTreeNode(T data) { super(data); } AbstractTreeNode(T data, Collection<AbstractTreeNode<T>> children) { super(data, children); } void replace(TreeNode<T> oldNode, TreeNode<T> newNode) { int index = this.getIndex(oldNode); this.remove(index); this.insert(newNode, index); } } }
collect-server/src/main/java/org/openforis/collect/designer/component/AbstractTreeModel.java
package org.openforis.collect.designer.component; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.Stack; import org.openforis.collect.metamodel.ui.UITabSet; import org.zkoss.zul.DefaultTreeModel; import org.zkoss.zul.DefaultTreeNode; import org.zkoss.zul.TreeNode; /** * * @author S. Ricci * */ public abstract class AbstractTreeModel<T> extends DefaultTreeModel<T> { private static final long serialVersionUID = 1L; AbstractTreeModel(AbstractTreeNode<T> root) { super(root); } public void deselect() { Collection<AbstractTreeNode<T>> emptySelection = Collections.emptyList(); setSelection(emptySelection); } public Collection<TreeNode<T>> getAllItems() { Collection<TreeNode<T>> result = new ArrayList<TreeNode<T>>(); Stack<TreeNode<T>> stack = new Stack<TreeNode<T>>(); stack.push(getRoot()); while ( ! stack.isEmpty() ) { TreeNode<T> treeNode = stack.pop(); result.add(treeNode); List<TreeNode<T>> children = treeNode.getChildren(); if ( children != null && ! children.isEmpty() ) { stack.addAll(children); } } return result; } public void openAllItems() { Collection<TreeNode<T>> allItems = getAllItems(); setOpenObjects(allItems); } public void removeSelectedNode() { int[] selectionPath = getSelectionPath(); if ( selectionPath != null ) { AbstractTreeNode<T> treeNode = (AbstractTreeNode<T>) getChild(selectionPath); AbstractTreeNode<T> parentTreeNode = (AbstractTreeNode<T>) treeNode.getParent(); parentTreeNode.remove(treeNode); } } @SuppressWarnings("unchecked") public void appendNodeToSelected(T data) { AbstractTreeNode<T> parentNode = getSelectedNode(); if( parentNode == null ) { parentNode = (AbstractTreeNode<T>) getRoot(); } else if ( parentNode.isLeaf() ) { parentNode = recreateNode(parentNode); } AbstractTreeNode<T> node = getNode(data); if ( node == null ) { node = createNode(data); parentNode.add(node); } addOpenObject(parentNode); setSelection(Arrays.asList(node)); } protected AbstractTreeNode<T> getSelectedNode() { int[] selectionPath = getSelectionPath(); return selectionPath != null ? (AbstractTreeNode<T>) getChild(selectionPath): null; } protected AbstractTreeNode<T> getParentNode(T item) { AbstractTreeNode<T> node = getNode(item); AbstractTreeNode<T> parent = (AbstractTreeNode<T>) node.getParent(); return parent; } protected int[] toArray(List<Integer> temp) { int[] result = new int[temp.size()]; for (int i = 0; i < temp.size(); i++) { int value = temp.get(i).intValue(); result[i] = value; } return result; } @SuppressWarnings("unchecked") public void select(T data) { Collection<? extends TreeNode<T>> selection; if ( data == null ) { selection = Collections.emptyList(); } else { AbstractTreeNode<T> treeNode = getNode(data); selection = Arrays.asList(treeNode); } setSelection(selection); } protected AbstractTreeNode<T> getNode(T data) { if ( data == null ) { return null; } else { int[] path = getNodePath(data); if ( path == null ) { return null; } else { return (AbstractTreeNode<T>) getChild(path); } } } protected int[] getNodePath(T data) { TreeNode<T> treeNode = getTreeNode(data); if ( treeNode == null ) { return null; } else { int[] result = getPath(treeNode); return result; } } protected TreeNode<T> getTreeNode(T data) { TreeNode<T> root = getRoot(); Stack<TreeNode<T>> treeNodesStack = new Stack<TreeNode<T>>(); treeNodesStack.push(root); while ( ! treeNodesStack.isEmpty() ) { TreeNode<T> treeNode = treeNodesStack.pop(); T treeNodeData = treeNode.getData(); if ( treeNodeData != null && treeNodeData.equals(data) ) { return treeNode; } List<TreeNode<T>> children = treeNode.getChildren(); if ( children != null && children.size() > 0 ) { treeNodesStack.addAll(children); } } return null; } protected AbstractTreeNode<T> recreateNode(AbstractTreeNode<T> node) { AbstractTreeNode<T> parent = (AbstractTreeNode<T>) node.getParent(); T data = node.getData(); AbstractTreeNode<T> newNode = createNode(data, true); parent.replace(node, newNode); return newNode; } protected AbstractTreeNode<T> createNode(T data) { return createNode(data, false); } protected abstract AbstractTreeNode<T> createNode( T data, boolean defineEmptyChildrenForLeaves); public void moveSelectedNode(int toIndex) { int[] selectionPath = getSelectionPath(); AbstractTreeNode<T> treeNode = (AbstractTreeNode<T>) getChild(selectionPath); AbstractTreeNode<T> parentTreeNode = (AbstractTreeNode<T>) treeNode.getParent(); Set<TreeNode<T>> openObjects = getOpenObjects(); parentTreeNode.insert(treeNode, toIndex); setOpenObjects(openObjects); @SuppressWarnings("unchecked") List<AbstractTreeNode<T>> selection = Arrays.asList(treeNode); setSelection(selection); } static abstract class AbstractTreeNode<T> extends DefaultTreeNode<T> { private static final long serialVersionUID = 1L; AbstractTreeNode(T data) { super(data); } AbstractTreeNode(T data, Collection<AbstractTreeNode<T>> children) { super(data, children); } void replace(TreeNode<T> oldNode, TreeNode<T> newNode) { int index = this.getIndex(oldNode); this.remove(index); this.insert(newNode, index); } } }
Code clean
collect-server/src/main/java/org/openforis/collect/designer/component/AbstractTreeModel.java
Code clean
<ide><path>ollect-server/src/main/java/org/openforis/collect/designer/component/AbstractTreeModel.java <ide> import java.util.Set; <ide> import java.util.Stack; <ide> <del>import org.openforis.collect.metamodel.ui.UITabSet; <ide> import org.zkoss.zul.DefaultTreeModel; <ide> import org.zkoss.zul.DefaultTreeNode; <ide> import org.zkoss.zul.TreeNode;
Java
bsd-2-clause
66bfb3c1ce13ce417ab7ea4f049900f537e7d029
0
BreakingBytes/SifterReader,mikofski/SifterReader
package com.BreakingBytes.SifterReader; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.text.util.Linkify; import android.widget.TextView; public class CategoryDetail extends Activity { public static final String CATEGORY_ISSUES_URL = "issues_url"; private SifterHelper mSifterHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.categories); mSifterHelper = new SifterHelper(this); TextView categoryName = (TextView) findViewById(R.id.category_name); TextView issuesURL = (TextView) findViewById(R.id.category_issues_url); Bundle extras = getIntent().getExtras(); if (extras == null) return; try { JSONObject category = new JSONObject(extras.getString(CategoriesActivity.CATEGORY)); if (category != null && checkFields(category)) { categoryName.setText(category.getString(CategoriesActivity.CATEGORY_NAME)); issuesURL.setText(category.getString(CATEGORY_ISSUES_URL)); Linkify.addLinks(issuesURL, Linkify.WEB_URLS); } } catch (JSONException e) { e.printStackTrace(); mSifterHelper.onException(e.toString()); } } private boolean checkFields(JSONObject category) throws JSONException { String API_ISSUES_URL = "api_issues_url"; JSONArray fieldNames = category.names(); int numKeys = fieldNames.length(); for (int j = 0;j < numKeys; j++) { if (!CategoriesActivity.CATEGORY_NAME.equals(fieldNames.getString(j)) && !CATEGORY_ISSUES_URL.equals(fieldNames.getString(j)) && !API_ISSUES_URL.equals(fieldNames.getString(j))) return false; } return true; } }
src/com/BreakingBytes/SifterReader/CategoryDetail.java
package com.BreakingBytes.SifterReader; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.text.util.Linkify; import android.widget.TextView; public class CategoryDetail extends Activity { public static final String CATEGORY_ISSUES_URL = "issues_url"; private SifterHelper mSifterHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.categories); mSifterHelper = new SifterHelper(this); // capture our View elements TextView categoryName = (TextView) findViewById(R.id.category_name); TextView issuesURL = (TextView) findViewById(R.id.category_issues_url); Bundle extras = getIntent().getExtras(); if (extras != null) { try { JSONObject category = new JSONObject(extras.getString(CategoriesActivity.CATEGORY)); if (category != null && checkFields(category)) { categoryName.setText(category.getString(CategoriesActivity.CATEGORY_NAME)); issuesURL.setText(category.getString(CATEGORY_ISSUES_URL)); Linkify.addLinks(issuesURL, Linkify.WEB_URLS); } } catch (JSONException e) { e.printStackTrace(); mSifterHelper.onException(e.toString()); } } } private boolean checkFields(JSONObject category) throws JSONException { String API_ISSUES_URL = "api_issues_url"; JSONArray fieldNames = category.names(); int numKeys = fieldNames.length(); for (int j = 0;j < numKeys; j++) { if (!CategoriesActivity.CATEGORY_NAME.equals(fieldNames.getString(j)) && !CATEGORY_ISSUES_URL.equals(fieldNames.getString(j)) && !API_ISSUES_URL.equals(fieldNames.getString(j))) return false; } return true; } }
refactor nested if statements
src/com/BreakingBytes/SifterReader/CategoryDetail.java
refactor nested if statements
<ide><path>rc/com/BreakingBytes/SifterReader/CategoryDetail.java <ide> <ide> mSifterHelper = new SifterHelper(this); <ide> <del> // capture our View elements <ide> TextView categoryName = (TextView) findViewById(R.id.category_name); <ide> TextView issuesURL = (TextView) findViewById(R.id.category_issues_url); <ide> <ide> Bundle extras = getIntent().getExtras(); <del> if (extras != null) { <del> try { <del> JSONObject category = new JSONObject(extras.getString(CategoriesActivity.CATEGORY)); <del> if (category != null && checkFields(category)) { <del> categoryName.setText(category.getString(CategoriesActivity.CATEGORY_NAME)); <del> issuesURL.setText(category.getString(CATEGORY_ISSUES_URL)); <del> Linkify.addLinks(issuesURL, Linkify.WEB_URLS); <del> } <del> } catch (JSONException e) { <del> e.printStackTrace(); <del> mSifterHelper.onException(e.toString()); <add> if (extras == null) <add> return; <add> try { <add> JSONObject category = new JSONObject(extras.getString(CategoriesActivity.CATEGORY)); <add> if (category != null && checkFields(category)) { <add> categoryName.setText(category.getString(CategoriesActivity.CATEGORY_NAME)); <add> issuesURL.setText(category.getString(CATEGORY_ISSUES_URL)); <add> Linkify.addLinks(issuesURL, Linkify.WEB_URLS); <ide> } <add> } catch (JSONException e) { <add> e.printStackTrace(); <add> mSifterHelper.onException(e.toString()); <ide> } <ide> } <ide>
Java
apache-2.0
08b34608bd157352942aec45538d08f5cea1de11
0
JNOSQL/diana-driver,JNOSQL/diana-driver
/* * Copyright 2017 Otavio Santana and others * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jnosql.diana.mongodb.document; import org.jnosql.diana.api.TypeReference; import org.jnosql.diana.api.document.Document; import org.jnosql.diana.api.document.DocumentCollectionManager; import org.jnosql.diana.api.document.DocumentCondition; import org.jnosql.diana.api.document.DocumentDeleteQuery; import org.jnosql.diana.api.document.DocumentEntity; import org.jnosql.diana.api.document.DocumentQuery; import org.jnosql.diana.api.document.Documents; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import static org.hamcrest.Matchers.contains; import static org.jnosql.diana.mongodb.document.DocumentConfigurationUtils.get; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class MongoDBDocumentCollectionManagerTest { public static final String COLLECTION_NAME = "person"; private DocumentCollectionManager entityManager; @Before public void setUp() { entityManager = get().get("database"); } @Test public void shouldSave() { DocumentEntity entity = getEntity(); DocumentEntity documentEntity = entityManager.save(entity); assertTrue(documentEntity.getDocuments().stream().map(Document::getName).anyMatch(s -> s.equals("_id"))); } @Test public void shouldUpdateSave() { DocumentEntity entity = getEntity(); DocumentEntity documentEntity = entityManager.save(entity); Document newField = Documents.of("newField", "10"); entity.add(newField); DocumentEntity updated = entityManager.update(entity); assertEquals(newField, updated.find("newField").get()); } @Test public void shouldRemoveEntity() { DocumentEntity documentEntity = entityManager.save(getEntity()); DocumentQuery query = DocumentQuery.of(COLLECTION_NAME); Optional<Document> id = documentEntity.find("_id"); query.and(DocumentCondition.eq(id.get())); entityManager.delete(DocumentDeleteQuery.of(query.getCollection(), query.getCondition().get())); assertTrue(entityManager.find(query).isEmpty()); } @Test public void shouldFindDocument() { DocumentEntity entity = entityManager.save(getEntity()); DocumentQuery query = DocumentQuery.of(COLLECTION_NAME); Optional<Document> id = entity.find("_id"); query.and(DocumentCondition.eq(id.get())); List<DocumentEntity> entities = entityManager.find(query); assertFalse(entities.isEmpty()); assertThat(entities, contains(entity)); } @Test public void shouldSaveSubDocument() { DocumentEntity entity = getEntity(); entity.add(Document.of("phones", Document.of("mobile", "1231231"))); DocumentEntity entitySaved = entityManager.save(entity); Document id = entitySaved.find("_id").get(); DocumentQuery query = DocumentQuery.of(COLLECTION_NAME); query.and(DocumentCondition.eq(id)); DocumentEntity entityFound = entityManager.find(query).get(0); Document subDocument = entityFound.find("phones").get(); Map<String, String> result = subDocument.get(new TypeReference<Map<String, String>>() {}); String key = result.keySet().stream().findFirst().get(); String value = result.get(key); assertEquals("mobile", key); assertEquals("1231231", value); } private DocumentEntity getEntity() { DocumentEntity entity = DocumentEntity.of(COLLECTION_NAME); Map<String, Object> map = new HashMap<>(); map.put("name", "Poliana"); map.put("city", "Salvador"); List<Document> documents = Documents.of(map); documents.forEach(entity::add); return entity; } }
mongodb-driver/src/test/java/org/jnosql/diana/mongodb/document/MongoDBDocumentCollectionManagerTest.java
/* * Copyright 2017 Otavio Santana and others * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jnosql.diana.mongodb.document; import org.jnosql.diana.api.document.Document; import org.jnosql.diana.api.document.DocumentCollectionManager; import org.jnosql.diana.api.document.DocumentCondition; import org.jnosql.diana.api.document.DocumentDeleteQuery; import org.jnosql.diana.api.document.DocumentEntity; import org.jnosql.diana.api.document.DocumentQuery; import org.jnosql.diana.api.document.Documents; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import static org.hamcrest.Matchers.contains; import static org.jnosql.diana.mongodb.document.DocumentConfigurationUtils.get; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class MongoDBDocumentCollectionManagerTest { public static final String COLLECTION_NAME = "person"; private DocumentCollectionManager entityManager; @Before public void setUp() { entityManager = get().get("database"); } @Test public void shouldSave() { DocumentEntity entity = getEntity(); DocumentEntity documentEntity = entityManager.save(entity); assertTrue(documentEntity.getDocuments().stream().map(Document::getName).anyMatch(s -> s.equals("_id"))); } @Test public void shouldUpdateSave() { DocumentEntity entity = getEntity(); DocumentEntity documentEntity = entityManager.save(entity); Document newField = Documents.of("newField", "10"); entity.add(newField); DocumentEntity updated = entityManager.update(entity); assertEquals(newField, updated.find("newField").get()); } @Test public void shouldRemoveEntity() { DocumentEntity documentEntity = entityManager.save(getEntity()); DocumentQuery query = DocumentQuery.of(COLLECTION_NAME); Optional<Document> id = documentEntity.find("_id"); query.and(DocumentCondition.eq(id.get())); entityManager.delete(DocumentDeleteQuery.of(query.getCollection(), query.getCondition().get())); assertTrue(entityManager.find(query).isEmpty()); } @Test public void shouldFindDocument() { DocumentEntity entity = entityManager.save(getEntity()); DocumentQuery query = DocumentQuery.of(COLLECTION_NAME); Optional<Document> id = entity.find("_id"); query.and(DocumentCondition.eq(id.get())); List<DocumentEntity> entities = entityManager.find(query); assertFalse(entities.isEmpty()); assertThat(entities, contains(entity)); } @Test public void shouldSaveSubDocument() { DocumentEntity entity = getEntity(); entity.add(Document.of("phones", Document.of("mobile", "1231231"))); DocumentEntity entitySaved = entityManager.save(entity); Document id = entitySaved.find("_id").get(); DocumentQuery query = DocumentQuery.of(COLLECTION_NAME); query.and(DocumentCondition.eq(id)); DocumentEntity entityFound = entityManager.find(query).get(0); Map<String, String> result = (Map<String, String>) entityFound.find("phones").get().getValue().get(); String key = result.keySet().stream().findFirst().get(); String value = result.get(key); assertEquals("mobile", key); assertEquals("1231231", value); } private DocumentEntity getEntity() { DocumentEntity entity = DocumentEntity.of(COLLECTION_NAME); Map<String, Object> map = new HashMap<>(); map.put("name", "Poliana"); map.put("city", "Salvador"); List<Document> documents = Documents.of(map); documents.forEach(entity::add); return entity; } }
Fixes api
mongodb-driver/src/test/java/org/jnosql/diana/mongodb/document/MongoDBDocumentCollectionManagerTest.java
Fixes api
<ide><path>ongodb-driver/src/test/java/org/jnosql/diana/mongodb/document/MongoDBDocumentCollectionManagerTest.java <ide> <ide> package org.jnosql.diana.mongodb.document; <ide> <add>import org.jnosql.diana.api.TypeReference; <ide> import org.jnosql.diana.api.document.Document; <ide> import org.jnosql.diana.api.document.DocumentCollectionManager; <ide> import org.jnosql.diana.api.document.DocumentCondition; <ide> DocumentQuery query = DocumentQuery.of(COLLECTION_NAME); <ide> query.and(DocumentCondition.eq(id)); <ide> DocumentEntity entityFound = entityManager.find(query).get(0); <del> Map<String, String> result = (Map<String, String>) entityFound.find("phones").get().getValue().get(); <add> Document subDocument = entityFound.find("phones").get(); <add> Map<String, String> result = subDocument.get(new TypeReference<Map<String, String>>() {}); <ide> String key = result.keySet().stream().findFirst().get(); <ide> String value = result.get(key); <ide> assertEquals("mobile", key);
Java
apache-2.0
d7c4b1eed425168e4ba59362fe7c5c3704dcd9b0
0
Wikidata/Wikidata-Toolkit,Wikidata/Wikidata-Toolkit
package org.wikidata.wdtk.examples; /* * #%L * Wikidata Toolkit Examples * %% * Copyright (C) 2014 - 2015 Wikidata Toolkit Developers * %% * 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. * #L% */ import java.io.IOException; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import org.wikidata.wdtk.datamodel.helpers.Datamodel; import org.wikidata.wdtk.datamodel.interfaces.EntityDocument; import org.wikidata.wdtk.datamodel.interfaces.ItemDocument; import org.wikidata.wdtk.wikibaseapi.BasicApiConnection; import org.wikidata.wdtk.wikibaseapi.WbSearchEntitiesResult; import org.wikidata.wdtk.wikibaseapi.WikibaseDataFetcher; import org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException; public class FetchOnlineDataExample { public static void main(String[] args) throws MediaWikiApiErrorException, IOException { ExampleHelpers.configureLogging(); printDocumentation(); WikibaseDataFetcher wbdf = new WikibaseDataFetcher( BasicApiConnection.getWikidataApiConnection(), Datamodel.SITE_WIKIDATA); System.out.println("*** Fetching data for one entity:"); EntityDocument q42 = wbdf.getEntityDocument("Q42"); System.out.println(q42); if (q42 instanceof ItemDocument) { System.out.println("The English name for entity Q42 is " + ((ItemDocument) q42).getLabels().get("en").getText()); } System.out.println("*** Fetching data for several entities:"); Map<String, EntityDocument> results = wbdf.getEntityDocuments("Q80", "P31"); // Keys of this map are Qids, but we only use the values here: for (EntityDocument ed : results.values()) { System.out.println("Successfully retrieved data for " + ed.getEntityId().getId()); } System.out .println("*** Fetching data using filters to reduce data volume:"); // Only site links from English Wikipedia: wbdf.getFilter().setSiteLinkFilter(Collections.singleton("enwiki")); // Only labels in French: wbdf.getFilter().setLanguageFilter(Collections.singleton("fr")); // No statements at all: wbdf.getFilter().setPropertyFilter(Collections.emptySet()); EntityDocument q8 = wbdf.getEntityDocument("Q8"); if (q8 instanceof ItemDocument) { System.out.println("The French label for entity Q8 is " + ((ItemDocument) q8).getLabels().get("fr").getText() + "\nand its English Wikipedia page has the title " + ((ItemDocument) q8).getSiteLinks().get("enwiki") .getPageTitle() + "."); } System.out.println("*** Fetching data based on page title:"); EntityDocument edPratchett = wbdf.getEntityDocumentByTitle("enwiki", "Terry Pratchett"); System.out.println("The Qid of Terry Pratchett is " + edPratchett.getEntityId().getId()); System.out.println("*** Fetching data based on several page titles:"); results = wbdf.getEntityDocumentsByTitle("enwiki", "Wikidata", "Wikipedia"); // In this case, keys are titles rather than Qids for (Entry<String, EntityDocument> entry : results.entrySet()) { System.out .println("Successfully retrieved data for page entitled \"" + entry.getKey() + "\": " + entry.getValue().getEntityId().getId()); } System.out.println("** Doing search on Wikidata:"); for(WbSearchEntitiesResult result : wbdf.searchEntities("Douglas Adams", "fr")) { System.out.println("Found " + result.getEntityId() + " with label " + result.getLabel()); } System.out.println("*** Done."); } /** * Prints some basic documentation about this program. */ public static void printDocumentation() { System.out .println("********************************************************************"); System.out.println("*** Wikidata Toolkit: FetchOnlineDataExample"); System.out.println("*** "); System.out .println("*** This program fetches individual data using the wikidata.org API."); System.out.println("*** It does not download any dump files."); System.out .println("********************************************************************"); } }
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/FetchOnlineDataExample.java
package org.wikidata.wdtk.examples; import java.io.IOException; /* * #%L * Wikidata Toolkit Examples * %% * Copyright (C) 2014 - 2015 Wikidata Toolkit Developers * %% * 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. * #L% */ import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import org.wikidata.wdtk.datamodel.helpers.Datamodel; import org.wikidata.wdtk.datamodel.interfaces.EntityDocument; import org.wikidata.wdtk.datamodel.interfaces.ItemDocument; import org.wikidata.wdtk.wikibaseapi.ApiConnection; import org.wikidata.wdtk.wikibaseapi.WbSearchEntitiesResult; import org.wikidata.wdtk.wikibaseapi.WikibaseDataFetcher; import org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException; public class FetchOnlineDataExample { public static void main(String[] args) throws MediaWikiApiErrorException, IOException { ExampleHelpers.configureLogging(); printDocumentation(); WikibaseDataFetcher wbdf = new WikibaseDataFetcher( ApiConnection.getTestWikidataApiConnection(), Datamodel.SITE_WIKIDATA); System.out.println("*** Fetching data for one entity:"); EntityDocument q42 = wbdf.getEntityDocument("P176"); System.out.println(q42); if (q42 instanceof ItemDocument) { System.out.println("The English name for entity Q42 is " + ((ItemDocument) q42).getLabels().get("en").getText()); } System.out.println("*** Fetching data for several entities:"); Map<String, EntityDocument> results = wbdf.getEntityDocuments("Q80", "P31"); // Keys of this map are Qids, but we only use the values here: for (EntityDocument ed : results.values()) { System.out.println("Successfully retrieved data for " + ed.getEntityId().getId()); } System.out .println("*** Fetching data using filters to reduce data volume:"); // Only site links from English Wikipedia: wbdf.getFilter().setSiteLinkFilter(Collections.singleton("enwiki")); // Only labels in French: wbdf.getFilter().setLanguageFilter(Collections.singleton("fr")); // No statements at all: wbdf.getFilter().setPropertyFilter(Collections.emptySet()); EntityDocument q8 = wbdf.getEntityDocument("Q8"); if (q8 instanceof ItemDocument) { System.out.println("The French label for entity Q8 is " + ((ItemDocument) q8).getLabels().get("fr").getText() + "\nand its English Wikipedia page has the title " + ((ItemDocument) q8).getSiteLinks().get("enwiki") .getPageTitle() + "."); } System.out.println("*** Fetching data based on page title:"); EntityDocument edPratchett = wbdf.getEntityDocumentByTitle("enwiki", "Terry Pratchett"); System.out.println("The Qid of Terry Pratchett is " + edPratchett.getEntityId().getId()); System.out.println("*** Fetching data based on several page titles:"); results = wbdf.getEntityDocumentsByTitle("enwiki", "Wikidata", "Wikipedia"); // In this case, keys are titles rather than Qids for (Entry<String, EntityDocument> entry : results.entrySet()) { System.out .println("Successfully retrieved data for page entitled \"" + entry.getKey() + "\": " + entry.getValue().getEntityId().getId()); } System.out.println("** Doing search on Wikidata:"); for(WbSearchEntitiesResult result : wbdf.searchEntities("Douglas Adams", "fr")) { System.out.println("Found " + result.getEntityId() + " with label " + result.getLabel()); } System.out.println("*** Done."); } /** * Prints some basic documentation about this program. */ public static void printDocumentation() { System.out .println("********************************************************************"); System.out.println("*** Wikidata Toolkit: FetchOnlineDataExample"); System.out.println("*** "); System.out .println("*** This program fetches individual data using the wikidata.org API."); System.out.println("*** It does not download any dump files."); System.out .println("********************************************************************"); } }
Improves FetchOnlineDataExample
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/FetchOnlineDataExample.java
Improves FetchOnlineDataExample
<ide><path>dtk-examples/src/main/java/org/wikidata/wdtk/examples/FetchOnlineDataExample.java <ide> package org.wikidata.wdtk.examples; <del> <del>import java.io.IOException; <ide> <ide> /* <ide> * #%L <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * You may obtain a copy of the License at <del> * <add> * <ide> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <add> * <ide> * Unless required by applicable law or agreed to in writing, software <ide> * distributed under the License is distributed on an "AS IS" BASIS, <ide> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <ide> * #L% <ide> */ <ide> <add>import java.io.IOException; <ide> import java.util.Collections; <ide> import java.util.Map; <ide> import java.util.Map.Entry; <ide> import org.wikidata.wdtk.datamodel.helpers.Datamodel; <ide> import org.wikidata.wdtk.datamodel.interfaces.EntityDocument; <ide> import org.wikidata.wdtk.datamodel.interfaces.ItemDocument; <del>import org.wikidata.wdtk.wikibaseapi.ApiConnection; <add>import org.wikidata.wdtk.wikibaseapi.BasicApiConnection; <ide> import org.wikidata.wdtk.wikibaseapi.WbSearchEntitiesResult; <ide> import org.wikidata.wdtk.wikibaseapi.WikibaseDataFetcher; <ide> import org.wikidata.wdtk.wikibaseapi.apierrors.MediaWikiApiErrorException; <ide> printDocumentation(); <ide> <ide> WikibaseDataFetcher wbdf = new WikibaseDataFetcher( <del> ApiConnection.getTestWikidataApiConnection(), <add> BasicApiConnection.getWikidataApiConnection(), <ide> Datamodel.SITE_WIKIDATA); <ide> <ide> System.out.println("*** Fetching data for one entity:"); <del> EntityDocument q42 = wbdf.getEntityDocument("P176"); <add> EntityDocument q42 = wbdf.getEntityDocument("Q42"); <ide> System.out.println(q42); <ide> <ide> if (q42 instanceof ItemDocument) { <ide> + ((ItemDocument) q8).getLabels().get("fr").getText() <ide> + "\nand its English Wikipedia page has the title " <ide> + ((ItemDocument) q8).getSiteLinks().get("enwiki") <del> .getPageTitle() + "."); <add> .getPageTitle() + "."); <ide> } <ide> <ide> System.out.println("*** Fetching data based on page title:");
Java
mit
1173b6704944222b23097ab7020b0417d5ce094a
0
hgl888/AntennaPod,ChaoticMind/AntennaPod,johnjohndoe/AntennaPod,waylife/AntennaPod,gk23/AntennaPod,volhol/AntennaPod,mxttie/AntennaPod,wskplho/AntennaPod,jimulabs/AntennaPod-mirror,gaohongyuan/AntennaPod,gaohongyuan/AntennaPod,wangjun/AntennaPod,corecode/AntennaPod,johnjohndoe/AntennaPod,udif/AntennaPod,udif/AntennaPod,richq/AntennaPod,gaohongyuan/AntennaPod,wooi/AntennaPod,TimB0/AntennaPod,keunes/AntennaPod,corecode/AntennaPod,TomHennen/AntennaPod,johnjohndoe/AntennaPod,TomHennen/AntennaPod,drabux/AntennaPod,volhol/AntennaPod,SpicyCurry/AntennaPod,mxttie/AntennaPod,mfietz/AntennaPod,domingos86/AntennaPod,drabux/AntennaPod,twiceyuan/AntennaPod,richq/AntennaPod,domingos86/AntennaPod,LTUvac/AntennaPod,richq/AntennaPod,jimulabs/AntennaPod-mirror,volhol/AntennaPod,twiceyuan/AntennaPod,waylife/AntennaPod,SpicyCurry/AntennaPod,mxttie/AntennaPod,queenp/AntennaPod,TimB0/AntennaPod,wskplho/AntennaPod,LTUvac/AntennaPod,queenp/AntennaPod,drabux/AntennaPod,cdysthe/AntennaPod,keunes/AntennaPod,gk23/AntennaPod,TomHennen/AntennaPod,LTUvac/AntennaPod,the100rabh/AntennaPod,twiceyuan/AntennaPod,waylife/AntennaPod,corecode/AntennaPod,queenp/AntennaPod,LTUvac/AntennaPod,mfietz/AntennaPod,mfietz/AntennaPod,the100rabh/AntennaPod,corecode/AntennaPod,hgl888/AntennaPod,samarone/AntennaPod,samarone/AntennaPod,wooi/AntennaPod,the100rabh/AntennaPod,wangjun/AntennaPod,TomHennen/AntennaPod,mfietz/AntennaPod,wooi/AntennaPod,gk23/AntennaPod,mxttie/AntennaPod,keunes/AntennaPod,samarone/AntennaPod,wangjun/AntennaPod,orelogo/AntennaPod,domingos86/AntennaPod,SpicyCurry/AntennaPod,cdysthe/AntennaPod,TimB0/AntennaPod,wooi/AntennaPod,orelogo/AntennaPod,domingos86/AntennaPod,jimulabs/AntennaPod-mirror,udif/AntennaPod,orelogo/AntennaPod,cdysthe/AntennaPod,keunes/AntennaPod,johnjohndoe/AntennaPod,drabux/AntennaPod,gaohongyuan/AntennaPod,SpicyCurry/AntennaPod,ChaoticMind/AntennaPod,wangjun/AntennaPod,ChaoticMind/AntennaPod,orelogo/AntennaPod,the100rabh/AntennaPod,twiceyuan/AntennaPod,wskplho/AntennaPod,richq/AntennaPod,hgl888/AntennaPod,TimB0/AntennaPod,udif/AntennaPod,gk23/AntennaPod
package de.danoeh.antennapod.core.syndication.util; import android.util.Log; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * Parses several date formats. */ public class SyndDateUtils { private static final String TAG = "DateUtils"; private static final String[] RFC822DATES = {"dd MMM yy HH:mm:ss Z",}; /** * RFC 3339 date format for UTC dates. */ public static final String RFC3339UTC = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * RFC 3339 date format for localtime dates with offset. */ public static final String RFC3339LOCAL = "yyyy-MM-dd'T'HH:mm:ssZ"; private static ThreadLocal<SimpleDateFormat> RFC822Formatter = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat(RFC822DATES[0], Locale.US); } }; private static ThreadLocal<SimpleDateFormat> RFC3339Formatter = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat(RFC3339UTC, Locale.US); } }; public static Date parseRFC822Date(String date) { Date result = null; if (date.contains("PDT")) { date = date.replace("PDT", "PST8PDT"); } if (date.contains(",")) { // Remove day of the week date = date.substring(date.indexOf(",") + 1).trim(); } SimpleDateFormat format = RFC822Formatter.get(); for (int i = 0; i < RFC822DATES.length; i++) { try { format.applyPattern(RFC822DATES[i]); result = format.parse(date); break; } catch (ParseException e) { e.printStackTrace(); } } if (result == null) { Log.e(TAG, "Unable to parse feed date correctly"); } return result; } public static Date parseRFC3339Date(String date) { Date result = null; SimpleDateFormat format = RFC3339Formatter.get(); boolean isLocal = date.endsWith("Z"); if (date.contains(".")) { // remove secfrac int fracIndex = date.indexOf("."); String first = date.substring(0, fracIndex); String second = null; if (isLocal) { second = date.substring(date.length() - 1); } else { if (date.contains("+")) { second = date.substring(date.indexOf("+")); } else { second = date.substring(date.indexOf("-")); } } date = first + second; } if (isLocal) { try { result = format.parse(date); } catch (ParseException e) { e.printStackTrace(); } } else { format.applyPattern(RFC3339LOCAL); // remove last colon StringBuffer buf = new StringBuffer(date.length() - 1); int colonIdx = date.lastIndexOf(':'); for (int x = 0; x < date.length(); x++) { if (x != colonIdx) buf.append(date.charAt(x)); } String bufStr = buf.toString(); try { result = format.parse(bufStr); } catch (ParseException e) { e.printStackTrace(); Log.e(TAG, "Unable to parse date"); } finally { format.applyPattern(RFC3339UTC); } } return result; } /** * Takes a string of the form [HH:]MM:SS[.mmm] and converts it to * milliseconds. * * @throws java.lang.NumberFormatException if the number segments contain invalid numbers. */ public static long parseTimeString(final String time) { String[] parts = time.split(":"); long result = 0; int idx = 0; if (parts.length == 3) { // string has hours result += Integer.valueOf(parts[idx]) * 3600000L; idx++; } if (parts.length >= 2) { result += Integer.valueOf(parts[idx]) * 60000L; idx++; result += (Float.valueOf(parts[idx])) * 1000L; } return result; } public static String formatRFC822Date(Date date) { SimpleDateFormat format = RFC822Formatter.get(); return format.format(date); } public static String formatRFC3339Local(Date date) { SimpleDateFormat format = RFC3339Formatter.get(); format.applyPattern(RFC3339LOCAL); String result = format.format(date); format.applyPattern(RFC3339UTC); return result; } public static String formatRFC3339UTC(Date date) { SimpleDateFormat format = RFC3339Formatter.get(); format.applyPattern(RFC3339UTC); return format.format(date); } }
core/src/main/java/de/danoeh/antennapod/core/syndication/util/SyndDateUtils.java
package de.danoeh.antennapod.core.syndication.util; import android.util.Log; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * Parses several date formats. */ public class SyndDateUtils { private static final String TAG = "DateUtils"; private static final String[] RFC822DATES = {"dd MMM yy HH:mm:ss Z",}; /** * RFC 3339 date format for UTC dates. */ public static final String RFC3339UTC = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * RFC 3339 date format for localtime dates with offset. */ public static final String RFC3339LOCAL = "yyyy-MM-dd'T'HH:mm:ssZ"; private static ThreadLocal<SimpleDateFormat> RFC822Formatter = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat(RFC822DATES[0], Locale.US); } }; private static ThreadLocal<SimpleDateFormat> RFC3339Formatter = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat(RFC3339UTC, Locale.US); } }; public static Date parseRFC822Date(String date) { Date result = null; if (date.contains("PDT")) { date = date.replace("PDT", "PST8PDT"); } if (date.contains(",")) { // Remove day of the week date = date.substring(date.indexOf(",") + 1).trim(); } SimpleDateFormat format = RFC822Formatter.get(); for (int i = 0; i < RFC822DATES.length; i++) { try { format.applyPattern(RFC822DATES[i]); result = format.parse(date); break; } catch (ParseException e) { e.printStackTrace(); } } if (result == null) { Log.e(TAG, "Unable to parse feed date correctly"); } return result; } public static Date parseRFC3339Date(String date) { Date result = null; SimpleDateFormat format = RFC3339Formatter.get(); boolean isLocal = date.endsWith("Z"); if (date.contains(".")) { // remove secfrac int fracIndex = date.indexOf("."); String first = date.substring(0, fracIndex); String second = null; if (isLocal) { second = date.substring(date.length() - 1); } else { if (date.contains("+")) { second = date.substring(date.indexOf("+")); } else { second = date.substring(date.indexOf("-")); } } date = first + second; } if (isLocal) { try { result = format.parse(date); } catch (ParseException e) { e.printStackTrace(); } } else { format.applyPattern(RFC3339LOCAL); // remove last colon StringBuffer buf = new StringBuffer(date.length() - 1); int colonIdx = date.lastIndexOf(':'); for (int x = 0; x < date.length(); x++) { if (x != colonIdx) buf.append(date.charAt(x)); } String bufStr = buf.toString(); try { result = format.parse(bufStr); } catch (ParseException e) { e.printStackTrace(); Log.e(TAG, "Unable to parse date"); } finally { format.applyPattern(RFC3339UTC); } } return result; } /** * Takes a string of the form [HH:]MM:SS[.mmm] and converts it to * milliseconds. * * @throws java.lang.NumberFormatException if the number segments contain invalid numbers. */ public static long parseTimeString(final String time) { String[] parts = time.split(":"); long result = 0; int idx = 0; if (parts.length == 3) { // string has hours result += Integer.valueOf(parts[idx]) * 3600000L; idx++; } result += Integer.valueOf(parts[idx]) * 60000L; idx++; result += (Float.valueOf(parts[idx])) * 1000L; return result; } public static String formatRFC822Date(Date date) { SimpleDateFormat format = RFC822Formatter.get(); return format.format(date); } public static String formatRFC3339Local(Date date) { SimpleDateFormat format = RFC3339Formatter.get(); format.applyPattern(RFC3339LOCAL); String result = format.format(date); format.applyPattern(RFC3339UTC); return result; } public static String formatRFC3339UTC(Date date) { SimpleDateFormat format = RFC3339Formatter.get(); format.applyPattern(RFC3339UTC); return format.format(date); } }
Fixed IndexOutOfBoundsException in parseTimeString
core/src/main/java/de/danoeh/antennapod/core/syndication/util/SyndDateUtils.java
Fixed IndexOutOfBoundsException in parseTimeString
<ide><path>ore/src/main/java/de/danoeh/antennapod/core/syndication/util/SyndDateUtils.java <ide> result += Integer.valueOf(parts[idx]) * 3600000L; <ide> idx++; <ide> } <del> result += Integer.valueOf(parts[idx]) * 60000L; <del> idx++; <del> result += (Float.valueOf(parts[idx])) * 1000L; <add> if (parts.length >= 2) { <add> result += Integer.valueOf(parts[idx]) * 60000L; <add> idx++; <add> result += (Float.valueOf(parts[idx])) * 1000L; <add> } <ide> return result; <ide> } <ide>
Java
apache-2.0
826887fabac78a03098ccebdb69c652532619f57
0
GwtMaterialDesign/gwt-material-demo,GwtMaterialDesign/gwt-material-demo,GwtMaterialDesign/gwt-material-demo,GwtMaterialDesign/gwt-material-demo
package gwt.material.design.demo.client.application.components.navbar; /* * #%L * GwtMaterial * %% * Copyright (C) 2015 - 2016 GwtMaterialDesign * %% * 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. * #L% */ import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Widget; import com.gwtplatform.mvp.client.ViewImpl; import gwt.material.design.client.ui.MaterialNavSection; import gwt.material.design.client.ui.MaterialPanel; import gwt.material.design.client.ui.MaterialToast; import gwt.material.design.demo.client.application.dto.DemoImageDTO; import gwt.material.design.demo.client.application.dto.DemoImagePanel; import javax.inject.Inject; public class NavBarView extends ViewImpl implements NavBarPresenter.MyView { interface Binder extends UiBinder<Widget, NavBarView> { } @UiField MaterialPanel typePanel; @UiField MaterialNavSection navSection; @Inject NavBarView(Binder uiBinder) { initWidget(uiBinder.createAndBindUi(this)); navSection.addSelectionHandler(selectionEvent -> MaterialToast.fireToast(selectionEvent.getSelectedItem() + " Selected Index")); typePanel.add(new DemoImagePanel(new DemoImageDTO("Default NavBar", "Provides a non-fixed navbar. Good for blogs.", "http://i.imgur.com/rGx7XRW.gif", generateDemoLink("default"), generateSource("navbardefault/DefaultNavBarView.ui.xml")))); typePanel.add(new DemoImagePanel(new DemoImageDTO("Fixed NavBar", "By setting layoutPosition='FIXED', your navbar will be fixed on top when scrolling through the content.", "http://i.imgur.com/muYAAjl.gif", generateDemoLink("fixed"), generateSource("navbarfixed/FixedNavBarView.ui.xml")))); typePanel.add(new DemoImagePanel(new DemoImageDTO("Tall NavBar", "You can easily adjust the navbar's height to make it tall by height='200px',", "http://i.imgur.com/dtUsHRd.gif", generateDemoLink("tall"), generateSource("navbartall/TallNavBarView.ui.xml")))); typePanel.add(new DemoImagePanel(new DemoImageDTO("Extended NavBar", "Using MaterialNavContent - you can easily attached any component for the extension of your MaterialNavBar", "http://i.imgur.com/bUYC6qs.png", generateDemoLink("extend"), generateSource("navbarextend/ExtendNavBarView.ui.xml")))); typePanel.add(new DemoImagePanel(new DemoImageDTO("Tabs in NavBar", "You can easily add tabs for secondary navigation on MaterialNavBar by attaching it on MaterialNavContent", "http://i.imgur.com/7c3AGBs.png", generateDemoLink("tab"), generateSource("navbartab/TabNavBarView.ui.xml")))); typePanel.add(new DemoImagePanel(new DemoImageDTO("Shrinkable NavBar", "Provides a delightful scrolling effect when expanding or shrinking the navbar.", "http://i.imgur.com/tHUDgqB.gif", generateDemoLink("shrink"), generateSource("navbarshrink/ShrinkNavBarView.ui.xml")))); } protected String generateSource(String type) { return "https://github.com/GwtMaterialDesign/gwt-material-patterns/tree/release_2.0/src/main/java/com/github/gwtmaterialdesign/client/application/" + type; } protected String generateDemoLink(String type) { return "https://gwtmaterialdesign.github.io/gwt-material-patterns/snapshot/#navbar_" + type; } }
src/main/java/gwt/material/design/demo/client/application/components/navbar/NavBarView.java
package gwt.material.design.demo.client.application.components.navbar; /* * #%L * GwtMaterial * %% * Copyright (C) 2015 - 2016 GwtMaterialDesign * %% * 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. * #L% */ import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Widget; import com.gwtplatform.mvp.client.ViewImpl; import gwt.material.design.client.ui.MaterialNavSection; import gwt.material.design.client.ui.MaterialPanel; import gwt.material.design.client.ui.MaterialToast; import gwt.material.design.demo.client.application.dto.DemoImageDTO; import gwt.material.design.demo.client.application.dto.DemoImagePanel; import javax.inject.Inject; public class NavBarView extends ViewImpl implements NavBarPresenter.MyView { interface Binder extends UiBinder<Widget, NavBarView> { } @UiField MaterialPanel typePanel; @UiField MaterialNavSection navSection; @Inject NavBarView(Binder uiBinder) { initWidget(uiBinder.createAndBindUi(this)); navSection.addSelectionHandler(selectionEvent -> MaterialToast.fireToast(selectionEvent.getSelectedItem() + " Selected Index")); typePanel.add(new DemoImagePanel(new DemoImageDTO("Default NavBar", "Provides a non-fixed navbar. Good for blogs.", "http://i.imgur.com/rGx7XRW.gif", generateDemoLink("default"), generateSource("navbardefault/DefaultNavBarView.ui.xml")))); typePanel.add(new DemoImagePanel(new DemoImageDTO("Fixed NavBar", "By setting layoutPosition='FIXED', your navbar will be fixed on top when scrolling through the content.", "http://i.imgur.com/muYAAjl.gif", generateDemoLink("fixed"), generateSource("navbarfixed/FixedNavBarView.ui.xml")))); typePanel.add(new DemoImagePanel(new DemoImageDTO("Tall NavBar", "You can easily adjust the navbar's height to make it tall by height='200px',", "http://i.imgur.com/dtUsHRd.gif", generateDemoLink("tall"), generateSource("navbartall/TallNavBarView.ui.xml")))); typePanel.add(new DemoImagePanel(new DemoImageDTO("Extended NavBar", "Using MaterialNavContent - you can easily attached any component for the extension of your MaterialNavBar", "http://i.imgur.com/bUYC6qs.png", generateDemoLink("extend"), generateSource("navbarextend/ExtendNavBarView.ui.xml")))); typePanel.add(new DemoImagePanel(new DemoImageDTO("Tabs in NavBar", "You can easily add tabs for secondary navigation on MaterialNavBar by attaching it on MaterialNavContent", "http://i.imgur.com/7c3AGBs.png", generateDemoLink("tabs"), generateSource("navbartab/TabNavBarView.ui.xml")))); typePanel.add(new DemoImagePanel(new DemoImageDTO("Shrinkable NavBar", "Provides a delightful scrolling effect when expanding or shrinking the navbar.", "http://i.imgur.com/tHUDgqB.gif", generateDemoLink("shrink"), generateSource("navbarshrink/ShrinkNavBarView.ui.xml")))); } protected String generateSource(String type) { return "https://github.com/GwtMaterialDesign/gwt-material-patterns/tree/release_2.0/src/main/java/com/github/gwtmaterialdesign/client/application/" + type; } protected String generateDemoLink(String type) { return "https://gwtmaterialdesign.github.io/gwt-material-patterns/snapshot/#navbar_" + type; } }
Fixed navbar tabs link demo.
src/main/java/gwt/material/design/demo/client/application/components/navbar/NavBarView.java
Fixed navbar tabs link demo.
<ide><path>rc/main/java/gwt/material/design/demo/client/application/components/navbar/NavBarView.java <ide> <ide> typePanel.add(new DemoImagePanel(new DemoImageDTO("Tabs in NavBar", "You can easily add tabs for secondary navigation on MaterialNavBar by attaching it on MaterialNavContent", <ide> "http://i.imgur.com/7c3AGBs.png", <del> generateDemoLink("tabs"), <add> generateDemoLink("tab"), <ide> generateSource("navbartab/TabNavBarView.ui.xml")))); <ide> <ide> typePanel.add(new DemoImagePanel(new DemoImageDTO("Shrinkable NavBar", "Provides a delightful scrolling effect when expanding or shrinking the navbar.",
JavaScript
mit
d095f50c596cd979222a0cd4b6673b058d7dabcd
0
buildo/react-autosize-textarea,buildo/react-autosize-textarea,buildo/react-autosize-textarea,buildo/react-autosize-textarea
import React from 'react'; import TextareaAutosize from '../src/TextareaAutosize'; class Example extends React.Component { constructor(props) { super(props); this.state = { value: 'replace me with your component' }; } render() { const textareaStyle = { padding: '10px 8px', border: '1px solid rgba(39,41,43,.15)', borderRadius: 4, fontSize: 15 }; return ( <div style={{ fontFamily: 'sans-serif', margin: 15 }}> <h2>Empty</h2> <TextareaAutosize style={textareaStyle} placeholder='try writing some lines' /> <h2>Minimum Height</h2> <TextareaAutosize rows='3' style={textareaStyle} placeholder='minimun height is 3 rows' /> <h2>Prefilled</h2> <TextareaAutosize style={textareaStyle} defaultValue={'this\nis\na\nlong\ninitial\ntext'} /> <h2>{'You can compare with this normal react <textarea>'}</h2> <textarea style={textareaStyle} defaultValue={'this\nis\na\nlong\ninitial\ntext'} /> </div> ); } } React.render(<Example />, document.getElementById('container'));
examples/examples.js
import React from 'react'; import TextareaAutosize from '../src/TextareaAutosize'; const Example = React.createClass({ propTypes: {}, getInitialState() { return { value: 'replace me with your component' }; }, render() { const textareaStyle = { padding: '10px 8px', border: '1px solid rgba(39,41,43,.15)', borderRadius: 4, fontSize: 15 }; return ( <div style={{fontFamily: 'sans-serif', margin: 15}}> <h2>Empty</h2> <TextareaAutosize style={textareaStyle} placeholder='try writing some lines'/> <h2>Minimum Height</h2> <TextareaAutosize rows='3' style={textareaStyle} placeholder='minimun height is 3 rows'/> <h2>Prefilled</h2> <TextareaAutosize style={textareaStyle} defaultValue={'this\nis\na\nlong\ninitial\ntext'}/> <h2>{'You can compare with this normal react <textarea>'}</h2> <textarea style={textareaStyle} defaultValue={'this\nis\na\nlong\ninitial\ntext'}/> </div> ); } }); React.render(<Example />, document.getElementById('container'));
use React.Component in examples
examples/examples.js
use React.Component in examples
<ide><path>xamples/examples.js <ide> import React from 'react'; <ide> import TextareaAutosize from '../src/TextareaAutosize'; <ide> <del>const Example = React.createClass({ <add>class Example extends React.Component { <ide> <del> propTypes: {}, <del> <del> getInitialState() { <del> return { <add> constructor(props) { <add> super(props); <add> this.state = { <ide> value: 'replace me with your component' <ide> }; <del> }, <add> } <ide> <ide> render() { <ide> <ide> }; <ide> <ide> return ( <del> <div style={{fontFamily: 'sans-serif', margin: 15}}> <add> <div style={{ fontFamily: 'sans-serif', margin: 15 }}> <ide> <h2>Empty</h2> <del> <TextareaAutosize style={textareaStyle} placeholder='try writing some lines'/> <add> <TextareaAutosize style={textareaStyle} placeholder='try writing some lines' /> <ide> <ide> <h2>Minimum Height</h2> <del> <TextareaAutosize rows='3' style={textareaStyle} placeholder='minimun height is 3 rows'/> <add> <TextareaAutosize rows='3' style={textareaStyle} placeholder='minimun height is 3 rows' /> <ide> <ide> <h2>Prefilled</h2> <del> <TextareaAutosize style={textareaStyle} defaultValue={'this\nis\na\nlong\ninitial\ntext'}/> <add> <TextareaAutosize style={textareaStyle} defaultValue={'this\nis\na\nlong\ninitial\ntext'} /> <ide> <ide> <h2>{'You can compare with this normal react <textarea>'}</h2> <del> <textarea style={textareaStyle} defaultValue={'this\nis\na\nlong\ninitial\ntext'}/> <add> <textarea style={textareaStyle} defaultValue={'this\nis\na\nlong\ninitial\ntext'} /> <ide> </div> <ide> ); <ide> } <ide> <del>}); <add>} <ide> <ide> React.render(<Example />, document.getElementById('container'));
JavaScript
mit
a726fa13614fbb17675e63cd1d9767ae6d40ea0c
0
ringcentral/ringcentral-js-widget,u9520107/ringcentral-js-widget,u9520107/ringcentral-js-widget,alvita/ringcentral-js-widget,alvita/ringcentral-js-widget,u9520107/ringcentral-js-widget,ringcentral/ringcentral-js-widget,alvita/ringcentral-js-widget,ringcentral/ringcentral-js-widget
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import formatNumber from 'ringcentral-integration/lib/formatNumber'; import { getRecipients } from 'ringcentral-integration/lib/messageHelper'; import Spinner from '../../components/Spinner'; import Panel from '../../components/Panel'; import MessageList from '../../components/MessageList'; import SearchInput from '../../components/SearchInput'; import styles from './styles.scss'; import i18n from './i18n'; function MessageSpiner() { return ( <div className={styles.spinerContainer}> <Spinner /> </div> ); } class MessagesPage extends Component { constructor(props) { super(props); this.onSearchChange = (e) => { const value = e.currentTarget.value; this.props.updateSearchingString(value); }; this.searchMessage = this.searchMessage.bind(this); this.getMessageRecipientNames = this.getMessageRecipientNames.bind(this); } getMessageRecipientNames(message) { let recipients = message.recipients; if (!recipients || recipients.length === 0) { recipients = this.props.getRecipientsList(message); } return recipients.map((recipient) => { const phoneNumber = recipient.phoneNumber || recipient.extensionNumber; if (phoneNumber && this.props.matcherContactName) { const matcherName = this.props.matcherContactName(phoneNumber); if (matcherName) { return matcherName; } return this.props.formatPhone(phoneNumber); } if (recipient.name) { return recipient.name; } return this.props.formatPhone(phoneNumber); }); } isMatchRecipients(message, searchText, searchNumber) { const recipients = this.props.getRecipientsList(message); for (const recipient of recipients) { const phoneNumber = recipient.phoneNumber || recipient.extensionNumber; let recipientName = null; if (phoneNumber) { if (searchNumber && searchNumber.length > 0 && phoneNumber.indexOf(searchNumber) >= 0) { return true; } if (this.props.matcherContactName) { const matcherName = this.props.matcherContactName(phoneNumber); if (matcherName) { recipientName = matcherName; } else { recipientName = phoneNumber; } } } if (!recipientName && recipient.name) { recipientName = recipient.name; } if (recipientName && recipientName.toLowerCase().indexOf(searchText) >= 0) { return true; } } return false; } searchMessage() { const searchString = this.props.searchingString; if (searchString.length < 3) { this.props.updateSearchResults([]); return; } const searchText = searchString.toLowerCase().trim(); let searchNumber = searchString.replace(/[^\d]/g, ''); if (searchString.length !== searchNumber.length && searchNumber.length < 2) { searchNumber = null; } const searchTextResults = this.props.searchMessagesText(searchText).reverse(); const searchContactresults = this.props.allMessages.filter(message => this.isMatchRecipients(message, searchText, searchNumber) ).reverse(); const results = []; const searchMap = {}; const addSearchResultToResult = (message) => { if (searchMap[message.conversationId]) { return; } searchMap[message.conversationId] = 1; results.push(message); }; searchContactresults.forEach(addSearchResultToResult); searchTextResults.forEach(addSearchResultToResult); this.props.updateSearchResults(results); } renderMessageList() { if (this.props.searchingString.length >= 3) { return ( <MessageList messages={this.props.searchingResults} loadNextPageMessages={() => null} loading={false} placeholder={i18n.getString('noSearchResults')} formatDateTime={this.props.formatDateTime} getMessageRecipientNames={this.getMessageRecipientNames} /> ); } return ( <MessageList messages={this.props.messages} loadNextPageMessages={this.props.loadNextPageMessages} placeholder={i18n.getString('noMessages')} formatDateTime={this.props.formatDateTime} getMessageRecipientNames={this.getMessageRecipientNames} /> ); } render() { const showSpinner = this.props.showSpinner; if (showSpinner) { return ( <div className={styles.root}> <MessageSpiner /> </div> ); } return ( <div className={styles.content}> <SearchInput value={this.props.searchingString} onChange={this.onSearchChange} onKeyUp={this.searchMessage} maxLength={30} placeholder={i18n.getString('search')} /> <Panel> {this.renderMessageList()} </Panel> </div> ); } } MessagesPage.propTypes = { messages: MessageList.propTypes.messages, allMessages: MessageList.propTypes.messages, searchingResults: MessageList.propTypes.messages, loadNextPageMessages: PropTypes.func.isRequired, updateSearchingString: PropTypes.func.isRequired, isLoadingNextPage: PropTypes.bool, showSpinner: PropTypes.bool.isRequired, searchingString: PropTypes.string.isRequired, formatDateTime: PropTypes.func.isRequired, formatPhone: PropTypes.func.isRequired, getRecipientsList: PropTypes.func.isRequired, searchMessagesText: PropTypes.func.isRequired, updateSearchResults: PropTypes.func.isRequired, matcherContactName: PropTypes.func, }; MessagesPage.defaultProps = { matcherContactName: null, }; function mapStateToProps(state, props) { return ({ currentLocale: props.locale.currentLocale, messages: props.messages.messages, allMessages: props.messageStore.conversations, showSpinner: ( !props.messages.ready || (props.contactMatcher && !props.contactMatcher.ready) || !props.extensionInfo.ready || !props.dateTimeFormat.ready ), lastUpdatedAt: props.messages.lastUpdatedAt, searchingString: props.messages.searchingString, searchingResults: props.messages.searchingResults, }); } function mapDispatchToProps(dispatch, props) { let matcherContactName = null; if (props.contactMatcher && props.contactMatcher.ready) { matcherContactName = (phoneNumber) => { const matcherNames = props.contactMatcher.dataMapping[phoneNumber]; if (matcherNames && matcherNames.length > 0) { return matcherNames.map(matcher => matcher.name).join('&'); } return null; }; } return { loadNextPageMessages: props.messages.loadNextPageMessages, updateSearchingString: props.messages.updateSearchingString, updateSearchResults: props.messages.updateSearchResults, formatDateTime: props.formatDateTime || (utcTimestamp => props.dateTimeFormat.formatDateTime({ utcTimestamp })), formatPhone: phoneNumber => formatNumber({ phoneNumber, areaCode: props.regionSettings.areaCode, countryCode: props.regionSettings.countryCode, }), getRecipientsList: message => getRecipients({ message, myExtensionNumber: props.extensionInfo.extensionNumber, }), searchMessagesText: searchText => props.messageStore.searchMessagesText(searchText), matcherContactName, }; } export default connect(mapStateToProps, mapDispatchToProps)(MessagesPage);
src/containers/MessagesPage/index.js
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import formatNumber from 'ringcentral-integration/lib/formatNumber'; import { getRecipients } from 'ringcentral-integration/lib/messageHelper'; import Spinner from '../../components/Spinner'; import Panel from '../../components/Panel'; import MessageList from '../../components/MessageList'; import SearchInput from '../../components/SearchInput'; import styles from './styles.scss'; import i18n from './i18n'; function MessageSpiner() { return ( <div className={styles.spinerContainer}> <Spinner /> </div> ); } class MessagesPage extends Component { constructor(props) { super(props); this.onSearchChange = (e) => { const value = e.currentTarget.value; this.props.updateSearchingString(value); }; this.searchMessage = this.searchMessage.bind(this); this.getMessageRecipientNames = this.getMessageRecipientNames.bind(this); } getMessageRecipientNames(message) { let recipients = message.recipients; if (!recipients || recipients.length === 0) { recipients = this.props.getRecipientsList(message); } return recipients.map((recipient) => { const phoneNumber = recipient.phoneNumber || recipient.extensionNumber; if (recipient.matchedNames) { const matcherName = recipient.matchedNames.map(matcher => matcher.name).join('&'); if (matcherName.length > 0) { return matcherName; } return this.props.formatPhone(phoneNumber); } if (recipient.name) { return recipient.name; } return this.props.formatPhone(phoneNumber); }); } isMatchRecipients(message, searchText, searchNumber) { const recipients = this.props.getRecipientsList(message); for (const recipient of recipients) { const phoneNumber = recipient.phoneNumber || recipient.extensionNumber; let recipientName = null; if (phoneNumber) { if (searchNumber && searchNumber.length > 0 && phoneNumber.indexOf(searchNumber) >= 0) { return true; } if (recipient.matchedNames) { const matcherName = recipient.matchedNames.map(matcher => matcher.name).join('&'); if (matcherName.length > 0) { recipientName = matcherName; } else { recipientName = phoneNumber; } } } if (!recipientName && recipient.name) { recipientName = recipient.name; } if (recipientName && recipientName.toLowerCase().indexOf(searchText) >= 0) { return true; } } return false; } searchMessage() { const searchString = this.props.searchingString; if (searchString.length < 3) { this.props.updateSearchResults([]); return; } const searchText = searchString.toLowerCase().trim(); let searchNumber = searchString.replace(/[^\d]/g, ''); if (searchString.length !== searchNumber.length && searchNumber.length < 2) { searchNumber = null; } const searchTextResults = this.props.searchMessagesText(searchText).reverse(); const searchContactresults = this.props.allMessages.filter(message => this.isMatchRecipients(message, searchText, searchNumber) ).reverse(); const results = []; const searchMap = {}; const addSearchResultToResult = (message) => { if (searchMap[message.conversationId]) { return; } searchMap[message.conversationId] = 1; results.push(message); }; searchContactresults.forEach(addSearchResultToResult); searchTextResults.forEach(addSearchResultToResult); this.props.updateSearchResults(results); } renderMessageList() { if (this.props.searchingString.length >= 3) { return ( <MessageList messages={this.props.searchingResults} loadNextPageMessages={() => null} loading={false} placeholder={i18n.getString('noSearchResults')} formatDateTime={this.props.formatDateTime} getMessageRecipientNames={this.getMessageRecipientNames} /> ); } return ( <MessageList messages={this.props.messages} loadNextPageMessages={this.props.loadNextPageMessages} placeholder={i18n.getString('noMessages')} formatDateTime={this.props.formatDateTime} getMessageRecipientNames={this.getMessageRecipientNames} /> ); } render() { const showSpinner = this.props.showSpinner; if (showSpinner) { return ( <div className={styles.root}> <MessageSpiner /> </div> ); } return ( <div className={styles.content}> <SearchInput value={this.props.searchingString} onChange={this.onSearchChange} onKeyUp={this.searchMessage} maxLength={30} placeholder={i18n.getString('search')} /> <Panel> {this.renderMessageList()} </Panel> </div> ); } } MessagesPage.propTypes = { messages: MessageList.propTypes.messages, allMessages: MessageList.propTypes.messages, searchingResults: MessageList.propTypes.messages, loadNextPageMessages: PropTypes.func.isRequired, updateSearchingString: PropTypes.func.isRequired, isLoadingNextPage: PropTypes.bool, showSpinner: PropTypes.bool.isRequired, searchingString: PropTypes.string.isRequired, formatDateTime: PropTypes.func.isRequired, formatPhone: PropTypes.func.isRequired, getRecipientsList: PropTypes.func.isRequired, searchMessagesText: PropTypes.func.isRequired, updateSearchResults: PropTypes.func.isRequired, }; function mapStateToProps(state, props) { return ({ currentLocale: props.locale.currentLocale, messages: props.messages.normalizedMessages, allMessages: props.messageStore.conversations, showSpinner: ( !props.messages.ready || (props.contactMatcher && !props.contactMatcher.ready) || !props.extensionInfo.ready || !props.dateTimeFormat.ready ), lastUpdatedAt: props.messages.lastUpdatedAt, searchingString: props.messages.searchingString, searchingResults: props.messages.searchingResults, }); } function mapDispatchToProps(dispatch, props) { return { loadNextPageMessages: props.messages.loadNextPageMessages, updateSearchingString: props.messages.updateSearchingString, updateSearchResults: props.messages.updateSearchResults, formatDateTime: props.formatDateTime || (utcTimestamp => props.dateTimeFormat.formatDateTime({ utcTimestamp })), formatPhone: phoneNumber => formatNumber({ phoneNumber, areaCode: props.regionSettings.areaCode, countryCode: props.regionSettings.countryCode, }), getRecipientsList: message => getRecipients({ message, myExtensionNumber: props.extensionInfo.extensionNumber, }), searchMessagesText: searchText => props.messageStore.searchMessagesText(searchText), }; } export default connect(mapStateToProps, mapDispatchToProps)(MessagesPage);
matche name in message search list (#135)
src/containers/MessagesPage/index.js
matche name in message search list (#135)
<ide><path>rc/containers/MessagesPage/index.js <ide> } <ide> return recipients.map((recipient) => { <ide> const phoneNumber = recipient.phoneNumber || recipient.extensionNumber; <del> if (recipient.matchedNames) { <del> const matcherName = recipient.matchedNames.map(matcher => matcher.name).join('&'); <del> if (matcherName.length > 0) { <add> if (phoneNumber && this.props.matcherContactName) { <add> const matcherName = this.props.matcherContactName(phoneNumber); <add> if (matcherName) { <ide> return matcherName; <ide> } <ide> return this.props.formatPhone(phoneNumber); <ide> if (searchNumber && searchNumber.length > 0 && phoneNumber.indexOf(searchNumber) >= 0) { <ide> return true; <ide> } <del> if (recipient.matchedNames) { <del> const matcherName = recipient.matchedNames.map(matcher => matcher.name).join('&'); <del> if (matcherName.length > 0) { <add> if (this.props.matcherContactName) { <add> const matcherName = this.props.matcherContactName(phoneNumber); <add> if (matcherName) { <ide> recipientName = matcherName; <ide> } else { <ide> recipientName = phoneNumber; <ide> getRecipientsList: PropTypes.func.isRequired, <ide> searchMessagesText: PropTypes.func.isRequired, <ide> updateSearchResults: PropTypes.func.isRequired, <add> matcherContactName: PropTypes.func, <add>}; <add> <add>MessagesPage.defaultProps = { <add> matcherContactName: null, <ide> }; <ide> <ide> function mapStateToProps(state, props) { <ide> return ({ <ide> currentLocale: props.locale.currentLocale, <del> messages: props.messages.normalizedMessages, <add> messages: props.messages.messages, <ide> allMessages: props.messageStore.conversations, <ide> showSpinner: ( <ide> !props.messages.ready || <ide> } <ide> <ide> function mapDispatchToProps(dispatch, props) { <add> let matcherContactName = null; <add> if (props.contactMatcher && props.contactMatcher.ready) { <add> matcherContactName = (phoneNumber) => { <add> const matcherNames = props.contactMatcher.dataMapping[phoneNumber]; <add> if (matcherNames && matcherNames.length > 0) { <add> return matcherNames.map(matcher => matcher.name).join('&'); <add> } <add> return null; <add> }; <add> } <ide> return { <ide> loadNextPageMessages: props.messages.loadNextPageMessages, <ide> updateSearchingString: props.messages.updateSearchingString, <ide> }), <ide> searchMessagesText: searchText => <ide> props.messageStore.searchMessagesText(searchText), <add> matcherContactName, <ide> }; <ide> } <ide>
JavaScript
lgpl-2.1
e5986324ffc3422c101258028f32e559a5d4bd73
0
endlessm/eos-knowledge-lib,endlessm/eos-knowledge-lib,endlessm/eos-knowledge-lib,endlessm/eos-knowledge-lib
// Copyright 2014 Endless Mobile, Inc. const Endless = imports.gi.Endless; const Gdk = imports.gi.Gdk; const GdkPixbuf = imports.gi.GdkPixbuf; const Gio = imports.gi.Gio; const GObject = imports.gi.GObject; const Gtk = imports.gi.Gtk; const Lang = imports.lang; const Actions = imports.app.actions; const Dispatcher = imports.app.dispatcher; const Launcher = imports.app.interfaces.launcher; const Module = imports.app.interfaces.module; const SearchBox = imports.app.modules.searchBox; const StyleClasses = imports.app.styleClasses; const Utils = imports.app.utils; /** * Defines how much the background slides when switching pages, and * therefore also how zoomed in the background image is from its * original size. */ const PARALLAX_BACKGROUND_SCALE = 1.1; /** * Class: Window * * This represents the toplevel window widget for template A, containing all * template A pages. * * Adds a lightbox above the section and article page, which can be * used to show content above either of these pages. */ const Window = new Lang.Class({ Name: 'Window', GTypeName: 'EknWindow', Extends: Endless.Window, Implements: [ Module.Module ], Properties: { 'factory': GObject.ParamSpec.override('factory', Module.Module), 'factory-name': GObject.ParamSpec.override('factory-name', Module.Module), /** * Property: section-page * * The section page template. */ 'section-page': GObject.ParamSpec.object('section-page', 'Section page', 'The section page of this view widget.', GObject.ParamFlags.READABLE, Gtk.Widget), /** * Property: article-page * * The article page template. */ 'article-page': GObject.ParamSpec.object('article-page', 'Article page', 'The article page of this view widget.', GObject.ParamFlags.READABLE, Gtk.Widget), /** * Property: search-page * * The search page template. */ 'search-page': GObject.ParamSpec.object('search-page', 'Search page', 'The search page of this view widget.', GObject.ParamFlags.READABLE, Gtk.Widget), /** * Property: background-image-uri * * The background image uri for this window. * Gets set on home page of the application. */ 'background-image-uri': GObject.ParamSpec.string('background-image-uri', 'Background image URI', 'The background image of this window.', GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY, ''), /** * Property: blur-background-image-uri * * The blurred background image uri for this window. * Gets set on section and article pages of the application. */ 'blur-background-image-uri': GObject.ParamSpec.string('blur-background-image-uri', 'Blurred background image URI', 'The blurred background image of this window.', GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY, ''), /** * Property: template-type * * A string for the template type the window should render as * currently support 'A' and 'B' templates. */ 'template-type': GObject.ParamSpec.string('template-type', 'Template Type', 'Which template the window should display with', GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY, 'A'), }, Signals: { /** * Event: search-focused * * This event is triggered when the user focuses the search bar. */ 'search-focused': { param_types: [GObject.TYPE_BOOLEAN] }, }, WINDOW_WIDTH_THRESHOLD: 800, WINDOW_HEIGHT_THRESHOLD: 600, TRANSITION_DURATION: 500, _init: function (props) { this.parent(props); let context = this.get_style_context(); this._bg_size_provider = new Gtk.CssProvider(); context.add_provider(this._bg_size_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION); this._home_page = this.create_submodule('home-page'); this._section_page = this.create_submodule('section-page'); this._all_sets_page = this.create_submodule('all-sets-page'); this._search_page = this.create_submodule('search-page'); this._article_page = this.create_submodule('article-page'); this._brand_screen = this.create_submodule('brand-screen'); if (this.template_type === 'B') { this._home_page.get_style_context().add_class(StyleClasses.HOME_PAGE_B); this._section_page.get_style_context().add_class(StyleClasses.SECTION_PAGE_B); this._search_page.get_style_context().add_class(StyleClasses.SEARCH_PAGE_B); this._article_page.get_style_context().add_class(StyleClasses.ARTICLE_PAGE_B); } else { this._home_page.get_style_context().add_class(StyleClasses.HOME_PAGE_A); this._section_page.get_style_context().add_class(StyleClasses.SECTION_PAGE_A); this._search_page.get_style_context().add_class(StyleClasses.SEARCH_PAGE_A); this._article_page.get_style_context().add_class(StyleClasses.ARTICLE_PAGE_A); } this._stack = new Gtk.Stack({ transition_duration: 0, }); if (this._brand_screen) this._stack.add(this._brand_screen); this._stack.add(this._home_page); this._stack.add(this._section_page); this._stack.add(this._search_page); this._stack.add(this._article_page); if (this._all_sets_page) this._stack.add(this._all_sets_page); // We need to pack a bunch of modules inside each other, but some of // them are optional. "matryoshka" is the innermost widget that needs to // have something packed around it. let matryoshka = this._stack; let navigation = this.create_submodule('navigation'); if (navigation) { navigation.add(matryoshka); matryoshka = navigation; } let lightbox = this.create_submodule('lightbox'); if (lightbox) { lightbox.add(matryoshka); matryoshka = lightbox; } this._history_buttons = new Endless.TopbarNavButton(); this._search_box = this.create_submodule('search', { no_show_all: true, visible: false, }); this.page_manager.add(matryoshka, { left_topbar_widget: this._history_buttons, center_topbar_widget: this._search_box, }); let frame_css = ''; if (this.background_image_uri) { frame_css += '\ EknWindow.background-left { \ background-image: url("' + this.background_image_uri + '");\ }\n'; try { let stream = Gio.File.new_for_uri(this.background_image_uri).read(null); let bg_pixbuf = GdkPixbuf.Pixbuf.new_from_stream(stream, null); this._background_image_width = bg_pixbuf.width; this._background_image_height = bg_pixbuf.height; } catch (e) { logError(e, 'Background image URI is not a valid format.'); } } if (this.blur_background_image_uri) { frame_css += '\ EknWindow.background-center, EknWindow.background-right { \ background-image: url("' + this.blur_background_image_uri + '");\ }'; } if (frame_css !== '') { let provider = new Gtk.CssProvider(); provider.load_from_data(frame_css); context.add_provider(provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION); } context.add_class(StyleClasses.BACKGROUND_LEFT); let dispatcher = Dispatcher.get_default(); dispatcher.dispatch({ action_type: Actions.NAV_BACK_ENABLED_CHANGED, enabled: false, }); dispatcher.dispatch({ action_type: Actions.NAV_FORWARD_ENABLED_CHANGED, enabled: false, }); this._history_buttons.back_button.connect('clicked', () => { dispatcher.dispatch({ action_type: Actions.HISTORY_BACK_CLICKED }); }); this._history_buttons.forward_button.connect('clicked', () => { dispatcher.dispatch({ action_type: Actions.HISTORY_FORWARD_CLICKED }); }); dispatcher.register((payload) => { switch(payload.action_type) { case Actions.HISTORY_BACK_ENABLED_CHANGED: this._history_buttons.back_button.sensitive = payload.enabled; break; case Actions.HISTORY_FORWARD_ENABLED_CHANGED: this._history_buttons.forward_button.sensitive = payload.enabled; break; case Actions.SEARCH_STARTED: case Actions.SHOW_SET: this.set_busy(true); break; case Actions.SEARCH_READY: case Actions.SEARCH_FAILED: case Actions.SET_READY: this.set_busy(false); break; case Actions.FIRST_LAUNCH: if (payload.timestamp) this.present_with_time(payload.timestamp); else this.present(); break; case Actions.SHOW_BRAND_SCREEN: if (this._brand_screen) this.show_page(this._brand_screen); break; case Actions.BRAND_SCREEN_DONE: if (this._brand_screen) this.show_page(this._home_page); break; case Actions.SHOW_HOME_PAGE: this.show_page(this._home_page); break; case Actions.SHOW_SECTION_PAGE: this.show_page(this._section_page); break; case Actions.SHOW_ALL_SETS_PAGE: this.show_page(this._all_sets_page); break; case Actions.SHOW_SEARCH_PAGE: this.show_page(this._search_page); break; case Actions.SHOW_ARTICLE_PAGE: this.show_page(this._article_page); break; } }); this._history_buttons.get_style_context().add_class(Gtk.STYLE_CLASS_LINKED); this._history_buttons.show_all(); this._stack.connect('notify::transition-running', function () { this._home_page.animating = this._stack.transition_running; if (this._stack.transition_running) context.add_class(StyleClasses.ANIMATING); else context.remove_class(StyleClasses.ANIMATING); }.bind(this)); this._stack.connect_after('notify::visible-child', this._after_stack_visible_child_changed.bind(this)); this.show_all(); this._set_background_position_style(StyleClasses.BACKGROUND_LEFT); }, _set_background_position_style: function (klass) { let context = this.get_style_context(); context.remove_class(StyleClasses.BACKGROUND_LEFT); context.remove_class(StyleClasses.BACKGROUND_CENTER); context.remove_class(StyleClasses.BACKGROUND_RIGHT); context.add_class(klass); }, _after_stack_visible_child_changed: function () { let new_page = this._stack.visible_child; this._search_box.visible = !Utils.has_descendant_with_type(new_page, SearchBox.SearchBox); }, show_page: function (new_page) { let old_page = this.get_visible_page(); if (old_page === new_page) { // Even though we didn't change, this should still count as the // first transition. this._stack.transition_duration = this.TRANSITION_DURATION; return; } let is_on_left = (page) => [this._home_page, this._brand_screen].indexOf(page) > -1; let is_on_center = (page) => [this._section_page, this._search_page].indexOf(page) > -1; let nav_back_visible = false; if (is_on_left(new_page)) { nav_back_visible = false; this._set_background_position_style(StyleClasses.BACKGROUND_LEFT); if (is_on_left(old_page)) { this._stack.transition_type = Gtk.StackTransitionType.CROSSFADE; } else { this._stack.transition_type = Gtk.StackTransitionType.SLIDE_RIGHT; } } else if (is_on_center(new_page)) { if (is_on_left(old_page)) { this._stack.transition_type = Gtk.StackTransitionType.SLIDE_LEFT; } else if (is_on_center(old_page)) { this._stack.transition_type = Gtk.StackTransitionType.CROSSFADE; } else if (this.template_type === 'B') { this._stack.transition_type = Gtk.StackTransitionType.CROSSFADE; } else { this._stack.transition_type = Gtk.StackTransitionType.SLIDE_RIGHT; } nav_back_visible = true; this._set_background_position_style(StyleClasses.BACKGROUND_CENTER); } else { if (this.template_type === 'B') { this._stack.transition_type = Gtk.StackTransitionType.CROSSFADE; } else { this._stack.transition_type = Gtk.StackTransitionType.SLIDE_LEFT; } nav_back_visible = true; this._set_background_position_style(StyleClasses.BACKGROUND_RIGHT); } Dispatcher.get_default().dispatch({ action_type: Actions.NAV_BACK_ENABLED_CHANGED, enabled: nav_back_visible, }); this._stack.visible_child = new_page; // The first transition on app startup has duration 0, subsequent ones // are normal. this._stack.transition_duration = this.TRANSITION_DURATION; }, /** * Method: get_visible_page * Returns the currently visible page */ get_visible_page: function () { return this._stack.visible_child; }, set_busy: function (busy) { let gdk_window = this.page_manager.get_window(); if (!gdk_window) return; let cursor = null; if (busy) cursor = Gdk.Cursor.new_for_display(Gdk.Display.get_default(), Gdk.CursorType.WATCH); gdk_window.cursor = cursor; }, // Module override get_slot_names: function () { return ['brand-screen', 'home-page', 'section-page', 'all-sets-page', 'search-page', 'article-page', 'navigation', 'lightbox', 'search']; }, vfunc_size_allocate: function (alloc) { this.parent(alloc); let context = this.get_style_context(); if (alloc.width <= this.WINDOW_WIDTH_THRESHOLD || alloc.height <= this.WINDOW_HEIGHT_THRESHOLD) { context.remove_class(StyleClasses.WINDOW_LARGE); context.add_class(StyleClasses.WINDOW_SMALL); } else { context.remove_class(StyleClasses.WINDOW_SMALL); context.add_class(StyleClasses.WINDOW_LARGE); } // FIXME: if GTK gains support for the 'vmax' CSS unit, then we can move // this calculation to pure CSS and get rid of the extra CSS provider. // https://developer.mozilla.org/en-US/docs/Web/CSS/length if (this.background_image_uri && (!this._last_allocation || this._last_allocation.width !== alloc.width || this._last_allocation.height !== alloc.height)) { let bg_mult_ratio = Math.max(alloc.width / this._background_image_width, alloc.height / this._background_image_height) * PARALLAX_BACKGROUND_SCALE; let bg_width = Math.ceil(this._background_image_width * bg_mult_ratio); let bg_height = Math.ceil(this._background_image_height * bg_mult_ratio); let frame_css = 'EknWindow { background-size: ' + bg_width + 'px ' + bg_height + 'px; }'; this._bg_size_provider.load_from_data(frame_css); } this._last_allocation = alloc; } });
js/app/modules/window.js
// Copyright 2014 Endless Mobile, Inc. const Endless = imports.gi.Endless; const Gdk = imports.gi.Gdk; const GdkPixbuf = imports.gi.GdkPixbuf; const Gio = imports.gi.Gio; const GObject = imports.gi.GObject; const Gtk = imports.gi.Gtk; const Lang = imports.lang; const Actions = imports.app.actions; const Dispatcher = imports.app.dispatcher; const Launcher = imports.app.interfaces.launcher; const Module = imports.app.interfaces.module; const SearchBox = imports.app.modules.searchBox; const StyleClasses = imports.app.styleClasses; const Utils = imports.app.utils; /** * Defines how much the background slides when switching pages, and * therefore also how zoomed in the background image is from its * original size. */ const PARALLAX_BACKGROUND_SCALE = 1.1; /** * Class: Window * * This represents the toplevel window widget for template A, containing all * template A pages. * * Adds a lightbox above the section and article page, which can be * used to show content above either of these pages. */ const Window = new Lang.Class({ Name: 'Window', GTypeName: 'EknWindow', Extends: Endless.Window, Implements: [ Module.Module ], Properties: { 'factory': GObject.ParamSpec.override('factory', Module.Module), 'factory-name': GObject.ParamSpec.override('factory-name', Module.Module), /** * Property: section-page * * The section page template. */ 'section-page': GObject.ParamSpec.object('section-page', 'Section page', 'The section page of this view widget.', GObject.ParamFlags.READABLE, Gtk.Widget), /** * Property: article-page * * The article page template. */ 'article-page': GObject.ParamSpec.object('article-page', 'Article page', 'The article page of this view widget.', GObject.ParamFlags.READABLE, Gtk.Widget), /** * Property: search-page * * The search page template. */ 'search-page': GObject.ParamSpec.object('search-page', 'Search page', 'The search page of this view widget.', GObject.ParamFlags.READABLE, Gtk.Widget), /** * Property: background-image-uri * * The background image uri for this window. * Gets set on home page of the application. */ 'background-image-uri': GObject.ParamSpec.string('background-image-uri', 'Background image URI', 'The background image of this window.', GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY, ''), /** * Property: blur-background-image-uri * * The blurred background image uri for this window. * Gets set on section and article pages of the application. */ 'blur-background-image-uri': GObject.ParamSpec.string('blur-background-image-uri', 'Blurred background image URI', 'The blurred background image of this window.', GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY, ''), /** * Property: template-type * * A string for the template type the window should render as * currently support 'A' and 'B' templates. */ 'template-type': GObject.ParamSpec.string('template-type', 'Template Type', 'Which template the window should display with', GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY, 'A'), }, Signals: { /** * Event: search-focused * * This event is triggered when the user focuses the search bar. */ 'search-focused': { param_types: [GObject.TYPE_BOOLEAN] }, }, WINDOW_WIDTH_THRESHOLD: 800, WINDOW_HEIGHT_THRESHOLD: 600, TRANSITION_DURATION: 500, _init: function (props) { this.parent(props); let context = this.get_style_context(); this._bg_size_provider = new Gtk.CssProvider(); context.add_provider(this._bg_size_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION); this._home_page = this.create_submodule('home-page'); this._section_page = this.create_submodule('section-page'); this._all_sets_page = this.create_submodule('all-sets-page'); this._search_page = this.create_submodule('search-page'); this._article_page = this.create_submodule('article-page'); this._brand_screen = this.create_submodule('brand-screen'); if (this.template_type === 'B') { this._home_page.get_style_context().add_class(StyleClasses.HOME_PAGE_B); this._section_page.get_style_context().add_class(StyleClasses.SECTION_PAGE_B); this._search_page.get_style_context().add_class(StyleClasses.SEARCH_PAGE_B); this._article_page.get_style_context().add_class(StyleClasses.ARTICLE_PAGE_B); } else { this._home_page.get_style_context().add_class(StyleClasses.HOME_PAGE_A); this._section_page.get_style_context().add_class(StyleClasses.SECTION_PAGE_A); this._search_page.get_style_context().add_class(StyleClasses.SEARCH_PAGE_A); this._article_page.get_style_context().add_class(StyleClasses.ARTICLE_PAGE_A); } this._stack = new Gtk.Stack({ transition_duration: 0, }); if (this._brand_screen) this._stack.add(this._brand_screen); this._stack.add(this._home_page); this._stack.add(this._section_page); this._stack.add(this._search_page); this._stack.add(this._article_page); if (this._all_sets_page) this._stack.add(this._all_sets_page); // We need to pack a bunch of modules inside each other, but some of // them are optional. "matryoshka" is the innermost widget that needs to // have something packed around it. let matryoshka = this._stack; let navigation = this.create_submodule('navigation'); if (navigation) { navigation.add(matryoshka); matryoshka = navigation; } let lightbox = this.create_submodule('lightbox'); if (lightbox) { lightbox.add(matryoshka); matryoshka = lightbox; } this._history_buttons = new Endless.TopbarNavButton(); this._search_box = this.create_submodule('search', { no_show_all: true, visible: false, }); this.page_manager.add(matryoshka, { left_topbar_widget: this._history_buttons, center_topbar_widget: this._search_box, }); let frame_css = ''; if (this.background_image_uri) { frame_css += '\ EknWindow.background-left { \ background-image: url("' + this.background_image_uri + '");\ }\n'; try { let stream = Gio.File.new_for_uri(this.background_image_uri).read(null); let bg_pixbuf = GdkPixbuf.Pixbuf.new_from_stream(stream, null); this._background_image_width = bg_pixbuf.width; this._background_image_height = bg_pixbuf.height; } catch (e) { logError(e, 'Background image URI is not a valid format.'); } } if (this.blur_background_image_uri) { frame_css += '\ EknWindow.background-center, EknWindow.background-right { \ background-image: url("' + this.blur_background_image_uri + '");\ }'; } if (frame_css !== '') { let provider = new Gtk.CssProvider(); provider.load_from_data(frame_css); context.add_provider(provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION); } context.add_class(StyleClasses.BACKGROUND_LEFT); let dispatcher = Dispatcher.get_default(); dispatcher.dispatch({ action_type: Actions.NAV_BACK_ENABLED_CHANGED, enabled: false, }); dispatcher.dispatch({ action_type: Actions.NAV_FORWARD_ENABLED_CHANGED, enabled: false, }); this._history_buttons.back_button.connect('clicked', () => { dispatcher.dispatch({ action_type: Actions.HISTORY_BACK_CLICKED }); }); this._history_buttons.forward_button.connect('clicked', () => { dispatcher.dispatch({ action_type: Actions.HISTORY_FORWARD_CLICKED }); }); dispatcher.register((payload) => { switch(payload.action_type) { case Actions.HISTORY_BACK_ENABLED_CHANGED: this._history_buttons.back_button.sensitive = payload.enabled; break; case Actions.HISTORY_FORWARD_ENABLED_CHANGED: this._history_buttons.forward_button.sensitive = payload.enabled; break; case Actions.SEARCH_STARTED: case Actions.SHOW_SET: this.set_busy(true); break; case Actions.SEARCH_READY: case Actions.SEARCH_FAILED: case Actions.SET_READY: this.set_busy(false); break; case Actions.FIRST_LAUNCH: if (payload.timestamp) this.present_with_time(payload.timestamp); else this.present(); break; case Actions.SHOW_BRAND_SCREEN: if (this._brand_screen) this.show_page(this._brand_screen); break; case Actions.BRAND_SCREEN_DONE: if (this._brand_screen) this.show_page(this._home_page); break; case Actions.SHOW_HOME_PAGE: this.show_page(this._home_page); break; case Actions.SHOW_SECTION_PAGE: this.show_page(this._section_page); break; case Actions.SHOW_ALL_SETS_PAGE: this.show_page(this._all_sets_page); break; case Actions.SHOW_SEARCH_PAGE: this.show_page(this._search_page); break; case Actions.SHOW_ARTICLE_PAGE: this.show_page(this._article_page); break; } }); this._history_buttons.get_style_context().add_class(Gtk.STYLE_CLASS_LINKED); this._history_buttons.show_all(); this._stack.connect('notify::transition-running', function () { this._home_page.animating = this._stack.transition_running; if (this._stack.transition_running) context.add_class(StyleClasses.ANIMATING); else context.remove_class(StyleClasses.ANIMATING); }.bind(this)); this._stack.connect_after('notify::visible-child', this._after_stack_visible_child_changed.bind(this)); this.show_all(); this._set_background_position_style(StyleClasses.BACKGROUND_LEFT); }, _set_background_position_style: function (klass) { let context = this.get_style_context(); context.remove_class(StyleClasses.BACKGROUND_LEFT); context.remove_class(StyleClasses.BACKGROUND_CENTER); context.remove_class(StyleClasses.BACKGROUND_RIGHT); context.add_class(klass); }, _after_stack_visible_child_changed: function () { let new_page = this._stack.visible_child; this._search_box.visible = !Utils.has_descendant_with_type(new_page, SearchBox.SearchBox); }, show_page: function (new_page) { let old_page = this.get_visible_page(); if (old_page === new_page) { // Even though we didn't change, this should still count as the // first transition. this._stack.transition_duration = this.TRANSITION_DURATION; return; } let is_on_left = (page) => [this._home_page, this._brand_screen].indexOf(page) > -1; let is_on_center = (page) => [this._section_page, this._search_page].indexOf(page) > -1; let nav_back_visible = false; if (is_on_left(new_page)) { nav_back_visible = false; this._set_background_position_style(StyleClasses.BACKGROUND_LEFT); if (is_on_left(old_page)) { this._stack.transition_type = Gtk.StackTransitionType.CROSSFADE; } else { this._stack.transition_type = Gtk.StackTransitionType.SLIDE_RIGHT; } } else if (is_on_center(new_page)) { if (is_on_left(old_page)) { this._stack.transition_type = Gtk.StackTransitionType.SLIDE_LEFT; } else if (is_on_center(old_page)) { this._stack.transition_type = Gtk.StackTransitionType.CROSSFADE; } else if (this.template_type === 'B') { this._stack.transition_type = Gtk.StackTransitionType.CROSSFADE; } else { this._stack.transition_type = Gtk.StackTransitionType.SLIDE_RIGHT; } nav_back_visible = true; this._set_background_position_style(StyleClasses.BACKGROUND_CENTER); } else { if (this.template_type === 'B') { this._stack.transition_type = Gtk.StackTransitionType.CROSSFADE; } else { this._stack.transition_type = Gtk.StackTransitionType.SLIDE_LEFT; } nav_back_visible = true; this._set_background_position_style(StyleClasses.BACKGROUND_RIGHT); } Dispatcher.get_default().dispatch({ action_type: Actions.NAV_BACK_ENABLED_CHANGED, enabled: nav_back_visible, }); this._stack.visible_child = new_page; // The first transition on app startup has duration 0, subsequent ones // are normal. this._stack.transition_duration = this.TRANSITION_DURATION; }, /** * Method: get_visible_page * Returns the currently visible page */ get_visible_page: function () { return this._stack.visible_child; }, set_busy: function (busy) { let gdk_window = this.page_manager.get_window(); if (!gdk_window) return; let cursor = null; if (busy) cursor = Gdk.Cursor.new_for_display(Gdk.Display.get_default(), Gdk.CursorType.WATCH); gdk_window.cursor = cursor; }, // Module override get_slot_names: function () { return ['brand-screen', 'home-page', 'section-page', 'all-sets-page', 'search-page', 'article-page', 'navigation', 'lightbox', 'search']; }, vfunc_size_allocate: function (alloc) { this.parent(alloc); let context = this.get_style_context(); if (alloc.width <= this.WINDOW_WIDTH_THRESHOLD || alloc.height <= this.WINDOW_HEIGHT_THRESHOLD) { context.remove_class(StyleClasses.WINDOW_LARGE); context.add_class(StyleClasses.WINDOW_SMALL); } else { context.remove_class(StyleClasses.WINDOW_SMALL); context.add_class(StyleClasses.WINDOW_LARGE); } // FIXME: if GTK gains support for the 'vmax' CSS unit, then we can move // this calculation to pure CSS and get rid of the extra CSS provider. // https://developer.mozilla.org/en-US/docs/Web/CSS/length if (this.background_image_uri && !this._last_allocation || this._last_allocation.width !== alloc.width || this._last_allocation.height !== alloc.height) { let bg_mult_ratio = Math.max(alloc.width / this._background_image_width, alloc.height / this._background_image_height) * PARALLAX_BACKGROUND_SCALE; let bg_width = Math.ceil(this._background_image_width * bg_mult_ratio); let bg_height = Math.ceil(this._background_image_height * bg_mult_ratio); let frame_css = 'EknWindow { background-size: ' + bg_width + 'px ' + bg_height + 'px; }'; this._bg_size_provider.load_from_data(frame_css); } this._last_allocation = alloc; } });
Fix short-circuiting precedence I got this wrong in a commit from a different issue. [endlessm/eos-sdk#3933]
js/app/modules/window.js
Fix short-circuiting precedence
<ide><path>s/app/modules/window.js <ide> // this calculation to pure CSS and get rid of the extra CSS provider. <ide> // https://developer.mozilla.org/en-US/docs/Web/CSS/length <ide> if (this.background_image_uri && <del> !this._last_allocation || <add> (!this._last_allocation || <ide> this._last_allocation.width !== alloc.width || <del> this._last_allocation.height !== alloc.height) { <add> this._last_allocation.height !== alloc.height)) { <ide> let bg_mult_ratio = Math.max(alloc.width / this._background_image_width, <ide> alloc.height / this._background_image_height) * <ide> PARALLAX_BACKGROUND_SCALE;
Java
agpl-3.0
6dd495f9061b90e7b529c714530521acbebcdea3
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
9b4d6866-2e60-11e5-9284-b827eb9e62be
hello.java
9b47fb60-2e60-11e5-9284-b827eb9e62be
9b4d6866-2e60-11e5-9284-b827eb9e62be
hello.java
9b4d6866-2e60-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>9b47fb60-2e60-11e5-9284-b827eb9e62be <add>9b4d6866-2e60-11e5-9284-b827eb9e62be
Java
mit
error: pathspec 'SpaceShell/src/fr/creationjeuxjava/tweenAccessors/SpriteTween.java' did not match any file(s) known to git
95b1e255f4cb547650396cf8fbf29533de1855fe
1
creationjeuxjava/spaceShell
package fr.creationjeuxjava.tweenAccessors; import aurelienribon.tweenengine.TweenAccessor; import com.badlogic.gdx.graphics.g2d.Sprite; /* SpriteTween.java by JohnCarmack, 16 fev. 2014 */ public class SpriteTween implements TweenAccessor<Sprite> { public static final int ALPHA = 1; @Override public int getValues(Sprite target, int tweenType, float[] returnValues) { switch (tweenType) { case ALPHA: returnValues[0] = target.getColor().a; return 1; default: return 0; } } @Override public void setValues(Sprite target, int tweenType, float[] newValues) { switch (tweenType) { case ALPHA: target.setColor(1, 1, 1, newValues[0]); break; } } }
SpaceShell/src/fr/creationjeuxjava/tweenAccessors/SpriteTween.java
add SpriteTween class for SplashScreen
SpaceShell/src/fr/creationjeuxjava/tweenAccessors/SpriteTween.java
add SpriteTween class for SplashScreen
<ide><path>paceShell/src/fr/creationjeuxjava/tweenAccessors/SpriteTween.java <add>package fr.creationjeuxjava.tweenAccessors; <add> <add>import aurelienribon.tweenengine.TweenAccessor; <add> <add>import com.badlogic.gdx.graphics.g2d.Sprite; <add> <add>/* SpriteTween.java by JohnCarmack, 16 fev. 2014 */ <add> <add>public class SpriteTween implements TweenAccessor<Sprite> { <add> <add> public static final int ALPHA = 1; <add> <add> @Override <add> public int getValues(Sprite target, int tweenType, float[] returnValues) { <add> switch (tweenType) { <add> case ALPHA: <add> returnValues[0] = target.getColor().a; <add> return 1; <add> default: <add> return 0; <add> } <add> } <add> <add> @Override <add> public void setValues(Sprite target, int tweenType, float[] newValues) { <add> switch (tweenType) { <add> case ALPHA: <add> target.setColor(1, 1, 1, newValues[0]); <add> break; <add> } <add> } <add>}
Java
apache-2.0
e817d02fce9198f4bca1a3c24a2163ff7d7d57b3
0
etothepii/stephenson
package uk.co.epii.stephenson.parser; import uk.co.epii.stephenson.cif.TransactionType; /** * User: James Robinson * Date: 17/08/2014 * Time: 12:39 */ public class TransactionTypeParser implements Parser<TransactionType> { @Override public TransactionType parse(String string) { if (string.equals("N")) { return TransactionType.NEW; } else if (string.equals("D")) { return TransactionType.DELETE; } else if (string.equals("R")) { return TransactionType.REVISE; } return null; } }
src/main/java/uk/co/epii/stephenson/parser/TransactionTypeParser.java
package uk.co.epii.stephenson.parser; import uk.co.epii.stephenson.cif.TransactionType; /** * User: James Robinson * Date: 17/08/2014 * Time: 12:39 */ public class TransactionTypeParser implements Parser<TransactionType> { @Override public TransactionType parse(String string) { return null; } }
Passes TransacctionTypeParser tests
src/main/java/uk/co/epii/stephenson/parser/TransactionTypeParser.java
Passes TransacctionTypeParser tests
<ide><path>rc/main/java/uk/co/epii/stephenson/parser/TransactionTypeParser.java <ide> * Time: 12:39 <ide> */ <ide> public class TransactionTypeParser implements Parser<TransactionType> { <add> <ide> @Override <ide> public TransactionType parse(String string) { <add> if (string.equals("N")) { <add> return TransactionType.NEW; <add> } <add> else if (string.equals("D")) { <add> return TransactionType.DELETE; <add> } <add> else if (string.equals("R")) { <add> return TransactionType.REVISE; <add> } <ide> return null; <ide> } <ide> }
Java
apache-2.0
27b3c619162a1f9636d12fb28c576acd434517c3
0
dhirajsb/quickstarts,fabric8io/quickstarts,EricWittmann/quickstarts,isatimur/quickstarts,fabric8io/quickstarts,hekonsek/quickstarts,KurtStam/ipaas-quickstarts,jstrachan/quickstarts,jstrachan/ipaas-quickstarts,jstrachan/quickstarts,KurtStam/ipaas-quickstarts,dhirajsb/quickstarts,rhuss/ipaas-quickstarts,dhirajsb/ipaas-quickstarts,oscerd/quickstarts,jimmidyson/ipaas-quickstarts,jmlambert78/ipaas-quickstarts,isatimur/quickstarts,chirino/ipaas-quickstarts,jstrachan/quickstarts,chirino/ipaas-quickstarts,jimmidyson/quickstarts,jimmidyson/quickstarts,rajdavies/ipaas-quickstarts,EricWittmann/quickstarts,fabric8io/quickstarts,jmlambert78/ipaas-quickstarts,jimmidyson/quickstarts,hekonsek/quickstarts,dhirajsb/quickstarts,jimmidyson/ipaas-quickstarts,KurtStam/ipaas-quickstarts,EricWittmann/quickstarts,stevef1uk/ipaas-quickstarts,jstrachan/quickstarts,stevef1uk/ipaas-quickstarts,oscerd/quickstarts,oscerd/quickstarts,rajdavies/ipaas-quickstarts,jmlambert78/ipaas-quickstarts,chirino/ipaas-quickstarts,jstrachan/ipaas-quickstarts,isatimur/quickstarts,hekonsek/quickstarts,rhuss/ipaas-quickstarts,rajdavies/ipaas-quickstarts,fabric8io/ipaas-quickstarts,jstrachan/ipaas-quickstarts,fabric8io/quickstarts,jstrachan/ipaas-quickstarts,rhuss/ipaas-quickstarts,KurtStam/ipaas-quickstarts,rhuss/ipaas-quickstarts,stevef1uk/ipaas-quickstarts,rajdavies/ipaas-quickstarts,jimmidyson/ipaas-quickstarts
/* * Copyright 2005-2014 Red Hat, Inc. * * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.fabric8.apps.gogs; import io.fabric8.kubernetes.generator.annotation.KubernetesModelProcessor; import io.fabric8.openshift.api.model.OAuthClientBuilder; import io.fabric8.openshift.api.model.template.TemplateBuilder; import java.util.Arrays; @KubernetesModelProcessor public class GogsModelProcessor { private static final String NAME = "gogs"; public void onList(TemplateBuilder builder) { builder.addNewOAuthClientObject() .withNewMetadata() .withName(NAME) .and() .withRedirectURIs(Arrays.asList( "http://localhost:3000", "http://gogs.${DOMAIN}", "https://gogs.${DOMAIN}")) .and() .addNewServiceObject() .withNewMetadata() .withName(NAME) .addToLabels("component", NAME) .addToLabels("provider", "fabric8") .endMetadata() .withNewSpec() .addNewPort() .withProtocol("TCP") .withPort(80) .withNewTargetPort(3000) .endPort() .addToSelector("component", NAME) .addToSelector("provider", "fabric8") .endSpec() .endServiceObject() // Second service .addNewServiceObject() .withNewMetadata() .withName(NAME + "-ssh") .addToLabels("component", NAME) .addToLabels("provider", "fabric8") .endMetadata() .withNewSpec() .addNewPort() .withProtocol("TCP") .withPort(22) .withNewTargetPort(22) .endPort() .addToSelector("component", NAME) .addToSelector("provider", "fabric8") .endSpec() .endServiceObject() .build(); } }
apps/gogs/src/main/java/io/fabric8/apps/gogs/GogsModelProcessor.java
/* * Copyright 2005-2014 Red Hat, Inc. * * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.fabric8.apps.gogs; import io.fabric8.kubernetes.generator.annotation.KubernetesModelProcessor; import io.fabric8.openshift.api.model.OAuthClientBuilder; import io.fabric8.openshift.api.model.template.TemplateBuilder; import java.util.Arrays; @KubernetesModelProcessor public class GogsModelProcessor { private static final String NAME = "gogs"; public void onList(TemplateBuilder builder) { builder.addNewOAuthClientObject() .withNewMetadata() .withName(NAME) .and() .withRedirectURIs(Arrays.asList( "http://localhost:3000", "http://gogs.${DOMAIN}", "https://gogs.${DOMAIN}")) .and() .addNewServiceObject() .withNewMetadata() .withName(NAME + "-http") .addToLabels("component", NAME) .addToLabels("provider", "fabric8") .endMetadata() .withNewSpec() .addNewPort() .withProtocol("TCP") .withPort(80) .withNewTargetPort(3000) .endPort() .addToSelector("component", NAME) .addToSelector("provider", "fabric8") .endSpec() .endServiceObject() // Second service .addNewServiceObject() .withNewMetadata() .withName(NAME + "-ssh") .addToLabels("component", NAME) .addToLabels("provider", "fabric8") .endMetadata() .withNewSpec() .addNewPort() .withProtocol("TCP") .withPort(22) .withNewTargetPort(22) .endPort() .addToSelector("component", NAME) .addToSelector("provider", "fabric8") .endSpec() .endServiceObject() .build(); } }
switch to new gogs service name
apps/gogs/src/main/java/io/fabric8/apps/gogs/GogsModelProcessor.java
switch to new gogs service name
<ide><path>pps/gogs/src/main/java/io/fabric8/apps/gogs/GogsModelProcessor.java <ide> .and() <ide> .addNewServiceObject() <ide> .withNewMetadata() <del> .withName(NAME + "-http") <add> .withName(NAME) <ide> .addToLabels("component", NAME) <ide> .addToLabels("provider", "fabric8") <ide> .endMetadata()
Java
mit
933a48b3e6400082bc006ec3934f64d44df03722
0
flocke/andOTP
/* * Copyright (C) 2017-2018 Jakob Nixdorf * Copyright (C) 2015 Bruno Bierbaumer * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.shadowice.flocke.andotp.Database; import android.net.Uri; import org.apache.commons.codec.binary.Base32; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.shadowice.flocke.andotp.Utilities.EntryThumbnail; import org.shadowice.flocke.andotp.Utilities.TokenCalculator; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; public class Entry { public enum OTPType { TOTP, HOTP, STEAM } private static final OTPType DEFAULT_TYPE = OTPType.TOTP; private static final int DEFAULT_PERIOD = 30; private static final String JSON_SECRET = "secret"; private static final String JSON_ISSUER = "issuer"; private static final String JSON_LABEL = "label"; private static final String JSON_PERIOD = "period"; private static final String JSON_COUNTER = "counter"; private static final String JSON_DIGITS = "digits"; private static final String JSON_TYPE = "type"; private static final String JSON_ALGORITHM = "algorithm"; private static final String JSON_TAGS = "tags"; private static final String JSON_THUMBNAIL = "thumbnail"; private static final String JSON_LAST_USED = "last_used"; private static final String JSON_USED_FREQUENCY = "used_frequency"; private OTPType type = OTPType.TOTP; private int period = TokenCalculator.TOTP_DEFAULT_PERIOD; private int digits = TokenCalculator.TOTP_DEFAULT_DIGITS; private TokenCalculator.HashAlgorithm algorithm = TokenCalculator.DEFAULT_ALGORITHM; private byte[] secret; private long counter; private String issuer; private String label; private String currentOTP; private boolean visible = false; private Runnable hideTask = null; private long last_update = 0; private long last_used = 0; private long used_frequency = 0; public List<String> tags = new ArrayList<>(); private EntryThumbnail.EntryThumbnails thumbnail = EntryThumbnail.EntryThumbnails.Default; private static final int COLOR_DEFAULT = 0; public static final int COLOR_RED = 1; private static final int EXPIRY_TIME = 8; private int color = COLOR_DEFAULT; public Entry(){} public Entry(OTPType type, String secret, int period, int digits, String issuer, String label, TokenCalculator.HashAlgorithm algorithm, List<String> tags) { this.type = type; this.secret = new Base32().decode(secret.toUpperCase()); this.period = period; this.digits = digits; this.issuer = issuer; this.label = label; this.algorithm = algorithm; this.tags = tags; setThumbnailFromIssuer(issuer); } public Entry(OTPType type, String secret, long counter, int digits, String issuer, String label, TokenCalculator.HashAlgorithm algorithm, List<String> tags) { this.type = type; this.secret = new Base32().decode(secret.toUpperCase()); this.counter = counter; this.digits = digits; this.issuer = issuer; this.label = label; this.algorithm = algorithm; this.tags = tags; setThumbnailFromIssuer(issuer); } public Entry(String contents) throws Exception { contents = contents.replaceFirst("otpauth", "http"); Uri uri = Uri.parse(contents); URL url = new URL(contents); if(!url.getProtocol().equals("http")){ throw new Exception("Invalid Protocol"); } switch (url.getHost()) { case "totp": type = OTPType.TOTP; break; case "hotp": type = OTPType.HOTP; break; case "steam": type = OTPType.STEAM; break; default: throw new Exception("unknown otp type"); } String secret = uri.getQueryParameter("secret"); String label = uri.getPath().substring(1); String counter = uri.getQueryParameter("counter"); String issuer = uri.getQueryParameter("issuer"); String period = uri.getQueryParameter("period"); String digits = uri.getQueryParameter("digits"); String algorithm = uri.getQueryParameter("algorithm"); List<String> tags = uri.getQueryParameters("tags"); if (type == OTPType.HOTP) { if (counter != null) { this.counter = Long.parseLong(counter); } else { throw new Exception("missing counter for HOTP"); } } else if (type == OTPType.TOTP || type == OTPType.STEAM) { if (period != null) { this.period = Integer.parseInt(period); } else { this.period = TokenCalculator.TOTP_DEFAULT_PERIOD; } } this.issuer = issuer; this.label = label; this.secret = new Base32().decode(secret.toUpperCase()); if (digits != null) { this.digits = Integer.parseInt(digits); } else { this.digits = this.type == OTPType.STEAM ? TokenCalculator.STEAM_DEFAULT_DIGITS : TokenCalculator.TOTP_DEFAULT_DIGITS; } if (algorithm != null) { this.algorithm = TokenCalculator.HashAlgorithm.valueOf(algorithm.toUpperCase()); } else { this.algorithm = TokenCalculator.DEFAULT_ALGORITHM; } if (tags != null) { this.tags = tags; } else { this.tags = new ArrayList<>(); } if (issuer != null) { setThumbnailFromIssuer(issuer); } } public Entry (JSONObject jsonObj) throws Exception { this.secret = new Base32().decode(jsonObj.getString(JSON_SECRET).toUpperCase()); this.label = jsonObj.getString(JSON_LABEL); try { this.issuer = jsonObj.getString(JSON_ISSUER); } catch (JSONException e) { // Older backup version did not save issuer and label separately this.issuer = ""; } try { this.type = OTPType.valueOf(jsonObj.getString(JSON_TYPE)); } catch(Exception e) { this.type = DEFAULT_TYPE; } try { this.period = jsonObj.getInt(JSON_PERIOD); } catch(Exception e) { if (type == OTPType.TOTP) this.period = DEFAULT_PERIOD; } try { this.counter = jsonObj.getLong(JSON_COUNTER); } catch (Exception e) { if (type == OTPType.HOTP) throw new Exception("missing counter for HOTP"); } try { this.digits = jsonObj.getInt(JSON_DIGITS); } catch(Exception e) { this.digits = TokenCalculator.TOTP_DEFAULT_DIGITS; } try { this.algorithm = TokenCalculator.HashAlgorithm.valueOf(jsonObj.getString(JSON_ALGORITHM)); } catch (Exception e) { this.algorithm = TokenCalculator.DEFAULT_ALGORITHM; } this.tags = new ArrayList<>(); try { JSONArray tagsArray = jsonObj.getJSONArray(JSON_TAGS); for(int i = 0; i < tagsArray.length(); i++) { this.tags.add(tagsArray.getString(i)); } } catch (Exception e) { // Nothing wrong here } try { this.thumbnail = EntryThumbnail.EntryThumbnails.valueOf(jsonObj.getString(JSON_THUMBNAIL)); } catch(Exception e) { this.thumbnail = EntryThumbnail.EntryThumbnails.Default; } try { this.last_used = jsonObj.getLong(JSON_LAST_USED); } catch (Exception e) { this.last_used = 0; } try { this.used_frequency = jsonObj.getLong(JSON_USED_FREQUENCY); } catch (Exception e) { this.used_frequency = 0; } } public JSONObject toJSON() throws JSONException { JSONObject jsonObj = new JSONObject(); jsonObj.put(JSON_SECRET, new String(new Base32().encode(getSecret()))); jsonObj.put(JSON_ISSUER, getIssuer()); jsonObj.put(JSON_LABEL, getLabel()); jsonObj.put(JSON_DIGITS, getDigits()); jsonObj.put(JSON_TYPE, getType().toString()); jsonObj.put(JSON_ALGORITHM, algorithm.toString()); jsonObj.put(JSON_THUMBNAIL, getThumbnail().name()); jsonObj.put(JSON_LAST_USED, getLastUsed()); jsonObj.put(JSON_USED_FREQUENCY, getUsedFrequency() ); if (type == OTPType.TOTP) jsonObj.put(JSON_PERIOD, getPeriod()); else if (type == OTPType.HOTP) jsonObj.put(JSON_COUNTER, getCounter()); JSONArray tagsArray = new JSONArray(); for(String tag : tags){ tagsArray.put(tag); } jsonObj.put(JSON_TAGS, tagsArray); return jsonObj; } public Uri toUri() { String type; switch (this.type) { case TOTP: type = "totp"; break; case HOTP: type = "hotp"; break; case STEAM: type = "steam"; break; default: return null; } Uri.Builder builder = new Uri.Builder() .scheme("otpauth") .authority(type) .appendPath(this.label) .appendQueryParameter("secret", new Base32().encodeAsString(this.secret)); if (this.issuer != null) { builder.appendQueryParameter("issuer", this.issuer); } switch (this.type) { case HOTP: builder.appendQueryParameter("counter", Long.toString(this.counter)); case TOTP: if (this.period != TokenCalculator.TOTP_DEFAULT_PERIOD) builder.appendQueryParameter("period", Integer.toString(this.period)); break; } if (this.digits != TokenCalculator.TOTP_DEFAULT_DIGITS) { builder.appendQueryParameter("digits", Integer.toString(this.digits)); } if (this.algorithm != TokenCalculator.DEFAULT_ALGORITHM) { builder.appendQueryParameter("algorithm", this.algorithm.name()); } for (String tag : this.tags) { builder.appendQueryParameter("tags", tag); } return builder.build(); } public boolean isTimeBased() { return type == OTPType.TOTP || type == OTPType.STEAM; } public boolean isCounterBased() { return type == OTPType.HOTP; } public OTPType getType() { return type; } public void setType(OTPType type) { this.type = type; } public byte[] getSecret() { return secret; } public void setSecret(byte[] secret) { this.secret = secret; } public String getIssuer() { return issuer; } public void setIssuer(String issuer) { this.issuer = issuer; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public int getPeriod() { return period; } public void setPeriod(int period) { this.period = period; } public long getCounter() { return counter; } public void setCounter(long counter) { this.counter = counter; } public int getDigits() { return digits; } public void setDigits(int digits) { this.digits = digits; } public List<String> getTags() { return tags; } public void setTags(List<String> tags) { this.tags = tags; } public EntryThumbnail.EntryThumbnails getThumbnail() { return thumbnail; } public void setThumbnail( EntryThumbnail.EntryThumbnails value) { thumbnail = value; } public TokenCalculator.HashAlgorithm getAlgorithm() { return this.algorithm; } public void setAlgorithm(TokenCalculator.HashAlgorithm algorithm) { this.algorithm = algorithm; } public boolean hasNonDefaultPeriod() { return this.period != TokenCalculator.TOTP_DEFAULT_PERIOD; } public boolean isVisible() { return visible; } public void setVisible(boolean value) { this.visible = value; } public void setHideTask(Runnable newTask) { this.hideTask = newTask; } public Runnable getHideTask() { return this.hideTask; } public long getLastUsed() { return this.last_used; } public void setLastUsed(long value) { this.last_used = value; } public long getUsedFrequency() { return used_frequency; } public void setUsedFrequency(long value) { this.used_frequency = value; } public String getCurrentOTP() { return currentOTP; } public boolean updateOTP() { if (type == OTPType.TOTP || type == OTPType.STEAM) { long time = System.currentTimeMillis() / 1000; long counter = time / this.getPeriod(); if (counter > last_update) { if (type == OTPType.TOTP) currentOTP = TokenCalculator.TOTP_RFC6238(secret, period, digits, algorithm); else if (type == OTPType.STEAM) currentOTP = TokenCalculator.TOTP_Steam(secret, period, digits, algorithm); last_update = counter; //New OTP. Change color to default color setColor(COLOR_DEFAULT); return true; } else { return false; } } else if (type == OTPType.HOTP) { currentOTP = TokenCalculator.HOTP(secret, counter, digits, algorithm); return true; } else { return false; } } /** * Checks if the OTP is expiring. The color for the entry will be changed to red if the expiry time is less than or equal to 8 seconds * COLOR_DEFAULT indicates that the OTP has not expired. In this case check if the OTP is about to expire. Update color to COLOR_RED if it's about to expire * COLOR_RED indicates that the OTP is already about to expire. Don't check again. * The color will be reset to COLOR_DEFAULT in {@link #updateOTP()} method * * @return Return true only if the color has changed to red to save from unnecessary notifying dataset * */ public boolean hasColorChanged() { if(color == COLOR_DEFAULT){ long time = System.currentTimeMillis() / 1000; if ((time % getPeriod()) > (getPeriod() - EXPIRY_TIME)) { setColor(COLOR_RED); return true; } } return false; } private void setThumbnailFromIssuer(String issuer) { try { this.thumbnail = EntryThumbnail.EntryThumbnails.valueOfIgnoreCase(issuer); } catch(Exception e) { this.thumbnail = EntryThumbnail.EntryThumbnails.Default; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Entry entry = (Entry) o; return period == entry.period && digits == entry.digits && type == entry.type && counter == entry.counter && algorithm == entry.algorithm && Arrays.equals(secret, entry.secret) && Objects.equals(label, entry.label); } @Override public int hashCode() { return Objects.hash(type, period, counter, digits, algorithm, secret, label); } public void setColor(int color) { this.color = color; } public int getColor() { return color; } }
app/src/main/java/org/shadowice/flocke/andotp/Database/Entry.java
/* * Copyright (C) 2017-2018 Jakob Nixdorf * Copyright (C) 2015 Bruno Bierbaumer * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.shadowice.flocke.andotp.Database; import android.net.Uri; import org.apache.commons.codec.binary.Base32; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.shadowice.flocke.andotp.Utilities.EntryThumbnail; import org.shadowice.flocke.andotp.Utilities.TokenCalculator; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; public class Entry { public enum OTPType { TOTP, HOTP, STEAM } private static final OTPType DEFAULT_TYPE = OTPType.TOTP; private static final int DEFAULT_PERIOD = 30; private static final String JSON_SECRET = "secret"; private static final String JSON_ISSUER = "issuer"; private static final String JSON_LABEL = "label"; private static final String JSON_PERIOD = "period"; private static final String JSON_COUNTER = "counter"; private static final String JSON_DIGITS = "digits"; private static final String JSON_TYPE = "type"; private static final String JSON_ALGORITHM = "algorithm"; private static final String JSON_TAGS = "tags"; private static final String JSON_THUMBNAIL = "thumbnail"; private static final String JSON_LAST_USED = "last_used"; private static final String JSON_USED_FREQUENCY = "used_frequency"; private OTPType type = OTPType.TOTP; private int period = TokenCalculator.TOTP_DEFAULT_PERIOD; private int digits = TokenCalculator.TOTP_DEFAULT_DIGITS; private TokenCalculator.HashAlgorithm algorithm = TokenCalculator.DEFAULT_ALGORITHM; private byte[] secret; private long counter; private String issuer; private String label; private String currentOTP; private boolean visible = false; private Runnable hideTask = null; private long last_update = 0; private long last_used = 0; private long used_frequency = 0; public List<String> tags = new ArrayList<>(); private EntryThumbnail.EntryThumbnails thumbnail = EntryThumbnail.EntryThumbnails.Default; private static final int COLOR_DEFAULT = 0; public static final int COLOR_RED = 1; private static final int EXPIRY_TIME = 8; private int color = COLOR_DEFAULT; public Entry(){} public Entry(OTPType type, String secret, int period, int digits, String issuer, String label, TokenCalculator.HashAlgorithm algorithm, List<String> tags) { this.type = type; this.secret = new Base32().decode(secret.toUpperCase()); this.period = period; this.digits = digits; this.issuer = issuer; this.label = label; this.algorithm = algorithm; this.tags = tags; setThumbnailFromIssuer(issuer); } public Entry(OTPType type, String secret, long counter, int digits, String issuer, String label, TokenCalculator.HashAlgorithm algorithm, List<String> tags) { this.type = type; this.secret = new Base32().decode(secret.toUpperCase()); this.counter = counter; this.digits = digits; this.issuer = issuer; this.label = label; this.algorithm = algorithm; this.tags = tags; setThumbnailFromIssuer(issuer); } public Entry(String contents) throws Exception { contents = contents.replaceFirst("otpauth", "http"); Uri uri = Uri.parse(contents); URL url = new URL(contents); if(!url.getProtocol().equals("http")){ throw new Exception("Invalid Protocol"); } if(url.getHost().equals("totp")){ type = OTPType.TOTP; } else if (url.getHost().equals("hotp")) { type = OTPType.HOTP; } else if (url.getHost().equals("steam")) { type = OTPType.STEAM; } else { throw new Exception("unknown otp type"); } String secret = uri.getQueryParameter("secret"); String label = uri.getPath().substring(1); String counter = uri.getQueryParameter("counter"); String issuer = uri.getQueryParameter("issuer"); String period = uri.getQueryParameter("period"); String digits = uri.getQueryParameter("digits"); String algorithm = uri.getQueryParameter("algorithm"); List<String> tags = uri.getQueryParameters("tags"); if (type == OTPType.HOTP) { if (counter != null) { this.counter = Long.parseLong(counter); } else { throw new Exception("missing counter for HOTP"); } } else if (type == OTPType.TOTP || type == OTPType.STEAM) { if (period != null) { this.period = Integer.parseInt(period); } else { this.period = TokenCalculator.TOTP_DEFAULT_PERIOD; } } this.issuer = issuer; this.label = label; this.secret = new Base32().decode(secret.toUpperCase()); if (digits != null) { this.digits = Integer.parseInt(digits); } else { this.digits = this.type == OTPType.STEAM ? TokenCalculator.STEAM_DEFAULT_DIGITS : TokenCalculator.TOTP_DEFAULT_DIGITS; } if (algorithm != null) { this.algorithm = TokenCalculator.HashAlgorithm.valueOf(algorithm.toUpperCase()); } else { this.algorithm = TokenCalculator.DEFAULT_ALGORITHM; } if (tags != null) { this.tags = tags; } else { this.tags = new ArrayList<>(); } if (issuer != null) { setThumbnailFromIssuer(issuer); } } public Entry (JSONObject jsonObj) throws Exception { this.secret = new Base32().decode(jsonObj.getString(JSON_SECRET).toUpperCase()); this.label = jsonObj.getString(JSON_LABEL); try { this.issuer = jsonObj.getString(JSON_ISSUER); } catch (JSONException e) { // Older backup version did not save issuer and label separately this.issuer = ""; } try { this.type = OTPType.valueOf(jsonObj.getString(JSON_TYPE)); } catch(Exception e) { this.type = DEFAULT_TYPE; } try { this.period = jsonObj.getInt(JSON_PERIOD); } catch(Exception e) { if (type == OTPType.TOTP) this.period = DEFAULT_PERIOD; } try { this.counter = jsonObj.getLong(JSON_COUNTER); } catch (Exception e) { if (type == OTPType.HOTP) throw new Exception("missing counter for HOTP"); } try { this.digits = jsonObj.getInt(JSON_DIGITS); } catch(Exception e) { this.digits = TokenCalculator.TOTP_DEFAULT_DIGITS; } try { this.algorithm = TokenCalculator.HashAlgorithm.valueOf(jsonObj.getString(JSON_ALGORITHM)); } catch (Exception e) { this.algorithm = TokenCalculator.DEFAULT_ALGORITHM; } this.tags = new ArrayList<>(); try { JSONArray tagsArray = jsonObj.getJSONArray(JSON_TAGS); for(int i = 0; i < tagsArray.length(); i++) { this.tags.add(tagsArray.getString(i)); } } catch (Exception e) { // Nothing wrong here } try { this.thumbnail = EntryThumbnail.EntryThumbnails.valueOf(jsonObj.getString(JSON_THUMBNAIL)); } catch(Exception e) { this.thumbnail = EntryThumbnail.EntryThumbnails.Default; } try { this.last_used = jsonObj.getLong(JSON_LAST_USED); } catch (Exception e) { this.last_used = 0; } try { this.used_frequency = jsonObj.getLong(JSON_USED_FREQUENCY); } catch (Exception e) { this.used_frequency = 0; } } public JSONObject toJSON() throws JSONException { JSONObject jsonObj = new JSONObject(); jsonObj.put(JSON_SECRET, new String(new Base32().encode(getSecret()))); jsonObj.put(JSON_ISSUER, getIssuer()); jsonObj.put(JSON_LABEL, getLabel()); jsonObj.put(JSON_DIGITS, getDigits()); jsonObj.put(JSON_TYPE, getType().toString()); jsonObj.put(JSON_ALGORITHM, algorithm.toString()); jsonObj.put(JSON_THUMBNAIL, getThumbnail().name()); jsonObj.put(JSON_LAST_USED, getLastUsed()); jsonObj.put(JSON_USED_FREQUENCY, getUsedFrequency() ); if (type == OTPType.TOTP) jsonObj.put(JSON_PERIOD, getPeriod()); else if (type == OTPType.HOTP) jsonObj.put(JSON_COUNTER, getCounter()); JSONArray tagsArray = new JSONArray(); for(String tag : tags){ tagsArray.put(tag); } jsonObj.put(JSON_TAGS, tagsArray); return jsonObj; } public Uri toUri() { String type; switch (this.type) { case TOTP: type = "totp"; break; case HOTP: type = "hotp"; break; default: return null; } Uri.Builder builder = new Uri.Builder() .scheme("otpauth") .authority(type) .appendPath(this.label) .appendQueryParameter("secret", new Base32().encodeAsString(this.secret)); if (this.issuer != null) { builder.appendQueryParameter("issuer", this.issuer); } switch (this.type) { case HOTP: builder.appendQueryParameter("counter", Long.toString(this.counter)); case TOTP: if (this.period != TokenCalculator.TOTP_DEFAULT_PERIOD) builder.appendQueryParameter("period", Integer.toString(this.period)); break; } if (this.digits != TokenCalculator.TOTP_DEFAULT_DIGITS) { builder.appendQueryParameter("digits", Integer.toString(this.digits)); } if (this.algorithm != TokenCalculator.DEFAULT_ALGORITHM) { builder.appendQueryParameter("algorithm", this.algorithm.name()); } for (String tag : this.tags) { builder.appendQueryParameter("tags", tag); } return builder.build(); } public boolean isTimeBased() { return type == OTPType.TOTP || type == OTPType.STEAM; } public boolean isCounterBased() { return type == OTPType.HOTP; } public OTPType getType() { return type; } public void setType(OTPType type) { this.type = type; } public byte[] getSecret() { return secret; } public void setSecret(byte[] secret) { this.secret = secret; } public String getIssuer() { return issuer; } public void setIssuer(String issuer) { this.issuer = issuer; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public int getPeriod() { return period; } public void setPeriod(int period) { this.period = period; } public long getCounter() { return counter; } public void setCounter(long counter) { this.counter = counter; } public int getDigits() { return digits; } public void setDigits(int digits) { this.digits = digits; } public List<String> getTags() { return tags; } public void setTags(List<String> tags) { this.tags = tags; } public EntryThumbnail.EntryThumbnails getThumbnail() { return thumbnail; } public void setThumbnail( EntryThumbnail.EntryThumbnails value) { thumbnail = value; } public TokenCalculator.HashAlgorithm getAlgorithm() { return this.algorithm; } public void setAlgorithm(TokenCalculator.HashAlgorithm algorithm) { this.algorithm = algorithm; } public boolean hasNonDefaultPeriod() { return this.period != TokenCalculator.TOTP_DEFAULT_PERIOD; } public boolean isVisible() { return visible; } public void setVisible(boolean value) { this.visible = value; } public void setHideTask(Runnable newTask) { this.hideTask = newTask; } public Runnable getHideTask() { return this.hideTask; } public long getLastUsed() { return this.last_used; } public void setLastUsed(long value) { this.last_used = value; } public long getUsedFrequency() { return used_frequency; } public void setUsedFrequency(long value) { this.used_frequency = value; } public String getCurrentOTP() { return currentOTP; } public boolean updateOTP() { if (type == OTPType.TOTP || type == OTPType.STEAM) { long time = System.currentTimeMillis() / 1000; long counter = time / this.getPeriod(); if (counter > last_update) { if (type == OTPType.TOTP) currentOTP = TokenCalculator.TOTP_RFC6238(secret, period, digits, algorithm); else if (type == OTPType.STEAM) currentOTP = TokenCalculator.TOTP_Steam(secret, period, digits, algorithm); last_update = counter; //New OTP. Change color to default color setColor(COLOR_DEFAULT); return true; } else { return false; } } else if (type == OTPType.HOTP) { currentOTP = TokenCalculator.HOTP(secret, counter, digits, algorithm); return true; } else { return false; } } /** * Checks if the OTP is expiring. The color for the entry will be changed to red if the expiry time is less than or equal to 8 seconds * COLOR_DEFAULT indicates that the OTP has not expired. In this case check if the OTP is about to expire. Update color to COLOR_RED if it's about to expire * COLOR_RED indicates that the OTP is already about to expire. Don't check again. * The color will be reset to COLOR_DEFAULT in {@link #updateOTP()} method * * @return Return true only if the color has changed to red to save from unnecessary notifying dataset * */ public boolean hasColorChanged() { if(color == COLOR_DEFAULT){ long time = System.currentTimeMillis() / 1000; if ((time % getPeriod()) > (getPeriod() - EXPIRY_TIME)) { setColor(COLOR_RED); return true; } } return false; } private void setThumbnailFromIssuer(String issuer) { try { this.thumbnail = EntryThumbnail.EntryThumbnails.valueOfIgnoreCase(issuer); } catch(Exception e) { this.thumbnail = EntryThumbnail.EntryThumbnails.Default; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Entry entry = (Entry) o; return period == entry.period && digits == entry.digits && type == entry.type && counter == entry.counter && algorithm == entry.algorithm && Arrays.equals(secret, entry.secret) && Objects.equals(label, entry.label); } @Override public int hashCode() { return Objects.hash(type, period, counter, digits, algorithm, secret, label); } public void setColor(int color) { this.color = color; } public int getColor() { return color; } }
Generate QR codes for Steam entries
app/src/main/java/org/shadowice/flocke/andotp/Database/Entry.java
Generate QR codes for Steam entries
<ide><path>pp/src/main/java/org/shadowice/flocke/andotp/Database/Entry.java <ide> throw new Exception("Invalid Protocol"); <ide> } <ide> <del> if(url.getHost().equals("totp")){ <del> type = OTPType.TOTP; <del> } else if (url.getHost().equals("hotp")) { <del> type = OTPType.HOTP; <del> } else if (url.getHost().equals("steam")) { <del> type = OTPType.STEAM; <del> } else { <del> throw new Exception("unknown otp type"); <add> switch (url.getHost()) { <add> case "totp": <add> type = OTPType.TOTP; <add> break; <add> case "hotp": <add> type = OTPType.HOTP; <add> break; <add> case "steam": <add> type = OTPType.STEAM; <add> break; <add> default: <add> throw new Exception("unknown otp type"); <ide> } <ide> <ide> String secret = uri.getQueryParameter("secret"); <ide> break; <ide> case HOTP: <ide> type = "hotp"; <add> break; <add> case STEAM: <add> type = "steam"; <ide> break; <ide> default: <ide> return null;
Java
mit
143598b091a3ae1dcc3b83d0ae7fc8096ad1e8d9
0
creativetrendsapps/SimplicityBrowser,creativetrendsapps/SimplicityBrowser
package com.creativetrends.app.simplicity.activities; import android.content.SharedPreferences; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.preference.PreferenceManager; import androidx.core.content.ContextCompat; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.creativetrends.app.simplicity.fragments.AboutFragment; import com.creativetrends.simplicity.app.R; /** * Created by Creative Trends Apps. */ public class AboutActivity extends AppCompatActivity { Toolbar toolbar; SharedPreferences preferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); preferences = PreferenceManager.getDefaultSharedPreferences(this); toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); Drawable drawable = toolbar.getNavigationIcon(); if (drawable != null) { drawable.setColorFilter(ContextCompat.getColor(this, R.color.grey_color), PorterDuff.Mode.SRC_ATOP); } } getFragmentManager().beginTransaction().replace(R.id.fragment_container, new AboutFragment()).commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onStart() { super.onStart(); } @Override protected void onDestroy() { super.onDestroy(); } @Override public void onBackPressed() { int count = getFragmentManager().getBackStackEntryCount(); if (count == 0) { super.onBackPressed(); getFragmentManager().popBackStack(); } } }
app/src/main/java/com/creativetrends/app/simplicity/activities/AboutActivity.java
package com.creativetrends.app.simplicity.activities; import android.content.SharedPreferences; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.creativetrends.app.simplicity.fragments.AboutFragment; import com.creativetrends.simplicity.app.R; /** * Created by Creative Trends Apps. */ public class AboutActivity extends AppCompatActivity { Toolbar toolbar; SharedPreferences preferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); preferences = PreferenceManager.getDefaultSharedPreferences(this); toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); Drawable drawable = toolbar.getNavigationIcon(); if (drawable != null) { drawable.setColorFilter(ContextCompat.getColor(this, R.color.grey_color), PorterDuff.Mode.SRC_ATOP); } } getFragmentManager().beginTransaction().replace(R.id.fragment_container, new AboutFragment()).commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onStart() { super.onStart(); } @Override protected void onDestroy() { super.onDestroy(); } @Override public void onBackPressed() { int count = getFragmentManager().getBackStackEntryCount(); if (count == 0) { super.onBackPressed(); getFragmentManager().popBackStack(); } } }
Update AboutActivity.java
app/src/main/java/com/creativetrends/app/simplicity/activities/AboutActivity.java
Update AboutActivity.java
<ide><path>pp/src/main/java/com/creativetrends/app/simplicity/activities/AboutActivity.java <ide> import android.graphics.drawable.Drawable; <ide> import android.os.Bundle; <ide> import android.preference.PreferenceManager; <del>import android.support.v4.content.ContextCompat; <del>import android.support.v7.app.AppCompatActivity; <del>import android.support.v7.widget.Toolbar; <add>import androidx.core.content.ContextCompat; <add>import androidx.appcompat.app.AppCompatActivity; <add>import androidx.appcompat.widget.Toolbar; <ide> import android.view.Menu; <ide> import android.view.MenuItem; <ide>
Java
apache-2.0
0485e92e8192a6719adc8c5dd1b8e35af69ff201
0
inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service
/* * Copyright 2012 Shared Learning Collaborative, LLC * * 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.slc.sli.api.translator; import com.sun.jersey.spi.container.ContainerRequest; import org.apache.commons.lang3.StringUtils; import org.slc.sli.api.constants.EntityNames; import org.slc.sli.api.constants.PathConstants; import org.slc.sli.api.constants.ResourceNames; import org.slc.sli.api.security.context.PagingRepositoryDelegate; import org.slc.sli.domain.Entity; import org.slc.sli.domain.NeutralCriteria; import org.slc.sli.domain.NeutralQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.util.UriTemplate; import java.util.*; /** * This class aligns request uri with dataModel * @author pghosh * */ @Component public class URITranslator { private Map<String,URITranlation> uriTranslationMap = new HashMap<String, URITranlation>(); public void setRepository(PagingRepositoryDelegate<Entity> repository) { this.repository = repository; } @Autowired private PagingRepositoryDelegate<Entity> repository; private static String PARENT_LEARNING_OBJECTIVE = "parentLearningObjective"; private static String CHILD_LEARNING_OBJECTIVE = "childLearningObjective"; private static String LEARNING_STANDARD = "learningStandards"; private static String ID_KEY = "_id"; public URITranslator() { translate(PARENT_LEARNING_OBJECTIVE).transformTo(ResourceNames.LEARNINGOBJECTIVES). usingPattern("{version}/learningObjectives/{id}/parentLearningObjectives"). usingCollection(EntityNames.LEARNING_OBJECTIVE) .withKey(PARENT_LEARNING_OBJECTIVE).andReference(ID_KEY).build(); translate(CHILD_LEARNING_OBJECTIVE).transformTo(ResourceNames.LEARNINGOBJECTIVES). usingPattern("{version}/learningObjectives/{id}/childLearningObjectives"). usingCollection(EntityNames.LEARNING_OBJECTIVE).withKey(ID_KEY) .andReference(PARENT_LEARNING_OBJECTIVE).build(); translate(LEARNING_STANDARD).transformTo(ResourceNames.LEARNINGSTANDARDS). usingPattern("{version}/learningObjectives/{id}/learningStandards"). usingCollection(EntityNames.LEARNING_OBJECTIVE).withKey(ID_KEY) .andReference(LEARNING_STANDARD).build(); } public void translate(ContainerRequest request) { String uri = request.getPath(); for (Map.Entry<String,URITranlation> entry:uriTranslationMap.entrySet()) { String key = entry.getKey(); if (uri.contains(key)) { String newPath = uriTranslationMap.get(key).translate(request.getPath()); request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(PathConstants.V1).path(newPath).build()); } } } private URITranslationBuilder translate (String resource) { return new URITranslationBuilder(resource); } private class URITranslationBuilder { private String transformResource; private String transformTo; private String pattern; private String parentEntity; private String key; private String referenceKey; private URITranslationBuilder(String transformResource) { this.transformResource = transformResource; } public URITranslationBuilder transformTo (String transformTo) { this.transformTo = transformTo; return this; } public URITranslationBuilder usingPattern (String pattern) { this.pattern = pattern; return this; } public URITranslationBuilder usingCollection (String parentEntity) { this.parentEntity = parentEntity; return this; } public URITranslationBuilder withKey (String key) { this.key = key; return this; } public URITranslationBuilder andReference (String referenceKey) { this.referenceKey = referenceKey; return this; } public void build () { uriTranslationMap.put(transformResource, new URITranlation(transformTo, pattern, parentEntity, key, referenceKey)); } } public class URITranlation { String transformTo; String pattern; String parentEntity; String key; String referenceKey; URITranlation(String transformTo, String pattern, String parentEntity, String key, String referenceKey) { this.transformTo = transformTo; this.pattern = pattern; this.parentEntity = parentEntity; this.key = key; this.referenceKey = referenceKey; } public String translate(String requestPath) { final UriTemplate uriTemplate = new UriTemplate(pattern); Map<String, String> matchList = uriTemplate.match(requestPath); List<String> translatedIdList = new ArrayList<String>(); NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.addCriteria(new NeutralCriteria(referenceKey, "in", Arrays.asList(matchList.get("id")))); neutralQuery.setOffset(0); neutralQuery.setLimit(0); Iterable<Entity> entities = repository.findAll(parentEntity, neutralQuery); for (Entity entity: entities) { if(key.equals("_id")) { translatedIdList.add(entity.getEntityId()); } else if (entity.getBody().containsKey(key)) { Object value = entity.getBody().get(key); if (value instanceof String) { translatedIdList.add((String) value); } else if (value instanceof List<?>) { for (String id : (List<String>) value) { translatedIdList.add(id); } } } } return buildTranslatedPath(translatedIdList); } private String buildTranslatedPath( List<String> translatedIdList) { return transformTo + "/" + StringUtils.join(translatedIdList, ","); } } public URITranlation getTranslator(String uri) { return uriTranslationMap.get(uri); } }
sli/api/src/main/java/org/slc/sli/api/translator/URITranslator.java
/* * Copyright 2012 Shared Learning Collaborative, LLC * * 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.slc.sli.api.translator; import com.sun.jersey.spi.container.ContainerRequest; import org.apache.commons.lang3.StringUtils; import org.slc.sli.api.constants.EntityNames; import org.slc.sli.api.constants.PathConstants; import org.slc.sli.api.constants.ResourceNames; import org.slc.sli.api.security.context.PagingRepositoryDelegate; import org.slc.sli.domain.Entity; import org.slc.sli.domain.NeutralCriteria; import org.slc.sli.domain.NeutralQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.util.UriTemplate; import java.util.*; /** * This class aligns request uri with dataModel * @author pghosh * */ @Component public class URITranslator { private Map<String,URITranlation> uriTranslationMap = new HashMap<String, URITranlation>(); public void setRepository(PagingRepositoryDelegate<Entity> repository) { this.repository = repository; } @Autowired private PagingRepositoryDelegate<Entity> repository; private static String PARENT_LEARNING_OBJECTIVE = "parentLearningObjective"; private static String CHILD_LEARNING_OBJECTIVE = "childLearningObjective"; private static String ID_KEY = "_id"; public URITranslator() { translate(PARENT_LEARNING_OBJECTIVE).transformTo(ResourceNames.LEARNINGOBJECTIVES). usingPattern("{version}/learningObjectives/{id}/parentLearningObjectives"). usingCollection(EntityNames.LEARNING_OBJECTIVE) .withKey(PARENT_LEARNING_OBJECTIVE).andReference(ID_KEY).build(); translate(CHILD_LEARNING_OBJECTIVE).transformTo(ResourceNames.LEARNINGOBJECTIVES). usingPattern("{version}/learningObjectives/{id}/childLearningObjectives"). usingCollection(EntityNames.LEARNING_OBJECTIVE).withKey(ID_KEY) .andReference(PARENT_LEARNING_OBJECTIVE).build(); } public void translate(ContainerRequest request) { String uri = request.getPath(); for (Map.Entry<String,URITranlation> entry:uriTranslationMap.entrySet()) { String key = entry.getKey(); if (uri.contains(key)) { String newPath = uriTranslationMap.get(key).translate(request.getPath()); request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(PathConstants.V1).path(newPath).build()); } } } private URITranslationBuilder translate (String resource) { return new URITranslationBuilder(resource); } private class URITranslationBuilder { private String transformResource; private String transformTo; private String pattern; private String parentEntity; private String key; private String referenceKey; private URITranslationBuilder(String transformResource) { this.transformResource = transformResource; } public URITranslationBuilder transformTo (String transformTo) { this.transformTo = transformTo; return this; } public URITranslationBuilder usingPattern (String pattern) { this.pattern = pattern; return this; } public URITranslationBuilder usingCollection (String parentEntity) { this.parentEntity = parentEntity; return this; } public URITranslationBuilder withKey (String key) { this.key = key; return this; } public URITranslationBuilder andReference (String referenceKey) { this.referenceKey = referenceKey; return this; } public void build () { uriTranslationMap.put(transformResource, new URITranlation(transformTo, pattern, parentEntity, key, referenceKey)); } } public class URITranlation { String transformTo; String pattern; String parentEntity; String key; String referenceKey; URITranlation(String transformTo, String pattern, String parentEntity, String key, String referenceKey) { this.transformTo = transformTo; this.pattern = pattern; this.parentEntity = parentEntity; this.key = key; this.referenceKey = referenceKey; } public String translate(String requestPath) { final UriTemplate uriTemplate = new UriTemplate(pattern); Map<String, String> matchList = uriTemplate.match(requestPath); List<String> translatedIdList = new ArrayList<String>(); NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.addCriteria(new NeutralCriteria(referenceKey, "in", Arrays.asList(matchList.get("id")))); neutralQuery.setOffset(0); neutralQuery.setLimit(0); Iterable<Entity> entities = repository.findAll(parentEntity, neutralQuery); for (Entity entity: entities) { if(key.equals("_id")) { translatedIdList.add(entity.getEntityId()); } else if (entity.getBody().containsKey(key)) { Object value = entity.getBody().get(key); if (value instanceof String) { translatedIdList.add((String) value); } else if (value instanceof List<?>) { for (String id : (List<String>) value) { translatedIdList.add(id); } } } } return buildTranslatedPath(translatedIdList); } private String buildTranslatedPath( List<String> translatedIdList) { return transformTo + "/" + StringUtils.join(translatedIdList, ","); } } public URITranlation getTranslator(String uri) { return uriTranslationMap.get(uri); } }
[DE2088] added support for learningObjectives/{id}/learningStandards
sli/api/src/main/java/org/slc/sli/api/translator/URITranslator.java
[DE2088] added support for learningObjectives/{id}/learningStandards
<ide><path>li/api/src/main/java/org/slc/sli/api/translator/URITranslator.java <ide> <ide> private static String PARENT_LEARNING_OBJECTIVE = "parentLearningObjective"; <ide> private static String CHILD_LEARNING_OBJECTIVE = "childLearningObjective"; <add> private static String LEARNING_STANDARD = "learningStandards"; <ide> private static String ID_KEY = "_id"; <ide> <ide> public URITranslator() { <ide> usingPattern("{version}/learningObjectives/{id}/childLearningObjectives"). <ide> usingCollection(EntityNames.LEARNING_OBJECTIVE).withKey(ID_KEY) <ide> .andReference(PARENT_LEARNING_OBJECTIVE).build(); <add> translate(LEARNING_STANDARD).transformTo(ResourceNames.LEARNINGSTANDARDS). <add> usingPattern("{version}/learningObjectives/{id}/learningStandards"). <add> usingCollection(EntityNames.LEARNING_OBJECTIVE).withKey(ID_KEY) <add> .andReference(LEARNING_STANDARD).build(); <ide> } <ide> <ide> public void translate(ContainerRequest request) {
Java
apache-2.0
5c2235fcfe4f2b8cdbebadd3d36f84c5f534bf52
0
mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid
/* * * * Licensed to the Apache Software Foundation (ASF) under one or more * * contributor license agreements. The ASF licenses this file to You * * under the Apache License, Version 2.0 (the "License"); you may not * * use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. For additional information regarding * * copyright in this work, please see the NOTICE file in the top level * * directory of this distribution. * */ package org.apache.usergrid.rest; import com.fasterxml.jackson.databind.JsonNode; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MediaType; import java.util.HashMap; import java.util.Map; import java.util.UUID; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; /** * test index creation */ public class IndexResourceIT extends AbstractRestIT { @Rule public TestContextSetup context = new TestContextSetup( this ); //Used for all MUUserResourceITTests private Logger LOG = LoggerFactory.getLogger(IndexResourceIT.class); public IndexResourceIT(){ } @Ignore( "will finish when tests are working from rest" ) @Test public void TestAddIndex() throws Exception{ String superToken = superAdminToken(); Map<String, Object> data = new HashMap<String, Object>(); data.put( "replicas", 0 ); data.put( "shards", 1 ); UUID appId = this.context.getAppUuid(); // change the password as admin. The old password isn't required JsonNode node = null; try { node = mapper.readTree(resource().path("/system/index/" + appId) .queryParam("access_token", superToken) .accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON_TYPE) .post(String.class, data)); }catch (Exception e){ LOG.error("failed", e); fail(e.toString()); } assertNull( getError( node ) ); refreshIndex("test-organization", "test-app"); } }
stack/rest/src/test/java/org/apache/usergrid/rest/IndexResourceIT.java
/* * * * Licensed to the Apache Software Foundation (ASF) under one or more * * contributor license agreements. The ASF licenses this file to You * * under the Apache License, Version 2.0 (the "License"); you may not * * use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. For additional information regarding * * copyright in this work, please see the NOTICE file in the top level * * directory of this distribution. * */ package org.apache.usergrid.rest; import com.fasterxml.jackson.databind.JsonNode; import org.junit.Rule; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MediaType; import java.util.HashMap; import java.util.Map; import java.util.UUID; import static org.junit.Assert.assertNull; /** * Classy class class. */ public class IndexResourceIT extends AbstractRestIT { @Rule public TestContextSetup context = new TestContextSetup( this ); //Used for all MUUserResourceITTests private Logger LOG = LoggerFactory.getLogger(IndexResourceIT.class); public IndexResourceIT(){ } @Test public void TestAddIndex() throws Exception{ String superToken = superAdminToken(); Map<String, Object> data = new HashMap<String, Object>(); data.put( "replicas", 0 ); data.put( "shards", 1 ); UUID appId = this.context.getAppUuid(); // change the password as admin. The old password isn't required JsonNode node = mapper.readTree( resource().path( "/index/"+appId ).queryParam( "access_token", superToken ) .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ) .post( String.class, data )); assertNull( getError( node ) ); refreshIndex("test-organization", "test-app"); } }
ignore test for now
stack/rest/src/test/java/org/apache/usergrid/rest/IndexResourceIT.java
ignore test for now
<ide><path>tack/rest/src/test/java/org/apache/usergrid/rest/IndexResourceIT.java <ide> package org.apache.usergrid.rest; <ide> <ide> import com.fasterxml.jackson.databind.JsonNode; <add>import org.junit.Ignore; <ide> import org.junit.Rule; <ide> import org.junit.Test; <ide> import org.slf4j.Logger; <ide> import java.util.UUID; <ide> <ide> import static org.junit.Assert.assertNull; <add>import static org.junit.Assert.fail; <ide> <ide> /** <del> * Classy class class. <add> * test index creation <ide> */ <ide> public class IndexResourceIT extends AbstractRestIT { <ide> <ide> <ide> } <ide> <add> @Ignore( "will finish when tests are working from rest" ) <ide> @Test <ide> public void TestAddIndex() throws Exception{ <ide> String superToken = superAdminToken(); <ide> UUID appId = this.context.getAppUuid(); <ide> <ide> // change the password as admin. The old password isn't required <del> JsonNode node = mapper.readTree( resource().path( "/index/"+appId ).queryParam( "access_token", superToken ) <del> .accept( MediaType.APPLICATION_JSON ).type( MediaType.APPLICATION_JSON_TYPE ) <del> .post( String.class, data )); <del> <add> JsonNode node = null; <add> try { <add> node = mapper.readTree(resource().path("/system/index/" + appId) <add> .queryParam("access_token", superToken) <add> .accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON_TYPE) <add> .post(String.class, data)); <add> }catch (Exception e){ <add> LOG.error("failed", e); <add> fail(e.toString()); <add> } <ide> assertNull( getError( node ) ); <ide> <ide> refreshIndex("test-organization", "test-app");
Java
apache-2.0
a71645cf0bc4bcf36b8f94ecbe3a7a8153c4c233
0
dyu/protostuff,myxyz/protostuff,protostuff/protostuff,dyu/protostuff,protostuff/protostuff,tsheasha/protostuff,myxyz/protostuff,Shvid/protostuff,Shvid/protostuff,tsheasha/protostuff
//======================================================================== //Copyright 2007-2011 David Yu [email protected] //------------------------------------------------------------------------ //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 io.protostuff.runtime; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Properties; /** * The runtime environment. * * @author David Yu * @created Jul 8, 2011 */ public final class RuntimeEnv { /** * Returns true if serializing enums by name is activated. Disabled by default. */ public static final boolean ENUMS_BY_NAME; /** * Enabled by default. For security purposes, you probably would want to register all known classes and disable this * option. */ public static final boolean AUTO_LOAD_POLYMORPHIC_CLASSES; /** * Disabled by default. Writes a sentinel value (uint32) in place of null values. * Works only on the binary formats (protostuff/graph/protobuf). */ public static final boolean ALLOW_NULL_ARRAY_ELEMENT; /** * Disabled by default. For pojos that are not declared final, they could still be morphed to their respective * subclasses (inheritance). Enable this option if your parent classes aren't abstract classes. */ public static final boolean MORPH_NON_FINAL_POJOS; /** * Disabled by default. If true, type metadata will be included on serialization for fields that are collection * interfaces. Enabling this is useful if you want to retain the actual collection impl used. * <p/> * If disabled, type metadata will not be included and instead, will be mapped to a default impl. * <p/> * * <pre> * Collection = ArrayList * List = ArrayList * Set = HashSet * SortedSet = TreeSet * NavigableSet = TreeSet * Queue = LinkedList * BlockingQueue = LinkedBlockingQueue * Deque = LinkedList * BlockingDequeue = LinkedBlockingDeque * </pre> * <p/> * You can optionally enable only for a particular field by annotation it with * {@link io.protostuff.Morph}. */ public static final boolean MORPH_COLLECTION_INTERFACES; /** * Disabled by default. If true, type metadata will be included on serialization for fields that are map interfaces. * Enabling this is useful if you want to retain the actual map impl used. * <p/> * If disabled, type metadata will not be included and instead, will be mapped to a default impl. * <p/> * * <pre> * Map = HashMap * SortedMap = TreeMap * NavigableMap = TreeMap * ConcurrentMap = ConcurrentHashMap * ConcurrentNavigableMap = ConcurrentSkipListMap * </pre> * <p/> * You can optionally enable only for a particular field by annotation it with * {@link io.protostuff.Morph}. */ public static final boolean MORPH_MAP_INTERFACES; /** * On repeated fields, the List/Collection itself is not serialized (only its values). If you enable this option, * the repeated field will be serialized as a standalone message with a collection schema. Even if the * List/Collection is empty, an empty collection message is still written. * <p/> * This is particularly useful if you rely on {@link Object#equals(Object)} on your pojos. * <p/> * Disabled by default for protobuf compatibility. */ public static final boolean COLLECTION_SCHEMA_ON_REPEATED_FIELDS; /** * If true, sun.misc.Unsafe is used to access the fields of the objects instead of plain java reflections. Enabled * by default if running on a sun jre. */ public static final boolean USE_SUN_MISC_UNSAFE; static final Method newInstanceFromObjectInputStream, newInstanceFromObjectStreamClass; static final int objectConstructorId; static final Constructor<Object> OBJECT_CONSTRUCTOR; public static final IdStrategy ID_STRATEGY; static { Constructor<Object> c = null; Class<?> reflectionFactoryClass = null; try { c = Object.class.getConstructor((Class[]) null); reflectionFactoryClass = Thread.currentThread() .getContextClassLoader() .loadClass("sun.reflect.ReflectionFactory"); } catch (Exception e) { // ignore } OBJECT_CONSTRUCTOR = c != null && reflectionFactoryClass != null ? c : null; newInstanceFromObjectInputStream = OBJECT_CONSTRUCTOR == null ? getMethodNewInstanceFromObjectInputStream() : null; if (newInstanceFromObjectInputStream != null) { newInstanceFromObjectInputStream.setAccessible(true); newInstanceFromObjectStreamClass = null; objectConstructorId = -1; } else { newInstanceFromObjectStreamClass = getMethodNewInstanceFromObjectStreamClass(); objectConstructorId = newInstanceFromObjectStreamClass == null ? -1 : getObjectConstructorIdFromObjectStreamClass(); } Properties props = OBJECT_CONSTRUCTOR == null ? new Properties() : System.getProperties(); ENUMS_BY_NAME = Boolean.parseBoolean(props.getProperty( "protostuff.runtime.enums_by_name", "false")); AUTO_LOAD_POLYMORPHIC_CLASSES = Boolean.parseBoolean(props.getProperty( "protostuff.runtime.auto_load_polymorphic_classes", "true")); ALLOW_NULL_ARRAY_ELEMENT = Boolean.parseBoolean(props.getProperty( "protostuff.runtime.allow_null_array_element", "false")); MORPH_NON_FINAL_POJOS = Boolean.parseBoolean(props.getProperty( "protostuff.runtime.morph_non_final_pojos", "false")); MORPH_COLLECTION_INTERFACES = Boolean.parseBoolean(props.getProperty( "protostuff.runtime.morph_collection_interfaces", "false")); MORPH_MAP_INTERFACES = Boolean.parseBoolean(props.getProperty( "protostuff.runtime.morph_map_interfaces", "false")); COLLECTION_SCHEMA_ON_REPEATED_FIELDS = Boolean .parseBoolean(props .getProperty( "protostuff.runtime.collection_schema_on_repeated_fields", "false")); // must be on a sun jre USE_SUN_MISC_UNSAFE = OBJECT_CONSTRUCTOR != null && Boolean.parseBoolean(props.getProperty( "protostuff.runtime.use_sun_misc_unsafe", "true")); String factoryProp = props .getProperty("protostuff.runtime.id_strategy_factory"); if (factoryProp == null) ID_STRATEGY = new DefaultIdStrategy(); else { final IdStrategy.Factory factory; try { factory = ((IdStrategy.Factory) loadClass(factoryProp) .newInstance()); } catch (Exception e) { throw new RuntimeException(e); } ID_STRATEGY = factory.create(); factory.postCreate(); } } private static Method getMethodNewInstanceFromObjectInputStream() { try { return java.io.ObjectInputStream.class.getDeclaredMethod( "newInstance", Class.class, Class.class); } catch (Exception e) { return null; } } private static Method getMethodNewInstanceFromObjectStreamClass() { try { return java.io.ObjectStreamClass.class.getDeclaredMethod( "newInstance", Class.class, int.class); } catch (Exception e) { return null; } } private static int getObjectConstructorIdFromObjectStreamClass() { try { Method getConstructorId = java.io.ObjectStreamClass.class .getDeclaredMethod("getConstructorId", Class.class); getConstructorId.setAccessible(true); return ((Integer) getConstructorId.invoke(null, Object.class)) .intValue(); } catch (Exception e) { return -1; } } @SuppressWarnings("unchecked") static <T> Class<T> loadClass(String className) { try { return (Class<T>) Thread.currentThread().getContextClassLoader() .loadClass(className); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } /** * Returns an instatiator for the specified {@code clazz}. */ public static <T> Instantiator<T> newInstantiator(Class<T> clazz) { final Constructor<T> constructor = getConstructor(clazz); if (constructor == null) { // non-sun jre if (newInstanceFromObjectInputStream == null) { if (objectConstructorId == -1) throw new RuntimeException( "Could not resolve constructor for " + clazz); return new Android3Instantiator<T>(clazz); } return new Android2Instantiator<T>(clazz); } return new DefaultInstantiator<T>(constructor); } private static <T> Constructor<T> getConstructor(Class<T> clazz) { try { return clazz.getDeclaredConstructor((Class[]) null); } catch (SecurityException e) { return null; // return OBJECT_CONSTRUCTOR == null ? null : // OnDemandSunReflectionFactory.getConstructor(clazz, // OBJECT_CONSTRUCTOR); } catch (NoSuchMethodException e) { return null; // return OBJECT_CONSTRUCTOR == null ? null : // OnDemandSunReflectionFactory.getConstructor(clazz, // OBJECT_CONSTRUCTOR); } } private RuntimeEnv() { } public static abstract class Instantiator<T> { /** * Creates a new instance of an object. */ public abstract T newInstance(); } static final class DefaultInstantiator<T> extends Instantiator<T> { final Constructor<T> constructor; DefaultInstantiator(Constructor<T> constructor) { this.constructor = constructor; constructor.setAccessible(true); } public T newInstance() { try { return constructor.newInstance((Object[]) null); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } static final class Android2Instantiator<T> extends Instantiator<T> { final Class<T> clazz; Android2Instantiator(Class<T> clazz) { this.clazz = clazz; } @SuppressWarnings("unchecked") public T newInstance() { try { return (T) newInstanceFromObjectInputStream.invoke(null, clazz, Object.class); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } static final class Android3Instantiator<T> extends Instantiator<T> { final Class<T> clazz; Android3Instantiator(Class<T> clazz) { this.clazz = clazz; } @SuppressWarnings("unchecked") public T newInstance() { try { return (T) newInstanceFromObjectStreamClass.invoke(null, clazz, objectConstructorId); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } }
protostuff-runtime-md/src/main/java/io/protostuff/runtime/RuntimeEnv.java
//======================================================================== //Copyright 2007-2011 David Yu [email protected] //------------------------------------------------------------------------ //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 io.protostuff.runtime; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Properties; /** * The runtime environment. * * @author David Yu * @created Jul 8, 2011 */ public final class RuntimeEnv { /** * Returns true if serializing enums by name is activated. Disabled by default. */ public static final boolean ENUMS_BY_NAME; /** * Enabled by default. For security purposes, you probably would want to register all known classes and disable this * option. */ public static final boolean AUTO_LOAD_POLYMORPHIC_CLASSES; /** * Disabled by default. For pojos that are not declared final, they could still be morphed to their respective * subclasses (inheritance). Enable this option if your parent classes aren't abstract classes. */ public static final boolean MORPH_NON_FINAL_POJOS; /** * Disabled by default. If true, type metadata will be included on serialization for fields that are collection * interfaces. Enabling this is useful if you want to retain the actual collection impl used. * <p/> * If disabled, type metadata will not be included and instead, will be mapped to a default impl. * <p/> * * <pre> * Collection = ArrayList * List = ArrayList * Set = HashSet * SortedSet = TreeSet * NavigableSet = TreeSet * Queue = LinkedList * BlockingQueue = LinkedBlockingQueue * Deque = LinkedList * BlockingDequeue = LinkedBlockingDeque * </pre> * <p/> * You can optionally enable only for a particular field by annotation it with * {@link io.protostuff.Morph}. */ public static final boolean MORPH_COLLECTION_INTERFACES; /** * Disabled by default. If true, type metadata will be included on serialization for fields that are map interfaces. * Enabling this is useful if you want to retain the actual map impl used. * <p/> * If disabled, type metadata will not be included and instead, will be mapped to a default impl. * <p/> * * <pre> * Map = HashMap * SortedMap = TreeMap * NavigableMap = TreeMap * ConcurrentMap = ConcurrentHashMap * ConcurrentNavigableMap = ConcurrentSkipListMap * </pre> * <p/> * You can optionally enable only for a particular field by annotation it with * {@link io.protostuff.Morph}. */ public static final boolean MORPH_MAP_INTERFACES; /** * On repeated fields, the List/Collection itself is not serialized (only its values). If you enable this option, * the repeated field will be serialized as a standalone message with a collection schema. Even if the * List/Collection is empty, an empty collection message is still written. * <p/> * This is particularly useful if you rely on {@link Object#equals(Object)} on your pojos. * <p/> * Disabled by default for protobuf compatibility. */ public static final boolean COLLECTION_SCHEMA_ON_REPEATED_FIELDS; /** * If true, sun.misc.Unsafe is used to access the fields of the objects instead of plain java reflections. Enabled * by default if running on a sun jre. */ public static final boolean USE_SUN_MISC_UNSAFE; static final Method newInstanceFromObjectInputStream, newInstanceFromObjectStreamClass; static final int objectConstructorId; static final Constructor<Object> OBJECT_CONSTRUCTOR; public static final IdStrategy ID_STRATEGY; static { Constructor<Object> c = null; Class<?> reflectionFactoryClass = null; try { c = Object.class.getConstructor((Class[]) null); reflectionFactoryClass = Thread.currentThread() .getContextClassLoader() .loadClass("sun.reflect.ReflectionFactory"); } catch (Exception e) { // ignore } OBJECT_CONSTRUCTOR = c != null && reflectionFactoryClass != null ? c : null; newInstanceFromObjectInputStream = OBJECT_CONSTRUCTOR == null ? getMethodNewInstanceFromObjectInputStream() : null; if (newInstanceFromObjectInputStream != null) { newInstanceFromObjectInputStream.setAccessible(true); newInstanceFromObjectStreamClass = null; objectConstructorId = -1; } else { newInstanceFromObjectStreamClass = getMethodNewInstanceFromObjectStreamClass(); objectConstructorId = newInstanceFromObjectStreamClass == null ? -1 : getObjectConstructorIdFromObjectStreamClass(); } Properties props = OBJECT_CONSTRUCTOR == null ? new Properties() : System.getProperties(); ENUMS_BY_NAME = Boolean.parseBoolean(props.getProperty( "protostuff.runtime.enums_by_name", "false")); AUTO_LOAD_POLYMORPHIC_CLASSES = Boolean.parseBoolean(props.getProperty( "protostuff.runtime.auto_load_polymorphic_classes", "true")); MORPH_NON_FINAL_POJOS = Boolean.parseBoolean(props.getProperty( "protostuff.runtime.morph_non_final_pojos", "false")); MORPH_COLLECTION_INTERFACES = Boolean.parseBoolean(props.getProperty( "protostuff.runtime.morph_collection_interfaces", "false")); MORPH_MAP_INTERFACES = Boolean.parseBoolean(props.getProperty( "protostuff.runtime.morph_map_interfaces", "false")); COLLECTION_SCHEMA_ON_REPEATED_FIELDS = Boolean .parseBoolean(props .getProperty( "protostuff.runtime.collection_schema_on_repeated_fields", "false")); // must be on a sun jre USE_SUN_MISC_UNSAFE = OBJECT_CONSTRUCTOR != null && Boolean.parseBoolean(props.getProperty( "protostuff.runtime.use_sun_misc_unsafe", "true")); String factoryProp = props .getProperty("protostuff.runtime.id_strategy_factory"); if (factoryProp == null) ID_STRATEGY = new DefaultIdStrategy(); else { final IdStrategy.Factory factory; try { factory = ((IdStrategy.Factory) loadClass(factoryProp) .newInstance()); } catch (Exception e) { throw new RuntimeException(e); } ID_STRATEGY = factory.create(); factory.postCreate(); } } private static Method getMethodNewInstanceFromObjectInputStream() { try { return java.io.ObjectInputStream.class.getDeclaredMethod( "newInstance", Class.class, Class.class); } catch (Exception e) { return null; } } private static Method getMethodNewInstanceFromObjectStreamClass() { try { return java.io.ObjectStreamClass.class.getDeclaredMethod( "newInstance", Class.class, int.class); } catch (Exception e) { return null; } } private static int getObjectConstructorIdFromObjectStreamClass() { try { Method getConstructorId = java.io.ObjectStreamClass.class .getDeclaredMethod("getConstructorId", Class.class); getConstructorId.setAccessible(true); return ((Integer) getConstructorId.invoke(null, Object.class)) .intValue(); } catch (Exception e) { return -1; } } @SuppressWarnings("unchecked") static <T> Class<T> loadClass(String className) { try { return (Class<T>) Thread.currentThread().getContextClassLoader() .loadClass(className); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } /** * Returns an instatiator for the specified {@code clazz}. */ public static <T> Instantiator<T> newInstantiator(Class<T> clazz) { final Constructor<T> constructor = getConstructor(clazz); if (constructor == null) { // non-sun jre if (newInstanceFromObjectInputStream == null) { if (objectConstructorId == -1) throw new RuntimeException( "Could not resolve constructor for " + clazz); return new Android3Instantiator<T>(clazz); } return new Android2Instantiator<T>(clazz); } return new DefaultInstantiator<T>(constructor); } private static <T> Constructor<T> getConstructor(Class<T> clazz) { try { return clazz.getDeclaredConstructor((Class[]) null); } catch (SecurityException e) { return null; // return OBJECT_CONSTRUCTOR == null ? null : // OnDemandSunReflectionFactory.getConstructor(clazz, // OBJECT_CONSTRUCTOR); } catch (NoSuchMethodException e) { return null; // return OBJECT_CONSTRUCTOR == null ? null : // OnDemandSunReflectionFactory.getConstructor(clazz, // OBJECT_CONSTRUCTOR); } } private RuntimeEnv() { } public static abstract class Instantiator<T> { /** * Creates a new instance of an object. */ public abstract T newInstance(); } static final class DefaultInstantiator<T> extends Instantiator<T> { final Constructor<T> constructor; DefaultInstantiator(Constructor<T> constructor) { this.constructor = constructor; constructor.setAccessible(true); } public T newInstance() { try { return constructor.newInstance((Object[]) null); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } static final class Android2Instantiator<T> extends Instantiator<T> { final Class<T> clazz; Android2Instantiator(Class<T> clazz) { this.clazz = clazz; } @SuppressWarnings("unchecked") public T newInstance() { try { return (T) newInstanceFromObjectInputStream.invoke(null, clazz, Object.class); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } static final class Android3Instantiator<T> extends Instantiator<T> { final Class<T> clazz; Android3Instantiator(Class<T> clazz) { this.clazz = clazz; } @SuppressWarnings("unchecked") public T newInstance() { try { return (T) newInstanceFromObjectStreamClass.invoke(null, clazz, objectConstructorId); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } }
issue 141
protostuff-runtime-md/src/main/java/io/protostuff/runtime/RuntimeEnv.java
issue 141
<ide><path>rotostuff-runtime-md/src/main/java/io/protostuff/runtime/RuntimeEnv.java <ide> * option. <ide> */ <ide> public static final boolean AUTO_LOAD_POLYMORPHIC_CLASSES; <add> <add> /** <add> * Disabled by default. Writes a sentinel value (uint32) in place of null values. <add> * Works only on the binary formats (protostuff/graph/protobuf). <add> */ <add> public static final boolean ALLOW_NULL_ARRAY_ELEMENT; <ide> <ide> /** <ide> * Disabled by default. For pojos that are not declared final, they could still be morphed to their respective <ide> AUTO_LOAD_POLYMORPHIC_CLASSES = Boolean.parseBoolean(props.getProperty( <ide> "protostuff.runtime.auto_load_polymorphic_classes", "true")); <ide> <add> ALLOW_NULL_ARRAY_ELEMENT = Boolean.parseBoolean(props.getProperty( <add> "protostuff.runtime.allow_null_array_element", "false")); <add> <ide> MORPH_NON_FINAL_POJOS = Boolean.parseBoolean(props.getProperty( <ide> "protostuff.runtime.morph_non_final_pojos", "false")); <ide>