answer
stringlengths
17
10.2M
package com.mychess.mychess; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.os.CountDownTimer; import android.os.IBinder; import android.speech.RecognitionListener; import android.speech.RecognizerIntent; import android.speech.SpeechRecognizer; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.mychess.mychess.Chess.Chess; import com.mychess.mychess.Chess.Ubicacion; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.util.ArrayList; public class Juego extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener { Servicio mService; boolean mBound = false; ImageView casillas[][] = new ImageView[8][8]; ImageView origen; ImageView destino; TextView tiempo; Tiempo tiempoMovimiento; TextView nombreColumnas[] = new TextView[8]; TextView numeroFila[] = new TextView[8]; int cOrigen; int cDestino; int fOrigen; int fDestino; boolean enroqueBlanco = true; boolean enroqueNegro = true; boolean jugadaLocal;// sirve para difenciar entre una jugada local y una remota Chess chess; TextView nombreUsuario; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_juego); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); inicializarCasillasBlanco(); setOnclickListener(); setDefaultColor(); nombreUsuario = (TextView) findViewById(R.id.nombreUsuario); SharedPreferences preferences = getSharedPreferences("usuario",MODE_PRIVATE); nombreUsuario.setText(preferences.getString("usuario",null)); tiempo = (TextView) findViewById(R.id.textView18); tiempoMovimiento = new Tiempo(); tiempoMovimiento.iniciar(); /* inicializcion del nuevo juego*/ chess = new Chess(); chess.newGame(); new SocketServidor().conectar(); RecibirMovimientos recibirMovimientos = new RecibirMovimientos(); recibirMovimientos.execute(); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(jugadaLocal) { SpeechRecognizer speechRecognizer = SpeechRecognizer.createSpeechRecognizer(Juego.this); Speech speech = new Speech(); speechRecognizer.setRecognitionListener(speech); Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); speechRecognizer.startListening(intent); }else Toast.makeText(Juego.this, "No es su turno", Toast.LENGTH_SHORT).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, Servicio.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { Servicio.LocalBinder binder = (Servicio.LocalBinder) service; mService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName name) { mBound = false; } }; @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.juego, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.jugar) { // Handle the camera action } else if (id == R.id.amigos) { Intent intent = new Intent(Juego.this, Amigos.class); startActivity(intent); } else if (id == R.id.logout) { SharedPreferences preferences =getSharedPreferences("usuario",MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.commit(); Intent intent= new Intent(this,Acceso.class); startActivity(intent); finish(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } private void inicializarCampos(int n){ nombreColumnas[0] = (TextView) findViewById(R.id.columnaa); nombreColumnas[1] = (TextView) findViewById(R.id.columnab); nombreColumnas[2] = (TextView) findViewById(R.id.columnac); nombreColumnas[3] = (TextView) findViewById(R.id.columnad); nombreColumnas[4] = (TextView) findViewById(R.id.columnae); nombreColumnas[5] = (TextView) findViewById(R.id.columnaf); nombreColumnas[6] = (TextView) findViewById(R.id.columnag); nombreColumnas[7] = (TextView) findViewById(R.id.columnah); numeroFila[0] = (TextView) findViewById(R.id.fila1); numeroFila[1]= (TextView) findViewById(R.id.fila2); numeroFila[2]= (TextView) findViewById(R.id.fila3); numeroFila[3]= (TextView) findViewById(R.id.fila4); numeroFila[4]= (TextView) findViewById(R.id.fila5); numeroFila[5]= (TextView) findViewById(R.id.fila6); numeroFila[6]= (TextView) findViewById(R.id.fila7); numeroFila[7]= (TextView) findViewById(R.id.fila8); nombreColumnas[0].setText("a"); nombreColumnas[1].setText("b"); nombreColumnas[2].setText("c"); nombreColumnas[3].setText("d"); nombreColumnas[4].setText("e"); nombreColumnas[5].setText("f"); nombreColumnas[6].setText("g"); nombreColumnas[7].setText("h"); numeroFila[0].setText("1"); numeroFila[1].setText("2"); numeroFila[2].setText("3"); numeroFila[3].setText("4"); numeroFila[4].setText("5"); numeroFila[5].setText("6"); numeroFila[6].setText("7"); numeroFila[7].setText("8"); if(n == 2) { nombreColumnas[0].setText("h"); nombreColumnas[1].setText("g"); nombreColumnas[2].setText("f"); nombreColumnas[3].setText("e"); nombreColumnas[4].setText("d"); nombreColumnas[5].setText("c"); nombreColumnas[6].setText("b"); nombreColumnas[7].setText("a"); numeroFila[0].setText("8"); numeroFila[1].setText("7"); numeroFila[2].setText("6"); numeroFila[3].setText("5"); numeroFila[4].setText("4"); numeroFila[5].setText("3"); numeroFila[6].setText("2"); numeroFila[7].setText("1"); } } private void inicializarCasillasBlanco() { casillas[0][0] = (ImageView) findViewById(R.id.a8); casillas[0][1] = (ImageView) findViewById(R.id.a7); casillas[0][2] = (ImageView) findViewById(R.id.a6); casillas[0][3] = (ImageView) findViewById(R.id.a5); casillas[0][4] = (ImageView) findViewById(R.id.a4); casillas[0][5] = (ImageView) findViewById(R.id.a3); casillas[0][6] = (ImageView) findViewById(R.id.a2); casillas[0][7] = (ImageView) findViewById(R.id.a1); casillas[1][0] = (ImageView) findViewById(R.id.b8); casillas[1][1] = (ImageView) findViewById(R.id.b7); casillas[1][2] = (ImageView) findViewById(R.id.b6); casillas[1][3] = (ImageView) findViewById(R.id.b5); casillas[1][4] = (ImageView) findViewById(R.id.b4); casillas[1][5] = (ImageView) findViewById(R.id.b3); casillas[1][6] = (ImageView) findViewById(R.id.b2); casillas[1][7] = (ImageView) findViewById(R.id.b1); casillas[2][0] = (ImageView) findViewById(R.id.c8); casillas[2][1] = (ImageView) findViewById(R.id.c7); casillas[2][2] = (ImageView) findViewById(R.id.c6); casillas[2][3] = (ImageView) findViewById(R.id.c5); casillas[2][4] = (ImageView) findViewById(R.id.c4); casillas[2][5] = (ImageView) findViewById(R.id.c3); casillas[2][6] = (ImageView) findViewById(R.id.c2); casillas[2][7] = (ImageView) findViewById(R.id.c1); casillas[3][0] = (ImageView) findViewById(R.id.d8); casillas[3][1] = (ImageView) findViewById(R.id.d7); casillas[3][2] = (ImageView) findViewById(R.id.d6); casillas[3][3] = (ImageView) findViewById(R.id.d5); casillas[3][4] = (ImageView) findViewById(R.id.d4); casillas[3][5] = (ImageView) findViewById(R.id.d3); casillas[3][6] = (ImageView) findViewById(R.id.d2); casillas[3][7] = (ImageView) findViewById(R.id.d1); casillas[4][0] = (ImageView) findViewById(R.id.e8); casillas[4][1] = (ImageView) findViewById(R.id.e7); casillas[4][2] = (ImageView) findViewById(R.id.e6); casillas[4][3] = (ImageView) findViewById(R.id.e5); casillas[4][4] = (ImageView) findViewById(R.id.e4); casillas[4][5] = (ImageView) findViewById(R.id.e3); casillas[4][6] = (ImageView) findViewById(R.id.e2); casillas[4][7] = (ImageView) findViewById(R.id.e1); casillas[5][0] = (ImageView) findViewById(R.id.f8); casillas[5][1] = (ImageView) findViewById(R.id.f7); casillas[5][2] = (ImageView) findViewById(R.id.f6); casillas[5][3] = (ImageView) findViewById(R.id.f5); casillas[5][4] = (ImageView) findViewById(R.id.f4); casillas[5][5] = (ImageView) findViewById(R.id.f3); casillas[5][6] = (ImageView) findViewById(R.id.f2); casillas[5][7] = (ImageView) findViewById(R.id.f1); casillas[6][0] = (ImageView) findViewById(R.id.g8); casillas[6][1] = (ImageView) findViewById(R.id.g7); casillas[6][2] = (ImageView) findViewById(R.id.g6); casillas[6][3] = (ImageView) findViewById(R.id.g5); casillas[6][4] = (ImageView) findViewById(R.id.g4); casillas[6][5] = (ImageView) findViewById(R.id.g3); casillas[6][6] = (ImageView) findViewById(R.id.g2); casillas[6][7] = (ImageView) findViewById(R.id.g1); casillas[7][0] = (ImageView) findViewById(R.id.h8); casillas[7][1] = (ImageView) findViewById(R.id.h7); casillas[7][2] = (ImageView) findViewById(R.id.h6); casillas[7][3] = (ImageView) findViewById(R.id.h5); casillas[7][4] = (ImageView) findViewById(R.id.h4); casillas[7][5] = (ImageView) findViewById(R.id.h3); casillas[7][6] = (ImageView) findViewById(R.id.h2); casillas[7][7] = (ImageView) findViewById(R.id.h1); colocarPiezas(1); inicializarCampos(1); jugadaLocal = true; } private void inicializarCasillasNegro() { casillas[0][0] = (ImageView) findViewById(R.id.h1); casillas[0][1] = (ImageView) findViewById(R.id.h2); casillas[0][2] = (ImageView) findViewById(R.id.h3); casillas[0][3] = (ImageView) findViewById(R.id.h4); casillas[0][4] = (ImageView) findViewById(R.id.h5); casillas[0][5] = (ImageView) findViewById(R.id.h6); casillas[0][6] = (ImageView) findViewById(R.id.h7); casillas[0][7] = (ImageView) findViewById(R.id.h8); casillas[1][0] = (ImageView) findViewById(R.id.g1); casillas[1][1] = (ImageView) findViewById(R.id.g2); casillas[1][2] = (ImageView) findViewById(R.id.g3); casillas[1][3] = (ImageView) findViewById(R.id.g4); casillas[1][4] = (ImageView) findViewById(R.id.g5); casillas[1][5] = (ImageView) findViewById(R.id.g6); casillas[1][6] = (ImageView) findViewById(R.id.g7); casillas[1][7] = (ImageView) findViewById(R.id.g8); casillas[2][0] = (ImageView) findViewById(R.id.f1); casillas[2][1] = (ImageView) findViewById(R.id.f2); casillas[2][2] = (ImageView) findViewById(R.id.f3); casillas[2][3] = (ImageView) findViewById(R.id.f4); casillas[2][4] = (ImageView) findViewById(R.id.f5); casillas[2][5] = (ImageView) findViewById(R.id.f6); casillas[2][6] = (ImageView) findViewById(R.id.f7); casillas[2][7] = (ImageView) findViewById(R.id.f8); casillas[3][0] = (ImageView) findViewById(R.id.e1); casillas[3][1] = (ImageView) findViewById(R.id.e2); casillas[3][2] = (ImageView) findViewById(R.id.e3); casillas[3][3] = (ImageView) findViewById(R.id.e4); casillas[3][4] = (ImageView) findViewById(R.id.e5); casillas[3][5] = (ImageView) findViewById(R.id.e6); casillas[3][6] = (ImageView) findViewById(R.id.e7); casillas[3][7] = (ImageView) findViewById(R.id.e8); casillas[4][0] = (ImageView) findViewById(R.id.d1); casillas[4][1] = (ImageView) findViewById(R.id.d2); casillas[4][2] = (ImageView) findViewById(R.id.d3); casillas[4][3] = (ImageView) findViewById(R.id.d4); casillas[4][4] = (ImageView) findViewById(R.id.d5); casillas[4][5] = (ImageView) findViewById(R.id.d6); casillas[4][6] = (ImageView) findViewById(R.id.d7); casillas[4][7] = (ImageView) findViewById(R.id.d8); casillas[5][0] = (ImageView) findViewById(R.id.c1); casillas[5][1] = (ImageView) findViewById(R.id.c2); casillas[5][2] = (ImageView) findViewById(R.id.c3); casillas[5][3] = (ImageView) findViewById(R.id.c4); casillas[5][4] = (ImageView) findViewById(R.id.c5); casillas[5][5] = (ImageView) findViewById(R.id.c6); casillas[5][6] = (ImageView) findViewById(R.id.c7); casillas[5][7] = (ImageView) findViewById(R.id.c8); casillas[6][0] = (ImageView) findViewById(R.id.b1); casillas[6][1] = (ImageView) findViewById(R.id.b2); casillas[6][2] = (ImageView) findViewById(R.id.b3); casillas[6][3] = (ImageView) findViewById(R.id.b4); casillas[6][4] = (ImageView) findViewById(R.id.b5); casillas[6][5] = (ImageView) findViewById(R.id.b6); casillas[6][6] = (ImageView) findViewById(R.id.b7); casillas[6][7] = (ImageView) findViewById(R.id.b8); casillas[7][0] = (ImageView) findViewById(R.id.a1); casillas[7][1] = (ImageView) findViewById(R.id.a2); casillas[7][2] = (ImageView) findViewById(R.id.a3); casillas[7][3] = (ImageView) findViewById(R.id.a4); casillas[7][4] = (ImageView) findViewById(R.id.a5); casillas[7][5] = (ImageView) findViewById(R.id.a6); casillas[7][6] = (ImageView) findViewById(R.id.a7); casillas[7][7] = (ImageView) findViewById(R.id.a8); colocarPiezas(1); inicializarCampos(2); jugadaLocal = false; } private void setDefaultColor() { boolean dark = true; for (int i = 0; i < 8; ++i) { for (int j = 0; j < 8; ++j) { if (dark) casillas[i][j].setBackgroundResource(R.color.casillablanca); else casillas[i][j].setBackgroundResource(R.color.casillnegra); dark = !dark; } dark = !dark; } } private void colocarPiezas(int bando){ casillas[0][7].setImageResource(bando == 1?R.mipmap.alpha_wr:R.mipmap.alpha_br); casillas[7][7].setImageResource(bando == 1?R.mipmap.alpha_wr:R.mipmap.alpha_br); casillas[0][6].setImageResource(bando == 1 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp); casillas[1][6].setImageResource(bando == 1 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp); casillas[2][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp); casillas[3][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp); casillas[4][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp); casillas[5][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp); casillas[6][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp); casillas[7][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp); casillas[1][7].setImageResource(bando == 1?R.mipmap.alpha_wn:R.mipmap.alpha_bn); casillas[6][7].setImageResource(bando == 1?R.mipmap.alpha_wn:R.mipmap.alpha_bn); casillas[2][7].setImageResource(bando == 1?R.mipmap.alpha_wb:R.mipmap.alpha_bb); casillas[5][7].setImageResource(bando == 1?R.mipmap.alpha_wb:R.mipmap.alpha_bb); casillas[3][7].setImageResource(bando == 1?R.mipmap.alpha_wq:R.mipmap.alpha_bq); casillas[4][7].setImageResource(bando == 1?R.mipmap.alpha_wk:R.mipmap.alpha_bk); casillas[7][0].setImageResource(bando == 2 ? R.mipmap.alpha_wr : R.mipmap.alpha_br); casillas[0][0].setImageResource(bando == 2 ? R.mipmap.alpha_wr : R.mipmap.alpha_br); casillas[0][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp); casillas[1][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp); casillas[2][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp); casillas[3][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp); casillas[4][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp); casillas[5][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp); casillas[6][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp); casillas[7][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp); casillas[1][0].setImageResource(bando == 2 ? R.mipmap.alpha_wn : R.mipmap.alpha_bn); casillas[6][0].setImageResource(bando == 2 ? R.mipmap.alpha_wn : R.mipmap.alpha_bn); casillas[2][0].setImageResource(bando == 2 ? R.mipmap.alpha_wb : R.mipmap.alpha_bb); casillas[5][0].setImageResource(bando == 2 ? R.mipmap.alpha_wb : R.mipmap.alpha_bb); casillas[3][0].setImageResource(bando == 2 ? R.mipmap.alpha_wq : R.mipmap.alpha_bq); casillas[4][0].setImageResource(bando == 2 ? R.mipmap.alpha_wk : R.mipmap.alpha_bk); } private void setOnclickListener() { for (int i = 0; i < 8; ++i) { for (int j = 0; j < 8; ++j) { casillas[i][j].setOnClickListener(this); } } } private int[] getPosition(int id) { int position[] = {-1, -1}; for (int i = 0; i < 8; ++i) { for (int j = 0; j < 8; ++j) { if (id == casillas[i][j].getId()) { position[0] = i; position[1] = j; return position;//si el click fue en una casilla se retorna la posicion } } } return position;//si el click no fue en una casilla se devuelven valores negativos en la posicion } private boolean validarCoordenadas(String coordenadas) { final String columnas = "abcdefgh"; final String filas = "87654321"; cOrigen = columnas.indexOf(coordenadas.charAt(0)); cDestino = columnas.indexOf(coordenadas.charAt(2)); fOrigen = filas.indexOf(coordenadas.charAt(1)); fDestino = filas.indexOf(coordenadas.charAt(3)); if(cOrigen == -1 || cDestino == -1 || fOrigen == -1 || fDestino == -1) return false; return true; } private void procesarResultados(ArrayList<String> listaCoordenadas) { String coordenadas; for (int i = 0; i < listaCoordenadas.size(); ++i) { coordenadas = listaCoordenadas.get(i).replace(" ", "").toLowerCase(); if (coordenadas.length() == 4) { if (validarCoordenadas(coordenadas)) { validarMovimiento(coordenadas); break; } } } } private void enviarMovimiento(String coordendas) { DataOutputStream out = null; try { out = new DataOutputStream(SocketServidor.getSocket().getOutputStream()); out.writeUTF(coordendas); tiempoMovimiento.reiniciar(); } catch (IOException e) { e.printStackTrace(); } } private void validarMovimiento(String coordenadas){ switch (chess.mover(coordenadas.substring(0,2),coordenadas.substring(2,4))) { case 2: Toast.makeText(Juego.this, "movimiento no valido", Toast.LENGTH_SHORT).show(); break; case 3: moverPieza(1,coordenadas); break; case 4: Toast.makeText(Juego.this, "movimiento no valido", Toast.LENGTH_SHORT).show(); break; case 0: moverPieza(2,coordenadas); break; } } private void moverPieza(int n,String coordenada){ if(jugadaLocal){ enviarMovimiento(crearCoordenada()); if(!enroque()) { casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable()); casillas[cOrigen][fOrigen].setImageDrawable(null); } }else{ validarCoordenadas(coordenada); if(!enroque()) { casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable()); casillas[cOrigen][fOrigen].setImageDrawable(null); } } jugadaLocal = !jugadaLocal; if(n == 1){ Toast.makeText(Juego.this, "Jaque Mate", Toast.LENGTH_SHORT).show(); } } private boolean enroque(){ if(enroqueBlanco) if(cOrigen == 4 && fOrigen == 7 && cDestino == 6 && fDestino == 7) { casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable()); casillas[cOrigen][fOrigen].setImageDrawable(null); casillas[5][7].setImageDrawable(casillas[7][7].getDrawable()); casillas[7][7].setImageDrawable(null); enroqueBlanco = !enroqueBlanco; return true; }else if(cOrigen == 4 && fOrigen == 7 && cDestino == 2 && fDestino == 7) { casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable()); casillas[cOrigen][fOrigen].setImageDrawable(null); casillas[3][7].setImageDrawable(casillas[0][7].getDrawable()); casillas[0][7].setImageDrawable(null); enroqueBlanco = !enroqueBlanco; return true; } if(enroqueNegro) if(cOrigen == 4 && fOrigen == 0 && cDestino == 6 && fDestino == 0) { casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable()); casillas[cOrigen][fOrigen].setImageDrawable(null); casillas[5][0].setImageDrawable(casillas[7][0].getDrawable()); casillas[7][0].setImageDrawable(null); enroqueNegro = !enroqueNegro; return true; }else if(cOrigen == 4 && fOrigen == 0 && cDestino == 2 && fDestino == 0) { casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable()); casillas[cOrigen][fOrigen].setImageDrawable(null); casillas[3][0].setImageDrawable(casillas[0][0].getDrawable()); casillas[0][0].setImageDrawable(null); enroqueNegro = !enroqueNegro; return true; } return false; } private String crearCoordenada() { String coordenada = ""; final String columnas = "abcdefgh"; final String filas = "87654321"; coordenada += columnas.charAt(cOrigen); coordenada += filas.charAt(fOrigen); coordenada += columnas.charAt(cDestino); coordenada += filas.charAt(fDestino); return coordenada; } @Override public void onClick(View v) { if(true) { int position[] = getPosition(v.getId()); if (position[0] != -1) {//si el valor es negativo indica que el click no se realizo en una casilla if (origen == null) { origen = casillas[position[0]][position[1]]; cOrigen = position[0]; fOrigen = position[1]; casillas[cOrigen][fOrigen].setBackgroundResource(R.color.origen); for(Ubicacion u:chess.mostrarMovimientos(fOrigen,cOrigen)) { casillas[u.getCol()][u.getFila()].setBackgroundResource(R.drawable.seleccion); } } else { cDestino = position[0]; fDestino = position[1]; destino = casillas[cDestino][fDestino]; if(!(destino == origen)) { validarMovimiento(crearCoordenada()); setDefaultColor(); }else setDefaultColor(); origen = null; } } }else{ Toast.makeText(Juego.this, "No es su turno", Toast.LENGTH_SHORT).show(); } } class Speech implements RecognitionListener { @Override public void onReadyForSpeech(Bundle params) { } @Override public void onBeginningOfSpeech() { } @Override public void onRmsChanged(float rmsdB) { } @Override public void onBufferReceived(byte[] buffer) { } @Override public void onEndOfSpeech() { } @Override public void onError(int error) { } @Override public void onResults(Bundle results) { ArrayList<String> listaPalabras = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); procesarResultados(listaPalabras); } @Override public void onPartialResults(Bundle partialResults) { } @Override public void onEvent(int eventType, Bundle params) { } } class Tiempo { CountDown countDown; public void iniciar() { countDown = new CountDown(60000, 1000); countDown.start(); } public void detener() { countDown.cancel(); } public void reiniciar() { tiempo.setText("60"); tiempo.setTextColor(Color.WHITE); countDown.cancel(); } class CountDown extends CountDownTimer { public CountDown(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); } @Override public void onTick(long millisUntilFinished) { long time = millisUntilFinished / 1000; tiempo.setText(String.valueOf(time)); if (time == 15) tiempo.setTextColor(Color.RED); } @Override public void onFinish() { } } } class RecibirMovimientos extends AsyncTask<Void, String, Boolean> { Socket socket; protected Boolean doInBackground(Void... params) { socket = SocketServidor.getSocket(); boolean continuar = true; while (continuar) { try { Thread.sleep(250); InputStream fromServer = SocketServidor.getSocket().getInputStream(); DataInputStream in = new DataInputStream(fromServer); publishProgress(in.readUTF()); } catch (Exception ex) { } } return null; } @Override protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); validarMovimiento(values[0]); Toast.makeText(Juego.this, values[0], Toast.LENGTH_SHORT).show(); tiempoMovimiento.iniciar(); } } }
package org.xbill.DNS; import java.io.*; import java.util.*; import org.xbill.DNS.utils.*; /** * Text - stores text strings * * @author Brian Wellington */ public class TXTRecord extends Record { private static TXTRecord member = new TXTRecord(); private List strings; private TXTRecord() {} private TXTRecord(Name name, short dclass, int ttl) { super(name, Type.TXT, dclass, ttl); } static TXTRecord getMember() { return member; } /** * Creates a TXT Record from the given data * @param strings The text strings */ public TXTRecord(Name name, short dclass, int ttl, List strings) { this(name, dclass, ttl); if (strings == null) throw new IllegalArgumentException ("TXTRecord: strings must not be null"); this.strings = strings; } /** * Creates a TXT Record from the given data * @param strings One text string */ public TXTRecord(Name name, short dclass, int ttl, String string) { this(name, dclass, ttl); this.strings = new ArrayList(); this.strings.add(string); } Record rrFromWire(Name name, short type, short dclass, int ttl, int length, DataByteInputStream in) throws IOException { TXTRecord rec = new TXTRecord(name, dclass, ttl); if (in == null) return rec; int count = 0; rec.strings = new ArrayList(); while (count < length) { int len = in.readByte(); byte [] b = new byte[len]; in.read(b); count += (len + 1); rec.strings.add(new String(b)); } return rec; } Record rdataFromString(Name name, short dclass, int ttl, MyStringTokenizer st, Name origin) throws TextParseException { TXTRecord rec = new TXTRecord(name, dclass, ttl); rec.strings = new ArrayList(); while (st.hasMoreTokens()) rec.strings.add(st.nextToken()); return rec; } /** converts to a String */ public String rdataToString() { StringBuffer sb = new StringBuffer(); if (strings != null) { Iterator it = strings.iterator(); while (it.hasNext()) { String s = (String) it.next(); sb.append("\""); sb.append(s); sb.append("\""); if (it.hasNext()) sb.append(" "); } } return sb.toString(); } /** Returns the text strings */ public List getStrings() { return strings; } void rrToWire(DataByteOutputStream out, Compression c) throws IOException { if (strings == null) return; Iterator it = strings.iterator(); while (it.hasNext()) { String s = (String) it.next(); out.writeString(s); } } }
package org.geomajas.gwt.client.controller; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.DoubleClickEvent; import com.google.gwt.event.dom.client.MouseEvent; import com.google.gwt.event.dom.client.MouseMoveEvent; import com.google.gwt.event.dom.client.MouseUpEvent; import com.google.gwt.i18n.client.NumberFormat; import com.smartgwt.client.widgets.Canvas; import com.smartgwt.client.widgets.Label; import com.smartgwt.client.widgets.layout.VLayout; import com.smartgwt.client.widgets.menu.Menu; import com.smartgwt.client.widgets.menu.MenuItem; import com.smartgwt.client.widgets.menu.MenuItemIfFunction; import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent; import org.geomajas.geometry.Coordinate; import org.geomajas.geometry.service.GeometryService; import org.geomajas.gwt.client.action.MenuAction; import org.geomajas.gwt.client.action.menu.ToggleSnappingAction; import org.geomajas.gwt.client.gfx.paintable.GfxGeometry; import org.geomajas.gwt.client.gfx.style.ShapeStyle; import org.geomajas.gwt.client.i18n.I18nProvider; import org.geomajas.gwt.client.map.layer.Layer; import org.geomajas.gwt.client.map.layer.VectorLayer; import org.geomajas.gwt.client.spatial.geometry.Geometry; import org.geomajas.gwt.client.spatial.geometry.GeometryFactory; import org.geomajas.gwt.client.spatial.geometry.operation.InsertCoordinateOperation; import org.geomajas.gwt.client.util.DistanceFormat; import org.geomajas.gwt.client.util.GeometryConverter; import org.geomajas.gwt.client.util.WidgetLayout; import org.geomajas.gwt.client.widget.MapWidget; import org.geomajas.gwt.client.widget.MapWidget.RenderGroup; import org.geomajas.gwt.client.widget.MapWidget.RenderStatus; /** * <p> * Controller that measures distances on the map, by clicking points. The actual distances are displayed in a label at * the top left of the map. * </p> * * @author Pieter De Graef * @author Oliver May */ public class MeasureDistanceController extends AbstractSnappingController { private static final ShapeStyle LINE_STYLE_1 = new ShapeStyle("#FFFFFF", 0, "#FF9900", 1, 2); private static final ShapeStyle LINE_STYLE_2 = new ShapeStyle("#FFFFFF", 0, "#FF5500", 1, 2); private boolean showArea; private boolean showCoordinate; private GfxGeometry distanceLine; private GfxGeometry lineSegment; private VLayout panel; private DistanceLabel label; private DistanceLabel areaLabel; private DistanceLabel coordinateLabel; private GeometryFactory factory; private float tempLength; private Menu menu; private GeometryFactory geometryFactory; // Constructor: /** * Construct a measureDistanceController. Default is to display the total distance and last line distance. * * @param mapWidget the mapwidget where the distance is measured on. */ public MeasureDistanceController(MapWidget mapWidget) { this(mapWidget, false, false); } /** * Construct a measureDistanceController. * * @param mapWidget the mapwidget where the distance is measured on. * @param showArea true if the area should be displayed * @param displayCoordinates the if the coordinates should be displayed. */ public MeasureDistanceController(MapWidget mapWidget, boolean showArea, boolean displayCoordinates) { super(mapWidget); distanceLine = new GfxGeometry("measureDistanceLine"); distanceLine.setStyle(LINE_STYLE_1); lineSegment = new GfxGeometry("measureDistanceLineSegment"); lineSegment.setStyle(LINE_STYLE_2); this.showArea = showArea; this.showCoordinate = displayCoordinates; geometryFactory = new GeometryFactory(mapWidget.getMapModel().getPrecision(), mapWidget.getMapModel().getSrid()); } // GraphicsController interface: /** Create the context menu for this controller. */ public void onActivate() { menu = new Menu(); menu.addItem(new CancelMeasuringAction(this)); Layer selectedLayer = mapWidget.getMapModel().getSelectedLayer(); if (selectedLayer instanceof VectorLayer) { menu.addItem(new ToggleSnappingAction((VectorLayer) selectedLayer, this)); } mapWidget.setContextMenu(menu); } /** Clean everything up. */ public void onDeactivate() { onDoubleClick(null); menu.destroy(); menu = null; mapWidget.setContextMenu(null); mapWidget.unregisterWorldPaintable(distanceLine); mapWidget.unregisterWorldPaintable(lineSegment); } /** Set a new point on the distance-line. */ public void onMouseUp(MouseUpEvent event) { if (event.getNativeButton() != NativeEvent.BUTTON_RIGHT) { Coordinate coordinate = getWorldPosition(event); if (distanceLine.getOriginalLocation() == null) { distanceLine.setGeometry(getFactory().createLineString(new Coordinate[]{coordinate})); mapWidget.registerWorldPaintable(distanceLine); mapWidget.registerWorldPaintable(lineSegment); showPanel(); } else { Geometry geometry = (Geometry) distanceLine.getOriginalLocation(); InsertCoordinateOperation op = new InsertCoordinateOperation(geometry.getNumPoints(), coordinate); geometry = op.execute(geometry); distanceLine.setGeometry(geometry); tempLength = (float) geometry.getLength(); updateMeasure(event, true); } mapWidget.render(mapWidget.getMapModel(), RenderGroup.VECTOR, RenderStatus.UPDATE); } } /** Update the drawing while moving the mouse. */ public void onMouseMove(MouseMoveEvent event) { if (isMeasuring() && distanceLine.getOriginalLocation() != null) { updateMeasure(event, false); } } private void showPanel() { panel = new VLayout(); panel.setParentElement(mapWidget); // panel.setValign(VerticalAlignment.TOP); panel.setShowEdges(true); panel.setWidth(120); panel.setPadding(3); panel.setLeft(mapWidget.getWidth() - 130); panel.setTop(-80); panel.setBackgroundColor("#FFFFFF"); panel.setAnimateTime(500); label = new DistanceLabel(); areaLabel = new DistanceLabel(); coordinateLabel = new DistanceLabel(); panel.addMember(label); if (showArea) { panel.addMember(areaLabel); } if (showCoordinate) { panel.addMember(coordinateLabel); } panel.animateMove(mapWidget.getWidth() - 130, 10); } private void updateMeasure(MouseEvent event, boolean complete) { Geometry geometry = (Geometry) distanceLine.getOriginalLocation(); Coordinate coordinate1 = geometry.getCoordinates()[distanceLine.getGeometry().getNumPoints() - 1]; Coordinate coordinate2 = getWorldPosition(event); lineSegment.setGeometry(getFactory().createLineString(new Coordinate[] { coordinate1, coordinate2 })); mapWidget.render(mapWidget.getMapModel(), RenderGroup.VECTOR, RenderStatus.UPDATE); label.setDistance(tempLength, (float) ((Geometry) lineSegment.getOriginalLocation()).getLength()); if (showArea && complete) { double area = GeometryService.getArea(GeometryConverter.toDto(geometryFactory. createLinearRing(geometry.getCoordinates()))); areaLabel.setArea(DistanceFormat.asMapArea(mapWidget, area)); } if (showCoordinate && complete) { coordinateLabel.setCoordinate(coordinate2.getX(), coordinate2.getY()); } } /** Stop the measuring, and remove all graphics from the map. */ public void onDoubleClick(DoubleClickEvent event) { tempLength = 0; mapWidget.unregisterWorldPaintable(distanceLine); mapWidget.unregisterWorldPaintable(lineSegment); distanceLine.setGeometry(null); lineSegment.setGeometry(null); if (panel != null) { panel.destroy(); } } // Private methods: private boolean isMeasuring() { return distanceLine.getGeometry() != null; } /** * The factory can only be used after the MapModel has initialized, that is why this getter exists... * * @return geometry factory */ private GeometryFactory getFactory() { if (factory == null) { factory = mapWidget.getMapModel().getGeometryFactory(); } return factory; } // Private classes: /** * The label that shows the distances. * * @author Pieter De Graef */ private class DistanceLabel extends Label { public DistanceLabel() { super(); setPadding(3); setAutoHeight(); } public void setDistance(float totalDistance, float radius) { String total = DistanceFormat.asMapLength(mapWidget, totalDistance); String r = DistanceFormat.asMapLength(mapWidget, radius); String dist = I18nProvider.getMenu().getMeasureDistanceString(total, r); setContents("<div><b>" + I18nProvider.getMenu().distance() + "</b>:</div><div style='margin-top:5px;'>" + dist + "</div>"); } public void setArea(String area) { String areaString = I18nProvider.getMenu().getMeasureAreaString(area); setContents("<div><b>" + I18nProvider.getMenu().area() + "</b>:</div><div style='margin-top:5px;'>" + areaString + "</div>"); } public void setCoordinate(double x, double y) { String coordinate = I18nProvider.getMenu().getMeasureCoordinateString(NumberFormat.getFormat(". format(x), NumberFormat.getFormat(".##").format(y)); setContents("<div><b>" + I18nProvider.getMenu().coordinate() + "</b>:</div><div style='margin-top:5px;'>" + coordinate + "</div>"); } } /** * Menu item that stop the measuring * * @author Pieter De Graef */ private class CancelMeasuringAction extends MenuAction { private final MeasureDistanceController controller; public CancelMeasuringAction(final MeasureDistanceController controller) { super(I18nProvider.getMenu().cancelMeasuring(), WidgetLayout.iconQuit); this.controller = controller; setEnableIfCondition(new MenuItemIfFunction() { public boolean execute(Canvas target, Menu menu, MenuItem item) { return controller.isMeasuring(); } }); } public void onClick(MenuItemClickEvent event) { controller.onDoubleClick(null); } } }
package com.linkedin.clustermanager.tools; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import com.linkedin.clustermanager.ClusterDataAccessor.InstanceConfigProperty; import com.linkedin.clustermanager.ClusterManagementService; import com.linkedin.clustermanager.ClusterManagerException; import com.linkedin.clustermanager.ZNRecord; import com.linkedin.clustermanager.agent.zk.ZKClusterManagementTool; import com.linkedin.clustermanager.agent.zk.ZNRecordSerializer; import com.linkedin.clustermanager.agent.zk.ZkClient; import com.linkedin.clustermanager.model.StateModelDefinition; import com.linkedin.clustermanager.util.CMUtil; import com.linkedin.clustermanager.util.ZKClientPool; public class ClusterSetup { public static final String zkServerAddress = "zkSvr"; // List info about the cluster / DB/ Instances public static final String listClusters = "listClusters"; public static final String listResourceGroups = "listResourceGroups"; public static final String listInstances = "listInstances"; // Add and rebalance public static final String addCluster = "addCluster"; public static final String addInstance = "addNode"; public static final String addResourceGroup = "addResourceGroup"; public static final String addStateModelDef = "addStateModelDef"; public static final String addIdealState = "addIdealState"; public static final String rebalance = "rebalance"; // Query info (TBD in V2) public static final String listClusterInfo = "listClusterInfo"; public static final String listInstanceInfo = "listInstanceInfo"; public static final String listResourceGroupInfo = "listResourceGroupInfo"; public static final String listResourceInfo = "listResourceInfo"; public static final String listStateModels = "listStateModels"; public static final String listStateModel = "listStateModel"; // TODO: refactor // setup for file-based cluster manager // public static final String configFile = "configFile"; // enable / disable Instances public static final String enableInstance = "enableInstance"; public static final String help = "help"; static Logger _logger = Logger.getLogger(ClusterSetup.class); String _zkServerAddress; public ClusterSetup(String zkServerAddress) { _zkServerAddress = zkServerAddress; } public void addCluster(String clusterName, boolean overwritePrevious) { ClusterManagementService managementTool = getClusterManagementTool(); managementTool.addCluster(clusterName, overwritePrevious); StateModelConfigGenerator generator = new StateModelConfigGenerator(); addStateModelDef(clusterName, "MasterSlave", generator.generateConfigForMasterSlave()); } public void addCluster(String clusterName, boolean overwritePrevious, String stateModDefName, ZNRecord stateModDef) { ClusterManagementService managementTool = getClusterManagementTool(); managementTool.addCluster(clusterName, overwritePrevious); addStateModelDef(clusterName, stateModDefName, stateModDef); } public void addInstancesToCluster(String clusterName, String[] InstanceInfoArray) { for (String InstanceInfo : InstanceInfoArray) { // the storage Instance info must be hostname:port format. if (InstanceInfo.length() > 0) { addInstanceToCluster(clusterName, InstanceInfo); } } } public void addInstanceToCluster(String clusterName, String InstanceAddress) { // InstanceAddress must be in host:port format int lastPos = InstanceAddress.lastIndexOf(":"); if (lastPos <= 0) { String error = "Invalid storage Instance info format: " + InstanceAddress; _logger.warn(error); throw new ClusterManagerException(error); } String host = InstanceAddress.substring(0, lastPos); String portStr = InstanceAddress.substring(lastPos + 1); int port = Integer.parseInt(portStr); addInstanceToCluster(clusterName, host, port); } public void addInstanceToCluster(String clusterName, String host, int port) { ClusterManagementService managementTool = getClusterManagementTool(); ZNRecord InstanceConfig = new ZNRecord(); String InstanceId = host + "_" + port; InstanceConfig.setId(InstanceId); InstanceConfig.setSimpleField(InstanceConfigProperty.HOST.toString(), host); InstanceConfig .setSimpleField(InstanceConfigProperty.PORT.toString(), "" + port); InstanceConfig.setSimpleField(InstanceConfigProperty.ENABLED.toString(), true + ""); managementTool.addInstance(clusterName, InstanceConfig); } public ClusterManagementService getClusterManagementTool() { ZkClient zkClient = ZKClientPool.getZkClient(_zkServerAddress); return new ZKClusterManagementTool(zkClient); } public void addStateModelDef(String clusterName, String stateModelDef, ZNRecord record) { ClusterManagementService managementTool = getClusterManagementTool(); managementTool.addStateModelDef(clusterName, stateModelDef, record); } public void addResourceGroupToCluster(String clusterName, String resourceGroup, int numResources, String stateModelRef) { ClusterManagementService managementTool = getClusterManagementTool(); managementTool.addResourceGroup(clusterName, resourceGroup, numResources, stateModelRef); } public void dropResourceGroupToCluster(String clusterName, String resourceGroup) { ClusterManagementService managementTool = getClusterManagementTool(); managementTool.dropResourceGroup(clusterName, resourceGroup); } public void rebalanceStorageCluster(String clusterName, String resourceGroupName, int replica) { ClusterManagementService managementTool = getClusterManagementTool(); List<String> InstanceNames = managementTool.getInstancesInCluster(clusterName); ZNRecord dbIdealState = managementTool.getResourceGroupIdealState( clusterName, resourceGroupName); int partitions = Integer .parseInt(dbIdealState.getSimpleField("partitions")); String masterStateValue = "MASTER"; String slaveStateValue = "SLAVE"; ZkClient zkClient = ZKClientPool.getZkClient(_zkServerAddress); String idealStatePath = CMUtil.getIdealStatePath(clusterName, resourceGroupName); ZNRecord idealState = zkClient.<ZNRecord>readData(idealStatePath); String stateModelName = idealState.getSimpleField("state_model_def_ref"); ZNRecord stateModDef = managementTool.getStateModelDef(clusterName, stateModelName); if (stateModDef != null) { StateModelDefinition def = new StateModelDefinition(stateModDef); String value = def.getMasterStateValue(); if ( value != null) masterStateValue = value; value = def.getSlaveStateValue(); if ( value != null) slaveStateValue = value; } idealState = IdealStateCalculatorForStorageNode .calculateIdealState(InstanceNames, partitions, replica, resourceGroupName, masterStateValue, slaveStateValue); idealState.merge(dbIdealState); managementTool.setResourceGroupIdealState(clusterName, resourceGroupName, idealState); } /** * Sets up a cluster with 6 Instances[localhost:8900 to localhost:8905], 1 * resourceGroup[EspressoDB] with a replication factor of 3 * * @param clusterName */ public void setupTestCluster(String clusterName) { addCluster(clusterName, true); String storageInstanceInfoArray[] = new String[6]; for (int i = 0; i < storageInstanceInfoArray.length; i++) { storageInstanceInfoArray[i] = "localhost:" + (8900 + i); } addInstancesToCluster(clusterName, storageInstanceInfoArray); addResourceGroupToCluster(clusterName, "TestDB", 10, "MasterSlave"); rebalanceStorageCluster(clusterName, "TestDB", 3); } public static void printUsage(Options cliOptions) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java " + ClusterSetup.class.getName(), cliOptions); } @SuppressWarnings("static-access") private static Options constructCommandLineOptions() { Option helpOption = OptionBuilder.withLongOpt(help) .withDescription("Prints command-line options info").create(); Option zkServerOption = OptionBuilder.withLongOpt(zkServerAddress) .withDescription("Provide zookeeper address").create(); zkServerOption.setArgs(1); zkServerOption.setRequired(true); zkServerOption.setArgName("ZookeeperServerAddress(Required)"); Option listClustersOption = OptionBuilder.withLongOpt(listClusters) .withDescription("List existing clusters").create(); listClustersOption.setArgs(0); listClustersOption.setRequired(false); Option listResourceGroupOption = OptionBuilder .withLongOpt(listResourceGroups) .withDescription("List resourceGroups hosted in a cluster").create(); listResourceGroupOption.setArgs(1); listResourceGroupOption.setRequired(false); listResourceGroupOption.setArgName("clusterName"); Option listInstancesOption = OptionBuilder.withLongOpt(listInstances) .withDescription("List Instances in a cluster").create(); listInstancesOption.setArgs(1); listInstancesOption.setRequired(false); listInstancesOption.setArgName("clusterName"); Option addClusterOption = OptionBuilder.withLongOpt(addCluster) .withDescription("Add a new cluster").create(); addClusterOption.setArgs(1); addClusterOption.setRequired(false); addClusterOption.setArgName("clusterName"); Option addInstanceOption = OptionBuilder.withLongOpt(addInstance) .withDescription("Add a new Instance to a cluster").create(); addInstanceOption.setArgs(2); addInstanceOption.setRequired(false); addInstanceOption.setArgName("clusterName InstanceAddress(host:port)"); Option addResourceGroupOption = OptionBuilder.withLongOpt(addResourceGroup) .withDescription("Add a resourceGroup to a cluster").create(); addResourceGroupOption.setArgs(4); addResourceGroupOption.setRequired(false); addResourceGroupOption .setArgName("clusterName resourceGroupName partitionNo stateModelRef"); Option addStateModelDefOption = OptionBuilder .withLongOpt(addStateModelDef) .withDescription("Add a State model to a cluster").create(); addStateModelDefOption.setArgs(2); addStateModelDefOption.setRequired(false); addStateModelDefOption.setArgName("clusterName <filename>"); Option addIdealStateOption = OptionBuilder .withLongOpt(addIdealState) .withDescription("Add a State model to a cluster").create(); addIdealStateOption.setArgs(3); addIdealStateOption.setRequired(false); addIdealStateOption.setArgName("clusterName reourceGroupName <filename>"); Option rebalanceOption = OptionBuilder.withLongOpt(rebalance) .withDescription("Rebalance a resourceGroup in a cluster").create(); rebalanceOption.setArgs(3); rebalanceOption.setRequired(false); rebalanceOption.setArgName("clusterName resourceGroupName replicationNo"); Option InstanceInfoOption = OptionBuilder.withLongOpt(listInstanceInfo) .withDescription("Query info of a Instance in a cluster").create(); InstanceInfoOption.setArgs(2); InstanceInfoOption.setRequired(false); InstanceInfoOption.setArgName("clusterName InstanceName"); Option clusterInfoOption = OptionBuilder.withLongOpt(listClusterInfo) .withDescription("Query info of a cluster").create(); clusterInfoOption.setArgs(1); clusterInfoOption.setRequired(false); clusterInfoOption.setArgName("clusterName"); Option resourceGroupInfoOption = OptionBuilder .withLongOpt(listResourceGroupInfo) .withDescription("Query info of a resourceGroup").create(); resourceGroupInfoOption.setArgs(2); resourceGroupInfoOption.setRequired(false); resourceGroupInfoOption.setArgName("clusterName resourceGroupName"); Option partitionInfoOption = OptionBuilder.withLongOpt(listResourceInfo) .withDescription("Query info of a partition").create(); partitionInfoOption.setArgs(2); partitionInfoOption.setRequired(false); partitionInfoOption.setArgName("clusterName partitionName"); Option enableInstanceOption = OptionBuilder.withLongOpt(enableInstance) .withDescription("Enable / disable a Instance").create(); enableInstanceOption.setArgs(3); enableInstanceOption.setRequired(false); enableInstanceOption.setArgName("clusterName InstanceName true/false"); Option listStateModelsOption = OptionBuilder.withLongOpt(listStateModels) .withDescription("Query info of state models in a cluster").create(); listStateModelsOption.setArgs(1); listStateModelsOption.setRequired(false); listStateModelsOption.setArgName("clusterName"); Option listStateModelOption = OptionBuilder.withLongOpt(listStateModel) .withDescription("Query info of a state model in a cluster").create(); listStateModelOption.setArgs(2); listStateModelOption.setRequired(false); listStateModelOption.setArgName("clusterName stateModelName"); // add an option group including either --zkSvr or --configFile /** Option fileOption = OptionBuilder.withLongOpt(configFile) .withDescription("Provide file to write states/messages").create(); fileOption.setArgs(1); fileOption.setRequired(true); fileOption.setArgName("File to write states/messages (Optional)"); **/ OptionGroup optionGroup = new OptionGroup(); optionGroup.addOption(zkServerOption); // optionGroup.addOption(fileOption); Options options = new Options(); options.addOption(helpOption); // options.addOption(zkServerOption); options.addOption(rebalanceOption); options.addOption(addResourceGroupOption); options.addOption(addClusterOption); options.addOption(addInstanceOption); options.addOption(listInstancesOption); options.addOption(listResourceGroupOption); options.addOption(listClustersOption); options.addOption(addIdealStateOption); options.addOption(rebalanceOption); options.addOption(InstanceInfoOption); options.addOption(clusterInfoOption); options.addOption(resourceGroupInfoOption); options.addOption(partitionInfoOption); options.addOption(enableInstanceOption); options.addOption(addStateModelDefOption); options.addOption(listStateModelsOption); options.addOption(listStateModelOption); options.addOptionGroup(optionGroup); return options; } private static byte[] readFile(String filePath) throws IOException { File file = new File(filePath); int size = (int)file.length(); byte[] bytes = new byte[size]; DataInputStream dis = new DataInputStream(new FileInputStream(file)); int read = 0; int numRead = 0; while (read < bytes.length && (numRead = dis.read(bytes, read, bytes.length-read)) >= 0) { read = read + numRead; } return bytes; } public static int processCommandLineArgs(String[] cliArgs) throws Exception { CommandLineParser cliParser = new GnuParser(); Options cliOptions = constructCommandLineOptions(); CommandLine cmd = null; try { cmd = cliParser.parse(cliOptions, cliArgs); } catch (ParseException pe) { System.err .println("CommandLineClient: failed to parse command-line options: " + pe.toString()); printUsage(cliOptions); System.exit(1); } /** if (cmd.hasOption(configFile)) { String file = cmd.getOptionValue(configFile); // for temporary test only, will move to command line // create fake db names List<FileBasedClusterManager.DBParam> dbParams = new ArrayList<FileBasedClusterManager.DBParam>(); dbParams.add(new FileBasedClusterManager.DBParam("BizFollow", 1)); dbParams.add(new FileBasedClusterManager.DBParam("BizProfile", 1)); dbParams.add(new FileBasedClusterManager.DBParam("EspressoDB", 10)); dbParams.add(new FileBasedClusterManager.DBParam("MailboxDB", 128)); dbParams.add(new FileBasedClusterManager.DBParam("MyDB", 8)); dbParams.add(new FileBasedClusterManager.DBParam("schemata", 1)); String[] InstancesInfo = { "localhost:8900" }; // ClusterViewSerializer serializer = new ClusterViewSerializer(file); int replica = 0; ClusterView view = FileBasedClusterManager .generateStaticConfigClusterView(InstancesInfo, dbParams, replica); // byte[] bytes; ClusterViewSerializer.serialize(view, new File(file)); // System.out.println(new String(bytes)); ClusterView restoredView = ClusterViewSerializer.deserialize(new File( file)); // System.out.println(restoredView); byte[] bytes = ClusterViewSerializer.serialize(restoredView); // System.out.println(new String(bytes)); return 0; } **/ ClusterSetup setupTool = new ClusterSetup( cmd.getOptionValue(zkServerAddress)); if (cmd.hasOption(addCluster)) { String clusterName = cmd.getOptionValue(addCluster); setupTool.addCluster(clusterName, false); return 0; } if (cmd.hasOption(addInstance)) { String clusterName = cmd.getOptionValues(addInstance)[0]; String InstanceAddressInfo = cmd.getOptionValues(addInstance)[1]; String[] InstanceAddresses = InstanceAddressInfo.split(";"); setupTool.addInstancesToCluster(clusterName, InstanceAddresses); return 0; } if (cmd.hasOption(addResourceGroup)) { String clusterName = cmd.getOptionValues(addResourceGroup)[0]; String resourceGroupName = cmd.getOptionValues(addResourceGroup)[1]; int partitions = Integer .parseInt(cmd.getOptionValues(addResourceGroup)[2]); String stateModelRef = cmd.getOptionValues(addResourceGroup)[3]; setupTool.addResourceGroupToCluster(clusterName, resourceGroupName, partitions, stateModelRef); return 0; } if (cmd.hasOption(rebalance)) { String clusterName = cmd.getOptionValues(rebalance)[0]; String resourceGroupName = cmd.getOptionValues(rebalance)[1]; int replicas = Integer.parseInt(cmd.getOptionValues(rebalance)[2]); setupTool.rebalanceStorageCluster(clusterName, resourceGroupName, replicas); return 0; } if (cmd.hasOption(listClusters)) { List<String> clusters = setupTool.getClusterManagementTool() .getClusters(); System.out.println("Existing clusters:"); for (String cluster : clusters) { System.out.println(cluster); } return 0; } if (cmd.hasOption(listResourceGroups)) { String clusterName = cmd.getOptionValue(listResourceGroups); List<String> resourceGroupNames = setupTool.getClusterManagementTool() .getResourceGroupsInCluster(clusterName); System.out.println("Existing resources in cluster " + clusterName + ":"); for (String resourceGroupName : resourceGroupNames) { System.out.println(resourceGroupName); } return 0; } else if(cmd.hasOption(listClusterInfo)) { String clusterName = cmd.getOptionValue(listClusterInfo); List<String> resourceGroupNames = setupTool.getClusterManagementTool() .getResourceGroupsInCluster(clusterName); List<String> Instances = setupTool.getClusterManagementTool() .getInstancesInCluster(clusterName); System.out.println("Existing resources in cluster " + clusterName + ":"); for (String resourceGroupName : resourceGroupNames) { System.out.println(resourceGroupName); } System.out.println("Instances in cluster " + clusterName + ":"); for (String InstanceName : Instances) { System.out.println(InstanceName); } return 0; } else if (cmd.hasOption(listInstances)) { String clusterName = cmd.getOptionValue(listInstances); List<String> Instances = setupTool.getClusterManagementTool() .getInstancesInCluster(clusterName); System.out.println("Instances in cluster " + clusterName + ":"); for (String InstanceName : Instances) { System.out.println(InstanceName); } return 0; } else if (cmd.hasOption(listInstanceInfo)) { String clusterName = cmd.getOptionValues(listInstanceInfo)[0]; String instanceName = cmd.getOptionValues(listInstanceInfo)[1]; ZNRecord record = setupTool.getClusterManagementTool().getInstanceConfig(clusterName, instanceName); String result = new String(new ZNRecordSerializer().serialize(record)); System.out.println(result); return 0; // print out current states and } else if (cmd.hasOption(listResourceGroupInfo)) { // print out partition number, db name and replication number // Also the ideal states and current states String clusterName = cmd.getOptionValues(listResourceGroupInfo)[0]; String resourceGroupName = cmd.getOptionValues(listResourceGroupInfo)[1]; ZNRecord idealState = setupTool.getClusterManagementTool().getResourceGroupIdealState(clusterName, resourceGroupName); ZNRecord externalView = setupTool.getClusterManagementTool().getResourceGroupExternalView(clusterName, resourceGroupName); System.out.println("IdealState for "+resourceGroupName+":"); System.out.println(new String(new ZNRecordSerializer().serialize(idealState))); System.out.println(); System.out.println("External view for "+resourceGroupName+":"); System.out.println(new String(new ZNRecordSerializer().serialize(externalView))); return 0; } else if (cmd.hasOption(listResourceInfo)) { // print out where the partition master / slaves locates } else if (cmd.hasOption(enableInstance)) { String clusterName = cmd.getOptionValues(enableInstance)[0]; String instanceName = cmd.getOptionValues(enableInstance)[1]; boolean enabled = Boolean.parseBoolean(cmd.getOptionValues(enableInstance)[1] .toLowerCase()); setupTool.getClusterManagementTool().enableInstance(clusterName, instanceName, enabled); return 0; } else if(cmd.hasOption(listStateModels)) { String clusterName = cmd.getOptionValues(listStateModels)[0]; List<String> stateModels = setupTool.getClusterManagementTool() .getStateModelDefs(clusterName); System.out.println("Existing state models:"); for (String stateModel : stateModels) { System.out.println(stateModel); } return 0; } else if (cmd.hasOption(listStateModel)) { String clusterName = cmd.getOptionValues(listStateModel)[0]; String stateModel = cmd.getOptionValues(listStateModel)[1]; ZNRecord record = setupTool.getClusterManagementTool().getStateModelDef(clusterName, stateModel); String result = new String(new ZNRecordSerializer().serialize(record)); System.out.println(result); return 0; } else if(cmd.hasOption(addStateModelDef)) { String clusterName = cmd.getOptionValues(addStateModelDef)[0]; String stateModelFile = cmd.getOptionValues(addStateModelDef)[1]; ZNRecord stateModelRecord = (ZNRecord)(new ZNRecordSerializer().deserialize(readFile(stateModelFile))); if(stateModelRecord.getId() == null || stateModelRecord.getId().length() == 0) { throw new IllegalArgumentException("ZNRecord for state model definition must have an id"); } setupTool.getClusterManagementTool().addStateModelDef(clusterName, stateModelRecord.getId(), stateModelRecord); return 0; } else if(cmd.hasOption(addIdealState)) { String clusterName = cmd.getOptionValues(addIdealState)[0]; String resourceGroupName = cmd.getOptionValues(addIdealState)[1]; String idealStateFile = cmd.getOptionValues(addIdealState)[2]; ZNRecord idealStateRecord = (ZNRecord)(new ZNRecordSerializer().deserialize(readFile(idealStateFile))); if(idealStateRecord.getId() == null || !idealStateRecord.getId().equals(resourceGroupName)) { throw new IllegalArgumentException("ideal state must have same id as resourceGroup name"); } setupTool.getClusterManagementTool().setResourceGroupIdealState(clusterName, resourceGroupName, idealStateRecord); return 0; } else if (cmd.hasOption(help)) { printUsage(cliOptions); return 0; } return 0; } /** * @param args * @throws Exception * @throws JsonMappingException * @throws JsonGenerationException */ public static void main(String[] args) throws Exception { // For temporary test only, remove later Logger.getRootLogger().setLevel(Level.ERROR); if (args.length == 0) { new ClusterSetup("localhost:2181") .setupTestCluster("storage-integration-cluster"); new ClusterSetup("localhost:2181") .setupTestCluster("relay-integration-cluster"); System.exit(0); } int ret = processCommandLineArgs(args); System.exit(ret); } }
package ch.ntb.inf.deep.cgPPC; import ch.ntb.inf.deep.cfg.TestCFG; import ch.ntb.inf.deep.classItems.Class; import ch.ntb.inf.deep.classItems.ICclassFileConsts; import ch.ntb.inf.deep.config.Configuration; import ch.ntb.inf.deep.linker.Linker32; import ch.ntb.inf.deep.ssa.TestSSA; import ch.ntb.inf.deep.strings.HString; public class TestCgPPC implements ICclassFileConsts { static CodeGen[] code; // static String[] config = new String[] {"C:/NTbcheckout/EUser/JCC/Deep/ExampleProject.deep","BootFromRam"}; static String[] config = new String[] {"D:/work/Crosssystem/deep/ExampleProject.deep","BootFromRam"}; public static void createCgPPC(Class clazz) { Linker32.prepareConstantBlock(clazz); TestSSA.createSSA(clazz); code = new CodeGen[TestCFG.cfg.length]; for (int i = 0; i < TestCFG.cfg.length; i++){ code[i] = new CodeGen(TestSSA.ssa[i]); TestSSA.ssa[i].print(0); code[i].print(); System.out.println(); } } public static int[] getCode(String name) { int i = 0; while (i < code.length && ! code[i].ssa.cfg.method.name.equals(HString.getHString(name))) i++; int len = code[i].iCount; int[] code1 = new int[len]; for (int k = 0; k < len; k++) code1[k] = code[i].instructions[k]; return code1; } }
package com.yahoo.vespa.config.server.metrics; import com.yahoo.config.provision.ApplicationId; import com.yahoo.slime.ArrayTraverser; import com.yahoo.slime.Inspector; import com.yahoo.slime.Slime; import com.yahoo.vespa.config.SlimeUtils; import com.yahoo.vespa.config.server.http.v2.MetricsResponse; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.net.URI; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.logging.Logger; import java.util.stream.Collectors; /** * @author olaa */ public class MetricsRetriever { private static final Logger logger = Logger.getLogger(MetricsRetriever.class.getName()); HttpClient httpClient = HttpClientBuilder.create().build(); public MetricsResponse retrieveAllMetrics(Map<ApplicationId, Map<String, List<URI>>> applicationHosts) { Map<ApplicationId, Map<String, MetricsAggregator>> allMetrics = applicationHosts.entrySet().stream() .collect(Collectors.toMap( Map.Entry::getKey, e -> getMetricsByCluster(e.getValue()))); return new MetricsResponse(200, allMetrics); } private Map<String, MetricsAggregator> getMetricsByCluster(Map<String, List<URI>> clusterHosts) { return clusterHosts.entrySet().stream() .collect(Collectors.toMap( Map.Entry::getKey, e -> getClusterMetrics(e.getValue()) ) ); } private MetricsAggregator getClusterMetrics(List<URI> hosts) { MetricsAggregator clusterMetrics = new MetricsAggregator(); hosts.stream() .forEach(host -> getHostMetrics(host, clusterMetrics)); return clusterMetrics; } private void getHostMetrics(URI hostURI, MetricsAggregator metrics) { Slime responseBody = doMetricsRequest(hostURI); Inspector services = responseBody.get().field("services"); services.traverse((ArrayTraverser) (i, servicesInspector) -> { parseService(servicesInspector, metrics); }); } private Slime doMetricsRequest(URI hostURI) { HttpGet get = new HttpGet(hostURI); try { HttpResponse response = httpClient.execute(get); InputStream is = response.getEntity().getContent(); Slime slime = SlimeUtils.jsonToSlime(is.readAllBytes()); is.close(); return slime; } catch (IOException e) { throw new UncheckedIOException(e); } } private void parseService(Inspector service, MetricsAggregator metrics) { String serviceName = service.field("name").asString(); Instant timestamp = Instant.ofEpochSecond(service.field("timestamp").asLong()); metrics.setTimestamp(timestamp); service.field("metrics").traverse((ArrayTraverser) (i, m) -> { Inspector values = m.field("values"); switch (serviceName) { case "container": metrics.addContainerQueryLatencyCount(values.field("query_latency.count").asDouble()); metrics.addContainerQueryLatencySum(values.field("query_latency.sum").asDouble()); metrics.addFeedLatencyCount(values.field("feed_latency.count").asDouble()); metrics.addFeedLatencySum(values.field("feed_latency.sum").asDouble()); break; case "qrserver": metrics.addQrQueryLatencyCount(values.field("query_latency.count").asDouble()); metrics.addQrQueryLatencySum(values.field("query_latency.sum").asDouble()); break; case "distributor": metrics.addDocumentCount(values.field("vds.distributor.docsstored.average").asDouble()); break; } }); } }
package unluac.decompile; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import unluac.decompile.block.AlwaysLoop; import unluac.decompile.block.Block; import unluac.decompile.block.BooleanIndicator; import unluac.decompile.block.Break; import unluac.decompile.block.CompareBlock; import unluac.decompile.block.DoEndBlock; import unluac.decompile.block.ElseEndBlock; import unluac.decompile.block.ForBlock; import unluac.decompile.block.IfThenElseBlock; import unluac.decompile.block.IfThenEndBlock; import unluac.decompile.block.OuterBlock; import unluac.decompile.block.RepeatBlock; import unluac.decompile.block.SetBlock; import unluac.decompile.block.TForBlock; import unluac.decompile.block.WhileBlock; import unluac.decompile.branch.AndBranch; import unluac.decompile.branch.AssignNode; import unluac.decompile.branch.Branch; import unluac.decompile.branch.EQNode; import unluac.decompile.branch.LENode; import unluac.decompile.branch.LTNode; import unluac.decompile.branch.OrBranch; import unluac.decompile.branch.TestNode; import unluac.decompile.branch.TestSetNode; import unluac.decompile.branch.TrueNode; import unluac.decompile.expression.ClosureExpression; import unluac.decompile.expression.ConstantExpression; import unluac.decompile.expression.Expression; import unluac.decompile.expression.FunctionCall; import unluac.decompile.expression.TableLiteral; import unluac.decompile.expression.TableReference; import unluac.decompile.expression.Vararg; import unluac.decompile.operation.CallOperation; import unluac.decompile.operation.GlobalSet; import unluac.decompile.operation.Operation; import unluac.decompile.operation.RegisterSet; import unluac.decompile.operation.ReturnOperation; import unluac.decompile.operation.TableSet; import unluac.decompile.operation.UpvalueSet; import unluac.decompile.statement.Assignment; import unluac.decompile.statement.Statement; import unluac.decompile.target.GlobalTarget; import unluac.decompile.target.TableTarget; import unluac.decompile.target.Target; import unluac.decompile.target.UpvalueTarget; import unluac.decompile.target.VariableTarget; import unluac.parse.LBoolean; import unluac.parse.LFunction; import unluac.util.Stack; import javax.swing.plaf.nimbus.State; public class Decompiler { private final int registers; private final int length; public final Code code; private final Upvalues upvalues; public final Declaration[] declList; protected Function f; protected LFunction function; private final LFunction[] functions; private final int params; private final int vararg; private final Op tforTarget; public Decompiler(LFunction function) { this.f = new Function(function); this.function = function; registers = function.maximumStackSize; length = function.code.length; code = new Code(function); if(function.locals.length >= function.numParams) { declList = new Declaration[function.locals.length]; for(int i = 0; i < declList.length; i++) { declList[i] = new Declaration(function.locals[i]); } } else { //TODO: debug info missing; declList = new Declaration[function.numParams]; for(int i = 0; i < declList.length; i++) { declList[i] = new Declaration("_ARG_" + i + "_", 0, length - 1); } } upvalues = new Upvalues(function.upvalues); functions = function.functions; params = function.numParams; vararg = function.vararg; tforTarget = function.header.version.getTForTarget(); } private Registers r; private Block outer; public void decompile() { r = new Registers(registers, length, declList, f); findReverseTargets(); handleBranches(true); outer = handleBranches(false); processSequence(1, length); } public void print() { print(new Output()); } public void print(OutputProvider out) { print(new Output(out)); } public void print(Output out) { handleInitialDeclares(out); outer.print(out); } private void handleInitialDeclares(Output out) { List<Declaration> initdecls = new ArrayList<Declaration>(declList.length); for(int i = params + (vararg & 1); i < declList.length; i++) { if(declList[i].begin == 0) { initdecls.add(declList[i]); } } if(initdecls.size() > 0) { out.print("local "); out.print(initdecls.get(0).name); for(int i = 1; i < initdecls.size(); i++) { out.print(", "); out.print(initdecls.get(i).name); } out.println(); } } private List<Operation> processLine(int line) { List<Operation> operations = new LinkedList<Operation>(); int A = code.A(line); int B = code.B(line); int C = code.C(line); int Bx = code.Bx(line); switch(code.op(line)) { case MOVE: operations.add(new RegisterSet(line, A, r.getExpression(B, line))); break; case LOADK: operations.add(new RegisterSet(line, A, f.getConstantExpression(Bx))); break; case LOADBOOL: operations.add(new RegisterSet(line, A, new ConstantExpression(new Constant(B != 0 ? LBoolean.LTRUE : LBoolean.LFALSE), -1))); break; case LOADNIL: { int maximum; if(function.header.version.usesOldLoadNilEncoding()) { maximum = B; } else { maximum = A + B; } while(A <= maximum) { operations.add(new RegisterSet(line, A, Expression.NIL)); A++; } break; } case GETUPVAL: operations.add(new RegisterSet(line, A, upvalues.getExpression(B))); break; case GETTABUP: if(B == 0 && (C & 0x100) != 0) { operations.add(new RegisterSet(line, A, f.getGlobalExpression(C & 0xFF))); //TODO: check } else { operations.add(new RegisterSet(line, A, new TableReference(upvalues.getExpression(B), r.getKExpression(C, line)))); } break; case GETGLOBAL: operations.add(new RegisterSet(line, A, f.getGlobalExpression(Bx))); break; case GETTABLE: operations.add(new RegisterSet(line, A, new TableReference(r.getExpression(B, line), r.getKExpression(C, line)))); break; case SETUPVAL: operations.add(new UpvalueSet(line, upvalues.getName(B), r.getExpression(A, line))); break; case SETTABUP: if(A == 0 && (B & 0x100) != 0) { operations.add(new GlobalSet(line, f.getGlobalName(B & 0xFF), r.getKExpression(C, line))); //TODO: check } else { operations.add(new TableSet(line, upvalues.getExpression(A), r.getKExpression(B, line), r.getKExpression(C, line), true, line)); } break; case SETGLOBAL: operations.add(new GlobalSet(line, f.getGlobalName(Bx), r.getExpression(A, line))); break; case SETTABLE: operations.add(new TableSet(line, r.getExpression(A, line), r.getKExpression(B, line), r.getKExpression(C, line), true, line)); break; case NEWTABLE: operations.add(new RegisterSet(line, A, new TableLiteral(B, C))); break; case SELF: { // We can later determine is : syntax was used by comparing subexpressions with == Expression common = r.getExpression(B, line); operations.add(new RegisterSet(line, A + 1, common)); operations.add(new RegisterSet(line, A, new TableReference(common, r.getKExpression(C, line)))); break; } case ADD: operations.add(new RegisterSet(line, A, Expression.makeADD(r.getKExpression(B, line), r.getKExpression(C, line)))); break; case SUB: operations.add(new RegisterSet(line, A, Expression.makeSUB(r.getKExpression(B, line), r.getKExpression(C, line)))); break; case MUL: operations.add(new RegisterSet(line, A, Expression.makeMUL(r.getKExpression(B, line), r.getKExpression(C, line)))); break; case DIV: operations.add(new RegisterSet(line, A, Expression.makeDIV(r.getKExpression(B, line), r.getKExpression(C, line)))); break; case MOD: operations.add(new RegisterSet(line, A, Expression.makeMOD(r.getKExpression(B, line), r.getKExpression(C, line)))); break; case POW: operations.add(new RegisterSet(line, A, Expression.makePOW(r.getKExpression(B, line), r.getKExpression(C, line)))); break; case UNM: operations.add(new RegisterSet(line, A, Expression.makeUNM(r.getExpression(B, line)))); break; case NOT: operations.add(new RegisterSet(line, A, Expression.makeNOT(r.getExpression(B, line)))); break; case LEN: operations.add(new RegisterSet(line, A, Expression.makeLEN(r.getExpression(B, line)))); break; case CONCAT: { Expression value = r.getExpression(C, line); //Remember that CONCAT is right associative. while(C value = Expression.makeCONCAT(r.getExpression(C, line), value); } operations.add(new RegisterSet(line, A, value)); break; } case JMP: case EQ: case LT: case LE: case TEST: case TESTSET: /* Do nothing ... handled with branches */ break; case CALL: { boolean multiple = (C >= 3 || C == 0); if(B == 0) B = registers - A; if(C == 0) C = registers - A + 1; Expression function = r.getExpression(A, line); Expression[] arguments = new Expression[B - 1]; for(int register = A + 1; register <= A + B - 1; register++) { arguments[register - A - 1] = r.getExpression(register, line); } FunctionCall value = new FunctionCall(function, arguments, multiple); if(C == 1) { operations.add(new CallOperation(line, value)); } else { if(C == 2 && !multiple) { operations.add(new RegisterSet(line, A, value)); } else { for(int register = A; register <= A + C - 2; register++) { operations.add(new RegisterSet(line, register, value)); } } } break; } case TAILCALL: { if(B == 0) B = registers - A; Expression function = r.getExpression(A, line); Expression[] arguments = new Expression[B - 1]; for(int register = A + 1; register <= A + B - 1; register++) { arguments[register - A - 1] = r.getExpression(register, line); } FunctionCall value = new FunctionCall(function, arguments, true); operations.add(new ReturnOperation(line, value)); skip[line + 1] = true; break; } case RETURN: { if(B == 0) B = registers - A + 1; Expression[] values = new Expression[B - 1]; for(int register = A; register <= A + B - 2; register++) { values[register - A] = r.getExpression(register, line); } operations.add(new ReturnOperation(line, values)); break; } case FORLOOP: case FORPREP: case TFORCALL: case TFORLOOP: /* Do nothing ... handled with branches */ break; case SETLIST: { if(C == 0) { C = code.codepoint(line + 1); skip[line + 1] = true; } if(B == 0) { B = registers - A - 1; } Expression table = r.getValue(A, line); for(int i = 1; i <= B; i++) { operations.add(new TableSet(line, table, new ConstantExpression(new Constant((C - 1) * 50 + i), -1), r.getExpression(A + i, line), false, r.getUpdated(A + i, line))); } break; } case CLOSE: break; case CLOSURE: { LFunction f = functions[Bx]; operations.add(new RegisterSet(line, A, new ClosureExpression(f, declList, line + 1))); if(function.header.version.usesInlineUpvalueDeclarations()) { // Skip upvalue declarations for(int i = 0; i < f.numUpvalues; i++) { skip[line + 1 + i] = true; } } break; } case VARARG: { boolean multiple = (B != 2); if(B == 1) throw new IllegalStateException(); if(B == 0) B = registers - A + 1; Expression value = new Vararg(B - 1, multiple); for(int register = A; register <= A + B - 2; register++) { operations.add(new RegisterSet(line, register, value)); } break; } default: throw new IllegalStateException("Illegal instruction: " + code.op(line)); } return operations; } /** * When lines are processed out of order, they are noted * here so they can be skipped when encountered normally. */ boolean[] skip; /** * Precalculated array of which lines are the targets of * jump instructions that go backwards... such targets * must be at the statement/block level in the outputted * code (they cannot be mid-expression). */ boolean[] reverseTarget; private void findReverseTargets() { reverseTarget = new boolean[length + 1]; Arrays.fill(reverseTarget, false); for(int line = 1; line <= length; line++) { if(code.op(line) == Op.JMP && code.sBx(line) < 0) { reverseTarget[line + 1 + code.sBx(line)] = true; } } } private Assignment processOperation(Operation operation, int line, int nextLine, Block block) { Assignment assign = null; boolean wasMultiple = false; Statement stmt = operation.process(r, block); if(stmt != null) { if(stmt instanceof Assignment) { assign = (Assignment) stmt; if(!assign.getFirstValue().isMultiple()) { block.addStatement(stmt); } else { wasMultiple = true; } } else { block.addStatement(stmt); } //System.out.println("-- added statemtent @" + line); if(assign != null) { //System.out.println("-- checking for multiassign @" + nextLine); while(nextLine < block.end && isMoveIntoTarget(nextLine)) { //System.out.println("-- found multiassign @" + nextLine); Target target = getMoveIntoTargetTarget(nextLine, line + 1); Expression value = getMoveIntoTargetValue(nextLine, line + 1); //updated? assign.addFirst(target, value); skip[nextLine] = true; nextLine++; } if(wasMultiple && !assign.getFirstValue().isMultiple()) { block.addStatement(stmt); } } } return assign; } private void processSequence(int begin, int end) { int blockIndex = 1; Stack<Block> blockStack = new Stack<Block>(); blockStack.push(blocks.get(0)); skip = new boolean[end + 1]; for(int line = begin; line <= end; line++) { /* System.out.print("-- line " + line + "; R[0] = "); r.getValue(0, line).print(new Output()); System.out.println(); System.out.print("-- line " + line + "; R[1] = "); r.getValue(1, line).print(new Output()); System.out.println(); System.out.print("-- line " + line + "; R[2] = "); r.getValue(2, line).print(new Output()); System.out.println(); */ Operation blockHandler = null; while(blockStack.peek().end <= line) { Block block = blockStack.pop(); blockHandler = block.process(this); if(blockHandler != null) { break; } } if(blockHandler == null) { while(blockIndex < blocks.size() && blocks.get(blockIndex).begin <= line) { blockStack.push(blocks.get(blockIndex++)); } } Block block = blockStack.peek(); r.startLine(line); //Must occur AFTER block.rewrite if(skip[line]) { List<Declaration> newLocals = r.getNewLocals(line); if(!newLocals.isEmpty()) { Assignment assign = new Assignment(); assign.declare(newLocals.get(0).begin); for(Declaration decl : newLocals) { assign.addLast(new VariableTarget(decl), r.getValue(decl.register, line)); } blockStack.peek().addStatement(assign); } continue; } List<Operation> operations = processLine(line); List<Declaration> newLocals = r.getNewLocals(blockHandler == null ? line : line - 1); //List<Declaration> newLocals = r.getNewLocals(line); Assignment assign = null; if(blockHandler == null) { if(code.op(line) == Op.LOADNIL) { assign = new Assignment(); int count = 0; for(Operation operation : operations) { RegisterSet set = (RegisterSet) operation; operation.process(r, block); if(r.isAssignable(set.register, set.line)) { assign.addLast(r.getTarget(set.register, set.line), set.value); count++; } } if(count > 0) { block.addStatement(assign); } } else { //System.out.println("-- Process iterating ... "); for(Operation operation : operations) { //System.out.println("-- iter"); Assignment temp = processOperation(operation, line, line + 1, block); if(temp != null) { assign = temp; //System.out.print("-- top assign -> "); temp.getFirstTarget().print(new Output()); System.out.println(); } } if(assign != null && assign.getFirstValue().isMultiple()) { block.addStatement(assign); } } } else { assign = processOperation(blockHandler, line, line, block); } if(assign != null) { if(!newLocals.isEmpty()) { assign.declare(newLocals.get(0).begin); for(Declaration decl : newLocals) { //System.out.println("-- adding decl @" + line); assign.addLast(new VariableTarget(decl), r.getValue(decl.register, line + 1)); } //blockStack.peek().addStatement(assign); } } if(blockHandler == null) { if(assign != null) { } else if(!newLocals.isEmpty() && code.op(line) != Op.FORPREP) { if(code.op(line) != Op.JMP || code.op(line + 1 + code.sBx(line)) != tforTarget) { assign = new Assignment(); assign.declare(newLocals.get(0).begin); for(Declaration decl : newLocals) { assign.addLast(new VariableTarget(decl), r.getValue(decl.register, line)); } blockStack.peek().addStatement(assign); } } } if(blockHandler != null) { //System.out.println("-- repeat @" + line); line continue; } } } private boolean isMoveIntoTarget(int line) { switch(code.op(line)) { case MOVE: return r.isAssignable(code.A(line), line) && !r.isLocal(code.B(line), line); case SETUPVAL: case SETGLOBAL: return !r.isLocal(code.A(line), line); case SETTABLE: { int C = code.C(line); if((C & 0x100) != 0) { return false; } else { return !r.isLocal(C, line); } } default: return false; } } private Target getMoveIntoTargetTarget(int line, int previous) { switch(code.op(line)) { case MOVE: return r.getTarget(code.A(line), line); case SETUPVAL: return new UpvalueTarget(upvalues.getName(code.B(line))); case SETGLOBAL: return new GlobalTarget(f.getGlobalName(code.Bx(line))); case SETTABLE: return new TableTarget(r.getExpression(code.A(line), previous), r.getKExpression(code.B(line), previous)); default: throw new IllegalStateException(); } } private Expression getMoveIntoTargetValue(int line, int previous) { int A = code.A(line); int B = code.B(line); int C = code.C(line); switch(code.op(line)) { case MOVE: return r.getValue(B, previous); case SETUPVAL: case SETGLOBAL: return r.getExpression(A, previous); case SETTABLE: if((C & 0x100) != 0) { throw new IllegalStateException(); } else { return r.getExpression(C, previous); } default: throw new IllegalStateException(); } } private ArrayList<Block> blocks; private OuterBlock handleBranches(boolean first) { List<Block> oldBlocks = blocks; blocks = new ArrayList<Block>(); OuterBlock outer = new OuterBlock(function, length); blocks.add(outer); boolean[] isBreak = new boolean[length + 1]; boolean[] loopRemoved = new boolean[length + 1]; boolean[] breakImmediateEnclosing= new boolean[length + 1]; if(!first) { for(Block block : oldBlocks) { if(block instanceof AlwaysLoop) { blocks.add(block); } if(block instanceof Break) { blocks.add(block); isBreak[block.begin] = true; } } List<Block> delete = new LinkedList<Block>(); for(Block block : blocks) { if(block instanceof AlwaysLoop) { for(Block block2 : blocks) { if(block != block2) { if(block.begin == block2.begin) { if(block.end < block2.end) { delete.add(block); loopRemoved[block.end - 1] = true; } else { delete.add(block2); loopRemoved[block2.end - 1] = true; } } } } } } for(Block block : delete) { blocks.remove(block); } } skip = new boolean[length + 1]; Stack<Branch> stack = new Stack<Branch>(); boolean reduce = false; boolean testset = false; int testsetend = -1; for(int line = 1; line <= length; line++) { if(!skip[line]) { switch(code.op(line)) { case EQ: { EQNode node = new EQNode(code.B(line), code.C(line), code.A(line) != 0, line, line + 2, line + 2 + code.sBx(line + 1)); stack.push(node); skip[line + 1] = true; if(code.op(node.end) == Op.LOADBOOL) { if(code.C(node.end) != 0) { node.isCompareSet = true; node.setTarget = code.A(node.end); } else if(code.op(node.end - 1) == Op.LOADBOOL) { if(code.C(node.end - 1) != 0) { node.isCompareSet = true; node.setTarget = code.A(node.end); } } } continue; } case LT: { LTNode node = new LTNode(code.B(line), code.C(line), code.A(line) != 0, line, line + 2, line + 2 + code.sBx(line + 1)); stack.push(node); skip[line + 1] = true; if(code.op(node.end) == Op.LOADBOOL) { if(code.C(node.end) != 0) { node.isCompareSet = true; node.setTarget = code.A(node.end); } else if(code.op(node.end - 1) == Op.LOADBOOL) { if(code.C(node.end - 1) != 0) { node.isCompareSet = true; node.setTarget = code.A(node.end); } } } continue; } case LE: { LENode node = new LENode(code.B(line), code.C(line), code.A(line) != 0, line, line + 2, line + 2 + code.sBx(line + 1)); stack.push(node); skip[line + 1] = true; if(code.op(node.end) == Op.LOADBOOL) { if(code.C(node.end) != 0) { node.isCompareSet = true; node.setTarget = code.A(node.end); } else if(code.op(node.end - 1) == Op.LOADBOOL) { if(code.C(node.end - 1) != 0) { node.isCompareSet = true; node.setTarget = code.A(node.end); } } } continue; } case TEST: stack.push(new TestNode(code.A(line), code.C(line) != 0, line, line + 2, line + 2 + code.sBx(line + 1))); skip[line + 1] = true; continue; case TESTSET: testset = true; testsetend = line + 2 + code.sBx(line + 1); stack.push(new TestSetNode(code.A(line), code.B(line), code.C(line) != 0, line, line + 2, line + 2 + code.sBx(line + 1))); skip[line + 1] = true; continue; case JMP: { reduce = true; int tline = line + 1 + code.sBx(line); if(tline >= 2 && code.op(tline - 1) == Op.LOADBOOL && code.C(tline - 1) != 0) { stack.push(new TrueNode(code.A(tline - 1), false, line, line + 1, tline)); skip[line + 1] = true; } else if(code.op(tline) == tforTarget && !skip[tline]) { int A = code.A(tline); int C = code.C(tline); if(C == 0) throw new IllegalStateException(); r.setInternalLoopVariable(A, tline, line + 1); //TODO: end? r.setInternalLoopVariable(A + 1, tline, line + 1); r.setInternalLoopVariable(A + 2, tline, line + 1); for(int index = 1; index <= C; index++) { r.setExplicitLoopVariable(A + 2 + index, line, tline + 2); //TODO: end? } skip[tline] = true; skip[tline + 1] = true; blocks.add(new TForBlock(function, line + 1, tline + 2, A, C, r)); } else if(code.sBx(line) == 2 && code.op(line + 1) == Op.LOADBOOL && code.C(line + 1) != 0) { /* This is the tail of a boolean set with a compare node and assign node */ blocks.add(new BooleanIndicator(function, line)); } else { /* for(Block block : blocks) { if(!block.breakable() && block.end == tline) { block.end = line; } } */ if(first || loopRemoved[line]) { if(tline > line) { isBreak[line] = true; blocks.add(new Break(function, line, tline)); } else { Block enclosing = enclosingBreakableBlock(line); if(enclosing != null && enclosing.breakable() && code.op(enclosing.end) == Op.JMP && code.sBx(enclosing.end) + enclosing.end + 1 == tline) { isBreak[line] = true; blocks.add(new Break(function, line, enclosing.end)); } else { blocks.add(new AlwaysLoop(function, tline, line + 1)); } } } } break; } case FORPREP: reduce = true; blocks.add(new ForBlock(function, line + 1, line + 2 + code.sBx(line), code.A(line), r)); skip[line + 1 + code.sBx(line)] = true; r.setInternalLoopVariable(code.A(line), line, line + 2 + code.sBx(line)); r.setInternalLoopVariable(code.A(line) + 1, line, line + 2 + code.sBx(line)); r.setInternalLoopVariable(code.A(line) + 2, line, line + 2 + code.sBx(line)); r.setExplicitLoopVariable(code.A(line) + 3, line, line + 2 + code.sBx(line)); break; case FORLOOP: /* Should be skipped by preceding FORPREP */ throw new IllegalStateException(); default: reduce = isStatement(line); break; } } if((line + 1) <= length && reverseTarget[line + 1]) { reduce = true; } if(testset && testsetend == line + 1) { reduce = true; } if(stack.isEmpty()) { reduce = false; } if(reduce) { reduce = false; Stack<Branch> conditions = new Stack<Branch>(); Stack<Stack<Branch>> backups = new Stack<Stack<Branch>>(); do { boolean isAssignNode = stack.peek() instanceof TestSetNode; int assignEnd = stack.peek().end; boolean compareCorrect = false; if(stack.peek() instanceof TrueNode) { isAssignNode = true; compareCorrect = true; //assignEnd = stack.peek().begin; if(code.C(assignEnd) != 0) { assignEnd += 2; } else { assignEnd += 1; } //System.exit(0); } else if(stack.peek().isCompareSet) { //System.err.println("c" + stack.peek().setTarget); if(code.op(stack.peek().begin) != Op.LOADBOOL || code.C(stack.peek().begin) == 0) { isAssignNode = true; if(code.C(assignEnd) != 0) { assignEnd += 2; } else { assignEnd += 1; } compareCorrect = true; } } else if(assignEnd - 3 >= 1 && code.op(assignEnd - 2) == Op.LOADBOOL && code.C(assignEnd - 2) != 0 && code.op(assignEnd - 3) == Op.JMP && code.sBx(assignEnd - 3) == 2) { if(stack.peek() instanceof TestNode) { TestNode node = (TestNode) stack.peek(); if(node.test == code.A(assignEnd - 2)) { isAssignNode = true; } } } else if(assignEnd - 2 >= 1 && code.op(assignEnd - 1) == Op.LOADBOOL && code.C(assignEnd - 1) != 0 && code.op(assignEnd - 2) == Op.JMP && code.sBx(assignEnd - 2) == 2) { if(stack.peek() instanceof TestNode) { isAssignNode = true; assignEnd += 1; } } else if(assignEnd - 1 >= 1 && code.op(assignEnd) == Op.LOADBOOL && code.C(assignEnd) != 0 && code.op(assignEnd - 1) == Op.JMP && code.sBx(assignEnd - 1) == 2) { if(stack.peek() instanceof TestNode) { isAssignNode = true; assignEnd += 2; } } else if(assignEnd - 1 >= 1 && r.isLocal(getAssignment(assignEnd - 1), assignEnd - 1) && assignEnd > stack.peek().line) { Declaration decl = r.getDeclaration(getAssignment(assignEnd - 1), assignEnd - 1); if(decl.begin == assignEnd - 1 && decl.end > assignEnd - 1) { isAssignNode = true; } } Branch currentBranch=stack.peek(); //fix empty else branch end //this is correct way.the below ignore empty else have problem. if (currentBranch.end-1>=1) { Block enclosing = enclosingUnprotectedBlock(currentBranch.begin); if (enclosing != null) { if(enclosing.getLoopback() == currentBranch.end) { int emptyElseEnd=enclosing.end; //skip used while (skip[emptyElseEnd-1]){ --emptyElseEnd; } int stackSize=stack.size(); emptyElseEnd=emptyElseEnd-stackSize+1; if (code.op(emptyElseEnd-1)==Op.JMP){ currentBranch.end=emptyElseEnd; } } } } if(!compareCorrect && assignEnd - 1 == stack.peek().begin && code.op(stack.peek().begin) == Op.LOADBOOL && code.C(stack.peek().begin) != 0) { backup = null; int begin = stack.peek().begin; assignEnd = begin + 2; int target = code.A(begin); conditions.push(popCompareSetCondition(stack, assignEnd)); conditions.peek().setTarget = target; conditions.peek().end = assignEnd; conditions.peek().begin = begin; } else if(isAssignNode) { backup = null; int target = stack.peek().setTarget; int begin = stack.peek().begin; conditions.push(popSetCondition(stack, assignEnd)); conditions.peek().setTarget = target; conditions.peek().end = assignEnd; conditions.peek().begin = begin; } else { backup = new Stack<Branch>(); conditions.push(popCondition(stack)); backup.reverse(); } backups.push(backup); //stop condition break by TestSetNode //like this // local e={} // if 1<d and 2<(e or {}).id then // xxx // else // xxx // end if (currentBranch instanceof TestSetNode && !stack.isEmpty()){ Branch nextBranch=stack.peek(); if (nextBranch.begin==currentBranch.line){ break; } } } while(!stack.isEmpty()); do { Branch cond = conditions.pop(); Stack<Branch> backup = backups.pop(); int breakTarget = breakTarget(cond.begin); boolean breakable = (breakTarget >= 1); if(breakable && code.op(breakTarget) == Op.JMP) { breakTarget += 1 + code.sBx(breakTarget); } if(breakable && breakTarget == cond.end) { Block immediateEnclosing = enclosingBlock(cond.begin); for(int iline = Math.max(cond.end, immediateEnclosing.end - 1); iline >= Math.max(cond.begin, immediateEnclosing.begin); iline if(code.op(iline) == Op.JMP && iline + 1 + code.sBx(iline) == breakTarget) { cond.end = iline; //fix wrap of if block and formate like "if xxx then else break end" if(!breakImmediateEnclosing[iline]) { breakImmediateEnclosing[iline] = true; break; } //continue search } } } /* A branch has a tail if the instruction just before the end target is JMP */ boolean hasTail = cond.end >= 2 && code.op(cond.end - 1) == Op.JMP; /* This is the target of the tail JMP */ int tail = hasTail ? cond.end + code.sBx(cond.end - 1) : -1; int originalTail = tail; Block enclosing = enclosingUnprotectedBlock(cond.begin); /* Checking enclosing unprotected block to undo JMP redirects. */ if(enclosing != null) { //System.err.println("loopback: " + enclosing.getLoopback()); //System.err.println("cond.end: " + cond.end); //System.err.println("tail : " + tail); if(enclosing.getLoopback() == cond.end) { cond.end = enclosing.end - 1; hasTail = cond.end >= 2 && code.op(cond.end - 1) == Op.JMP; tail = hasTail ? cond.end + code.sBx(cond.end - 1) : -1; } if(hasTail && enclosing.getLoopback() == tail) { tail = enclosing.end - 1; } } if(cond.isSet) { boolean empty = cond.begin == cond.end; if(code.op(cond.begin) == Op.JMP && code.sBx(cond.begin) == 2 && code.op(cond.begin + 1) == Op.LOADBOOL && code.C(cond.begin + 1) != 0) { empty = true; } blocks.add(new SetBlock(function, cond, cond.setTarget, line, cond.begin, cond.end, empty, r)); } else if(code.op(cond.begin) == Op.LOADBOOL && code.C(cond.begin) != 0) { int begin = cond.begin; int target = code.A(begin); if(code.B(begin) == 0) { cond = cond.invert(); } blocks.add(new CompareBlock(function, begin, begin + 2, target, cond)); } else if(cond.end < cond.begin) { blocks.add(new RepeatBlock(function, cond, r)); } else if(hasTail) { Op endOp = code.op(cond.end - 2); boolean isEndCondJump = endOp == Op.EQ || endOp == Op.LE || endOp == Op.LT || endOp == Op.TEST || endOp == Op.TESTSET; if(tail > cond.end || (tail == cond.end && !isEndCondJump)) { Op op = code.op(tail - 1); int sbx = code.sBx(tail - 1); int loopback2 = tail + sbx; boolean isBreakableLoopEnd = function.header.version.isBreakableLoopEnd(op); if(isBreakableLoopEnd && loopback2 <= cond.begin && !isBreak[tail - 1]) { /* (ends with break) */ blocks.add(new IfThenEndBlock(function, cond, backup, r)); } else { skip[cond.end - 1] = true; //Skip the JMP over the else block /* skip the empty else jump. the logic is same,but byte code is not same. ep: if a then if b then print("b") else if c then if d the print("d") else --empty end else --empty end end else print("a2") end print("x") */ /* int skipOtherLine=cond.end-2; while (skipOtherLine >0 ){ //check the same as if (code.op(skipOtherLine)==Op.JMP && (skipOtherLine+1+ code.sBx(skipOtherLine))==loopback2) { skip[skipOtherLine] = true; skipOtherLine--; }else{ break; } } */ boolean emptyElse = tail == cond.end; IfThenElseBlock ifthen = new IfThenElseBlock(function, cond, originalTail, emptyElse, r); blocks.add(ifthen); if(!emptyElse) { ElseEndBlock elseend = new ElseEndBlock(function, cond.end, tail); blocks.add(elseend); } } } else { int loopback = tail; boolean existsStatement = false; for(int sl = loopback; sl < cond.begin; sl++) { if(!skip[sl] && isStatement(sl)) { existsStatement = true; break; } } //TODO: check for 5.2-style if cond then break end if(loopback >= cond.begin || existsStatement) { blocks.add(new IfThenEndBlock(function, cond, backup, r)); } else { skip[cond.end - 1] = true; blocks.add(new WhileBlock(function, cond, originalTail, r)); } } } else { blocks.add(new IfThenEndBlock(function, cond, backup, r)); } } while(!conditions.isEmpty()); } } //Find variables whose scope isn't controlled by existing blocks: for(Declaration decl : declList) { if(!decl.forLoop && !decl.forLoopExplicit) { boolean needsDoEnd = true; for(Block block : blocks) { if(block.contains(decl.begin)) { if(block.scopeEnd() == decl.end) { needsDoEnd = false; break; } } } if(needsDoEnd) { //Without accounting for the order of declarations, we might //create another do..end block later that would eliminate the //need for this one. But order of decls should fix this. blocks.add(new DoEndBlock(function, decl.begin, decl.end + 1)); } } } // Remove breaks that were later parsed as else jumps ListIterator<Block> iter = blocks.listIterator(); while(iter.hasNext()) { Block block = iter.next(); if(skip[block.begin] && block instanceof Break) { iter.remove(); } } Collections.sort(blocks); backup = null; return outer; } private int breakTarget(int line) { int tline = Integer.MAX_VALUE; for(Block block : blocks) { if(block.breakable() && block.contains(line)) { tline = Math.min(tline, block.end); } } if(tline == Integer.MAX_VALUE) return -1; return tline; } private Block enclosingBlock(int line) { //Assumes the outer block is first Block outer = blocks.get(0); Block enclosing = outer; for(int i = 1; i < blocks.size(); i++) { Block next = blocks.get(i); if(next.isContainer() && enclosing.contains(next) && next.contains(line) && !next.loopRedirectAdjustment) { enclosing = next; } } return enclosing; } private Block enclosingBlock(Block block) { //Assumes the outer block is first Block outer = blocks.get(0); Block enclosing = outer; for(int i = 1; i < blocks.size(); i++) { Block next = blocks.get(i); if(next == block) continue; if(next.contains(block) && enclosing.contains(next)) { enclosing = next; } } return enclosing; } private Block enclosingBreakableBlock(int line) { Block outer = blocks.get(0); Block enclosing = outer; for(int i = 1; i < blocks.size(); i++) { Block next = blocks.get(i); if(enclosing.contains(next) && next.contains(line) && next.breakable() && !next.loopRedirectAdjustment) { enclosing = next; } } return enclosing == outer ? null : enclosing; } private Block enclosingUnprotectedBlock(int line) { //Assumes the outer block is first Block outer = blocks.get(0); Block enclosing = outer; for(int i = 1; i < blocks.size(); i++) { Block next = blocks.get(i); if(enclosing.contains(next) && next.contains(line) && next.isUnprotected() && !next.loopRedirectAdjustment) { enclosing = next; } } return enclosing == outer ? null : enclosing; } private static Stack<Branch> backup; public Branch popCondition(Stack<Branch> stack) { Branch branch = stack.pop(); if(backup != null) backup.push(branch); if(branch instanceof TestSetNode) { throw new IllegalStateException(); } int begin = branch.begin; if(code.op(branch.begin) == Op.JMP) { begin += 1 + code.sBx(branch.begin); } while(!stack.isEmpty()) { Branch next = stack.peek(); if(next instanceof TestSetNode) break; if(next.end == begin) { branch = new OrBranch(popCondition(stack).invert(), branch); } else if(next.end == branch.end) { branch = new AndBranch(popCondition(stack), branch); } else { if (next instanceof TestNode) { if (downTestNode(stack,begin,branch.end,branch.line)) { continue; } } break; } } return branch; } public boolean haveRelation(Branch branch,int begin,int end){ return branch.end==begin || branch.end==end; } public boolean isTestGroup(Branch branch,int begin,int end,int line){ // return branch.end==line; return branch.begin+1==branch.end; } public boolean haveRelation2(Branch branch,Stack<Branch> stack){ //check have relation between stack first not TestGroup return !stack.isEmpty() && (branch.begin==stack.peek().end || branch.end==stack.peek().end); } public boolean haveRelationBetweenBranch(Branch a,Branch b){ return a.begin==b.end || a.end==b.end || a.end==b.begin; } //public boolean checkNextTest(Stack<Branch> stack,int begin,int end){ // Branch next=stack.pop(); // Branch next2=stack.peek(); // if (haveRelation(next2,begin,end)) { // return true; // return false; // public boolean downTestNode(Stack<Branch> stack,int begin,int end,int line){ // if (stack.size()==1) return false; // //check until not TestNode // LinkedList<Branch> list=new LinkedList<Branch>(); // Branch branch=null; // boolean retValue=false; // while (!stack.isEmpty()){ // branch=stack.pop(); // list.add(branch); // //(a or b)Test // if ((branch instanceof TestNode) && isTestGroup(branch,begin,end,line)){ // retValue=!stack.isEmpty(); // break; // if (!stack.isEmpty()){ // //this is look for,put on top // branch=stack.pop(); // list.addFirst(branch); // //restore stack // if (list.size()>0) { // for (int i = list.size()-1; i >= 0; i--) { // stack.push(list.get(i)); //// //if have TestNode add it //// if (retValue){ //// stack.push(branch); // return retValue; public boolean downTestNode(Stack<Branch> stack,int begin,int end,int line){ if (stack.size()==1) return false; Branch branch=stack.peek(); //(a or b) if (!isTestGroup(branch,begin,end,line)) return false; //check until not TestNode LinkedList<Branch> list=new LinkedList<Branch>(); boolean retValue=false; while (!stack.isEmpty()){ branch=stack.pop(); //(a or b)Branch if ( (branch instanceof TestNode) && isTestGroup(branch,begin,end,line)){ //(a or) list.add(branch); }else{ Branch last=list.getLast(); if (!haveRelationBetweenBranch(last,branch)) { retValue = true; list.addFirst(branch); }else{ retValue=false; list.add(branch); } break; } } //restore stack if (list.size()>0) { for (int i = list.size()-1; i >= 0; i stack.push(list.get(i)); } } // //if have TestNode add it // if (retValue){ // stack.push(branch); return retValue; } public Branch popSetCondition(Stack<Branch> stack, int assignEnd) { //System.err.println("assign end " + assignEnd); stack.push(new AssignNode(assignEnd - 1, assignEnd, assignEnd)); //Invert argument doesn't matter because begin == end Branch rtn = _helper_popSetCondition(stack, false, assignEnd); return rtn; } public Branch popCompareSetCondition(Stack<Branch> stack, int assignEnd) { Branch top = stack.pop(); boolean invert = false; if(code.B(top.begin) == 0) invert = true;//top = top.invert(); top.begin = assignEnd; top.end = assignEnd; stack.push(top); //stack.pop(); //stack.push(new AssignNode(assignEnd - 1, assignEnd, assignEnd)); //Invert argument doesn't matter because begin == end Branch rtn = _helper_popSetCondition(stack, invert, assignEnd); return rtn; } private Branch _helper_popSetCondition(Stack<Branch> stack, boolean invert, int assignEnd) { Branch branch = stack.pop(); int begin = branch.begin; int end = branch.end; //System.err.println(stack.size()); //System.err.println("_helper_popSetCondition; count: " + count); //System.err.println("_helper_popSetCondition; begin: " + begin); //System.err.println("_helper_popSetCondition; end: " + end); if(invert) { branch = branch.invert(); } if(code.op(begin) == Op.LOADBOOL) { if(code.C(begin) != 0) { begin += 2; } else { begin += 1; } } if(code.op(end) == Op.LOADBOOL) { if(code.C(end) != 0) { end += 2; } else { end += 1; } } //System.err.println("_helper_popSetCondition; begin_adj: " + begin); //System.err.println("_helper_popSetCondition; end_adj: " + end); //if(count >= 2) System.exit(1); int target = branch.setTarget; while(!stack.isEmpty()) { Branch next = stack.peek(); //System.err.println("_helper_popSetCondition; next begin: " + next.begin); //System.err.println("_helper_popSetCondition; next end: " + next.end); boolean ninvert; int nend = next.end; if(code.op(next.end) == Op.LOADBOOL) { ninvert = code.B(next.end) != 0; if(code.C(next.end) != 0) { nend += 2; } else { nend += 1; } } else if(next instanceof TestSetNode) { TestSetNode node = (TestSetNode) next; ninvert = node.invert; } else if(next instanceof TestNode) { TestNode node = (TestNode) next; ninvert = node.invert; } else { ninvert = false; if(nend >= assignEnd) { //System.err.println("break"); break; } } int addr; if(ninvert == invert) { addr = end; } else { addr = begin; } //System.err.println(" addr: " + addr + "(" + begin + ", " + end + ")"); //System.err.println(" nend: " + nend); //System.err.println(" ninv: " + ninvert); //System.exit(0); if(addr == nend) { if(addr != nend) ninvert = !ninvert; if(ninvert) { branch = new OrBranch(_helper_popSetCondition(stack, ninvert, assignEnd), branch); } else { branch = new AndBranch(_helper_popSetCondition(stack, ninvert, assignEnd), branch); } branch.end = nend; } else { if(!(branch instanceof TestSetNode)) { stack.push(branch); branch = popCondition(stack); } //System.out.println("--break"); break; } } branch.isSet = true; branch.setTarget = target; return branch; } private boolean isStatement(int line) { return isStatement(line, -1); } private boolean isStatement(int line, int testRegister) { switch(code.op(line)) { case MOVE: case LOADK: case LOADBOOL: case GETUPVAL: case GETTABUP: case GETGLOBAL: case GETTABLE: case NEWTABLE: case ADD: case SUB: case MUL: case DIV: case MOD: case POW: case UNM: case NOT: case LEN: case CONCAT: case CLOSURE: return r.isLocal(code.A(line), line) || code.A(line) == testRegister; case LOADNIL: for(int register = code.A(line); register <= code.B(line); register++) { if(r.isLocal(register, line)) { return true; } } return false; case SETGLOBAL: case SETUPVAL: case SETTABUP: case SETTABLE: case JMP: case TAILCALL: case RETURN: case FORLOOP: case FORPREP: case TFORCALL: case TFORLOOP: case CLOSE: return true; case SELF: return r.isLocal(code.A(line), line) || r.isLocal(code.A(line) + 1, line); case EQ: case LT: case LE: case TEST: case TESTSET: case SETLIST: return false; case CALL: { int a = code.A(line); int c = code.C(line); if(c == 1) { return true; } if(c == 0) c = registers - a + 1; for(int register = a; register < a + c - 1; register++) { if(r.isLocal(register, line)) { return true; } } return (c == 2 && a == testRegister); } case VARARG: { int a = code.A(line); int b = code.B(line); if(b == 0) b = registers - a + 1; for(int register = a; register < a + b - 1; register++) { if(r.isLocal(register, line)) { return true; } } return false; } default: throw new IllegalStateException("Illegal opcode: " + code.op(line)); } } /** * Returns the single register assigned to at the line or * -1 if no register or multiple registers is/are assigned to. */ private int getAssignment(int line) { switch(code.op(line)) { case MOVE: case LOADK: case LOADBOOL: case GETUPVAL: case GETTABUP: case GETGLOBAL: case GETTABLE: case NEWTABLE: case ADD: case SUB: case MUL: case DIV: case MOD: case POW: case UNM: case NOT: case LEN: case CONCAT: case CLOSURE: case SETTABLE: case SETLIST: return code.A(line); case LOADNIL: if(code.A(line) == code.B(line)) { return code.A(line); } else { return -1; } case SETGLOBAL: case SETUPVAL: case SETTABUP: // case SETTABLE: case JMP: case TAILCALL: case RETURN: case FORLOOP: case FORPREP: case TFORCALL: case TFORLOOP: case CLOSE: return -1; case SELF: return -1; case EQ: case LT: case LE: case TEST: case TESTSET: // case SETLIST: return -1; case CALL: { if(code.C(line) == 2) { return code.A(line); } else { return -1; } } case VARARG: { if(code.C(line) == 2) { return code.B(line); } else { return -1; } } default: throw new IllegalStateException("Illegal opcode: " + code.op(line)); } } }
package com.ecyrd.jspwiki; import java.util.*; import org.apache.log4j.*; /* BUGS - if a wikilink is added to a page, then removed, RefMan still thinks that the page refers to the wikilink page. Hm. */ /* A word about synchronizing: I expect this object to be accessed in three situations: - when a WikiEngine is created and it scans its wikipages - when the WE saves a page - when a JSP page accesses one of the WE's ReferenceManagers to display a list of (un)referenced pages. So, access to this class is fairly rare, and usually triggered by user interaction. OTOH, the methods in this class use their storage objects intensively (and, sorry to say, in an unoptimized manner =). My deduction: using unsynchronized HashMaps etc and syncing methods or code blocks is preferrable to using slow, synced storage objects. We don't have iterative code here, so I'm going to use synced methods for now. Please contact me if you notice problems with ReferenceManager, and especially with synchronization, or if you have suggestions about syncing. ebu@memecry.net */ /** * Keeps track of wikipage references: * <UL> * <LI>What pages a given page refers to * <LI>What pages refer to a given page * </UL> * * This is a quick'n'dirty approach without any finesse in storage and * searching algorithms; we trust java.util.*. * <P> * This class contains two HashMaps, m_refersTo and m_referredBy. The * first is indexed by WikiPage names and contains a Collection of all * WikiPages the page refers to. (Multiple references are not counted, * naturally.) The second is indexed by WikiPage names and contains * a HashSet of all pages that refer to the indexing page. (Notice - * the keys of both HashMaps should be kept in sync.) * <P> * When a page is added or edited, its references are parsed, a Collection * is received, and we crudely replace anything previous with this new * Collection. We then check each referenced page name and make sure they * know they are referred to by the new page. * <P> * Based on this information, we can perform non-optimal searches for * e.g. unreferenced pages, top ten lists, etc. * <P> * The owning class must take responsibility of filling in any pre-existing * information, probably by loading each and every WikiPage and calling this * class to update the references when created. * * @author ebu@memecry.net * @since 1.6.1 */ public class ReferenceManager { /** Maps page wikiname to a Collection of pages it refers to. The Collection * must contain Strings. The Collection may contain names of non-existing * pages. */ private HashMap m_refersTo; /** Maps page wikiname to a HashSet of referring pages. The HashSet must * contain Strings. Non-existing pages (a reference exists, but not a file * for the page contents) may have an empty HashSet in m_referredBy. */ private HashMap m_referredBy; /** The WikiEngine that owns this object. */ private WikiEngine m_engine; private static final Category log = Category.getInstance(ReferenceManager.class); /** * Builds a new ReferenceManager with default (null) entries for * the WikiPages contained in the pages Collection. (This collection * must be given for subsequent updateReferences() calls to work.) * <P> * The collection should contain an entry for all currently existing WikiPages. * * @param pages a Collection of WikiPages */ public ReferenceManager( WikiEngine engine, Collection pages ) { m_refersTo = new HashMap(); m_referredBy = new HashMap(); m_engine = engine; buildKeyLists( pages ); } /** * Updates the referred pages of a new or edited WikiPage. If a refersTo * entry for this page already exists, it is removed and a new one is built * from scratch. Also calls updateReferredBy() for each referenced page. * <P> * This is the method to call when a new page has been created and we * want to a) set up its references and b) notify the referred pages * of the references. Use this method during run-time. */ public synchronized void updateReferences( String page, Collection references ) { // Create a new entry in m_refersTo. Collection oldRefTo = (Collection)m_refersTo.get( page ); m_refersTo.remove( page ); m_refersTo.put( page, references ); // We know the page exists, since it's making references somewhere. // If an entry for it didn't exist previously in m_referredBy, make // sure one is added now. if( !m_referredBy.containsKey( page ) ) m_referredBy.put( page, new HashSet() ); // Get all pages that used to be referred to by 'page' and // remove that reference. (We don't want to try to figure out // which particular references were removed...) cleanReferredBy( page, oldRefTo, references ); // Notify all referred pages of their referinesshoodicity. Iterator it = references.iterator(); while( it.hasNext() ) { String referredPageName = (String)it.next(); updateReferredBy( referredPageName, page ); } //dump(); } private void cleanReferredBy( String referrer, Collection oldReferred, Collection newReferred ) { // Two ways to go about this. One is to look up all pages previously // referred by referrer and remove referrer from their lists, and let // the update put them back in (except possibly removed ones). // The other is to get the old referred to list, compare to the new, // and tell the ones missing in the latter to remove referrer from // their list. Hm. We'll just try the first for now. Need to come // back and optimize this a bit. if( oldReferred == null ) return; Iterator it = oldReferred.iterator(); while( it.hasNext() ) { String referredPage = (String)it.next(); HashSet oldRefBy = (HashSet)m_referredBy.get( referredPage ); if( oldRefBy != null ) { oldRefBy.remove( referrer ); } // If the page is referred to by no one AND it doesn't even // exist, we might just as well forget about this entry. // It will be added again elsewhere if new references appear. if( ( ( oldRefBy == null ) || ( oldRefBy.isEmpty() ) ) && ( m_engine.pageExists( referredPage ) == false ) ) { m_referredBy.remove( referredPage ); } } } /** * When initially building a ReferenceManager from scratch, call this method * BEFORE calling updateReferences() with a full list of existing page names. * It builds the refersTo and referredBy key lists, thus enabling * updateReferences() to function correctly. * <P> * This method should NEVER be called after initialization. It clears all mappings * from the reference tables. * * @param pages a Collection containing WikiPage objects. */ private synchronized void buildKeyLists( Collection pages ) { m_refersTo.clear(); m_referredBy.clear(); Iterator it = pages.iterator(); try { while( it.hasNext() ) { WikiPage page = (WikiPage)it.next(); // We add a non-null entry to referredBy to indicate the referred page exists m_referredBy.put( page.getName(), new HashSet() ); // Just add a key to refersTo; the keys need to be in sync with referredBy. m_refersTo.put( page.getName(), null ); } } catch( ClassCastException e ) { log.fatal( "Invalid collection entry in ReferenceManager.buildKeyLists().", e ); } } /** * Marks the page as referred to by the referrer. If the page does not * exist previously, nothing is done. (This means that some page, somewhere, * has a link to a page that does not exist.) * <P> * This method is NOT synchronized. It should only be referred to from * within a synchronized method, or it should be made synced if necessary. */ private void updateReferredBy( String page, String referrer ) { // We're not really interested in first level self-references. if( page.equals( referrer ) ) return; HashSet referrers = (HashSet)m_referredBy.get( page ); // Even if 'page' has not been created yet, it can still be referenced. // This requires we don't use m_referredBy keys when looking up missing // pages, of course. if(referrers == null) { referrers = new HashSet(); m_referredBy.put( page, referrers ); } referrers.add( referrer ); } /** * Finds all unreferenced pages. This requires a linear scan through * m_referredBy to locate keys with null or empty values. */ public synchronized Collection findUnreferenced() { ArrayList unref = new ArrayList(); Set keys = m_referredBy.keySet(); Iterator it = keys.iterator(); while( it.hasNext() ) { String key = (String) it.next(); HashSet refs = (HashSet) m_referredBy.get( key ); if( refs == null || refs.isEmpty() ) unref.add( key ); } return( unref ); } /** * Finds all references to non-existant pages. This requires a linear * scan through m_refersTo values; each value must have a corresponding * key entry in the reference HashMaps, otherwise such a page has never * been created. * <P> * Returns a Collection containing Strings of unreferenced page names. * Each non-existant page name is shown only once - we don't return information * on who referred to it. */ public synchronized Collection findUncreated() { HashSet uncreated = new HashSet(); // Go through m_refersTo values and check that m_refersTo has the corresponding keys. // We want to reread the code to make sure our HashMaps are in sync... Collection allReferences = m_refersTo.values(); Iterator it = allReferences.iterator(); while( it.hasNext() ) { ArrayList refs = (ArrayList)it.next(); if( refs != null ) { Iterator rit = refs.iterator(); while( rit.hasNext() ) { String aReference = (String)rit.next(); if( m_engine.pageExists( aReference ) == false ) uncreated.add( aReference ); } } } return( uncreated ); } /** * Find all pages that refer to this page. Returns null if the page * does not exist or is not referenced at all, otherwise returns a * collection containint page names (String) that refer to this one. */ public synchronized Collection findReferrers( String pagename ) { HashSet refs = (HashSet)m_referredBy.get( pagename ); if( refs == null || refs.isEmpty() ) return( null ); else return( refs ); } /** * Test method: dumps the contents of our link lists to stdout. * This method is NOT synchronized, and should be used in testing * with one user, one WikiEngine only. */ // FIXME: Remove, not good putting debug code in distribution. }
package com.erigitic.config; import com.google.inject.Inject; import ninja.leaping.configurate.ConfigurationNode; import ninja.leaping.configurate.commented.CommentedConfigurationNode; import ninja.leaping.configurate.hocon.HoconConfigurationLoader; import ninja.leaping.configurate.loader.ConfigurationLoader; import org.slf4j.Logger; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.event.entity.player.PlayerJoinEvent; import org.spongepowered.api.service.config.DefaultConfig; import java.io.File; import java.io.IOException; public class AccountManager { @Inject private Logger logger; //Load the default config so we grab the parent directory. private File accountsConfig; private ConfigurationLoader<CommentedConfigurationNode> configManager; private ConfigurationNode config = null; /** * Default Constructor so we can access this class from elsewhere */ public AccountManager() { } /** * Setup the config file that will contain the user accounts. These accounts will contain the users money amount. */ public void setupConfig() { accountsConfig = new File("config/TotalEconomy/accounts.conf"); configManager = HoconConfigurationLoader.builder().setFile(accountsConfig).build(); try { if (!accountsConfig.exists()) { accountsConfig.createNewFile(); } } catch (IOException e) { logger.warn("ERROR: Could not load/create accounts config file!"); } } public void createAccount(Player player) { try { config = configManager.load(); if (config.getNode(player.getName(), "balance").getValue() == null) { //TODO: Set balance to the default config defined starting balance config.getNode(player.getName(), "balance").setValue("0"); } configManager.save(config); } catch (IOException e) { logger.warn("ERROR: Could not create account!"); } } }
package org.chromium.content.browser; import android.content.Context; import android.util.Log; import android.util.SparseIntArray; import android.view.Surface; import java.util.ArrayList; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.chromium.base.CalledByNative; import org.chromium.base.JNINamespace; import org.chromium.base.ThreadUtils; import org.chromium.content.app.ChildProcessService; import org.chromium.content.app.PrivilegedProcessService; import org.chromium.content.app.SandboxedProcessService; import org.chromium.content.common.IChildProcessCallback; import org.chromium.content.common.IChildProcessService; /** * This class provides the method to start/stop ChildProcess called by native. */ @JNINamespace("content") public class ChildProcessLauncher { private static String TAG = "ChildProcessLauncher"; private static final int CALLBACK_FOR_UNKNOWN_PROCESS = 0; private static final int CALLBACK_FOR_GPU_PROCESS = 1; private static final int CALLBACK_FOR_RENDERER_PROCESS = 2; private static final String SWITCH_PROCESS_TYPE = "type"; private static final String SWITCH_PPAPI_BROKER_PROCESS = "ppapi-broker"; private static final String SWITCH_RENDERER_PROCESS = "renderer"; private static final String SWITCH_GPU_PROCESS = "gpu-process"; // The upper limit on the number of simultaneous sandboxed and privileged child service process // instances supported. Each limit must not exceed total number of SandboxedProcessServiceX // classes and PrivilegedProcessServiceX classes declared in this package and defined as // services in the embedding application's manifest file. // (See {@link ChildProcessService} for more details on defining the services.) /* package */ static final int MAX_REGISTERED_SANDBOXED_SERVICES = 13; /* package */ static final int MAX_REGISTERED_PRIVILEGED_SERVICES = 3; private static class ChildConnectionAllocator { // Connections to services. Indices of the array correspond to the service numbers. private ChildProcessConnection[] mChildProcessConnections; // The list of free (not bound) service indices. When looking for a free service, the first // index in that list should be used. When a service is unbound, its index is added to the // end of the list. This is so that we avoid immediately reusing the freed service (see // unbound for a short time. If a new connection to the same service is bound at that point, // the process is reused and bad things happen (mostly static variables are set when we // don't expect them to). // SHOULD BE ACCESSED WITH mConnectionLock. private ArrayList<Integer> mFreeConnectionIndices; private final Object mConnectionLock = new Object(); private Class<? extends ChildProcessService> mChildClass; private final boolean mInSandbox; public ChildConnectionAllocator(boolean inSandbox) { int numChildServices = inSandbox ? MAX_REGISTERED_SANDBOXED_SERVICES : MAX_REGISTERED_PRIVILEGED_SERVICES; mChildProcessConnections = new ChildProcessConnection[numChildServices]; mFreeConnectionIndices = new ArrayList<Integer>(numChildServices); for (int i = 0; i < numChildServices; i++) { mFreeConnectionIndices.add(i); } setServiceClass(inSandbox ? SandboxedProcessService.class : PrivilegedProcessService.class); mInSandbox = inSandbox; } public void setServiceClass(Class<? extends ChildProcessService> childClass) { mChildClass = childClass; } public ChildProcessConnection allocate( Context context, ChildProcessConnection.DeathCallback deathCallback) { synchronized(mConnectionLock) { if (mFreeConnectionIndices.isEmpty()) { Log.w(TAG, "Ran out of service." ); return null; } int slot = mFreeConnectionIndices.remove(0); assert mChildProcessConnections[slot] == null; mChildProcessConnections[slot] = new ChildProcessConnection(context, slot, mInSandbox, deathCallback, mChildClass); return mChildProcessConnections[slot]; } } public void free(ChildProcessConnection connection) { synchronized(mConnectionLock) { int slot = connection.getServiceNumber(); if (mChildProcessConnections[slot] != connection) { int occupier = mChildProcessConnections[slot] == null ? -1 : mChildProcessConnections[slot].getServiceNumber(); Log.e(TAG, "Unable to find connection to free in slot: " + slot + " already occupied by service: " + occupier); assert false; } else { mChildProcessConnections[slot] = null; assert !mFreeConnectionIndices.contains(slot); mFreeConnectionIndices.add(slot); } } } } // Service class for child process. As the default value it uses SandboxedProcessService0 and // PrivilegedProcessService0. private static final ChildConnectionAllocator sSandboxedChildConnectionAllocator = new ChildConnectionAllocator(true); private static final ChildConnectionAllocator sPrivilegedChildConnectionAllocator = new ChildConnectionAllocator(false); private static boolean sConnectionAllocated = false; // Sets service class for sandboxed service and privileged service. public static void setChildProcessClass( Class<? extends SandboxedProcessService> sandboxedServiceClass, Class<? extends PrivilegedProcessService> privilegedServiceClass) { // We should guarantee this is called before allocating connection. assert !sConnectionAllocated; sSandboxedChildConnectionAllocator.setServiceClass(sandboxedServiceClass); sPrivilegedChildConnectionAllocator.setServiceClass(privilegedServiceClass); } private static ChildConnectionAllocator getConnectionAllocator(boolean inSandbox) { return inSandbox ? sSandboxedChildConnectionAllocator : sPrivilegedChildConnectionAllocator; } private static ChildProcessConnection allocateConnection(Context context, boolean inSandbox) { ChildProcessConnection.DeathCallback deathCallback = new ChildProcessConnection.DeathCallback() { @Override public void onChildProcessDied(int pid) { stop(pid); } }; sConnectionAllocated = true; return getConnectionAllocator(inSandbox).allocate(context, deathCallback); } private static ChildProcessConnection allocateBoundConnection(Context context, String[] commandLine, boolean inSandbox) { ChildProcessConnection connection = allocateConnection(context, inSandbox); if (connection != null) { connection.start(commandLine); } return connection; } private static void freeConnection(ChildProcessConnection connection) { if (connection == null) { return; } getConnectionAllocator(connection.isInSandbox()).free(connection); return; } // Represents an invalid process handle; same as base/process/process.h kNullProcessHandle. private static final int NULL_PROCESS_HANDLE = 0; // Map from pid to ChildService connection. private static Map<Integer, ChildProcessConnection> sServiceMap = new ConcurrentHashMap<Integer, ChildProcessConnection>(); // Map from pid to the count of oom bindings. "Oom binding" is a binding that raises the process // oom priority so that it shouldn't be killed by the OS out-of-memory killer under normal // conditions (it can still be killed under drastic memory pressure). private static SparseIntArray sOomBindingCount = new SparseIntArray(); // A pre-allocated and pre-bound connection ready for connection setup, or null. private static ChildProcessConnection sSpareSandboxedConnection = null; /** * Returns the child process service interface for the given pid. This may be called on * any thread, but the caller must assume that the service can disconnect at any time. All * service calls should catch and handle android.os.RemoteException. * * @param pid The pid (process handle) of the service obtained from {@link #start}. * @return The IChildProcessService or null if the service no longer exists. */ public static IChildProcessService getChildService(int pid) { ChildProcessConnection connection = sServiceMap.get(pid); if (connection != null) { return connection.getService(); } return null; } /** * Should be called early in startup so the work needed to spawn the child process can be done * in parallel to other startup work. Must not be called on the UI thread. Spare connection is * created in sandboxed child process. * @param context the application context used for the connection. */ public static void warmUp(Context context) { synchronized (ChildProcessLauncher.class) { assert !ThreadUtils.runningOnUiThread(); if (sSpareSandboxedConnection == null) { sSpareSandboxedConnection = allocateBoundConnection(context, null, true); } } } private static String getSwitchValue(final String[] commandLine, String switchKey) { if (commandLine == null || switchKey == null) { return null; } // This format should be matched with the one defined in command_line.h. final String switchKeyPrefix = "--" + switchKey + "="; for (String command : commandLine) { if (command != null && command.startsWith(switchKeyPrefix)) { return command.substring(switchKeyPrefix.length()); } } return null; } /** * Spawns and connects to a child process. May be called on any thread. It will not block, but * will instead callback to {@link #nativeOnChildProcessStarted} when the connection is * established. Note this callback will not necessarily be from the same thread (currently it * always comes from the main thread). * * @param context Context used to obtain the application context. * @param commandLine The child process command line argv. * @param file_ids The ID that should be used when mapping files in the created process. * @param file_fds The file descriptors that should be mapped in the created process. * @param file_auto_close Whether the file descriptors should be closed once they were passed to * the created process. * @param clientContext Arbitrary parameter used by the client to distinguish this connection. */ @CalledByNative static void start( Context context, final String[] commandLine, int[] fileIds, int[] fileFds, boolean[] fileAutoClose, final int clientContext) { assert fileIds.length == fileFds.length && fileFds.length == fileAutoClose.length; FileDescriptorInfo[] filesToBeMapped = new FileDescriptorInfo[fileFds.length]; for (int i = 0; i < fileFds.length; i++) { filesToBeMapped[i] = new FileDescriptorInfo(fileIds[i], fileFds[i], fileAutoClose[i]); } assert clientContext != 0; int callbackType = CALLBACK_FOR_UNKNOWN_PROCESS; boolean inSandbox = true; String processType = getSwitchValue(commandLine, SWITCH_PROCESS_TYPE); if (SWITCH_RENDERER_PROCESS.equals(processType)) { callbackType = CALLBACK_FOR_RENDERER_PROCESS; } else if (SWITCH_GPU_PROCESS.equals(processType)) { callbackType = CALLBACK_FOR_GPU_PROCESS; } else if (SWITCH_PPAPI_BROKER_PROCESS.equals(processType)) { inSandbox = false; } ChildProcessConnection allocatedConnection = null; synchronized (ChildProcessLauncher.class) { if (inSandbox) { allocatedConnection = sSpareSandboxedConnection; sSpareSandboxedConnection = null; } } if (allocatedConnection == null) { allocatedConnection = allocateBoundConnection(context, commandLine, inSandbox); if (allocatedConnection == null) { // Notify the native code so it can free the heap allocated callback. nativeOnChildProcessStarted(clientContext, 0); return; } } final ChildProcessConnection connection = allocatedConnection; Log.d(TAG, "Setting up connection to process: slot=" + connection.getServiceNumber()); ChildProcessConnection.ConnectionCallbacks connectionCallbacks = new ChildProcessConnection.ConnectionCallbacks() { public void onConnected(int pid, int oomBindingCount) { Log.d(TAG, "on connect callback, pid=" + pid + " context=" + clientContext); if (pid != NULL_PROCESS_HANDLE) { sOomBindingCount.put(pid, oomBindingCount); sServiceMap.put(pid, connection); } else { freeConnection(connection); } nativeOnChildProcessStarted(clientContext, pid); } public void onOomBindingAdded(int pid) { if (pid != NULL_PROCESS_HANDLE) { sOomBindingCount.put(pid, sOomBindingCount.get(pid) + 1); } } public void onOomBindingRemoved(int pid) { if (pid != NULL_PROCESS_HANDLE) { int count = sOomBindingCount.get(pid, -1); assert count > 0; count if (count > 0) { sOomBindingCount.put(pid, count); } else { sOomBindingCount.delete(pid); } } } }; // TODO(sievers): Revisit this as it doesn't correctly handle the utility process // assert callbackType != CALLBACK_FOR_UNKNOWN_PROCESS; connection.setupConnection(commandLine, filesToBeMapped, createCallback(callbackType), connectionCallbacks); } /** * Terminates a child process. This may be called from any thread. * * @param pid The pid (process handle) of the service connection obtained from {@link #start}. */ @CalledByNative static void stop(int pid) { Log.d(TAG, "stopping child connection: pid=" + pid); ChildProcessConnection connection = sServiceMap.remove(pid); if (connection == null) { LogPidWarning(pid, "Tried to stop non-existent connection"); return; } connection.stop(); freeConnection(connection); } /** * Remove the initial child process binding. Child processes are bound with initial binding to * protect them from getting killed before they are put to use. This method allows to remove the * binding once it is no longer needed. */ static void removeInitialBinding(int pid) { ChildProcessConnection connection = sServiceMap.get(pid); if (connection == null) { LogPidWarning(pid, "Tried to remove a binding for a non-existent connection"); return; } connection.removeInitialBinding(); } /** * Bind a child process as a high priority process so that it has the same priority as the main * process. This can be used for the foreground renderer process to distinguish it from the the * background renderer process. * * @param pid The process handle of the service connection obtained from {@link #start}. */ static void bindAsHighPriority(int pid) { ChildProcessConnection connection = sServiceMap.get(pid); if (connection == null) { LogPidWarning(pid, "Tried to bind a non-existent connection"); return; } connection.attachAsActive(); } /** * Unbind a high priority process which is bound by {@link #bindAsHighPriority}. * * @param pid The process handle of the service obtained from {@link #start}. */ static void unbindAsHighPriority(int pid) { ChildProcessConnection connection = sServiceMap.get(pid); if (connection == null) { LogPidWarning(pid, "Tried to unbind non-existent connection"); return; } connection.detachAsActive(); } /** * @return True iff the given service process is protected from the out-of-memory killing, or it * was protected from it when it died. */ static boolean isOomProtected(int pid) { return sOomBindingCount.get(pid) > 0; } /** * This implementation is used to receive callbacks from the remote service. */ private static IChildProcessCallback createCallback(final int callbackType) { return new IChildProcessCallback.Stub() { /** * This is called by the remote service regularly to tell us about new values. Note that * IPC calls are dispatched through a thread pool running in each process, so the code * executing here will NOT be running in our main thread -- so, to update the UI, we * need to use a Handler. */ @Override public void establishSurfacePeer( int pid, Surface surface, int primaryID, int secondaryID) { // Do not allow a malicious renderer to connect to a producer. This is only used // from stream textures managed by the GPU process. if (callbackType != CALLBACK_FOR_GPU_PROCESS) { Log.e(TAG, "Illegal callback for non-GPU process."); return; } nativeEstablishSurfacePeer(pid, surface, primaryID, secondaryID); } @Override public Surface getViewSurface(int surfaceId) { // Do not allow a malicious renderer to get to our view surface. if (callbackType != CALLBACK_FOR_GPU_PROCESS) { Log.e(TAG, "Illegal callback for non-GPU process."); return null; } return nativeGetViewSurface(surfaceId); } }; }; private static void LogPidWarning(int pid, String message) { // This class is effectively a no-op in single process mode, so don't log warnings there. if (pid > 0 && !nativeIsSingleProcess()) { Log.w(TAG, message + ", pid=" + pid); } } private static native void nativeOnChildProcessStarted(int clientContext, int pid); private static native Surface nativeGetViewSurface(int surfaceId); private static native void nativeEstablishSurfacePeer( int pid, Surface surface, int primaryID, int secondaryID); private static native boolean nativeIsSingleProcess(); }
package com.esotericsoftware.clippy; import static com.esotericsoftware.clippy.util.Util.*; import static com.esotericsoftware.minlog.Log.*; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map.Entry; import com.esotericsoftware.clippy.PhilipsHue.PhilipsHueTimeline; import com.esotericsoftware.clippy.util.ColorTimeline; import com.esotericsoftware.clippy.util.Sun; import com.esotericsoftware.jsonbeans.Json; import com.esotericsoftware.jsonbeans.JsonException; import com.esotericsoftware.jsonbeans.JsonReader; import com.esotericsoftware.jsonbeans.JsonSerializable; import com.esotericsoftware.jsonbeans.JsonValue; import com.esotericsoftware.jsonbeans.JsonWriter; import com.esotericsoftware.minlog.Log; /** @author Nathan Sweet */ public class Config { static public final Clippy clippy = Clippy.instance; static private final File configFile = new File(System.getProperty("user.home"), ".clippy/config.json"); public boolean allowDuplicateClips; public int maxLengthToStore = 1024 * 1024; // 1 MB public String log = "info"; public String toggleHotkey = "ctrl shift alt Z"; public String uploadHotkey = "ctrl shift V"; public int popupWidth = 640; public int popupCount = 20; public int popupSearchCount = 60; public boolean popupDefaultNumbers; public String popupHotkey = "ctrl shift INSERT"; public String font = "Consolas-14"; public String screenshotHotkey = null; public String screenshotAppHotkey = "ctrl alt shift BACK_SLASH"; public String screenshotRegionHotkey = "ctrl alt BACK_SLASH"; public String screenshotLastRegionHotkey = "ctrl shift BACK_SLASH"; public ImageUpload imageUpload = ImageUpload.imgur; public TextUpload textUpload = TextUpload.pastebin; public FileUpload fileUpload = null; public boolean pasteAfterUpload = true; public boolean uploadProgressBar = true; public String pastebinDevKey = "c835896db1ea7dea6dd60b1c4412f1c3"; public String pastebinFormat = "text"; public String pastebinPrivate = "1"; public String pastebinExpire = "N"; public boolean pastebinRaw = true; public String ftpServer; public int ftpPort; public String ftpUser; public String ftpPassword; public String ftpDir; public String ftpUrl; public int breakWarningMinutes = 55; public String breakStartSound = "breakStart"; public String breakFlashSound = "breakFlash"; public String breakEndSound = "breakEnd"; public int breakReminderMinutes = 5; public int breakResetMinutes = 5; public HashMap<String, ColorTimesReference> colorTimelines; public ColorTimesReference gamma; public boolean philipsHueEnabled; public int philipsHueDisableMinutes = 90; public int philipsHueSwitchCheckMillis = 1000; public ArrayList<PhilipsHueLights> philipsHue; public boolean tobiiEnabled; public String tobiiClickHotkey = "CAPS_LOCK"; public float tobiiHeadSensitivityX = 6; public float tobiiHeadSensitivityY = 8; public String dnsUser; public String dnsPassword; public String dnsID; public int dnsMinutes = 30; public String pluginClass; public Config () { if (configFile.exists()) { JsonValue root = new JsonReader().parse(configFile); if (root != null) { try { json.readFields(this, root); } catch (Exception ex) { if (ERROR) error("Unable to read config.json.", ex); Runtime.getRuntime().halt(0); } } } else { gamma = new ColorTimesReference(); gamma.times = new ArrayList(); gamma.times.add(new ColorTime("5:30am", 1, 1, 0.7f, 0.6f)); gamma.times.add(new ColorTime("6:00am", 1, 1, 1, 1)); gamma.times.add(new ColorTime("6:00pm", 1, 1, 1, 1)); gamma.times.add(new ColorTime("9:00pm", 1, 1, 0.7f, 0.6f)); // Save default config file. configFile.getParentFile().mkdirs(); try { writeJson(this, configFile); } catch (Exception ex) { if (WARN) warn("Unable to write config.json.", ex); } } try { if (System.getProperty("dev") != null) Log.TRACE(); else Log.set((Integer)Log.class.getField("LEVEL_" + log.toUpperCase()).get(null)); } catch (Exception ex) { if (WARN) warn("Unable to set logging level.", ex); } if (TRACE) trace("Config file: " + configFile.getAbsolutePath()); } static public enum ImageUpload { ftp, sftp, imgur } static public enum TextUpload { ftp, sftp, pastebin } static public enum FileUpload { ftp, sftp } static public class ColorTimesReference { public String name; public ArrayList<ColorTime> times; public ArrayList<ColorTime> getTimes () { if (name != null) { ArrayList<ColorTime> times = clippy.config.colorTimelines.get(name).getTimes(); if (times == null) throw new JsonException("Color timeline not found: " + name); Collections.sort(times); return times; } return times; } } static public class ColorTime implements com.esotericsoftware.jsonbeans.JsonSerializable, Comparable<ColorTime> { static private final SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mma"); String time; public float brightness, r, g, b, kelvin; public Power power; public transient int dayMillis = -1, sunrise, sunset; public ColorTime () { } public ColorTime (String time, float brightness, float r, float g, float b) { this.time = time; this.brightness = brightness; this.r = r; this.g = g; this.b = b; } public void write (Json json) { // Only written for default gamma config. JsonWriter writer = json.getWriter(); try { writer.set("time", time); writer.set("brightness", brightness); writer.set("r", r); writer.set("g", g); writer.set("b", b); } catch (IOException ex) { throw new JsonException(ex); } } public void read (Json json, JsonValue jsonData) { json.readFields(this, jsonData); if (kelvin != 0) { float[] rgb = ColorTimeline.kelvinToRGB(kelvin); r = rgb[0]; g = rgb[1]; b = rgb[2]; } String time = this.time; if (time == null) return; if (time.startsWith("sunrise") || time.startsWith("sunset")) { double latitude; int add = 0; try { String[] values = time.split(":"); latitude = Double.parseDouble(values[1]); if (values[0].contains("+")) add = Integer.parseInt(values[0].split("\\+")[1]); if (values[0].contains("-")) add = -Integer.parseInt(values[0].split("\\-")[1]); } catch (Exception ex) { throw new RuntimeException("Invalid color time: " + time, ex); } Date date = new Date(); Calendar calendar = Calendar.getInstance(); if (time.startsWith("sunrise")) { calendar.setTime(Sun.sunrise(latitude, date.getYear(), date.getMonth(), date.getDate())); } else { calendar.setTime(Sun.sunset(latitude, date.getYear(), date.getMonth(), date.getDate())); } calendar.add(Calendar.MINUTE, add); time = dateFormat.format(calendar.getTime()).toLowerCase(); } boolean pm = time.contains("pm"); String[] values = time.replace("am", "").replace("pm", "").split(":"); if (values.length != 2) throw new RuntimeException("Invalid gamma time: " + time); try { int hour = Integer.parseInt(values[0]); if (hour < 0 || hour >= 24) hour = 0; if (pm) { if (hour < 12) hour += 12; } else if (hour == 12) hour = 0; int minute = Integer.parseInt(values[1]); if (minute < 0 || minute > 60) minute = 0; dayMillis = hour * 60 * 60 * 1000 + minute * 60 * 1000; } catch (NumberFormatException ex) { throw new RuntimeException("Invalid color time: " + time, ex); } } public int compareTo (ColorTime other) { return dayMillis - other.dayMillis; } public String toString () { String timeString; if (dayMillis < 0) timeString = ""; else timeString = (dayMillis / 3600000) + ":" + (dayMillis % 3600000) / 60000 + ", "; if (kelvin != 0) return "[" + timeString + kelvin + "K]"; else return "[" + timeString + r + "," + g + "," + b + "]"; } static public enum Power { on, off, unchanged } } static public class PhilipsHueLights implements com.esotericsoftware.jsonbeans.JsonSerializable { /** May be null to specify all lights. Prefix with "group:" for a group name. */ public String name; public String model; /** May be null. */ public String switchName; /** May be null. */ public HashMap<String, ColorTimesReference> times; public transient PhilipsHueTimeline timeline; public void write (Json json) { json.writeField(this, "name"); json.writeField(this, "model"); json.writeField(this, "switchName", "switch"); try { json.getWriter().object("timelines"); for (Entry<String, ColorTimesReference> entry : times.entrySet()) json.writeValue(entry.getKey(), entry.getValue(), ArrayList.class, ColorTime.class); json.getWriter().pop(); } catch (IOException ex) { throw new JsonException(ex); } } public void read (Json json, JsonValue data) { json.readField(this, "name", data); json.readField(this, "model", data); json.readField(this, "switchName", "switch", null, data); times = new HashMap(); for (JsonValue map = data.getChild("timelines"); map != null; map = map.next) times.put(map.name, json.readValue(ColorTimesReference.class, map)); } } }
package com.example.gametel_server; import java.io.BufferedReader; import java.io.IOException; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.mortbay.jetty.Connector; import org.mortbay.jetty.Request; import org.mortbay.jetty.Server; import org.mortbay.jetty.bio.SocketConnector; import org.mortbay.jetty.handler.AbstractHandler; import android.test.ActivityInstrumentationTestCase2; import android.util.Log; import com.jayway.android.robotium.solo.Solo; @SuppressWarnings("rawtypes") public class TheTest extends ActivityInstrumentationTestCase2 { private static Class<?> launcherActivityClass; static { try { launcherActivityClass = Class.forName(TestRunInformation.getFullLauncherName()); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") public TheTest() throws ClassNotFoundException { super(TestRunInformation.getPackageName(), launcherActivityClass); } private Solo solo; private Server server; @Override protected void setUp() throws Exception { solo = new Solo(getInstrumentation(), getActivity()); } public void testCanOpenSettings() { server = new Server(); try { server.setHandler(new HelloWorld()); server.addConnector(createConnector()); server.start(); log("Started the server.."); server.join(); } catch (Exception e) { e.printStackTrace(); } log("Finished running the test."); } private Connector createConnector() { SocketConnector socketConnector = new SocketConnector(); socketConnector.setPort(54767); socketConnector.setAcceptors(1); return socketConnector; } public class HelloWorld extends AbstractHandler { @Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, int arg3) throws IOException, ServletException { log("Request Path: %s", request.getPathInfo()); log("ContentLength = %d", request.getContentLength()); log("ContentType = %s", request.getContentType()); final StringBuilder stringBuilder = new StringBuilder(); final BufferedReader reader = request.getReader(); String line = null; while (null != (line = reader.readLine())) { stringBuilder.append(line); } log("Content = \n\n%s", stringBuilder.toString()); final Map params = request.getParameterMap(); for (final Object key : params.keySet()) { log("%s = %s", key, params.get(key).toString()); } response.setContentType("application/json;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("{title: 'Hello World', sender: 'Android'}"); log("I just invoked this from my browser on my computer."); ((Request) request).setHandled(true); if (request.getPathInfo().equals("/kill")) { try { response.flushBuffer(); server.stop(); } catch (Exception e) { e.printStackTrace(); } } } } private void log(final String message, final Object... args) { Log.v(getClass().getName(), String.format(message, args)); } @Override public void tearDown() throws Exception { solo.finishOpenedActivities(); } }
package continuum.rest.http.netty; import continuum.rest.http.HttpServerConfig; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpContentCompressor; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; /** * Initializes a netty server */ public class NettyHttpServerInitializer extends ChannelInitializer<SocketChannel> { private final HttpServerConfig config; public NettyHttpServerInitializer(HttpServerConfig config) { this.config = config; } @Override public void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpRequestDecoder()); p.addLast(new HttpResponseEncoder()); p.addLast(new HttpContentCompressor()); //p.addLast(new HttpServerCodec()); p.addLast(new NettyHttpServerHandler(config)); } }
package com.gh4a.loader; import java.util.ArrayList; import java.util.Collection; import org.eclipse.egit.github.core.client.NoSuchPageException; import org.eclipse.egit.github.core.client.PageIterator; import android.content.Context; import android.support.v4.content.AsyncTaskLoader; import android.util.Log; import com.gh4a.Constants; public class PageIteratorLoader<T> extends AsyncTaskLoader<LoaderResult<PageIteratorLoader<T>.LoadedPage<T>>> { private PageIterator<T> mPageIterator; private ArrayList<T> mPreviouslyLoadedData; public class LoadedPage<T> { public final Collection<T> results; public final boolean hasMoreData; private LoadedPage(Collection<T> r, boolean hmd) { results = r; hasMoreData = hmd; } } public PageIteratorLoader(Context context, PageIterator<T> pageIterator) { super(context); mPageIterator = pageIterator; mPreviouslyLoadedData = new ArrayList<>(); onContentChanged(); } @Override public void onContentChanged() { super.onContentChanged(); mPageIterator.reset(); mPreviouslyLoadedData.clear(); } @Override protected void onReset() { super.onReset(); mPageIterator.reset(); mPreviouslyLoadedData.clear(); } @Override public LoaderResult<LoadedPage<T>> loadInBackground() { if (mPageIterator.hasNext()) { try { Collection<T> newData = mPageIterator.next(); mPreviouslyLoadedData = new ArrayList<>(mPreviouslyLoadedData); mPreviouslyLoadedData.addAll(newData); } catch (NoSuchPageException e) { // should only happen in case of an empty repo return new LoaderResult<>(new LoadedPage<>(mPreviouslyLoadedData, false)); } catch (Exception e) { Log.e(Constants.LOG_TAG, e.getMessage(), e); return new LoaderResult<>(e); } } return new LoaderResult<>(new LoadedPage<>(mPreviouslyLoadedData, mPageIterator.hasNext())); } @Override protected void onStartLoading() { if (takeContentChanged()) { forceLoad(); } } @Override protected void onStopLoading() { cancelLoad(); } }
package com.yahoo.vespa.hosted.controller.api.role; import com.yahoo.restapi.Path; import java.net.URI; import java.util.EnumSet; import java.util.List; import java.util.Optional; import java.util.Set; /** * This declares and groups all known REST API paths in the controller. * * When creating a new API, its paths must be added here and a policy must be declared in {@link Policy}. * * @author mpolden * @author jonmv */ enum PathGroup { /** Paths exclusive to operators (including read), used for system management. */ classifiedOperator("/application/v4/notifications", "/configserver/v1/{*}", "/deployment/v1/{*}"), /** Paths used for system management by operators. */ operator("/controller/v1/{*}", "/flags/v1/{*}", "/loadbalancers/v1/{*}", "/nodes/v2/{*}", "/orchestrator/v1/{*}", "/os/v1/{*}", "/provision/v2/{*}", "/zone/v2/{*}", "/routing/v1/", "/routing/v1/status/environment/{*}", "/routing/v1/inactive/environment/{*}", "/state/v1/{*}", "/changemanagement/v1/{*}"), /** Paths used for creating and reading user resources. */ user("/application/v4/user", "/athenz/v1/{*}"), /** Paths used for creating tenants with proper access control. */ tenant(Matcher.tenant, "/application/v4/tenant/{tenant}"), /** Paths used for user management on the tenant level. */ tenantUsers(Matcher.tenant, "/user/v1/tenant/{tenant}"), /** Paths used by tenant administrators. */ tenantInfo(Matcher.tenant, "/application/v4/tenant/{tenant}/application/", "/application/v4/tenant/{tenant}/info/", "/application/v4/tenant/{tenant}/info/profile", "/application/v4/tenant/{tenant}/info/billing", "/application/v4/tenant/{tenant}/notifications", "/routing/v1/status/tenant/{tenant}/{*}"), tenantKeys(Matcher.tenant, "/application/v4/tenant/{tenant}/key/"), tenantArchiveAccess(Matcher.tenant, "/application/v4/tenant/{tenant}/archive-access"), billingToken(Matcher.tenant, "/billing/v1/tenant/{tenant}/token"), billingInstrument(Matcher.tenant, "/billing/v1/tenant/{tenant}/instrument/{*}"), billingPlan(Matcher.tenant, "/billing/v1/tenant/{tenant}/plan/{*}"), billingCollection(Matcher.tenant, "/billing/v1/tenant/{tenant}/collection/{*}"), billingList(Matcher.tenant, "/billing/v1/tenant/{tenant}/billing/{*}"), billing(Matcher.tenant, "/billing/v2/tenant/{tenant}/{*}"), accountant("/billing/v2/accountant/{*}"), applicationKeys(Matcher.tenant, Matcher.application, "/application/v4/tenant/{tenant}/application/{application}/key/"), /** Path for the base application resource. */ application(Matcher.tenant, Matcher.application, "/application/v4/tenant/{tenant}/application/{application}", "/application/v4/tenant/{tenant}/application/{application}/instance/", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}"), /** Paths used for user management on the application level. */ applicationUsers(Matcher.tenant, Matcher.application, "/user/v1/tenant/{tenant}/application/{application}"), /** Paths used by application administrators. */ applicationInfo(Matcher.tenant, Matcher.application, "/application/v4/tenant/{tenant}/application/{application}/submit/{build}", "/application/v4/tenant/{tenant}/application/{application}/package", "/application/v4/tenant/{tenant}/application/{application}/diff/{number}", "/application/v4/tenant/{tenant}/application/{application}/compile-version", "/application/v4/tenant/{tenant}/application/{application}/deployment", "/application/v4/tenant/{tenant}/application/{application}/deploying/{*}", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/deploying/{*}", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/job/{*}", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/{environment}/region/{region}/nodes", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/{environment}/region/{region}/clusters", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/{environment}/region/{region}/content/{*}", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/{environment}/region/{region}/logs", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/{environment}/region/{region}/orchestrator", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/{environment}/region/{region}/suspended", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/{environment}/region/{region}/service/{*}", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/{environment}/region/{region}/access/support", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/{environment}/region/{region}/global-rotation/{*}", "/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{ignored}/nodes", "/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{ignored}/clusters", "/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{ignored}/logs", "/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{ignored}/metrics", "/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{ignored}/suspended", "/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{ignored}/service/{*}", "/application/v4/tenant/{tenant}/application/{application}/environment/{environment}/region/{region}/instance/{ignored}/global-rotation/{*}", "/application/v4/tenant/{tenant}/application/{application}/metering", "/routing/v1/inactive/tenant/{tenant}/application/{application}/instance/{ignored}/environment/prod/region/{region}"), // TODO jonmv: remove /** Path used to restart development nodes. */ developmentRestart(Matcher.tenant, Matcher.application, Matcher.instance, "/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/dev/region/{region}/restart", "/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/perf/region/{region}/restart", "/application/v4/tenant/{tenant}/application/{application}/environment/dev/region/{region}/instance/{instance}/restart", "/application/v4/tenant/{tenant}/application/{application}/environment/perf/region/{region}/instance/{instance}/restart"), // TODO jonmv: remove /** Path used to restart production nodes. */ productionRestart(Matcher.tenant, Matcher.application, "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/prod/region/{region}/restart", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/test/region/{region}/restart", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/staging/region/{region}/restart", "/application/v4/tenant/{tenant}/application/{application}/environment/prod/region/{region}/instance/{ignored}/restart", "/application/v4/tenant/{tenant}/application/{application}/environment/test/region/{region}/instance/{ignored}/restart", "/application/v4/tenant/{tenant}/application/{application}/environment/staging/region/{region}/instance/{ignored}/restart"), /** Path used to manipulate reindexing status. */ reindexing(Matcher.tenant, Matcher.application, "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/{environment}/region/{region}/reindex", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/{environment}/region/{region}/reindexing"), serviceDump(Matcher.tenant, Matcher.application, "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/{environment}/region/{region}/node/{node}/service-dump"), /** Paths used for development deployments. */ developmentDeployment(Matcher.tenant, Matcher.application, Matcher.instance, "/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/deploy/{job}", "/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/dev/region/{region}", "/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/dev/region/{region}/deploy", "/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/dev/region/{region}/suspend", "/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/perf/region/{region}", "/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/perf/region/{region}/deploy", "/application/v4/tenant/{tenant}/application/{application}/instance/{instance}/environment/perf/region/{region}/suspend", "/application/v4/tenant/{tenant}/application/{application}/environment/dev/region/{region}/instance/{instance}", "/application/v4/tenant/{tenant}/application/{application}/environment/dev/region/{region}/instance/{instance}/deploy", "/application/v4/tenant/{tenant}/application/{application}/environment/perf/region/{region}/instance/{instance}", "/application/v4/tenant/{tenant}/application/{application}/environment/perf/region/{region}/instance/{instance}/deploy"), // TODO jonmv: remove /** Paths used for production deployments. */ productionDeployment(Matcher.tenant, Matcher.application, "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/prod/region/{region}", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/prod/region/{region}/deploy", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/test/region/{region}", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/test/region/{region}/deploy", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/staging/region/{region}", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/environment/staging/region/{region}/deploy", "/application/v4/tenant/{tenant}/application/{application}/environment/prod/region/{region}/instance/{ignored}", "/application/v4/tenant/{tenant}/application/{application}/environment/prod/region/{region}/instance/{ignored}/deploy", "/application/v4/tenant/{tenant}/application/{application}/environment/test/region/{region}/instance/{ignored}", "/application/v4/tenant/{tenant}/application/{application}/environment/test/region/{region}/instance/{ignored}/deploy", "/application/v4/tenant/{tenant}/application/{application}/environment/staging/region/{region}/instance/{ignored}", "/application/v4/tenant/{tenant}/application/{application}/environment/staging/region/{region}/instance/{ignored}/deploy"), /** Paths used for continuous deployment to production. */ submission(Matcher.tenant, Matcher.application, "/application/v4/tenant/{tenant}/application/{application}/submit", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/submit"), /** Paths used for other tasks by build services. */ // TODO: This will vanish. buildService(Matcher.tenant, Matcher.application, "/application/v4/tenant/{tenant}/application/{application}/jobreport", "/application/v4/tenant/{tenant}/application/{application}/instance/{ignored}/jobreport"), /** Paths which contain (not very strictly) classified information about customers. */ classifiedTenantInfo("/application/v4/", "/application/v4/tenant/"), /** Paths providing public information. */ publicInfo("/user/v1/user", // Information about who you are. "/badge/v1/{*}", // Badges for deployment jobs. "/zone/v1/{*}", // Lists environment and regions. "/cli/v1/{*}"), // Public information for Vespa CLI. /** Paths used for deploying system-wide feature flags. */ systemFlagsDeploy("/system-flags/v1/deploy"), /** Paths used for "dry-running" system-wide feature flags. */ systemFlagsDryrun("/system-flags/v1/dryrun"), /** Paths used for receiving payment callbacks */ paymentProcessor("/payment/notification"), /** Paths used for invoice management */ hostedAccountant("/billing/v1/invoice/{*}", "/billing/v1/billing"), /** Path used for listing endpoint certificate request and re-requesting endpoint certificates */ endpointCertificates("/endpointcertificates/"), /** Path used for secret store management */ secretStore(Matcher.tenant, "/application/v4/tenant/{tenant}/secret-store/{*}"), /** Paths used to proxy Horizon metric requests */ horizonProxy("/horizon/v1/{*}"), /** Paths used to list and request access to tenant resources */ accessRequests(Matcher.tenant, "/application/v4/tenant/{tenant}/access/request/operator"), /** Paths used to approve requests to access tenant resources */ accessRequestApproval(Matcher.tenant, "/application/v4/tenant/{tenant}/access/approve/operator", "/application/v4/tenant/{tenant}/access/managed/operator"); final List<String> pathSpecs; final List<Matcher> matchers; PathGroup(String... pathSpecs) { this(List.of(), List.of(pathSpecs)); } PathGroup(Matcher first, String... pathSpecs) { this(List.of(first), List.of(pathSpecs)); } PathGroup(Matcher first, Matcher second, String... pathSpecs) { this(List.of(first, second), List.of(pathSpecs)); } PathGroup(Matcher first, Matcher second, Matcher third, String... pathSpecs) { this(List.of(first, second, third), List.of(pathSpecs)); } /** Creates a new path group, if the given context matchers are each present exactly once in each of the given specs. */ PathGroup(List<Matcher> matchers, List<String> pathSpecs) { this.matchers = matchers; this.pathSpecs = pathSpecs; } /** Returns path if it matches any spec in this group, with match groups set by the match. */ private Optional<Path> get(URI uri) { Path matcher = new Path(uri); for (String spec : pathSpecs) // Iterate to be sure the Path's state is that of the match. if (matcher.matches(spec)) return Optional.of(matcher); return Optional.empty(); } /** All known path groups */ static Set<PathGroup> all() { return EnumSet.allOf(PathGroup.class); } static Set<PathGroup> allExcept(PathGroup... pathGroups) { return EnumSet.complementOf(EnumSet.copyOf(List.of(pathGroups))); } static Set<PathGroup> allExcept(Set<PathGroup> pathGroups) { return EnumSet.complementOf(EnumSet.copyOf(pathGroups)); } static Set<PathGroup> operatorRestrictedPaths() { var paths = billingPathsNoToken(); paths.add(PathGroup.billingToken); paths.add(accessRequestApproval); return paths; } static Set<PathGroup> billingPathsNoToken() { return EnumSet.of( PathGroup.billingCollection, PathGroup.billingInstrument, PathGroup.billingList, PathGroup.billingPlan, PathGroup.billing, PathGroup.hostedAccountant ); } /** Returns whether this group matches path in given context */ boolean matches(URI uri, Context context) { return get(uri).map(p -> { boolean match = true; String tenant = p.get(Matcher.tenant.name); if (tenant != null && context.tenant().isPresent()) { match = context.tenant().get().value().equals(tenant); } String application = p.get(Matcher.application.name); if (application != null && context.application().isPresent()) { match &= context.application().get().value().equals(application); } String instance = p.get(Matcher.instance.name); if (instance != null && context.instance().isPresent()) { match &= context.instance().get().value().equals(instance); } return match; }).orElse(false); } /** Fragments used to match parts of a path to create a context. */ enum Matcher { tenant("{tenant}"), application("{application}"), instance("{instance}"); final String pattern; final String name; Matcher(String pattern) { this.pattern = pattern; this.name = pattern.substring(1, pattern.length() - 1); } } }
package com.haxademic.core.image; import java.awt.image.BufferedImage; import java.nio.ByteBuffer; import processing.core.PApplet; import processing.core.PConstants; import processing.core.PGraphics; import processing.core.PImage; import processing.opengl.PGL; import com.haxademic.core.draw.color.ColorHax; public class ImageUtil { public static final int BLACK_INT = -16777216; public static final int CLEAR_INT = 48356; public static final int EMPTY_INT = 0; public static int getPixelIndex( PImage image, int x, int y ) { return (int) x + y * image.width; } public static int getPixelIndex( PApplet image, int x, int y ) { return (int) x + y * image.width; } /** * Return the color int for a specific pixel of a PImage * @param image Image to grab pixel color from * @param x x pixel of the image * @param y y pixel of the image * @return The color as an int */ public static int getPixelColor( PImage image, int x, int y ) { if( x < 0 || y < 0 || x > image.width - 1 || y > image.height - 1 || image.pixels == null || image.pixels.length < getPixelIndex( image, x, y ) ) return 0; return image.pixels[ getPixelIndex( image, x, y ) ]; } public static int getPixelColor( PGraphics image, int x, int y ) { if( x < 0 || y < 0 || x > image.width - 1 || y > image.height - 1 || image.pixels == null || image.pixels.length < getPixelIndex( image, x, y ) ) return 0; return image.pixels[ getPixelIndex( image, x, y ) ]; } public static int getPixelColor( PApplet image, int x, int y ) { if( x < 0 || y < 0 || x > image.width - 1 || y > image.height - 1 || image.pixels == null || image.pixels.length < getPixelIndex( image, x, y ) ) return 0; return image.pixels[ getPixelIndex( image, x, y ) ]; } // needs testing.... public static int getPixelColorFast( PApplet p, PGraphics image, int x, int y ) { PGL pgl = image.beginPGL(); ByteBuffer buffer = ByteBuffer.allocateDirect(1 * 1 * Integer.SIZE / 8); pgl.readPixels(x, y, 1, 1, PGL.RGBA, PGL.UNSIGNED_BYTE, buffer); // get the first three bytes int r = buffer.get() & 0xFF; int g = buffer.get() & 0xFF; int b = buffer.get() & 0xFF; buffer.clear(); image.endPGL(); return p.color(r, g, b); } public static float getBrightnessForPixel( PApplet p, PImage image, int x, int y ) { return p.brightness( image.pixels[ getPixelIndex( image, x, y ) ] ) * 0.1f; } public static float colorDifference( PApplet p, int color1, int color2 ) { return (Math.abs(p.red(color1) - p.red(color2)) + Math.abs(p.green(color1) - p.green(color2)) + Math.abs(p.blue(color1) - p.blue(color2)) ) / 765f; } public static float brightnessDifference( PApplet p, int color1, int color2 ) { return Math.abs((p.red(color1) + p.green(color1) + p.blue(color1)) - (p.red(color2) + p.green(color2) + p.blue(color2))) / 765f; } public static PImage getReversePImage( PImage image ) { PImage reverse = new PImage( image.width, image.height ); for( int i=0; i < image.width; i++ ){ for(int j=0; j < image.height; j++){ reverse.set( image.width - 1 - i, j, image.get(i, j) ); } } return reverse; } public static PImage getReversePImageFast( PImage image ) { PImage reverse = new PImage( image.width, image.height ); reverse.loadPixels(); for (int i = 0; i < image.width; i++) { for (int j = 0; j < image.height; j++) { reverse.pixels[j*image.width+i] = image.pixels[(image.width - i - 1) + j*image.width]; // Reversing x to mirror the image } } reverse.updatePixels(); return reverse; } public static PImage getScaledImage( PImage image, int newWidth, int newHeight ) { PImage scaled = new PImage( newWidth, newHeight ); scaled.copy( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight ); return scaled; } public static void clearPGraphics( PGraphics pg ) { // pg.beginDraw(); pg.background(0,0); // pg.endDraw(); } public static PImage bufferedToPImage( BufferedImage bimg ) { try { PImage img = new PImage(bimg.getWidth(),bimg.getHeight(),PConstants.ARGB); bimg.getRGB(0, 0, img.width, img.height, img.pixels, 0, img.width); img.updatePixels(); return img; } catch(Exception e) { System.err.println("Can't create image from buffer"); e.printStackTrace(); } return null; } public static BufferedImage pImageToBuffered( PImage pimg ) { return (BufferedImage) pimg.getNative(); // BufferedImage dest = new BufferedImage( pimg.width, pimg.height, BufferedImage.TYPE_INT_ARGB ); // Graphics2D g2 = dest.createGraphics(); // g2.drawImage( pimg.getImage(), 0, 0, null ); // g2.finalize(); // g2.dispose(); // return dest; } public static void cropFillCopyImage( PImage src, PImage dest, boolean cropFill ) { float containerW = dest.width; float containerH = dest.height; float imageW = src.width; float imageH = src.height; float ratioW = containerW / imageW; float ratioH = containerH / imageH; float shorterRatio = ratioW > ratioH ? ratioH : ratioW; float longerRatio = ratioW > ratioH ? ratioW : ratioH; float resizedW = cropFill ? (float)Math.ceil(imageW * longerRatio) : (float)Math.ceil(imageW * shorterRatio); float resizedH = cropFill ? (float)Math.ceil(imageH * longerRatio) : (float)Math.ceil(imageH * shorterRatio); float offsetX = (float)Math.ceil((containerW - resizedW) * 0.5f); float offsetY = (float)Math.ceil((containerH - resizedH) * 0.5f); dest.copy( src, 0, 0, (int) imageW, (int) imageH, (int) offsetX, (int) offsetY, (int) resizedW, (int) resizedH ); } public static float[] getOffsetAndSizeToCrop( float containerW, float containerH, float imageW, float imageH, boolean cropFill ) { float ratioW = containerW / imageW; float ratioH = containerH / imageH; float shorterRatio = ratioW > ratioH ? ratioH : ratioW; float longerRatio = ratioW > ratioH ? ratioW : ratioH; float resizedW = (cropFill) ? (float) Math.ceil(imageW * longerRatio) : (float) Math.ceil(imageW * shorterRatio); float resizedH = cropFill ? (float) Math.ceil(imageH * longerRatio) : (float) Math.ceil(imageH * shorterRatio); float offsetX = (float) Math.ceil((containerW - resizedW) * 0.5f); float offsetY = (float) Math.ceil((containerH - resizedH) * 0.5f); return new float[]{offsetX, offsetY, resizedW, resizedH}; } public static void chromaKeyImage( PApplet p, PImage sourceImg, PImage dest ) { float threshRange = 20f; float r = 0; float g = 0; float b = 0; for( int x=0; x < sourceImg.width; x++ ){ for( int y=0; y < sourceImg.height; y++ ){ int pixelColor = ImageUtil.getPixelColor( sourceImg, x, y ); r = ColorHax.redFromColorInt( pixelColor ); g = ColorHax.greenFromColorInt( pixelColor ); b = ColorHax.blueFromColorInt( pixelColor ); // if green is greater than both other color components, black it out if( g > r && g > b ) { dest.set( x, y, p.color( 255, 0 ) ); } else if( g > r - threshRange && g > b - threshRange ) { dest.set( x, y, p.color( r, g, b ) ); } else { dest.set( x, y, p.color( r, g, b ) ); } } } } }
package org.csstudio.ui.util; import java.util.Arrays; import java.util.List; import org.csstudio.ui.util.dialogs.ExceptionDetailsErrorDialog; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.handlers.HandlerUtil; /** * Abstract class for all commands that use AdapterUtil for conversion * and displays the exception in a suitable dialog. * * @author carcassi * */ public abstract class AbstractAdaptedHandler<T> extends AbstractHandler { private final Class<T> clazz; public AbstractAdaptedHandler(Class<T> dataType) { this.clazz = dataType; } /** * Searches for the view of the given class with the given view id. * * @param clazz the view class * @param viewId the view id * @return the view * @throws PartInitException if the view was not found * @throws ClassCastException if the view is of a different type */ public static <T> T findView(Class<T> clazz, String viewId) throws PartInitException { IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchWindow window = workbench.getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); return clazz.cast(page.showView(viewId)); } @Override public Object execute(ExecutionEvent event) throws ExecutionException { ISelection selection = HandlerUtil.getActiveMenuSelection(event); try { execute(Arrays.asList(AdapterUtil.convert(selection, clazz)), event); } catch (Exception ex) { ExceptionDetailsErrorDialog.openError(HandlerUtil.getActiveShell(event), "Error executing command...", ex); } return null; } /** * Implements the command. The selection is already converted to the target class. * * @param data data in the selection * @param event event of the command */ protected abstract void execute(List<T> data, ExecutionEvent event) throws Exception; }
package org.hisp.dhis.android.core.data.server; public class RealServerMother { public static String url2_29 = "https://play.dhis2.org/2.29/api/"; public static String url2_30 = "https://play.dhis2.org/2.30/api/"; public static String url2_31 = "https://play.dhis2.org/2.31.3/api/"; public static String url2_32 = "https://play.dhis2.org/2.32.0/api/"; public static String url_dev = "https://play.dhis2.org/dev/api/"; public static String android_current = "https://play.dhis2.org/android-current/api/"; public static String url = android_current; public static String user = "android"; public static String password = "Android123"; }
package com.jmex.model.ogrexml; import static com.jmex.model.XMLUtil.getAttribute; import static com.jmex.model.XMLUtil.getChildNode; import static com.jmex.model.XMLUtil.getFloatAttribute; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXException; import com.jme.light.DirectionalLight; import com.jme.light.Light; import com.jme.light.PointLight; import com.jme.math.Matrix3f; import com.jme.math.Quaternion; import com.jme.math.Vector3f; import com.jme.renderer.ColorRGBA; import com.jme.scene.state.LightState; import com.jme.system.DisplaySystem; import com.jme.util.export.StringBoolMap; import com.jme.util.export.StringFloatMap; import com.jme.util.export.StringIntMap; import com.jme.util.export.StringStringMap; import com.jme.util.resource.RelativeResourceLocator; import com.jme.util.resource.ResourceLocator; import com.jme.util.resource.ResourceLocatorTool; import com.jmex.model.ModelFormatException; public class SceneLoader { /* The commented-out Camera loading code has been removed. If you need * that code, pull revision 645 of this file from Subversion. */ private static final Logger logger = Logger.getLogger(SceneLoader.class.getName()); /** * This method just returns null. * @deprecated This class no longer manages cameras. * @returns null */ @Deprecated public com.jme.renderer.Camera getCamera() { return null; } private Map<String, Material> materials = new HashMap<String, Material>(); private LightState ls = null; private com.jme.scene.Node scene; private Vector3f[] temp = new Vector3f[3]; private boolean modelsOnly = false; /** * @see #setModelsOnly(boolean) */ public boolean isModelsOnly() { return modelsOnly; } /** * Specify whether you want to load just models from the dotScene file. * Default behavior is to load lights and environment form the dotScene * file (i.e., modesOnly false). * <P> * If you set modelsOnly to true before running a load() method, then<UL> * <LI>No LightState will be created * <LI>Lights in the dotScene file will be ignored * <LI>The environment element of the dotScene file will be ignored * </UL> * </P> <P> * This setter must be called between SceneLoader instantiation and * .load() invocation. * </P> */ public void setModelsOnly(boolean modelsOnly) { this.modelsOnly = modelsOnly; } public SceneLoader(){ scene = new com.jme.scene.Node(); // We create with no name here, but algorithms below ensure that // getScene() will return a Node with a good name set. } private Light loadLight(Node light, Vector3f pos, Quaternion rot){ String type = getAttribute(light, "type"); Light l = null; if (type.equals("directional")){ //Vector3f dir = loadVector3(getChildNode(light, "normal")); DirectionalLight dl = new DirectionalLight(); dl.setEnabled(true); Matrix3f tempMat = rot.toRotationMatrix(); dl.setDirection(tempMat.getColumn(2)); l = dl; }else if (type.equals("point")){ PointLight pl = new PointLight(); pl.setEnabled(true); pl.setLocation(pos); l = pl; Node att = getChildNode(light, "lightAttenuation"); if (att != null){ pl.setAttenuate(true); pl.setConstant(getFloatAttribute(att, "constant")); pl.setLinear(getFloatAttribute(att, "linear")); pl.setQuadratic(getFloatAttribute(att, "quadratic")); } }else{ logger.warning("UNSUPPORTED LIGHT: "+type); } Node diffuseNode = getChildNode(light, "colourDiffuse"); if (diffuseNode != null) l.setDiffuse(loadColor(diffuseNode)); Node specularNode = getChildNode(light, "colourSpecular"); if (specularNode != null) l.setDiffuse(loadColor(specularNode)); return l; } private Vector3f loadVector3(Node vector){ Vector3f vec = new Vector3f(); vec.x = getFloatAttribute(vector, "x"); vec.y = getFloatAttribute(vector, "y"); vec.z = getFloatAttribute(vector, "z"); return vec; } private Quaternion loadQuaternion(Node quaternion){ Quaternion q = new Quaternion(); q.x = getFloatAttribute(quaternion, "x"); q.y = getFloatAttribute(quaternion, "y"); q.z = getFloatAttribute(quaternion, "z"); q.w = getFloatAttribute(quaternion, "w"); return q; } private ColorRGBA loadColor(Node color){ ColorRGBA c = new ColorRGBA(); c.r = getFloatAttribute(color, "r"); c.g = getFloatAttribute(color, "g"); c.b = getFloatAttribute(color, "b"); return c; } /** * Populates the specified jME Node with data from the specified XML Node. * <P> * The Ogre exporter and Blender generally use node-type-specific * name spaces for node names. * Consequently, the Ogre dotScene exporter generates the same name for * nodes and for the first entity child thereof. * To maintain jME-preferred scene Spatial name uniqueness, we append * the suffix "DotNode" to the node names in the dotScene file. * </P> * * @param targetJmeNode An unpopulated com.jme.scene.Node. * We will consitute the node and add its descendants. * @param sourceXmlNode XML node which children will be reaped from. */ public void loadNode(com.jme.scene.Node targetJmeNode, Node sourceXmlNode) throws IOException, ModelFormatException { Node childNode, lightNode = null; String tagName; String origNodeName; // Node name before we supply suffix, as explained // in the JavaDocs above. // First handle attributes, then element children. if (targetJmeNode.getName() == null) { // If caller has set an explicit name before calling this method, // we ignore name attr. in order to not clobber. origNodeName = getAttribute(sourceXmlNode, "name"); if (origNodeName == null) { logger.warning("dotScene node element has no name. " + "Assigning name 'dotSceneNode'"); origNodeName = "dotScene"; } targetJmeNode.setName(origNodeName.endsWith("DotNode") ? origNodeName : (origNodeName + "DotNode")); } else { origNodeName = targetJmeNode.getName(); } logger.finest("NODE(" + targetJmeNode.getName() + ")"); NodeList childList = sourceXmlNode.getChildNodes(); int childCount = childList.getLength(); for (int i = 0; i < childCount; i++) { childNode = childList.item(i); tagName = childNode.getNodeName(); if (tagName.equals("position")) { targetJmeNode.setLocalTranslation(loadVector3(childNode)); } else if (tagName.equals("quaternion")) { targetJmeNode.setLocalRotation(loadQuaternion(childNode)); } else if (tagName.equals("scale")) { targetJmeNode.setLocalScale(loadVector3(childNode)); } else if (tagName.equals("entity")) { URL url = ResourceLocatorTool.locateResource( ResourceLocatorTool.TYPE_MODEL, getAttribute(childNode, "meshFile") + ".xml"); if (url == null) { logger.warning("Invalid URL for entity child of node " + targetJmeNode.getName() + ". Skipping."); } else { OgreLoader loader = new OgreLoader(); loader.setMaterials(materials); String entityName = getAttribute(childNode, "name"); OgreEntityNode entityNode = loader.loadModel(url, (entityName == null) ? origNodeName : entityName); targetJmeNode.attachChild(entityNode); } } else if (tagName.equals("light")) { if (!modelsOnly) { lightNode = childNode; } } else if (tagName.equals("node")) { com.jme.scene.Node newNode = new com.jme.scene.Node(); //DotSceneNode newNode = new DotSceneNode(); loadNode(newNode, childNode); // This is the recurse! targetJmeNode.attachChild(newNode); } else if (tagName.equals("userData")) { Node parentNode = childNode.getParentNode(); NodeList props = childNode.getChildNodes(); StringFloatMap floatAttrMap = null; StringBoolMap boolAttrMap = null; StringIntMap intAttrMap = null; StringStringMap strAttrMap = null; for (int j=0;j<props.getLength();j++) { Node propNode = props.item(j); tagName = propNode.getNodeName(); if (tagName.equals("property")) { String propType = getAttribute(propNode, "type"); String propKey = getAttribute(propNode,"name"); String propValue = getAttribute(propNode,"data"); if (propType.equalsIgnoreCase("FLOAT") || propType.equalsIgnoreCase("TIME")) { if (floatAttrMap == null) { floatAttrMap = new StringFloatMap(); targetJmeNode.setUserData("floatSpatialAppAttrs", floatAttrMap); } floatAttrMap.put(getAttribute(propNode,"name"), new Float(getAttribute(propNode,"data"))); } else if (propType.equalsIgnoreCase("BOOL")) { if (boolAttrMap == null) { boolAttrMap = new StringBoolMap(); targetJmeNode.setUserData("boolSpatialAppAttrs", boolAttrMap); } String name = getAttribute(propNode,"name"); String attr = getAttribute(propNode,"data"); boolAttrMap.put(name, attr.equals("0")?false:true); } else if (propType.equalsIgnoreCase("INT")) { if (intAttrMap == null) { intAttrMap = new StringIntMap(); targetJmeNode.setUserData("intSpatialAppAttrs", intAttrMap); } intAttrMap.put(getAttribute(propNode,"name"), new Integer(getAttribute(propNode,"data"))); } else { if (strAttrMap == null) { strAttrMap = new StringStringMap(); targetJmeNode.setUserData("stringSpatialAppAttrs", strAttrMap); } strAttrMap.put(getAttribute(propNode,"name"), getAttribute(propNode,"data")); } } } } else if (!(childNode instanceof Text)) { logger.warning("Ignoring unexpected element '" + tagName + "' of type " + childNode.getClass().getName()); } } if (lightNode != null) { ls.attach(loadLight(lightNode, targetJmeNode.getLocalTranslation(), targetJmeNode.getLocalRotation())); } } public void loadExternals(Node externals) throws IOException{ Node item = externals.getFirstChild(); while (item != null){ if (item.getNodeName().equals("item")){ if (getAttribute(item, "type").equals("material")){ String file = getAttribute(getChildNode(item, "file"), "name"); MaterialLoader matloader = new MaterialLoader(); URL url = ResourceLocatorTool.locateResource( ResourceLocatorTool.TYPE_TEXTURE, file); logger.fine("Loading materials from '" + url + "'..."); if (url != null){ InputStream in = url.openStream(); matloader.load(in); in.close(); materials.putAll(matloader.getMaterials()); } } } item = item.getNextSibling(); } logger.fine("Loaded materials. Now have: " + materials.keySet()); } public void loadEnvironment(Node env){ if (ls == null) { throw new IllegalStateException("Light state is not set up yet"); } Node ambient = getChildNode(env, "colourAmbient"); if (ambient != null){ ls.setGlobalAmbient(loadColor(ambient)); } Node background = getChildNode(env, "colourBackground"); if (background != null){ //DisplaySystem.getDisplaySystem().getRenderer().setBackgroundColor(loadColor(background)); } } public void load(Node sceneXmlNode) throws IOException, ModelFormatException { if (!modelsOnly) { ls = DisplaySystem.getDisplaySystem() .getRenderer().createLightState(); scene.setRenderState(ls); } String version = getAttribute(sceneXmlNode, "formatVersion"); Node externals = getChildNode(sceneXmlNode, "externals"); Node nodes = getChildNode(sceneXmlNode, "nodes"); // TODO: According to the DTD, the "nodes" element may have // transformation attributes. We should not ignore them. Node environment = getChildNode(sceneXmlNode, "environment"); loadExternals(externals); if (!modelsOnly) { loadEnvironment(environment); } loadNode(scene, nodes); } /** * @return a com.jme.scene.Node populated with the aggregation of all * load() calls that have been applied to this instance. */ public com.jme.scene.Node getScene(){ return scene; } /** * Adds data from the specified dotScene file onto a scene node (which may * then be retrieved with getScene(). * * @see #getScene() */ public void load(InputStream in) throws IOException, ModelFormatException { if (scene.getName() == null) { scene.setName("OgreScene"); // Apply default name if nothing more specific applied up to this // point. } try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(in); Element rootEl = doc.getDocumentElement(); if (rootEl == null) { throw new ModelFormatException( "No root node in XML document, when trying to read '" + "scene'"); } if (!rootEl.getTagName().equals("scene")) { throw new ModelFormatException( "Input XML file does not have required root element '" + "scene'"); } load(rootEl); scene.updateGeometricState(0, true); scene.updateRenderState(); } catch (ParserConfigurationException ex) { throw new IOException("Error configuring parser"); } catch (SAXException ex) { throw new IOException("Error with xml parser"); } } /** * Convenience wrapper * * @see #load(URL) */ public void load(URI uri) throws IOException, ModelFormatException { load(uri.toURL()); } /** * Adds contents of dotScene file at specified URI onto a scene node, * automatically adding the containing directory to the resource locator * paths for the duration of the load. * The scene node may then be retrieved with getScene(). * <P> * An example of invoking this method for a filesystem file:<CODE><PRE> * ogreSceneLoader.load(file.toURL()); * </PRE></CODE> * </P> * * @see #getScene() * @see RelativeResourceLocator */ public void load(URL url) throws IOException, ModelFormatException { if (scene.getName() == null) { String urlPath = url.getPath(); if (urlPath == null) { throw new IOException("URL contains no path: " + url); } String sceneName = urlPath.replaceFirst(".*[\\\\/]", ""). replaceFirst("\\..*", ""); if (!sceneName.matches(".*(?i)scene.*")) { sceneName += "Scene"; // It's very likely that a scene file name without "scene" in // it duplicates an internal object name, so we add "Scene" to // the name to make it unique. } if (sceneName.length() < 1) { // Let load(InputStream in) apply default name logger.warning("Falling back to default scene name, since " + "failed to generate a good name from URL '" + url + "'"); } else { scene.setName(sceneName); } } ResourceLocator locator = null; try { locator = new RelativeResourceLocator(url); } catch (URISyntaxException use) { throw new IllegalArgumentException("Bad URL: " + use); } ResourceLocatorTool.addResourceLocator( ResourceLocatorTool.TYPE_TEXTURE, locator); ResourceLocatorTool.addResourceLocator( ResourceLocatorTool.TYPE_MODEL, locator); InputStream stream = null; try { stream = url.openStream(); if (stream == null) { throw new IOException("Failed to load model file '" + url + "'"); } logger.fine("Loading materials from '" + url + "'..."); load(stream); stream.close(); } finally { if (stream != null) stream.close(); ResourceLocatorTool.removeResourceLocator( ResourceLocatorTool.TYPE_TEXTURE, locator); ResourceLocatorTool.removeResourceLocator( ResourceLocatorTool.TYPE_MODEL, locator); locator = null; // Just to encourage GC } } /** * This method is provided so that users can import multiple dotScene files * and have unique top-level nodes for each load; or if you just want to * specify your own top-level node name. * <P> * This method is not necessary for uniqueness purposes if you use the * load(URL) method, unless your target URLs happen to have the same file * base name (without the preceding path and following suffix). * </P> <P> * This setter must be called between SceneLoader instantiation and * .load() invocation. * </P> */ public void setName(String newName) { scene.setName(newName); } /** * Use this method to re-use the Materials loaded by this SceneLoader for * other purposes, such as to load other dotScene or Mesh files. */ public Map<String, Material> getMaterials() { return materials; } /** * Reuse an existing Materials collection. * Materials files referred to by the dotScene will still be loaded. */ public void addMaterials(Map<String, Material> newMaterials) { materials.putAll(newMaterials); } }
package com.mamewo.malarm24; import java.io.IOException; import java.util.List; import android.app.AlertDialog; import android.app.ListActivity; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public final class PlaylistViewer extends ListActivity implements OnItemLongClickListener, OnItemClickListener, ServiceConnection { private ListView listView_; //private ArrayAdapter<String> adapter_; private MusicAdapter adapter_; private M3UPlaylist playlist_; private MalarmPlayerService player_; //R.array.tune_operation static private final int UP_INDEX = 0; static private final int DOWN_INDEX = 1; static private final int DELETE_INDEX = 2; static final private String TAG = "malarm"; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); listView_ = getListView(); listView_.setLongClickable(true); listView_.setOnItemLongClickListener(this); listView_.setOnItemClickListener(this); player_ = null; Intent intent = new Intent(this, MalarmPlayerService.class); startService(intent); //TODO: handle failure of bindService boolean result = bindService(intent, this, Context.BIND_AUTO_CREATE); Log.d(TAG, "bindService: " + result); } @Override public void onStart() { super.onStart(); Intent i = getIntent(); String which = i.getStringExtra("playlist"); int title_id = 0; if ("sleep".equals(which)) { playlist_ = MalarmPlayerService.sleepPlaylist_; title_id = R.string.sleep_playlist_viewer_title; } else { playlist_ = MalarmPlayerService.wakeupPlaylist_; title_id = R.string.wakeup_playlist_viewer_title; } adapter_ = new MusicAdapter(this, playlist_.toList()); setListAdapter(adapter_); setTitle(title_id); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.playlist_viewer_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.save_playlist: try { playlist_.save(); //TODO: localize MalarmActivity.showMessage(this, "saved"); } catch (IOException e) { //TODO: localize MalarmActivity.showMessage(this, "failed: " + e.getMessage()); } break; default: break; } return true; } //TODO: implement undo? //TODO: add selected effect @Override public boolean onItemLongClick(AdapterView<?> adapter_view, View view, int position, long id) { final int pos = position; final String title = (String)adapter_view.getItemAtPosition(pos); new AlertDialog.Builder(PlaylistViewer.this) .setTitle(title) //TODO: show detail of tune .setItems(R.array.tune_operation, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == UP_INDEX) { if (pos == 0) { //TODO: disable item return; } adapter_.remove(title); adapter_.insert(title, pos-1); playlist_.remove(pos); playlist_.insert(pos-1, title); } else if (which == DOWN_INDEX) { if (pos == adapter_.getCount()-1) { //TODO: disable item return; } adapter_.remove(title); adapter_.insert(title, pos + 1); playlist_.remove(pos); playlist_.insert(pos+1, title); } else if (which == DELETE_INDEX) { adapter_.remove(playlist_.toList().get(pos)); playlist_.remove(pos); } } }) .setNegativeButton(R.string.cancel, null) .create() .show(); return true; } @Override public void onItemClick(AdapterView<?> adapter, View view, int pos, long id) { if (null == player_) { return; } player_.playMusic(playlist_, pos, true); // Intent i = getIntent(); // String which = i.getStringExtra("playlist"); // Intent playIntent = new Intent(this, MalarmActivity.class); // playIntent.setAction(MalarmActivity.PLAY_ACTION); // playIntent.putExtra("playlist", which); // playIntent.putExtra("position", pos); // startActivity(playIntent); } final private class MusicAdapter extends ArrayAdapter<String> { public MusicAdapter(Context context) { super(context, R.layout.playlist_item); } public MusicAdapter(Context context, List<String> list) { super(context, R.layout.playlist_item, list); } public View getView(int position, View convertView, ViewGroup parent) { View view; if (null == convertView) { view = View.inflate(PlaylistViewer.this, R.layout.playlist_item, null); } else { view = convertView; } String title = getItem(position); TextView titleView = (TextView) view.findViewById(R.id.title_view); titleView.setText(title); return view; } } @Override public void onServiceConnected(ComponentName name, IBinder binder) { Log.d(TAG, "onServiceConnected"); player_ = ((MalarmPlayerService.LocalBinder)binder).getService(); } @Override public void onServiceDisconnected(ComponentName name) { Log.d(TAG, "onServiceDisconnected"); player_.clearPlayerStateListener(); player_ = null; } }
package org.hisp.dhis.android.core.category; import org.hisp.dhis.android.core.arch.handlers.IdentifiableSyncHandlerImpl; import org.hisp.dhis.android.core.arch.handlers.LinkSyncHandler; import org.hisp.dhis.android.core.common.HandleAction; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import dagger.Reusable; @Reusable final class CategoryOptionComboHandler extends IdentifiableSyncHandlerImpl<CategoryOptionCombo> { private final LinkSyncHandler<CategoryOptionComboCategoryOptionLink> categoryOptionComboCategoryOptionLinkHandler; @Inject CategoryOptionComboHandler(CategoryOptionComboStore store, LinkSyncHandler<CategoryOptionComboCategoryOptionLink> categoryOptionComboCategoryOptionLinkHandler) { super(store); this.categoryOptionComboCategoryOptionLinkHandler = categoryOptionComboCategoryOptionLinkHandler; } @Override protected void afterObjectHandled(CategoryOptionCombo optionCombo, HandleAction action) { if (optionCombo.categoryOptions() != null) { List<CategoryOptionComboCategoryOptionLink> categoryOptionComboCategoryOptionLinks = new ArrayList<>(); for (CategoryOption categoryOption : optionCombo.categoryOptions()) { categoryOptionComboCategoryOptionLinks.add(CategoryOptionComboCategoryOptionLink.builder() .categoryOptionCombo(optionCombo.uid()).categoryOption(categoryOption.uid()).build()); } categoryOptionComboCategoryOptionLinkHandler.handleMany(optionCombo.uid(), categoryOptionComboCategoryOptionLinks); } } }
package de.jeha.kame.crawler.service; import de.jeha.kame.crawler.service.config.CrawlerServiceConfiguration; import de.jeha.kame.crawler.service.health.MongoDbHealthCheck; import de.jeha.kame.crawler.service.resources.CrawlResource; import io.dropwizard.Application; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import org.glassfish.jersey.server.ServerProperties; /** * @author jenshadlich@googlemail.com */ public class CrawlerService extends Application<CrawlerServiceConfiguration> { private static final String APPLICATION_NAME = "crawler-service"; public static void main(String... args) throws Exception { new CrawlerService().run(args); } @Override public String getName() { return APPLICATION_NAME; } @Override public void initialize(Bootstrap<CrawlerServiceConfiguration> bootstrap) { // nothing to do yet } @Override public void run(CrawlerServiceConfiguration configuration, Environment environment) { environment.jersey().register(new CrawlResource(configuration.getCrawler().build())); environment.healthChecks().register("mongoDb", new MongoDbHealthCheck(configuration.getMongoDb())); environment.jersey().disable(ServerProperties.WADL_FEATURE_DISABLE); } }
package test.com.ctrip.platform.dal.dao.task; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; import java.util.LinkedHashMap; import java.util.Map; import com.ctrip.platform.dal.dao.helper.AbstractDalParser; public class ClientTestDalParser extends AbstractDalParser<ClientTestModel>{ private static final String tableName= "dal_client_test"; private static final String[] columnNames = new String[]{ "id","quantity","dbIndex","tableIndex","type","address","last_changed" }; private static final String[] primaryKeyNames = new String[]{"id"}; private static final int[] columnTypes = new int[]{ Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.SMALLINT, Types.VARCHAR, Types.TIMESTAMP }; public ClientTestDalParser(String databaseName) { super(databaseName, tableName, columnNames, primaryKeyNames, columnTypes); } private boolean _DEBUG = false; @Override public ClientTestModel map(ResultSet rs, int rowNum) throws SQLException { if(_DEBUG) { ResultSetMetaData rsmd = rs.getMetaData(); String[] columns = new String[rsmd.getColumnCount()]; for(int i = 0; i < columns.length; i++) { columns[i] = rsmd.getColumnName(i + 1); } } ClientTestModel model = new ClientTestModel(); model.setId(rs.getInt(1)); model.setQuantity(getInteger(rs.getObject(2))); model.setDbIndex(getInteger(rs.getObject(3))); model.setTableIndex(getInteger(rs.getObject(4))); model.setType(rs.getShort(5)); model.setAddress(rs.getString(6)); model.setLastChanged(rs.getTimestamp(7)); return model; } private Integer getInteger(Object value) { if(value == null) return null; return ((Number)value).intValue(); } @Override public boolean isAutoIncrement() { return true; } @Override public Number getIdentityValue(ClientTestModel pojo) { return pojo.getId(); } @Override public Map<String, ?> getPrimaryKeys(ClientTestModel pojo) { Map<String, Object> keys = new LinkedHashMap<String, Object>(); keys.put("id", pojo.getId()); return keys; } @Override public Map<String, ?> getFields(ClientTestModel pojo) { Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("id", pojo.getId()); map.put("quantity", pojo.getQuantity()); map.put("dbIndex", pojo.getDbIndex()); map.put("tableIndex", pojo.getTableIndex()); map.put("type", pojo.getType()); map.put("address", pojo.getAddress()); map.put("last_changed", pojo.getLastChanged()); return map; } }
package com.sensei.search.nodes; import java.net.InetAddress; import java.net.InetSocketAddress; import org.apache.log4j.Logger; import com.linkedin.norbert.cluster.Node; import com.linkedin.norbert.cluster.javaapi.Cluster; import com.linkedin.norbert.network.NetworkingException; import com.linkedin.norbert.network.javaapi.MessageHandler; import com.linkedin.norbert.network.javaapi.NetworkServer; import com.linkedin.norbert.network.javaapi.ServerBootstrap; import com.linkedin.norbert.network.javaapi.ServerConfig; public class SenseiNode{ private static Logger logger = Logger.getLogger(SenseiNode.class); private final String _zookeeperURL; private final int _id; private final SenseiNodeMessageHandler _msgHandler; private final int[] _partitions; private final String _clusterName; private ServerBootstrap _bootstrap; private NetworkServer _server; private final int _port; public SenseiNode(String clusterName,int id,int port,int[] partitions,SenseiNodeMessageHandler msgHandler,String zookeeperURL){ _id = id; _port = port; _partitions = partitions; _msgHandler = msgHandler; _zookeeperURL = zookeeperURL; _clusterName = clusterName; } public void startup() throws Exception{ ServerConfig serverConfig = new ServerConfig(); serverConfig.setClusterName(_clusterName); serverConfig.setZooKeeperUrls(_zookeeperURL); serverConfig.setMessageHandlers(new MessageHandler[]{_msgHandler}); serverConfig.setNodeId(_id); _bootstrap = new ServerBootstrap(serverConfig); Cluster cluster = _bootstrap.getCluster(); boolean nodeExists = false; try{ logger.info("waiting to connect to cluster..."); cluster.awaitConnection(); Node node = cluster.getNodeWithId(_id); nodeExists = (node!=null); if (!nodeExists){ cluster.addNode(_id, new InetSocketAddress(InetAddress.getLocalHost(),_port),_partitions); Thread.sleep(1000); logger.info("added node id: "+_id); } } catch(Exception e){ logger.error(e.getMessage(),e); } _server = _bootstrap.getNetworkServer(); try { logger.info("binding server ..."); _server.bind(); logger.info("started..."); if (nodeExists){ logger.warn("existing node found, will try to overwrite."); try{ cluster.removeNode(_id); } catch(Exception e){ logger.error("problem removing old node: "+e.getMessage(),e); } cluster.addNode(_id, new InetSocketAddress(InetAddress.getLocalHost(),_port),_partitions); Thread.sleep(1000); logger.info("added node id: "+_id); } } catch (NetworkingException e) { logger.info("shutting down..."); try { if (!nodeExists){ cluster.removeNode(_id); } } catch(Exception ex){ logger.warn(ex.getMessage()); } finally{ try{ _server.shutdown(); } finally{ _bootstrap.shutdown(); } } } } public void shutdown() throws Exception{ logger.info("shutting down..."); try { Cluster cluster = _bootstrap.getCluster(); cluster.removeNode(_id); } catch(Exception e){ logger.warn(e.getMessage()); } finally{ try{ _server.shutdown(); } finally{ _bootstrap.shutdown(); } } } }
package org.deeplearning4j.nn.updater; import org.apache.commons.math3.util.FastMath; import org.deeplearning4j.datasets.iterator.impl.IrisDataSetIterator; import org.deeplearning4j.nn.api.Layer; import org.deeplearning4j.nn.api.OptimizationAlgorithm; import org.deeplearning4j.nn.api.Updater; import org.deeplearning4j.nn.conf.LearningRatePolicy; import org.deeplearning4j.nn.conf.MultiLayerConfiguration; import org.deeplearning4j.nn.conf.NeuralNetConfiguration; import org.deeplearning4j.nn.conf.distribution.NormalDistribution; import org.deeplearning4j.nn.conf.layers.DenseLayer; import org.deeplearning4j.nn.conf.layers.OutputLayer; import org.deeplearning4j.nn.gradient.DefaultGradient; import org.deeplearning4j.nn.gradient.Gradient; import org.deeplearning4j.nn.layers.factory.LayerFactories; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; import org.deeplearning4j.nn.params.DefaultParamInitializer; import org.deeplearning4j.nn.weights.WeightInit; import org.deeplearning4j.optimize.api.ConvexOptimizer; import org.deeplearning4j.optimize.solvers.StochasticGradientDescent; import org.deeplearning4j.optimize.stepfunctions.NegativeDefaultStepFunction; import org.junit.Before; import org.junit.Test; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.dataset.DataSet; import org.nd4j.linalg.factory.Nd4j; import org.nd4j.linalg.lossfunctions.LossFunctions; import org.nd4j.linalg.ops.transforms.Transforms; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; /** * Test learning rate and momentum decay policies */ public class TestDecayPolicies { int nIn = 3; int nOut = 2; double epsilon = 1e-8; INDArray weightGradient = Nd4j.ones(nIn,nOut); INDArray biasGradient = Nd4j.ones(1,nOut); Gradient gradientSingle = new DefaultGradient(); Gradient gradientMLN = new DefaultGradient(); INDArray val, gradExpected, vPrev; String key; Map<String, INDArray> tmpStorage, tmpStorage2, tmpStorage3, tmpStorage4 = new HashMap<>(); org.deeplearning4j.nn.conf.Updater[] updaters = { org.deeplearning4j.nn.conf.Updater.SGD, org.deeplearning4j.nn.conf.Updater.ADAGRAD, org.deeplearning4j.nn.conf.Updater.ADAM, org.deeplearning4j.nn.conf.Updater.RMSPROP, }; @Before public void beforeDo(){ int nLayers = 2; String wKey, bKey; gradientSingle.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient); gradientSingle.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient); for (int j=0; j < nLayers; j++){ wKey = String.valueOf(j) + "_" + DefaultParamInitializer.WEIGHT_KEY; gradientMLN.setGradientFor(wKey, weightGradient); bKey = String.valueOf(j) + "_" + DefaultParamInitializer.BIAS_KEY ; gradientMLN.setGradientFor(bKey, biasGradient); } val = null; gradExpected = null; vPrev = null; tmpStorage = new HashMap<>(); tmpStorage2 = new HashMap<>(); tmpStorage3 = new HashMap<>(); tmpStorage4 = new HashMap<>(); } @Test public void testLearningRateExponentialDecaySingleLayer() { int iterations = 2; double lr = 1e-2; double decayRate = 2; NeuralNetConfiguration conf = new NeuralNetConfiguration.Builder() .learningRate(lr) .learningRateDecayPolicy(LearningRatePolicy.Exponential) .lrPolicyDecayRate(decayRate) .iterations(iterations) .layer(new DenseLayer.Builder() .nIn(nIn).nOut(nOut).updater(org.deeplearning4j.nn.conf.Updater.SGD).build()) .build(); Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0); Updater updater = UpdaterCreator.getUpdater(layer); Gradient gradientActual = new DefaultGradient(); gradientActual.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient); gradientActual.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient); for (int i = 0; i < iterations; i++) { updater.update(layer, gradientActual, i, 1); double expectedLr = calcExponentialDecay(lr, decayRate, i); assertEquals(expectedLr, layer.conf().getLearningRateByParam("W"), 1e-4); assertEquals(expectedLr, layer.conf().getLearningRateByParam("b"), 1e-4); } } @Test public void testLearningRateInverseDecaySingleLayer() { int iterations = 2; double lr = 1e-2; double decayRate = 2; double power = 3; NeuralNetConfiguration conf = new NeuralNetConfiguration.Builder() .learningRate(lr) .learningRateDecayPolicy(LearningRatePolicy.Inverse) .lrPolicyDecayRate(decayRate) .lrPolicyPower(power) .iterations(iterations) .layer(new DenseLayer.Builder() .nIn(nIn).nOut(nOut).updater(org.deeplearning4j.nn.conf.Updater.SGD).build()) .build(); Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0); Updater updater = UpdaterCreator.getUpdater(layer); Gradient gradientActual = new DefaultGradient(); gradientActual.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient); gradientActual.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient); for (int i = 0; i < iterations; i++) { updater.update(layer, gradientActual, i, 1); double expectedLr = calcInverseDecay(lr, decayRate, i, power); assertEquals(expectedLr, layer.conf().getLearningRateByParam("W"), 1e-4); assertEquals(expectedLr, layer.conf().getLearningRateByParam("b"), 1e-4); } } @Test public void testLearningRateStepDecaySingleLayer() { int iterations = 2; double lr = 1e-2; double decayRate = 2; double steps = 3; NeuralNetConfiguration conf = new NeuralNetConfiguration.Builder() .learningRate(lr) .learningRateDecayPolicy(LearningRatePolicy.Step) .lrPolicyDecayRate(decayRate) .lrPolicySteps(steps) .iterations(iterations) .layer(new DenseLayer.Builder() .nIn(nIn).nOut(nOut).updater(org.deeplearning4j.nn.conf.Updater.SGD).build()) .build(); Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0); Updater updater = UpdaterCreator.getUpdater(layer); Gradient gradientActual = new DefaultGradient(); gradientActual.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient); gradientActual.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient); for (int i = 0; i < iterations; i++) { updater.update(layer, gradientActual, i, 1); double expectedLr = calcStepDecay(lr, decayRate, i, steps); assertEquals(expectedLr, layer.conf().getLearningRateByParam("W"), 1e-4); assertEquals(expectedLr, layer.conf().getLearningRateByParam("b"), 1e-4); } } @Test public void testLearningRatePolyDecaySingleLayer() { int iterations = 2; double lr = 1e-2; double power = 3; NeuralNetConfiguration conf = new NeuralNetConfiguration.Builder() .learningRate(lr) .learningRateDecayPolicy(LearningRatePolicy.Poly) .lrPolicyPower(power) .iterations(iterations) .layer(new DenseLayer.Builder() .nIn(nIn).nOut(nOut).updater(org.deeplearning4j.nn.conf.Updater.SGD).build()) .build(); Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0); Updater updater = UpdaterCreator.getUpdater(layer); Gradient gradientActual = new DefaultGradient(); gradientActual.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient); gradientActual.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient); for (int i = 0; i < iterations; i++) { updater.update(layer, gradientActual, i, 1); double expectedLr = calcPolyDecay(lr, i, power, iterations); assertEquals(expectedLr, layer.conf().getLearningRateByParam("W"), 1e-4); assertEquals(expectedLr, layer.conf().getLearningRateByParam("b"), 1e-4); } } @Test public void testLearningRateSigmoidDecaySingleLayer() { int iterations = 2; double lr = 1e-2; double decayRate = 2; double steps = 3; NeuralNetConfiguration conf = new NeuralNetConfiguration.Builder() .learningRate(lr) .learningRateDecayPolicy(LearningRatePolicy.Sigmoid) .lrPolicyDecayRate(decayRate) .lrPolicySteps(steps) .iterations(iterations) .layer(new DenseLayer.Builder() .nIn(nIn).nOut(nOut).updater(org.deeplearning4j.nn.conf.Updater.SGD).build()) .build(); Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0); Updater updater = UpdaterCreator.getUpdater(layer); Gradient gradientActual = new DefaultGradient(); gradientActual.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient); gradientActual.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient); for (int i = 0; i < iterations; i++) { updater.update(layer, gradientActual, i, 1); double expectedLr = calcSigmoidDecay(layer.conf().getLearningRateByParam("W"), decayRate, i, steps); assertEquals(expectedLr, layer.conf().getLearningRateByParam("W"), 1e-4); assertEquals(expectedLr, layer.conf().getLearningRateByParam("b"), 1e-4); } } @Test public void testLearningRateScheduleSingleLayer() { Map<Integer, Double> learningRateAfter = new HashMap<>(); learningRateAfter.put(1, 0.2); int iterations = 2; for (org.deeplearning4j.nn.conf.Updater updaterFunc : updaters) { double lr = 1e-2; NeuralNetConfiguration conf = new NeuralNetConfiguration.Builder() .learningRate(lr).learningRateSchedule(learningRateAfter) .learningRateDecayPolicy(LearningRatePolicy.Schedule) .iterations(iterations) .layer(new DenseLayer.Builder() .nIn(nIn).nOut(nOut).updater(updaterFunc).build()) .build(); Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0); Updater updater = UpdaterCreator.getUpdater(layer); Gradient gradientActual = new DefaultGradient(); gradientActual.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient); gradientActual.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient); Gradient gradientExpected = new DefaultGradient(); gradientExpected.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient); gradientExpected.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient); for (int i = 0; i < 2; i++) { updater.update(layer, gradientActual, i, 1); if(updaterFunc.equals(org.deeplearning4j.nn.conf.Updater.SGD)) lr = testSGDComputation(gradientActual, gradientExpected, lr, learningRateAfter, i); else if(updaterFunc.equals(org.deeplearning4j.nn.conf.Updater.ADAGRAD)) lr = testAdaGradComputation(gradientActual, gradientExpected, lr, learningRateAfter, i); else if(updaterFunc.equals(org.deeplearning4j.nn.conf.Updater.ADAM)) lr = testAdamComputation(gradientActual, gradientExpected, lr, learningRateAfter, i); else if(updaterFunc.equals(org.deeplearning4j.nn.conf.Updater.RMSPROP)) lr = testRMSPropComputation(gradientActual, gradientExpected, lr, learningRateAfter, i); assertEquals(lr, layer.conf().getLearningRateByParam("W"), 1e-4); } } } @Test public void testLearningRateScheduleMLN(){ Map<Integer,Double> learningRateAfter = new HashMap<>(); learningRateAfter.put(1, 0.2); int iterations = 2; int[] nIns = {4,2}; int[] nOuts = {2,3}; for (org.deeplearning4j.nn.conf.Updater updaterFunc : updaters) { double lr = 1e-2; MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder() .learningRate(lr).learningRateDecayPolicy(LearningRatePolicy.Schedule) .learningRateSchedule(learningRateAfter).iterations(iterations) .updater(updaterFunc) .list() .layer(0, new DenseLayer.Builder().nIn(nIns[0]).nOut(nOuts[0]).build()) .layer(1, new OutputLayer.Builder().nIn(nIns[1]).nOut(nOuts[1]).build()) .backprop(true).pretrain(false) .build(); MultiLayerNetwork net = new MultiLayerNetwork(conf); net.init(); Updater updater = UpdaterCreator.getUpdater(net); String wKey, bKey; Gradient gradientActual = new DefaultGradient(); Gradient gradientExpected = new DefaultGradient(); for (int k = 0; k < net.getnLayers(); k++) { wKey = String.valueOf(k) + "_" + DefaultParamInitializer.WEIGHT_KEY; gradientActual.setGradientFor(wKey, weightGradient); gradientExpected.setGradientFor(wKey, weightGradient); bKey = String.valueOf(k) + "_" + DefaultParamInitializer.BIAS_KEY; gradientActual.setGradientFor(bKey, biasGradient); gradientExpected.setGradientFor(bKey, biasGradient); } for (int i = 0; i < 2; i++) { updater.update(net, gradientActual, i, 1); if(updaterFunc.equals(org.deeplearning4j.nn.conf.Updater.SGD)) lr = testSGDComputation(gradientActual, gradientExpected, lr, learningRateAfter, i); else if(updaterFunc.equals(org.deeplearning4j.nn.conf.Updater.ADAGRAD)) lr = testAdaGradComputation(gradientActual, gradientExpected, lr, learningRateAfter, i); // else if(updaterFunc.equals(org.deeplearning4j.nn.conf.Updater.ADAM)) // lr = testAdamComputation(gradientActual, gradientExpected, lr, learningRateAfter, i); else if(updaterFunc.equals(org.deeplearning4j.nn.conf.Updater.RMSPROP)) lr = testRMSPropComputation(gradientActual, gradientExpected, lr, learningRateAfter, i); // TODO check if this is cycling through the learning rate schedule... assertEquals(lr, net.getLayer(1).conf().getLearningRateByParam("W"), 1e-4); } } } @Test public void testLearningRateScoreDecay(){ double lr = 0.01; double lrScoreDecay = 0.10; int[] nIns = {4,2}; int[] nOuts = {2,3}; int oldScore = 1; int newScore = 1; int iteration = 3; INDArray gradientW = Nd4j.ones(nIns[0], nOuts[0]); MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder() .learningRate(lr) .learningRateDecayPolicy(LearningRatePolicy.Score) .lrPolicyDecayRate(lrScoreDecay) .list() .layer(0, new DenseLayer.Builder().nIn(nIns[0]).nOut(nOuts[0]).updater(org.deeplearning4j.nn.conf.Updater.SGD).build()) .layer(1, new OutputLayer.Builder().nIn(nIns[1]).nOut(nOuts[1]).updater(org.deeplearning4j.nn.conf.Updater.SGD).build()) .backprop(true).pretrain(false) .build(); MultiLayerNetwork net = new MultiLayerNetwork(conf); net.init(); ConvexOptimizer opt = new StochasticGradientDescent(net.getDefaultConfiguration(), new NegativeDefaultStepFunction(), null, net); opt.checkTerminalConditions(gradientW, oldScore, newScore, iteration); assertEquals(lrScoreDecay, net.getLayer(0).conf().getLrPolicyDecayRate(), 1e-4); assertEquals(lr*(lrScoreDecay + Nd4j.EPS_THRESHOLD), net.getLayer(0).conf().getLearningRateByParam("W"), 1e-4); } @Test public void testOriginalLearningRateUnchanged() { // Confirm learning rate is unchanged while hash is updated DataSet ds = new IrisDataSetIterator(150,150).next(); ds.normalizeZeroMeanZeroUnitVariance(); Nd4j.getRandom().setSeed(12345); MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder() .regularization(false) .optimizationAlgo(OptimizationAlgorithm.CONJUGATE_GRADIENT) .learningRate(1.0) .learningRateDecayPolicy(LearningRatePolicy.Score) .lrPolicyDecayRate(0.10) .weightInit(WeightInit.DISTRIBUTION).dist(new NormalDistribution(0, 1)) .updater(org.deeplearning4j.nn.conf.Updater.SGD) .seed(12345L) .list() .layer(0, new DenseLayer.Builder() .nIn(4).nOut(3) .activation("sigmoid") .build()) .layer(1, new OutputLayer.Builder(LossFunctions.LossFunction.MSE) .activation("tanh") .nIn(3).nOut(3) .build()) .pretrain(false).backprop(true) .build(); MultiLayerNetwork mln = new MultiLayerNetwork(conf); mln.init(); //Run a number of iterations of learning mln.setInput(ds.getFeatureMatrix()); mln.setLabels(ds.getLabels()); mln.computeGradientAndScore(); for( int j=0; j<1; j++ ) mln.fit(ds); mln.computeGradientAndScore(); double lr0 = mln.getLayer(0).conf().getLayer().getLearningRate(); double lr1 = mln.getLayer(1).conf().getLayer().getLearningRate(); assertEquals(1.0, lr0, 0.0); assertEquals(1.0, lr1, 0.0); } @Test public void testMomentumScheduleSingleLayer(){ double lr = 1e-2; double mu = 0.6; Map<Integer,Double> momentumAfter = new HashMap<>(); momentumAfter.put(1, 0.2); int iterations = 2; NeuralNetConfiguration conf = new NeuralNetConfiguration.Builder() .learningRate(lr).momentum(mu) .momentumAfter(momentumAfter).iterations(iterations) .layer(new DenseLayer.Builder() .nIn(nIn).nOut(nOut).updater(org.deeplearning4j.nn.conf.Updater.NESTEROVS).build()) .build(); Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0); Updater updater = UpdaterCreator.getUpdater(layer); Gradient gradientExpected = new DefaultGradient(); gradientExpected.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient); gradientExpected.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient); for (int i = 0; i < 2; i++) { updater.update(layer, gradientSingle, i, 1); mu = testNesterovsComputation(gradientSingle, gradientExpected, lr, mu, momentumAfter, i); assertEquals(mu, layer.conf().getLayer().getMomentum(), 1e-4); } } @Test public void testMomentumScheduleMLN(){ double lr = 1e-2; double mu = 0.6; Map<Integer,Double> momentumAfter = new HashMap<>(); momentumAfter.put(1, 0.2); int iterations = 2; int[] nIns = {4,2}; int[] nOuts = {2,3}; MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder() .learningRate(lr).momentum(mu).momentumAfter(momentumAfter).iterations(iterations) .list() .layer(0, new DenseLayer.Builder().nIn(nIns[0]).nOut(nOuts[0]).updater(org.deeplearning4j.nn.conf.Updater.NESTEROVS).build()) .layer(1, new OutputLayer.Builder().nIn(nIns[1]).nOut(nOuts[1]).updater(org.deeplearning4j.nn.conf.Updater.NESTEROVS).build()) .backprop(true).pretrain(false) .build(); MultiLayerNetwork net = new MultiLayerNetwork(conf); net.init(); Updater updater = UpdaterCreator.getUpdater(net); String wKey, bKey; Gradient gradientExpected = new DefaultGradient(); for (int k=0; k < net.getnLayers(); k++){ wKey = String.valueOf(k) + "_" + DefaultParamInitializer.WEIGHT_KEY; gradientExpected.setGradientFor(wKey, weightGradient); bKey = String.valueOf(k) + "_" + DefaultParamInitializer.BIAS_KEY ; gradientExpected.setGradientFor(bKey, biasGradient); } for (int i = 0; i < 2; i++) { updater.update(net, gradientMLN, i, 1); mu = testNesterovsComputation(gradientMLN, gradientExpected, lr, mu, momentumAfter, i); assertEquals(mu, net.getLayer(1).conf().getLayer().getMomentum(), 1e-4); } } ///// Updater Calculations public double testSGDComputation(Gradient gradientActual, Gradient gradientExpected, double lr, Map<Integer, Double> learningRateAfter, int i){ for (Map.Entry<String, INDArray> entry : gradientExpected.gradientForVariable().entrySet()) { if (learningRateAfter != null) lr = (learningRateAfter.containsKey(i)) ? learningRateAfter.get(i) : lr; key = entry.getKey(); val = entry.getValue(); gradExpected = val.mul(lr); gradientExpected.setGradientFor(key, gradExpected); assertEquals(gradExpected, gradientActual.getGradientFor(key)); } return lr; } public double testNesterovsComputation(Gradient gradientActual, Gradient gradientExpected, double lr, double mu, Map<Integer, Double> momentumAfter, int i) { for (Map.Entry<String, INDArray> entry : gradientExpected.gradientForVariable().entrySet()) { if(momentumAfter !=null) mu = (momentumAfter.containsKey(i)) ? momentumAfter.get(i) : mu; key = entry.getKey(); val = entry.getValue(); INDArray vTmp = tmpStorage.get(key); if(vTmp == null) vTmp = Nd4j.zeros(val.shape()); vPrev = vTmp; vTmp = vPrev.mul(mu).subi(val.mul(lr)); gradExpected = vPrev.muli(mu).addi(vTmp.mul(-mu - 1)); gradientExpected.setGradientFor(key, gradExpected); assertEquals(gradExpected, gradientActual.getGradientFor(entry.getKey())); tmpStorage.put(key, vTmp); } return mu; } public double testAdaGradComputation(Gradient gradientActual, Gradient gradientExpected, double lr, Map<Integer, Double> learningRateAfter, int i) { for (Map.Entry<String, INDArray> entry : gradientExpected.gradientForVariable().entrySet()) { if (learningRateAfter != null) lr = (learningRateAfter.containsKey(i)) ? learningRateAfter.get(i) : lr; key = entry.getKey(); val = entry.getValue(); INDArray historicalGradient = tmpStorage.get(key); if(historicalGradient == null) historicalGradient = val.mul(val); else historicalGradient.addi(val.mul(val)); gradExpected = Transforms.sqrt(historicalGradient.add(epsilon)).rdiv(lr).mul(val); assertEquals(gradExpected, gradientActual.getGradientFor(key)); gradientExpected.setGradientFor(key, gradExpected); tmpStorage.put(key, historicalGradient); } return lr; } public double testAdamComputation(Gradient gradientActual, Gradient gradientExpected, double lr, Map<Integer, Double> learningRateAfter, int i) { double beta1 = 0.9; double beta2 = 0.999; for (Map.Entry<String, INDArray> entry : gradientExpected.gradientForVariable().entrySet()) { if (learningRateAfter != null) lr = (learningRateAfter.containsKey(i)) ? learningRateAfter.get(i) : lr; key = entry.getKey(); val = entry.getValue(); INDArray mTmp = tmpStorage2.get(key); INDArray vTmp = tmpStorage3.get(key); if(mTmp == null) mTmp = Nd4j.zeros(val.shape()); if(vTmp == null) vTmp = Nd4j.zeros(val.shape()); mTmp.muli(beta1).addi(val.mul(1.0-beta1)); vTmp.muli(beta2).addi(val.mul(val).mul(1.0-beta2)); double beta1t = FastMath.pow(beta1, i); double beta2t = FastMath.pow(beta2, i); double alphat = lr * FastMath.sqrt(1-beta2t)/(1-beta1t); gradExpected = mTmp.mul(alphat).divi(Transforms.sqrt(vTmp).addi(epsilon)); gradientExpected.setGradientFor(key, gradExpected); assertEquals(gradExpected, gradientActual.getGradientFor(key)); tmpStorage2.put(key, mTmp); tmpStorage3.put(key, vTmp); } return lr; } public double testRMSPropComputation(Gradient gradientActual, Gradient gradientExpected, double lr, Map<Integer, Double> learningRateAfter, int i) { double rmsDecay = 0.95; for (Map.Entry<String, INDArray> entry : gradientExpected.gradientForVariable().entrySet()) { if (learningRateAfter != null) lr = (learningRateAfter.containsKey(i)) ? learningRateAfter.get(i) : lr; key = entry.getKey(); val = entry.getValue(); INDArray lastGTmp = tmpStorage4.get(key); if(lastGTmp==null) lastGTmp = Nd4j.zeros(val.shape()); lastGTmp.muli(rmsDecay).addi(val.mul(val).muli(1 - rmsDecay)); gradExpected = val.mul(lr).div(Transforms.sqrt(lastGTmp.add(Nd4j.EPS_THRESHOLD))); gradientExpected.setGradientFor(key, gradExpected); assertEquals(gradExpected, gradientActual.getGradientFor(key)); tmpStorage4.put(key, lastGTmp); } return lr; } ///// Learning Rate Decay Policy Calculations public double calcExponentialDecay(double lr, double decayRate, double iteration){ return lr * Math.pow(decayRate, iteration); } public double calcInverseDecay(double lr, double decayRate, double iteration, double power){ return lr / Math.pow((1+decayRate * iteration), power); } public double calcStepDecay(double lr, double decayRate, double iteration, double steps){ return lr * Math.pow(decayRate, Math.floor(iteration/steps)); } public double calcPolyDecay(double lr, double iteration, double power, double maxIterations){ return lr * Math.pow((1 - iteration/maxIterations), power); } public double calcSigmoidDecay(double lr, double decayRate, double iteration, double steps){ return lr / (1 + Math.exp(-decayRate * (iteration - steps))); } }
package org.deeplearning4j.nn.conf.layers; import lombok.extern.slf4j.Slf4j; import org.deeplearning4j.nn.conf.Updater; import org.deeplearning4j.nn.conf.distribution.Distribution; import org.deeplearning4j.nn.conf.distribution.NormalDistribution; import org.deeplearning4j.nn.weights.WeightInit; import org.nd4j.linalg.learning.*; import org.nd4j.linalg.learning.config.*; import java.util.HashMap; import java.util.Map; @Slf4j public class LayerValidation { /** * Validate the updater configuration - setting the default updater values, if necessary */ public static void updaterValidation(String layerName, Layer layer, Double learningRate, Double momentum, Map<Integer, Double> momentumSchedule, Double adamMeanDecay, Double adamVarDecay, Double rho, Double rmsDecay, Double epsilon) { updaterValidation(layerName, layer, learningRate == null ? Double.NaN : learningRate, momentum == null ? Double.NaN : momentum, momentumSchedule, adamMeanDecay == null ? Double.NaN : adamMeanDecay, adamVarDecay == null ? Double.NaN : adamVarDecay, rho == null ? Double.NaN : rho, rmsDecay == null ? Double.NaN : rmsDecay, epsilon == null ? Double.NaN : epsilon); } /** * Validate the updater configuration - setting the default updater values, if necessary */ public static void updaterValidation(String layerName, Layer layer, double learningRate, double momentum, Map<Integer, Double> momentumSchedule, double adamMeanDecay, double adamVarDecay, double rho, double rmsDecay, double epsilon) { if ((!Double.isNaN(momentum) || !Double.isNaN(layer.getMomentum())) && layer.getUpdater() != Updater.NESTEROVS) log.warn("Layer \"" + layerName + "\" momentum has been set but will not be applied unless the updater is set to NESTEROVS."); if ((momentumSchedule != null || layer.getMomentumSchedule() != null) && layer.getUpdater() != Updater.NESTEROVS) log.warn("Layer \"" + layerName + "\" momentum schedule has been set but will not be applied unless the updater is set to NESTEROVS."); if ((!Double.isNaN(adamVarDecay) || (!Double.isNaN(layer.getAdamVarDecay()))) && layer.getUpdater() != Updater.ADAM) log.warn("Layer \"" + layerName + "\" adamVarDecay is set but will not be applied unless the updater is set to Adam."); if ((!Double.isNaN(adamMeanDecay) || !Double.isNaN(layer.getAdamMeanDecay())) && layer.getUpdater() != Updater.ADAM) log.warn("Layer \"" + layerName + "\" adamMeanDecay is set but will not be applied unless the updater is set to Adam."); if ((!Double.isNaN(rho) || !Double.isNaN(layer.getRho())) && layer.getUpdater() != Updater.ADADELTA) log.warn("Layer \"" + layerName + "\" rho is set but will not be applied unless the updater is set to ADADELTA."); if ((!Double.isNaN(rmsDecay) || (!Double.isNaN(layer.getRmsDecay()))) && layer.getUpdater() != Updater.RMSPROP) log.warn("Layer \"" + layerName + "\" rmsdecay is set but will not be applied unless the updater is set to RMSPROP."); //Set values from old (deprecated) .epsilon(), .momentum(), etc methods to the built-in updaters //Also set LR, where appropriate //Note that default values for all other parameters are set by default in the Sgd/Adam/whatever classes //Hence we don't need to set them here //Finally: we'll also set the (updater enumeration field to something sane) to avoid updater=SGD, // iupdater=Adam() type situations. Though the updater field isn't used, we don't want to confuse users IUpdater u = layer.getIUpdater(); if(!Double.isNaN(learningRate)){ //Note that for LRs, if user specifies .learningRate(x).updater(Updater.SGD) (for example), we need to set the // LR in the Sgd object. We can do this using the schedules method, which also works for custom updaters u.applySchedules(0, learningRate); } if(u instanceof Sgd){ layer.setUpdater(Updater.SGD); } else if(u instanceof Adam ){ Adam a = (Adam)u; if(!Double.isNaN(epsilon)){ a.setEpsilon(epsilon); } if(!Double.isNaN(adamMeanDecay)){ a.setBeta1(adamMeanDecay); } if(!Double.isNaN(adamVarDecay)){ a.setBeta2(adamVarDecay); } layer.setUpdater(Updater.ADAM); } else if(u instanceof AdaDelta) { AdaDelta a = (AdaDelta)u; if(!Double.isNaN(rho)){ a.setRho(rho); } if(!Double.isNaN(epsilon)){ a.setEpsilon(epsilon); } layer.setUpdater(Updater.ADADELTA); } else if(u instanceof Nesterovs ){ Nesterovs n = (Nesterovs)u; if(!Double.isNaN(momentum)){ n.setMomentum(momentum); } if(momentumSchedule != null){ n.setMomentumSchedule(momentumSchedule); } layer.setUpdater(Updater.NESTEROVS); } else if(u instanceof AdaGrad){ AdaGrad a = (AdaGrad)u; if(!Double.isNaN(epsilon)){ a.setEpsilon(epsilon); } layer.setUpdater(Updater.ADAGRAD); } else if(u instanceof RmsProp){ RmsProp r = (RmsProp)u; if(!Double.isNaN(epsilon)){ r.setEpsilon(epsilon); } if(!Double.isNaN(rmsDecay)){ r.setRmsDecay(rmsDecay); } layer.setUpdater(Updater.RMSPROP); } else if(u instanceof AdaMax){ AdaMax a = (AdaMax)u; if(!Double.isNaN(epsilon)){ a.setEpsilon(epsilon); } if(!Double.isNaN(adamMeanDecay)){ a.setBeta1(adamMeanDecay); } if(!Double.isNaN(adamVarDecay)){ a.setBeta2(adamVarDecay); } layer.setUpdater(Updater.ADAMAX); } else if(u instanceof NoOp){ layer.setUpdater(Updater.NONE); } else { //Probably a custom updater layer.setUpdater(null); } } public static void generalValidation(String layerName, Layer layer, boolean useRegularization, boolean useDropConnect, Double dropOut, Double l2, Double l2Bias, Double l1, Double l1Bias, Distribution dist) { generalValidation(layerName, layer, useRegularization, useDropConnect, dropOut == null ? 0.0 : dropOut, l2 == null ? Double.NaN : l2, l2Bias == null ? Double.NaN : l2Bias, l1 == null ? Double.NaN : l1, l1Bias == null ? Double.NaN : l1Bias, dist); } public static void generalValidation(String layerName, Layer layer, boolean useRegularization, boolean useDropConnect, double dropOut, double l2, double l2Bias, double l1, double l1Bias, Distribution dist) { if (useDropConnect && (Double.isNaN(dropOut) && (Double.isNaN(layer.getDropOut())))) log.warn("Layer \"" + layerName + "\" dropConnect is set to true but dropout rate has not been added to configuration."); if (useDropConnect && layer.getDropOut() == 0.0) log.warn("Layer \"" + layerName + " dropConnect is set to true but dropout rate is set to 0.0"); if (useRegularization && (Double.isNaN(l1) && layer != null && Double.isNaN(layer.getL1()) && Double.isNaN(l2) && Double.isNaN(layer.getL2()) && Double.isNaN(l2Bias) && Double.isNaN(l1Bias) && (Double.isNaN(dropOut) || dropOut == 0.0) && (Double.isNaN(layer.getDropOut()) || layer.getDropOut() == 0.0))) log.warn("Layer \"" + layerName + "\" regularization is set to true but l1, l2 or dropout has not been added to configuration."); if (layer != null) { if (useRegularization) { if (!Double.isNaN(l1) && Double.isNaN(layer.getL1())) { layer.setL1(l1); } if (!Double.isNaN(l2) && Double.isNaN(layer.getL2())) { layer.setL2(l2); } if (!Double.isNaN(l1Bias) && Double.isNaN(layer.getL1Bias())) { layer.setL1Bias(l1Bias); } if (!Double.isNaN(l2Bias) && Double.isNaN(layer.getL2Bias())) { layer.setL2Bias(l2Bias); } } else if (!useRegularization && ((!Double.isNaN(l1) && l1 > 0.0) || (!Double.isNaN(layer.getL1()) && layer.getL1() > 0.0) || (!Double.isNaN(l2) && l2 > 0.0) || (!Double.isNaN(layer.getL2()) && layer.getL2() > 0.0) || (!Double.isNaN(l1Bias) && l1Bias > 0.0) || (!Double.isNaN(layer.getL1Bias()) && layer.getL1Bias() > 0.0) || (!Double.isNaN(l2Bias) && l2Bias > 0.0) || (!Double.isNaN(layer.getL2Bias()) && layer.getL2Bias() > 0.0))) { log.warn("Layer \"" + layerName + "\" l1 or l2 has been added to configuration but useRegularization is set to false."); } if (Double.isNaN(l2) && Double.isNaN(layer.getL2())) { layer.setL2(0.0); } if (Double.isNaN(l1) && Double.isNaN(layer.getL1())) { layer.setL1(0.0); } if (Double.isNaN(l2Bias) && Double.isNaN(layer.getL2Bias())) { layer.setL2Bias(0.0); } if (Double.isNaN(l1Bias) && Double.isNaN(layer.getL1Bias())) { layer.setL1Bias(0.0); } if (layer.getWeightInit() == WeightInit.DISTRIBUTION) { if (dist != null && layer.getDist() == null) layer.setDist(dist); else if (dist == null && layer.getDist() == null) { layer.setDist(new NormalDistribution(0, 1)); log.warn("Layer \"" + layerName + "\" distribution is automatically set to normalize distribution with mean 0 and variance 1."); } } else if ((dist != null || layer.getDist() != null)) { log.warn("Layer \"" + layerName + "\" distribution is set but will not be applied unless weight init is set to WeighInit.DISTRIBUTION."); } } } }
package org.cytoscape.ding.impl; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Paint; import java.awt.TexturePaint; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.VolatileImage; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import javax.imageio.ImageIO; import javax.swing.Icon; import javax.swing.JLayeredPane; import org.cytoscape.application.NetworkViewRenderer; import org.cytoscape.application.swing.CyEdgeViewContextMenuFactory; import org.cytoscape.application.swing.CyNetworkViewContextMenuFactory; import org.cytoscape.application.swing.CyNodeViewContextMenuFactory; import org.cytoscape.ding.DVisualLexicon; import org.cytoscape.ding.EdgeView; import org.cytoscape.ding.GraphView; import org.cytoscape.ding.GraphViewChangeListener; import org.cytoscape.ding.GraphViewObject; import org.cytoscape.ding.NodeView; import org.cytoscape.ding.ObjectPosition; import org.cytoscape.ding.PrintLOD; import org.cytoscape.ding.customgraphics.NullCustomGraphics; import org.cytoscape.ding.icon.VisualPropertyIconFactory; import org.cytoscape.ding.impl.cyannotator.CyAnnotator; import org.cytoscape.ding.impl.cyannotator.AnnotationFactoryManager; import org.cytoscape.ding.impl.events.GraphViewChangeListenerChain; import org.cytoscape.ding.impl.events.GraphViewEdgesHiddenEvent; import org.cytoscape.ding.impl.events.GraphViewEdgesRestoredEvent; import org.cytoscape.ding.impl.events.GraphViewEdgesUnselectedEvent; import org.cytoscape.ding.impl.events.GraphViewNodesHiddenEvent; import org.cytoscape.ding.impl.events.GraphViewNodesRestoredEvent; import org.cytoscape.ding.impl.events.GraphViewNodesUnselectedEvent; import org.cytoscape.ding.impl.events.ViewportChangeListener; import org.cytoscape.ding.impl.events.ViewportChangeListenerChain; import org.cytoscape.ding.impl.visualproperty.CustomGraphicsVisualProperty; import org.cytoscape.event.CyEventHelper; import org.cytoscape.graph.render.immed.GraphGraphics; import org.cytoscape.graph.render.stateful.GraphLOD; import org.cytoscape.graph.render.stateful.GraphRenderer; import org.cytoscape.model.CyEdge; import org.cytoscape.model.CyIdentifiable; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNode; import org.cytoscape.model.SUIDFactory; import org.cytoscape.model.events.AboutToRemoveEdgesEvent; import org.cytoscape.model.events.AboutToRemoveEdgesListener; import org.cytoscape.model.events.AboutToRemoveNodesEvent; import org.cytoscape.model.events.AboutToRemoveNodesListener; import org.cytoscape.model.events.AddedEdgesEvent; import org.cytoscape.model.events.AddedEdgesListener; import org.cytoscape.model.events.AddedNodesEvent; import org.cytoscape.model.events.AddedNodesListener; import org.cytoscape.model.subnetwork.CyRootNetworkManager; import org.cytoscape.model.subnetwork.CySubNetwork; import org.cytoscape.service.util.CyServiceRegistrar; import org.cytoscape.spacial.SpacialEntry2DEnumerator; import org.cytoscape.spacial.SpacialIndex2D; import org.cytoscape.spacial.SpacialIndex2DFactory; import org.cytoscape.task.EdgeViewTaskFactory; import org.cytoscape.task.NetworkViewLocationTaskFactory; import org.cytoscape.task.NetworkViewTaskFactory; import org.cytoscape.task.NodeViewTaskFactory; import org.cytoscape.util.intr.LongBTree; import org.cytoscape.util.intr.LongEnumerator; import org.cytoscape.util.intr.LongHash; import org.cytoscape.util.intr.LongStack; import org.cytoscape.view.model.CyNetworkView; import org.cytoscape.view.model.CyNetworkViewManager; import org.cytoscape.view.model.View; import org.cytoscape.view.model.VisualLexicon; import org.cytoscape.view.model.VisualProperty; import org.cytoscape.view.model.events.AboutToRemoveEdgeViewsEvent; import org.cytoscape.view.model.events.AboutToRemoveNodeViewsEvent; import org.cytoscape.view.model.events.AddedEdgeViewsEvent; import org.cytoscape.view.model.events.AddedNodeViewsEvent; import org.cytoscape.view.model.events.FitContentEvent; import org.cytoscape.view.model.events.FitContentListener; import org.cytoscape.view.model.events.FitSelectedEvent; import org.cytoscape.view.model.events.FitSelectedListener; import org.cytoscape.view.model.events.UpdateNetworkPresentationEvent; import org.cytoscape.view.presentation.RenderingEngine; import org.cytoscape.view.presentation.property.BasicVisualLexicon; import org.cytoscape.view.presentation.property.values.HandleFactory; import org.cytoscape.view.vizmap.VisualMappingManager; import org.cytoscape.view.vizmap.VisualStyle; import org.cytoscape.work.swing.DialogTaskManager; import org.cytoscape.work.undo.UndoSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * DING implementation of Cytoscpae 3. * * Explain relationship to cytoscape. * * Throughout this code I am assuming that nodes or edges are never removed from * the underlying RootGraph. This assumption was made in the old GraphView * implementation. Removal from the RootGraph is the only thing that can affect * m_drawPersp and m_structPersp that is beyond our control. * * @author Nerius Landys */ public class DGraphView extends AbstractDViewModel<CyNetwork> implements CyNetworkView, RenderingEngine<CyNetwork>, GraphView, Printable, AddedEdgesListener, AddedNodesListener, AboutToRemoveEdgesListener, AboutToRemoveNodesListener, FitContentListener, FitSelectedListener { private static final Logger logger = LoggerFactory.getLogger(DGraphView.class); // Size of square for moving handle static final float DEFAULT_ANCHOR_SIZE = 12.0f; static final Paint DEFAULT_ANCHOR_SELECTED_PAINT = Color.red; static final Paint DEFAULT_ANCHOR_UNSELECTED_PAINT = Color.DARK_GRAY; private final CyEventHelper cyEventHelper; // Size of snapshot image protected static int DEF_SNAPSHOT_SIZE = 400; /** * Enum to identify ding canvases - used in getCanvas(Canvas canvasId) */ public enum Canvas { BACKGROUND_CANVAS, NETWORK_CANVAS, FOREGROUND_CANVAS; } public enum ShapeType { NODE_SHAPE, LINE_TYPE, ARROW_SHAPE; } /** * Common object used for synchronization. */ final Object m_lock = new Object(); /** * A common buffer object used to pass information about. X-Y coords of the * minimum bounding box? */ final float[] m_extentsBuff = new float[4]; final double[] m_extentsBuffD = new double[4]; /** * A common general path variable used for holding lots of shapes. */ final GeneralPath m_path = new GeneralPath(); /** * Holds the NodeView data for the nodes that are visible. This will change * as nodes are hidden from the view. */ final CySubNetwork m_drawPersp; /** * RTree used for querying node positions. */ SpacialIndex2D m_spacial; /** * RTree used for querying Edge Handle positions. Used by DNodeView, * DEdgeView, and InnerCanvas. */ SpacialIndex2D m_spacialA; final DNodeDetails m_nodeDetails; final DEdgeDetails m_edgeDetails; final NodeViewDefaultSupport nodeViewDefaultSupport; final EdgeViewDefaultSupport edgeViewDefaultSupport; /** * Level of detail specific to printing. Not used for rendering. */ PrintLOD m_printLOD; private final Map<CyNode, NodeView> nodeViewMap; private final Map<CyEdge, EdgeView> edgeViewMap; Long m_identifier; final float m_defaultNodeXMin; final float m_defaultNodeYMin; final float m_defaultNodeXMax; final float m_defaultNodeYMax; /** * Ref to network canvas object. */ InnerCanvas m_networkCanvas; /** * Ref to background canvas object. */ ArbitraryGraphicsCanvas m_backgroundCanvas; /** * Ref to foreground canvas object. */ ArbitraryGraphicsCanvas m_foregroundCanvas; /** * Current image width */ int imageWidth = 0; /** * Current image Height */ int imageHeight = 0; boolean m_nodeSelection = true; boolean m_edgeSelection = true; /** * BTree of selected nodes. */ final LongBTree m_selectedNodes; // Positive. /** * BTree of selected edges. */ final LongBTree m_selectedEdges; // Positive. /** * BTree of selected anchors. */ final LongBTree m_selectedAnchors; /** * State variable for when nodes have moved. */ volatile boolean m_contentChanged = false; /** * State variable for when zooming/panning have changed. */ volatile boolean m_viewportChanged = false; /** * List of listeners. */ final GraphViewChangeListener[] m_lis = new GraphViewChangeListener[1]; /** * List of listeners. */ final ContentChangeListener[] m_cLis = new ContentChangeListener[1]; /** * List of listeners. */ final ViewportChangeListener[] m_vLis = new ViewportChangeListener[1]; private final LongHash m_hash = new LongHash(); int m_lastSize = 0; /** * Used for caching texture paint. */ Paint m_lastPaint = null; /** * Used for caching texture paint. */ Paint m_lastTexturePaint = null; /** * Snapshot of current view. Will be updated by CONTENT_CHANGED event. * * This is used by a new nested network feature from 2.7. */ private BufferedImage snapshotImage; /** * Represents current snapshot is latest version or not. */ private boolean latest; final Map<NodeViewTaskFactory, Map> nodeViewTFs; final Map<EdgeViewTaskFactory, Map> edgeViewTFs; final Map<NetworkViewTaskFactory, Map> emptySpaceTFs; final Map<NetworkViewLocationTaskFactory, Map> networkViewLocationTfs; final Map<CyEdgeViewContextMenuFactory, Map> cyEdgeViewContextMenuFactory; final Map<CyNodeViewContextMenuFactory, Map> cyNodeViewContextMenuFactory; final Map<CyNetworkViewContextMenuFactory, Map> cyNetworkViewContextMenuFactory; final DialogTaskManager manager; private final Properties props; private final CyAnnotator cyAnnotator; private boolean annotationsLoaded; private boolean servicesRegistered; private final VisualMappingManager vmm; private final CyNetworkViewManager netViewMgr; private final CyServiceRegistrar registrar; private final HandleFactory handleFactory; /** * Create presentation from View Model * */ public DGraphView(final CyNetworkView view, CyRootNetworkManager cyRoot, UndoSupport undo, SpacialIndex2DFactory spacialFactory, final VisualLexicon dingLexicon, ViewTaskFactoryListener vtfl, DialogTaskManager manager, CyEventHelper eventHelper, AnnotationFactoryManager annMgr, final DingGraphLOD dingGraphLOD, final VisualMappingManager vmm, final CyNetworkViewManager netViewMgr, final HandleFactory handleFactory, final CyServiceRegistrar registrar) { this(view.getModel(), cyRoot, undo, spacialFactory, dingLexicon, vtfl, manager, eventHelper, annMgr, dingGraphLOD, vmm, netViewMgr, handleFactory, registrar); } /** * * @param model * @param dataFactory * @param cyRoot * @param undo * @param spacialFactory * @param dingLexicon * @param vtfl * @param manager * @param cyEventHelper * @param tableMgr * @param annMgr * @param dingGraphLOD */ public DGraphView(final CyNetwork model, CyRootNetworkManager cyRoot, UndoSupport undo, SpacialIndex2DFactory spacialFactory, final VisualLexicon dingLexicon, ViewTaskFactoryListener vtfl, DialogTaskManager manager, CyEventHelper cyEventHelper, AnnotationFactoryManager annMgr, final DingGraphLOD dingGraphLOD, final VisualMappingManager vmm, final CyNetworkViewManager netViewMgr, final HandleFactory handleFactory, final CyServiceRegistrar registrar) { super(model, dingLexicon); this.props = new Properties(); this.vmm = vmm; this.registrar = registrar; this.handleFactory = handleFactory; long start = System.currentTimeMillis(); logger.debug("Phase 1: rendering start."); this.nodeViewTFs = vtfl.nodeViewTFs; this.edgeViewTFs = vtfl.edgeViewTFs; this.emptySpaceTFs = vtfl.emptySpaceTFs; this.networkViewLocationTfs = vtfl.networkViewLocationTFs; this.cyEdgeViewContextMenuFactory = vtfl.cyEdgeViewContextMenuFactory; this.cyNodeViewContextMenuFactory = vtfl.cyNodeViewContexMenuFactory; this.cyNetworkViewContextMenuFactory = vtfl.cyNetworkViewContextMenuFactory; this.netViewMgr = netViewMgr; this.manager = manager; this.cyEventHelper = cyEventHelper; // creating empty subnetworks // m_drawPersp = cyRoot.getRootNetwork(model).addSubNetwork(SavePolicy.DO_NOT_SAVE); // cyEventHelper.silenceEventSource(m_drawPersp); // New simple implementation of the graph to keep track of visible nodes/edges. m_drawPersp = new MinimalNetwork(SUIDFactory.getNextSUID()); m_spacial = spacialFactory.createSpacialIndex2D(); m_spacialA = spacialFactory.createSpacialIndex2D(); m_nodeDetails = new DNodeDetails(this); m_edgeDetails = new DEdgeDetails(this); nodeViewDefaultSupport = new NodeViewDefaultSupport(m_nodeDetails, m_lock); edgeViewDefaultSupport = new EdgeViewDefaultSupport(m_edgeDetails, m_lock); nodeViewMap = new ConcurrentHashMap<CyNode, NodeView>(); edgeViewMap = new ConcurrentHashMap<CyEdge, EdgeView>(); m_printLOD = new PrintLOD(); m_defaultNodeXMin = 0.0f; m_defaultNodeYMin = 0.0f; m_defaultNodeXMax = m_defaultNodeXMin + DNodeView.DEFAULT_WIDTH; m_defaultNodeYMax = m_defaultNodeYMin + DNodeView.DEFAULT_HEIGHT; m_networkCanvas = new InnerCanvas(m_lock, this, undo); m_backgroundCanvas = new ArbitraryGraphicsCanvas(this, m_networkCanvas, Color.white, true, true); addViewportChangeListener(m_backgroundCanvas); m_foregroundCanvas = new ArbitraryGraphicsCanvas(this, m_networkCanvas, Color.white, true, false); addViewportChangeListener(m_foregroundCanvas); m_selectedNodes = new LongBTree(); m_selectedEdges = new LongBTree(); m_selectedAnchors = new LongBTree(); logger.debug("Phase 2: Canvas created: time = " + (System.currentTimeMillis() - start)); this.title = model.getRow(model).get(CyNetwork.NAME, String.class); // Create view model / presentations for the graph for (final CyNode nn : model.getNodeList()) addNodeView(nn); for (final CyEdge ee : model.getEdgeList()) addEdgeView(ee); logger.debug("Phase 3: All views created: time = " + (System.currentTimeMillis() - start)); // Used to synchronize ding's internal selection state with the rest of Cytoscape. new FlagAndSelectionHandler(this); logger.debug("Phase 4: Everything created: time = " + (System.currentTimeMillis() - start)); setGraphLOD(dingGraphLOD); // Finally, intialize our annotations this.cyAnnotator = new CyAnnotator(this, annMgr); //Updating the snapshot for nested networks this.addContentChangeListener(new DGraphViewContentChangeListener()); } @Override public CyNetwork getNetwork() { return model; } /** * Whether node selection is enabled. * * @return Whether node selection is enabled. */ @Override public boolean nodeSelectionEnabled() { return m_nodeSelection; } /** * Whether edge selection is enabled. * * @return Whether edge selection is enabled. */ @Override public boolean edgeSelectionEnabled() { return m_edgeSelection; } /** * Enabling the ability to select nodes. */ @Override public void enableNodeSelection() { synchronized (m_lock) { m_nodeSelection = true; } } /** * Disables the ability to select nodes. */ @Override public void disableNodeSelection() { final long[] unselectedNodes; synchronized (m_lock) { m_nodeSelection = false; unselectedNodes = getSelectedNodeIndices(); if (unselectedNodes.length > 0) { // Adding this line to speed things up from O(n*log(n)) to O(n). m_selectedNodes.empty(); for (int i = 0; i < unselectedNodes.length; i++) ((DNodeView) getDNodeView(unselectedNodes[i])) .unselectInternal(); m_contentChanged = true; } } if (unselectedNodes.length > 0) { final GraphViewChangeListener listener = m_lis[0]; if (listener != null) { listener.graphViewChanged(new GraphViewNodesUnselectedEvent( this, makeNodeList(unselectedNodes, this))); } } } /** * Enables the ability to select edges. */ @Override public void enableEdgeSelection() { synchronized (m_lock) { m_edgeSelection = true; } } /** * Disables the ability to select edges. */ @Override public void disableEdgeSelection() { final long[] unselectedEdges; synchronized (m_lock) { m_edgeSelection = false; unselectedEdges = getSelectedEdgeIndices(); if (unselectedEdges.length > 0) { // Adding this line to speed things up from O(n*log(n)) to O(n). m_selectedEdges.empty(); for (int i = 0; i < unselectedEdges.length; i++) getDEdgeView(unselectedEdges[i]).unselectInternal(); m_contentChanged = true; } } if (unselectedEdges.length > 0) { final GraphViewChangeListener listener = m_lis[0]; if (listener != null) { listener.graphViewChanged(new GraphViewEdgesUnselectedEvent( this, makeEdgeList(unselectedEdges, this))); } // Update the view after listener events are fired because listeners // may change something in the graph. updateView(); } } /** * Returns an array of selected node indices. * * @return An array of selected node indices. */ @Override public long[] getSelectedNodeIndices() { synchronized (m_lock) { // all nodes from the btree final LongEnumerator elms = m_selectedNodes.searchRange( Integer.MIN_VALUE, Integer.MAX_VALUE, false); final long[] returnThis = new long[elms.numRemaining()]; for (int i = 0; i < returnThis.length; i++) // GINY requires all node indices to be negative (why?), // hence the bitwise complement here. returnThis[i] = elms.nextLong(); return returnThis; } } /** * Returns a list of selected node objects. * * @return A list of selected node objects. */ @Override public List<CyNode> getSelectedNodes() { synchronized (m_lock) { // all nodes from the btree final LongEnumerator elms = m_selectedNodes.searchRange(Integer.MIN_VALUE, Integer.MAX_VALUE, false); final ArrayList<CyNode> returnThis = new ArrayList<CyNode>(); while (elms.numRemaining() > 0) // GINY requires all node indices to be negative (why?), // hence the bitwise complement here. returnThis.add(model.getNode(elms.nextLong())); return returnThis; } } /** * Returns an array of selected edge indices. * * @return An array of selected edge indices. */ @Override public long[] getSelectedEdgeIndices() { synchronized (m_lock) { final LongEnumerator elms = m_selectedEdges.searchRange(Integer.MIN_VALUE, Integer.MAX_VALUE, false); final long[] returnThis = new long[elms.numRemaining()]; for (int i = 0; i < returnThis.length; i++) returnThis[i] = elms.nextLong(); return returnThis; } } /** * Returns a list of selected edge objects. * * @return A list of selected edge objects. */ @Override public List<CyEdge> getSelectedEdges() { synchronized (m_lock) { final LongEnumerator elms = m_selectedEdges.searchRange(Integer.MIN_VALUE, Integer.MAX_VALUE, false); final ArrayList<CyEdge> returnThis = new ArrayList<CyEdge>(); while (elms.numRemaining() > 0) returnThis.add(model.getEdge(elms.nextLong())); return returnThis; } } /** * Add GraphViewChangeListener to linked list of GraphViewChangeListeners. * AAAAAARRRGGGGHHHHHH!!!! * * @param l * GraphViewChangeListener to be added to the list. */ @Override public void addGraphViewChangeListener(GraphViewChangeListener l) { m_lis[0] = GraphViewChangeListenerChain.add(m_lis[0], l); } /** * Remove GraphViewChangeListener from linked list of * GraphViewChangeListeners. AAAAAARRRGGGGHHHHHH!!!! * * @param l * GraphViewChangeListener to be removed from the list. */ @Override public void removeGraphViewChangeListener(GraphViewChangeListener l) { m_lis[0] = GraphViewChangeListenerChain.remove(m_lis[0], l); } /** * Sets the background color on the canvas. * * @param paint * The Paint (color) to apply to the background. */ @Override public void setBackgroundPaint(Paint paint) { synchronized (m_lock) { if (paint instanceof Color) { m_backgroundCanvas.setBackground((Color) paint); m_contentChanged = true; } else { logger.debug("DGraphView.setBackgroundPaint(), Color not found."); } } } /** * Returns the background color on the canvas. * * @return The background color on the canvas. */ @Override public Paint getBackgroundPaint() { return m_backgroundCanvas.getBackground(); } /** * Returns the InnerCanvas object. The InnerCanvas object is the actual * component that the network is rendered on. * * @return The InnerCanvas object. */ @Override public Component getComponent() { return m_networkCanvas; } /** * Adds a NodeView object to the GraphView. Creates NodeView if one doesn't * already exist. * * @param nodeInx * The index of the NodeView object to be added. * * @return The NodeView object that is added to the GraphView. */ @Override public NodeView addNodeView(final CyNode node) { final DNodeView newView; synchronized (m_lock) { newView = addNodeViewInternal(node); // View already exists. if (newView == null) return nodeViewMap.get(node); m_contentChanged = true; } final GraphViewChangeListener listener = m_lis[0]; if (listener != null) { listener.graphViewChanged(new GraphViewNodesRestoredEvent(this, makeList(newView.getModel()))); } return newView; } /** * Should synchronize around m_lock. */ private final DNodeView addNodeViewInternal(final CyNode node) { final long nodeInx = node.getSUID(); final NodeView oldView = nodeViewMap.get(node); if (oldView != null) return null; m_drawPersp.addNode(node); final DNodeView dNodeView = new DNodeView(lexicon, this, node, vmm, netViewMgr); // WARNING: DO not call the following in view creation. This is VERY slow. //Boolean selected = getModel().getRow(node).get(CyNetwork.SELECTED, Boolean.class); //if (selected != null && selected) // dNodeView.select(); nodeViewMap.put(node, dNodeView); m_spacial.insert(nodeInx, m_defaultNodeXMin, m_defaultNodeYMin, m_defaultNodeXMax, m_defaultNodeYMax); cyEventHelper.addEventPayload((CyNetworkView) this, (View<CyNode>) dNodeView, AddedNodeViewsEvent.class); return dNodeView; } /** * Adds EdgeView to the GraphView. * * @param edgeInx * The index of EdgeView to be added. * * @return The EdgeView that was added. */ @Override public EdgeView addEdgeView(final CyEdge edge) { if (edge == null) throw new NullPointerException("edge is null"); final NodeView sourceNode; final NodeView targetNode; final DEdgeView dEdgeView; synchronized (m_lock) { final EdgeView oldView = edgeViewMap.get(edge); if (oldView != null) return oldView; sourceNode = addNodeViewInternal(edge.getSource()); targetNode = addNodeViewInternal(edge.getTarget()); m_drawPersp.addEdge(edge); dEdgeView = new DEdgeView(this, edge, handleFactory, lexicon); edgeViewMap.put(edge, dEdgeView); m_contentChanged = true; } // Under no circumstances should we be holding m_lock when the listener // events are fired. final GraphViewChangeListener listener = m_lis[0]; if (listener != null) { // Only fire this event if either of the nodes is new. The node // will be null if it already existed. if ((sourceNode != null) || (targetNode != null)) { long[] nodeInx; if (sourceNode == null) { nodeInx = new long[] { targetNode.getCyNode().getSUID() }; } else if (targetNode == null) { nodeInx = new long[] { sourceNode.getCyNode().getSUID() }; } else { nodeInx = new long[] { sourceNode.getCyNode().getSUID(), targetNode.getCyNode().getSUID()}; } listener.graphViewChanged(new GraphViewNodesRestoredEvent(this, makeNodeList(nodeInx, this))); } listener.graphViewChanged(new GraphViewEdgesRestoredEvent(this, makeList(dEdgeView.getCyEdge()))); } cyEventHelper.addEventPayload((CyNetworkView) this, (View<CyEdge>) dEdgeView, AddedEdgeViewsEvent.class); return dEdgeView; } /** * Removes a NodeView based on specified NodeView. * * @param nodeView * The NodeView object to be removed. * * @return The NodeView object that was removed. */ @Override public NodeView removeNodeView(NodeView nodeView) { return removeNodeView(nodeView.getCyNode().getSUID()); } /** * Removes a NodeView based on specified Node. * * @param node * The Node object connected to the NodeView to be removed. * * @return The NodeView object that was removed. */ @Override public NodeView removeNodeView(CyNode node) { return removeNodeView(node.getSUID()); } /** * Removes a NodeView based on a specified index. * * @param nodeInx * The index of the NodeView to be removed. * * @return The NodeView object that was removed. */ @Override public NodeView removeNodeView(long nodeInx) { final List<CyEdge> hiddenEdgeInx; final DNodeView returnThis; final CyNode nnode; nnode = model.getNode(nodeInx); returnThis = (DNodeView) nodeViewMap.get(nnode); if (returnThis == null) { return null; } cyEventHelper.addEventPayload((CyNetworkView) this, (View<CyNode>) returnThis, AboutToRemoveNodeViewsEvent.class); synchronized (m_lock) { // We have to query edges in the m_structPersp, not m_drawPersp // because what if the node is hidden? hiddenEdgeInx = model.getAdjacentEdgeList(nnode, CyEdge.Type.ANY); // This isn't an error. Only if the nodeInx is invalid will // getAdjacentEdgeIndicesArray // return null. If there are no adjacent edges, then it will return // an array of length 0. if (hiddenEdgeInx == null) return null; for (final CyEdge ee : hiddenEdgeInx) removeEdgeViewInternal(ee); nodeViewMap.remove(nnode); returnThis.unselectInternal(); // If this node was hidden, it won't be in m_drawPersp. m_drawPersp.removeNodes(Collections.singletonList(nnode)); // m_structPersp.removeNode(nodeInx); m_nodeDetails.unregisterNode(nnode); // If this node was hidden, it won't be in m_spacial. m_spacial.delete(nodeInx); m_contentChanged = true; } final GraphViewChangeListener listener = m_lis[0]; if (listener != null) { if (hiddenEdgeInx.size() > 0) { listener.graphViewChanged(new GraphViewEdgesHiddenEvent(this, hiddenEdgeInx)); } listener.graphViewChanged(new GraphViewNodesHiddenEvent(this, makeList(returnThis.getModel()))); } return returnThis; } /** * Removes an EdgeView based on an EdgeView. * * @param edgeView * The EdgeView to be removed. * * @return The EdgeView that was removed. */ @Override public EdgeView removeEdgeView(EdgeView edgeView) { return removeEdgeView(edgeView.getCyEdge().getSUID()); } /** * Removes an EdgeView based on an Edge. * * @param edge * The Edge of the EdgeView to be removed. * * @return The EdgeView that was removed. */ @Override public EdgeView removeEdgeView(CyEdge edge) { return removeEdgeView(edge.getSUID()); } /** * Removes an EdgeView based on an EdgeIndex. * * @param edgeInx * The edge index of the EdgeView to be removed. * * @return The EdgeView that was removed. */ @Override public EdgeView removeEdgeView(long edgeInx) { final DEdgeView returnThis; final CyEdge edge; edge = model.getEdge(edgeInx); if (edge == null) { return null; } EdgeView view = edgeViewMap.get(edge); if (view == null) { return null; } cyEventHelper.addEventPayload((CyNetworkView) this, (View<CyEdge>) view, AboutToRemoveEdgeViewsEvent.class); synchronized (m_lock) { returnThis = removeEdgeViewInternal(edge); if (returnThis != null) { m_contentChanged = true; } } if (returnThis != null) { final GraphViewChangeListener listener = m_lis[0]; if (listener != null) { listener.graphViewChanged(new GraphViewEdgesHiddenEvent(this, makeList(edge))); } } return returnThis; } /** * Should synchronize around m_lock. */ private DEdgeView removeEdgeViewInternal(CyEdge edge) { // We can't remove this yet, because the map is used // later in unselectInternal... final DEdgeView returnThis = (DEdgeView)edgeViewMap.get(edge); if (returnThis == null) { return returnThis; } returnThis.unselectInternal(); // Now we can remove it edgeViewMap.remove(edge); m_drawPersp.removeEdges(Collections.singletonList(edge)); m_edgeDetails.unregisterEdge(edge); return returnThis; } @Override public Long getIdentifier() { return m_identifier; } @Override public void setIdentifier(Long id) { m_identifier = id; } @Override public double getZoom() { return m_networkCanvas.m_scaleFactor; } /** * Set the zoom level and redraw the view. */ @Override public void setZoom(final double zoom) { synchronized (m_lock) { m_networkCanvas.m_scaleFactor = checkZoom(zoom, m_networkCanvas.m_scaleFactor); m_viewportChanged = true; } } private void fitContent(final boolean updateView) { cyEventHelper.flushPayloadEvents(); synchronized (m_lock) { if (m_spacial.queryOverlap(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, m_extentsBuff, 0, false).numRemaining() == 0) { return; } // At this point, we actually want doubles m_extentsBuffD[0] = (double)m_extentsBuff[0]; m_extentsBuffD[1] = (double)m_extentsBuff[1]; m_extentsBuffD[2] = (double)m_extentsBuff[2]; m_extentsBuffD[3] = (double)m_extentsBuff[3]; // Adjust the content based on the foreground canvas m_foregroundCanvas.adjustBounds(m_extentsBuffD); // Adjust the content based on the background canvas m_backgroundCanvas.adjustBounds(m_extentsBuffD); if (!isValueLocked(BasicVisualLexicon.NETWORK_CENTER_X_LOCATION)) setVisualProperty(BasicVisualLexicon.NETWORK_CENTER_X_LOCATION, (m_extentsBuffD[0] + m_extentsBuffD[2]) / 2.0d); if (!isValueLocked(BasicVisualLexicon.NETWORK_CENTER_Y_LOCATION)) setVisualProperty(BasicVisualLexicon.NETWORK_CENTER_Y_LOCATION, (m_extentsBuffD[1] + m_extentsBuffD[3]) / 2.0d); if (!isValueLocked(BasicVisualLexicon.NETWORK_SCALE_FACTOR)) { // Apply a factor 0.98 to zoom, so that it leaves a small border around the network and any annotations. final double zoom = Math.min(((double) m_networkCanvas.getWidth()) / (m_extentsBuffD[2] - m_extentsBuffD[0]), ((double) m_networkCanvas.getHeight()) / (m_extentsBuffD[3] - m_extentsBuffD[1])) * 0.98; // Update view model. Zoom Level should be modified. setVisualProperty(BasicVisualLexicon.NETWORK_SCALE_FACTOR, zoom); } } if (updateView) this.updateView(); } /** * Resize the network view to the size of the canvas and redraw it. */ @Override public void fitContent() { fitContent(/* updateView = */ true); } /** * Redraw the canvas. */ @Override public void updateView() { //System.out.println(this.toString() + ": Update view called: " + this.model); //Thread.dumpStack(); //final long start = System.currentTimeMillis(); cyEventHelper.flushPayloadEvents(); m_networkCanvas.repaint(); //Check if image size has changed if so, visual property needs to be changed as well if (m_networkCanvas.getWidth() != imageWidth || m_networkCanvas.getHeight() != imageHeight) { imageWidth = m_networkCanvas.getWidth(); imageHeight = m_networkCanvas.getHeight(); setVisualProperty(BasicVisualLexicon.NETWORK_WIDTH,(double)imageWidth); setVisualProperty(BasicVisualLexicon.NETWORK_HEIGHT,(double)imageHeight); } //System.out.println("Repaint finished in " + (System.currentTimeMillis() - start) + " msec."); // Fire for updating other presentations. cyEventHelper.fireEvent(new UpdateNetworkPresentationEvent(this)); } /** * Returns an iterator of all node views, including those that are currently * hidden. * * @return DOCUMENT ME! */ @Override public Iterator<NodeView> getNodeViewsIterator() { synchronized (m_lock) { return nodeViewMap.values().iterator(); } } /** * Returns the count of all node views, including those that are currently * hidden. * * @return DOCUMENT ME! */ @Override public int getNodeViewCount() { synchronized (m_lock) { return nodeViewMap.size(); } } /** * Returns the count of all edge views, including those that are currently * hidden. * * @return DOCUMENT ME! */ @Override public int getEdgeViewCount() { synchronized (m_lock) { return edgeViewMap.size(); } } @Override public DNodeView getDNodeView(final CyNode node) { // TODO: remove cast! if (node != null && nodeViewMap.containsKey(node)) return (DNodeView)nodeViewMap.get(node); else return null; } @Override public DNodeView getDNodeView(final long nodeInx) { return getDNodeView(model.getNode(nodeInx)); } @Override public List<EdgeView> getEdgeViewsList() { synchronized (m_lock) { final ArrayList<EdgeView> returnThis = new ArrayList<EdgeView>( edgeViewMap.size()); final Iterator<EdgeView> values = edgeViewMap.values().iterator(); while (values.hasNext()) returnThis.add(values.next()); return returnThis; } } /** * Returns all edge views (including the hidden ones) that are either 1. * directed, having oneNode as source and otherNode as target or 2. * undirected, having oneNode and otherNode as endpoints. Note that this * behaviour is similar to that of CyNetwork.edgesList(Node, Node). * * @param oneNode * DOCUMENT ME! * @param otherNode * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public List<EdgeView> getEdgeViewsList(CyNode oneNode, CyNode otherNode) { synchronized (m_lock) { List<CyEdge> edges = model.getConnectingEdgeList(oneNode, otherNode, CyEdge.Type.ANY); if (edges == null) { return null; } final ArrayList<EdgeView> returnThis = new ArrayList<EdgeView>(); Iterator<CyEdge> it = edges.iterator(); while (it.hasNext()) { CyEdge e = it.next(); EdgeView ev = getDEdgeView(e); if (ev != null) returnThis.add(ev); } return returnThis; } } /** * Similar to getEdgeViewsList(Node, Node), only that one has control of * whether or not to include undirected edges. * * @param oneNodeInx * DOCUMENT ME! * @param otherNodeInx * DOCUMENT ME! * @param includeUndirected * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public List<EdgeView> getEdgeViewsList(long oneNodeInx, long otherNodeInx, boolean includeUndirected) { CyNode n1; CyNode n2; synchronized (m_lock) { n1 = model.getNode(oneNodeInx); n2 = model.getNode(otherNodeInx); } return getEdgeViewsList(n1, n2); } /** * {@inheritDoc} */ @Override public DEdgeView getDEdgeView(final long edgeInx) { return getDEdgeView(model.getEdge(edgeInx)); } @Override public Iterator<EdgeView> getEdgeViewsIterator() { return edgeViewMap.values().iterator(); } @Override public DEdgeView getDEdgeView(final CyEdge edge) { if (edge == null) { return null; } return (DEdgeView)edgeViewMap.get(edge); } @Override public int edgeCount() { return getEdgeViewCount(); } @Override public int nodeCount() { return getNodeViewCount(); } @Override public boolean hideGraphObject(Object obj) { return hideGraphObjectInternal(obj, true); } private boolean hideGraphObjectInternal(Object obj, boolean fireListenerEvents) { if (obj instanceof DEdgeView) { final DEdgeView eView = (DEdgeView) obj; final CyEdge edge; synchronized (m_lock) { edge = eView.getCyEdge(); if (!m_drawPersp.removeEdges(Collections.singletonList(edge))) return false; eView.unselectInternal(); m_contentChanged = true; } if (fireListenerEvents) { final GraphViewChangeListener listener = m_lis[0]; if (listener != null) { listener.graphViewChanged(new GraphViewEdgesHiddenEvent(this, makeList(eView.getCyEdge()))); } } return true; } else if (obj instanceof DNodeView) { List<CyEdge> edges; long nodeInx; CyNode nnode; synchronized (m_lock) { final DNodeView nView = (DNodeView) obj; nodeInx = nView.getCyNode().getSUID(); nnode = model.getNode(nodeInx); // If the node is already hidden, don't do anything. if (m_drawPersp.getNode(nodeInx) == null) return false; edges = m_drawPersp.getAdjacentEdgeList(nnode, CyEdge.Type.ANY); if (edges != null) { for (final CyEdge ee : edges) hideGraphObjectInternal(edgeViewMap.get(ee), false); } nView.unselectInternal(); m_spacial.exists(nodeInx, m_extentsBuff, 0); nView.m_hiddenXMin = m_extentsBuff[0]; nView.m_hiddenYMin = m_extentsBuff[1]; nView.m_hiddenXMax = m_extentsBuff[2]; nView.m_hiddenYMax = m_extentsBuff[3]; m_drawPersp.removeNodes(Collections.singletonList(nnode)); m_spacial.delete(nodeInx); m_contentChanged = true; } if (fireListenerEvents) { final GraphViewChangeListener listener = m_lis[0]; if (listener != null) { if (edges != null && edges.size() > 0) { listener.graphViewChanged(new GraphViewEdgesHiddenEvent( this, edges)); } listener.graphViewChanged(new GraphViewNodesHiddenEvent( this, makeList(nnode))); } } return true; } else { return false; } } final boolean isHidden(final DEdgeView edgeView) { synchronized (m_lock) { final long edgeIndex = edgeView.getCyEdge().getSUID(); return !m_drawPersp.containsEdge(m_drawPersp.getEdge(edgeIndex)); } } final boolean isHidden(final DNodeView nodeView) { synchronized (m_lock) { final long nodeIndex = nodeView.getCyNode().getSUID(); return !m_drawPersp.containsNode(m_drawPersp.getNode(nodeIndex)); } } /** * @param obj * should be either a DEdgeView or a DNodeView. * * @return DOCUMENT ME! */ @Override public boolean showGraphObject(Object obj) { return showGraphObjectInternal(obj, true); } private boolean showGraphObjectInternal(Object obj, boolean fireListenerEvents) { if (obj instanceof DNodeView) { long nodeInx; final DNodeView nView = (DNodeView) obj; synchronized (m_lock) { nodeInx = nView.getCyNode().getSUID(); CyNode nnode = model.getNode(nodeInx); if (nnode == null || !m_drawPersp.addNode(nnode)) return false; m_spacial.insert(nodeInx, nView.m_hiddenXMin, nView.m_hiddenYMin, nView.m_hiddenXMax, nView.m_hiddenYMax); m_contentChanged = true; } if (fireListenerEvents) { final GraphViewChangeListener listener = m_lis[0]; if (listener != null) { listener.graphViewChanged(new GraphViewNodesRestoredEvent( this, makeList(nView.getModel()))); } } return true; } else if (obj instanceof DEdgeView) { CyNode sourceNode; CyNode targetNode; CyEdge newEdge; synchronized (m_lock) { final CyEdge edge = model.getEdge(((DEdgeView) obj).getCyEdge().getSUID()); if (edge == null) return false; // The edge exists in m_structPersp, therefore its source and target // node views must also exist. sourceNode = edge.getSource(); targetNode = edge.getTarget(); final DNodeView srcDnv = getDNodeView(sourceNode); final DNodeView tgtDnv = getDNodeView(targetNode); if (isHidden(srcDnv) || isHidden(tgtDnv)) return false; if (!showGraphObjectInternal(srcDnv, false)) sourceNode = null; if (!showGraphObjectInternal(tgtDnv, false)) targetNode = null; newEdge = edge; if (!m_drawPersp.addEdge(newEdge)) return false; m_contentChanged = true; } if (fireListenerEvents) { final GraphViewChangeListener listener = m_lis[0]; if (listener != null) { if (sourceNode != null) { listener.graphViewChanged(new GraphViewNodesRestoredEvent(this, makeList(sourceNode))); } if (targetNode != null) { listener.graphViewChanged(new GraphViewNodesRestoredEvent(this, makeList(targetNode))); } listener.graphViewChanged(new GraphViewEdgesRestoredEvent(this, makeList(newEdge))); } } return true; } else { return false; } } @Override public boolean hideGraphObjects(List<? extends GraphViewObject> objects) { final Iterator<? extends GraphViewObject> it = objects.iterator(); while (it.hasNext()) hideGraphObject(it.next()); return true; } /** * DOCUMENT ME! * * @param objects * DOCUMENT ME! * * @return DOCUMENT ME! */ @Override public boolean showGraphObjects(List<? extends GraphViewObject> objects) { final Iterator<? extends GraphViewObject> it = objects.iterator(); while (it.hasNext()) showGraphObject(it.next()); return true; } // Auxiliary methods specific to this GraphView implementation: @Override public void setCenter(double x, double y) { synchronized (m_lock) { m_networkCanvas.setCenter(x,y); m_viewportChanged = true; // Update view model // TODO: don't do it from here? setVisualProperty(BasicVisualLexicon.NETWORK_CENTER_X_LOCATION, m_networkCanvas.m_xCenter); setVisualProperty(BasicVisualLexicon.NETWORK_CENTER_Y_LOCATION, m_networkCanvas.m_yCenter); } } public Point2D getCenter() { synchronized (m_lock) { return new Point2D.Double(m_networkCanvas.m_xCenter, m_networkCanvas.m_yCenter); } } @Override public void fitSelected() { cyEventHelper.flushPayloadEvents(); synchronized (m_lock) { LongEnumerator selectedElms = m_selectedNodes.searchRange(Integer.MIN_VALUE, Integer.MAX_VALUE, false); // Only check for selected edges if we don't have selected nodes. if (selectedElms.numRemaining() == 0 && edgeSelectionEnabled()) { selectedElms = getSelectedEdgeNodes(); if (selectedElms.numRemaining() == 0) return; } float xMin = Float.POSITIVE_INFINITY; float yMin = Float.POSITIVE_INFINITY; float xMax = Float.NEGATIVE_INFINITY; float yMax = Float.NEGATIVE_INFINITY; long leftMost = 0; long rightMost = 0; while (selectedElms.numRemaining() > 0) { final long node = selectedElms.nextLong(); m_spacial.exists(node, m_extentsBuff, 0); if (m_extentsBuff[0] < xMin) { xMin = m_extentsBuff[0]; leftMost = node; } if (m_extentsBuff[2] > xMax) { xMax = m_extentsBuff[2]; rightMost = node; } yMin = Math.min(yMin, m_extentsBuff[1]); yMax = Math.max(yMax, m_extentsBuff[3]); } xMin = xMin - (getLabelWidth(leftMost) / 2); xMax = xMax + (getLabelWidth(rightMost) / 2); if (!isValueLocked(BasicVisualLexicon.NETWORK_CENTER_Y_LOCATION)) { double zoom = Math.min(((double) m_networkCanvas.getWidth()) / (((double) xMax) - ((double) xMin)), ((double) m_networkCanvas.getHeight()) / (((double) yMax) - ((double) yMin))); zoom = checkZoom(zoom, m_networkCanvas.m_scaleFactor); // Update view model. Zoom Level should be modified. setVisualProperty(BasicVisualLexicon.NETWORK_SCALE_FACTOR, zoom); } if (!isValueLocked(BasicVisualLexicon.NETWORK_CENTER_X_LOCATION)) { final double xCenter = (((double) xMin) + ((double) xMax)) / 2.0d; setVisualProperty(BasicVisualLexicon.NETWORK_CENTER_X_LOCATION, xCenter); } if (!isValueLocked(BasicVisualLexicon.NETWORK_CENTER_Y_LOCATION)) { final double yCenter = (((double) yMin) + ((double) yMax)) / 2.0d; setVisualProperty(BasicVisualLexicon.NETWORK_CENTER_Y_LOCATION, yCenter); } } updateView(); } /** * @return An LongEnumerator listing the nodes that are endpoints of the * currently selected edges. */ private LongEnumerator getSelectedEdgeNodes() { synchronized (m_lock) { final LongEnumerator selectedEdges = m_selectedEdges.searchRange(Integer.MIN_VALUE,Integer.MAX_VALUE,false); final LongHash nodeIds = new LongHash(); while (selectedEdges.numRemaining() > 0) { final long edge = selectedEdges.nextLong(); CyEdge currEdge = model.getEdge(edge); CyNode source = currEdge.getSource(); long sourceId = source.getSUID(); nodeIds.put(sourceId); CyNode target = currEdge.getTarget(); long targetId = target.getSUID(); nodeIds.put(targetId); } return nodeIds.elements(); } } private int getLabelWidth(long node) { DNodeView x = ((DNodeView) getDNodeView(node)); if (x == null) return 0; String s = x.getText(); if (s == null) return 0; char[] lab = s.toCharArray(); if (lab == null) return 0; if (m_networkCanvas.m_fontMetrics == null) return 0; return m_networkCanvas.m_fontMetrics.charsWidth(lab, 0, lab.length); } @Override public void setGraphLOD(GraphLOD lod) { synchronized (m_lock) { m_networkCanvas.m_lod[0] = lod; m_contentChanged = true; } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public GraphLOD getGraphLOD() { return m_networkCanvas.m_lod[0]; } @Override public void setPrintingTextAsShape(boolean textAsShape) { synchronized (m_lock) { m_printLOD.setPrintingTextAsShape(textAsShape); } } /** * Efficiently computes the set of nodes intersecting an axis-aligned query * rectangle; the query rectangle is specified in the node coordinate * system, not the component coordinate system. * <p> * NOTE: The order of elements placed on the stack follows the rendering * order of nodes; the element waiting to be popped off the stack is the * node that is rendered last, and thus is "on top of" other nodes * potentially beneath it. * <p> * HINT: To perform a point query simply set xMin equal to xMax and yMin * equal to yMax. * * @param xMinimum * a boundary of the query rectangle: the minimum X coordinate. * @param yMinimum * a boundary of the query rectangle: the minimum Y coordinate. * @param xMaximum * a boundary of the query rectangle: the maximum X coordinate. * @param yMaximum * a boundary of the query rectangle: the maximum Y coordinate. * @param treatNodeShapesAsRectangle * if true, nodes are treated as rectangles for purposes of the * query computation; if false, true node shapes are respected, * at the expense of slowing down the query by a constant factor. * @param returnVal * RootGraph indices of nodes intersecting the query rectangle * will be placed onto this stack; the stack is not emptied by * this method initially. */ public void getNodesIntersectingRectangle(double xMinimum, double yMinimum, double xMaximum, double yMaximum, boolean treatNodeShapesAsRectangle, LongStack returnVal) { synchronized (m_lock) { final float xMin = (float) xMinimum; final float yMin = (float) yMinimum; final float xMax = (float) xMaximum; final float yMax = (float) yMaximum; final SpacialEntry2DEnumerator under = m_spacial.queryOverlap(xMin, yMin, xMax, yMax, null, 0, false); final int totalHits = under.numRemaining(); if (treatNodeShapesAsRectangle) { for (int i = 0; i < totalHits; i++) returnVal.push(under.nextLong()); } else { final double x = xMin; final double y = yMin; final double w = ((double) xMax) - xMin; final double h = ((double) yMax) - yMin; for (int i = 0; i < totalHits; i++) { final long node = under.nextExtents(m_extentsBuff, 0); final CyNode cyNode = model.getNode(node); // The only way that the node can miss the intersection // query is // if it intersects one of the four query rectangle's // corners. if (((m_extentsBuff[0] < xMin) && (m_extentsBuff[1] < yMin)) || ((m_extentsBuff[0] < xMin) && (m_extentsBuff[3] > yMax)) || ((m_extentsBuff[2] > xMax) && (m_extentsBuff[3] > yMax)) || ((m_extentsBuff[2] > xMax) && (m_extentsBuff[1] < yMin))) { m_networkCanvas.m_grafx.getNodeShape(m_nodeDetails.getShape(cyNode), m_extentsBuff[0], m_extentsBuff[1], m_extentsBuff[2], m_extentsBuff[3], m_path); if ((w > 0) && (h > 0)) { if (m_path.intersects(x, y, w, h)) returnVal.push(node); } else { if (m_path.contains(x, y)) returnVal.push(node); } } else returnVal.push(node); } } } } /** * DOCUMENT ME! * * @param xMin * DOCUMENT ME! * @param yMin * DOCUMENT ME! * @param xMax * DOCUMENT ME! * @param yMax * DOCUMENT ME! * @param returnVal * DOCUMENT ME! */ public void queryDrawnEdges(int xMin, int yMin, int xMax, int yMax, LongStack returnVal) { synchronized (m_lock) { m_networkCanvas.computeEdgesIntersecting(xMin, yMin, xMax, yMax, returnVal); } } /** * Extents of the nodes. */ public boolean getExtents(double[] extentsBuff) { synchronized (m_lock) { if (m_spacial.queryOverlap(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, m_extentsBuff, 0, false) .numRemaining() == 0) { return false; } extentsBuff[0] = m_extentsBuff[0]; extentsBuff[1] = m_extentsBuff[1]; extentsBuff[2] = m_extentsBuff[2]; extentsBuff[3] = m_extentsBuff[3]; return true; } } /** * DOCUMENT ME! * * @param coords * DOCUMENT ME! */ @Override public void xformComponentToNodeCoords(double[] coords) { synchronized (m_lock) { m_networkCanvas.m_grafx.xformImageToNodeCoords(coords); } } /** * DOCUMENT ME! * * @param coords * DOCUMENT ME! */ public void xformNodeToComponentCoords(double[] coords) { synchronized (m_lock) { m_networkCanvas.m_grafx.xformNodetoImageCoords(coords); } } /** * This method is called by the BirdsEyeView to get a snapshot of the graphics. * * @param img * DOCUMENT ME! * @param lod * DOCUMENT ME! * @param bgPaint * DOCUMENT ME! * @param xCenter * DOCUMENT ME! * @param yCenter * DOCUMENT ME! * @param scaleFactor * DOCUMENT ME! */ //TODO: Need to fix up scaling and sizing. public void drawSnapshot(VolatileImage img, GraphLOD lod, Paint bgPaint, double xMin, double yMin, double xCenter, double yCenter, double scaleFactor) { // First paint the background m_backgroundCanvas.drawCanvas(img, xMin, yMin, xCenter, yCenter, scaleFactor); synchronized (m_lock) { GraphRenderer.renderGraph(m_drawPersp, m_spacial, lod, m_nodeDetails, m_edgeDetails, m_hash, new GraphGraphics(img, false, false), bgPaint, xCenter, yCenter, scaleFactor); } // Finally, draw the foreground m_foregroundCanvas.drawCanvas(img, xMin, yMin, xCenter, yCenter, scaleFactor); } /** * DOCUMENT ME! * * @param l * DOCUMENT ME! */ public void addContentChangeListener(ContentChangeListener l) { m_cLis[0] = ContentChangeListenerChain.add(m_cLis[0], l); } /** * DOCUMENT ME! * * @param l * DOCUMENT ME! */ public void removeContentChangeListener(ContentChangeListener l) { m_cLis[0] = ContentChangeListenerChain.remove(m_cLis[0], l); } public ContentChangeListener getContentChangeListener() { return m_cLis[0]; } /** * DOCUMENT ME! * * @param l * DOCUMENT ME! */ public void addViewportChangeListener(ViewportChangeListener l) { m_vLis[0] = ViewportChangeListenerChain.add(m_vLis[0], l); } /** * DOCUMENT ME! * * @param l * DOCUMENT ME! */ public void removeViewportChangeListener(ViewportChangeListener l) { m_vLis[0] = ViewportChangeListenerChain.remove(m_vLis[0], l); } /** * DOCUMENT ME! * * @param g * DOCUMENT ME! * @param pageFormat * DOCUMENT ME! * @param page * DOCUMENT ME! * * @return DOCUMENT ME! */ public int print(Graphics g, PageFormat pageFormat, int page) { if (page == 0) { ((Graphics2D) g).translate(pageFormat.getImageableX(), pageFormat.getImageableY()); // make sure the whole image on the screen will fit to the printable // area of the paper double image_scale = Math .min(pageFormat.getImageableWidth() / m_networkCanvas.getWidth(), pageFormat.getImageableHeight() / m_networkCanvas.getHeight()); if (image_scale < 1.0d) { ((Graphics2D) g).scale(image_scale, image_scale); } // old school // g.clipRect(0, 0, getComponent().getWidth(), // getComponent().getHeight()); // getComponent().print(g); // from InternalFrameComponent g.clipRect(0, 0, m_backgroundCanvas.getWidth(), m_backgroundCanvas.getHeight()); m_backgroundCanvas.print(g); m_networkCanvas.print(g); m_foregroundCanvas.print(g); return PAGE_EXISTS; } else { return NO_SUCH_PAGE; } } /** * Method to return a reference to the network canvas. This method existed * before the addition of background and foreground canvases, and it remains * for backward compatibility. * * @return InnerCanvas */ public InnerCanvas getCanvas() { return m_networkCanvas; } /** * Method to return a reference to a DingCanvas object, given a canvas id. * * @param canvasId * Canvas * @return DingCanvas */ public DingCanvas getCanvas(Canvas canvasId) { if (canvasId == Canvas.BACKGROUND_CANVAS) { return m_backgroundCanvas; } else if (canvasId == Canvas.NETWORK_CANVAS) { return m_networkCanvas; } else if (canvasId == Canvas.FOREGROUND_CANVAS) { return m_foregroundCanvas; } // made it here return null; } private Image createImage(int width, final int height, double shrink, final boolean skipBackground) { // Validate arguments if (width < 0 || height < 0) { throw new IllegalArgumentException("DGraphView.createImage(int width, int height): " + "width and height arguments must be greater than zero"); } if (shrink < 0 || shrink > 1.0) { logger.debug("DGraphView.createImage(width,height,shrink) shrink is invalid: " + shrink + " using default of 1.0"); shrink = 1.0; } // We want the width and height to be the same proportions as our network Dimension originalSize = m_networkCanvas.getSize(); if (originalSize.getHeight() > 0.0 && originalSize.getWidth() > 0.0) { double ratio = (double)originalSize.getHeight() / (double) originalSize.getWidth(); width = (int)((double)height/ratio); } // create image to return final Image image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE); final Graphics g = image.getGraphics(); if (!skipBackground) { // paint background canvas into image originalSize = m_backgroundCanvas.getSize(); m_backgroundCanvas.setSize(width, height); m_backgroundCanvas.paint(g); // Restore background size m_backgroundCanvas.setSize(originalSize); } // paint inner canvas (network) originalSize = m_networkCanvas.getSize(); m_networkCanvas.setSize(width, height); fitContent(/* updateView = */ false); setZoom(getZoom() * shrink); m_networkCanvas.paint(g); // Restore network to original size m_networkCanvas.setSize(originalSize); fitContent(/* updateView = */ false); // paint foreground canvas originalSize = m_foregroundCanvas.getSize(); m_foregroundCanvas.setSize(width, height); m_foregroundCanvas.paint(g); // Restore foreground to original size m_foregroundCanvas.setSize(originalSize); return image; } public Image createImage(int width, int height, double shrink) { return createImage(width, height, shrink, /* skipBackground = */ false); } /** * utility that returns the nodeView that is located at input point * * @param pt */ public NodeView getPickedNodeView(Point2D pt) { NodeView nv = null; double[] locn = new double[2]; locn[0] = pt.getX(); locn[1] = pt.getY(); long chosenNode = 0; xformComponentToNodeCoords(locn); final LongStack nodeStack = new LongStack(); getNodesIntersectingRectangle( (float) locn[0], (float) locn[1], (float) locn[0], (float) locn[1], (m_networkCanvas.getLastRenderDetail() & GraphRenderer.LOD_HIGH_DETAIL) == 0, nodeStack); chosenNode = (nodeStack.size() > 0) ? nodeStack.peek() : -1; if (chosenNode >= 0) { nv = getDNodeView(chosenNode); } return nv; } /** * DOCUMENT ME! * * @param pt * DOCUMENT ME! * @return DOCUMENT ME! */ @Override public EdgeView getPickedEdgeView(Point2D pt) { EdgeView ev = null; final LongStack edgeStack = new LongStack(); queryDrawnEdges((int) pt.getX(), (int) pt.getY(), (int) pt.getX(), (int) pt.getY(), edgeStack); long chosenEdge = 0; chosenEdge = (edgeStack.size() > 0) ? edgeStack.peek() : -1; if (chosenEdge >= 0) { ev = getDEdgeView(chosenEdge); } return ev; } final float getAnchorSize() { return DEFAULT_ANCHOR_SIZE; } final Paint getAnchorSelectedPaint() { return DEFAULT_ANCHOR_SELECTED_PAINT; } final Paint getAnchorUnselectedPaint() { return DEFAULT_ANCHOR_UNSELECTED_PAINT; } private double checkZoom(double zoom, double orig) { if (zoom > 0) return zoom; logger.debug("invalid zoom: " + zoom + " using orig: " + orig); return orig; } private String title; /** * DOCUMENT ME! * * @param title * DOCUMENT ME! */ public void setTitle(String title) { this.title = title; } @Override public String getTitle() { return title; } /** * Set selected nodes * @param nodes * @return */ public boolean setSelected(final CyNode[] nodes) { for ( CyNode node : nodes ) getDNodeView(node).select(); return true; } public boolean setSelected(final CyEdge[] edges) { for ( CyEdge edge : edges ) getDEdgeView(edge).setSelected(true); return true; } public List<NodeView> getNodeViewsList() { ArrayList<NodeView> list = new ArrayList<NodeView>(getNodeViewCount()); for (CyNode nn : getNetwork().getNodeList()) list.add(getDNodeView(nn.getSUID())); return list; } /** * This method is used by freehep lib to export network as graphics. */ @Override public void print(Graphics g) { m_backgroundCanvas.print(g); m_networkCanvas.print(g); m_foregroundCanvas.print(g); } /** * This method is used by BitmapExporter to export network as graphics (png, * jpg, bmp) */ @Override public void printNoImposter(Graphics g) { m_backgroundCanvas.print(g); m_networkCanvas.printNoImposter(g); m_foregroundCanvas.print(g); } /** * Our implementation of Component setBounds(). If we don't do this, the * individual canvas do not get rendered. * * @param x * int * @param y * int * @param width * int * @param height * int */ @Override public void setBounds(int x, int y, int width, int height) { // call reshape on each canvas m_backgroundCanvas.setBounds(x, y, width, height); m_networkCanvas.setBounds(x, y, width, height); m_foregroundCanvas.setBounds(x, y, width, height); // If this is the first call to setBounds, load any annotations if (!annotationsLoaded) { annotationsLoaded = true; cyAnnotator.loadAnnotations(); } } @Override public void setSize(Dimension d) { m_networkCanvas.setSize(d); } @Override public Container getContainer(JLayeredPane jlp) { return new InternalFrameComponent(jlp, this); } @Override public void addMouseListener(MouseListener m) { m_networkCanvas.addMouseListener(m); } @Override public void addMouseMotionListener(MouseMotionListener m) { m_networkCanvas.addMouseMotionListener(m); } @Override public void addKeyListener(KeyListener k) { m_networkCanvas.addKeyListener(k); } @Override public void removeMouseListener(MouseListener m) { m_networkCanvas.removeMouseListener(m); } @Override public void removeMouseMotionListener(MouseMotionListener m) { m_networkCanvas.removeMouseMotionListener(m); } @Override public void removeKeyListener(KeyListener k) { m_networkCanvas.removeKeyListener(k); } static <X> List<X> makeList(X nodeOrEdge) { List<X> nl = new ArrayList<X>(1); nl.add(nodeOrEdge); return nl; } static List<CyNode> makeNodeList(long[] nodeids, GraphView view) { List<CyNode> l = new ArrayList<CyNode>(nodeids.length); for (long nid : nodeids) l.add(((DNodeView)view.getDNodeView(nid)).getModel()); return l; } static List<CyEdge> makeEdgeList(long[] edgeids, GraphView view) { List<CyEdge> l = new ArrayList<CyEdge>(edgeids.length); for (long nid : edgeids) l.add(view.getDEdgeView(nid).getCyEdge()); return l; } @Override public Printable createPrintable() { return this; } @Override public Properties getProperties() { return this.props; } /** * Common API for all rendering engines. */ @Override public Image createImage(int width, int height) { return createImage(width, height, 1, true); } @Override public VisualLexicon getVisualLexicon() { return lexicon; } @Override public CyNetworkView getViewModel() { return this; } @Override public <V> Icon createIcon(VisualProperty<V> vp, V value, int w, int h) { return VisualPropertyIconFactory.createIcon(value, w, h); } /** * Returns the current snapshot image of this view. * * <p> * No unnecessary image object will be created if networks in the current * session does not contain any nested network, i.e., should not have * performance/memory issue. * * @return Image of this view. It is always up-to-date. */ TexturePaint getSnapshot(final double width, final double height) { if (!latest) { // Need to update snapshot. snapshotImage = (BufferedImage)createImage(DEF_SNAPSHOT_SIZE, DEF_SNAPSHOT_SIZE, 1, /* skipBackground = */ true); latest = true; } // Handle non-square images // Get the height and width of the image int imageWidth = snapshotImage.getWidth(); int imageHeight = snapshotImage.getHeight(); double ratio = (double)imageHeight / (double) imageWidth; int adjustedWidth = (int)((double)width/ratio)+1; final Rectangle2D rect = new Rectangle2D.Double(-adjustedWidth / 2, -height / 2, adjustedWidth, height); final TexturePaint texturePaint = new TexturePaint(snapshotImage, rect); return texturePaint; } /** * Converts a BufferedImage to a lossless PNG. */ private byte[] convertToCompressedImage(final BufferedImage bufferedImage) { try { final ByteArrayOutputStream baos = new ByteArrayOutputStream(100000); ImageIO.write(bufferedImage, "png", baos); final byte[] retval = baos.toByteArray(); return retval; } catch (final IOException e) { logger.warn("Failed to convert a BufferedImage to a PNG. (" + e + ")"); return null; } } /** * Converts a PNG to a BufferedImage. */ private BufferedImage convertToBufferedImage(final byte[] compressedImage) { try { final ByteArrayInputStream is = new ByteArrayInputStream(compressedImage); final BufferedImage retval = (BufferedImage)ImageIO.read(is); return retval; } catch (final IOException e) { logger.warn("Failed to convert a PNG to a BufferedImage. (" + e + ")"); return null; } } /** * Listener for update flag of snapshot image. */ private final class DGraphViewContentChangeListener implements ContentChangeListener { public void contentChanged() { latest = false; } } @Override public void printCanvas(Graphics printCanvas) { logger.debug("PrintCanvas called: " + printCanvas); // Check properties related to printing: boolean exportAsShape = false; final String exportAsShapeString = props.getProperty("exportTextAsShape"); if (exportAsShapeString != null) exportAsShape = Boolean.parseBoolean(exportAsShapeString); setPrintingTextAsShape(exportAsShape); print(printCanvas); logger.debug("PrintCanvas Done: "); } @Override public void handleEvent(AboutToRemoveNodesEvent e) { if (model != e.getSource()) return; List<View<CyNode>> nvs = new ArrayList<View<CyNode>>(e.getNodes().size()); for ( CyNode n : e.getNodes()) { View<CyNode> v = this.getNodeView(n); if ( v != null) nvs.add(v); } if (nvs.size() <= 0) return; //cyEventHelper.fireEvent(new AboutToRemoveNodeViewsEvent(this, nvs)); for ( CyNode n : e.getNodes()) this.removeNodeView(n); } @Override public void handleEvent(AboutToRemoveEdgesEvent e) { if (model != e.getSource()) return; List<View<CyEdge>> evs = new ArrayList<View<CyEdge>>(e.getEdges().size()); for ( CyEdge edge : e.getEdges() ) { View<CyEdge> v = getEdgeView(edge); if ( v != null) evs.add(v); } if (evs.size() <= 0) return; //cyEventHelper.fireEvent(new AboutToRemoveEdgeViewsEvent(this, evs)); for ( CyEdge edge : e.getEdges() ) this.removeEdgeView(edge); //edgeViews.remove(edge); } @Override public void handleEvent(AddedNodesEvent e) { // Respond to the event only if the source is equal to the network model // associated with this view. if (model != e.getSource()) return; for (CyNode node : e.getPayloadCollection()) { this.addNodeView(node); } } @Override public void handleEvent(AddedEdgesEvent e) { if (model != e.getSource()) return; for ( CyEdge edge : e.getPayloadCollection()) { addEdgeView(edge); } } @Override public Collection<View<CyNode>> getNodeViews() { // This cast is always safe in current implementation. // Also, since this is a concurrent collection, this operation is thread-safe. return (Collection) nodeViewMap.values(); } @Override public Collection<View<CyEdge>> getEdgeViews() { // This cast is always safe in current implementation. // Also, since this is a concurrent collection, this operation is thread-safe. return (Collection) edgeViewMap.values(); } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public Collection<View<? extends CyIdentifiable>> getAllViews() { synchronized (m_lock) { final List views = new ArrayList(nodeViewMap.size() + edgeViewMap.size() + 1); Collection nodeViews = nodeViewMap.values(); views.addAll(nodeViews); Collection edgeViews = edgeViewMap.values(); views.addAll(edgeViews); views.add(this); return views; } } @Override protected <T, V extends T> void applyVisualProperty(final VisualProperty<? extends T> vpOriginal, V value) { if (value == null) return; // WARNING!!!!!!! // No calls to other methods from this method should trigger calls to updateView(). // Allowing this can cause deadlocks. The expectation is that anyone using // setVisualProperty() should call updateView() themselves. final VisualProperty<?> vp = vpOriginal; if (vp == DVisualLexicon.NETWORK_NODE_SELECTION) { boolean b = ((Boolean) value).booleanValue(); if (b) enableNodeSelection(); else disableNodeSelection(); } else if (vp == DVisualLexicon.NETWORK_EDGE_SELECTION) { boolean b = ((Boolean) value).booleanValue(); if (b) enableEdgeSelection(); else disableEdgeSelection(); } else if (vp == BasicVisualLexicon.NETWORK_BACKGROUND_PAINT) { setBackgroundPaint((Paint) value); } else if (vp == BasicVisualLexicon.NETWORK_CENTER_X_LOCATION) { final double x = (Double) value; if (x != m_networkCanvas.m_xCenter) setCenter(x, m_networkCanvas.m_yCenter); } else if (vp == BasicVisualLexicon.NETWORK_CENTER_Y_LOCATION) { final double y = (Double) value; if (y != m_networkCanvas.m_yCenter) setCenter(m_networkCanvas.m_xCenter, y); } else if (vp == BasicVisualLexicon.NETWORK_SCALE_FACTOR) { setZoom(((Double) value).doubleValue()); } else if (vp == BasicVisualLexicon.NETWORK_WIDTH) { m_networkCanvas.setSize(((Double)value).intValue(), m_networkCanvas.getHeight()); } else if (vp == BasicVisualLexicon.NETWORK_HEIGHT) { m_networkCanvas.setSize(m_networkCanvas.getWidth(), ((Double)value).intValue()); } } @Override public void clearValueLock(final VisualProperty<?> vp) { directLocks.remove(vp); allLocks.remove(vp); applyVisualProperty(vp, visualProperties.get(vp)); // always apply the regular vp } @Override public <T> T getVisualProperty(final VisualProperty<T> vp) { Object value = null; if (vp == DVisualLexicon.NETWORK_NODE_SELECTION) { value = nodeSelectionEnabled(); } else if (vp == DVisualLexicon.NETWORK_EDGE_SELECTION) { value = edgeSelectionEnabled(); } else if (vp == BasicVisualLexicon.NETWORK_BACKGROUND_PAINT) { value = getBackgroundPaint(); } else if (vp == BasicVisualLexicon.NETWORK_CENTER_X_LOCATION) { value = getCenter().getX(); } else if (vp == BasicVisualLexicon.NETWORK_CENTER_Y_LOCATION) { value = getCenter().getY(); } else if (vp == BasicVisualLexicon.NETWORK_SCALE_FACTOR) { value = getZoom(); } else { value = super.getVisualProperty(vp); } return (T) value; } @Override public View<CyNode> getNodeView(final CyNode node) { return (View<CyNode>) getDNodeView(node.getSUID()); } @Override public View<CyEdge> getEdgeView(final CyEdge edge) { return (View<CyEdge>) getDEdgeView(edge.getSUID()); } @Override public void handleEvent(FitSelectedEvent e) { if (e.getSource().equals(this)) { fitSelected(); } } @Override public void handleEvent(FitContentEvent e) { if (e.getSource().equals(this)) { fitContent(); } } @Override @SuppressWarnings("unchecked") public <T, V extends T> void setViewDefault(VisualProperty<? extends T> vp, V defaultValue) { if (vp.shouldIgnoreDefault()) return; final Class<?> targetType = vp.getTargetDataType(); final VisualStyle style = vmm.getVisualStyle(this); // Visibility should be applied directly to each edge view. if (vp == BasicVisualLexicon.EDGE_VISIBLE) { // TODO: Run in parallel. fork/join? applyToAllEdges(vp, defaultValue); return; } // In DING, there is no default W, H, and D. // Also, visibility should be applied directly to each node view. if (vp == BasicVisualLexicon.NODE_SIZE || vp == BasicVisualLexicon.NODE_WIDTH || vp == BasicVisualLexicon.NODE_HEIGHT || vp == BasicVisualLexicon.NODE_VISIBLE) { // TODO: Run in parallel. fork/join? applyToAllNodes(vp, defaultValue); return; } if ((VisualProperty<?>) vp instanceof CustomGraphicsVisualProperty) { if (style.getDefaultValue(vp) != NullCustomGraphics.getNullObject()) { applyToAllNodes(vp, defaultValue); return; } } if (vp != DVisualLexicon.NODE_LABEL_POSITION && defaultValue instanceof ObjectPosition) { // This is a CustomGraphicsPosition. if (defaultValue.equals(ObjectPositionImpl.DEFAULT_POSITION) == false) { applyToAllNodes(vp, defaultValue); return; } } if (targetType == CyNode.class) { applyToAllNodes(vp, null); m_nodeDetails.clear(); nodeViewDefaultSupport.setViewDefault((VisualProperty<V>)vp, defaultValue); } else if (targetType == CyEdge.class) { // applyToAllEdges(vp, null); m_edgeDetails.clear(); edgeViewDefaultSupport.setViewDefault((VisualProperty<V>)vp, defaultValue); } else if (targetType == CyNetwork.class) { // For networks, just set as regular visual property value. (No defaults) this.setVisualProperty(vp, defaultValue); } } private final <T, V extends T> void applyToAllNodes(final VisualProperty<? extends T> vp, final V defaultValue) { final Collection<NodeView> nodes = this.nodeViewMap.values(); for (final NodeView n : nodes) ((DNodeView) n).setVisualProperty(vp, defaultValue); } private final <T, V extends T> void applyToAllEdges(final VisualProperty<? extends T> vp, final V defaultValue) { final Collection<EdgeView> edges = this.edgeViewMap.values(); for (final EdgeView e : edges) ((DEdgeView) e).setVisualProperty(vp, defaultValue); } public CyAnnotator getCyAnnotator() { return cyAnnotator; } @Override public String toString() { return "DGraphView: suid=" + suid + ", model=" + model; } public void registerServices() { synchronized (this) { if (servicesRegistered) return; registrar.registerAllServices(this, new Properties()); servicesRegistered = true; } } @Override public void dispose() { synchronized (this) { if (!servicesRegistered) return; registrar.unregisterAllServices(this); servicesRegistered = false; m_lis[0] = null; cyAnnotator.dispose(); m_networkCanvas.dispose(); } } @Override protected <T, V extends T> V getDefaultValue(VisualProperty<T> vp) { return null; } @Override public String getRendererId() { return DingRenderer.ID; } }
package <%=packageName%>.web.rest; <% if (databaseType == 'cassandra') { %> import <%=packageName%>.AbstractCassandraTest;<% } %> import <%=packageName%>.<%= mainClass %>; import <%=packageName%>.domain.<%= entityClass %>; <%_ for (idx in relationships) { // import entities in required relationships var relationshipValidate = relationships[idx].relationshipValidate; var otherEntityNameCapitalized = relationships[idx].otherEntityNameCapitalized; if (relationshipValidate != null && relationshipValidate === true) { _%> import <%=packageName%>.domain.<%= otherEntityNameCapitalized %>; <%_ } } _%> import <%=packageName%>.repository.<%= entityClass %>Repository;<% if (service != 'no') { %> import <%=packageName%>.service.<%= entityClass %>Service;<% } if (searchEngine == 'elasticsearch') { %> import <%=packageName%>.repository.search.<%= entityClass %>SearchRepository;<% } if (dto == 'mapstruct') { %> import <%=packageName%>.service.dto.<%= entityClass %>DTO; import <%=packageName%>.service.mapper.<%= entityClass %>Mapper;<% } %> import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.hamcrest.Matchers.hasItem; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders;<% if (databaseType == 'sql') { %> import org.springframework.transaction.annotation.Transactional;<% } %><% if (fieldsContainBlob == true) { %> import org.springframework.util.Base64Utils;<% } %> import javax.annotation.PostConstruct; import javax.inject.Inject;<% if (databaseType == 'sql') { %> import javax.persistence.EntityManager;<% } %><% if (fieldsContainLocalDate == true) { %> import java.time.LocalDate;<% } %><% if (fieldsContainZonedDateTime == true) { %> import java.time.Instant; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter;<% } %><% if (fieldsContainLocalDate == true || fieldsContainZonedDateTime == true) { %> import java.time.ZoneId;<% } %><% if (fieldsContainBigDecimal == true) { %> import java.math.BigDecimal;<% } %><% if (fieldsContainBlob == true && databaseType === 'cassandra') { %> import java.nio.ByteBuffer;<% } %> import java.util.List;<% if (databaseType == 'cassandra') { %> import java.util.UUID;<% } %> import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; <%_ for (idx in fields) { if (fields[idx].fieldIsEnum == true) { _%>import <%=packageName%>.domain.enumeration.<%= fields[idx].fieldType %>; <%_ } } _%> /** * Test class for the <%= entityClass %>Resource REST controller. * * @see <%= entityClass %>Resource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = <%= mainClass %>.class) public class <%= entityClass %>ResourceIntTest <% if (databaseType == 'cassandra') { %>extends AbstractCassandraTest <% } %>{<%_ if (fieldsContainZonedDateTime == true) { _%> private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneId.of("Z"));<%_ } _%> <% for (idx in fields) { var defaultValueName = 'DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase(); var updatedValueName = 'UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase(); var defaultValue = 1; var updatedValue = 2; if (fields[idx].fieldValidate == true) { if (fields[idx].fieldValidateRules.indexOf('max') != -1) { defaultValue = fields[idx].fieldValidateRulesMax; updatedValue = parseInt(fields[idx].fieldValidateRulesMax) - 1; } if (fields[idx].fieldValidateRules.indexOf('min') != -1) { defaultValue = fields[idx].fieldValidateRulesMin; updatedValue = parseInt(fields[idx].fieldValidateRulesMin) + 1; } if (fields[idx].fieldValidateRules.indexOf('minbytes') != -1) { defaultValue = fields[idx].fieldValidateRulesMinbytes; updatedValue = fields[idx].fieldValidateRulesMinbytes; } if (fields[idx].fieldValidateRules.indexOf('maxbytes') != -1) { updatedValue = fields[idx].fieldValidateRulesMaxbytes; } } var fieldType = fields[idx].fieldType; var fieldTypeBlobContent = fields[idx].fieldTypeBlobContent; var isEnum = fields[idx].fieldIsEnum; var enumValue1; var enumValue2; if (isEnum) { var values = fields[idx].fieldValues.replace(/\s/g, '').split(','); enumValue1 = values[0]; if (values.length > 1) { enumValue2 = values[1]; } else { enumValue2 = enumValue1; } } if (fieldType == 'String') { // Generate Strings, using the min and max string length if they are configured var sampleTextString = ""; var updatedTextString = ""; var sampleTextMinLength = fields[idx].fieldValidateRulesMinlength; if (sampleTextMinLength == undefined) { sampleTextMinLength = fields[idx].fieldValidateRulesMaxlength; if (sampleTextMinLength == undefined) { sampleTextMinLength = 5; } } for( var i = 0; i < sampleTextMinLength; i++ ) { sampleTextString += "A"; updatedTextString += "B"; } %> private static final String <%=defaultValueName %> = "<%=sampleTextString %>"; private static final String <%=updatedValueName %> = "<%=updatedTextString %>";<% } else if (fieldType == 'Integer') { %> private static final Integer <%=defaultValueName %> = <%= defaultValue %>; private static final Integer <%=updatedValueName %> = <%= updatedValue %>;<% } else if (fieldType == 'Long') { %> private static final Long <%=defaultValueName %> = <%= defaultValue %>L; private static final Long <%=updatedValueName %> = <%= updatedValue %>L;<% } else if (fieldType == 'Float') { %> private static final <%=fieldType %> <%=defaultValueName %> = <%= defaultValue %>F; private static final <%=fieldType %> <%=updatedValueName %> = <%= updatedValue %>F;<% } else if (fieldType == 'Double') { %> private static final <%=fieldType %> <%=defaultValueName %> = <%= defaultValue %>D; private static final <%=fieldType %> <%=updatedValueName %> = <%= updatedValue %>D;<% } else if (fieldType == 'BigDecimal') { %> private static final BigDecimal <%=defaultValueName %> = new BigDecimal(<%= defaultValue %>); private static final BigDecimal <%=updatedValueName %> = new BigDecimal(<%= updatedValue %>);<% } else if (fieldType == 'UUID') { %> private static final UUID <%=defaultValueName %> = UUID.randomUUID(); private static final UUID <%=updatedValueName %> = UUID.randomUUID();<% } else if (fieldType == 'LocalDate') { %> private static final LocalDate <%=defaultValueName %> = LocalDate.ofEpochDay(0L); private static final LocalDate <%=updatedValueName %> = LocalDate.now(ZoneId.systemDefault());<% } else if (fieldType == 'ZonedDateTime') { %> private static final ZonedDateTime <%=defaultValueName %> = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneId.systemDefault()); private static final ZonedDateTime <%=updatedValueName %> = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0); private static final String <%=defaultValueName %>_STR = dateTimeFormatter.format(<%= defaultValueName %>);<% } else if (fieldType == 'Boolean') { %> private static final Boolean <%=defaultValueName %> = false; private static final Boolean <%=updatedValueName %> = true;<% } else if ((fieldType == 'byte[]' || fieldType === 'ByteBuffer') && fieldTypeBlobContent != 'text') { %> <%_ if (databaseType !== 'cassandra') { _%> private static final byte[] <%=defaultValueName %> = TestUtil.createByteArray(<%= defaultValue %>, "0"); private static final byte[] <%=updatedValueName %> = TestUtil.createByteArray(<%= updatedValue %>, "1"); <%_ } else { _%> private static final ByteBuffer <%=defaultValueName %> = ByteBuffer.wrap(TestUtil.createByteArray(<%= defaultValue %>, "0")); private static final ByteBuffer <%=updatedValueName %> = ByteBuffer.wrap(TestUtil.createByteArray(<%= updatedValue %>, "1")); <%_ } _%> private static final String <%=defaultValueName %>_CONTENT_TYPE = "image/jpg"; private static final String <%=updatedValueName %>_CONTENT_TYPE = "image/png";<% } else if (fieldTypeBlobContent == 'text') { %> private static final String <%=defaultValueName %> = "<%=sampleTextString %>"; private static final String <%=updatedValueName %> = "<%=updatedTextString %>";<% } else if (isEnum) { %> private static final <%=fieldType %> <%=defaultValueName %> = <%=fieldType %>.<%=enumValue1 %>; private static final <%=fieldType %> <%=updatedValueName %> = <%=fieldType %>.<%=enumValue2 %>;<% } } %> @Inject private <%= entityClass %>Repository <%= entityInstance %>Repository;<% if (dto == 'mapstruct') { %> @Inject private <%= entityClass %>Mapper <%= entityInstance %>Mapper;<% } if (service != 'no') { %> @Inject private <%= entityClass %>Service <%= entityInstance %>Service;<% } if (searchEngine == 'elasticsearch') { %> @Inject private <%= entityClass %>SearchRepository <%= entityInstance %>SearchRepository;<% } %> @Inject private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Inject private PageableHandlerMethodArgumentResolver pageableArgumentResolver; <%_ if (databaseType == 'sql') { _%> @Inject private EntityManager em; <%_ } _%> private MockMvc rest<%= entityClass %>MockMvc; private <%= entityClass %> <%= entityInstance %>; @PostConstruct public void setup() { MockitoAnnotations.initMocks(this); <%= entityClass %>Resource <%= entityInstance %>Resource = new <%= entityClass %>Resource(); <%_ if (service != 'no') { _%> ReflectionTestUtils.setField(<%= entityInstance %>Resource, "<%= entityInstance %>Service", <%= entityInstance %>Service); <%_ } else { _%> <%_ if (searchEngine == 'elasticsearch') { _%> ReflectionTestUtils.setField(<%= entityInstance %>Resource, "<%= entityInstance %>SearchRepository", <%= entityInstance %>SearchRepository); <%_ } _%> ReflectionTestUtils.setField(<%= entityInstance %>Resource, "<%= entityInstance %>Repository", <%= entityInstance %>Repository); <%_ } _%> <%_ if (service == 'no' && dto == 'mapstruct') { _%> ReflectionTestUtils.setField(<%= entityInstance %>Resource, "<%= entityInstance %>Mapper", <%= entityInstance %>Mapper); <%_ } _%> this.rest<%= entityClass %>MockMvc = MockMvcBuilders.standaloneSetup(<%= entityInstance %>Resource) .setCustomArgumentResolvers(pageableArgumentResolver) .setMessageConverters(jacksonMessageConverter).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static <%= entityClass %> createEntity(<% if (databaseType == 'sql') { %>EntityManager em<% } %>) { <%= entityClass %> <%= entityInstance %> = new <%= entityClass %>(); <%_ for (idx in fields) { _%> <%= entityInstance %>.set<%= fields[idx].fieldInJavaBeanMethod %>(<%='DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase()%>); <%_ if ((fields[idx].fieldType == 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent != 'text') { _%> <%= entityInstance %>.set<%= fields[idx].fieldInJavaBeanMethod %>ContentType(<%='DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase()%>_CONTENT_TYPE); <%_ } _%> <%_ } _%> <%_ for (idx in relationships) { var relationshipValidate = relationships[idx].relationshipValidate; var otherEntityNameCapitalized = relationships[idx].otherEntityNameCapitalized; var relationshipFieldName = relationships[idx].relationshipFieldName; var relationshipType = relationships[idx].relationshipType; var relationshipNameCapitalizedPlural = relationships[idx].relationshipNameCapitalizedPlural; var relationshipNameCapitalized = relationships[idx].relationshipNameCapitalized; if (relationshipValidate != null && relationshipValidate === true) { _%> // Add required entity <%= otherEntityNameCapitalized %> <%= relationshipFieldName %> = <%= otherEntityNameCapitalized %>ResourceIntTest.createEntity(em); em.persist(<%= relationshipFieldName %>); em.flush(); <%_ if (relationshipType == 'many-to-many') { _%> <%= entityInstance %>.get<%= relationshipNameCapitalizedPlural %>().add(<%= relationshipFieldName %>); <%_ } else { _%> <%= entityInstance %>.set<%= relationshipNameCapitalized %>(<%= relationshipFieldName %>); <%_ } _%> <%_ } } _%> return <%= entityInstance %>; } @Before public void initTest() { <%_ if (databaseType == 'mongodb' || databaseType == 'cassandra') { _%> <%= entityInstance %>Repository.deleteAll();<% } if (searchEngine == 'elasticsearch') { %> <%= entityInstance %>SearchRepository.deleteAll(); <%_ } _%> <%= entityInstance %> = createEntity(em); } @Test<% if (databaseType == 'sql') { %> @Transactional<% } %> public void create<%= entityClass %>() throws Exception { int databaseSizeBeforeCreate = <%= entityInstance %>Repository.findAll().size(); // Create the <%= entityClass %><% if (dto == 'mapstruct') { %> <%= entityClass %>DTO <%= entityInstance %>DTO = <%= entityInstance %>Mapper.<%= entityInstance %>To<%= entityClass %>DTO(<%= entityInstance %>);<% } %> rest<%= entityClass %>MockMvc.perform(post("/api/<%= entityApiUrl %>") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(<%= entityInstance %><% if (dto == 'mapstruct') { %>DTO<% } %>))) .andExpect(status().isCreated()); // Validate the <%= entityClass %> in the database List<<%= entityClass %>> <%= entityInstancePlural %> = <%= entityInstance %>Repository.findAll(); assertThat(<%= entityInstancePlural %>).hasSize(databaseSizeBeforeCreate + 1); <%= entityClass %> test<%= entityClass %> = <%= entityInstancePlural %>.get(<%= entityInstancePlural %>.size() - 1); <%_ for (idx in fields) { if (fields[idx].fieldType == 'ZonedDateTime') { _%> assertThat(test<%= entityClass %>.get<%=fields[idx].fieldInJavaBeanMethod%>()).isEqualTo(<%='DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase()%>); <%_ } else if ((fields[idx].fieldType == 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent != 'text') { _%> assertThat(test<%= entityClass %>.get<%=fields[idx].fieldInJavaBeanMethod%>()).isEqualTo(<%='DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase()%>); assertThat(test<%= entityClass %>.get<%=fields[idx].fieldInJavaBeanMethod%>ContentType()).isEqualTo(<%='DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase()%>_CONTENT_TYPE); <%_ } else if (fields[idx].fieldType.toLowerCase() == 'boolean') { _%> assertThat(test<%= entityClass %>.is<%=fields[idx].fieldInJavaBeanMethod%>()).isEqualTo(<%='DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase()%>); <%_ } else { _%> assertThat(test<%= entityClass %>.get<%=fields[idx].fieldInJavaBeanMethod%>()).isEqualTo(<%='DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase()%>); <%_ }} if (searchEngine == 'elasticsearch') { _%> // Validate the <%= entityClass %> in ElasticSearch <%= entityClass %> <%= entityInstance %>Es = <%= entityInstance %>SearchRepository.findOne(test<%= entityClass %>.getId()); assertThat(<%= entityInstance %>Es).isEqualToComparingFieldByField(test<%= entityClass %>); <%_ } _%> } <% for (idx in fields) { %><% if (fields[idx].fieldValidate == true) { var required = false; if (fields[idx].fieldValidate == true && fields[idx].fieldValidateRules.indexOf('required') != -1) { required = true; } if (required) { %> @Test<% if (databaseType == 'sql') { %> @Transactional<% } %> public void check<%= fields[idx].fieldInJavaBeanMethod %>IsRequired() throws Exception { int databaseSizeBeforeTest = <%= entityInstance %>Repository.findAll().size(); // set the field null <%= entityInstance %>.set<%= fields[idx].fieldInJavaBeanMethod %>(null); // Create the <%= entityClass %>, which fails.<% if (dto == 'mapstruct') { %> <%= entityClass %>DTO <%= entityInstance %>DTO = <%= entityInstance %>Mapper.<%= entityInstance %>To<%= entityClass %>DTO(<%= entityInstance %>);<% } %> rest<%= entityClass %>MockMvc.perform(post("/api/<%= entityApiUrl %>") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(<%= entityInstance %><% if (dto == 'mapstruct') { %>DTO<% } %>))) .andExpect(status().isBadRequest()); List<<%= entityClass %>> <%= entityInstancePlural %> = <%= entityInstance %>Repository.findAll(); assertThat(<%= entityInstancePlural %>).hasSize(databaseSizeBeforeTest); } <% } } } %> @Test<% if (databaseType == 'sql') { %> @Transactional<% } %> public void getAll<%= entityClassPlural %>() throws Exception { // Initialize the database <%= entityInstance %>Repository.save<% if (databaseType == 'sql') { %>AndFlush<% } %>(<%= entityInstance %>); // Get all the <%= entityInstancePlural %> rest<%= entityClass %>MockMvc.perform(get("/api/<%= entityApiUrl %>?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))<% if (databaseType == 'sql') { %> .andExpect(jsonPath("$.[*].id").value(hasItem(<%= entityInstance %>.getId().intValue())))<% } %><% if (databaseType == 'mongodb') { %> .andExpect(jsonPath("$.[*].id").value(hasItem(<%= entityInstance %>.getId())))<% } %><% if (databaseType == 'cassandra') { %> .andExpect(jsonPath("$.[*].id").value(hasItem(<%= entityInstance %>.getId().toString())))<% } %><% for (idx in fields) {%> <%_ if ((fields[idx].fieldType == 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent != 'text') { _%> .andExpect(jsonPath("$.[*].<%=fields[idx].fieldName%>ContentType").value(hasItem(<%='DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase()%>_CONTENT_TYPE))) <%_ } _%> .andExpect(jsonPath("$.[*].<%=fields[idx].fieldName%>").value(hasItem(<% if ((fields[idx].fieldType == 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent != 'text') { %>Base64Utils.encodeToString(<% } %><%='DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase()%><% if ((fields[idx].fieldType == 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent != 'text') { %><% if (databaseType == 'cassandra') { %>.array()<% } %>)<% } else if (fields[idx].fieldType == 'Integer') { %><% } else if (fields[idx].fieldType == 'Long') { %>.intValue()<% } else if (fields[idx].fieldType == 'Float' || fields[idx].fieldType == 'Double') { %>.doubleValue()<% } else if (fields[idx].fieldType == 'BigDecimal') { %>.intValue()<% } else if (fields[idx].fieldType == 'Boolean') { %>.booleanValue()<% } else if (fields[idx].fieldType == 'ZonedDateTime') { %>_STR<% } else { %>.toString()<% } %>)))<% } %>; } @Test<% if (databaseType == 'sql') { %> @Transactional<% } %> public void get<%= entityClass %>() throws Exception { // Initialize the database <%= entityInstance %>Repository.save<% if (databaseType == 'sql') { %>AndFlush<% } %>(<%= entityInstance %>); // Get the <%= entityInstance %> rest<%= entityClass %>MockMvc.perform(get("/api/<%= entityApiUrl %>/{id}", <%= entityInstance %>.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))<% if (databaseType == 'sql') { %> .andExpect(jsonPath("$.id").value(<%= entityInstance %>.getId().intValue()))<% } %><% if (databaseType == 'mongodb') { %> .andExpect(jsonPath("$.id").value(<%= entityInstance %>.getId()))<% } %><% if (databaseType == 'cassandra') { %> .andExpect(jsonPath("$.id").value(<%= entityInstance %>.getId().toString()))<% } %><% for (idx in fields) {%> <%_ if ((fields[idx].fieldType == 'byte[]' || fields[idx].fieldType == 'ByteBuffer') && fields[idx].fieldTypeBlobContent != 'text') { _%> .andExpect(jsonPath("$.<%=fields[idx].fieldName%>ContentType").value(<%='DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase()%>_CONTENT_TYPE)) <%_ } _%> .andExpect(jsonPath("$.<%=fields[idx].fieldName%>").value(<% if ((fields[idx].fieldType == 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent != 'text') { %>Base64Utils.encodeToString(<% } %><%='DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase()%><% if ((fields[idx].fieldType == 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent != 'text') { %><% if (databaseType === 'cassandra') { %>.array()<% } %>)<% } else if (fields[idx].fieldType == 'Integer') { %><% } else if (fields[idx].fieldType == 'Long') { %>.intValue()<% } else if (fields[idx].fieldType == 'Float' || fields[idx].fieldType == 'Double') { %>.doubleValue()<% } else if (fields[idx].fieldType == 'BigDecimal') { %>.intValue()<% } else if (fields[idx].fieldType == 'Boolean') { %>.booleanValue()<% } else if (fields[idx].fieldType == 'ZonedDateTime') { %>_STR<% } else { %>.toString()<% } %>))<% } %>; } @Test<% if (databaseType == 'sql') { %> @Transactional<% } %> public void getNonExisting<%= entityClass %>() throws Exception { // Get the <%= entityInstance %> rest<%= entityClass %>MockMvc.perform(get("/api/<%= entityApiUrl %>/{id}", <% if (databaseType == 'sql' || databaseType == 'mongodb') { %>Long.MAX_VALUE<% } %><% if (databaseType == 'cassandra') { %>UUID.randomUUID().toString()<% } %>)) .andExpect(status().isNotFound()); } @Test<% if (databaseType == 'sql') { %> @Transactional<% } %> public void update<%= entityClass %>() throws Exception { // Initialize the database <%_ if (service != 'no' && dto != 'mapstruct') { _%> <%= entityInstance %>Service.save(<%= entityInstance %>); <%_ } else { _%> <%= entityInstance %>Repository.save<% if (databaseType == 'sql') { %>AndFlush<% } %>(<%= entityInstance %>);<% if (searchEngine == 'elasticsearch') { %> <%= entityInstance %>SearchRepository.save(<%= entityInstance %>);<%_ } _%> <%_ } _%> int databaseSizeBeforeUpdate = <%= entityInstance %>Repository.findAll().size(); // Update the <%= entityInstance %> <%= entityClass %> updated<%= entityClass %> = <%= entityInstance %>Repository.findOne(<%= entityInstance %>.getId()); <%_ for (idx in fields) { _%> updated<%= entityClass %>.set<%= fields[idx].fieldInJavaBeanMethod %>(<%='UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase()%>); <%_ if ((fields[idx].fieldType == 'byte[]' || fields[idx].fieldType == 'ByteBuffer') && fields[idx].fieldTypeBlobContent != 'text') { _%> updated<%= entityClass %>.set<%= fields[idx].fieldInJavaBeanMethod %>ContentType(<%='UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase()%>_CONTENT_TYPE); <%_ } _%> <%_ } _%> <%_ if (dto == 'mapstruct') { _%> <%= entityClass %>DTO <%= entityInstance %>DTO = <%= entityInstance %>Mapper.<%= entityInstance %>To<%= entityClass %>DTO(updated<%= entityClass %>); <%_ } _%> rest<%= entityClass %>MockMvc.perform(put("/api/<%= entityApiUrl %>") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(<% if (dto == 'mapstruct') { %><%= entityInstance %>DTO<% } else { %>updated<%= entityClass %><% } %>))) .andExpect(status().isOk()); // Validate the <%= entityClass %> in the database List<<%= entityClass %>> <%= entityInstancePlural %> = <%= entityInstance %>Repository.findAll(); assertThat(<%= entityInstancePlural %>).hasSize(databaseSizeBeforeUpdate); <%= entityClass %> test<%= entityClass %> = <%= entityInstancePlural %>.get(<%= entityInstancePlural %>.size() - 1); <%_ for (idx in fields) { if (fields[idx].fieldType == 'ZonedDateTime') { _%> assertThat(test<%= entityClass %>.get<%=fields[idx].fieldInJavaBeanMethod%>()).isEqualTo(<%='UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase()%>); <%_ } else if ((fields[idx].fieldType == 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent != 'text') { _%> assertThat(test<%= entityClass %>.get<%=fields[idx].fieldInJavaBeanMethod%>()).isEqualTo(<%='UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase()%>); assertThat(test<%= entityClass %>.get<%=fields[idx].fieldInJavaBeanMethod%>ContentType()).isEqualTo(<%='UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase()%>_CONTENT_TYPE); <%_ } else if (fields[idx].fieldType.toLowerCase() == 'boolean') { _%> assertThat(test<%= entityClass %>.is<%=fields[idx].fieldInJavaBeanMethod%>()).isEqualTo(<%='UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase()%>); <%_ } else { _%> assertThat(test<%= entityClass %>.get<%=fields[idx].fieldInJavaBeanMethod%>()).isEqualTo(<%='UPDATED_' + fields[idx].fieldNameUnderscored.toUpperCase()%>); <%_ } } if (searchEngine == 'elasticsearch') { _%> // Validate the <%= entityClass %> in ElasticSearch <%= entityClass %> <%= entityInstance %>Es = <%= entityInstance %>SearchRepository.findOne(test<%= entityClass %>.getId()); assertThat(<%= entityInstance %>Es).isEqualToComparingFieldByField(test<%= entityClass %>); <%_ } _%> } @Test<% if (databaseType == 'sql') { %> @Transactional<% } %> public void delete<%= entityClass %>() throws Exception { // Initialize the database <%_ if (service != 'no' && dto != 'mapstruct') { _%> <%= entityInstance %>Service.save(<%= entityInstance %>); <%_ } else { _%> <%= entityInstance %>Repository.save<% if (databaseType == 'sql') { %>AndFlush<% } %>(<%= entityInstance %>);<% if (searchEngine == 'elasticsearch') { %> <%= entityInstance %>SearchRepository.save(<%= entityInstance %>);<%_ } _%> <%_ } _%> int databaseSizeBeforeDelete = <%= entityInstance %>Repository.findAll().size(); // Get the <%= entityInstance %> rest<%= entityClass %>MockMvc.perform(delete("/api/<%= entityApiUrl %>/{id}", <%= entityInstance %>.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk());<% if (searchEngine == 'elasticsearch') { %> // Validate ElasticSearch is empty boolean <%= entityInstance %>ExistsInEs = <%= entityInstance %>SearchRepository.exists(<%= entityInstance %>.getId()); assertThat(<%= entityInstance %>ExistsInEs).isFalse();<% } %> // Validate the database is empty List<<%= entityClass %>> <%= entityInstancePlural %> = <%= entityInstance %>Repository.findAll(); assertThat(<%= entityInstancePlural %>).hasSize(databaseSizeBeforeDelete - 1); }<% if (searchEngine == 'elasticsearch') { %> @Test<% if (databaseType == 'sql') { %> @Transactional<% } %> public void search<%= entityClass %>() throws Exception { // Initialize the database <%_ if (service != 'no' && dto != 'mapstruct') { _%> <%= entityInstance %>Service.save(<%= entityInstance %>); <%_ } else { _%> <%= entityInstance %>Repository.save<% if (databaseType == 'sql') { %>AndFlush<% } %>(<%= entityInstance %>); <%= entityInstance %>SearchRepository.save(<%= entityInstance %>); <%_ } _%> // Search the <%= entityInstance %> rest<%= entityClass %>MockMvc.perform(get("/api/_search/<%= entityApiUrl %>?query=id:" + <%= entityInstance %>.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))<% if (databaseType == 'sql') { %> .andExpect(jsonPath("$.[*].id").value(hasItem(<%= entityInstance %>.getId().intValue())))<% } %><% if (databaseType == 'mongodb') { %> .andExpect(jsonPath("$.[*].id").value(hasItem(<%= entityInstance %>.getId())))<% } %><% if (databaseType == 'cassandra') { %> .andExpect(jsonPath("$.[*].id").value(hasItem(<%= entityInstance %>.getId().toString())))<% } %><% for (idx in fields) {%> <%_ if ((fields[idx].fieldType == 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent != 'text') { _%> .andExpect(jsonPath("$.[*].<%=fields[idx].fieldName%>ContentType").value(hasItem(<%='DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase()%>_CONTENT_TYPE))) <%_ } _%> .andExpect(jsonPath("$.[*].<%=fields[idx].fieldName%>").value(hasItem(<% if ((fields[idx].fieldType == 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent != 'text') { %>Base64Utils.encodeToString(<% } %><%='DEFAULT_' + fields[idx].fieldNameUnderscored.toUpperCase()%><% if ((fields[idx].fieldType == 'byte[]' || fields[idx].fieldType === 'ByteBuffer') && fields[idx].fieldTypeBlobContent != 'text') { %><% if (databaseType === 'cassandra') { %>.array()<% } %>)<% } else if (fields[idx].fieldType == 'Integer') { %><% } else if (fields[idx].fieldType == 'Long') { %>.intValue()<% } else if (fields[idx].fieldType == 'Float' || fields[idx].fieldType == 'Double') { %>.doubleValue()<% } else if (fields[idx].fieldType == 'BigDecimal') { %>.intValue()<% } else if (fields[idx].fieldType == 'Boolean') { %>.booleanValue()<% } else if (fields[idx].fieldType == 'ZonedDateTime') { %>_STR<% } else { %>.toString()<% } %>)))<% } %>; }<% } %> }
package org.jnosql.artemis.graph.query; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.VertexProperty; import org.jnosql.artemis.DynamicQueryException; import org.jnosql.artemis.graph.cdi.WeldJUnit4Runner; import org.jnosql.artemis.graph.model.Person; import org.jnosql.artemis.reflection.ClassRepresentation; import org.jnosql.artemis.reflection.ClassRepresentations; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import javax.inject.Inject; import java.util.List; import java.util.Optional; import static java.util.stream.Collectors.toList; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(WeldJUnit4Runner.class) public class GraphQueryParserTest { @Inject private ClassRepresentations classRepresentations; private GraphQueryParser parser; private ClassRepresentation classRepresentation; @Inject private Graph graph; @Before public void setUp() { graph.traversal().V().toList().forEach(Vertex::remove); graph.traversal().E().toList().forEach(Edge::remove); parser = new GraphQueryParser(); classRepresentation = classRepresentations.get(Person.class); } @After public void after() { graph.traversal().V().toList().forEach(Vertex::remove); graph.traversal().E().toList().forEach(Edge::remove); } @Test public void shouldFindByName() { graph.addVertex(T.label, "Person", "name", "name"); GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByName", new Object[]{"name"}, classRepresentation, traversal); Optional<Vertex> vertex = traversal.tryNext(); assertTrue(vertex.isPresent()); assertEquals("Person", vertex.get().label()); VertexProperty<Object> name = vertex.get().property("name"); assertEquals("name", name.value()); } @Test public void shouldFindByNameAndAge() { graph.addVertex(T.label, "Person", "name", "name", "age", 10); GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByNameAndAge", new Object[]{"name", 10}, classRepresentation, traversal); Optional<Vertex> vertex = traversal.tryNext(); assertTrue(vertex.isPresent()); assertEquals("Person", vertex.get().label()); VertexProperty<Object> name = vertex.get().property("name"); VertexProperty<Object> age = vertex.get().property("age"); assertEquals("name", name.value()); assertEquals(10, age.value()); } @Test public void shouldFindByAgeLessThan() { graph.addVertex(T.label, "Person", "name", "name", "age", 10); graph.addVertex(T.label, "Person", "name", "name2", "age", 9); graph.addVertex(T.label, "Person", "name", "name3", "age", 8); GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByAgeLessThan", new Object[]{10}, classRepresentation, traversal); assertEquals(2, traversal.toList().size()); } @Test public void shouldFindByAgeGreaterThan() { graph.addVertex(T.label, "Person", "name", "name", "age", 10); graph.addVertex(T.label, "Person", "name", "name2", "age", 9); graph.addVertex(T.label, "Person", "name", "name3", "age", 11); graph.addVertex(T.label, "Person", "name", "name4", "age", 12); graph.addVertex(T.label, "Person", "name", "name5", "age", 13); GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByAgeGreaterThan", new Object[]{10}, classRepresentation, traversal); assertEquals(3, traversal.toList().size()); } @Test public void shouldFindByAgeLessEqualThan() { graph.addVertex(T.label, "Person", "name", "name", "age", 10); graph.addVertex(T.label, "Person", "name", "name2", "age", 9); graph.addVertex(T.label, "Person", "name", "name3", "age", 11); graph.addVertex(T.label, "Person", "name", "name4", "age", 12); graph.addVertex(T.label, "Person", "name", "name5", "age", 13); GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByAgeLessEqualThan", new Object[]{10}, classRepresentation, traversal); assertEquals(2, traversal.toList().size()); } @Test public void shouldFindByAgeGreaterEqualThan() { graph.addVertex(T.label, "Person", "name", "name", "age", 10); graph.addVertex(T.label, "Person", "name", "name2", "age", 9); graph.addVertex(T.label, "Person", "name", "name3", "age", 11); graph.addVertex(T.label, "Person", "name", "name4", "age", 12); graph.addVertex(T.label, "Person", "name", "name5", "age", 13); GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByAgeGreaterEqualThan", new Object[]{10}, classRepresentation, traversal); } @Test public void shouldFindByNameAndAgeBetween() { graph.addVertex(T.label, "Person", "name", "name", "age", 10); graph.addVertex(T.label, "Person", "name", "name2", "age", 9); graph.addVertex(T.label, "Person", "name", "name3", "age", 11); graph.addVertex(T.label, "Person", "name", "name4", "age", 12); graph.addVertex(T.label, "Person", "name", "name5", "age", 13); GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByNameAndAgeBetween", new Object[]{"name", 10, 12}, classRepresentation, traversal); assertEquals(1, traversal.toList().size()); } @Test public void shouldFindByKnowsOutV() { Vertex poliana = graph.addVertex(T.label, "Person", "name", "Poliana", "age", 10); Vertex otavio = graph.addVertex(T.label, "Person", "name", "Otavio", "age", 9); poliana.addEdge("knows", otavio); GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByKnowsOutV", new Object[]{}, classRepresentation, traversal); Optional<Vertex> vertex = traversal.tryNext(); assertTrue(vertex.isPresent()); assertEquals(otavio.id(), vertex.get().id()); } @Test public void shouldFindByOutV() { Vertex poliana = graph.addVertex(T.label, "Person", "name", "Poliana", "age", 10); Vertex otavio = graph.addVertex(T.label, "Person", "name", "Otavio", "age", 9); poliana.addEdge("knows", otavio); GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByOutV", new Object[]{"knows"}, classRepresentation, traversal); Optional<Vertex> vertex = traversal.tryNext(); assertTrue(vertex.isPresent()); assertEquals(otavio.id(), vertex.get().id()); } @Test public void shouldFindByKnowsInV() { Vertex poliana = graph.addVertex(T.label, "Person", "name", "Poliana", "age", 10); Vertex otavio = graph.addVertex(T.label, "Person", "name", "Otavio", "age", 9); poliana.addEdge("knows", otavio); GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByKnowsInV", new Object[]{}, classRepresentation, traversal); Optional<Vertex> vertex = traversal.tryNext(); assertTrue(vertex.isPresent()); assertEquals(poliana.id(), vertex.get().id()); } @Test public void shouldFindByInV() { Vertex poliana = graph.addVertex(T.label, "Person", "name", "Poliana", "age", 10); Vertex otavio = graph.addVertex(T.label, "Person", "name", "Otavio", "age", 9); poliana.addEdge("knows", otavio); GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByInV", new Object[]{"knows"}, classRepresentation, traversal); Optional<Vertex> vertex = traversal.tryNext(); assertTrue(vertex.isPresent()); assertEquals(poliana.id(), vertex.get().id()); } @Test public void shouldFindByKnowsBothV() { Vertex poliana = graph.addVertex(T.label, "Person", "name", "Poliana", "age", 10); Vertex otavio = graph.addVertex(T.label, "Person", "name", "Otavio", "age", 9); poliana.addEdge("knows", otavio); GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByKnowsBothV", new Object[]{}, classRepresentation, traversal); List<Vertex> vertices = traversal.toList(); List<Object> ids = vertices.stream().map(Vertex::id).collect(toList()); assertThat(ids, containsInAnyOrder(poliana.id(), otavio.id())); } @Test public void shouldFindByBothV() { Vertex poliana = graph.addVertex(T.label, "Person", "name", "Poliana", "age", 10); Vertex otavio = graph.addVertex(T.label, "Person", "name", "Otavio", "age", 9); poliana.addEdge("knows", otavio); GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByBothV", new Object[]{"knows"}, classRepresentation, traversal); List<Vertex> vertices = traversal.toList(); List<Object> ids = vertices.stream().map(Vertex::id).collect(toList()); assertThat(ids, containsInAnyOrder(poliana.id(), otavio.id())); } @Test public void shouldFindByNameAndKnowsOutV() { Vertex poliana = graph.addVertex(T.label, "Person", "name", "Poliana", "age", 10); Vertex otavio = graph.addVertex(T.label, "Person", "name", "Otavio", "age", 9); poliana.addEdge("knows", otavio); GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByNameAndKnowsOutV", new Object[]{"Poliana"}, classRepresentation, traversal); Optional<Vertex> vertex = traversal.tryNext(); assertTrue(vertex.isPresent()); assertEquals(otavio.id(), vertex.get().id()); } @Test public void shouldFindByKnowsOutVAndName() { Vertex poliana = graph.addVertex(T.label, "Person", "name", "Poliana", "age", 10); Vertex otavio = graph.addVertex(T.label, "Person", "name", "Otavio", "age", 9); poliana.addEdge("knows", otavio); GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByKnowsOutVAndName", new Object[]{"Otavio"}, classRepresentation, traversal); Optional<Vertex> vertex = traversal.tryNext(); assertTrue(vertex.isPresent()); assertEquals(otavio.id(), vertex.get().id()); } @Test(expected = DynamicQueryException.class) public void shouldReturnErrorWhenIsMissedArgument() { GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByNameAndAgeBetween", new Object[]{"name", 10}, classRepresentation, traversal); } @Test(expected = DynamicQueryException.class) public void shouldReturnErrorWhenIsMissedArgument2() { GraphTraversal<Vertex, Vertex> traversal = graph.traversal().V(); parser.findByParse("findByName", new Object[]{}, classRepresentation, traversal); } }
package ca.uhn.fhir.jpa.dao.r4; import ca.uhn.fhir.jpa.api.config.DaoConfig; import ca.uhn.fhir.jpa.dao.BaseHapiFhirDao; import ca.uhn.fhir.jpa.model.entity.ModelConfig; import ca.uhn.fhir.jpa.model.entity.NormalizedQuantitySearchLevel; import ca.uhn.fhir.jpa.model.entity.ResourceEncodingEnum; import ca.uhn.fhir.jpa.model.entity.ResourceHistoryTable; import ca.uhn.fhir.jpa.model.entity.ResourceIndexedSearchParamString; import ca.uhn.fhir.jpa.model.entity.ResourceTable; import ca.uhn.fhir.jpa.model.entity.ResourceTag; import ca.uhn.fhir.jpa.model.entity.TagTypeEnum; import ca.uhn.fhir.jpa.partition.SystemRequestDetails; import ca.uhn.fhir.jpa.provider.SystemProviderDstu2Test; import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum; import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.rest.api.Constants; import ca.uhn.fhir.rest.api.server.IBundleProvider; import ca.uhn.fhir.rest.param.ReferenceParam; import ca.uhn.fhir.rest.param.StringParam; import ca.uhn.fhir.rest.param.TokenParam; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.PreconditionFailedException; import ca.uhn.fhir.rest.server.exceptions.ResourceGoneException; import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; import ca.uhn.fhir.rest.server.exceptions.ResourceVersionConflictException; import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; import ca.uhn.fhir.util.BundleBuilder; import ca.uhn.fhir.util.ClasspathUtil; import org.apache.commons.io.IOUtils; import org.hamcrest.Matchers; import org.hl7.fhir.instance.model.api.IAnyResource; import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.r4.model.AllergyIntolerance; import org.hl7.fhir.r4.model.Appointment; import org.hl7.fhir.r4.model.Attachment; import org.hl7.fhir.r4.model.Binary; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent; import org.hl7.fhir.r4.model.Bundle.BundleEntryRequestComponent; import org.hl7.fhir.r4.model.Bundle.BundleEntryResponseComponent; import org.hl7.fhir.r4.model.Bundle.BundleType; import org.hl7.fhir.r4.model.Bundle.HTTPVerb; import org.hl7.fhir.r4.model.CanonicalType; import org.hl7.fhir.r4.model.Coding; import org.hl7.fhir.r4.model.Communication; import org.hl7.fhir.r4.model.Condition; import org.hl7.fhir.r4.model.DateTimeType; import org.hl7.fhir.r4.model.DiagnosticReport; import org.hl7.fhir.r4.model.Encounter; import org.hl7.fhir.r4.model.EpisodeOfCare; import org.hl7.fhir.r4.model.HumanName; import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.Identifier; import org.hl7.fhir.r4.model.Medication; import org.hl7.fhir.r4.model.MedicationRequest; import org.hl7.fhir.r4.model.Meta; import org.hl7.fhir.r4.model.Observation; import org.hl7.fhir.r4.model.Observation.ObservationStatus; import org.hl7.fhir.r4.model.OperationOutcome; import org.hl7.fhir.r4.model.OperationOutcome.IssueSeverity; import org.hl7.fhir.r4.model.Organization; import org.hl7.fhir.r4.model.Patient; import org.hl7.fhir.r4.model.Practitioner; import org.hl7.fhir.r4.model.Quantity; import org.hl7.fhir.r4.model.Reference; import org.hl7.fhir.r4.model.Resource; import org.hl7.fhir.r4.model.Task; import org.hl7.fhir.r4.model.ValueSet; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; import javax.annotation.Nonnull; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.emptyString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.matchesPattern; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class FhirSystemDaoR4Test extends BaseJpaR4SystemTest { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirSystemDaoR4Test.class); @AfterEach public void after() { myDaoConfig.setAllowInlineMatchUrlReferences(false); myDaoConfig.setAllowMultipleDelete(new DaoConfig().isAllowMultipleDelete()); myModelConfig.setNormalizedQuantitySearchLevel(NormalizedQuantitySearchLevel.NORMALIZED_QUANTITY_SEARCH_NOT_SUPPORTED); myDaoConfig.setBundleBatchPoolSize(new DaoConfig().getBundleBatchPoolSize()); myDaoConfig.setBundleBatchMaxPoolSize(new DaoConfig().getBundleBatchMaxPoolSize()); myDaoConfig.setAutoCreatePlaceholderReferenceTargets(new DaoConfig().isAutoCreatePlaceholderReferenceTargets()); myModelConfig.setAutoVersionReferenceAtPaths(new ModelConfig().getAutoVersionReferenceAtPaths()); } @BeforeEach public void beforeDisableResultReuse() { myInterceptorRegistry.registerInterceptor(myInterceptor); myDaoConfig.setReuseCachedSearchResultsForMillis(null); myDaoConfig.setBundleBatchPoolSize(1); myDaoConfig.setBundleBatchMaxPoolSize(1); } private Bundle createInputTransactionWithPlaceholderIdInMatchUrl(HTTPVerb theVerb) { Patient pat = new Patient(); pat .addIdentifier() .setSystem("http://acme.org") .setValue("ID1"); Observation obs = new Observation(); obs .getCode() .addCoding() .setSystem("http://loinc.org") .setCode("29463-7"); obs.setEffective(new DateTimeType("2011-09-03T11:13:00-04:00")); obs.setValue(new Quantity() .setValue(new BigDecimal("123.4")) .setCode("kg") .setSystem("http://unitsofmeasure.org") .setUnit("kg")); obs.getSubject().setReference("urn:uuid:0001"); Observation obs2 = new Observation(); obs2 .getCode() .addCoding() .setSystem("http://loinc.org") .setCode("29463-7"); obs2.setEffective(new DateTimeType("2017-09-03T11:13:00-04:00")); obs2.setValue(new Quantity() .setValue(new BigDecimal("123.4")) .setCode("kg") .setSystem("http://unitsofmeasure.org") .setUnit("kg")); obs2.getSubject().setReference("urn:uuid:0001"); /* * Put one observation before the patient it references, and * one after it just to make sure that order doesn't matter */ Bundle input = new Bundle(); input.setType(BundleType.TRANSACTION); if (theVerb == HTTPVerb.PUT) { input .addEntry() .setFullUrl("urn:uuid:0002") .setResource(obs) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Observation?subject=urn:uuid:0001&code=http%3A%2F%2Floinc.org|29463-7&date=2011-09-03T11:13:00-04:00"); input .addEntry() .setFullUrl("urn:uuid:0001") .setResource(pat) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Patient?identifier=http%3A%2F%2Facme.org|ID1"); input .addEntry() .setFullUrl("urn:uuid:0003") .setResource(obs2) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Observation?subject=urn:uuid:0001&code=http%3A%2F%2Floinc.org|29463-7&date=2017-09-03T11:13:00-04:00"); } else if (theVerb == HTTPVerb.POST) { input .addEntry() .setFullUrl("urn:uuid:0002") .setResource(obs) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Observation") .setIfNoneExist("Observation?subject=urn:uuid:0001&code=http%3A%2F%2Floinc.org|29463-7&date=2011-09-03T11:13:00-04:00"); input .addEntry() .setFullUrl("urn:uuid:0001") .setResource(pat) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Patient") .setIfNoneExist("Patient?identifier=http%3A%2F%2Facme.org|ID1"); input .addEntry() .setFullUrl("urn:uuid:0003") .setResource(obs2) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Observation") .setIfNoneExist("Observation?subject=urn:uuid:0001&code=http%3A%2F%2Floinc.org|29463-7&date=2017-09-03T11:13:00-04:00"); } return input; } @SuppressWarnings("unchecked") private <T extends org.hl7.fhir.r4.model.Resource> T find(Bundle theBundle, Class<T> theType, int theIndex) { int count = 0; for (BundleEntryComponent nextEntry : theBundle.getEntry()) { if (nextEntry.getResource() != null && theType.isAssignableFrom(nextEntry.getResource().getClass())) { if (count == theIndex) { return (T) nextEntry.getResource(); } count++; } } fail(); return null; } @Test public void testTransactionReSavesPreviouslyDeletedResources() { { Bundle input = new Bundle(); input.setType(BundleType.TRANSACTION); Patient pt = new Patient(); pt.setId("pt"); pt.setActive(true); input .addEntry() .setResource(pt) .getRequest() .setUrl("Patient/pt") .setMethod(HTTPVerb.PUT); Observation obs = new Observation(); obs.setId("obs"); obs.getSubject().setReference("Patient/pt"); input .addEntry() .setResource(obs) .getRequest() .setUrl("Observation/obs") .setMethod(HTTPVerb.PUT); mySystemDao.transaction(null, input); } myObservationDao.delete(new IdType("Observation/obs")); myPatientDao.delete(new IdType("Patient/pt")); { Bundle input = new Bundle(); input.setType(BundleType.TRANSACTION); Patient pt = new Patient(); pt.setId("pt"); pt.setActive(true); input .addEntry() .setResource(pt) .getRequest() .setUrl("Patient/pt") .setMethod(HTTPVerb.PUT); Observation obs = new Observation(); obs.setId("obs"); obs.getSubject().setReference("Patient/pt"); input .addEntry() .setResource(obs) .getRequest() .setUrl("Observation/obs") .setMethod(HTTPVerb.PUT); mySystemDao.transaction(null, input); } myPatientDao.read(new IdType("Patient/pt")); } @Test public void testResourceCounts() { Patient p = new Patient(); p.setActive(true); myPatientDao.create(p); Observation o = new Observation(); o.setStatus(ObservationStatus.AMENDED); myObservationDao.create(o); Map<String, Long> counts = mySystemDao.getResourceCounts(); assertEquals(new Long(1L), counts.get("Patient")); assertEquals(new Long(1L), counts.get("Observation")); assertEquals(null, counts.get("Organization")); } @Test public void testBatchCreateWithBadRead() { Bundle request = new Bundle(); request.setType(BundleType.BATCH); Patient p; p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue("FOO"); request .addEntry() .setResource(p) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Patient"); request .addEntry() .getRequest() .setMethod(HTTPVerb.GET) .setUrl("Patient/BABABABA"); Bundle response = mySystemDao.transaction(mySrd, request); assertEquals(2, response.getEntry().size()); assertEquals("201 Created", response.getEntry().get(0).getResponse().getStatus()); assertThat(response.getEntry().get(0).getResponse().getLocation(), matchesPattern(".*Patient/[0-9]+.*")); assertEquals("404 Not Found", response.getEntry().get(1).getResponse().getStatus()); OperationOutcome oo = (OperationOutcome) response.getEntry().get(1).getResponse().getOutcome(); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(oo)); assertEquals(IssueSeverity.ERROR, oo.getIssue().get(0).getSeverity()); assertEquals("Resource Patient/BABABABA is not known", oo.getIssue().get(0).getDiagnostics()); } @Test public void testBatchCreateWithBadSearch() { Bundle request = new Bundle(); request.setType(BundleType.BATCH); Patient p; p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue("FOO"); request .addEntry() .setResource(p) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Patient"); request .addEntry() .getRequest() .setMethod(HTTPVerb.GET) .setUrl("Patient?foobadparam=1"); Bundle response = mySystemDao.transaction(mySrd, request); assertEquals(2, response.getEntry().size()); assertEquals("201 Created", response.getEntry().get(0).getResponse().getStatus()); assertThat(response.getEntry().get(0).getResponse().getLocation(), matchesPattern(".*Patient/[0-9]+.*")); assertEquals("400 Bad Request", response.getEntry().get(1).getResponse().getStatus()); OperationOutcome oo = (OperationOutcome) response.getEntry().get(1).getResponse().getOutcome(); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(oo)); assertEquals(IssueSeverity.ERROR, oo.getIssue().get(0).getSeverity()); assertThat(oo.getIssue().get(0).getDiagnostics(), containsString("Unknown search parameter")); } @Test public void testCircularCreateAndDelete() { Encounter enc = new Encounter(); enc.setId(IdType.newRandomUuid()); Condition cond = new Condition(); cond.setId(IdType.newRandomUuid()); EpisodeOfCare ep = new EpisodeOfCare(); ep.setId(IdType.newRandomUuid()); enc.getEpisodeOfCareFirstRep().setReference(ep.getId()); cond.getEncounter().setReference(enc.getId()); ep.getDiagnosisFirstRep().getCondition().setReference(cond.getId()); Bundle inputBundle = new Bundle(); inputBundle.setType(Bundle.BundleType.TRANSACTION); inputBundle .addEntry() .setResource(ep) .setFullUrl(ep.getId()) .getRequest().setMethod(HTTPVerb.POST); inputBundle .addEntry() .setResource(cond) .setFullUrl(cond.getId()) .getRequest().setMethod(HTTPVerb.POST); inputBundle .addEntry() .setResource(enc) .setFullUrl(enc.getId()) .getRequest().setMethod(HTTPVerb.POST); Bundle resp = mySystemDao.transaction(mySrd, inputBundle); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); IdType epId = new IdType(resp.getEntry().get(0).getResponse().getLocation()); IdType condId = new IdType(resp.getEntry().get(1).getResponse().getLocation()); IdType encId = new IdType(resp.getEntry().get(2).getResponse().getLocation()); // Make sure a single one can't be deleted try { myEncounterDao.delete(encId); fail(); } catch (ResourceVersionConflictException e) { // good } /* * Now delete all 3 by transaction */ inputBundle = new Bundle(); inputBundle.setType(Bundle.BundleType.TRANSACTION); inputBundle .addEntry() .getRequest().setMethod(HTTPVerb.DELETE) .setUrl(epId.toUnqualifiedVersionless().getValue()); inputBundle .addEntry() .getRequest().setMethod(HTTPVerb.DELETE) .setUrl(encId.toUnqualifiedVersionless().getValue()); inputBundle .addEntry() .getRequest().setMethod(HTTPVerb.DELETE) .setUrl(condId.toUnqualifiedVersionless().getValue()); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(inputBundle)); resp = mySystemDao.transaction(mySrd, inputBundle); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); // They should now be deleted try { myEncounterDao.read(encId.toUnqualifiedVersionless()); fail(); } catch (ResourceGoneException e) { // good } } /** * See #410 */ @Test public void testContainedArePreservedForBug410() throws IOException { String input = ClasspathUtil.loadResource("/r4/bug-410-bundle.xml"); Bundle bundle = myFhirCtx.newXmlParser().parseResource(Bundle.class, input); Bundle output = mySystemDao.transaction(mySrd, bundle); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(output)); IdType id = new IdType(output.getEntry().get(1).getResponse().getLocation()); MedicationRequest mo = myMedicationRequestDao.read(id); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(mo)); } @Test public void testMultipleUpdatesWithNoChangesDoesNotResultInAnUpdateForTransaction() { Bundle bundle; // First time Patient p = new Patient(); p.setActive(true); bundle = new Bundle(); bundle.setType(BundleType.TRANSACTION); bundle .addEntry() .setResource(p) .setFullUrl("Patient/A") .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Patient/A"); Bundle resp = mySystemDao.transaction(mySrd, bundle); assertThat(resp.getEntry().get(0).getResponse().getLocation(), endsWith("Patient/A/_history/1")); // Second time should not result in an update p = new Patient(); p.setActive(true); bundle = new Bundle(); bundle.setType(BundleType.TRANSACTION); bundle .addEntry() .setResource(p) .setFullUrl("Patient/A") .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Patient/A"); resp = mySystemDao.transaction(mySrd, bundle); assertThat(resp.getEntry().get(0).getResponse().getLocation(), endsWith("Patient/A/_history/1")); // And third time should not result in an update p = new Patient(); p.setActive(true); bundle = new Bundle(); bundle.setType(BundleType.TRANSACTION); bundle .addEntry() .setResource(p) .setFullUrl("Patient/A") .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Patient/A"); resp = mySystemDao.transaction(mySrd, bundle); assertThat(resp.getEntry().get(0).getResponse().getLocation(), endsWith("Patient/A/_history/1")); myPatientDao.read(new IdType("Patient/A")); myPatientDao.read(new IdType("Patient/A/_history/1")); try { myPatientDao.read(new IdType("Patient/A/_history/2")); fail(); } catch (ResourceNotFoundException e) { // good } try { myPatientDao.read(new IdType("Patient/A/_history/3")); fail(); } catch (ResourceNotFoundException e) { // good } } @Test public void testReindexing() throws InterruptedException { Patient p = new Patient(); p.addName().setFamily("family"); final IIdType id = myPatientDao.create(p, mySrd).getId().toUnqualified(); sleepUntilTimeChanges(); ValueSet vs = new ValueSet(); vs.setUrl("http://foo"); myValueSetDao.create(vs, mySrd); sleepUntilTimeChanges(); ResourceTable entity = new TransactionTemplate(myTxManager).execute(t -> myEntityManager.find(ResourceTable.class, id.getIdPartAsLong())); assertEquals(Long.valueOf(1), entity.getIndexStatus()); Long jobId = myResourceReindexingSvc.markAllResourcesForReindexing(); myResourceReindexingSvc.forceReindexingPass(); entity = new TransactionTemplate(myTxManager).execute(t -> myEntityManager.find(ResourceTable.class, id.getIdPartAsLong())); assertEquals(Long.valueOf(1), entity.getIndexStatus()); // Just make sure this doesn't cause a choke myResourceReindexingSvc.forceReindexingPass(); /* * We expect a final reindex count of 3 because there are 2 resources to * reindex and the final pass uses the most recent time as the low threshold, * so it indexes the newest resource one more time. It wouldn't be a big deal * if this ever got fixed so that it ends up with 2 instead of 3. */ runInTransaction(() -> { Optional<Integer> reindexCount = myResourceReindexJobDao.getReindexCount(jobId); assertEquals(3, reindexCount.orElseThrow(() -> new NullPointerException("No job " + jobId)).intValue()); }); // Try making the resource unparseable TransactionTemplate template = new TransactionTemplate(myTxManager); template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); template.execute((TransactionCallback<ResourceTable>) t -> { ResourceHistoryTable resourceHistoryTable = myResourceHistoryTableDao.findForIdAndVersionAndFetchProvenance(id.getIdPartAsLong(), id.getVersionIdPartAsLong()); resourceHistoryTable.setEncoding(ResourceEncodingEnum.JSON); try { resourceHistoryTable.setResource("{\"resourceType\":\"FOO\"}".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Error(e); } myResourceHistoryTableDao.save(resourceHistoryTable); ResourceTable table = myResourceTableDao.findById(id.getIdPartAsLong()).orElseThrow(IllegalStateException::new); table.setIndexStatus(null); myResourceTableDao.save(table); return null; }); myResourceReindexingSvc.markAllResourcesForReindexing(); myResourceReindexingSvc.forceReindexingPass(); entity = new TransactionTemplate(myTxManager).execute(theStatus -> myEntityManager.find(ResourceTable.class, id.getIdPartAsLong())); assertEquals(Long.valueOf(2), entity.getIndexStatus()); } @Test public void testReindexingCurrentVersionDeleted() { Patient p = new Patient(); p.addName().setFamily("family1"); final IIdType id = myPatientDao.create(p, mySrd).getId().toUnqualifiedVersionless(); p = new Patient(); p.setId(id.getValue()); p.addName().setFamily("family1"); p.addName().setFamily("family2"); myPatientDao.update(p); p = new Patient(); p.setId(id.getValue()); p.addName().setFamily("family1"); p.addName().setFamily("family2"); p.addName().setFamily("family3"); myPatientDao.update(p); SearchParameterMap searchParamMap = new SearchParameterMap(); searchParamMap.setLoadSynchronous(true); searchParamMap.add(Patient.SP_FAMILY, new StringParam("family2")); assertEquals(1, myPatientDao.search(searchParamMap).size().intValue()); runInTransaction(() -> { ResourceHistoryTable historyEntry = myResourceHistoryTableDao.findForIdAndVersionAndFetchProvenance(id.getIdPartAsLong(), 3); assertNotNull(historyEntry); myResourceHistoryTableDao.delete(historyEntry); }); Long jobId = myResourceReindexingSvc.markAllResourcesForReindexing(); myResourceReindexingSvc.forceReindexingPass(); searchParamMap = new SearchParameterMap(); searchParamMap.setLoadSynchronous(true); searchParamMap.add(Patient.SP_FAMILY, new StringParam("family2")); IBundleProvider search = myPatientDao.search(searchParamMap); assertEquals(1, search.size().intValue()); p = (Patient) search.getResources(0, 1).get(0); assertEquals("3", p.getIdElement().getVersionIdPart()); } @Test public void testReindexingSingleStringHashValueIsDeleted() { Patient p = new Patient(); p.addName().setFamily("family1"); final IIdType id = myPatientDao.create(p, mySrd).getId().toUnqualifiedVersionless(); SearchParameterMap searchParamMap = new SearchParameterMap(); searchParamMap.setLoadSynchronous(true); searchParamMap.add(Patient.SP_FAMILY, new StringParam("family1")); assertEquals(1, myPatientDao.search(searchParamMap).size().intValue()); runInTransaction(() -> { myEntityManager .createQuery("UPDATE ResourceIndexedSearchParamString s SET s.myHashNormalizedPrefix = 0") .executeUpdate(); }); myCaptureQueriesListener.clear(); Integer found = myPatientDao.search(searchParamMap).size(); myCaptureQueriesListener.logSelectQueriesForCurrentThread(); assertEquals(0, found.intValue()); myResourceReindexingSvc.markAllResourcesForReindexing(); myResourceReindexingSvc.forceReindexingPass(); runInTransaction(() -> { ResourceIndexedSearchParamString param = myResourceIndexedSearchParamStringDao.findAll() .stream() .filter(t -> t.getParamName().equals("family")) .findFirst() .orElseThrow(() -> new IllegalArgumentException()); assertEquals(-6332913947530887803L, param.getHashNormalizedPrefix().longValue()); }); assertEquals(1, myPatientDao.search(searchParamMap).size().intValue()); } @Test public void testReindexingSingleStringHashIdentityValueIsDeleted() { Patient p = new Patient(); p.addName().setFamily("family1"); final IIdType id = myPatientDao.create(p, mySrd).getId().toUnqualifiedVersionless(); SearchParameterMap searchParamMap = new SearchParameterMap(); searchParamMap.setLoadSynchronous(true); searchParamMap.add(Patient.SP_FAMILY, new StringParam("family1")); assertEquals(1, myPatientDao.search(searchParamMap).size().intValue()); runInTransaction(() -> { Long i = myEntityManager .createQuery("SELECT count(s) FROM ResourceIndexedSearchParamString s WHERE s.myHashIdentity = 0", Long.class) .getSingleResult(); assertEquals(0L, i.longValue()); myEntityManager .createQuery("UPDATE ResourceIndexedSearchParamString s SET s.myHashIdentity = 0") .executeUpdate(); i = myEntityManager .createQuery("SELECT count(s) FROM ResourceIndexedSearchParamString s WHERE s.myHashIdentity = 0", Long.class) .getSingleResult(); assertThat(i, greaterThan(1L)); }); myResourceReindexingSvc.markAllResourcesForReindexing(); myResourceReindexingSvc.forceReindexingPass(); runInTransaction(() -> { Long i = myEntityManager .createQuery("SELECT count(s) FROM ResourceIndexedSearchParamString s WHERE s.myHashIdentity = 0", Long.class) .getSingleResult(); assertEquals(0L, i.longValue()); }); } @Test public void testSystemMetaOperation() { Meta meta = mySystemDao.metaGetOperation(mySrd); List<Coding> published = meta.getTag(); assertEquals(0, published.size()); String methodName = "testSystemMetaOperation"; IIdType id1; { Patient patient = new Patient(); patient.addIdentifier().setSystem("urn:system").setValue(methodName); patient.addName().setFamily("Tester").addGiven("Joe"); patient.getMeta().addTag(null, "Dog", "Puppies"); patient.getMeta().getSecurity().add(new Coding().setSystem("seclabel:sys:1").setCode("seclabel:code:1").setDisplay("seclabel:dis:1")); patient.getMeta().getProfile().add(new CanonicalType("http://profile/1")); id1 = myPatientDao.create(patient, mySrd).getId(); } { Patient patient = new Patient(); patient.addIdentifier().setSystem("urn:system").setValue(methodName); patient.addName().setFamily("Tester").addGiven("Joe"); patient.getMeta().addTag("http://foo", "Cat", "Kittens"); patient.getMeta().getSecurity().add(new Coding().setSystem("seclabel:sys:2").setCode("seclabel:code:2").setDisplay("seclabel:dis:2")); patient.getMeta().getProfile().add(new CanonicalType("http://profile/2")); myPatientDao.create(patient, mySrd); } meta = mySystemDao.metaGetOperation(mySrd); published = meta.getTag(); assertEquals(2, published.size()); assertEquals(null, published.get(0).getSystem()); assertEquals("Dog", published.get(0).getCode()); assertEquals("Puppies", published.get(0).getDisplay()); assertEquals("http://foo", published.get(1).getSystem()); assertEquals("Cat", published.get(1).getCode()); assertEquals("Kittens", published.get(1).getDisplay()); List<Coding> secLabels = meta.getSecurity(); assertEquals(2, secLabels.size()); assertEquals("seclabel:sys:1", secLabels.get(0).getSystemElement().getValue()); assertEquals("seclabel:code:1", secLabels.get(0).getCodeElement().getValue()); assertEquals("seclabel:dis:1", secLabels.get(0).getDisplayElement().getValue()); assertEquals("seclabel:sys:2", secLabels.get(1).getSystemElement().getValue()); assertEquals("seclabel:code:2", secLabels.get(1).getCodeElement().getValue()); assertEquals("seclabel:dis:2", secLabels.get(1).getDisplayElement().getValue()); List<CanonicalType> profiles = meta.getProfile(); assertEquals(2, profiles.size()); assertEquals("http://profile/1", profiles.get(0).getValue()); assertEquals("http://profile/2", profiles.get(1).getValue()); myPatientDao.removeTag(id1, TagTypeEnum.TAG, null, "Dog", mySrd); myPatientDao.removeTag(id1, TagTypeEnum.SECURITY_LABEL, "seclabel:sys:1", "seclabel:code:1", mySrd); myPatientDao.removeTag(id1, TagTypeEnum.PROFILE, BaseHapiFhirDao.NS_JPA_PROFILE, "http://profile/1", mySrd); meta = mySystemDao.metaGetOperation(mySrd); published = meta.getTag(); assertEquals(1, published.size()); assertEquals("http://foo", published.get(0).getSystem()); assertEquals("Cat", published.get(0).getCode()); assertEquals("Kittens", published.get(0).getDisplay()); secLabels = meta.getSecurity(); assertEquals(1, secLabels.size()); assertEquals("seclabel:sys:2", secLabels.get(0).getSystemElement().getValue()); assertEquals("seclabel:code:2", secLabels.get(0).getCodeElement().getValue()); assertEquals("seclabel:dis:2", secLabels.get(0).getDisplayElement().getValue()); profiles = meta.getProfile(); assertEquals(1, profiles.size()); assertEquals("http://profile/2", profiles.get(0).getValue()); } @Test public void testTransaction1() throws IOException { String inputBundleString = loadClasspath("/david-bundle-error.json"); Bundle bundle = myFhirCtx.newJsonParser().parseResource(Bundle.class, inputBundleString); Bundle resp = mySystemDao.transaction(mySrd, bundle); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); assertEquals("201 Created", resp.getEntry().get(0).getResponse().getStatus()); } @Test public void testNestedTransaction_ReadsBlocked() { String methodName = "testTransactionBatchWithFailingRead"; Bundle request = new Bundle(); request.setType(BundleType.TRANSACTION); Patient p = new Patient(); p.addName().setFamily(methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST); request.addEntry().getRequest().setMethod(HTTPVerb.GET).setUrl("Patient?identifier=foo"); try { runInTransaction(() -> { mySystemDao.transactionNested(mySrd, request); }); fail(); } catch (InvalidRequestException e) { assertEquals("Can not invoke read operation on nested transaction", e.getMessage()); } } @Test public void testTransactionBatchWithFailingRead() { String methodName = "testTransactionBatchWithFailingRead"; Bundle request = new Bundle(); request.setType(BundleType.BATCH); Patient p = new Patient(); p.addName().setFamily(methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST); request.addEntry().getRequest().setMethod(HTTPVerb.GET).setUrl("Patient/THIS_ID_DOESNT_EXIST"); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(2, resp.getEntry().size()); assertEquals(BundleType.BATCHRESPONSE, resp.getTypeElement().getValue()); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); BundleEntryResponseComponent respEntry; // Bundle.entry[0] is create response assertEquals("201 Created", resp.getEntry().get(0).getResponse().getStatus()); assertThat(resp.getEntry().get(0).getResponse().getLocation(), startsWith("Patient/")); // Bundle.entry[1] is failed read response Resource oo = resp.getEntry().get(1).getResponse().getOutcome(); assertEquals(OperationOutcome.class, oo.getClass()); assertEquals(IssueSeverity.ERROR, ((OperationOutcome) oo).getIssue().get(0).getSeverityElement().getValue()); assertEquals("Resource Patient/THIS_ID_DOESNT_EXIST is not known", ((OperationOutcome) oo).getIssue().get(0).getDiagnostics()); assertEquals("404 Not Found", resp.getEntry().get(1).getResponse().getStatus()); // Check POST respEntry = resp.getEntry().get(0).getResponse(); assertEquals("201 Created", respEntry.getStatus()); IdType createdId = new IdType(respEntry.getLocation()); assertEquals("Patient", createdId.getResourceType()); myPatientDao.read(createdId, mySrd); // shouldn't fail // Check GET respEntry = resp.getEntry().get(1).getResponse(); assertThat(respEntry.getStatus(), startsWith("404")); } @Test public void testTransactionWithConditionalCreates_IdenticalMatchUrlsDifferentTypes_Unqualified() { BundleBuilder bb = new BundleBuilder(myFhirCtx); Patient pt = new Patient(); pt.addIdentifier().setSystem("foo").setValue("bar"); bb.addTransactionCreateEntry(pt).conditional("identifier=foo|bar"); Observation obs = new Observation(); obs.addIdentifier().setSystem("foo").setValue("bar"); bb.addTransactionCreateEntry(obs).conditional("identifier=foo|bar"); Bundle outcome = mySystemDao.transaction(mySrd, (Bundle) bb.getBundle()); assertEquals("201 Created", outcome.getEntry().get(0).getResponse().getStatus()); assertThat(outcome.getEntry().get(0).getResponse().getLocation(), matchesPattern(".*Patient/[0-9]+/_history/1")); assertEquals("201 Created", outcome.getEntry().get(1).getResponse().getStatus()); assertThat(outcome.getEntry().get(1).getResponse().getLocation(), matchesPattern(".*Observation/[0-9]+/_history/1")); // Take 2 bb = new BundleBuilder(myFhirCtx); pt = new Patient(); pt.addIdentifier().setSystem("foo").setValue("bar"); bb.addTransactionCreateEntry(pt).conditional("identifier=foo|bar"); obs = new Observation(); obs.addIdentifier().setSystem("foo").setValue("bar"); bb.addTransactionCreateEntry(obs).conditional("identifier=foo|bar"); outcome = mySystemDao.transaction(mySrd, (Bundle) bb.getBundle()); assertEquals("200 OK", outcome.getEntry().get(0).getResponse().getStatus()); assertThat(outcome.getEntry().get(0).getResponse().getLocation(), matchesPattern(".*Patient/[0-9]+/_history/1")); assertEquals("200 OK", outcome.getEntry().get(1).getResponse().getStatus()); assertThat(outcome.getEntry().get(1).getResponse().getLocation(), matchesPattern(".*Observation/[0-9]+/_history/1")); } @Test public void testTransactionWithConditionalCreates_IdenticalMatchUrlsDifferentTypes_Qualified() { BundleBuilder bb = new BundleBuilder(myFhirCtx); Patient pt = new Patient(); pt.addIdentifier().setSystem("foo").setValue("bar"); bb.addTransactionCreateEntry(pt).conditional("Patient?identifier=foo|bar"); Observation obs = new Observation(); obs.addIdentifier().setSystem("foo").setValue("bar"); bb.addTransactionCreateEntry(obs).conditional("Observation?identifier=foo|bar"); Bundle outcome = mySystemDao.transaction(mySrd, (Bundle) bb.getBundle()); assertEquals("201 Created", outcome.getEntry().get(0).getResponse().getStatus()); assertThat(outcome.getEntry().get(0).getResponse().getLocation(), matchesPattern(".*Patient/[0-9]+/_history/1")); assertEquals("201 Created", outcome.getEntry().get(1).getResponse().getStatus()); assertThat(outcome.getEntry().get(1).getResponse().getLocation(), matchesPattern(".*Observation/[0-9]+/_history/1")); // Take 2 bb = new BundleBuilder(myFhirCtx); pt = new Patient(); pt.addIdentifier().setSystem("foo").setValue("bar"); bb.addTransactionCreateEntry(pt).conditional("Patient?identifier=foo|bar"); obs = new Observation(); obs.addIdentifier().setSystem("foo").setValue("bar"); bb.addTransactionCreateEntry(obs).conditional("Observation?identifier=foo|bar"); outcome = mySystemDao.transaction(mySrd, (Bundle) bb.getBundle()); assertEquals("200 OK", outcome.getEntry().get(0).getResponse().getStatus()); assertThat(outcome.getEntry().get(0).getResponse().getLocation(), matchesPattern(".*Patient/[0-9]+/_history/1")); assertEquals("200 OK", outcome.getEntry().get(1).getResponse().getStatus()); assertThat(outcome.getEntry().get(1).getResponse().getLocation(), matchesPattern(".*Observation/[0-9]+/_history/1")); } @Test public void testTransactionWithConditionalCreate_NoResourceTypeInUrl() { BundleBuilder bb = new BundleBuilder(myFhirCtx); Patient pt = new Patient(); pt.setActive(true); bb.addTransactionCreateEntry(pt).conditional("active=true"); pt = new Patient(); pt.setActive(false); bb.addTransactionCreateEntry(pt).conditional("active=false"); Bundle outcome = mySystemDao.transaction(mySrd, (Bundle) bb.getBundle()); assertEquals("201 Created", outcome.getEntry().get(0).getResponse().getStatus()); assertEquals("201 Created", outcome.getEntry().get(1).getResponse().getStatus()); // Take 2 bb = new BundleBuilder(myFhirCtx); pt = new Patient(); pt.setActive(true); bb.addTransactionCreateEntry(pt).conditional("active=true"); pt = new Patient(); pt.setActive(false); bb.addTransactionCreateEntry(pt).conditional("active=false"); Bundle outcome2 = mySystemDao.transaction(mySrd, (Bundle) bb.getBundle()); assertEquals("200 OK", outcome2.getEntry().get(0).getResponse().getStatus()); assertEquals("200 OK", outcome2.getEntry().get(1).getResponse().getStatus()); assertThat(outcome.getEntry().get(0).getResponse().getLocation(), endsWith("/_history/1")); assertThat(outcome.getEntry().get(1).getResponse().getLocation(), endsWith("/_history/1")); assertEquals(outcome.getEntry().get(0).getResponse().getLocation(), outcome2.getEntry().get(0).getResponse().getLocation()); assertEquals(outcome.getEntry().get(1).getResponse().getLocation(), outcome2.getEntry().get(1).getResponse().getLocation()); // Take 3 bb = new BundleBuilder(myFhirCtx); pt = new Patient(); pt.setActive(true); bb.addTransactionCreateEntry(pt).conditional("?active=true"); pt = new Patient(); pt.setActive(false); bb.addTransactionCreateEntry(pt).conditional("?active=false"); Bundle outcome3 = mySystemDao.transaction(mySrd, (Bundle) bb.getBundle()); assertEquals("200 OK", outcome3.getEntry().get(0).getResponse().getStatus()); assertEquals("200 OK", outcome3.getEntry().get(1).getResponse().getStatus()); assertEquals(outcome.getEntry().get(0).getResponse().getLocation(), outcome3.getEntry().get(0).getResponse().getLocation()); assertEquals(outcome.getEntry().get(1).getResponse().getLocation(), outcome3.getEntry().get(1).getResponse().getLocation()); } @Test public void testTransactionNoContainedRedux() throws IOException { //Pre-create the patient, which will cause the ifNoneExist to prevent a new creation during bundle transaction Patient patient = loadResourceFromClasspath(Patient.class, "/r4/preexisting-patient.json"); myPatientDao.create(patient); //Post the Bundle containing a conditional POST with an identical patient from the above resource. Bundle request = loadResourceFromClasspath(Bundle.class, "/r4/transaction-no-contained-2.json"); Bundle outcome = mySystemDao.transaction(mySrd, request); IdType taskId = new IdType(outcome.getEntry().get(0).getResponse().getLocation()); Task task = myTaskDao.read(taskId, mySrd); assertThat(task.getBasedOn().get(0).getReference(), matchesPattern("Patient/[0-9]+")); } @Test public void testTransactionNoContained() throws IOException { // Run once (should create the patient) Bundle request = loadResourceFromClasspath(Bundle.class, "/r4/transaction-no-contained.json"); mySystemDao.transaction(mySrd, request); // Run a second time (no conditional update) request = loadResourceFromClasspath(Bundle.class, "/r4/transaction-no-contained.json"); Bundle outcome = mySystemDao.transaction(mySrd, request); ourLog.info("Outcome: {}", myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(outcome)); IdType communicationId = new IdType(outcome.getEntry().get(1).getResponse().getLocation()); Communication communication = myCommunicationDao.read(communicationId, mySrd); assertThat(communication.getSubject().getReference(), matchesPattern("Patient/[0-9]+")); ourLog.info("Outcome: {}", myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(communication)); } @Test public void testTransactionCreateInlineMatchUrlWithNoMatches() { String methodName = "testTransactionCreateInlineMatchUrlWithNoMatches"; Bundle request = new Bundle(); myDaoConfig.setAllowInlineMatchUrlReferences(true); Observation o = new Observation(); o.getCode().setText("Some Observation"); o.getSubject().setReference("Patient?identifier=urn%3Asystem%7C" + methodName); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.POST); try { mySystemDao.transaction(mySrd, request); fail(); } catch (ResourceNotFoundException e) { assertEquals("Invalid match URL \"Patient?identifier=urn%3Asystem%7CtestTransactionCreateInlineMatchUrlWithNoMatches\" - No resources match this search", e.getMessage()); } } @Test public void testTransactionMissingResourceForPost() { Bundle request = new Bundle(); request.setType(BundleType.TRANSACTION); request .addEntry() .setFullUrl("Patient/") .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Patient/"); try { mySystemDao.transaction(mySrd, request); fail(); } catch (InvalidRequestException e) { assertEquals("Missing required resource in Bundle.entry[0].resource for operation POST", e.getMessage()); } } @Test public void testTransactionMissingResourceForPut() { Bundle request = new Bundle(); request.setType(BundleType.TRANSACTION); request .addEntry() .setFullUrl("Patient/123") .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Patient/123"); try { mySystemDao.transaction(mySrd, request); fail(); } catch (InvalidRequestException e) { assertEquals("Missing required resource in Bundle.entry[0].resource for operation PUT", e.getMessage()); } } @Test public void testBatchMissingResourceForPost() { Bundle request = new Bundle(); request.setType(BundleType.BATCH); request .addEntry() .setFullUrl("Patient/") .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Patient/"); Bundle outcome = mySystemDao.transaction(mySrd, request); ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(outcome)); assertEquals("400 Bad Request", outcome.getEntry().get(0).getResponse().getStatus()); assertEquals(IssueSeverity.ERROR, ((OperationOutcome) outcome.getEntry().get(0).getResponse().getOutcome()).getIssueFirstRep().getSeverity()); assertEquals("Missing required resource in Bundle.entry[0].resource for operation POST", ((OperationOutcome) outcome.getEntry().get(0).getResponse().getOutcome()).getIssueFirstRep().getDiagnostics()); validate(outcome); } @Test public void testBatchMissingResourceForPut() { Bundle request = new Bundle(); request.setType(BundleType.BATCH); request .addEntry() .setFullUrl("Patient/123") .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Patient/123"); Bundle outcome = mySystemDao.transaction(mySrd, request); ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(outcome)); assertEquals("400 Bad Request", outcome.getEntry().get(0).getResponse().getStatus()); assertEquals(IssueSeverity.ERROR, ((OperationOutcome) outcome.getEntry().get(0).getResponse().getOutcome()).getIssueFirstRep().getSeverity()); assertEquals("Missing required resource in Bundle.entry[0].resource for operation PUT", ((OperationOutcome) outcome.getEntry().get(0).getResponse().getOutcome()).getIssueFirstRep().getDiagnostics()); validate(outcome); } @Test public void testBatchMissingUrlForPost() { Bundle request = new Bundle(); request.setType(BundleType.BATCH); request .addEntry() .setResource(new Patient().setActive(true)) .getRequest() .setMethod(HTTPVerb.POST); Bundle outcome = mySystemDao.transaction(mySrd, request); ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(outcome)); assertEquals("201 Created", outcome.getEntry().get(0).getResponse().getStatus()); validate(outcome); } @Test public void testConditionalUpdate_forObservationWithNonExistentPatientSubject_shouldCreateLinkedResources() { Bundle transactionBundle = new Bundle().setType(BundleType.TRANSACTION); // Patient HumanName patientName = new HumanName().setFamily("TEST_LAST_NAME").addGiven("TEST_FIRST_NAME"); Identifier patientIdentifier = new Identifier().setSystem("http://example.com/mrns").setValue("U1234567890"); Patient patient = new Patient() .setName(List.of(patientName)) .setIdentifier(List.of(patientIdentifier)); patient.setId(IdType.newRandomUuid()); transactionBundle .addEntry() .setFullUrl(patient.getId()) .setResource(patient) .getRequest() .setMethod(Bundle.HTTPVerb.PUT) .setUrl("/Patient?identifier=" + patientIdentifier.getSystem() + "|" + patientIdentifier.getValue()); // Observation Observation observation = new Observation(); observation.setId(IdType.newRandomUuid()); observation.getSubject().setReference(patient.getIdElement().toUnqualifiedVersionless().toString()); transactionBundle .addEntry() .setFullUrl(observation.getId()) .setResource(observation) .getRequest() .setMethod(Bundle.HTTPVerb.PUT) .setUrl("/Observation?subject=" + patient.getIdElement().toUnqualifiedVersionless().toString()); ourLog.info("Patient TEMP UUID: {}", patient.getId()); String s = myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(transactionBundle); System.out.println(s); Bundle outcome= mySystemDao.transaction(null, transactionBundle); String patientLocation = outcome.getEntry().get(0).getResponse().getLocation(); assertThat(patientLocation, matchesPattern("Patient/[a-z0-9-]+/_history/1")); String observationLocation = outcome.getEntry().get(1).getResponse().getLocation(); assertThat(observationLocation, matchesPattern("Observation/[a-z0-9-]+/_history/1")); } @Test public void testTransactionCreateInlineMatchUrlWithOneMatch() { String methodName = "testTransactionCreateInlineMatchUrlWithOneMatch"; Bundle request = new Bundle(); myDaoConfig.setAllowInlineMatchUrlReferences(true); Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.setId("Patient/" + methodName); IIdType id = myPatientDao.update(p, mySrd).getId(); ourLog.info("Created patient, got it: {}", id); Observation o = new Observation(); o.getCode().setText("Some Observation"); o.getSubject().setReference("Patient?identifier=urn%3Asystem%7C" + methodName); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.POST); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(1, resp.getEntry().size()); BundleEntryComponent respEntry = resp.getEntry().get(0); assertEquals(Constants.STATUS_HTTP_201_CREATED + " Created", respEntry.getResponse().getStatus()); assertThat(respEntry.getResponse().getLocation(), containsString("Observation/")); assertThat(respEntry.getResponse().getLocation(), endsWith("/_history/1")); assertEquals("1", respEntry.getResponse().getEtag()); o = myObservationDao.read(new IdType(respEntry.getResponse().getLocationElement()), mySrd); assertEquals(id.toVersionless().getValue(), o.getSubject().getReference()); assertEquals("1", o.getIdElement().getVersionIdPart()); } @Test public void testTransactionUpdateTwoResourcesWithSameId() { Bundle request = new Bundle(); Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue("DDD"); p.setId("Patient/ABC"); request.addEntry() .setResource(p) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Patient/ABC"); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue("DDD"); p.setId("Patient/ABC"); request.addEntry() .setResource(p) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Patient/ABC"); try { mySystemDao.transaction(mySrd, request); fail(); } catch (InvalidRequestException e) { assertThat(e.getMessage(), containsString("Transaction bundle contains multiple resources with ID: Patient/ABC")); } } @Test public void testTransactionCreateInlineMatchUrlWithOneMatch2() { String methodName = "testTransactionCreateInlineMatchUrlWithOneMatch2"; Bundle request = new Bundle(); myDaoConfig.setAllowInlineMatchUrlReferences(true); Patient p = new Patient(); p.addName().addGiven("Heute"); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.setId("Patient/" + methodName); IIdType id = myPatientDao.update(p, mySrd).getId(); ourLog.info("Created patient, got it: {}", id); Observation o = new Observation(); o.getCode().setText("Some Observation"); o.getSubject().setReference("Patient/?given=heute"); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.POST); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(1, resp.getEntry().size()); BundleEntryComponent respEntry = resp.getEntry().get(0); assertEquals(Constants.STATUS_HTTP_201_CREATED + " Created", respEntry.getResponse().getStatus()); assertThat(respEntry.getResponse().getLocation(), containsString("Observation/")); assertThat(respEntry.getResponse().getLocation(), endsWith("/_history/1")); assertEquals("1", respEntry.getResponse().getEtag()); o = myObservationDao.read(new IdType(respEntry.getResponse().getLocationElement()), mySrd); assertEquals(id.toVersionless().getValue(), o.getSubject().getReference()); assertEquals("1", o.getIdElement().getVersionIdPart()); } @Test public void testTransactionCreateInlineMatchUrlWithOneMatchLastUpdated() { Bundle request = new Bundle(); Observation o = new Observation(); o.getCode().setText("Some Observation"); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.POST).setIfNoneExist("Observation?_lastUpdated=gt2011-01-01"); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(1, resp.getEntry().size()); BundleEntryComponent respEntry = resp.getEntry().get(0); assertEquals(Constants.STATUS_HTTP_201_CREATED + " Created", respEntry.getResponse().getStatus()); assertThat(respEntry.getResponse().getLocation(), containsString("Observation/")); assertThat(respEntry.getResponse().getLocation(), endsWith("/_history/1")); assertEquals("1", respEntry.getResponse().getEtag()); /* * Second time should not update */ request = new Bundle(); o = new Observation(); o.getCode().setText("Some Observation"); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.POST).setIfNoneExist("Observation?_lastUpdated=gt2011-01-01"); resp = mySystemDao.transaction(mySrd, request); assertEquals(1, resp.getEntry().size()); respEntry = resp.getEntry().get(0); assertEquals(Constants.STATUS_HTTP_200_OK + " OK", respEntry.getResponse().getStatus()); assertThat(respEntry.getResponse().getLocation(), containsString("Observation/")); assertThat(respEntry.getResponse().getLocation(), endsWith("/_history/1")); assertEquals("1", respEntry.getResponse().getEtag()); /* * Third time should not update */ request = new Bundle(); o = new Observation(); o.getCode().setText("Some Observation"); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.POST).setIfNoneExist("Observation?_lastUpdated=gt2011-01-01"); resp = mySystemDao.transaction(mySrd, request); assertEquals(1, resp.getEntry().size()); respEntry = resp.getEntry().get(0); assertEquals(Constants.STATUS_HTTP_200_OK + " OK", respEntry.getResponse().getStatus()); assertThat(respEntry.getResponse().getLocation(), containsString("Observation/")); assertThat(respEntry.getResponse().getLocation(), endsWith("/_history/1")); assertEquals("1", respEntry.getResponse().getEtag()); } @Test public void testTransactionWithDuplicateConditionalCreates() { Bundle request = new Bundle(); request.setType(BundleType.TRANSACTION); Practitioner p = new Practitioner(); p.setId(IdType.newRandomUuid()); p.addIdentifier().setSystem("http://foo").setValue("bar"); request.addEntry() .setFullUrl(p.getId()) .setResource(p) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Practitioner/") .setIfNoneExist("Practitioner?identifier=http://foo|bar"); Observation o = new Observation(); o.setId(IdType.newRandomUuid()); o.getPerformerFirstRep().setReference(p.getId()); request.addEntry() .setFullUrl(o.getId()) .setResource(o) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Observation/"); p = new Practitioner(); p.setId(IdType.newRandomUuid()); p.addIdentifier().setSystem("http://foo").setValue("bar"); request.addEntry() .setFullUrl(p.getId()) .setResource(p) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Practitioner/") .setIfNoneExist("Practitioner?identifier=http://foo|bar"); o = new Observation(); o.setId(IdType.newRandomUuid()); o.getPerformerFirstRep().setReference(p.getId()); request.addEntry() .setFullUrl(o.getId()) .setResource(o) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Observation/"); Bundle response = mySystemDao.transaction(null, request); ourLog.info("Response:\n{}", myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(response)); List<String> responseTypes = response .getEntry() .stream() .map(t -> new IdType(t.getResponse().getLocation()).getResourceType()) .collect(Collectors.toList()); assertThat(responseTypes.toString(), responseTypes, contains("Practitioner", "Observation", "Observation")); } @Test public void testTransactionWithDuplicateConditionalCreatesWithResourceLinkReference() { Bundle request = new Bundle(); request.setType(BundleType.TRANSACTION); Practitioner p = new Practitioner(); p.setId(IdType.newRandomUuid()); p.addIdentifier().setSystem("http://foo").setValue("bar"); request.addEntry() .setFullUrl(p.getId()) .setResource(p) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Practitioner/") .setIfNoneExist("Practitioner?identifier=http://foo|bar"); Observation o = new Observation(); o.setId(IdType.newRandomUuid()); o.getPerformerFirstRep().setResource(p); request.addEntry() .setFullUrl(o.getId()) .setResource(o) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Observation/"); p = new Practitioner(); p.setId(IdType.newRandomUuid()); p.addIdentifier().setSystem("http://foo").setValue("bar"); request.addEntry() .setFullUrl(p.getId()) .setResource(p) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Practitioner/") .setIfNoneExist("Practitioner?identifier=http://foo|bar"); o = new Observation(); o.setId(IdType.newRandomUuid()); o.getPerformerFirstRep().setResource(p); request.addEntry() .setFullUrl(o.getId()) .setResource(o) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Observation/"); Bundle response = mySystemDao.transaction(null, request); ourLog.info("Response:\n{}", myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(response)); List<String> responseTypes = response .getEntry() .stream() .map(t -> new IdType(t.getResponse().getLocation()).getResourceType()) .collect(Collectors.toList()); assertThat(responseTypes.toString(), responseTypes, contains("Practitioner", "Observation", "Observation")); } @Test public void testTransactionWithDuplicateConditionalUpdates() { Bundle request = new Bundle(); request.setType(BundleType.TRANSACTION); Practitioner p = new Practitioner(); p.setId(IdType.newRandomUuid()); p.addIdentifier().setSystem("http://foo").setValue("bar"); request.addEntry() .setFullUrl(p.getId()) .setResource(p) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Practitioner?identifier=http://foo|bar"); Observation o = new Observation(); o.setId(IdType.newRandomUuid()); o.getPerformerFirstRep().setReference(p.getId()); request.addEntry() .setFullUrl(o.getId()) .setResource(o) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Observation/"); p = new Practitioner(); p.setId(IdType.newRandomUuid()); p.addIdentifier().setSystem("http://foo").setValue("bar"); request.addEntry() .setFullUrl(p.getId()) .setResource(p) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Practitioner?identifier=http://foo|bar"); o = new Observation(); o.setId(IdType.newRandomUuid()); o.getPerformerFirstRep().setReference(p.getId()); request.addEntry() .setFullUrl(o.getId()) .setResource(o) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Observation/"); Bundle response = mySystemDao.transaction(null, request); ourLog.info("Response:\n{}", myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(response)); List<String> responseTypes = response .getEntry() .stream() .map(t -> new IdType(t.getResponse().getLocation()).getResourceType()) .collect(Collectors.toList()); assertThat(responseTypes.toString(), responseTypes, contains("Practitioner", "Observation", "Observation")); } @Test public void testTransactionCreateInlineMatchUrlWithTwoMatches() { String methodName = "testTransactionCreateInlineMatchUrlWithTwoMatches"; Bundle request = new Bundle(); myDaoConfig.setAllowInlineMatchUrlReferences(true); Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); myPatientDao.create(p, mySrd).getId(); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); myPatientDao.create(p, mySrd).getId(); Observation o = new Observation(); o.getCode().setText("Some Observation"); o.getSubject().setReference("Patient?identifier=urn%3Asystem%7C" + methodName); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.POST); try { mySystemDao.transaction(mySrd, request); fail(); } catch (PreconditionFailedException e) { assertEquals("Invalid match URL \"Patient?identifier=urn%3Asystem%7CtestTransactionCreateInlineMatchUrlWithTwoMatches\" - Multiple resources match this search", e.getMessage()); } } @Test public void testTransactionCreateMatchUrlWithOneMatch() { String methodName = "testTransactionCreateMatchUrlWithOneMatch"; Bundle request = new Bundle(); Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.setId("Patient/" + methodName); IIdType id = myPatientDao.update(p, mySrd).getId(); ourLog.info("Created patient, got it: {}", id); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.addName().setFamily("Hello"); p.setId("Patient/" + methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST).setIfNoneExist("Patient?identifier=urn%3Asystem%7C" + methodName); Observation o = new Observation(); o.getCode().setText("Some Observation"); o.getSubject().setReference("Patient/" + methodName); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.POST); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(2, resp.getEntry().size()); BundleEntryComponent respEntry = resp.getEntry().get(0); assertEquals(Constants.STATUS_HTTP_200_OK + " OK", respEntry.getResponse().getStatus()); assertThat(respEntry.getResponse().getLocation(), endsWith("Patient/" + id.getIdPart() + "/_history/1")); assertEquals("1", respEntry.getResponse().getEtag()); respEntry = resp.getEntry().get(1); assertEquals(Constants.STATUS_HTTP_201_CREATED + " Created", respEntry.getResponse().getStatus()); assertThat(respEntry.getResponse().getLocation(), containsString("Observation/")); assertThat(respEntry.getResponse().getLocation(), endsWith("/_history/1")); assertEquals("1", respEntry.getResponse().getEtag()); o = myObservationDao.read(new IdType(respEntry.getResponse().getLocationElement()), mySrd); assertEquals(id.toVersionless().getValue(), o.getSubject().getReference()); assertEquals("1", o.getIdElement().getVersionIdPart()); } @Test public void testTransactionCreateMatchUrlWithTwoMatch() { String methodName = "testTransactionCreateMatchUrlWithTwoMatch"; Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); IIdType id = myPatientDao.create(p, mySrd).getId(); ourLog.info("Created patient, got it: {}", id); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); id = myPatientDao.create(p, mySrd).getId(); ourLog.info("Created patient, got it: {}", id); Bundle request = new Bundle(); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.addName().setFamily("Hello"); p.setId("Patient/" + methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST).setIfNoneExist("Patient?identifier=urn%3Asystem%7C" + methodName); Observation o = new Observation(); o.getCode().setText("Some Observation"); o.getSubject().setReference("Patient/" + methodName); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.POST); try { mySystemDao.transaction(mySrd, request); fail(); } catch (PreconditionFailedException e) { assertThat(e.getMessage(), containsString("with match URL \"Patient")); } } @Test public void testTransactionCreateMatchUrlWithZeroMatch() { String methodName = "testTransactionCreateMatchUrlWithZeroMatch"; Bundle request = new Bundle(); Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.addName().setFamily("Hello"); p.setId("Patient/" + methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST).setIfNoneExist("Patient?identifier=urn%3Asystem%7C" + methodName); Observation o = new Observation(); o.getCode().setText("Some Observation"); o.getSubject().setReference("Patient/" + methodName); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.POST); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(BundleType.TRANSACTIONRESPONSE, resp.getTypeElement().getValue()); assertEquals(2, resp.getEntry().size()); BundleEntryComponent respEntry = resp.getEntry().get(0); assertEquals(Constants.STATUS_HTTP_201_CREATED + " Created", respEntry.getResponse().getStatus()); String patientId = respEntry.getResponse().getLocation(); assertThat(patientId, not(endsWith("Patient/" + methodName + "/_history/1"))); assertThat(patientId, (endsWith("/_history/1"))); assertThat(patientId, (containsString("Patient/"))); assertEquals("1", respEntry.getResponse().getEtag()); respEntry = resp.getEntry().get(1); assertEquals(Constants.STATUS_HTTP_201_CREATED + " Created", respEntry.getResponse().getStatus()); assertThat(respEntry.getResponse().getLocation(), containsString("Observation/")); assertThat(respEntry.getResponse().getLocation(), endsWith("/_history/1")); assertEquals("1", respEntry.getResponse().getEtag()); o = myObservationDao.read(new IdType(respEntry.getResponse().getLocationElement()), mySrd); assertEquals(new IdType(patientId).toUnqualifiedVersionless().getValue(), o.getSubject().getReference()); } @Test public void testTransactionCreateNoMatchUrl() { String methodName = "testTransactionCreateNoMatchUrl"; Bundle request = new Bundle(); Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.setId("Patient/" + methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST).setIfNoneExist("Patient?identifier=urn%3Asystem%7C" + methodName); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(1, resp.getEntry().size()); BundleEntryComponent respEntry = resp.getEntry().get(0); assertEquals(Constants.STATUS_HTTP_201_CREATED + " Created", respEntry.getResponse().getStatus()); String patientId = respEntry.getResponse().getLocation(); assertThat(patientId, not(containsString("test"))); } @Test public void testTransactionCreateWithBadRead() { Bundle request = new Bundle(); request.setType(BundleType.TRANSACTION); Patient p; p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue("FOO"); request .addEntry() .setResource(p) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Patient"); request .addEntry() .getRequest() .setMethod(HTTPVerb.GET) .setUrl("Patient/BABABABA"); Bundle response = mySystemDao.transaction(mySrd, request); assertEquals(2, response.getEntry().size()); assertEquals("201 Created", response.getEntry().get(0).getResponse().getStatus()); assertThat(response.getEntry().get(0).getResponse().getLocation(), matchesPattern(".*Patient/[0-9]+.*")); assertEquals("404 Not Found", response.getEntry().get(1).getResponse().getStatus()); OperationOutcome oo = (OperationOutcome) response.getEntry().get(1).getResponse().getOutcome(); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(oo)); assertEquals(IssueSeverity.ERROR, oo.getIssue().get(0).getSeverity()); assertEquals("Resource Patient/BABABABA is not known", oo.getIssue().get(0).getDiagnostics()); } @Test public void testTransactionCreateWithBadSearch() { Bundle request = new Bundle(); request.setType(BundleType.TRANSACTION); Patient p; p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue("FOO"); request .addEntry() .setResource(p) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Patient"); request .addEntry() .getRequest() .setMethod(HTTPVerb.GET) .setUrl("Patient?foobadparam=1"); Bundle response = mySystemDao.transaction(mySrd, request); assertEquals(2, response.getEntry().size()); assertEquals("201 Created", response.getEntry().get(0).getResponse().getStatus()); assertThat(response.getEntry().get(0).getResponse().getLocation(), matchesPattern(".*Patient/[0-9]+.*")); assertEquals("400 Bad Request", response.getEntry().get(1).getResponse().getStatus()); OperationOutcome oo = (OperationOutcome) response.getEntry().get(1).getResponse().getOutcome(); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(oo)); assertEquals(IssueSeverity.ERROR, oo.getIssue().get(0).getSeverity()); assertThat(oo.getIssue().get(0).getDiagnostics(), containsString("Unknown search parameter")); } @Test public void testTransactionCreateWithDuplicateMatchUrl01() { String methodName = "testTransactionCreateWithDuplicateMatchUrl01"; Bundle request = new Bundle(); Patient p; p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST).setIfNoneExist("Patient?identifier=urn%3Asystem%7C" + methodName); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST).setIfNoneExist("Patient?identifier=urn%3Asystem%7C" + methodName); mySystemDao.transaction(mySrd, request); assertEquals(1, logAllResources()); assertEquals(1, logAllResourceVersions()); } @Test public void testTransactionCreateWithDuplicateMatchUrl02() { String methodName = "testTransactionCreateWithDuplicateMatchUrl02"; Bundle request = new Bundle(); Patient p; p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST).setIfNoneExist("Patient?identifier=urn%3Asystem%7C" + methodName); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST); try { mySystemDao.transaction(mySrd, request); fail(); } catch (InvalidRequestException e) { assertEquals(e.getMessage(), "Unable to process Transaction - Request would cause multiple resources to match URL: \"Patient?identifier=urn%3Asystem%7CtestTransactionCreateWithDuplicateMatchUrl02\". Does transaction request contain duplicates?"); } } @Test public void testTransactionCreateWithInvalidMatchUrl() { String methodName = "testTransactionCreateWithInvalidMatchUrl"; Bundle request = new Bundle(); Patient p; p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); BundleEntryRequestComponent entry = request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST); try { entry.setIfNoneExist("Patient?identifier identifier" + methodName); mySystemDao.transaction(mySrd, request); fail(); } catch (InvalidRequestException e) { assertEquals("Failed to parse match URL[Patient?identifier identifiertestTransactionCreateWithInvalidMatchUrl] - URL is invalid (must not contain spaces)", e.getMessage()); } try { entry.setIfNoneExist("Patient?identifier="); mySystemDao.transaction(mySrd, request); fail(); } catch (InvalidRequestException e) { assertEquals("Invalid match URL[Patient?identifier=] - URL has no search parameters", e.getMessage()); } try { entry.setIfNoneExist("Patient?foo=bar"); mySystemDao.transaction(mySrd, request); fail(); } catch (InvalidRequestException e) { assertEquals("Failed to parse match URL[Patient?foo=bar] - Resource type Patient does not have a parameter with name: foo", e.getMessage()); } } @Test public void testTransactionCreateWithInvalidReferenceNumeric() { String methodName = "testTransactionCreateWithInvalidReferenceNumeric"; Bundle request = new Bundle(); Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.addName().setFamily("Hello"); p.getManagingOrganization().setReference("Organization/9999999999999999"); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST); try { mySystemDao.transaction(mySrd, request); fail(); } catch (InvalidRequestException e) { assertThat(e.getMessage(), containsString("Resource Organization/9999999999999999 not found, specified in path: Patient.managingOrganization")); } } @Test public void testTransactionCreateWithInvalidReferenceTextual() { String methodName = "testTransactionCreateWithInvalidReferenceTextual"; Bundle request = new Bundle(); Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.addName().setFamily("Hello"); p.getManagingOrganization().setReference("Organization/" + methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST); try { mySystemDao.transaction(mySrd, request); fail(); } catch (InvalidRequestException e) { assertThat(e.getMessage(), containsString("Resource Organization/" + methodName + " not found, specified in path: Patient.managingOrganization")); } } @Test public void testTransactionCreateWithLinks() { Bundle request = new Bundle(); request.setType(BundleType.TRANSACTION); Observation o = new Observation(); o.setId("A"); o.setStatus(ObservationStatus.AMENDED); request.addEntry() .setResource(o) .getRequest().setUrl("A").setMethod(HTTPVerb.PUT); try { mySystemDao.transaction(mySrd, request); fail(); } catch (InvalidRequestException e) { assertEquals("Invalid match URL[Observation?A] - URL has no search parameters", e.getMessage()); } } @Test public void testTransactionCreateWithPutUsingAbsoluteUrl() { String methodName = "testTransactionCreateWithPutUsingAbsoluteUrl"; Bundle request = new Bundle(); request.setType(BundleType.TRANSACTION); Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.PUT).setUrl("http://localhost/server/base/Patient/" + methodName); mySystemDao.transaction(mySrd, request); myPatientDao.read(new IdType("Patient/" + methodName), mySrd); } @Test public void testTransactionCreateWithPutUsingUrl() { String methodName = "testTransactionCreateWithPutUsingUrl"; Bundle request = new Bundle(); request.setType(BundleType.TRANSACTION); Observation o = new Observation(); o.getSubject().setReference("Patient/" + methodName); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.PUT).setUrl("Observation/a" + methodName); Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.PUT).setUrl("Patient/" + methodName); mySystemDao.transaction(mySrd, request); myObservationDao.read(new IdType("Observation/a" + methodName), mySrd); myPatientDao.read(new IdType("Patient/" + methodName), mySrd); } @Test public void testTransactionCreateWithPutUsingUrl2() throws Exception { String req = IOUtils.toString(FhirSystemDaoR4Test.class.getResourceAsStream("/r4/bundle.xml"), StandardCharsets.UTF_8); Bundle request = myFhirCtx.newXmlParser().parseResource(Bundle.class, req); mySystemDao.transaction(mySrd, request); } @Test public void testTransactionDeleteByResourceId() { String methodName = "testTransactionDeleteByResourceId"; Patient p1 = new Patient(); p1.addIdentifier().setSystem("urn:system").setValue(methodName); IIdType id1 = myPatientDao.create(p1, mySrd).getId(); ourLog.info("Created patient, got it: {}", id1); Patient p2 = new Patient(); p2.addIdentifier().setSystem("urn:system").setValue(methodName); p2.setId("Patient/" + methodName); IIdType id2 = myPatientDao.update(p2, mySrd).getId(); ourLog.info("Created patient, got it: {}", id2); Bundle request = new Bundle(); request.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl("Patient/" + id1.getIdPart()); request.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl("Patient/" + id2.getIdPart()); myPatientDao.read(id1.toVersionless(), mySrd); myPatientDao.read(id2.toVersionless(), mySrd); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(2, resp.getEntry().size()); assertEquals("204 No Content", resp.getEntry().get(0).getResponse().getStatus()); assertEquals("204 No Content", resp.getEntry().get(1).getResponse().getStatus()); try { myPatientDao.read(id1.toVersionless(), mySrd); fail(); } catch (ResourceGoneException e) { // good } try { myPatientDao.read(id2.toVersionless(), mySrd); fail(); } catch (ResourceGoneException e) { // good } } /** * See #253 Test that the order of deletes is version independent */ @Test public void testTransactionDeleteIsOrderIndependantTargetFirst() { String methodName = "testTransactionDeleteIsOrderIndependantTargetFirst"; Patient p1 = new Patient(); p1.addIdentifier().setSystem("urn:system").setValue(methodName); IIdType pid = myPatientDao.create(p1, mySrd).getId().toUnqualifiedVersionless(); ourLog.info("Created patient, got it: {}", pid); Observation o1 = new Observation(); o1.getSubject().setReferenceElement(pid); IIdType oid1 = myObservationDao.create(o1, mySrd).getId().toUnqualifiedVersionless(); Observation o2 = new Observation(); o2.addIdentifier().setValue(methodName); o2.getSubject().setReferenceElement(pid); IIdType oid2 = myObservationDao.create(o2, mySrd).getId().toUnqualifiedVersionless(); myPatientDao.read(pid, mySrd); myObservationDao.read(oid1, mySrd); // The target is Patient, so try with it first in the bundle Bundle request = new Bundle(); request.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl(pid.getValue()); request.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl(oid1.getValue()); request.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl("Observation?identifier=" + methodName); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(3, resp.getEntry().size()); assertEquals("204 No Content", resp.getEntry().get(0).getResponse().getStatus()); assertEquals("204 No Content", resp.getEntry().get(1).getResponse().getStatus()); assertEquals("204 No Content", resp.getEntry().get(2).getResponse().getStatus()); try { myPatientDao.read(pid, mySrd); fail(); } catch (ResourceGoneException e) { // good } try { myObservationDao.read(oid1, mySrd); fail(); } catch (ResourceGoneException e) { // good } try { myObservationDao.read(oid2, mySrd); fail(); } catch (ResourceGoneException e) { // good } } /** * See #253 Test that the order of deletes is version independent */ @Test public void testTransactionDeleteIsOrderIndependantTargetLast() { String methodName = "testTransactionDeleteIsOrderIndependantTargetFirst"; Patient p1 = new Patient(); p1.addIdentifier().setSystem("urn:system").setValue(methodName); IIdType pid = myPatientDao.create(p1, mySrd).getId().toUnqualifiedVersionless(); ourLog.info("Created patient, got it: {}", pid); Observation o1 = new Observation(); o1.getSubject().setReferenceElement(pid); IIdType oid1 = myObservationDao.create(o1, mySrd).getId().toUnqualifiedVersionless(); Observation o2 = new Observation(); o2.addIdentifier().setValue(methodName); o2.getSubject().setReferenceElement(pid); IIdType oid2 = myObservationDao.create(o2, mySrd).getId().toUnqualifiedVersionless(); myPatientDao.read(pid, mySrd); myObservationDao.read(oid1, mySrd); // The target is Patient, so try with it last in the bundle Bundle request = new Bundle(); request.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl(oid1.getValue()); request.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl("Observation?identifier=" + methodName); request.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl(pid.getValue()); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(3, resp.getEntry().size()); assertEquals("204 No Content", resp.getEntry().get(0).getResponse().getStatus()); assertEquals("204 No Content", resp.getEntry().get(1).getResponse().getStatus()); assertEquals("204 No Content", resp.getEntry().get(2).getResponse().getStatus()); try { myPatientDao.read(pid, mySrd); fail(); } catch (ResourceGoneException e) { // good } try { myObservationDao.read(oid1, mySrd); fail(); } catch (ResourceGoneException e) { // good } try { myObservationDao.read(oid2, mySrd); fail(); } catch (ResourceGoneException e) { // good } } @Test public void testTransactionDeleteMatchUrlWithOneMatch() { String methodName = "testTransactionDeleteMatchUrlWithOneMatch"; Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); IIdType id = myPatientDao.create(p, mySrd).getId(); ourLog.info("Created patient, got it: {}", id); Bundle request = new Bundle(); request.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl("Patient?identifier=urn%3Asystem%7C" + methodName); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(1, resp.getEntry().size()); BundleEntryComponent nextEntry = resp.getEntry().get(0); assertEquals(Constants.STATUS_HTTP_204_NO_CONTENT + " No Content", nextEntry.getResponse().getStatus()); try { myPatientDao.read(id.toVersionless(), mySrd); fail(); } catch (ResourceGoneException e) { } try { myPatientDao.read(new IdType("Patient/" + methodName), mySrd); fail(); } catch (ResourceNotFoundException e) { } IBundleProvider history = myPatientDao.history(id, null, null, null, mySrd); assertEquals(2, history.size().intValue()); assertNotNull(ResourceMetadataKeyEnum.DELETED_AT.get((IAnyResource) history.getResources(0, 1).get(0))); assertNotNull(ResourceMetadataKeyEnum.DELETED_AT.get((IAnyResource) history.getResources(0, 1).get(0)).getValue()); assertNull(ResourceMetadataKeyEnum.DELETED_AT.get((IAnyResource) history.getResources(1, 2).get(0))); } @Test public void testTransactionDeleteMatchUrlWithTwoMatch() { myDaoConfig.setAllowMultipleDelete(false); String methodName = "testTransactionDeleteMatchUrlWithTwoMatch"; Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); IIdType id = myPatientDao.create(p, mySrd).getId(); ourLog.info("Created patient, got it: {}", id); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); id = myPatientDao.create(p, mySrd).getId(); ourLog.info("Created patient, got it: {}", id); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.addName().setFamily("Hello"); p.setId("Patient/" + methodName); Bundle request = new Bundle(); request.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl("Patient?identifier=urn%3Asystem%7C" + methodName); try { mySystemDao.transaction(mySrd, request); fail(); } catch (PreconditionFailedException e) { assertThat(e.getMessage(), containsString("resource with match URL \"Patient?")); } } @Test public void testTransactionDeleteMatchUrlWithZeroMatch() { String methodName = "testTransactionDeleteMatchUrlWithZeroMatch"; Bundle request = new Bundle(); request.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl("Patient?identifier=urn%3Asystem%7C" + methodName); // try { Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(1, resp.getEntry().size()); assertEquals("204 No Content", resp.getEntry().get(0).getResponse().getStatus()); // fail(); // } catch (ResourceNotFoundException e) { // assertThat(e.getMessage(), containsString("resource matching URL \"Patient?")); } @Test public void testTransactionDeleteNoMatchUrl() { String methodName = "testTransactionDeleteNoMatchUrl"; Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.setId("Patient/" + methodName); IIdType id = myPatientDao.update(p, mySrd).getId(); ourLog.info("Created patient, got it: {}", id); Bundle request = new Bundle(); request.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl("Patient?identifier=urn%3Asystem%7C" + methodName); Bundle res = mySystemDao.transaction(mySrd, request); assertEquals(1, res.getEntry().size()); assertEquals(Constants.STATUS_HTTP_204_NO_CONTENT + " No Content", res.getEntry().get(0).getResponse().getStatus()); try { myPatientDao.read(id.toVersionless(), mySrd); fail(); } catch (ResourceGoneException e) { } } @Test public void testTransactionDoesNotLeavePlaceholderIds() { String input; try { input = IOUtils.toString(getClass().getResourceAsStream("/cdr-bundle.json"), StandardCharsets.UTF_8); } catch (IOException e) { fail(e.toString()); return; } Bundle bundle = myFhirCtx.newJsonParser().parseResource(Bundle.class, input); mySystemDao.transaction(mySrd, bundle); IBundleProvider history = mySystemDao.history(null, null, null, null); Bundle list = toBundleR4(history); ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(list)); assertEquals(6, list.getEntry().size()); Patient p = find(list, Patient.class, 0); assertTrue(p.getIdElement().isIdPartValidLong()); assertTrue(p.getGeneralPractitionerFirstRep().getReferenceElement().isIdPartValidLong()); } @Test public void testTransactionDoesntUpdateUnchangesResourceWithPlaceholderIds() { Bundle output, input; BundleEntryResponseComponent respEntry; IdType createdPatientId; SearchParameterMap map; IBundleProvider search; input = new Bundle(); /* * Create a transaction with a patient and an observation using * placeholder IDs in them */ Patient pat = new Patient(); pat.setId(IdType.newRandomUuid()); pat.addIdentifier().setSystem("foo").setValue("bar"); input .addEntry() .setResource(pat) .setFullUrl(pat.getId()) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("/Patient") .setIfNoneExist("Patient?identifier=foo|bar"); Observation obs = new Observation(); obs.addIdentifier().setSystem("foo").setValue("dog"); obs.getSubject().setReference(pat.getId()); input .addEntry() .setResource(obs) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("/Observation?identifier=foo|dog"); output = mySystemDao.transaction(mySrd, input); /* * Both resrouces should be created and have version 1 */ respEntry = output.getEntry().get(0).getResponse(); assertEquals("201 Created", respEntry.getStatus()); createdPatientId = new IdType(respEntry.getLocation()); assertEquals("Patient", createdPatientId.getResourceType()); assertEquals("1", createdPatientId.getVersionIdPart()); respEntry = output.getEntry().get(1).getResponse(); assertEquals("201 Created", respEntry.getStatus()); IdType createdObservationId = new IdType(respEntry.getLocation()); assertEquals("Observation", createdObservationId.getResourceType()); assertEquals("1", createdObservationId.getVersionIdPart()); /* * Searches for both resources should work and the reference * should be substituted correctly */ // Patient map = new SearchParameterMap(); map.setLoadSynchronous(true); map.add(Patient.SP_IDENTIFIER, new TokenParam("foo", "bar")); search = myPatientDao.search(map); assertThat(toUnqualifiedVersionlessIdValues(search), contains(createdPatientId.toUnqualifiedVersionless().getValue())); pat = (Patient) search.getResources(0, 1).get(0); assertEquals("foo", pat.getIdentifierFirstRep().getSystem()); // Observation map = new SearchParameterMap(); map.setLoadSynchronous(true); map.add(Observation.SP_IDENTIFIER, new TokenParam("foo", "dog")); search = myObservationDao.search(map); assertThat(toUnqualifiedVersionlessIdValues(search), contains(createdObservationId.toUnqualifiedVersionless().getValue())); obs = (Observation) search.getResources(0, 1).get(0); assertEquals("foo", obs.getIdentifierFirstRep().getSystem()); assertEquals(createdPatientId.toUnqualifiedVersionless().getValue(), obs.getSubject().getReference()); /* * Now run the same transaction, which should not make any changes this time * around */ input = new Bundle(); pat = new Patient(); pat.setId(IdType.newRandomUuid()); pat.addIdentifier().setSystem("foo").setValue("bar"); input .addEntry() .setResource(pat) .setFullUrl(pat.getId()) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("/Patient") .setIfNoneExist("Patient?identifier=foo|bar"); obs = new Observation(); obs.addIdentifier().setSystem("foo").setValue("dog"); obs.getSubject().setReference(pat.getId()); input .addEntry() .setResource(obs) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("/Observation?identifier=foo|dog"); output = mySystemDao.transaction(mySrd, input); /* * Should still have version 1 of both resources */ respEntry = output.getEntry().get(0).getResponse(); assertEquals("200 OK", respEntry.getStatus()); createdObservationId = new IdType(respEntry.getLocation()); assertEquals("Patient", createdObservationId.getResourceType()); assertEquals("1", createdObservationId.getVersionIdPart()); respEntry = output.getEntry().get(1).getResponse(); assertEquals("200 OK", respEntry.getStatus()); createdObservationId = new IdType(respEntry.getLocation()); assertEquals("Observation", createdObservationId.getResourceType()); assertEquals("1", createdObservationId.getVersionIdPart()); /* * Searches for both resources should still work and the reference * should be substituted correctly */ // Patient map = new SearchParameterMap(); map.setLoadSynchronous(true); map.add(Patient.SP_IDENTIFIER, new TokenParam("foo", "bar")); search = myPatientDao.search(map); assertThat(toUnqualifiedVersionlessIdValues(search), contains(createdPatientId.toUnqualifiedVersionless().getValue())); pat = (Patient) search.getResources(0, 1).get(0); assertEquals("foo", pat.getIdentifierFirstRep().getSystem()); // Observation map = new SearchParameterMap(); map.setLoadSynchronous(true); map.add(Observation.SP_IDENTIFIER, new TokenParam("foo", "dog")); search = myObservationDao.search(map); assertThat(toUnqualifiedVersionlessIdValues(search), contains(createdObservationId.toUnqualifiedVersionless().getValue())); obs = (Observation) search.getResources(0, 1).get(0); assertEquals("foo", obs.getIdentifierFirstRep().getSystem()); assertEquals(createdPatientId.toUnqualifiedVersionless().getValue(), obs.getSubject().getReference()); /* * Now run the transaction, but this time with an actual * change to the Observation */ input = new Bundle(); pat = new Patient(); pat.setId(IdType.newRandomUuid()); pat.addIdentifier().setSystem("foo").setValue("bar"); input .addEntry() .setResource(pat) .setFullUrl(pat.getId()) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("/Patient") .setIfNoneExist("Patient?identifier=foo|bar"); obs = new Observation(); obs.addIdentifier().setSystem("foo").setValue("dog"); obs.setStatus(ObservationStatus.FINAL); obs.getSubject().setReference(pat.getId()); input .addEntry() .setResource(obs) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("/Observation?identifier=foo|dog"); output = mySystemDao.transaction(mySrd, input); /* * Observation should now be version 2 */ respEntry = output.getEntry().get(0).getResponse(); assertEquals("200 OK", respEntry.getStatus()); createdObservationId = new IdType(respEntry.getLocation()); assertEquals("Patient", createdObservationId.getResourceType()); assertEquals("1", createdObservationId.getVersionIdPart()); respEntry = output.getEntry().get(1).getResponse(); assertEquals("200 OK", respEntry.getStatus()); createdObservationId = new IdType(respEntry.getLocation()); assertEquals("Observation", createdObservationId.getResourceType()); assertEquals("2", createdObservationId.getVersionIdPart()); /* * Searches for both resources should still work and the reference * should be substituted correctly */ // Patient map = new SearchParameterMap(); map.setLoadSynchronous(true); map.add(Patient.SP_IDENTIFIER, new TokenParam("foo", "bar")); search = myPatientDao.search(map); assertThat(toUnqualifiedVersionlessIdValues(search), contains(createdPatientId.toUnqualifiedVersionless().getValue())); pat = (Patient) search.getResources(0, 1).get(0); assertEquals("foo", pat.getIdentifierFirstRep().getSystem()); // Observation map = new SearchParameterMap(); map.setLoadSynchronous(true); map.add(Observation.SP_IDENTIFIER, new TokenParam("foo", "dog")); search = myObservationDao.search(map); assertThat(toUnqualifiedVersionlessIdValues(search), contains(createdObservationId.toUnqualifiedVersionless().getValue())); obs = (Observation) search.getResources(0, 1).get(0); assertEquals("foo", obs.getIdentifierFirstRep().getSystem()); assertEquals(createdPatientId.toUnqualifiedVersionless().getValue(), obs.getSubject().getReference()); assertEquals(ObservationStatus.FINAL, obs.getStatus()); } @Test public void testTransactionDoubleConditionalCreateOnlyCreatesOne() { Bundle inputBundle = new Bundle(); inputBundle.setType(Bundle.BundleType.TRANSACTION); Encounter enc1 = new Encounter(); enc1.addIdentifier().setSystem("urn:foo").setValue("12345"); inputBundle .addEntry() .setResource(enc1) .getRequest() .setMethod(HTTPVerb.POST) .setIfNoneExist("Encounter?identifier=urn:foo|12345"); Encounter enc2 = new Encounter(); enc2.addIdentifier().setSystem("urn:foo").setValue("12345"); inputBundle .addEntry() .setResource(enc2) .getRequest() .setMethod(HTTPVerb.POST) .setIfNoneExist("Encounter?identifier=urn:foo|12345"); mySystemDao.transaction(mySrd, inputBundle); assertEquals(1, logAllResources()); assertEquals(1, logAllResourceVersions()); } @Test public void testTransactionDoubleConditionalUpdateOnlyCreatesOne() { Bundle inputBundle = new Bundle(); inputBundle.setType(Bundle.BundleType.TRANSACTION); Encounter enc1 = new Encounter(); enc1.addIdentifier().setSystem("urn:foo").setValue("12345"); inputBundle .addEntry() .setResource(enc1) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Encounter?identifier=urn:foo|12345"); Encounter enc2 = new Encounter(); enc2.addIdentifier().setSystem("urn:foo").setValue("12345"); inputBundle .addEntry() .setResource(enc2) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Encounter?identifier=urn:foo|12345"); mySystemDao.transaction(mySrd, inputBundle); assertEquals(1, logAllResources()); assertEquals(1, logAllResourceVersions()); } @Test public void testTransactionFailsWithDuplicateIds() { Bundle request = new Bundle(); Patient patient1 = new Patient(); patient1.setId(new IdType("Patient/testTransactionFailsWithDusplicateIds")); patient1.addIdentifier().setSystem("urn:system").setValue("testPersistWithSimpleLinkP01"); request.addEntry().setResource(patient1).getRequest().setMethod(HTTPVerb.POST); Patient patient2 = new Patient(); patient2.setId(new IdType("Patient/testTransactionFailsWithDusplicateIds")); patient2.addIdentifier().setSystem("urn:system").setValue("testPersistWithSimpleLinkP02"); request.addEntry().setResource(patient2).getRequest().setMethod(HTTPVerb.POST); assertThrows(InvalidRequestException.class, () -> { mySystemDao.transaction(mySrd, request); }); } @Test public void testTransactionFromBundle() throws Exception { InputStream bundleRes = SystemProviderDstu2Test.class.getResourceAsStream("/transaction_link_patient_eve.xml"); String bundleStr = IOUtils.toString(bundleRes, StandardCharsets.UTF_8); Bundle bundle = myFhirCtx.newXmlParser().parseResource(Bundle.class, bundleStr); Bundle resp = mySystemDao.transaction(mySrd, bundle); ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(resp)); assertThat(resp.getEntry().get(0).getResponse().getLocation(), startsWith("Patient/a555-44-4444/_history/")); assertThat(resp.getEntry().get(1).getResponse().getLocation(), startsWith("Patient/temp6789/_history/")); assertThat(resp.getEntry().get(2).getResponse().getLocation(), startsWith("Organization/GHH/_history/")); Patient p = myPatientDao.read(new IdType("Patient/a555-44-4444/_history/1"), mySrd); assertEquals("Patient/temp6789", p.getLink().get(0).getOther().getReference()); } @Test public void testTransactionFromBundle2() throws Exception { String input = IOUtils.toString(getClass().getResourceAsStream("/transaction-bundle.xml"), StandardCharsets.UTF_8); Bundle bundle = myFhirCtx.newXmlParser().parseResource(Bundle.class, input); Bundle response = mySystemDao.transaction(mySrd, bundle); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(response)); assertEquals("201 Created", response.getEntry().get(0).getResponse().getStatus()); assertThat(response.getEntry().get(0).getResponse().getLocation(), matchesPattern("Practitioner/[0-9]+/_history/1")); /* * Now a second time */ bundle = myFhirCtx.newXmlParser().parseResource(Bundle.class, input); response = mySystemDao.transaction(mySrd, bundle); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(response)); assertEquals("200 OK", response.getEntry().get(0).getResponse().getStatus()); assertThat(response.getEntry().get(0).getResponse().getLocation(), matchesPattern("Practitioner/[0-9]+/_history/1")); } @Test public void testTransactionFromBundle6() throws Exception { InputStream bundleRes = SystemProviderDstu2Test.class.getResourceAsStream("/simone_bundle3.xml"); String bundle = IOUtils.toString(bundleRes, StandardCharsets.UTF_8); Bundle output = mySystemDao.transaction(mySrd, myFhirCtx.newXmlParser().parseResource(Bundle.class, bundle)); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(output)); } @Test public void testTransactionFromBundleJosh() throws Exception { InputStream bundleRes = SystemProviderDstu2Test.class.getResourceAsStream("/josh-bundle.json"); String bundleStr = IOUtils.toString(bundleRes, StandardCharsets.UTF_8); Bundle bundle = myFhirCtx.newJsonParser().parseResource(Bundle.class, bundleStr); Bundle resp = mySystemDao.transaction(mySrd, bundle); ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(resp)); assertEquals("201 Created", resp.getEntry().get(0).getResponse().getStatus()); assertEquals("201 Created", resp.getEntry().get(1).getResponse().getStatus()); } @Test public void testTransactionOrdering() { String methodName = "testTransactionOrdering"; //@formatter:off /* * Transaction Order, per the spec: * * Process any DELETE interactions * Process any POST interactions * Process any PUT interactions * Process any GET interactions * * This test creates a transaction bundle that includes * these four operations in the reverse order and verifies * that they are invoked correctly. */ //@formatter:off int pass = 0; IdType patientPlaceholderId = IdType.newRandomUuid(); Bundle req = testTransactionOrderingCreateBundle(methodName, pass, patientPlaceholderId); Bundle resp = mySystemDao.transaction(mySrd, req); testTransactionOrderingValidateResponse(pass, resp); pass = 1; patientPlaceholderId = IdType.newRandomUuid(); req = testTransactionOrderingCreateBundle(methodName, pass, patientPlaceholderId); resp = mySystemDao.transaction(mySrd, req); testTransactionOrderingValidateResponse(pass, resp); } private Bundle testTransactionOrderingCreateBundle(String methodName, int pass, IdType patientPlaceholderId) { Bundle req = new Bundle(); req.addEntry().getRequest().setMethod(HTTPVerb.GET).setUrl("Patient?identifier=" + methodName); Observation obs = new Observation(); obs.getSubject().setReferenceElement(patientPlaceholderId); obs.addIdentifier().setValue(methodName); obs.getCode().setText(methodName + pass); req.addEntry().setResource(obs).getRequest().setMethod(HTTPVerb.PUT).setUrl("Observation?identifier=" + methodName); Patient pat = new Patient(); pat.addIdentifier().setValue(methodName); pat.addName().setFamily(methodName + pass); req.addEntry().setResource(pat).setFullUrl(patientPlaceholderId.getValue()).getRequest().setMethod(HTTPVerb.POST).setUrl("Patient"); req.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl("Patient?identifier=" + methodName); return req; } private void testTransactionOrderingValidateResponse(int pass, Bundle resp) { ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); assertEquals(4, resp.getEntry().size()); assertEquals("200 OK", resp.getEntry().get(0).getResponse().getStatus()); if (pass == 0) { assertEquals("201 Created", resp.getEntry().get(1).getResponse().getStatus()); assertThat(resp.getEntry().get(1).getResponse().getLocation(), startsWith("Observation/")); assertThat(resp.getEntry().get(1).getResponse().getLocation(), endsWith("_history/1")); } else { assertEquals("200 OK", resp.getEntry().get(1).getResponse().getStatus()); assertThat(resp.getEntry().get(1).getResponse().getLocation(), startsWith("Observation/")); assertThat(resp.getEntry().get(1).getResponse().getLocation(), endsWith("_history/2")); } assertEquals("201 Created", resp.getEntry().get(2).getResponse().getStatus()); assertThat(resp.getEntry().get(2).getResponse().getLocation(), startsWith("Patient/")); if (pass == 0) { assertEquals("204 No Content", resp.getEntry().get(3).getResponse().getStatus()); } else { assertEquals("204 No Content", resp.getEntry().get(3).getResponse().getStatus()); } Bundle respGetBundle = (Bundle) resp.getEntry().get(0).getResource(); assertEquals(1, respGetBundle.getEntry().size()); assertEquals("testTransactionOrdering" + pass, ((Patient) respGetBundle.getEntry().get(0).getResource()).getName().get(0).getFamily()); assertThat(respGetBundle.getLink("self").getUrl(), endsWith("/Patient?identifier=testTransactionOrdering")); } @Test public void testTransactionOruBundle() throws IOException { myDaoConfig.setAllowMultipleDelete(true); String input = IOUtils.toString(getClass().getResourceAsStream("/r4/oruBundle.json"), StandardCharsets.UTF_8); Bundle inputBundle; Bundle outputBundle; inputBundle = myFhirCtx.newJsonParser().parseResource(Bundle.class, input); outputBundle = mySystemDao.transaction(mySrd, inputBundle); ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(outputBundle)); inputBundle = myFhirCtx.newJsonParser().parseResource(Bundle.class, input); outputBundle = mySystemDao.transaction(mySrd, inputBundle); ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(outputBundle)); IBundleProvider allPatients = myPatientDao.search(new SearchParameterMap()); assertEquals(1, allPatients.size().intValue()); } @Test public void testTransactionReadAndSearch() { String methodName = "testTransactionReadAndSearch"; Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.setId("Patient/" + methodName); IIdType idv1 = myPatientDao.update(p, mySrd).getId(); ourLog.info("Created patient, got id: {}", idv1); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.addName().setFamily("Family Name"); p.setId("Patient/" + methodName); IIdType idv2 = myPatientDao.update(p, mySrd).getId(); ourLog.info("Updated patient, got id: {}", idv2); Bundle request = new Bundle(); request.addEntry().getRequest().setMethod(HTTPVerb.GET).setUrl(idv1.toUnqualifiedVersionless().getValue()); request.addEntry().getRequest().setMethod(HTTPVerb.GET).setUrl(idv1.toUnqualified().getValue()); request.addEntry().getRequest().setMethod(HTTPVerb.GET).setUrl("Patient?identifier=urn%3Asystem%7C" + methodName); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(3, resp.getEntry().size()); BundleEntryComponent nextEntry; nextEntry = resp.getEntry().get(0); assertEquals(Patient.class, nextEntry.getResource().getClass()); assertEquals(idv2.toUnqualified(), nextEntry.getResource().getIdElement().toUnqualified()); nextEntry = resp.getEntry().get(1); assertEquals(Patient.class, nextEntry.getResource().getClass()); assertEquals(idv1.toUnqualified(), nextEntry.getResource().getIdElement().toUnqualified()); nextEntry = resp.getEntry().get(2); assertEquals(Bundle.class, nextEntry.getResource().getClass()); Bundle respBundle = (Bundle) nextEntry.getResource(); assertEquals(1, respBundle.getTotal()); } @Test public void testTransactionReadWithIfNoneMatch() { String methodName = "testTransactionReadWithIfNoneMatch"; Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.setId("Patient/" + methodName); IIdType idv1 = myPatientDao.update(p, mySrd).getId(); ourLog.info("Created patient, got id: {}", idv1); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.addName().setFamily("Family Name"); p.setId("Patient/" + methodName); IIdType idv2 = myPatientDao.update(p, mySrd).getId(); ourLog.info("Updated patient, got id: {}", idv2); Bundle request = new Bundle(); request.addEntry().getRequest().setMethod(HTTPVerb.GET).setUrl(idv1.toUnqualifiedVersionless().getValue()); request.addEntry().getRequest().setMethod(HTTPVerb.GET).setUrl(idv1.toUnqualifiedVersionless().getValue()).setIfNoneMatch("W/\"" + idv1.getVersionIdPart() + "\""); request.addEntry().getRequest().setMethod(HTTPVerb.GET).setUrl(idv1.toUnqualifiedVersionless().getValue()).setIfNoneMatch("W/\"" + idv2.getVersionIdPart() + "\""); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(3, resp.getEntry().size()); BundleEntryComponent nextEntry; nextEntry = resp.getEntry().get(0); assertNotNull(nextEntry.getResource()); assertEquals(Patient.class, nextEntry.getResource().getClass()); assertEquals(idv2.toUnqualified(), nextEntry.getResource().getIdElement().toUnqualified()); assertEquals("200 OK", nextEntry.getResponse().getStatus()); nextEntry = resp.getEntry().get(1); assertNotNull(nextEntry.getResource()); assertEquals(Patient.class, nextEntry.getResource().getClass()); assertEquals(idv2.toUnqualified(), nextEntry.getResource().getIdElement().toUnqualified()); assertEquals("200 OK", nextEntry.getResponse().getStatus()); nextEntry = resp.getEntry().get(2); assertEquals("304 Not Modified", nextEntry.getResponse().getStatus()); assertNull(nextEntry.getResource()); } @Test public void testTransactionWithRefsToConditionalCreate() { Bundle b = createTransactionBundleForTestTransactionWithRefsToConditionalCreate(); mySystemDao.transaction(mySrd, b); IBundleProvider history = myObservationDao.search(new SearchParameterMap().setLoadSynchronous(true)); Bundle list = toBundleR4(history); assertEquals(1, list.getEntry().size()); Observation o = find(list, Observation.class, 0); assertThat(o.getSubject().getReference(), matchesPattern("Patient/[0-9]+")); b = createTransactionBundleForTestTransactionWithRefsToConditionalCreate(); mySystemDao.transaction(mySrd, b); history = myObservationDao.search(new SearchParameterMap().setLoadSynchronous(true)); list = toBundleR4(history); assertEquals(1, list.getEntry().size()); o = find(list, Observation.class, 0); assertThat(o.getSubject().getReference(), matchesPattern("Patient/[0-9]+")); } /** * DAOs can't handle references where <code>Reference.setResource</code> * is set but not <code>Reference.setReference</code> so make sure * we block this so it doesn't get used accidentally. */ @Test @Disabled public void testTransactionWithResourceReferenceInsteadOfIdReferenceBlocked() { Bundle input = createBundleWithConditionalCreateReferenceByResource(); mySystemDao.transaction(mySrd, input); // Fails the second time try { input = createBundleWithConditionalCreateReferenceByResource(); mySystemDao.transaction(mySrd, input); fail(); } catch (InternalErrorException e) { assertEquals("References by resource with no reference ID are not supported in DAO layer", e.getMessage()); } } @Test public void testTransactionWithContainedResource() { Organization organization = new Organization(); organization.setName("ORG NAME"); Patient patient = new Patient(); patient.getManagingOrganization().setResource(organization); BundleBuilder bundleBuilder = new BundleBuilder(myFhirCtx); bundleBuilder.addTransactionCreateEntry(patient); Bundle outcome = mySystemDao.transaction(null, (Bundle) bundleBuilder.getBundle()); String id = outcome.getEntry().get(0).getResponse().getLocation(); patient = myPatientDao.read(new IdType(id)); assertEquals("#1", patient.getManagingOrganization().getReference()); assertEquals("#1", patient.getContained().get(0).getId()); } @Nonnull private Bundle createBundleWithConditionalCreateReferenceByResource() { Bundle input = new Bundle(); input.setType(BundleType.TRANSACTION); Patient p = new Patient(); p.setId(IdType.newRandomUuid()); p.addIdentifier().setSystem("foo").setValue("bar"); input.addEntry() .setFullUrl(p.getId()) .setResource(p) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Patient") .setIfNoneExist("Patient?identifier=foo|bar"); Observation o1 = new Observation(); o1.setId(IdType.newRandomUuid()); o1.setStatus(ObservationStatus.FINAL); o1.getSubject().setResource(p); // Not allowed input.addEntry() .setFullUrl(o1.getId()) .setResource(o1) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Observation"); return input; } @Test public void testDeleteInTransactionShouldFailWhenReferencesExist() { final Observation obs1 = new Observation(); obs1.setStatus(ObservationStatus.FINAL); IIdType obs1id = myObservationDao.create(obs1).getId().toUnqualifiedVersionless(); final Observation obs2 = new Observation(); obs2.setStatus(ObservationStatus.FINAL); IIdType obs2id = myObservationDao.create(obs2).getId().toUnqualifiedVersionless(); final DiagnosticReport rpt = new DiagnosticReport(); rpt.addResult(new Reference(obs2id)); IIdType rptId = myDiagnosticReportDao.create(rpt).getId().toUnqualifiedVersionless(); myObservationDao.read(obs1id); myObservationDao.read(obs2id); myDiagnosticReportDao.read(rptId); Bundle b = new Bundle(); b.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl(obs2id.getValue()); try { mySystemDao.transaction(mySrd, b); fail(); } catch (ResourceVersionConflictException e) { // good, transaction should not succeed because DiagnosticReport has a reference to the obs2 } } @Test public void testDeleteInTransactionShouldSucceedWhenReferencesAreAlsoRemoved() { final Observation obs1 = new Observation(); obs1.setStatus(ObservationStatus.FINAL); IIdType obs1id = myObservationDao.create(obs1).getId().toUnqualifiedVersionless(); final Observation obs2 = new Observation(); obs2.setStatus(ObservationStatus.FINAL); IIdType obs2id = myObservationDao.create(obs2).getId().toUnqualifiedVersionless(); final DiagnosticReport rpt = new DiagnosticReport(); rpt.addResult(new Reference(obs2id)); IIdType rptId = myDiagnosticReportDao.create(rpt).getId().toUnqualifiedVersionless(); myObservationDao.read(obs1id); myObservationDao.read(obs2id); myDiagnosticReportDao.read(rptId); Bundle b = new Bundle(); b.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl(obs2id.getValue()); b.addEntry().getRequest().setMethod(HTTPVerb.DELETE).setUrl(rptId.getValue()); try { // transaction should succeed because the DiagnosticReport which references obs2 is also deleted mySystemDao.transaction(mySrd, b); } catch (ResourceVersionConflictException e) { fail(); } } private Bundle createTransactionBundleForTestTransactionWithRefsToConditionalCreate() { Bundle b = new Bundle(); b.setType(BundleType.TRANSACTION); Patient p = new Patient(); p.setId(IdType.newRandomUuid()); p.addIdentifier().setSystem("foo").setValue("bar"); b.addEntry() .setFullUrl(p.getId()) .setResource(p) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Patient") .setIfNoneExist("Patient?identifier=foo|bar"); b.addEntry() .getRequest() .setMethod(HTTPVerb.DELETE) .setUrl("Observation?status=final"); Observation o = new Observation(); o.setId(IdType.newRandomUuid()); o.setStatus(ObservationStatus.FINAL); o.getSubject().setReference(p.getId()); b.addEntry() .setFullUrl(o.getId()) .setResource(o) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Observation"); return b; } @Test public void testTransactionWithUnknownTemnporaryIdReference() { String methodName = "testTransactionWithUnknownTemnporaryIdReference"; Bundle request = new Bundle(); Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST).setUrl("Patient"); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.getManagingOrganization().setReference(IdType.newRandomUuid().getValue()); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST).setUrl("Patient"); try { mySystemDao.transaction(mySrd, request); fail(); } catch (InvalidRequestException e) { assertThat(e.getMessage(), Matchers.matchesPattern("Unable to satisfy placeholder ID urn:uuid:[0-9a-z-]+ found in element named 'managingOrganization' within resource of type: Patient")); } } @Test public void testTransactionSearchWithCount() { String methodName = "testTransactionSearchWithCount"; Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.setId("Patient/" + methodName); IIdType idv1 = myPatientDao.update(p, mySrd).getId(); ourLog.info("Created patient, got id: {}", idv1); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.addName().setFamily("Family Name"); p.setId("Patient/" + methodName); IIdType idv2 = myPatientDao.update(p, mySrd).getId(); ourLog.info("Updated patient, got id: {}", idv2); Bundle request = new Bundle(); request.addEntry().getRequest().setMethod(HTTPVerb.GET).setUrl("Patient?" + Constants.PARAM_COUNT + "=1&_total=accurate"); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(1, resp.getEntry().size()); BundleEntryComponent nextEntry = resp.getEntry().get(0); assertEquals(Bundle.class, nextEntry.getResource().getClass()); Bundle respBundle = (Bundle) nextEntry.getResource(); assertThat(respBundle.getTotal(), greaterThan(0)); // Invalid _count request = new Bundle(); request.addEntry().getRequest().setMethod(HTTPVerb.GET).setUrl("Patient?" + Constants.PARAM_COUNT + "=GKJGKJG"); try { mySystemDao.transaction(mySrd, request); } catch (InvalidRequestException e) { assertEquals(e.getMessage(), ("Invalid _count value: GKJGKJG")); } // Empty _count request = new Bundle(); request.addEntry().getRequest().setMethod(HTTPVerb.GET).setUrl("Patient?" + Constants.PARAM_COUNT + "="); respBundle = mySystemDao.transaction(mySrd, request); assertThat(respBundle.getEntry().size(), greaterThan(0)); } @Test public void testTransactionSingleEmptyResource() { Bundle request = new Bundle(); request.setType(BundleType.SEARCHSET); Patient p = new Patient(); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST); try { mySystemDao.transaction(mySrd, request); fail(); } catch (InvalidRequestException e) { assertEquals("Unable to process transaction where incoming Bundle.type = searchset", e.getMessage()); } } @Test public void testTransactionUpdateMatchUrlWithOneMatch() { String methodName = "testTransactionUpdateMatchUrlWithOneMatch"; Bundle request = new Bundle(); Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); IIdType id = myPatientDao.create(p, mySrd).getId(); ourLog.info("Created patient, got it: {}", id); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.addName().setFamily("Hello"); p.setId("Patient/" + methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.PUT).setUrl("Patient?identifier=urn%3Asystem%7C" + methodName); Observation o = new Observation(); o.getCode().setText("Some Observation"); o.getSubject().setReference("Patient/" + methodName); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.POST); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(2, resp.getEntry().size()); BundleEntryComponent nextEntry = resp.getEntry().get(0); assertEquals("200 OK", nextEntry.getResponse().getStatus()); assertThat(nextEntry.getResponse().getLocation(), not(containsString("test"))); assertEquals(id.toVersionless(), p.getIdElement().toVersionless()); assertNotEquals(id, p.getId()); assertThat(p.getId(), endsWith("/_history/2")); nextEntry = resp.getEntry().get(0); assertEquals(Constants.STATUS_HTTP_200_OK + " OK", nextEntry.getResponse().getStatus()); assertThat(nextEntry.getResponse().getLocation(), not(emptyString())); nextEntry = resp.getEntry().get(1); o = myObservationDao.read(new IdType(nextEntry.getResponse().getLocation()), mySrd); assertEquals(id.toVersionless().getValue(), o.getSubject().getReference()); } @Test public void testTransactionUpdateMatchUrlWithTwoMatch() { String methodName = "testTransactionUpdateMatchUrlWithTwoMatch"; Bundle request = new Bundle(); Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); IIdType id = myPatientDao.create(p, mySrd).getId(); ourLog.info("Created patient, got it: {}", id); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); id = myPatientDao.create(p, mySrd).getId(); ourLog.info("Created patient, got it: {}", id); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.addName().setFamily("Hello"); p.setId("Patient/" + methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.PUT).setUrl("Patient?identifier=urn%3Asystem%7C" + methodName); Observation o = new Observation(); o.getCode().setText("Some Observation"); o.getSubject().setReference("Patient/" + methodName); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.POST); try { mySystemDao.transaction(mySrd, request); fail(); } catch (PreconditionFailedException e) { assertThat(e.getMessage(), containsString("with match URL \"Patient")); } } @Test public void testTransactionUpdateMatchUrlWithZeroMatch() { String methodName = "testTransactionUpdateMatchUrlWithZeroMatch"; Bundle request = new Bundle(); Patient p = new Patient(); p.addName().setFamily("Hello"); IIdType id = myPatientDao.create(p, mySrd).getId(); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.addName().setFamily("Hello"); p.setId(methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.PUT).setUrl("Patient?identifier=urn%3Asystem%7C" + methodName); Observation o = new Observation(); o.getCode().setText("Some Observation"); o.getSubject().setReference("Patient/" + methodName); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.POST); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(2, resp.getEntry().size()); BundleEntryComponent nextEntry = resp.getEntry().get(0); assertEquals(Constants.STATUS_HTTP_201_CREATED + " Created", nextEntry.getResponse().getStatus()); IdType patientId = new IdType(nextEntry.getResponse().getLocation()); assertThat(nextEntry.getResponse().getLocation(), not(containsString("test"))); assertNotEquals(id.toVersionless(), patientId.toVersionless()); assertThat(patientId.getValue(), endsWith("/_history/1")); nextEntry = resp.getEntry().get(1); o = myObservationDao.read(new IdType(nextEntry.getResponse().getLocation()), mySrd); assertEquals(patientId.toVersionless().getValue(), o.getSubject().getReference()); } @Test public void testTransactionUpdateNoMatchUrl() { String methodName = "testTransactionUpdateNoMatchUrl"; Bundle request = new Bundle(); Patient p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.setId("Patient/" + methodName); IIdType id = myPatientDao.update(p, mySrd).getId(); ourLog.info("Created patient, got it: {}", id); p = new Patient(); p.addIdentifier().setSystem("urn:system").setValue(methodName); p.addName().setFamily("Hello"); p.setId("Patient/" + methodName); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.PUT).setUrl("Patient/" + id.getIdPart()); Observation o = new Observation(); o.getCode().setText("Some Observation"); o.getSubject().setReference("Patient/" + methodName); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.POST); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(2, resp.getEntry().size()); BundleEntryComponent nextEntry = resp.getEntry().get(0); assertEquals("200 OK", nextEntry.getResponse().getStatus()); assertThat(nextEntry.getResponse().getLocation(), (containsString("test"))); assertEquals(id.toVersionless(), new IdType(nextEntry.getResponse().getLocation()).toVersionless()); assertThat(nextEntry.getResponse().getLocation(), endsWith("/_history/2")); assertNotEquals(id, new IdType(nextEntry.getResponse().getLocation())); nextEntry = resp.getEntry().get(1); assertEquals(Constants.STATUS_HTTP_201_CREATED + " Created", nextEntry.getResponse().getStatus()); o = myObservationDao.read(new IdType(resp.getEntry().get(1).getResponse().getLocation()), mySrd); assertEquals(id.toVersionless().getValue(), o.getSubject().getReference()); } @Test public void testTransactionWIthInvalidPlaceholder() { Bundle res = new Bundle(); res.setType(BundleType.TRANSACTION); Observation o1 = new Observation(); o1.setId("cid:observation1"); o1.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds02"); res.addEntry().setResource(o1).getRequest().setMethod(HTTPVerb.POST).setUrl("Observation"); try { mySystemDao.transaction(mySrd, res); fail(); } catch (InvalidRequestException e) { assertEquals("Invalid placeholder ID found: cid:observation1 - Must be of the form 'urn:uuid:[uuid]' or 'urn:oid:[oid]'", e.getMessage()); } } @Test public void testTransactionWhichFailsPersistsNothing() { // Run a transaction which points to that practitioner // in a field that isn't allowed to refer to a practitioner Bundle input = new Bundle(); input.setType(BundleType.TRANSACTION); Patient pt = new Patient(); pt.setId("PT"); pt.setActive(true); pt.addName().setFamily("FAMILY"); input.addEntry() .setResource(pt) .getRequest().setMethod(HTTPVerb.PUT).setUrl("Patient/PT"); Observation obs = new Observation(); obs.setId("OBS"); obs.getCode().addCoding().setSystem("foo").setCode("bar"); obs.addPerformer().setReference("Practicioner/AAAAA"); input.addEntry() .setResource(obs) .getRequest().setMethod(HTTPVerb.PUT).setUrl("Observation/OBS"); try { mySystemDao.transaction(mySrd, input); fail(); } catch (UnprocessableEntityException e) { assertThat(e.getMessage(), containsString("Resource type 'Practicioner' is not valid for this path")); } assertThat(myResourceTableDao.findAll(), empty()); assertThat(myResourceIndexedSearchParamStringDao.findAll(), empty()); } /** * Format changed, source isn't valid */ @Test @Disabled public void testTransactionWithBundledValidationSourceAndTarget() throws Exception { InputStream bundleRes = SystemProviderDstu2Test.class.getResourceAsStream("/questionnaire-sdc-profile-example-ussg-fht.xml"); String bundleStr = IOUtils.toString(bundleRes, StandardCharsets.UTF_8); Bundle bundle = myFhirCtx.newXmlParser().parseResource(Bundle.class, bundleStr); Bundle resp = mySystemDao.transaction(mySrd, bundle); String encoded = myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(resp); ourLog.info(encoded); encoded = myFhirCtx.newJsonParser().setPrettyPrint(false).encodeResourceToString(resp); //@formatter:off assertThat(encoded, containsString("\"response\":{" + "\"status\":\"201 Created\"," + "\"location\":\"Questionnaire/54127-6/_history/1\",")); //@formatter:on /* * Upload again to update */ resp = mySystemDao.transaction(mySrd, bundle); encoded = myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(resp); ourLog.info(encoded); encoded = myFhirCtx.newJsonParser().setPrettyPrint(false).encodeResourceToString(resp); //@formatter:off assertThat(encoded, containsString("\"response\":{" + "\"status\":\"200 OK\"," + "\"location\":\"Questionnaire/54127-6/_history/2\",")); //@formatter:on } @Test public void testTransactionWithCircularReferences() { Bundle request = new Bundle(); request.setType(BundleType.TRANSACTION); Encounter enc = new Encounter(); enc.addIdentifier().setSystem("A").setValue("1"); enc.setId(IdType.newRandomUuid()); Condition cond = new Condition(); cond.addIdentifier().setSystem("A").setValue("2"); cond.setId(IdType.newRandomUuid()); enc.addDiagnosis().getCondition().setReference(cond.getId()); cond.getEncounter().setReference(enc.getId()); request .addEntry() .setFullUrl(enc.getId()) .setResource(enc) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Encounter?identifier=A|1"); request .addEntry() .setFullUrl(cond.getId()) .setResource(cond) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Condition?identifier=A|2"); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(2, resp.getEntry().size()); BundleEntryComponent respEntry = resp.getEntry().get(0); assertEquals(Constants.STATUS_HTTP_201_CREATED + " Created", respEntry.getResponse().getStatus()); respEntry = resp.getEntry().get(1); assertEquals(Constants.STATUS_HTTP_201_CREATED + " Created", respEntry.getResponse().getStatus()); } @Test public void testTransactionWithCircularReferences2() throws IOException { Bundle request = loadResourceFromClasspath(Bundle.class, "/dstu3_transaction.xml"); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(3, resp.getEntry().size()); BundleEntryComponent respEntry = resp.getEntry().get(0); assertEquals(Constants.STATUS_HTTP_201_CREATED + " Created", respEntry.getResponse().getStatus()); respEntry = resp.getEntry().get(1); assertEquals(Constants.STATUS_HTTP_201_CREATED + " Created", respEntry.getResponse().getStatus()); } @Test public void testTransactionWithCircularReferences3() throws IOException { Bundle request = loadResourceFromClasspath(Bundle.class, "/r4/r4_transaction2.xml"); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(3, resp.getEntry().size()); BundleEntryComponent respEntry = resp.getEntry().get(0); assertEquals(Constants.STATUS_HTTP_201_CREATED + " Created", respEntry.getResponse().getStatus()); respEntry = resp.getEntry().get(1); assertEquals(Constants.STATUS_HTTP_201_CREATED + " Created", respEntry.getResponse().getStatus()); } @Test public void testTransactionWithConditionalUpdateDoesntUpdateIfNoChange() { Observation obs = new Observation(); obs.addIdentifier() .setSystem("http://acme.org") .setValue("ID1"); obs .getCode() .addCoding() .setSystem("http://loinc.org") .setCode("29463-7"); obs.setEffective(new DateTimeType("2011-09-03T11:13:00-04:00")); obs.setValue(new Quantity() .setValue(new BigDecimal("123.4")) .setCode("kg") .setSystem("http://unitsofmeasure.org") .setUnit("kg")); Bundle input = new Bundle(); input.setType(BundleType.TRANSACTION); input .addEntry() .setFullUrl("urn:uuid:0001") .setResource(obs) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Observation?identifier=http%3A%2F%2Facme.org|ID1"); Bundle output = mySystemDao.transaction(mySrd, input); assertEquals(1, output.getEntry().size()); IdType id = new IdType(output.getEntry().get(0).getResponse().getLocation()); assertEquals("Observation", id.getResourceType()); assertEquals("1", id.getVersionIdPart()); /* * Try again with same contents */ Observation obs2 = new Observation(); obs2.addIdentifier() .setSystem("http://acme.org") .setValue("ID1"); obs2 .getCode() .addCoding() .setSystem("http://loinc.org") .setCode("29463-7"); obs2.setEffective(new DateTimeType("2011-09-03T11:13:00-04:00")); obs2.setValue(new Quantity() .setValue(new BigDecimal("123.4")) .setCode("kg") .setSystem("http://unitsofmeasure.org") .setUnit("kg")); Bundle input2 = new Bundle(); input2.setType(BundleType.TRANSACTION); input2 .addEntry() .setFullUrl("urn:uuid:0001") .setResource(obs2) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Observation?identifier=http%3A%2F%2Facme.org|ID1"); Bundle output2 = mySystemDao.transaction(mySrd, input2); assertEquals(1, output2.getEntry().size()); IdType id2 = new IdType(output2.getEntry().get(0).getResponse().getLocation()); assertEquals("Observation", id2.getResourceType()); assertEquals("1", id2.getVersionIdPart()); assertEquals(id.getValue(), id2.getValue()); } @Test public void testTransactionWithConditionalUpdateDoesntUpdateIfNoChangeWithNormalizedQuantitySearchSupported() { myModelConfig.setNormalizedQuantitySearchLevel(NormalizedQuantitySearchLevel.NORMALIZED_QUANTITY_SEARCH_SUPPORTED); Observation obs = new Observation(); obs.addIdentifier() .setSystem("http://acme.org") .setValue("ID1"); obs .getCode() .addCoding() .setSystem("http://loinc.org") .setCode("29463-7"); obs.setEffective(new DateTimeType("2011-09-03T11:13:00-04:00")); obs.setValue(new Quantity() .setValue(new BigDecimal("123.4")) .setCode("kg") .setSystem("http://unitsofmeasure.org") .setUnit("kg")); Bundle input = new Bundle(); input.setType(BundleType.TRANSACTION); input .addEntry() .setFullUrl("urn:uuid:0001") .setResource(obs) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Observation?identifier=http%3A%2F%2Facme.org|ID1"); Bundle output = mySystemDao.transaction(mySrd, input); assertEquals(1, output.getEntry().size()); IdType id = new IdType(output.getEntry().get(0).getResponse().getLocation()); assertEquals("Observation", id.getResourceType()); assertEquals("1", id.getVersionIdPart()); /* * Try again with same contents */ Observation obs2 = new Observation(); obs2.addIdentifier() .setSystem("http://acme.org") .setValue("ID1"); obs2 .getCode() .addCoding() .setSystem("http://loinc.org") .setCode("29463-7"); obs2.setEffective(new DateTimeType("2011-09-03T11:13:00-04:00")); obs2.setValue(new Quantity() .setValue(new BigDecimal("123.4")) .setCode("kg") .setSystem("http://unitsofmeasure.org") .setUnit("kg")); Bundle input2 = new Bundle(); input2.setType(BundleType.TRANSACTION); input2 .addEntry() .setFullUrl("urn:uuid:0001") .setResource(obs2) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Observation?identifier=http%3A%2F%2Facme.org|ID1"); Bundle output2 = mySystemDao.transaction(mySrd, input2); assertEquals(1, output2.getEntry().size()); IdType id2 = new IdType(output2.getEntry().get(0).getResponse().getLocation()); assertEquals("Observation", id2.getResourceType()); assertEquals("1", id2.getVersionIdPart()); assertEquals(id.getValue(), id2.getValue()); } @Test public void testTransactionWithIfMatch() { Patient p = new Patient(); p.setId("P1"); p.setActive(true); myPatientDao.update(p); p.setActive(false); Bundle b = new Bundle(); b.setType(BundleType.TRANSACTION); b.addEntry() .setFullUrl("Patient/P1") .setResource(p) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Patient/P1") .setIfMatch("2"); try { mySystemDao.transaction(mySrd, b); } catch (ResourceVersionConflictException e) { assertEquals("Trying to update Patient/P1/_history/2 but this is not the current version", e.getMessage()); } b = new Bundle(); b.setType(BundleType.TRANSACTION); b.addEntry() .setFullUrl("Patient/P1") .setResource(p) .getRequest() .setMethod(HTTPVerb.PUT) .setUrl("Patient/P1") .setIfMatch("1"); Bundle resp = mySystemDao.transaction(mySrd, b); assertEquals("Patient/P1/_history/2", new IdType(resp.getEntry().get(0).getResponse().getLocation()).toUnqualified().getValue()); } @Test public void testTransactionWithIfNoneExist() { Patient p = new Patient(); p.setId("P1"); p.setActive(true); myPatientDao.update(p); p = new Patient(); p.setActive(true); p.addName().setFamily("AAA"); Bundle b = new Bundle(); b.setType(BundleType.TRANSACTION); b.addEntry() .setFullUrl("Patient") .setResource(p) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Patient/P1") .setIfNoneExist("Patient?active=true"); Bundle resp = mySystemDao.transaction(mySrd, b); assertEquals("Patient/P1/_history/1", new IdType(resp.getEntry().get(0).getResponse().getLocation()).toUnqualified().getValue()); p = new Patient(); p.setActive(false); p.addName().setFamily("AAA"); b = new Bundle(); b.setType(BundleType.TRANSACTION); b.addEntry() .setFullUrl("Patient") .setResource(p) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Patient/P1") .setIfNoneExist("Patient?active=false"); resp = mySystemDao.transaction(mySrd, b); assertThat(new IdType(resp.getEntry().get(0).getResponse().getLocation()).toUnqualified().getValue(), matchesPattern("Patient/[0-9]+/_history/1")); } @Test public void testTransactionWithInlineMatchUrl() throws Exception { myDaoConfig.setAllowInlineMatchUrlReferences(true); Patient patient = new Patient(); patient.addIdentifier().setSystem("http: myPatientDao.create(patient, mySrd); String input = IOUtils.toString(getClass().getResourceAsStream("/simone-conditional-url.xml"), StandardCharsets.UTF_8); Bundle bundle = myFhirCtx.newXmlParser().parseResource(Bundle.class, input); Bundle response = mySystemDao.transaction(mySrd, bundle); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(response)); } @Test public void testTransactionWithInlineMatchUrlMultipleMatches() throws Exception { myDaoConfig.setAllowInlineMatchUrlReferences(true); Patient patient = new Patient(); patient.addIdentifier().setSystem("http: myPatientDao.create(patient, mySrd); patient = new Patient(); patient.addIdentifier().setSystem("http: myPatientDao.create(patient, mySrd); String input = IOUtils.toString(getClass().getResourceAsStream("/simone-conditional-url.xml"), StandardCharsets.UTF_8); Bundle bundle = myFhirCtx.newXmlParser().parseResource(Bundle.class, input); try { mySystemDao.transaction(mySrd, bundle); fail(); } catch (PreconditionFailedException e) { assertEquals("Invalid match URL \"Patient?identifier=http: } } @Test public void testTransactionWithInlineMatchUrlNoMatches() throws Exception { myDaoConfig.setAllowInlineMatchUrlReferences(true); String input = IOUtils.toString(getClass().getResourceAsStream("/simone-conditional-url.xml"), StandardCharsets.UTF_8); Bundle bundle = myFhirCtx.newXmlParser().parseResource(Bundle.class, input); try { mySystemDao.transaction(mySrd, bundle); fail(); } catch (ResourceNotFoundException e) { assertEquals("Invalid match URL \"Patient?identifier=http: } } @Test public void testTransactionWithInvalidType() { Bundle request = new Bundle(); request.setType(BundleType.SEARCHSET); Patient p = new Patient(); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST); try { mySystemDao.transaction(mySrd, request); fail(); } catch (InvalidRequestException e) { assertEquals("Unable to process transaction where incoming Bundle.type = searchset", e.getMessage()); } } /** * See #801 */ @Test @Disabled public void testTransactionWithMatchUrlToReferenceInSameBundle() throws IOException { String input = IOUtils.toString(getClass().getResourceAsStream("/r4/bug801.json"), StandardCharsets.UTF_8); Bundle bundle = myFhirCtx.newJsonParser().parseResource(Bundle.class, input); try { mySystemDao.transaction(mySrd, bundle); fail(); } catch (ResourceNotFoundException e) { // expected } } @Test public void testTransactionWithMultiBundle() throws IOException { String inputBundleString = loadClasspath("/r4/batch-error.xml"); Bundle bundle = myFhirCtx.newXmlParser().parseResource(Bundle.class, inputBundleString); Bundle resp = mySystemDao.transaction(mySrd, bundle); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); assertEquals("201 Created", resp.getEntry().get(0).getResponse().getStatus()); new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus theStatus) { Set<String> values = new HashSet<String>(); for (ResourceTag next : myResourceTagDao.findAll()) { if (!values.add(next.toString())) { ourLog.info("Found duplicate tag on resource of type {}", next.getResource().getResourceType()); ourLog.info("Tag was: {} / {}", next.getTag().getSystem(), next.getTag().getCode()); } } } }); } @Test public void testTransactionWithNullReference() { Patient p = new Patient(); p.addName().setFamily("family"); final IIdType id = myPatientDao.create(p, mySrd).getId().toUnqualifiedVersionless(); Bundle inputBundle = new Bundle(); //@formatter:off Patient app0 = new Patient(); app0.addName().setFamily("NEW PATIENT"); String placeholderId0 = IdDt.newRandomUuid().getValue(); inputBundle .addEntry() .setResource(app0) .setFullUrl(placeholderId0) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Patient"); //@formatter:on //@formatter:off Appointment app1 = new Appointment(); app1.addParticipant().getActor().setReference(id.getValue()); inputBundle .addEntry() .setResource(app1) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Appointment"); //@formatter:on //@formatter:off Appointment app2 = new Appointment(); app2.addParticipant().getActor().setDisplay("NO REF"); app2.addParticipant().getActor().setDisplay("YES REF").setReference(placeholderId0); inputBundle .addEntry() .setResource(app2) .getRequest() .setMethod(HTTPVerb.POST) .setUrl("Appointment"); //@formatter:on Bundle outputBundle = mySystemDao.transaction(mySrd, inputBundle); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(outputBundle)); assertEquals(3, outputBundle.getEntry().size()); IdDt id0 = new IdDt(outputBundle.getEntry().get(0).getResponse().getLocation()); IdDt id2 = new IdDt(outputBundle.getEntry().get(2).getResponse().getLocation()); app2 = myAppointmentDao.read(id2, mySrd); assertEquals("NO REF", app2.getParticipant().get(0).getActor().getDisplay()); assertEquals(null, app2.getParticipant().get(0).getActor().getReference()); assertEquals("YES REF", app2.getParticipant().get(1).getActor().getDisplay()); assertEquals(id0.toUnqualifiedVersionless().getValue(), app2.getParticipant().get(1).getActor().getReference()); } /* * Make sure we are able to handle placeholder IDs in match URLs, e.g. * * "request": { * "method": "PUT", * "url": "Observation?subject=urn:uuid:8dba64a8-2aca-48fe-8b4e-8c7bf2ab695a&code=http%3A%2F%2Floinc.org|29463-7&date=2011-09-03T11:13:00-04:00" * } * </pre> */ @Test public void testTransactionWithPlaceholderIdInMatchUrlPost() { Bundle input = createInputTransactionWithPlaceholderIdInMatchUrl(HTTPVerb.POST); Bundle output = mySystemDao.transaction(null, input); assertEquals("201 Created", output.getEntry().get(0).getResponse().getStatus()); assertEquals("201 Created", output.getEntry().get(1).getResponse().getStatus()); assertEquals("201 Created", output.getEntry().get(2).getResponse().getStatus()); Bundle input2 = createInputTransactionWithPlaceholderIdInMatchUrl(HTTPVerb.POST); Bundle output2 = mySystemDao.transaction(null, input2); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(output2)); assertEquals("200 OK", output2.getEntry().get(0).getResponse().getStatus()); assertEquals("200 OK", output2.getEntry().get(1).getResponse().getStatus()); assertEquals("200 OK", output2.getEntry().get(2).getResponse().getStatus()); } /* * Make sure we are able to handle placeholder IDs in match URLs, e.g. * * "request": { * "method": "PUT", * "url": "Observation?subject=urn:uuid:8dba64a8-2aca-48fe-8b4e-8c7bf2ab695a&code=http%3A%2F%2Floinc.org|29463-7&date=2011-09-03T11:13:00-04:00" * } * </pre> */ @Test public void testTransactionWithPlaceholderIdInMatchUrlPut() { Bundle input = createInputTransactionWithPlaceholderIdInMatchUrl(HTTPVerb.PUT); Bundle output = mySystemDao.transaction(null, input); assertEquals("201 Created", output.getEntry().get(0).getResponse().getStatus()); assertEquals("201 Created", output.getEntry().get(1).getResponse().getStatus()); assertEquals("201 Created", output.getEntry().get(2).getResponse().getStatus()); Bundle input2 = createInputTransactionWithPlaceholderIdInMatchUrl(HTTPVerb.PUT); Bundle output2 = mySystemDao.transaction(null, input2); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(output2)); assertEquals("200 OK", output2.getEntry().get(0).getResponse().getStatus()); assertEquals("200 OK", output2.getEntry().get(1).getResponse().getStatus()); assertEquals("200 OK", output2.getEntry().get(2).getResponse().getStatus()); } /** * Per a message on the mailing list */ @Test public void testTransactionWithPostDoesntUpdate() throws Exception { // First bundle (name is Joshua) String input = IOUtils.toString(getClass().getResource("/r4/post1.xml"), StandardCharsets.UTF_8); Bundle request = myFhirCtx.newXmlParser().parseResource(Bundle.class, input); Bundle response = mySystemDao.transaction(mySrd, request); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(response)); assertEquals(1, response.getEntry().size()); assertEquals("201 Created", response.getEntry().get(0).getResponse().getStatus()); assertEquals("1", response.getEntry().get(0).getResponse().getEtag()); String id = response.getEntry().get(0).getResponse().getLocation(); // Now the second (name is Adam, shouldn't get used) input = IOUtils.toString(getClass().getResource("/r4/post2.xml"), StandardCharsets.UTF_8); request = myFhirCtx.newXmlParser().parseResource(Bundle.class, input); response = mySystemDao.transaction(mySrd, request); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(response)); assertEquals(1, response.getEntry().size()); assertEquals("200 OK", response.getEntry().get(0).getResponse().getStatus()); assertEquals("1", response.getEntry().get(0).getResponse().getEtag()); String id2 = response.getEntry().get(0).getResponse().getLocation(); assertEquals(id, id2); Patient patient = myPatientDao.read(new IdType(id), mySrd); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(patient)); assertEquals("Joshua", patient.getNameFirstRep().getGivenAsSingleString()); } @Test public void testTransactionWithReferenceResource() { Bundle request = new Bundle(); Patient p = new Patient(); p.setActive(true); p.setId(IdType.newRandomUuid()); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST).setUrl(p.getId()); Observation o = new Observation(); o.getCode().setText("Some Observation"); o.getSubject().setResource(p); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.POST); Bundle resp = mySystemDao.transaction(mySrd, request); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); String patientId = new IdType(resp.getEntry().get(0).getResponse().getLocation()).toUnqualifiedVersionless().getValue(); assertThat(patientId, startsWith("Patient/")); SearchParameterMap params = new SearchParameterMap(); params.setLoadSynchronous(true); params.add("subject", new ReferenceParam(patientId)); IBundleProvider found = myObservationDao.search(params); assertEquals(1, found.size().intValue()); } @Test public void testTransactionWithReferenceToCreateIfNoneExist() { Bundle bundle = new Bundle(); bundle.setType(BundleType.TRANSACTION); Medication med = new Medication(); IdType medId = IdType.newRandomUuid(); med.setId(medId); med.getCode().addCoding().setSystem("billscodes").setCode("theCode"); bundle.addEntry().setResource(med).setFullUrl(medId.getValue()).getRequest().setMethod(HTTPVerb.POST).setIfNoneExist("Medication?code=billscodes|theCode"); MedicationRequest mo = new MedicationRequest(); mo.setMedication(new Reference(medId)); bundle.addEntry().setResource(mo).setFullUrl(mo.getIdElement().getValue()).getRequest().setMethod(HTTPVerb.POST); ourLog.info("Request:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(bundle)); Bundle outcome = mySystemDao.transaction(mySrd, bundle); ourLog.info("Response:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(outcome)); IdType medId1 = new IdType(outcome.getEntry().get(0).getResponse().getLocation()); IdType medOrderId1 = new IdType(outcome.getEntry().get(1).getResponse().getLocation()); /* * Again! */ bundle = new Bundle(); bundle.setType(BundleType.TRANSACTION); med = new Medication(); medId = IdType.newRandomUuid(); med.getCode().addCoding().setSystem("billscodes").setCode("theCode"); bundle.addEntry().setResource(med).setFullUrl(medId.getValue()).getRequest().setMethod(HTTPVerb.POST).setIfNoneExist("Medication?code=billscodes|theCode"); mo = new MedicationRequest(); mo.setMedication(new Reference(medId)); bundle.addEntry().setResource(mo).setFullUrl(mo.getIdElement().getValue()).getRequest().setMethod(HTTPVerb.POST); outcome = mySystemDao.transaction(mySrd, bundle); IdType medId2 = new IdType(outcome.getEntry().get(0).getResponse().getLocation()); IdType medOrderId2 = new IdType(outcome.getEntry().get(1).getResponse().getLocation()); assertTrue(medId1.isIdPartValidLong()); assertTrue(medId2.isIdPartValidLong()); assertTrue(medOrderId1.isIdPartValidLong()); assertTrue(medOrderId2.isIdPartValidLong()); assertEquals(medId1, medId2); assertNotEquals(medOrderId1, medOrderId2); } @Test public void testTransactionWithReferenceUuid() { Bundle request = new Bundle(); Patient p = new Patient(); p.setActive(true); p.setId(IdType.newRandomUuid()); request.addEntry().setResource(p).getRequest().setMethod(HTTPVerb.POST).setUrl(p.getId()); Observation o = new Observation(); o.getCode().setText("Some Observation"); o.getSubject().setReference(p.getId()); request.addEntry().setResource(o).getRequest().setMethod(HTTPVerb.POST); Bundle resp = mySystemDao.transaction(mySrd, request); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); String patientId = new IdType(resp.getEntry().get(0).getResponse().getLocation()).toUnqualifiedVersionless().getValue(); assertThat(patientId, startsWith("Patient/")); SearchParameterMap params = new SearchParameterMap(); params.setLoadSynchronous(true); params.add("subject", new ReferenceParam(patientId)); IBundleProvider found = myObservationDao.search(params); assertEquals(1, found.size().intValue()); } @Test public void testTransactionWithRelativeOidIds() { Bundle res = new Bundle(); res.setType(BundleType.TRANSACTION); Patient p1 = new Patient(); p1.setId("urn:oid:0.1.2.3"); p1.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds01"); res.addEntry().setResource(p1).getRequest().setMethod(HTTPVerb.POST).setUrl("Patient"); Observation o1 = new Observation(); o1.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds02"); o1.setSubject(new Reference("urn:oid:0.1.2.3")); res.addEntry().setResource(o1).getRequest().setMethod(HTTPVerb.POST).setUrl("Observation"); Observation o2 = new Observation(); o2.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds03"); o2.setSubject(new Reference("urn:oid:0.1.2.3")); res.addEntry().setResource(o2).getRequest().setMethod(HTTPVerb.POST).setUrl("Observation"); Bundle resp = mySystemDao.transaction(mySrd, res); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); assertEquals(BundleType.TRANSACTIONRESPONSE, resp.getTypeElement().getValue()); assertEquals(3, resp.getEntry().size()); assertTrue(new IdType(resp.getEntry().get(0).getResponse().getLocation()).getIdPart().matches("^[0-9]+$"), resp.getEntry().get(0).getResponse().getLocation()); assertTrue(new IdType(resp.getEntry().get(1).getResponse().getLocation()).getIdPart().matches("^[0-9]+$"), resp.getEntry().get(1).getResponse().getLocation()); assertTrue(new IdType(resp.getEntry().get(2).getResponse().getLocation()).getIdPart().matches("^[0-9]+$"), resp.getEntry().get(2).getResponse().getLocation()); o1 = myObservationDao.read(new IdType(resp.getEntry().get(1).getResponse().getLocation()), mySrd); o2 = myObservationDao.read(new IdType(resp.getEntry().get(2).getResponse().getLocation()), mySrd); assertThat(o1.getSubject().getReferenceElement().getValue(), endsWith("Patient/" + p1.getIdElement().getIdPart())); assertThat(o2.getSubject().getReferenceElement().getValue(), endsWith("Patient/" + p1.getIdElement().getIdPart())); } // /** // * Issue #55 // */ // @Test // public void testTransactionWithCidIds() throws Exception { // Bundle request = new Bundle(); // Patient p1 = new Patient(); // p1.setId("cid:patient1"); // p1.addIdentifier().setSystem("system").setValue("testTransactionWithCidIds01"); // res.add(p1); // Observation o1 = new Observation(); // o1.setId("cid:observation1"); // o1.getIdentifier().setSystem("system").setValue("testTransactionWithCidIds02"); // o1.setSubject(new Reference("Patient/cid:patient1")); // res.add(o1); // Observation o2 = new Observation(); // o2.setId("cid:observation2"); // o2.getIdentifier().setSystem("system").setValue("testTransactionWithCidIds03"); // o2.setSubject(new Reference("Patient/cid:patient1")); // res.add(o2); // ourSystemDao.transaction(res); // assertTrue(p1.getId().getValue(), p1.getId().getIdPart().matches("^[0-9]+$")); // assertTrue(o1.getId().getValue(), o1.getId().getIdPart().matches("^[0-9]+$")); // assertTrue(o2.getId().getValue(), o2.getId().getIdPart().matches("^[0-9]+$")); // assertThat(o1.getSubject().getReference().getValue(), endsWith("Patient/" + p1.getId().getIdPart())); // assertThat(o2.getSubject().getReference().getValue(), endsWith("Patient/" + p1.getId().getIdPart())); // @Test // public void testTransactionWithDelete() throws Exception { // Bundle request = new Bundle(); // /* // * Create 3 // */ // List<IResource> res; // res = new ArrayList<IResource>(); // Patient p1 = new Patient(); // p1.addIdentifier().setSystem("urn:system").setValue("testTransactionWithDelete"); // res.add(p1); // Patient p2 = new Patient(); // p2.addIdentifier().setSystem("urn:system").setValue("testTransactionWithDelete"); // res.add(p2); // Patient p3 = new Patient(); // p3.addIdentifier().setSystem("urn:system").setValue("testTransactionWithDelete"); // res.add(p3); // ourSystemDao.transaction(res); // /* // * Verify // */ // IBundleProvider results = ourPatientDao.search(Patient.SP_IDENTIFIER, new TokenParam("urn:system", // "testTransactionWithDelete")); // assertEquals(3, results.size()); // /* // * Now delete 2 // */ // request = new Bundle(); // res = new ArrayList<IResource>(); // List<IResource> existing = results.getResources(0, 3); // p1 = new Patient(); // p1.setId(existing.get(0).getId()); // ResourceMetadataKeyEnum.DELETED_AT.put(p1, InstantDt.withCurrentTime()); // res.add(p1); // p2 = new Patient(); // p2.setId(existing.get(1).getId()); // ResourceMetadataKeyEnum.DELETED_AT.put(p2, InstantDt.withCurrentTime()); // res.add(p2); // ourSystemDao.transaction(res); // /* // * Verify // */ // IBundleProvider results2 = ourPatientDao.search(Patient.SP_IDENTIFIER, new TokenParam("urn:system", // "testTransactionWithDelete")); // assertEquals(1, results2.size()); // List<IResource> existing2 = results2.getResources(0, 1); // assertEquals(existing2.get(0).getId(), existing.get(2).getId()); /** * This is not the correct way to do it, but we'll allow it to be lenient */ @Test public void testTransactionWithRelativeOidIdsQualified() { Bundle res = new Bundle(); res.setType(BundleType.TRANSACTION); Patient p1 = new Patient(); p1.setId("urn:oid:0.1.2.3"); p1.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds01"); res.addEntry().setResource(p1).getRequest().setMethod(HTTPVerb.POST).setUrl("Patient"); Observation o1 = new Observation(); o1.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds02"); o1.setSubject(new Reference("Patient/urn:oid:0.1.2.3")); res.addEntry().setResource(o1).getRequest().setMethod(HTTPVerb.POST).setUrl("Observation"); Observation o2 = new Observation(); o2.addIdentifier().setSystem("system").setValue("testTransactionWithRelativeOidIds03"); o2.setSubject(new Reference("Patient/urn:oid:0.1.2.3")); res.addEntry().setResource(o2).getRequest().setMethod(HTTPVerb.POST).setUrl("Observation"); Bundle resp = mySystemDao.transaction(mySrd, res); ourLog.info(myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(resp)); assertEquals(BundleType.TRANSACTIONRESPONSE, resp.getTypeElement().getValue()); assertEquals(3, resp.getEntry().size()); assertTrue(new IdType(resp.getEntry().get(0).getResponse().getLocation()).getIdPart().matches("^[0-9]+$"), resp.getEntry().get(0).getResponse().getLocation()); assertTrue(new IdType(resp.getEntry().get(1).getResponse().getLocation()).getIdPart().matches("^[0-9]+$"), resp.getEntry().get(1).getResponse().getLocation()); assertTrue(new IdType(resp.getEntry().get(2).getResponse().getLocation()).getIdPart().matches("^[0-9]+$"), resp.getEntry().get(2).getResponse().getLocation()); o1 = myObservationDao.read(new IdType(resp.getEntry().get(1).getResponse().getLocation()), mySrd); o2 = myObservationDao.read(new IdType(resp.getEntry().get(2).getResponse().getLocation()), mySrd); assertThat(o1.getSubject().getReferenceElement().getValue(), endsWith("Patient/" + p1.getIdElement().getIdPart())); assertThat(o2.getSubject().getReferenceElement().getValue(), endsWith("Patient/" + p1.getIdElement().getIdPart())); } @Test public void testTransactionWithReplacement() { byte[] bytes = new byte[]{0, 1, 2, 3, 4}; Binary binary = new Binary(); binary.setId(IdType.newRandomUuid()); binary.setContent(bytes); binary.setContentType("application/pdf"); DiagnosticReport dr = new DiagnosticReport(); dr.setId(IdDt.newRandomUuid()); Attachment attachment = new Attachment(); attachment.setContentType("application/pdf"); attachment.setUrl(binary.getId()); // this one has substitution dr.addPresentedForm(attachment); Attachment attachment2 = new Attachment(); attachment2.setUrl(IdType.newRandomUuid().getValue()); // this one has no subscitution dr.addPresentedForm(attachment2); Bundle transactionBundle = new Bundle(); transactionBundle.setType(BundleType.TRANSACTION); Bundle.BundleEntryComponent binaryEntry = new Bundle.BundleEntryComponent(); binaryEntry.setResource(binary).setFullUrl(binary.getId()).getRequest().setUrl("Binary").setMethod(Bundle.HTTPVerb.POST); transactionBundle.addEntry(binaryEntry); Bundle.BundleEntryComponent drEntry = new Bundle.BundleEntryComponent(); drEntry.setResource(dr).setFullUrl(dr.getId()).getRequest().setUrl("DiagnosticReport").setMethod(Bundle.HTTPVerb.POST); transactionBundle.addEntry(drEntry); Bundle transactionResp = mySystemDao.transaction(mySrd, transactionBundle); assertEquals(2, transactionResp.getEntry().size()); // Validate Binary binary = myBinaryDao.read(new IdType(transactionResp.getEntry().get(0).getResponse().getLocation())); assertArrayEquals(bytes, binary.getContent()); // Validate DiagnosticReport dr = myDiagnosticReportDao.read(new IdType(transactionResp.getEntry().get(1).getResponse().getLocation())); assertEquals(binary.getIdElement().toUnqualifiedVersionless().getValue(), dr.getPresentedForm().get(0).getUrl()); assertEquals(attachment2.getUrl(), dr.getPresentedForm().get(1).getUrl()); } /** * See #467 */ @Test public void testTransactionWithSelfReferentialLink() { /* * Link to each other */ Bundle request = new Bundle(); Organization o1 = new Organization(); o1.setId(IdType.newRandomUuid()); o1.setName("ORG1"); request.addEntry().setResource(o1).getRequest().setMethod(HTTPVerb.POST); Organization o2 = new Organization(); o2.setName("ORG2"); o2.setId(IdType.newRandomUuid()); request.addEntry().setResource(o2).getRequest().setMethod(HTTPVerb.POST); o1.getPartOf().setReference(o2.getId()); o2.getPartOf().setReference(o1.getId()); Bundle resp = mySystemDao.transaction(mySrd, request); assertEquals(BundleType.TRANSACTIONRESPONSE, resp.getTypeElement().getValue()); assertEquals(2, resp.getEntry().size()); IdType id1 = new IdType(resp.getEntry().get(0).getResponse().getLocation()); IdType id2 = new IdType(resp.getEntry().get(1).getResponse().getLocation()); ourLog.info("ID1: {}", id1); SearchParameterMap map = new SearchParameterMap(); map.add(Organization.SP_PARTOF, new ReferenceParam(id1.toUnqualifiedVersionless().getValue())); IBundleProvider res = myOrganizationDao.search(map); assertEquals(1, res.size().intValue()); assertEquals(id2.toUnqualifiedVersionless().getValue(), res.getResources(0, 1).get(0).getIdElement().toUnqualifiedVersionless().getValue()); map = new SearchParameterMap(); map.add(Organization.SP_PARTOF, new ReferenceParam(id2.toUnqualifiedVersionless().getValue())); res = myOrganizationDao.search(map); assertEquals(1, res.size().intValue()); assertEquals(id1.toUnqualifiedVersionless().getValue(), res.getResources(0, 1).get(0).getIdElement().toUnqualifiedVersionless().getValue()); /* * Link to self */ request = new Bundle(); o1 = new Organization(); o1.setId(id1); o1.setName("ORG1"); request.addEntry().setResource(o1).getRequest().setMethod(HTTPVerb.PUT).setUrl(id1.toUnqualifiedVersionless().getValue()); o2 = new Organization(); o2.setName("ORG2"); o2.setId(id2); request.addEntry().setResource(o2).getRequest().setMethod(HTTPVerb.PUT).setUrl(id2.toUnqualifiedVersionless().getValue()); o1.getPartOf().setReference(o1.getId()); o2.getPartOf().setReference(o2.getId()); resp = mySystemDao.transaction(mySrd, request); assertEquals(BundleType.TRANSACTIONRESPONSE, resp.getTypeElement().getValue()); assertEquals(2, resp.getEntry().size()); id1 = new IdType(resp.getEntry().get(0).getResponse().getLocation()); id2 = new IdType(resp.getEntry().get(1).getResponse().getLocation()); ourLog.info("ID1: {}", id1); map = new SearchParameterMap(); map.add(Organization.SP_PARTOF, new ReferenceParam(id1.toUnqualifiedVersionless().getValue())); res = myOrganizationDao.search(map); assertEquals(1, res.size().intValue()); assertEquals(id1.toUnqualifiedVersionless().getValue(), res.getResources(0, 1).get(0).getIdElement().toUnqualifiedVersionless().getValue()); map = new SearchParameterMap(); map.add(Organization.SP_PARTOF, new ReferenceParam(id2.toUnqualifiedVersionless().getValue())); res = myOrganizationDao.search(map); assertEquals(1, res.size().intValue()); assertEquals(id2.toUnqualifiedVersionless().getValue(), res.getResources(0, 1).get(0).getIdElement().toUnqualifiedVersionless().getValue()); } /** * See #811 */ @Test public void testUpdatePreviouslyDeletedResourceInBatch() { AllergyIntolerance ai = new AllergyIntolerance(); ai.setId("AIA1914009"); ai.addNote().setText("Hello"); IIdType id = myAllergyIntoleranceDao.update(ai).getId(); assertEquals("1", id.getVersionIdPart()); id = myAllergyIntoleranceDao.delete(ai.getIdElement().toUnqualifiedVersionless()).getId(); assertEquals("2", id.getVersionIdPart()); try { myAllergyIntoleranceDao.read(ai.getIdElement().toUnqualifiedVersionless()); fail(); } catch (ResourceGoneException e) { // good } Bundle batch = new Bundle(); batch.setType(BundleType.BATCH); ai = new AllergyIntolerance(); ai.setId("AIA1914009"); ai.addNote().setText("Hello"); batch .addEntry() .setFullUrl("AllergyIntolerance/AIA1914009") .setResource(ai) .getRequest() .setUrl("AllergyIntolerance/AIA1914009") .setMethod(HTTPVerb.PUT); mySystemDao.transaction(mySrd, batch); id = myAllergyIntoleranceDao.read(ai.getIdElement().toUnqualifiedVersionless()).getIdElement(); assertEquals("3", id.getVersionIdPart()); } }
package org.eclipse.hawkbit.amqp; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.UUID; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.eclipse.hawkbit.api.HostnameResolver; import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; import org.eclipse.hawkbit.artifact.repository.model.DbArtifactHash; import org.eclipse.hawkbit.cache.CacheConstants; import org.eclipse.hawkbit.cache.DownloadArtifactCache; import org.eclipse.hawkbit.cache.DownloadType; import org.eclipse.hawkbit.dmf.amqp.api.EventTopic; import org.eclipse.hawkbit.dmf.amqp.api.MessageHeaderKey; import org.eclipse.hawkbit.dmf.amqp.api.MessageType; import org.eclipse.hawkbit.dmf.json.model.ActionUpdateStatus; import org.eclipse.hawkbit.dmf.json.model.Artifact; import org.eclipse.hawkbit.dmf.json.model.ArtifactHash; import org.eclipse.hawkbit.dmf.json.model.DownloadResponse; import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken; import org.eclipse.hawkbit.dmf.json.model.TenantSecurityToken.FileResource; import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails; import org.eclipse.hawkbit.repository.ArtifactManagement; import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.EntityFactory; import org.eclipse.hawkbit.repository.RepositoryConstants; import org.eclipse.hawkbit.repository.eventbus.event.TargetAssignDistributionSetEvent; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.exception.TenantNotExistException; import org.eclipse.hawkbit.repository.exception.ToManyStatusEntriesException; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.ActionStatus; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.LocalArtifact; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.util.IpUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.AmqpRejectAndDontRequeueException; import org.springframework.amqp.core.Message; import org.springframework.amqp.core.MessageProperties; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cache.Cache; import org.springframework.http.HttpStatus; import org.springframework.messaging.handler.annotation.Header; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.CredentialsExpiredException; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.web.util.UriComponentsBuilder; import com.google.common.eventbus.EventBus; /** * * {@link AmqpMessageHandlerService} handles all incoming AMQP messages for the * queue which is configure for the property hawkbit.dmf.rabbitmq.receiverQueue. * */ public class AmqpMessageHandlerService extends BaseAmqpService { private static final Logger LOG = LoggerFactory.getLogger(AmqpMessageHandlerService.class); @Autowired private ControllerManagement controllerManagement; @Autowired private AmqpControllerAuthentfication authenticationManager; @Autowired private ArtifactManagement artifactManagement; @Autowired private EventBus eventBus; @Autowired @Qualifier(CacheConstants.DOWNLOAD_ID_CACHE) private Cache cache; @Autowired private HostnameResolver hostnameResolver; @Autowired private EntityFactory entityFactory; @Autowired private SystemSecurityContext systemSecurityContext; /** * Constructor. * * @param defaultTemplate * the configured amqp template. */ public AmqpMessageHandlerService(final RabbitTemplate defaultTemplate) { super(defaultTemplate); } /** * Method to handle all incoming DMF amqp messages. * * @param message * incoming message * @param type * the message type * @param tenant * the contentType of the message * * @return a message if <null> no message is send back to sender */ @RabbitListener(queues = "${hawkbit.dmf.rabbitmq.receiverQueue}", containerFactory = "listenerContainerFactory") public Message onMessage(final Message message, @Header(MessageHeaderKey.TYPE) final String type, @Header(MessageHeaderKey.TENANT) final String tenant) { return onMessage(message, type, tenant, getRabbitTemplate().getConnectionFactory().getVirtualHost()); } /** * Executed on a authentication request. * * @param message * the amqp message * @return the rpc message back to supplier. */ @RabbitListener(queues = "${hawkbit.dmf.rabbitmq.authenticationReceiverQueue}", containerFactory = "listenerContainerFactory") public Message onAuthenticationRequest(final Message message) { checkContentTypeJson(message); final SecurityContext oldContext = SecurityContextHolder.getContext(); try { return handleAuthentifiactionMessage(message); } catch (final IllegalArgumentException ex) { throw new AmqpRejectAndDontRequeueException("Invalid message!", ex); } catch (final TenantNotExistException | ToManyStatusEntriesException e) { throw new AmqpRejectAndDontRequeueException(e); } finally { SecurityContextHolder.setContext(oldContext); } } /** * * Executed if a amqp message arrives. * * @param message * the message * @param type * the type * @param tenant * the tenant * @param virtualHost * the virtual host * @return the rpc message back to supplier. */ public Message onMessage(final Message message, final String type, final String tenant, final String virtualHost) { checkContentTypeJson(message); final SecurityContext oldContext = SecurityContextHolder.getContext(); try { final MessageType messageType = MessageType.valueOf(type); switch (messageType) { case THING_CREATED: setTenantSecurityContext(tenant); registerTarget(message, virtualHost); break; case EVENT: setTenantSecurityContext(tenant); final String topicValue = getStringHeaderKey(message, MessageHeaderKey.TOPIC, "EventTopic is null"); final EventTopic eventTopic = EventTopic.valueOf(topicValue); handleIncomingEvent(message, eventTopic); break; default: logAndThrowMessageError(message, "No handle method was found for the given message type."); } } catch (final IllegalArgumentException ex) { throw new AmqpRejectAndDontRequeueException("Invalid message!", ex); } catch (final TenantNotExistException teex) { throw new AmqpRejectAndDontRequeueException(teex); } finally { SecurityContextHolder.setContext(oldContext); } return null; } private Message handleAuthentifiactionMessage(final Message message) { final DownloadResponse authentificationResponse = new DownloadResponse(); final MessageProperties messageProperties = message.getMessageProperties(); final TenantSecurityToken secruityToken = convertMessage(message, TenantSecurityToken.class); final FileResource fileResource = secruityToken.getFileResource(); try { SecurityContextHolder.getContext().setAuthentication(authenticationManager.doAuthenticate(secruityToken)); final LocalArtifact localArtifact = findLocalArtifactByFileResource(fileResource); if (localArtifact == null) { LOG.info("target {} requested file resource {} which does not exists to download", secruityToken.getControllerId(), fileResource); throw new EntityNotFoundException(); } checkIfArtifactIsAssignedToTarget(secruityToken, localArtifact); final Artifact artifact = convertDbArtifact(artifactManagement.loadLocalArtifactBinary(localArtifact)); if (artifact == null) { throw new EntityNotFoundException(); } authentificationResponse.setArtifact(artifact); final String downloadId = UUID.randomUUID().toString(); // SHA1 key is set, download by SHA1 final DownloadArtifactCache downloadCache = new DownloadArtifactCache(DownloadType.BY_SHA1, localArtifact.getSha1Hash()); cache.put(downloadId, downloadCache); authentificationResponse .setDownloadUrl(UriComponentsBuilder.fromUri(hostnameResolver.resolveHostname().toURI()) .path("/api/v1/downloadserver/downloadId/").path(downloadId).build().toUriString()); authentificationResponse.setResponseCode(HttpStatus.OK.value()); } catch (final BadCredentialsException | AuthenticationServiceException | CredentialsExpiredException e) { LOG.error("Login failed", e); authentificationResponse.setResponseCode(HttpStatus.FORBIDDEN.value()); authentificationResponse.setMessage("Login failed"); } catch (final URISyntaxException e) { LOG.error("URI build exception", e); authentificationResponse.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value()); authentificationResponse.setMessage("Building download URI failed"); } catch (final EntityNotFoundException e) { final String errorMessage = "Artifact for resource " + fileResource + "not found "; LOG.warn(errorMessage, e); authentificationResponse.setResponseCode(HttpStatus.NOT_FOUND.value()); authentificationResponse.setMessage(errorMessage); } return getMessageConverter().toMessage(authentificationResponse, messageProperties); } /** * check action for this download purposes, the method will throw an * EntityNotFoundException in case the controller is not allowed to download * this file because it's not assigned to an action and not assigned to this * controller. Otherwise no controllerId is set = anonymous download * * @param secruityToken * the security token which holds the target ID to check on * @param localArtifact * the local artifact to verify if the given target is allowed to * download this artifact */ private void checkIfArtifactIsAssignedToTarget(final TenantSecurityToken secruityToken, final LocalArtifact localArtifact) { final String controllerId = secruityToken.getControllerId(); if (controllerId == null) { LOG.info("anonymous download no authentication check for artifact {}", localArtifact); return; } LOG.debug("no anonymous download request, doing authentication check for target {} and artifact {}", controllerId, localArtifact); if (!controllerManagement.hasTargetArtifactAssigned(controllerId, localArtifact)) { LOG.info("target {} tried to download artifact {} which is not assigned to the target", controllerId, localArtifact); throw new EntityNotFoundException(); } LOG.info("download security check for target {} and artifact {} granted", controllerId, localArtifact); } private LocalArtifact findLocalArtifactByFileResource(final FileResource fileResource) { if (fileResource.getSha1() != null) { return artifactManagement.findFirstLocalArtifactsBySHA1(fileResource.getSha1()); } else if (fileResource.getFilename() != null) { return artifactManagement.findLocalArtifactByFilename(fileResource.getFilename()).stream().findFirst() .orElse(null); } else if (fileResource.getSoftwareModuleFilenameResource() != null) { return artifactManagement .findByFilenameAndSoftwareModule(fileResource.getSoftwareModuleFilenameResource().getFilename(), fileResource.getSoftwareModuleFilenameResource().getSoftwareModuleId()) .stream().findFirst().orElse(null); } return null; } private static Artifact convertDbArtifact(final DbArtifact dbArtifact) { final Artifact artifact = new Artifact(); artifact.setSize(dbArtifact.getSize()); final DbArtifactHash dbArtifactHash = dbArtifact.getHashes(); artifact.setHashes(new ArtifactHash(dbArtifactHash.getSha1(), dbArtifactHash.getMd5())); return artifact; } private static void setSecurityContext(final Authentication authentication) { final SecurityContextImpl securityContextImpl = new SecurityContextImpl(); securityContextImpl.setAuthentication(authentication); SecurityContextHolder.setContext(securityContextImpl); } private static void setTenantSecurityContext(final String tenantId) { final AnonymousAuthenticationToken authenticationToken = new AnonymousAuthenticationToken( UUID.randomUUID().toString(), "AMQP-Controller", Collections.singletonList(new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS))); authenticationToken.setDetails(new TenantAwareAuthenticationDetails(tenantId, true)); setSecurityContext(authenticationToken); } /** * Method to create a new target or to find the target if it already exists. * * @param targetID * the ID of the target/thing * @param ip * the ip of the target/thing */ private void registerTarget(final Message message, final String virtualHost) { final String thingId = getStringHeaderKey(message, MessageHeaderKey.THING_ID, "ThingId is null"); final String replyTo = message.getMessageProperties().getReplyTo(); if (StringUtils.isEmpty(replyTo)) { logAndThrowMessageError(message, "No ReplyTo was set for the createThing Event."); } final URI amqpUri = IpUtil.createAmqpUri(virtualHost, replyTo); final Target target = controllerManagement.findOrRegisterTargetIfItDoesNotexist(thingId, amqpUri); LOG.debug("Target {} reported online state.", thingId); lookIfUpdateAvailable(target); } private void lookIfUpdateAvailable(final Target target) { final List<Action> actions = controllerManagement.findActionByTargetAndActive(target); if (actions.isEmpty()) { return; } // action are ordered by ASC final Action action = actions.get(0); final DistributionSet distributionSet = action.getDistributionSet(); final List<SoftwareModule> softwareModuleList = controllerManagement .findSoftwareModulesByDistributionSet(distributionSet); final String targetSecurityToken = systemSecurityContext.runAsSystem(() -> target.getSecurityToken()); eventBus.post(new TargetAssignDistributionSetEvent(target.getOptLockRevision(), target.getTenant(), target.getControllerId(), action.getId(), softwareModuleList, target.getTargetInfo().getAddress(), targetSecurityToken)); } /** * Method to handle the different topics to an event. * * @param message * the incoming event message. * @param topic * the topic of the event. */ private void handleIncomingEvent(final Message message, final EventTopic topic) { if (EventTopic.UPDATE_ACTION_STATUS.equals(topic)) { updateActionStatus(message); return; } logAndThrowMessageError(message, "Got event without appropriate topic."); } /** * Method to update the action status of an action through the event. * * @param actionUpdateStatus * the object form the ampq message */ private void updateActionStatus(final Message message) { final ActionUpdateStatus actionUpdateStatus = convertMessage(message, ActionUpdateStatus.class); final Action action = checkActionExist(message, actionUpdateStatus); final ActionStatus actionStatus = createActionStatus(message, actionUpdateStatus, action); switch (actionUpdateStatus.getActionStatus()) { case DOWNLOAD: actionStatus.setStatus(Status.DOWNLOAD); break; case RETRIEVED: actionStatus.setStatus(Status.RETRIEVED); break; case RUNNING: actionStatus.setStatus(Status.RUNNING); break; case CANCELED: actionStatus.setStatus(Status.CANCELED); break; case FINISHED: actionStatus.setStatus(Status.FINISHED); break; case ERROR: actionStatus.setStatus(Status.ERROR); break; case WARNING: actionStatus.setStatus(Status.WARNING); break; case CANCEL_REJECTED: handleCancelRejected(message, action, actionStatus); break; default: logAndThrowMessageError(message, "Status for action does not exisit."); } final Action addUpdateActionStatus = getUpdateActionStatus(actionStatus); if (!addUpdateActionStatus.isActive()) { lookIfUpdateAvailable(action.getTarget()); } } private ActionStatus createActionStatus(final Message message, final ActionUpdateStatus actionUpdateStatus, final Action action) { final ActionStatus actionStatus = entityFactory.generateActionStatus(); actionUpdateStatus.getMessage().forEach(actionStatus::addMessage); if (ArrayUtils.isNotEmpty(message.getMessageProperties().getCorrelationId())) { actionStatus.addMessage(RepositoryConstants.SERVER_MESSAGE_PREFIX + "DMF message correlation-id " + convertCorrelationId(message)); } actionStatus.setAction(action); actionStatus.setOccurredAt(System.currentTimeMillis()); return actionStatus; } private static String convertCorrelationId(final Message message) { return new String(message.getMessageProperties().getCorrelationId(), StandardCharsets.UTF_8); } private Action getUpdateActionStatus(final ActionStatus actionStatus) { if (actionStatus.getStatus().equals(Status.CANCELED)) { return controllerManagement.addCancelActionStatus(actionStatus); } return controllerManagement.addUpdateActionStatus(actionStatus); } private Action checkActionExist(final Message message, final ActionUpdateStatus actionUpdateStatus) { final Long actionId = actionUpdateStatus.getActionId(); LOG.debug("Target notifies intermediate about action {} with status {}.", actionId, actionUpdateStatus.getActionStatus().name()); if (actionId == null) { logAndThrowMessageError(message, "Invalid message no action id"); } final Action action = controllerManagement.findActionWithDetails(actionId); if (action == null) { logAndThrowMessageError(message, "Got intermediate notification about action " + actionId + " but action does not exist"); } return action; } private void handleCancelRejected(final Message message, final Action action, final ActionStatus actionStatus) { if (action.isCancelingOrCanceled()) { actionStatus.setStatus(Status.WARNING); // cancel action rejected, write warning status message and fall // back to running action status } else { logAndThrowMessageError(message, "Cancel recjected message is not allowed, if action is on state: " + action.getStatus()); } } private static void checkContentTypeJson(final Message message) { final MessageProperties messageProperties = message.getMessageProperties(); if (messageProperties.getContentType() != null && messageProperties.getContentType().contains("json")) { return; } throw new AmqpRejectAndDontRequeueException("Content-Type is not JSON compatible"); } void setControllerManagement(final ControllerManagement controllerManagement) { this.controllerManagement = controllerManagement; } void setHostnameResolver(final HostnameResolver hostnameResolver) { this.hostnameResolver = hostnameResolver; } void setAuthenticationManager(final AmqpControllerAuthentfication authenticationManager) { this.authenticationManager = authenticationManager; } void setArtifactManagement(final ArtifactManagement artifactManagement) { this.artifactManagement = artifactManagement; } void setCache(final Cache cache) { this.cache = cache; } void setEventBus(final EventBus eventBus) { this.eventBus = eventBus; } void setEntityFactory(final EntityFactory entityFactory) { this.entityFactory = entityFactory; } void setSystemSecurityContext(final SystemSecurityContext systemSecurityContext) { this.systemSecurityContext = systemSecurityContext; } }
package org.jboss.as.host.controller; import java.io.DataInput; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.net.ssl.SSLContext; import javax.security.auth.callback.CallbackHandler; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.domain.controller.SlaveRegistrationException; import org.jboss.as.domain.management.CallbackHandlerFactory; import org.jboss.as.domain.management.SecurityRealm; import org.jboss.as.host.controller.discovery.DiscoveryOption; import org.jboss.as.host.controller.mgmt.DomainControllerProtocol; import org.jboss.as.network.NetworkUtils; import org.jboss.as.protocol.ProtocolChannelClient; import org.jboss.as.protocol.ProtocolConnectionConfiguration; import org.jboss.as.protocol.ProtocolConnectionManager; import org.jboss.as.protocol.ProtocolConnectionUtils; import org.jboss.as.protocol.ProtocolMessages; import org.jboss.as.protocol.StreamUtils; import org.jboss.as.protocol.mgmt.AbstractManagementRequest; import org.jboss.as.protocol.mgmt.ActiveOperation; import org.jboss.as.protocol.mgmt.FlushableDataOutput; import org.jboss.as.protocol.mgmt.FutureManagementChannel; import org.jboss.as.protocol.mgmt.ManagementChannelHandler; import org.jboss.as.protocol.mgmt.ManagementPingRequest; import org.jboss.as.protocol.mgmt.ManagementPongRequestHandler; import org.jboss.as.protocol.mgmt.ManagementRequestContext; import org.jboss.as.remoting.management.ManagementRemotingServices; import org.jboss.dmr.ModelNode; import org.jboss.remoting3.Channel; import org.jboss.remoting3.Connection; import org.jboss.threads.AsyncFuture; import org.wildfly.security.manager.WildFlySecurityManager; /** * A connection to a remote domain controller. Once successfully connected this {@code ManagementClientChannelStrategy} * implementation will try to reconnect with a remote host-controller. * * @author Emanuel Muckenhuber */ class RemoteDomainConnection extends FutureManagementChannel { private static final String CHANNEL_SERVICE_TYPE = ManagementRemotingServices.DOMAIN_CHANNEL; private static final long INTERVAL; private static final long TIMEOUT; static { long interval = -1; try { interval = Long.parseLong(WildFlySecurityManager.getPropertyPrivileged("jboss.as.domain.ping.interval", "15000")); } catch (Exception e) { // TODO log } finally { INTERVAL = interval > 0 ? interval : 15000; } long timeout = -1; try { timeout = Long.parseLong(WildFlySecurityManager.getPropertyPrivileged("jboss.as.domain.ping.timeout", "30000")); } catch (Exception e) { // TODO log } finally { TIMEOUT = timeout > 0 ? timeout : 30000; } } private final String localHostName; private final String username; private final SecurityRealm realm; private final ModelNode localHostInfo; private final RemoteDomainConnection.HostRegistrationCallback callback; private final ProtocolConnectionManager connectionManager; private final ProtocolChannelClient.Configuration configuration; private final ManagementChannelHandler channelHandler; private final ExecutorService executorService; private final ScheduledExecutorService scheduledExecutorService; private final ManagementPongRequestHandler pongHandler = new ManagementPongRequestHandler(); private final List<DiscoveryOption> discoveryOptions; private URI uri; private volatile boolean closing = false; RemoteDomainConnection(final String localHostName, final ModelNode localHostInfo, final ProtocolChannelClient.Configuration configuration, final SecurityRealm realm, final String username, final List<DiscoveryOption> discoveryOptions, final ExecutorService executorService, final ScheduledExecutorService scheduledExecutorService, final HostRegistrationCallback callback) { this.callback = callback; this.localHostName = localHostName; this.localHostInfo = localHostInfo; this.configuration = configuration; this.username = username; this.realm = realm; this.discoveryOptions = discoveryOptions; this.executorService = executorService; this.channelHandler = new ManagementChannelHandler(this, executorService); this.scheduledExecutorService = scheduledExecutorService; this.connectionManager = ProtocolConnectionManager.create(new InitialConnectTask()); } /** * Try to connect to the remote host. * * @throws IOException */ protected void connect() throws IOException { // Connect to the remote HC connectionManager.connect(); } /** * The channel handler. * * @return the channel handler */ protected ManagementChannelHandler getChannelHandler() { return channelHandler; } @Override public Channel getChannel() throws IOException { Channel result; if (!closing) { // Normal case result = awaitChannel(); } else { // TODO WFLY-1511 this 'closing' stuff is just a quick and dirty fix; do it better // We're closing so we don't need to wait for a channel if there isn't one // If there isn't one the master will either be shut down itself or will detect the close // of the existing channel result = super.getChannel(); if (result == null) { // Better than returning null with a subsequent NPE throw ProtocolMessages.MESSAGES.channelClosed(); } } return result; } /** * Set the configuration uri. * * @param uri the uri */ protected void setUri(URI uri) { this.uri = uri; } @Override public void close() throws IOException { synchronized (this) { closing = true; try { if(isConnected()) { try { channelHandler.executeRequest(new UnregisterModelControllerRequest(), null).getResult().await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } finally { try { connectionManager.shutdown(); } finally { super.close(); closing = false; } } } } protected boolean isConnected() { return super.isConnected(); } /** * Connect and register at the remote domain controller. * * @return connection the established connection * @throws IOException */ protected Connection openConnection() throws IOException { // Perhaps this can just be done once? CallbackHandler callbackHandler = null; SSLContext sslContext = null; if (realm != null) { sslContext = realm.getSSLContext(); CallbackHandlerFactory handlerFactory = realm.getSecretCallbackHandlerFactory(); if (handlerFactory != null) { String username = this.username != null ? this.username : localHostName; callbackHandler = handlerFactory.getCallbackHandler(username); } } final ProtocolConnectionConfiguration config = ProtocolConnectionConfiguration.copy(configuration); config.setCallbackHandler(callbackHandler); config.setSslContext(sslContext); config.setUri(uri); // Connect return ProtocolConnectionUtils.connectSync(config); } @Override public void connectionOpened(final Connection connection) throws IOException { final Channel channel = openChannel(connection, CHANNEL_SERVICE_TYPE, configuration.getOptionMap()); if(setChannel(channel)) { channel.receiveMessage(channelHandler.getReceiver()); channel.addCloseHandler(channelHandler); try { // Start the registration process channelHandler.executeRequest(new RegisterHostControllerRequest(), null).getResult().get(); } catch (Exception e) { if(e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } throw new IOException(e); } // Registered registered(); } else { channel.closeAsync(); } } protected Future<Connection> reconnect() { return executorService.submit(new Callable<Connection>() { @Override public Connection call() throws Exception { final ReconnectPolicy reconnectPolicy = ReconnectPolicy.RECONNECT; int reconnectionCount = 0; for(;;) { // Try to connect to the remote host controller by looping through all // discovery options String host = null; int port = -1; reconnectPolicy.wait(reconnectionCount); for (DiscoveryOption discoveryOption : discoveryOptions) { try { discoveryOption.discover(); host = discoveryOption.getRemoteDomainControllerHost(); port = discoveryOption.getRemoteDomainControllerPort(); setUri(new URI("remote://" + NetworkUtils.formatPossibleIpv6Address(host) + ":" + port)); HostControllerLogger.ROOT_LOGGER.debugf("trying to reconnect to remote host-controller"); return connectionManager.connect(); } catch (IOException e) { HostControllerLogger.ROOT_LOGGER.debugf(e, "failed to reconnect to the remote host-controller"); } catch (IllegalStateException e) { HostControllerLogger.ROOT_LOGGER.debugf(e, "failed to reconnect to the remote host-controller"); } } reconnectionCount++; } } }); } /** * Resolve the subsystem versions. * * @param extensions the extensions * @return the resolved subsystem versions */ ModelNode resolveSubsystemVersions(ModelNode extensions) { return callback.resolveSubsystemVersions(extensions); } /** * Apply the remote read domain model result. * * @param result the domain model result * @return whether it was applied successfully or not */ boolean applyDomainModel(ModelNode result) { if(! result.hasDefined(ModelDescriptionConstants.RESULT)) { return false; } final List<ModelNode> bootOperations= result.get(ModelDescriptionConstants.RESULT).asList(); return callback.applyDomainModel(bootOperations); } void registered() { // schedule(new PingTask()); callback.registrationComplete(channelHandler); } private void schedule(PingTask task) { scheduledExecutorService.schedule(task, INTERVAL, TimeUnit.MILLISECONDS); } interface HostRegistrationCallback { /** * Get the versions for all registered subsystems. * * @param extensions the extension list * @return the subsystem versions */ ModelNode resolveSubsystemVersions(ModelNode extensions); /** * Apply the remote domain model. * * @param result the read-domain-model operation result * @return {@code true} if the model was applied successfully, {@code false} otherwise */ boolean applyDomainModel(List<ModelNode> result); /** * Event that the registration was completed. * * @param handler the handler */ void registrationComplete(ManagementChannelHandler handler); } /** * The host-controller registration request. */ private class RegisterHostControllerRequest extends AbstractManagementRequest<Void, Void> { @Override public byte getOperationType() { return DomainControllerProtocol.REGISTER_HOST_CONTROLLER_REQUEST; } @Override protected void sendRequest(final ActiveOperation.ResultHandler<Void> resultHandler, final ManagementRequestContext<Void> context, final FlushableDataOutput output) throws IOException { output.write(DomainControllerProtocol.PARAM_HOST_ID); output.writeUTF(localHostName); ModelNode hostInfo = localHostInfo.clone(); hostInfo.get(RemoteDomainConnectionService.DOMAIN_CONNECTION_ID).set(pongHandler.getConnectionId()); hostInfo.writeExternal(output); } @Override public void handleRequest(final DataInput input, final ActiveOperation.ResultHandler<Void> resultHandler, final ManagementRequestContext<Void> context) throws IOException { byte param = input.readByte(); // If it failed if(param != DomainControllerProtocol.PARAM_OK) { final byte errorCode = input.readByte(); final String message = input.readUTF(); resultHandler.failed(new SlaveRegistrationException(SlaveRegistrationException.ErrorCode.parseCode(errorCode), message)); return; } final ModelNode extensions = new ModelNode(); extensions.readExternal(input); context.executeAsync(new ManagementRequestContext.AsyncTask<Void>() { @Override public void execute(ManagementRequestContext<Void> voidManagementRequestContext) throws Exception { final ModelNode subsystems = resolveSubsystemVersions(extensions); channelHandler.executeRequest(context.getOperationId(), new RegisterSubsystemsRequest(subsystems)); } }); } } private class RegisterSubsystemsRequest extends AbstractManagementRequest<Void, Void> { private final ModelNode subsystems; private RegisterSubsystemsRequest(ModelNode subsystems) { this.subsystems = subsystems; } @Override public byte getOperationType() { return DomainControllerProtocol.REQUEST_SUBSYSTEM_VERSIONS; } @Override protected void sendRequest(ActiveOperation.ResultHandler<Void> registrationResultResultHandler, ManagementRequestContext<Void> voidManagementRequestContext, FlushableDataOutput output) throws IOException { output.writeByte(DomainControllerProtocol.PARAM_OK); subsystems.writeExternal(output); } @Override public void handleRequest(final DataInput input, final ActiveOperation.ResultHandler<Void> resultHandler, final ManagementRequestContext<Void> context) throws IOException { byte param = input.readByte(); // If it failed if(param != DomainControllerProtocol.PARAM_OK) { final byte errorCode = input.readByte(); final String message = input.readUTF(); resultHandler.failed(new SlaveRegistrationException(SlaveRegistrationException.ErrorCode.parseCode(errorCode), message)); return; } final ModelNode domainModel = new ModelNode(); domainModel.readExternal(input); context.executeAsync(new ManagementRequestContext.AsyncTask<Void>() { @Override public void execute(ManagementRequestContext<Void> voidManagementRequestContext) throws Exception { // Apply the domain model final boolean success = applyDomainModel(domainModel); if(success) { channelHandler.executeRequest(context.getOperationId(), new CompleteRegistrationRequest(DomainControllerProtocol.PARAM_OK)); } else { channelHandler.executeRequest(context.getOperationId(), new CompleteRegistrationRequest(DomainControllerProtocol.PARAM_ERROR)); resultHandler.failed(new SlaveRegistrationException(SlaveRegistrationException.ErrorCode.UNKNOWN, "")); } } }); } } private class CompleteRegistrationRequest extends AbstractManagementRequest<Void, Void> { private final byte outcome; private final String message = "yay!"; private CompleteRegistrationRequest(final byte outcome) { this.outcome = outcome; } @Override public byte getOperationType() { return DomainControllerProtocol.COMPLETE_HOST_CONTROLLER_REGISTRATION; } @Override protected void sendRequest(final ActiveOperation.ResultHandler<Void> resultHandler, final ManagementRequestContext<Void> context, final FlushableDataOutput output) throws IOException { output.writeByte(outcome); output.writeUTF(message); } @Override public void handleRequest(DataInput input, ActiveOperation.ResultHandler<Void> resultHandler, ManagementRequestContext<Void> voidManagementRequestContext) throws IOException { final byte param = input.readByte(); // If it failed if(param != DomainControllerProtocol.PARAM_OK) { final byte errorCode = input.readByte(); final String message = input.readUTF(); resultHandler.failed(new SlaveRegistrationException(SlaveRegistrationException.ErrorCode.parseCode(errorCode), message)); return; } resultHandler.done(null); } } private class UnregisterModelControllerRequest extends AbstractManagementRequest<Void, Void> { @Override public byte getOperationType() { return DomainControllerProtocol.UNREGISTER_HOST_CONTROLLER_REQUEST; } @Override protected void sendRequest(ActiveOperation.ResultHandler<Void> resultHandler, ManagementRequestContext<Void> voidManagementRequestContext, FlushableDataOutput output) throws IOException { output.write(DomainControllerProtocol.PARAM_HOST_ID); output.writeUTF(localHostName); } @Override public void handleRequest(DataInput input, ActiveOperation.ResultHandler<Void> resultHandler, ManagementRequestContext<Void> voidManagementRequestContext) throws IOException { HostControllerLogger.ROOT_LOGGER.unregisteredAtRemoteHostController(); resultHandler.done(null); } } private class PingTask implements Runnable { private Long remoteInstanceID; @Override public void run() { if (isConnected()) { boolean fail = false; AsyncFuture<Long> future = null; try { if (System.currentTimeMillis() - channelHandler.getLastMessageReceivedTime() > INTERVAL) { future = channelHandler.executeRequest(ManagementPingRequest.INSTANCE, null).getResult(); Long id = future.get(TIMEOUT, TimeUnit.MILLISECONDS); if (remoteInstanceID != null && !remoteInstanceID.equals(id)) { HostControllerLogger.DOMAIN_LOGGER.masterHostControllerChanged(); fail = true; } else { remoteInstanceID = id; } } } catch (IOException e) { HostControllerLogger.DOMAIN_LOGGER.debug("Caught exception sending ping request", e); } catch (InterruptedException e) { safeCancel(future); Thread.currentThread().interrupt(); } catch (ExecutionException e) { HostControllerLogger.DOMAIN_LOGGER.debug("Caught exception sending ping request", e); } catch (TimeoutException e) { fail = true; safeCancel(future); HostControllerLogger.DOMAIN_LOGGER.masterHostControllerUnreachable(TIMEOUT); } finally { if (fail) { Channel channel = null; try { channel = channelHandler.getChannel(); } catch (IOException e) { // ignore; shouldn't happen as the channel is already established if this task is running } StreamUtils.safeClose(channel); } else { schedule(this); } } } } void safeCancel(Future<?> future) { if (future != null) { future.cancel(true); } } } class InitialConnectTask implements ProtocolConnectionManager.ConnectTask { @Override public Connection connect() throws IOException { return openConnection(); } @Override public ProtocolConnectionManager.ConnectionOpenHandler getConnectionOpenedHandler() { return RemoteDomainConnection.this; } @Override public ProtocolConnectionManager.ConnectTask connectionClosed() { HostControllerLogger.ROOT_LOGGER.lostRemoteDomainConnection(); return new ReconnectTaskWrapper(reconnect()); } @Override public void shutdown() { } } class ReconnectTaskWrapper implements ProtocolConnectionManager.ConnectTask { private final Future<Connection> connectionFuture; ReconnectTaskWrapper(Future<Connection> connectionFuture) { this.connectionFuture = connectionFuture; } @Override public Connection connect() throws IOException { final Connection connection = openConnection(); HostControllerLogger.ROOT_LOGGER.reconnectedToMaster(); return connection; } @Override public ProtocolConnectionManager.ConnectionOpenHandler getConnectionOpenedHandler() { return RemoteDomainConnection.this; } @Override public ProtocolConnectionManager.ConnectTask connectionClosed() { HostControllerLogger.ROOT_LOGGER.lostRemoteDomainConnection(); return new ReconnectTaskWrapper(reconnect()); } @Override public void shutdown() { connectionFuture.cancel(true); } } }
package com.autonomy.abc.indexes; import com.autonomy.abc.config.HostedTestBase; import com.autonomy.abc.config.TestConfig; import com.autonomy.abc.selenium.config.ApplicationType; import com.autonomy.abc.selenium.connections.ConnectionService; import com.autonomy.abc.selenium.connections.Connector; import com.autonomy.abc.selenium.connections.WebConnector; import com.autonomy.abc.selenium.element.GritterNotice; import com.autonomy.abc.selenium.find.Find; import com.autonomy.abc.selenium.indexes.Index; import com.autonomy.abc.selenium.indexes.IndexService; import com.autonomy.abc.selenium.menu.NavBarTabId; import com.autonomy.abc.selenium.page.connections.ConnectionsPage; import com.autonomy.abc.selenium.page.connections.NewConnectionPage; import com.autonomy.abc.selenium.page.indexes.IndexesDetailPage; import com.autonomy.abc.selenium.page.indexes.IndexesPage; import com.autonomy.abc.selenium.page.promotions.PromotionsDetailPage; import com.autonomy.abc.selenium.promotions.PinToPositionPromotion; import com.autonomy.abc.selenium.promotions.PromotionService; import com.autonomy.abc.selenium.search.IndexFilter; import com.autonomy.abc.selenium.search.SearchQuery; import com.autonomy.abc.selenium.util.DriverUtil; import com.autonomy.abc.selenium.util.Errors; import com.autonomy.abc.selenium.util.PageUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.NoSuchElementException; import static com.autonomy.abc.framework.ABCAssert.assertThat; import static com.autonomy.abc.framework.ABCAssert.verifyThat; import static com.autonomy.abc.matchers.ElementMatchers.containsText; import static junit.framework.TestCase.fail; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.core.AllOf.allOf; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsCollectionContaining.hasItem; public class IndexesPageITCase extends HostedTestBase { private final static Logger LOGGER = LoggerFactory.getLogger(IndexesPageITCase.class); private IndexService indexService; private IndexesPage indexesPage; public IndexesPageITCase(TestConfig config, String browser, ApplicationType type, Platform platform) { super(config, browser, type, platform); // requires a separate account where indexes can safely be added and deleted setInitialUser(config.getUser("index_tests")); } @Before public void setUp() { body.getSideNavBar().switchPage(NavBarTabId.INDEXES); indexesPage = getElementFactory().getIndexesPage(); body = getBody(); indexService = getApplication().createIndexService(getElementFactory()); } @Test //CSA-1450 public void testDeletingIndex(){ Index index = new Index("index"); indexesPage = indexService.setUpIndex(index); verifyThat(indexesPage.getIndexDisplayNames(), hasItem(index.getName())); indexService.deleteIndex(index); verifyThat(indexesPage.getIndexDisplayNames(), not(hasItem(index.getName()))); } @Test //CSA-1720 public void testDefaultIndexIsNotDeletedWhenDeletingTheSoleConnectorAssociatedWithIt(){ ConnectionService cs = getApplication().createConnectionService(getElementFactory()); WebConnector connector = new WebConnector("http: //Create connection cs.setUpConnection(connector); try { //Try to delete the connection, (and the default index) cs.deleteConnection(connector, true); } catch (ElementNotVisibleException | NoSuchElementException e) { //If there's an error it is likely because the index couldn't be deleted - which is expected //Need to exit the deletion modal that will still be open getDriver().findElement(By.cssSelector(".modal-footer [type=button]")).click(); } //Navigate to indexes body.getSideNavBar().switchPage(NavBarTabId.INDEXES); IndexesPage indexesPage = getElementFactory().getIndexesPage(); //Make sure default index is still there assertThat(indexesPage.getIndexDisplayNames(), hasItem(Index.DEFAULT.getDisplayName())); } @Test //Potentially should be in ConnectionsPageITCase //CSA1710 public void testAttemptingToDeleteConnectionWhileItIsProcessingDoesNotDeleteAssociatedIndex(){ body.getSideNavBar().switchPage(NavBarTabId.CONNECTIONS); ConnectionsPage connectionsPage = getElementFactory().getConnectionsPage(); ConnectionService connectionService = getApplication().createConnectionService(getElementFactory()); //Create connector; index will be automatically set to 'bbc' WebConnector connector = new WebConnector("http: Index index = connector.getIndex(); //Create new connector - NO WAIT connectionsPage.newConnectionButton().click(); NewConnectionPage newConnectionPage = getElementFactory().getNewConnectionPage(); connector.makeWizard(newConnectionPage).apply(); //Try deleting the index straight away, while it is still processing //TODO change the Gritter Notice it's expecting try { connectionService.deleteConnection(connector, true); } catch (Exception e) { LOGGER.warn("Error deleting index"); } //Navigate to Indexes body.getSideNavBar().switchPage(NavBarTabId.INDEXES); IndexesPage indexesPage = getElementFactory().getIndexesPage(); //Ensure the index wasn't deleted assertThat(indexesPage.getIndexDisplayNames(), hasItem(index.getName())); } @Test //CSA1626 public void testDeletingIndexDoesNotInvalidatePromotions(){ //Create connection - attached to the same index (we need it to have data for a promotion) ConnectionService connectionService = getApplication().createConnectionService(getElementFactory()); WebConnector connector = new WebConnector("http: connectionService.setUpConnection(connector); //Create a promotion (using the index created) PromotionService promotionService = getApplication().createPromotionService(getElementFactory()); PinToPositionPromotion ptpPromotion = new PinToPositionPromotion(1,"trigger"); SearchQuery search = new SearchQuery("bbc").withFilter(new IndexFilter(connector.getIndex())); try { int numberOfDocs = 1; promotionService.setUpPromotion(ptpPromotion, search, numberOfDocs); //Now delete the index connectionService.deleteConnection(connector, true); //Navigate to the promotion - this will time out if it can't get to the Promotions Detail Page PromotionsDetailPage pdp = promotionService.goToDetails(ptpPromotion); //Get the promoted documents, there should still be one //TODO this is a workaround as getting promoted documents 'properly' errors if they are 'Unknown Document's List<WebElement> promotedDocuments = getDriver().findElements(By.cssSelector(".promoted-documents-list h3")); assertThat(promotedDocuments.size(), is(numberOfDocs)); //All documents should know be 'unknown documents' for(WebElement promotedDocument : promotedDocuments){ assertThat(promotedDocument.getText(), is("Unknown Document")); } } finally { promotionService.deleteAll(); } } @Test //CSA1544 public void testNoInvalidIndexNameNotifications(){ ConnectionService connectionService = getApplication().createConnectionService(getElementFactory()); Connector hassleRecords = new WebConnector("http: String errorMessage = "Index name invalid"; connectionService.setUpConnection(hassleRecords); try { new WebDriverWait(getDriver(),30).until(GritterNotice.notificationContaining(errorMessage)); fail("Index name should be valid - likely failed due to double encoding of requests"); } catch (TimeoutException e){ LOGGER.info("Timeout exception"); } body.getTopNavBar().notificationsDropdown(); for(String message : body.getTopNavBar().getNotifications().getAllNotificationMessages()){ assertThat(message,not(errorMessage)); } } @Test //CSA-1689 public void testNewlyCreatedIndexSize (){ IndexService indexService = getApplication().createIndexService(getElementFactory()); indexService.deleteAllIndexes(); Index index = new Index("yellow cat red cat"); indexService.setUpIndex(index); indexService.goToDetails(index); IndexesDetailPage indexesDetailPage = getElementFactory().getIndexesDetailPage(); verifyThat(indexesDetailPage.sizeString(), allOf(containsString("128 B"), containsString("(0 items)"))); } @Test //CSA-1735 public void testNavigatingToNonExistingIndexByURL(){ getDriver().get("https://search.dev.idolondemand.com/search/#/index/doesntexistmate"); verifyThat(PageUtil.getWrapperContent(getDriver()), containsText(Errors.Index.INVALID_INDEX)); } @Test //CSA-1886 public void testDeletingDefaultIndex(){ IndexService indexService = getApplication().createIndexService(getElementFactory()); indexService.deleteIndexViaAPICalls(Index.DEFAULT, getCurrentUser(), config.getApiUrl()); getDriver().navigate().refresh(); indexesPage = getElementFactory().getIndexesPage(); body = getBody(); verifyThat(indexesPage.getIndexDisplayNames(), hasItem(Index.DEFAULT.getName())); } @Test //CCUK-3450 public void testFindNoParametricFields(){ Index index = new Index("index"); indexService.setUpIndex(index); List<String> browserHandles = DriverUtil.createAndListWindowHandles(getDriver()); try { getDriver().switchTo().window(browserHandles.get(1)); getDriver().get(config.getFindUrl()); getDriver().manage().window().maximize(); Find find = getElementFactory().getFindPage(); find.search("search"); find.filterBy(new IndexFilter(index)); verifyThat(find.getResultsPage().getResultsDiv().getText(), is("No results found")); } finally { getDriver().switchTo().window(browserHandles.get(1)); getDriver().close(); getDriver().switchTo().window(browserHandles.get(0)); } } @After public void tearDown(){ try { getApplication().createConnectionService(getElementFactory()).deleteAllConnections(false); getApplication().createIndexService(getElementFactory()).deleteAllIndexes(); } catch (Exception e) { LOGGER.warn("Failed to tear down"); } } }
package no.ssb.vtl.script.expressions; import no.ssb.vtl.model.FilteringSpecification; import no.ssb.vtl.model.VTLBoolean; import no.ssb.vtl.model.VTLExpression; import no.ssb.vtl.model.VTLObject; import no.ssb.vtl.model.VtlFiltering; import no.ssb.vtl.script.expressions.equality.AbstractEqualityExpression; import no.ssb.vtl.script.expressions.equality.EqualExpression; import no.ssb.vtl.script.expressions.equality.GraterThanExpression; import no.ssb.vtl.script.expressions.equality.GreaterOrEqualExpression; import no.ssb.vtl.script.expressions.equality.IsNotNullExpression; import no.ssb.vtl.script.expressions.equality.IsNullExpression; import no.ssb.vtl.script.expressions.equality.LesserOrEqualExpression; import no.ssb.vtl.script.expressions.equality.LesserThanExpression; import no.ssb.vtl.script.expressions.equality.NotEqualExpression; import no.ssb.vtl.script.expressions.logic.AndExpression; import no.ssb.vtl.script.expressions.logic.OrExpression; import no.ssb.vtl.script.expressions.logic.XorExpression; import javax.script.SimpleBindings; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import static java.lang.String.format; public class VtlFilteringConverter { public static VtlFiltering convert(AbstractEqualityExpression equalityExpression) { VTLExpression leftOperand = equalityExpression.getLeftOperand(); VTLExpression rightOperand = equalityExpression.getRightOperand(); // We only support filter in the form of variable OP literal. if ((leftOperand instanceof VariableExpression && rightOperand instanceof LiteralExpression) || (leftOperand instanceof LiteralExpression && rightOperand instanceof VariableExpression)) { VariableExpression variableExpression = (VariableExpression) (leftOperand instanceof VariableExpression ? leftOperand : rightOperand); LiteralExpression literalExpression = (LiteralExpression) (leftOperand instanceof LiteralExpression ? leftOperand : rightOperand); // Use the internal identifier with dataset prefix if it is a membership expression. // This should be refactored at some point. String column = ""; if (variableExpression instanceof MembershipExpression) { column = ((MembershipExpression) variableExpression).getDatasetIdentifier() + "_"; } column = column + variableExpression.getIdentifier(); VTLObject value = literalExpression.resolve(null); if (equalityExpression instanceof EqualExpression) { return VtlFiltering.eq(column, value.get()); } else if (equalityExpression instanceof NotEqualExpression) { return VtlFiltering.neq(column, value.get()); } else if (equalityExpression instanceof GreaterOrEqualExpression) { return VtlFiltering.ge(column, value.get()); } else if (equalityExpression instanceof GraterThanExpression) { return VtlFiltering.gt(column, value.get()); } else if (equalityExpression instanceof LesserOrEqualExpression) { return VtlFiltering.le(column, value.get()); } else if (equalityExpression instanceof LesserThanExpression) { return VtlFiltering.lt(column, value.get()); } else if (equalityExpression instanceof IsNullExpression) { if (equalityExpression instanceof IsNotNullExpression) { return VtlFiltering.neq(column, value.get()); } else { return VtlFiltering.eq(column, value.get()); } } } // Unsupported expressions are converted to TRUE. return VtlFiltering.literal(false, FilteringSpecification.Operator.TRUE, null, null); } public static VtlFiltering convert(VTLExpression predicate) { if (!predicate.getVTLType().equals(VTLBoolean.class)) { throw new IllegalArgumentException(format("predicate %s was not a boolean", predicate)); } if (predicate instanceof OrExpression) { return convert((OrExpression) predicate); } else if (predicate instanceof AndExpression) { return convert((AndExpression) predicate); } else if (predicate instanceof XorExpression) { throw new UnsupportedOperationException(); } else if (predicate instanceof AbstractEqualityExpression) { return convert((AbstractEqualityExpression) predicate); } else if (predicate instanceof LiteralExpression) { VTLBoolean value = (VTLBoolean) predicate.resolve(new SimpleBindings(Collections.emptyMap())); return VtlFiltering.literal(!value.get(), FilteringSpecification.Operator.TRUE, null, value); } return VtlFiltering.literal(false, FilteringSpecification.Operator.TRUE, null, null); } public static VtlFiltering convert(OrExpression orExpression) { List<VtlFiltering> ops = new ArrayList<>(); if (orExpression.getLeftOperand() instanceof OrExpression) { ops.addAll(convert((OrExpression) orExpression.getLeftOperand()).getOperands()); } else { ops.add(convert(orExpression.getLeftOperand())); } VtlFiltering sub = convert(orExpression.getRightOperand()); if (sub != null && sub.getOperator() != FilteringSpecification.Operator.TRUE) { ops.add(sub); } return VtlFiltering.or(ops.toArray(new VtlFiltering[0])); } public static VtlFiltering convert(AndExpression andExpression) { List<VtlFiltering> ops = new ArrayList<>(); if (andExpression.getLeftOperand() instanceof AndExpression) { ops.addAll(convert((AndExpression) andExpression.getLeftOperand()).getOperands()); } else { ops.add(convert(andExpression.getLeftOperand())); } ops.add(convert(andExpression.getRightOperand())); return VtlFiltering.and(ops.toArray(new VtlFiltering[0])); } }
package com.intellij.execution.filters; import com.intellij.openapi.project.DumbService; import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiClass; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.InheritanceUtil; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; /** * This filter includes decorations not only for stack-trace lines, but also for exception names */ class AdvancedExceptionFilter extends ExceptionFilter { AdvancedExceptionFilter(@NotNull GlobalSearchScope scope) { super(scope); } @Override @NotNull List<ResultItem> getExceptionClassNameItems(ExceptionInfo prevLineException) { ExceptionInfoCache.ClassResolveInfo info = myCache.resolveClass(prevLineException.getExceptionClassName()); List<PsiClass> classMap = new ArrayList<>(); info.myClasses.forEach((key, value) -> { PsiClass psiClass = ObjectUtils.tryCast(value, PsiClass.class); if (psiClass != null && (DumbService.isDumb(psiClass.getProject()) || InheritanceUtil.isInheritor(psiClass, CommonClassNames.JAVA_LANG_THROWABLE))) { classMap.add(psiClass); } }); List<ResultItem> exceptionResults = new ArrayList<>(); if (!classMap.isEmpty()) { JvmExceptionOccurrenceFilter.EP_NAME.forEachExtensionSafe(filter -> { ResultItem res = filter.applyFilter(prevLineException.getExceptionClassName(), classMap, prevLineException.getClassNameOffset()); ContainerUtil.addIfNotNull(exceptionResults, res); }); } return exceptionResults; } }
package com.intellij.codeInspection; import com.intellij.codeInsight.daemon.JavaErrorBundle; import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel; import com.intellij.java.analysis.JavaAnalysisBundle; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.psi.*; import com.intellij.psi.util.ConstantEvaluationOverflowException; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class NumericOverflowInspection extends AbstractBaseJavaLocalInspectionTool { private static final Key<String> HAS_OVERFLOW_IN_CHILD = Key.create("HAS_OVERFLOW_IN_CHILD"); public boolean ignoreLeftShiftWithNegativeResult = true; @Nullable @Override public JComponent createOptionsPanel() { return new SingleCheckboxOptionsPanel(JavaAnalysisBundle.message("ignore.operation.which.results.in.negative.value"), this, "ignoreLeftShiftWithNegativeResult"); } @Nls @NotNull @Override public String getGroupDisplayName() { return InspectionsBundle.message("group.names.numeric.issues"); } @NotNull @Override public String getShortName() { return "NumericOverflow"; } @NotNull @Override public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) { return new JavaElementVisitor() { @Override public void visitReferenceExpression(PsiReferenceExpression expression) { if (!(expression.getParent() instanceof PsiMethodCallExpression)) { visitExpression(expression); } } @Override public void visitArrayAccessExpression(PsiArrayAccessExpression expression) { // never constant } @Override public void visitCallExpression(PsiCallExpression callExpression) { // never constant } @Override public void visitExpression(PsiExpression expression) { boolean hasOverflow = hasOverflow(expression, holder.getProject()); if (hasOverflow && (!ignoreLeftShiftWithNegativeResult || !isLeftShiftWithNegativeResult(expression, holder.getProject()))) { holder.registerProblem(expression, JavaErrorBundle.message("numeric.overflow.in.expression"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } } }; } private static boolean isLeftShiftWithNegativeResult(PsiExpression expression, Project project) { PsiBinaryExpression binOp = ObjectUtils.tryCast(PsiUtil.skipParenthesizedExprDown(expression), PsiBinaryExpression.class); if (binOp == null || !binOp.getOperationTokenType().equals(JavaTokenType.LTLT)) return false; PsiConstantEvaluationHelper helper = JavaPsiFacade.getInstance(project).getConstantEvaluationHelper(); Object lOperandValue = helper.computeConstantExpression(binOp.getLOperand()); Object rOperandValue = helper.computeConstantExpression(binOp.getROperand()); if (lOperandValue instanceof Character) lOperandValue = (int)((Character)lOperandValue).charValue(); if (rOperandValue instanceof Character) rOperandValue = (int)((Character)rOperandValue).charValue(); if (!(lOperandValue instanceof Number) || !(rOperandValue instanceof Number)) return false; if (lOperandValue instanceof Long) { long l = ((Number)lOperandValue).longValue(); long r = ((Number)rOperandValue).longValue(); return Long.numberOfLeadingZeros(l) - (r & 0x3F) == 0; } else { int l = ((Number)lOperandValue).intValue(); int r = ((Number)rOperandValue).intValue(); return Integer.numberOfLeadingZeros(l) - (r & 0x1F) == 0; } } private static boolean hasOverflow(PsiExpression expr, @NotNull Project project) { if (!TypeConversionUtil.isNumericType(expr.getType())) { return false; } boolean result = false; boolean toStoreInParent = false; try { if (expr.getUserData(HAS_OVERFLOW_IN_CHILD) == null) { JavaPsiFacade.getInstance(project).getConstantEvaluationHelper().computeConstantExpression(expr, true); } else { toStoreInParent = true; expr.putUserData(HAS_OVERFLOW_IN_CHILD, null); } } catch (ConstantEvaluationOverflowException e) { result = toStoreInParent = true; } finally { PsiElement parent = expr.getParent(); if (toStoreInParent && parent instanceof PsiExpression) { parent.putUserData(HAS_OVERFLOW_IN_CHILD, ""); } } return result; } }
package org.ccnx.ccn.profiles.security.access.group; import java.util.logging.Level; import org.bouncycastle.util.Arrays; import org.ccnx.ccn.impl.security.crypto.CCNDigestHelper; import org.ccnx.ccn.impl.support.DataUtils; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.impl.support.Tuple; import org.ccnx.ccn.io.content.ContentEncodingException; import org.ccnx.ccn.profiles.CCNProfile; import org.ccnx.ccn.profiles.VersionMissingException; import org.ccnx.ccn.profiles.VersioningProfile; import org.ccnx.ccn.profiles.security.access.AccessControlProfile; import org.ccnx.ccn.protocol.CCNTime; import org.ccnx.ccn.protocol.ContentName; /** * This class specifies how a number of access control elements are named: * - users, and their keys * - groups, and their keys * - access control lists (ACLs) * - node keys, and their encryption under ACL member keys * - if used, markers indicating where to find ACLs/node keys */ public class GroupAccessControlProfile extends AccessControlProfile implements CCNProfile { // These may eventually want to move somewhere more general public static final String GROUP_PREFIX = "Groups"; public static final byte [] GROUP_PREFIX_BYTES = ContentName.componentParseNative(GROUP_PREFIX); public static final String USER_PREFIX = "Users"; public static final byte [] USER_PREFIX_BYTES = ContentName.componentParseNative(USER_PREFIX); public static final String GROUP_MEMBERSHIP_LIST_NAME = "MembershipList"; public static final String GROUP_POINTER_TO_PARENT_GROUP_NAME = "PointerToParentGroup"; public static final String ACL_NAME = "ACL"; public static final byte [] ACL_NAME_BYTES = ContentName.componentParseNative(ACL_NAME); public static final String NODE_KEY_NAME = "NK"; public static final byte [] NODE_KEY_NAME_BYTES = ContentName.componentParseNative(NODE_KEY_NAME); // These two must be the same length public static final byte [] USER_PRINCIPAL_PREFIX = ContentName.componentParseNative("p"); public static final byte [] GROUP_PRINCIPAL_PREFIX = ContentName.componentParseNative("g"); public static final ContentName ACL_POSTFIX = new ContentName(new byte[][]{ACCESS_CONTROL_MARKER_BYTES, ACL_NAME_BYTES}); /** * This class records information about a CCN principal. * This information includes: * - principal type (group, etc), * - friendly name (the name the principal is known by) * - version * * We define a mapping between name components and principals: * <TYPE_PREFIX>:<NAMESPACE_HASH>:<FRIENDLY_NAME>:<VERSION> * */ public static class PrincipalInfo { // Number of parts expected in a PI component representation private static final int PI_COMPONENT_COUNT = 4; // However long our distinguishing hashes should be public static final int DISTINGUISHING_HASH_LENGTH = 8; private byte [] _typeMarker; private byte[] _distinguishingHash; private String _friendlyName; private CCNTime _versionTimestamp; /** * Parse the principal info for a specified public key name * @param isGroup whether the principal is a group * @param publicKeyName the public key name * @return the corresponding principal info * @throws VersionMissingException * @throws ContentEncodingException */ public PrincipalInfo(GroupAccessControlManager accessControlManager, ContentName publicKeyName) throws VersionMissingException, ContentEncodingException { boolean isGroup = accessControlManager.isGroupName(publicKeyName); _typeMarker = (isGroup ? GROUP_PRINCIPAL_PREFIX : USER_PRINCIPAL_PREFIX); _versionTimestamp = VersioningProfile.getLastVersionAsTimestamp(publicKeyName); // Now need to parse the principal name into a distinguishing hash and friendly name // How to do this depends on which group it is; there might be a postfix for the // name to deal with Tuple<ContentName, String> distinguishingPrefixAndFriendlyName = accessControlManager.parsePrefixAndFriendlyNameFromPublicKeyName(publicKeyName); _distinguishingHash = contentPrefixToDistinguishingHash(distinguishingPrefixAndFriendlyName.first()); _friendlyName = distinguishingPrefixAndFriendlyName.second(); } public PrincipalInfo(byte [] principalInfoNameComponent) { if (!PrincipalInfo.isPrincipalNameComponent(principalInfoNameComponent) || (principalInfoNameComponent.length <= USER_PRINCIPAL_PREFIX.length)) throw new IllegalArgumentException("Not a valid principal name component!"); int pos = 0; try { // The group and user principal prefixes are of the same length _typeMarker = new byte[GROUP_PRINCIPAL_PREFIX.length]; System.arraycopy(principalInfoNameComponent, pos, _typeMarker, 0, _typeMarker.length); pos += _typeMarker.length; pos += CCNProfile.COMPONENT_SEPARATOR.length; // The distinguishing hash is of length DISTINGUISHING_HASH_LENGTH _distinguishingHash = new byte[DISTINGUISHING_HASH_LENGTH]; System.arraycopy(principalInfoNameComponent, pos, _distinguishingHash, 0, _distinguishingHash.length); pos += _distinguishingHash.length; pos += CCNProfile.COMPONENT_SEPARATOR.length; // friendly name until the next COMPONENT_SEPARATOR // We only check for the first byte of COMPONENT_SEPARATOR // since that byte is known to not appear in a friendly name int fnLength = 0; while (principalInfoNameComponent[pos + fnLength] != CCNProfile.COMPONENT_SEPARATOR[0]) fnLength++; byte[] friendlyNameBytes = new byte[fnLength]; System.arraycopy(principalInfoNameComponent, pos, friendlyNameBytes, 0, fnLength); _friendlyName = ContentName.componentPrintNative(friendlyNameBytes); pos += fnLength; pos += CCNProfile.COMPONENT_SEPARATOR.length; // the rest is the timestamp byte[] timestampBytes = new byte[principalInfoNameComponent.length - pos]; System.arraycopy(principalInfoNameComponent, pos, timestampBytes, 0, timestampBytes.length); _versionTimestamp = new CCNTime(timestampBytes); } catch (Exception e) { // we're having some trouble here... Log.severe(Log.FAC_ACCESSCONTROL, "PrincipalInfo: error in parsing component {0}", ContentName.componentPrintURI(principalInfoNameComponent)); Log.severe(Log.FAC_ACCESSCONTROL, "PrincipalInfo: typeMarker {0}, distinguishing hash {1}, friendly name {2}, timestamp {3}", ContentName.componentPrintURI(_typeMarker), ContentName.componentPrintURI(_distinguishingHash), _friendlyName, _versionTimestamp); System.exit(1); } } /** * Principal names for links to wrapped key blocks take the form: * {GROUP_PRINCIPAL_PREFIX | PRINCIPAL_PREFIX} COMPONENT_SEPARATOR distinguisingHash COMPONENT_SEPARATOR friendlName COMPONENT_SEPARATOR timestamp as 12-bit binary * This allows a single enumeration of a wrapped key directory to determine * not only which principals the keys are wrapped for, but also what versions of their * private keys the keys are wrapped under (also determinable from the contents of the * wrapped key blocks, but to do that you have to pull the wrapped key block). * These serve as the name of a link to the actual wrapped key block. */ public byte[] toNameComponent() { byte [] prefix = (isGroup() ? GROUP_PRINCIPAL_PREFIX : USER_PRINCIPAL_PREFIX); byte [] bytePrincipal = ContentName.componentParseNative(friendlyName()); byte [] byteTime = versionTimestamp().toBinaryTime(); byte [] component = new byte[prefix.length + distinguishingHash().length + bytePrincipal.length + byteTime.length + 3*COMPONENT_SEPARATOR.length]; // java 1.6 has much better functions for array copying int offset = 0; System.arraycopy(prefix, 0, component, offset, prefix.length); offset += prefix.length; System.arraycopy(COMPONENT_SEPARATOR, 0, component, offset, COMPONENT_SEPARATOR.length); offset += COMPONENT_SEPARATOR.length; System.arraycopy(distinguishingHash(), 0, component, offset, distinguishingHash().length); offset += distinguishingHash().length; System.arraycopy(COMPONENT_SEPARATOR, 0, component, offset, COMPONENT_SEPARATOR.length); offset += COMPONENT_SEPARATOR.length; System.arraycopy(bytePrincipal, 0, component, offset, bytePrincipal.length); offset += bytePrincipal.length; System.arraycopy(COMPONENT_SEPARATOR, 0, component, offset, COMPONENT_SEPARATOR.length); offset += COMPONENT_SEPARATOR.length; System.arraycopy(byteTime, 0, component, offset, byteTime.length); return component; } /** * Parses the principal name from a group public key. * For groups, the last component of the public key is GROUP_PUBLIC_KEY_NAME = "Key". * The principal name is the one-before-last component. * @param publicKeyName the name of the group public key * @return the corresponding principal name */ public static String parsePrincipalNameFromGroupPublicKeyName(ContentName publicKeyName) { ContentName cn = VersioningProfile.cutTerminalVersion(publicKeyName).first(); return ContentName.componentPrintNative(cn.component(cn.count() - 2)); } /** * Parses the principal name from a public key name. * Do not use this method for group public keys. * For groups, use instead parsePrincipalNameFromGroupPublicKeyName * @param publicKeyName the public key name * @return the corresponding principal name */ public static String parsePrincipalNameFromPublicKeyName(ContentName publicKeyName) { return ContentName.componentPrintNative(VersioningProfile.cutTerminalVersion(publicKeyName).first().lastComponent()); } public boolean isGroup() { return Arrays.areEqual(GROUP_PRINCIPAL_PREFIX, _typeMarker); } public String friendlyName() { return _friendlyName; } public byte[] distinguishingHash() { return _distinguishingHash; } public CCNTime versionTimestamp() { return _versionTimestamp; } /** * Returns whether a specified name component is the name of a principal * @param nameComponent the name component * @return */ public static boolean isPrincipalNameComponent(byte [] nameComponent) { return (DataUtils.isBinaryPrefix(GroupAccessControlProfile.USER_PRINCIPAL_PREFIX, nameComponent) || DataUtils.isBinaryPrefix(GroupAccessControlProfile.GROUP_PRINCIPAL_PREFIX, nameComponent)); } /** * A first stab * @throws ContentEncodingException */ public static byte [] contentPrefixToDistinguishingHash(ContentName name) throws ContentEncodingException { byte [] fullDigest = CCNDigestHelper.digest(name.encode()); // Ensure that the distinguishing hash is always exactly of length DISTINGUISHING_HASH_LENGTH // to enable correct parsing of a byte[] representing a PrincipalInfo if (fullDigest.length > DISTINGUISHING_HASH_LENGTH) { byte [] returnedDigest = new byte[DISTINGUISHING_HASH_LENGTH]; System.arraycopy(fullDigest, 0, returnedDigest, 0, DISTINGUISHING_HASH_LENGTH); return returnedDigest; } else if (fullDigest.length < DISTINGUISHING_HASH_LENGTH) { byte [] returnedDigest = new byte[DISTINGUISHING_HASH_LENGTH]; System.arraycopy(fullDigest, 0, returnedDigest, 0, fullDigest.length); return returnedDigest; } return fullDigest; } } /** * Returns whether the specified name is the name of a node key * @param name the name * @return */ public static boolean isNodeKeyName(ContentName name) { if (!isAccessName(name) || !VersioningProfile.hasTerminalVersion(name)) { return false; } int versionComponent = VersioningProfile.findLastVersionComponent(name); if (name.stringComponent(versionComponent - 1).equals(NODE_KEY_NAME)) { return true; } return false; } /** * Get the name of the node key for a given content node, if there is one. * This is nodeName/<access marker>/NK, with a version then added for a specific node key. * @param nodeName the name of the content node * @return the name of the corresponding node key */ public static ContentName nodeKeyName(ContentName nodeName) { ContentName rootName = accessRoot(nodeName); ContentName nodeKeyName = new ContentName(rootName, ACCESS_CONTROL_MARKER_BYTES, NODE_KEY_NAME_BYTES); return nodeKeyName; } /** * Get the name of the access control list (ACL) for a given content node. * This is nodeName/<access marker>/ACL. * @param nodeName the name of the content node * @return the name of the corresponding ACL */ public static ContentName aclName(ContentName nodeName) { ContentName baseName = accessRoot(nodeName); return baseName.append(aclPostfix()); } public static ContentName aclPostfix() { return ACL_POSTFIX; } /** * Get the name of the user namespace. * This assumes a top-level namespace, where the group information is stored in * namespace/Groups and namespace/Users.. * @param namespace the top-level name space * @return the name of the user namespace */ public static ContentName userNamespaceName(ContentName namespace) { return new ContentName(accessRoot(namespace), USER_PREFIX_BYTES); } /** * Get the name of the namespace for a specified user. * @param userNamespace the name of the user namespace * @param userName the user name * @return the name of the namespace for the user */ public static ContentName userNamespaceName(ContentName userNamespace, String userName) { return ContentName.fromNative(userNamespace, userName); } /** * Get the name of the group namespace. * This assumes a top-level namespace, where the group information is stored in * namespace/Groups and namespace/Users.. * @param namespace the top-level name space * @return the name of the group namespace */ public static ContentName groupNamespaceName(ContentName namespace) { return new ContentName(accessRoot(namespace), GROUP_PREFIX_BYTES); } /** * Get the name of the namespace for a specified group. * @param namespace the top-level namespace * @param groupFriendlyName the name of the group * @return the name of the namespace for the group */ public static ContentName groupName(ContentName namespace, String groupFriendlyName) { return ContentName.fromNative(groupNamespaceName(namespace), groupFriendlyName); } /** * Get the name of a group public key. * This is the unversioned root. The actual public key is stored at the latest version of * this name. The private key and decoding blocks are stored under that version, with * the segments of the group public key. * @param groupNamespaceName the namespace of the group * @param groupFriendlyName the name of the group * @return the name of the group public key */ public static ContentName groupPublicKeyName(ContentName groupNamespaceName, String groupFriendlyName) { return ContentName.fromNative(ContentName.fromNative(groupNamespaceName, groupFriendlyName), AccessControlProfile.GROUP_PUBLIC_KEY_NAME); } /** * Get the name of the public key of a group specified by its full name * @param groupFullName the full name of the group * @return the name of the group public key */ public static ContentName groupPublicKeyName(ContentName groupFullName) { return ContentName.fromNative(groupFullName, AccessControlProfile.GROUP_PUBLIC_KEY_NAME); } /** * Get the name of a group membership list for a specified group * @param groupNamespaceName the namespace of the group * @param groupFriendlyName the name of the group * @return the name of the group membership list */ public static ContentName groupMembershipListName(ContentName groupNamespaceName, String groupFriendlyName) { return ContentName.fromNative(ContentName.fromNative(groupNamespaceName, groupFriendlyName), GROUP_MEMBERSHIP_LIST_NAME); } /** * Get the friendly name of a specified group * @param groupName the full name of the group * @return the friendly name of the group */ public static String groupNameToFriendlyName(ContentName groupName) { return ContentName.componentPrintNative(groupName.lastComponent()); } /** * Get the name of a group private key. * We hang the wrapped private key directly off the public key version. * @param groupPublicKeyNameAndVersion the versioned name of the group public key * @return the versioned name of the group private key */ public static ContentName groupPrivateKeyDirectory(ContentName groupPublicKeyNameAndVersion) { return groupPublicKeyNameAndVersion; } public static ContentName groupPointerToParentGroupName(ContentName groupFullName) { return ContentName.fromNative(groupFullName, GROUP_POINTER_TO_PARENT_GROUP_NAME); } }
package org.ccnx.ccn.test.profiles.security.access.group; import java.io.IOException; import java.security.Key; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.util.ArrayList; import java.util.Comparator; import java.util.Random; import java.util.TreeSet; import javax.crypto.KeyGenerator; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.impl.security.crypto.CCNDigestHelper; import org.ccnx.ccn.impl.support.ByteArrayCompare; import org.ccnx.ccn.io.content.Link; import org.ccnx.ccn.io.content.WrappedKey; import org.ccnx.ccn.io.content.WrappedKey.WrappedKeyObject; import org.ccnx.ccn.profiles.VersioningProfile; import org.ccnx.ccn.profiles.security.access.group.Group; import org.ccnx.ccn.profiles.security.access.group.GroupAccessControlManager; import org.ccnx.ccn.profiles.security.access.group.GroupAccessControlProfile; import org.ccnx.ccn.profiles.security.access.group.PrincipalKeyDirectory; import org.ccnx.ccn.protocol.ContentName; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public class KeyDirectoryTestRepo { static Random rand = new Random(); static final String directoryBase = "/test"; static final String keyDirectoryBase = "/test/KeyDirectoryTestRepo-"; static ContentName keyDirectoryName; static ContentName userStore; static String principalName = "pgolle-"; static ContentName publicKeyName; static ContentName versionedDirectoryName; static PrivateKey wrappedPrivateKey; static Key AESSecretKey; static KeyPair wrappingKeyPair; static byte[] wrappingPKID; static GroupAccessControlManager acm; class TestPrincipalKeyDirectory extends PrincipalKeyDirectory { public TestPrincipalKeyDirectory() throws IOException { super(acm, versionedDirectoryName, handle); } /* * Retrieve the wrapped key from the KD by principalName. * As above, the key is unwrapped and we check that the result is as expected. * */ public void testGetWrappedKeyForPrincipal() throws Exception { // unwrap the key and check that the unwrapped secret key is correct WrappedKeyObject wko = kd.getWrappedKeyForPrincipal(principalName); Assert.assertNotNull(wko); WrappedKey wk = wko.wrappedKey(); Key unwrappedSecretKey = wk.unwrapKey(wrappingKeyPair.getPrivate()); Assert.assertEquals(AESSecretKey, unwrappedSecretKey); } } static TestPrincipalKeyDirectory kd; static int testCount = 0; static CCNHandle handle; @AfterClass public static void tearDownAfterClass() throws Exception { kd.stopEnumerating(); handle.close(); } @BeforeClass public static void setUpBeforeClass() throws Exception { // randomize names to minimize stateful effects of ccnd/repo caches. keyDirectoryName = ContentName.fromNative(keyDirectoryBase + Integer.toString(rand.nextInt(10000))); principalName = principalName + Integer.toString(rand.nextInt(10000)); handle = CCNHandle.open(); ContentName cnDirectoryBase = ContentName.fromNative(directoryBase); ContentName groupStore = GroupAccessControlProfile.groupNamespaceName(cnDirectoryBase); userStore = ContentName.fromNative(cnDirectoryBase, "Users"); acm = new GroupAccessControlManager(cnDirectoryBase, groupStore, userStore); versionedDirectoryName = VersioningProfile.addVersion(keyDirectoryName); } /** * Ensures that the tests run in the correct order. * @throws Exception */ @Test public void testInOrder() throws Exception { testKeyDirectoryCreation(); testAddPrivateKey(); testGetUnwrappedKeyGroupMember(); testAddWrappedKey(); addWrappingKeyToACM(); testGetWrappedKeyForKeyID(); kd.testGetWrappedKeyForPrincipal(); testGetUnwrappedKey(); testGetPrivateKey(); testGetUnwrappedKeySuperseded(); testAddPreviousKeyBlock(); } /* * Create a new versioned KeyDirectory */ public void testKeyDirectoryCreation() throws Exception { kd = new TestPrincipalKeyDirectory(); // verify that the keyDirectory is created Assert.assertNotNull(kd); } public void testAddPrivateKey() throws Exception { // generate a private key to wrap KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); wrappingKeyPair = kpg.generateKeyPair(); wrappedPrivateKey = wrappingKeyPair.getPrivate(); // generate a AES wrapping key KeyGenerator kg = KeyGenerator.getInstance("AES"); AESSecretKey = kg.generateKey(); // add private key block kd.addPrivateKeyBlock(wrappedPrivateKey, AESSecretKey); kd.waitForChildren(); // this was the first add; need to wait till we have any data, hopefully NE responder will fast path Assert.assertTrue(kd.hasPrivateKeyBlock()); } /* * Unwrap the private key via membership in a group */ public void testGetUnwrappedKeyGroupMember() throws Exception { ContentName myIdentity = ContentName.fromNative(userStore, "pgolle"); acm.publishMyIdentity(myIdentity, null); // add myself to a newly created group String randomGroupName = "testGroup" + rand.nextInt(10000); ArrayList<Link> newMembers = new ArrayList<Link>(); newMembers.add(new Link(myIdentity)); Group myGroup = acm.groupManager().createGroup(randomGroupName, newMembers, 0); Assert.assertTrue(acm.groupManager().haveKnownGroupMemberships()); Thread.sleep(2000); // FIXME: this delay is necessary for the repo-write to complete // it should not be needed, as the data should be available locally. PrincipalKeyDirectory pkd = myGroup.privateKeyDirectory(acm); pkd.waitForChildren(); Assert.assertTrue(pkd.hasPrivateKeyBlock()); // add to the KeyDirectory the secret key wrapped in the public key ContentName versionDirectoryName2 = VersioningProfile.addVersion( ContentName.fromNative(keyDirectoryBase + Integer.toString(rand.nextInt(10000)) )); PrincipalKeyDirectory kd2 = new PrincipalKeyDirectory(acm, versionDirectoryName2, handle); PublicKey groupPublicKey = myGroup.publicKey(); ContentName groupPublicKeyName = myGroup.publicKeyName(); kd2.addWrappedKeyBlock(AESSecretKey, groupPublicKeyName, groupPublicKey); // retrieve the secret key byte[] expectedKeyID = CCNDigestHelper.digest(AESSecretKey.getEncoded()); kd2.waitForChildren(); Thread.sleep(10000); Key unwrappedSecretKey = kd2.getUnwrappedKey(expectedKeyID); Assert.assertEquals(AESSecretKey, unwrappedSecretKey); kd2.stopEnumerating(); } /* * Wraps the AES key in an RSA wrapping key * and adds the wrapped key to the KeyDirectory */ public void testAddWrappedKey() throws Exception { // generate a public key to wrap KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); wrappingKeyPair = kpg.generateKeyPair(); PublicKey publicKey = wrappingKeyPair.getPublic(); wrappingPKID = CCNDigestHelper.digest(publicKey.getEncoded()); publicKeyName = ContentName.fromNative(userStore, principalName); ContentName versionPublicKeyName = VersioningProfile.addVersion(publicKeyName); // add to the KeyDirectory the secret key wrapped in the public key kd.addWrappedKeyBlock(AESSecretKey, versionPublicKeyName, publicKey); } /* * Adds the wrapping key to the AccessControlManager. */ public void addWrappingKeyToACM() throws Exception { PrivateKey privKey = wrappingKeyPair.getPrivate(); byte[] publicKeyIdentifier = CCNDigestHelper.digest(wrappingKeyPair.getPublic().getEncoded()); handle.keyManager().getSecureKeyCache().addMyPrivateKey(publicKeyIdentifier, privKey); } /* * Create a new (unversioned) KeyDirectory object with the same * directory name as above. Check that the constructor retrieves the latest * version of the KeyDirectory. * Retrieve the wrapped key from the KeyDirectory by its KeyID, * unwrap it, and check that the secret key retrieved is as expected. * */ public void testGetWrappedKeyForKeyID() throws Exception { CCNHandle handle = CCNHandle.open(); // Use unversioned constructor so KeyDirectory returns the latest version PrincipalKeyDirectory uvkd = new PrincipalKeyDirectory(acm, keyDirectoryName, handle); while (!uvkd.hasChildren() || uvkd.getCopyOfWrappingKeyIDs().size() == 0) { uvkd.waitForNewChildren(); } // check the ID of the wrapping key TreeSet<byte[]> wkid = uvkd.getCopyOfWrappingKeyIDs(); Assert.assertEquals(1, wkid.size()); Comparator<byte[]> byteArrayComparator = new ByteArrayCompare(); Assert.assertEquals(0, byteArrayComparator.compare(wkid.first(), wrappingPKID)); // check name ContentName wkName = uvkd.getWrappedKeyNameForKeyID(wrappingPKID); Assert.assertNotNull(wkName); // unwrap the key and check that the unwrapped secret key is correct WrappedKeyObject wko = uvkd.getWrappedKeyForKeyID(wrappingPKID); WrappedKey wk = wko.wrappedKey(); Key unwrappedSecretKey = wk.unwrapKey(wrappingKeyPair.getPrivate()); Assert.assertEquals(AESSecretKey, unwrappedSecretKey); uvkd.stopEnumerating(); } /* * Retrieve the wrapped key directly from the KD * and check that the result is as expected. * */ public void testGetUnwrappedKey() throws Exception { byte[] expectedKeyID = CCNDigestHelper.digest(AESSecretKey.getEncoded()); Key unwrappedSecretKey = kd.getUnwrappedKey(expectedKeyID); Assert.assertEquals(AESSecretKey, unwrappedSecretKey); } /* * Retrieve the private key from KD and check the result */ public void testGetPrivateKey() throws Exception { Assert.assertTrue(kd.hasPrivateKeyBlock()); PrivateKey privKey = kd.getPrivateKey(); Assert.assertEquals(wrappedPrivateKey, privKey); } /* * Create an "old" key directory, which is superseded by the kd created above * Check that the unwrappedKey for the old superseded KD can be obtained. */ public void testGetUnwrappedKeySuperseded() throws Exception { // create a superseded key directory ContentName supersededKeyDirectoryName = ContentName.fromNative(keyDirectoryBase + rand.nextInt(10000) + "/superseded"); ContentName versionSupersededKeyDirectoryName = VersioningProfile.addVersion(supersededKeyDirectoryName); CCNHandle handle = CCNHandle.open(); PrincipalKeyDirectory skd = new PrincipalKeyDirectory(acm, versionSupersededKeyDirectoryName, handle); // generate a AES wrapping key KeyGenerator kg = KeyGenerator.getInstance("AES"); Key supersededAESSecretKey = kg.generateKey(); byte[] expectedKeyID = CCNDigestHelper.digest(supersededAESSecretKey.getEncoded()); // add a superseded block ContentName supersedingKeyName = keyDirectoryName; skd.addSupersededByBlock(supersededAESSecretKey, supersedingKeyName, null, AESSecretKey); while (!skd.hasChildren() || !skd.hasSupersededBlock()) skd.waitForNewChildren(); Assert.assertTrue(skd.hasSupersededBlock()); Assert.assertNotNull(skd.getSupersededBlockName()); // get unwrapped key for superseded KD Key unwrappedSecretKey = skd.getUnwrappedKey(expectedKeyID); Assert.assertEquals(supersededAESSecretKey, unwrappedSecretKey); skd.stopEnumerating(); } /* * Add a previous key block */ public void testAddPreviousKeyBlock() throws Exception { Assert.assertTrue(! kd.hasPreviousKeyBlock()); // generate a new AES wrapping key KeyGenerator kg = KeyGenerator.getInstance("AES"); Key newAESSecretKey = kg.generateKey(); ContentName supersedingKeyName = ContentName.fromNative(keyDirectoryBase + "previous"); kd.addPreviousKeyBlock(AESSecretKey, supersedingKeyName, newAESSecretKey); kd.waitForNewChildren(); Assert.assertTrue(kd.hasPreviousKeyBlock()); } }
package com.hp.octane.plugins.jenkins.events; import com.google.inject.Inject; import com.hp.octane.integrations.dto.DTOFactory; import com.hp.octane.integrations.dto.events.CIEvent; import com.hp.octane.integrations.dto.events.CIEventType; import com.hp.octane.integrations.dto.events.PhaseType; import com.hp.octane.integrations.dto.pipelines.PipelineNode; import com.hp.octane.integrations.dto.pipelines.PipelinePhase; import com.hp.octane.integrations.dto.snapshots.CIBuildResult; import com.hp.octane.plugins.jenkins.model.CIEventCausesFactory; import com.hp.octane.plugins.jenkins.model.processors.builders.WorkFlowRunProcessor; import com.hp.octane.plugins.jenkins.model.processors.parameters.ParameterProcessors; import com.hp.octane.plugins.jenkins.model.processors.projects.AbstractProjectProcessor; import com.hp.octane.plugins.jenkins.model.processors.scm.SCMProcessor; import com.hp.octane.plugins.jenkins.model.processors.scm.SCMProcessors; import com.hp.octane.plugins.jenkins.tests.TestListener; import com.hp.octane.plugins.jenkins.tests.gherkin.GherkinEventsService; import hudson.Extension; import hudson.matrix.MatrixConfiguration; import hudson.matrix.MatrixRun; import hudson.model.*; import hudson.model.listeners.RunListener; import jenkins.model.Jenkins; import javax.annotation.Nonnull; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; @Extension public final class RunListenerImpl extends RunListener<Run> { private static final DTOFactory dtoFactory = DTOFactory.getInstance(); private ExecutorService executor = new ThreadPoolExecutor(0, 5, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); @Inject private TestListener testListener; @Override public void onStarted(final Run r, TaskListener listener) { CIEvent event; if (r.getClass().getName().equals("org.jenkinsci.plugins.workflow.job.WorkflowRun")) { event = dtoFactory.newDTO(CIEvent.class) .setEventType(CIEventType.STARTED) .setProject(r.getParent().getName()) .setBuildCiId(String.valueOf(r.getNumber())) .setNumber(String.valueOf(r.getNumber())) .setStartTime(r.getStartTimeInMillis()) .setPhaseType(PhaseType.POST) .setEstimatedDuration(r.getEstimatedDuration()) .setCauses(CIEventCausesFactory.processCauses(extractCauses(r))); EventsService.getExtensionInstance().dispatchEvent(event); WorkFlowRunProcessor workFlowRunProcessor = new WorkFlowRunProcessor(r); workFlowRunProcessor.registerEvents(executor); } else { if (r.getParent() instanceof MatrixConfiguration) { AbstractBuild build = (AbstractBuild) r; event = dtoFactory.newDTO(CIEvent.class) .setEventType(CIEventType.STARTED) .setProject(((MatrixRun) r).getParentBuild().getParent().getName()) .setProjectDisplayName(((MatrixRun) r).getParentBuild().getParent().getName()) .setBuildCiId(String.valueOf(build.getNumber())) .setNumber(String.valueOf(build.getNumber())) .setStartTime(build.getStartTimeInMillis()) .setEstimatedDuration(build.getEstimatedDuration()) .setCauses(CIEventCausesFactory.processCauses(extractCauses(build))) .setParameters(ParameterProcessors.getInstances(build)); EventsService.getExtensionInstance().dispatchEvent(event); } else if (r instanceof AbstractBuild) { AbstractBuild build = (AbstractBuild) r; event = dtoFactory.newDTO(CIEvent.class) .setEventType(CIEventType.STARTED) .setProject(build.getProject().getName()) .setProjectDisplayName(build.getProject().getName()) .setBuildCiId(String.valueOf(build.getNumber())) .setNumber(String.valueOf(build.getNumber())) .setStartTime(build.getStartTimeInMillis()) .setEstimatedDuration(build.getEstimatedDuration()) .setCauses(CIEventCausesFactory.processCauses(extractCauses(build))) .setParameters(ParameterProcessors.getInstances(build)); if (isInternal(r)) { event.setPhaseType(PhaseType.INTERNAL); } else { event.setPhaseType(PhaseType.POST); } EventsService.getExtensionInstance().dispatchEvent(event); } } } private boolean isInternal(Run r) { try { Cause.UpstreamCause cause = (Cause.UpstreamCause) r.getCauses().get(0); String causeJobName = cause.getUpstreamProject(); TopLevelItem currentJobParent = Jenkins.getInstance().getItem(causeJobName); // for Pipeline As A Code Plugin if (currentJobParent.getClass().getName().equals("org.jenkinsci.plugins.workflow.job.WorkflowJob")) { return true; } // for MultiJob or Matrix Plugin if (currentJobParent.getClass().getName().equals("com.tikal.jenkins.plugins.multijob.MultiJobProject") || currentJobParent.getClass().getName().equals("hudson.matrix.MatrixProject")) { List<PipelinePhase> phases = AbstractProjectProcessor.getFlowProcessor(((AbstractProject) currentJobParent)).getInternals(); for (PipelinePhase p : phases) { for (PipelineNode n : p.getJobs()) { if (n.getName().equals(r.getParent().getName())) { return true; } } } return false; } return false; // Elsewhere } catch (ClassCastException e) { return false; // happens only in the root node } } @Override public void onCompleted(Run r, @Nonnull TaskListener listener) { CIBuildResult result; if (r.getResult() == Result.SUCCESS) { result = CIBuildResult.SUCCESS; } else if (r.getResult() == Result.ABORTED) { result = CIBuildResult.ABORTED; } else if (r.getResult() == Result.FAILURE) { result = CIBuildResult.FAILURE; } else if (r.getResult() == Result.UNSTABLE) { result = CIBuildResult.UNSTABLE; } else { result = CIBuildResult.UNAVAILABLE; } if (r instanceof AbstractBuild) { AbstractBuild build = (AbstractBuild) r; SCMProcessor scmProcessor = SCMProcessors.getAppropriate(build.getProject().getScm().getClass().getName()); CIEvent event = dtoFactory.newDTO(CIEvent.class) .setEventType(CIEventType.FINISHED) .setProject(getProjectName(r)) .setProjectDisplayName(getProjectName(r)) .setBuildCiId(String.valueOf(build.getNumber())) .setNumber(String.valueOf(build.getNumber())) .setStartTime(build.getStartTimeInMillis()) .setEstimatedDuration(build.getEstimatedDuration()) .setCauses(CIEventCausesFactory.processCauses(extractCauses(build))) .setParameters(ParameterProcessors.getInstances(build)) .setResult(result) .setScmData(scmProcessor == null ? null : scmProcessor.getSCMData(build)) .setDuration(build.getDuration()); EventsService.getExtensionInstance().dispatchEvent(event); GherkinEventsService.copyGherkinTestResultsToBuildDir(build); testListener.processBuild(build, listener); } else if (r.getClass().getName().equals("org.jenkinsci.plugins.workflow.job.WorkflowRun")) { CIEvent event = dtoFactory.newDTO(CIEvent.class) .setEventType(CIEventType.FINISHED) .setProject(getProjectName(r)) .setBuildCiId(String.valueOf(r.getNumber())) .setNumber(String.valueOf(r.getNumber())) .setStartTime(r.getStartTimeInMillis()) .setEstimatedDuration(r.getEstimatedDuration()) .setCauses(CIEventCausesFactory.processCauses(extractCauses(r))) .setResult(result) .setDuration(r.getDuration()); EventsService.getExtensionInstance().dispatchEvent(event); } } private String getProjectName(Run r) { if (r.getParent() instanceof MatrixConfiguration) { return ((MatrixRun) r).getParentBuild().getParent().getName(); } if (r.getParent().getClass().getName().equals("org.jenkinsci.plugins.workflow.job.WorkflowJob")) { return r.getParent().getName(); } return ((AbstractBuild) r).getProject().getName(); } private List<Cause> extractCauses(Run r) { if (r.getParent() instanceof MatrixConfiguration) { return ((MatrixRun) r).getParentBuild().getCauses(); } else { return r.getCauses(); } } }
package org.ihtsdo.otf.mapping.jpa.services; import java.util.ArrayList; 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.NoSuchElementException; import java.util.Properties; import java.util.Set; import javax.persistence.NoResultException; import org.apache.log4j.Logger; import org.apache.lucene.util.Version; import org.hibernate.CacheMode; import org.hibernate.search.jpa.FullTextEntityManager; import org.hibernate.search.jpa.Search; import org.ihtsdo.otf.mapping.helpers.FeedbackConversationList; import org.ihtsdo.otf.mapping.helpers.FeedbackConversationListJpa; import org.ihtsdo.otf.mapping.helpers.FeedbackList; import org.ihtsdo.otf.mapping.helpers.FeedbackListJpa; import org.ihtsdo.otf.mapping.helpers.LocalException; import org.ihtsdo.otf.mapping.helpers.MapRecordList; import org.ihtsdo.otf.mapping.helpers.MapUserList; import org.ihtsdo.otf.mapping.helpers.MapUserListJpa; import org.ihtsdo.otf.mapping.helpers.MapUserRole; import org.ihtsdo.otf.mapping.helpers.PfsParameter; import org.ihtsdo.otf.mapping.helpers.PfsParameterJpa; import org.ihtsdo.otf.mapping.helpers.ProjectSpecificAlgorithmHandler; import org.ihtsdo.otf.mapping.helpers.SearchResult; import org.ihtsdo.otf.mapping.helpers.SearchResultList; import org.ihtsdo.otf.mapping.helpers.TrackingRecordList; import org.ihtsdo.otf.mapping.helpers.TrackingRecordListJpa; import org.ihtsdo.otf.mapping.helpers.TreePositionList; import org.ihtsdo.otf.mapping.helpers.ValidationResult; import org.ihtsdo.otf.mapping.helpers.ValidationResultJpa; import org.ihtsdo.otf.mapping.helpers.WorkflowAction; import org.ihtsdo.otf.mapping.helpers.WorkflowPath; import org.ihtsdo.otf.mapping.helpers.WorkflowStatus; import org.ihtsdo.otf.mapping.helpers.WorkflowType; import org.ihtsdo.otf.mapping.jpa.FeedbackConversationJpa; import org.ihtsdo.otf.mapping.jpa.FeedbackJpa; import org.ihtsdo.otf.mapping.jpa.MapRecordJpa; import org.ihtsdo.otf.mapping.jpa.handlers.AbstractWorkflowPathHandler; import org.ihtsdo.otf.mapping.jpa.handlers.WorkflowFixErrorPathHandler; import org.ihtsdo.otf.mapping.jpa.handlers.WorkflowNonLegacyPathHandler; import org.ihtsdo.otf.mapping.jpa.handlers.WorkflowQaPathHandler; import org.ihtsdo.otf.mapping.jpa.handlers.WorkflowReviewProjectPathHandler; import org.ihtsdo.otf.mapping.model.Feedback; import org.ihtsdo.otf.mapping.model.FeedbackConversation; import org.ihtsdo.otf.mapping.model.MapNote; import org.ihtsdo.otf.mapping.model.MapProject; import org.ihtsdo.otf.mapping.model.MapRecord; import org.ihtsdo.otf.mapping.model.MapUser; import org.ihtsdo.otf.mapping.reports.Report; import org.ihtsdo.otf.mapping.reports.ReportResultItem; import org.ihtsdo.otf.mapping.rf2.Concept; import org.ihtsdo.otf.mapping.services.ContentService; import org.ihtsdo.otf.mapping.services.WorkflowService; import org.ihtsdo.otf.mapping.services.helpers.ConfigUtility; import org.ihtsdo.otf.mapping.services.helpers.WorkflowPathHandler; import org.ihtsdo.otf.mapping.workflow.TrackingRecord; import org.ihtsdo.otf.mapping.workflow.TrackingRecordJpa; import org.ihtsdo.otf.mapping.workflow.WorkflowException; import org.ihtsdo.otf.mapping.workflow.WorkflowExceptionJpa; /** * Default workflow service implementation. */ public class WorkflowServiceJpa extends MappingServiceJpa implements WorkflowService { /** * Instantiates an empty {@link WorkflowServiceJpa}. * * @throws Exception the exception */ public WorkflowServiceJpa() throws Exception { super(); } /* see superclass */ @Override public TrackingRecord addTrackingRecord(TrackingRecord trackingRecord) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.persist(trackingRecord); tx.commit(); } else { manager.persist(trackingRecord); } return trackingRecord; } /* see superclass */ @Override public void removeTrackingRecord(Long trackingRecordId) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); TrackingRecord ma = manager.find(TrackingRecordJpa.class, trackingRecordId); if (manager.contains(ma)) { manager.remove(ma); } else { manager.remove(manager.merge(ma)); } tx.commit(); } else { TrackingRecord ma = manager.find(TrackingRecordJpa.class, trackingRecordId); if (manager.contains(ma)) { manager.remove(ma); } else { manager.remove(manager.merge(ma)); } } } /* see superclass */ @Override public void removeFeedbackConversation(Long feedbackId) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); FeedbackConversation fa = manager.find(FeedbackConversationJpa.class, feedbackId); if (manager.contains(fa)) { manager.remove(fa); } else { manager.remove(manager.merge(fa)); } tx.commit(); } else { FeedbackConversation fa = manager.find(FeedbackConversationJpa.class, feedbackId); if (manager.contains(fa)) { manager.remove(fa); } else { manager.remove(manager.merge(fa)); } } } /* see superclass */ @Override public void removeFeedback(Long feedbackId) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); Feedback fa = manager.find(FeedbackJpa.class, feedbackId); final FeedbackConversation conv = fa.getFeedbackConversation(); conv.removeFeedback(fa); manager.merge(conv); tx.commit(); } else { Feedback fa = manager.find(FeedbackJpa.class, feedbackId); final FeedbackConversation conv = fa.getFeedbackConversation(); conv.removeFeedback(fa); manager.merge(conv); } } /* see superclass */ @Override public void updateTrackingRecord(TrackingRecord record) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.merge(record); tx.commit(); } else { manager.merge(record); } } /* see superclass */ @SuppressWarnings("unchecked") @Override public TrackingRecordList getTrackingRecords() throws Exception { TrackingRecordListJpa trackingRecordList = new TrackingRecordListJpa(); trackingRecordList.setTrackingRecords(manager .createQuery("select tr from TrackingRecordJpa tr").getResultList()); return trackingRecordList; } /* see superclass */ @Override public TrackingRecord getTrackingRecordForMapProjectAndConcept( MapProject mapProject, Concept concept) { try { return (TrackingRecord) manager .createQuery( "select tr from TrackingRecordJpa tr where mapProjectId = :mapProjectId and terminology = :terminology and terminologyVersion = :terminologyVersion and terminologyId = :terminologyId") .setParameter("mapProjectId", mapProject.getId()) .setParameter("terminology", concept.getTerminology()) .setParameter("terminologyVersion", concept.getTerminologyVersion()) .setParameter("terminologyId", concept.getTerminologyId()) .getSingleResult(); } catch (Exception e) { return null; } } /* see superclass */ @Override public TrackingRecord getTrackingRecordForMapProjectAndConcept( MapProject mapProject, String terminologyId) { try { return (TrackingRecord) manager .createQuery( "select tr from TrackingRecordJpa tr where mapProjectId = :mapProjectId and terminology = :terminology and terminologyVersion = :terminologyVersion and terminologyId = :terminologyId") .setParameter("mapProjectId", mapProject.getId()) .setParameter("terminology", mapProject.getSourceTerminology()) .setParameter("terminologyVersion", mapProject.getSourceTerminologyVersion()) .setParameter("terminologyId", terminologyId).getSingleResult(); } catch (Exception e) { return null; } } /* see superclass */ @SuppressWarnings("unchecked") @Override public TrackingRecordList getTrackingRecordsForMapProject( MapProject mapProject) throws Exception { TrackingRecordListJpa trackingRecordList = new TrackingRecordListJpa(); javax.persistence.Query query = manager .createQuery( "select tr from TrackingRecordJpa tr where mapProjectId = :mapProjectId") .setParameter("mapProjectId", mapProject.getId()); trackingRecordList.setTrackingRecords(query.getResultList()); return trackingRecordList; } /* see superclass */ @Override public TrackingRecord getTrackingRecord(MapProject mapProject, String terminologyId) throws Exception { javax.persistence.Query query = manager .createQuery( "select tr from TrackingRecordJpa tr where mapProjectId = :mapProjectId and terminologyId = :terminologyId") .setParameter("mapProjectId", mapProject.getId()) .setParameter("terminologyId", terminologyId); return (TrackingRecord) query.getSingleResult(); } /* see superclass */ @Override public WorkflowException addWorkflowException( WorkflowException trackingRecord) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.persist(trackingRecord); tx.commit(); } else { manager.persist(trackingRecord); } return trackingRecord; } /* see superclass */ @Override public void removeWorkflowException(Long trackingRecordId) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); WorkflowException ma = manager.find(WorkflowExceptionJpa.class, trackingRecordId); if (manager.contains(ma)) { manager.remove(ma); } else { manager.remove(manager.merge(ma)); } tx.commit(); } else { WorkflowException ma = manager.find(WorkflowExceptionJpa.class, trackingRecordId); if (manager.contains(ma)) { manager.remove(ma); } else { manager.remove(manager.merge(ma)); } } } /* see superclass */ @Override public void updateWorkflowException(WorkflowException workflowException) throws Exception { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.merge(workflowException); tx.commit(); } else { manager.merge(workflowException); } } /* see superclass */ @Override public WorkflowException getWorkflowException(MapProject mapProject, String terminologyId) { final javax.persistence.Query query = manager .createQuery( "select we from WorkflowExceptionJpa we where mapProjectId = :mapProjectId" + " and terminology = :terminology and terminologyVersion = :terminologyVersion and terminologyId = :terminologyId") .setParameter("mapProjectId", mapProject.getId()) .setParameter("terminology", mapProject.getSourceTerminology()) .setParameter("terminologyVersion", mapProject.getSourceTerminologyVersion()) .setParameter("terminologyId", terminologyId); // try to get the expected single result try { return (WorkflowException) query.getSingleResult(); } catch (NoResultException e) { return null; } } /* see superclass */ @Override public void createQAWork(Report report) throws Exception { if (report.getResults() == null || report.getResults().size() != 1) { throw new Exception( "Failed to provide a report with one result set " + report.getId()); } Set<String> conceptIds = new HashSet<>(); for (final ReportResultItem resultItem : report.getResults().get(0) .getReportResultItems()) { conceptIds.add(resultItem.getItemId()); } // open the services ContentService contentService = new ContentServiceJpa(); // get the map project and concept MapProject mapProject = getMapProject(report.getMapProjectId()); // find the qa user MapUser mapUser = null; for (final MapUser user : getMapUsers().getMapUsers()) { if (user.getUserName().equals("qa")) mapUser = user; } for (final String conceptId : conceptIds) { final Concept concept = contentService.getConcept(conceptId, mapProject.getSourceTerminology(), mapProject.getSourceTerminologyVersion()); final MapRecordList recordList = getMapRecordsForProjectAndConcept(mapProject.getId(), conceptId); // lazy initialize recordList.getMapRecords().size(); for (final MapRecord mapRecord : recordList.getMapRecords()) { // set the label on the record mapRecord.addLabel(report.getReportDefinition().getName()); // process the workflow action - only if published/READY if (mapRecord.getWorkflowStatus().equals(WorkflowStatus.PUBLISHED) || mapRecord.getWorkflowStatus() .equals(WorkflowStatus.READY_FOR_PUBLICATION)) { processWorkflowAction(mapProject, concept, mapUser, mapRecord, WorkflowAction.CREATE_QA_RECORD); } } } contentService.close(); } /** * Perform workflow actions based on a specified action. * ASSIGN_FROM_INITIAL_RECORD is the only routine that requires a map record * to be passed in All other cases that all required mapping information (e.g. * map records) be current in the database (i.e. updateMapRecord has been * called) * * @param mapProject the map project * @param concept the concept * @param mapUser the map user * @param mapRecord the map record * @param workflowAction the workflow action * @throws Exception the exception */ @Override public void processWorkflowAction(MapProject mapProject, Concept concept, MapUser mapUser, MapRecord mapRecord, WorkflowAction workflowAction) throws Exception { Logger.getLogger(WorkflowServiceJpa.class) .info("Processing workflow action by " + mapUser.getName() + ": " + workflowAction.toString()); if (mapRecord != null) { Logger.getLogger(WorkflowServiceJpa.class) .info(" Record attached: " + mapRecord.getConceptId()); } // TODO: this is terrible - transaction scope should be managed externally // from here as this makes it very hard to do batch things. setTransactionPerOperation(true); // instantiate the algorithm handler for this project ProjectSpecificAlgorithmHandler algorithmHandler = (ProjectSpecificAlgorithmHandler) Class .forName(mapProject.getProjectSpecificAlgorithmHandlerClass()) .newInstance(); algorithmHandler.setMapProject(mapProject); // locate any existing workflow tracking records for this project and // concept // NOTE: Exception handling deliberate, since tracking record may or may // not exist // depending on workflow path TrackingRecord trackingRecord = null; try { trackingRecord = getTrackingRecord(mapProject, concept.getTerminologyId()); } catch (NoResultException e) { // do nothing (leave trackingRecord null) } // declare the validation result for existing tracking records ValidationResult result = null; // declare the workflow handler AbstractWorkflowPathHandler handler = null; // if no tracking record, create one (NOTE: Must be FIX_ERROR or QA // path) if (trackingRecord == null) { Logger.getLogger(this.getClass()).debug("Creating new tracking record"); // create a tracking record for this concept with no records or // users trackingRecord = new TrackingRecordJpa(); trackingRecord.setMapProjectId(mapProject.getId()); trackingRecord.setTerminology(concept.getTerminology()); trackingRecord.setTerminologyVersion(concept.getTerminologyVersion()); trackingRecord.setTerminologyId(concept.getTerminologyId()); trackingRecord.setDefaultPreferredName(concept.getDefaultPreferredName()); // This block of code is way too slow for any batch mode. trackingRecord.setSortKey(concept.getTerminologyId()); // // get the tree positions for this concept and set the sort key // // // to the first retrieved // final ContentService contentService = new ContentServiceJpa(); // try { // TreePositionList treePositionsList = contentService // .getTreePositionsWithDescendants(concept.getTerminologyId(), // concept.getTerminology(), concept.getTerminologyVersion()); // // handle inactive concepts - which don't have tree positions // if (treePositionsList.getCount() == 0) { // trackingRecord.setSortKey(""); // } else { // trackingRecord.setSortKey( // treePositionsList.getTreePositions().get(0).getAncestorPath()); // } catch (Exception e) { // throw e; // } finally { // contentService.close(); // if Qa Path, instantiate Qa Path handler if (workflowAction.equals(WorkflowAction.CREATE_QA_RECORD)) { handler = (AbstractWorkflowPathHandler) Class .forName(ConfigUtility.getConfigProperties() .getProperty("workflow.path.handler.QA_PATH.class")) .newInstance(); trackingRecord.setWorkflowPath(WorkflowPath.QA_PATH); } // otherwise, use Fix Error Path else { handler = (AbstractWorkflowPathHandler) Class .forName(ConfigUtility.getConfigProperties() .getProperty("workflow.path.handler.FIX_ERROR_PATH.class")) .newInstance(); trackingRecord.setWorkflowPath(WorkflowPath.FIX_ERROR_PATH); } } // otherwise, instantiate based on tracking record else { Logger.getLogger(WorkflowServiceJpa.class) .debug(" Tracking Record: " + trackingRecord.toString()); handler = (AbstractWorkflowPathHandler) Class .forName(ConfigUtility.getConfigProperties() .getProperty("workflow.path.handler." + trackingRecord.getWorkflowPath() + ".class")) .newInstance(); } if (handler == null) { throw new Exception("Could not determine workflow handler"); } // validate the tracking record by its handler result = handler.validateTrackingRecordForActionAndUser(trackingRecord, workflowAction, mapUser); // validation only run on retrieved tracking records (not constructed // ones) if (result != null && !result.isValid()) { Logger.getLogger(WorkflowServiceJpa.class).info(result.toString()); StringBuffer message = new StringBuffer(); message.append("Errors were detected in the workflow for:\n"); message.append(" Project\t: " + mapProject.getName() + "\n"); message.append(" Concept\t: " + concept.getTerminologyId() + "\n"); message.append( " Path:\t " + trackingRecord.getWorkflowPath().toString() + "\n"); message.append(" User\t: " + mapUser.getUserName() + "\n"); message.append(" Action\t: " + workflowAction.toString() + "\n"); message.append("\n"); // record information message.append("Records involved:\n"); message.append(" " + "id\tUser\tWorkflowStatus\n"); for (final MapRecord mr : getMapRecordsForTrackingRecord( trackingRecord)) { message.append( " " + mr.getId().toString() + "\t" + mr.getOwner().getUserName() + "\t" + mr.getWorkflowStatus().toString() + "\n"); } message.append("\n"); message.append("Errors reported:\n"); for (final String error : result.getErrors()) { message.append(" " + error + "\n"); } message.append("\n"); // log the message Logger.getLogger(WorkflowServiceJpa.class) .error("Workflow error detected\n" + message.toString()); // send email if indicated Properties config = ConfigUtility.getConfigProperties(); String notificationRecipients = config.getProperty("send.notification.recipients"); if (!notificationRecipients.isEmpty() && "true".equals(config.getProperty("mail.enabled"))) { String from; if (config.containsKey("mail.smtp.from")) { from = config.getProperty("mail.smtp.from"); } else { from = config.getProperty("mail.smtp.user"); } Properties props = new Properties(); props.put("mail.smtp.user", config.getProperty("mail.smtp.user")); props.put("mail.smtp.password", config.getProperty("mail.smtp.password")); props.put("mail.smtp.host", config.getProperty("mail.smtp.host")); props.put("mail.smtp.port", config.getProperty("mail.smtp.port")); props.put("mail.smtp.starttls.enable", config.getProperty("mail.smtp.starttls.enable")); props.put("mail.smtp.auth", config.getProperty("mail.smtp.auth")); ConfigUtility.sendEmail( mapProject.getName() + " Workflow Error Alert, Concept " + concept.getTerminologyId(), from, notificationRecipients, message.toString(), props, "true".equals(config.getProperty("mail.smtp.auth"))); } throw new LocalException("Workflow action " + workflowAction.toString() + " could not be performed on concept " + trackingRecord.getTerminologyId()); } Set<MapRecord> mapRecords = getMapRecordsForTrackingRecord(trackingRecord); // if the record passed in updates an existing record, replace it in the // set if (mapRecord != null && mapRecord.getId() != null) { for (final MapRecord mr : mapRecords) { if (mr.getId().equals(mapRecord.getId())) { mapRecords.remove(mr); mapRecords.add(mapRecord); break; } } } // process the workflow action mapRecords = handler.processWorkflowAction(trackingRecord, workflowAction, mapProject, mapUser, mapRecords, mapRecord); Logger.getLogger(WorkflowServiceJpa.class).debug("Synchronizing..."); // synchronize the map records via helper function Set<MapRecord> syncedRecords = synchronizeMapRecords(trackingRecord, mapRecords); // clear the pointer fields (i.e. ids and names of mapping // objects) trackingRecord.setMapRecordIds(new HashSet<Long>()); trackingRecord.setAssignedUserNames(null); trackingRecord.setUserAndWorkflowStatusPairs(null); // recalculate the pointer fields for (MapRecord mr : syncedRecords) { trackingRecord.addMapRecordId(mr.getId()); trackingRecord.addAssignedUserName(mr.getOwner().getUserName()); trackingRecord.addUserAndWorkflowStatusPair(mr.getOwner().getUserName(), mr.getWorkflowStatus().toString()); } Logger.getLogger(WorkflowServiceJpa.class) .info("Revised tracking record: " + trackingRecord.toString()); // if the tracking record is ready for removal, delete it if ((getWorkflowStatusForTrackingRecord(trackingRecord) .equals(WorkflowStatus.READY_FOR_PUBLICATION) || getWorkflowStatusForTrackingRecord(trackingRecord) .equals(WorkflowStatus.PUBLISHED)) && trackingRecord.getMapRecordIds().size() == 1) { Logger.getLogger(WorkflowServiceJpa.class) .debug(" Publication ready, removing tracking record."); removeTrackingRecord(trackingRecord.getId()); // else add the tracking record if new } else if (trackingRecord.getId() == null) { Logger.getLogger(WorkflowServiceJpa.class) .debug(" New workflow concept, adding tracking record."); addTrackingRecord(trackingRecord); // otherwise update the tracking record } else { Logger.getLogger(WorkflowServiceJpa.class) .debug(" Still in workflow, updating tracking record."); updateTrackingRecord(trackingRecord); } } /** * Algorithm has gotten needlessly complex due to conflicting service changes * and algorithm handler changes. However, the basic process is this: * * 1) Function takes a set of map records returned from the algorithm handler * These map records may have a hibernate id (updated/unchanged) or not * (added) 2) The passed map records are detached from the persistence * environment. 3) The existing (in database) records are re-retrieved from * the database. Note that this is why the passed map records are detached -- * otherwise they are overwritten. 4) Each record in the detached set is * checked against the 'refreshed' database record set - if the detached * record is not in the set, then it has been added - if the detached record * is in the set, check it for updates - if it has been changed, update it - * if no change, disregard 5) Each record in the 'refreshed' databased record * set is checked against the new set - if the refreshed record is not in the * new set, delete it from the database 6) Return the detached set as * re-synchronized with the database * * Note on naming conventions used in this method: - mapRecords: the set of * records passed in as argument - newRecords: The set of records to be * returned after synchronization - oldRecords: The set of records retrieved * by id from the database for comparison - syncedRecords: The synchronized * set of records for return from this routine * * @param trackingRecord the tracking record * @param mapRecords the map records * @return the sets the * @throws Exception the exception */ @Override public Set<MapRecord> synchronizeMapRecords(TrackingRecord trackingRecord, Set<MapRecord> mapRecords) throws Exception { Set<MapRecord> newRecords = new HashSet<>(); Set<MapRecord> oldRecords = new HashSet<>(); Set<MapRecord> syncedRecords = new HashSet<>(); // detach the currently persisted map records from the workflow service // to avoid overwrite by retrieval of existing records for (final MapRecord mr : mapRecords) { Logger.getLogger(this.getClass()).debug(" Map record attached: " + mr.getId() + ", " + mr.getWorkflowStatus()); manager.detach(mr); newRecords.add(mr); // ensure that all map records with ids are on the tracking record // NOTE: This was added after workflow refactoring to ensure that // FIX_ERROR_PATH and QA_PATH records were properly retrieved from // the database, despite the tracking record not yet // "containing" these records if (mr.getId() != null) { // map record ids is a set, simply add (no worry about // duplicates) trackingRecord.addMapRecordId(mr.getId()); } } // retrieve the old (existing) records if (trackingRecord.getMapRecordIds() != null) { for (final Long id : trackingRecord.getMapRecordIds()) { MapRecord oldRecord = getMapRecord(id); oldRecords.add(oldRecord); Logger.getLogger(this.getClass()) .debug(" Existing record retrieved: " + oldRecord.getId()); } } // cycle over new records to check for additions or updates for (final MapRecord mr : newRecords) { Logger.getLogger(WorkflowServiceJpa.class) .debug(" Checking attached record: " + mr.getId()); if (mr.getId() == null) { Logger.getLogger(WorkflowServiceJpa.class).debug(" Add record"); // deep copy the detached record into a new // persistence-environment record // this routine also duplicates child collections to avoid // detached object errors MapRecord newRecord = new MapRecordJpa(mr, false); // add the record to the database addMapRecord(newRecord); // add the record to the return list syncedRecords.add(newRecord); } // otherwise, check for update else { // if the old map record is changed, update it if (!mr.isEquivalent(getMapRecordInSet(oldRecords, mr.getId()))) { Logger.getLogger(WorkflowServiceJpa.class).debug(" Update record"); /* * Special handling for MapNotes based on mapRecordsMapNotes * N:M FK table. Without this, updates to an already persisted * map note will violate duplicate entry constraint on the table. */ Set<MapNote> notesToUpdate = mr.getMapNotes(); // Persist with clearing out the notes mr.setMapNotes(new HashSet<MapNote>()); updateMapRecord(mr); // Persist with all notes including updated ones mr.setMapNotes(notesToUpdate); updateMapRecord(mr); } else { Logger.getLogger(WorkflowServiceJpa.class) .debug(" Record unchanged"); } syncedRecords.add(mr); } } // cycle over old records to check for deletions for (final MapRecord mr : oldRecords) { Logger.getLogger(this.getClass()) .debug(" Checking for deleted records: " + mr.getId()); // if old record is not in the new record set, delete it if (getMapRecordInSet(syncedRecords, mr.getId()) == null) { Logger.getLogger(WorkflowServiceJpa.class).debug(" Delete record"); removeMapRecord(mr.getId()); } else { Logger.getLogger(WorkflowServiceJpa.class).debug(" Record exists"); } } return syncedRecords; } /** * Gets the map record in set. * * @param mapRecords the map records * @param mapRecordId the map record id * @return the map record in set */ @SuppressWarnings("static-method") private MapRecord getMapRecordInSet(Set<MapRecord> mapRecords, Long mapRecordId) { if (mapRecordId == null) return null; for (final MapRecord mr : mapRecords) { if (mapRecordId.equals(mr.getId())) return mr; } return null; } /* see superclass */ @Override public void computeWorkflow(MapProject mapProject) throws Exception { Logger.getLogger(WorkflowServiceJpa.class) .info("Start computing workflow for " + mapProject.getName()); // set the transaction parameter and tracking variables setTransactionPerOperation(false); int commitCt = 1000; int trackingRecordCt = 0; // Clear the workflow for this project Logger.getLogger(WorkflowServiceJpa.class).info(" Clear old workflow"); clearWorkflowForMapProject(mapProject); // open the services @SuppressWarnings("resource") ContentService contentService = new ContentServiceJpa(); String workflowPath; switch (mapProject.getWorkflowType()) { case CONFLICT_PROJECT: workflowPath = "NON_LEGACY_PATH"; break; case REVIEW_PROJECT: workflowPath = "REVIEW_PROJECT_PATH"; break; default: workflowPath = mapProject.getWorkflowType().toString(); break; } // get the workflow handler for this project WorkflowPathHandler workflowHandler = this.getWorkflowPathHandler(workflowPath); // get the concepts in scope SearchResultList conceptsInScope = findConceptsInScope(mapProject.getId(), null); // construct a hashset of concepts in scope Set<String> conceptIds = new HashSet<>(); for (final SearchResult sr : conceptsInScope.getIterable()) { conceptIds.add(sr.getTerminologyId()); } Logger.getLogger(WorkflowServiceJpa.class) .info(" Concept ids put into hash set: " + conceptIds.size()); // get the current records MapRecordList mapRecords = getMapRecordsForMapProject(mapProject.getId()); Logger.getLogger(WorkflowServiceJpa.class).info( "Processing existing records (" + mapRecords.getCount() + " found)"); // instantiate a mapped set of non-published records Map<String, List<MapRecord>> unpublishedRecords = new HashMap<>(); // cycle over the map records, and remove concept ids if a map record is // publication-ready for (final MapRecord mapRecord : mapRecords.getIterable()) { // if this map record is not eligible for insertion into workflow // skip it and remove the`concept id from the set if (!workflowHandler.isMapRecordInWorkflow(mapRecord)) { conceptIds.remove(mapRecord.getConceptId()); } // if this concept is in scope, add to workflow else if (conceptIds.contains(mapRecord.getConceptId())) { List<MapRecord> originIds; // if this key does not yet have a constructed list, make one, // otherwise get the existing list if (unpublishedRecords.containsKey(mapRecord.getConceptId())) { originIds = unpublishedRecords.get(mapRecord.getConceptId()); } else { originIds = new ArrayList<>(); } originIds.add(mapRecord); unpublishedRecords.put(mapRecord.getConceptId(), originIds); } } Logger.getLogger(WorkflowServiceJpa.class) .info(" Concepts with no publication-ready map record: " + conceptIds.size()); Logger.getLogger(WorkflowServiceJpa.class) .info(" Concepts with unpublished map record content: " + unpublishedRecords.size()); beginTransaction(); // if (workflowHandler.isEmptyWorkflowAllowed()) { // construct the tracking records for unmapped concepts for (final String terminologyId : conceptIds) { // empty workflow check: no records for this id and empty workflow not // allowed if (!unpublishedRecords.containsKey(terminologyId) && !workflowHandler.isEmptyWorkflowAllowed()) { continue; } // retrieve the concept for this result Concept concept = contentService.getConcept(terminologyId, mapProject.getSourceTerminology(), mapProject.getSourceTerminologyVersion()); // if concept could not be retrieved, throw exception if (concept == null) { contentService.close(); throw new Exception("Failed to retrieve concept " + terminologyId); } // skip inactive concepts if (!concept.isActive()) { Logger.getLogger(WorkflowServiceJpa.class) .warn("Skipped inactive concept " + terminologyId); continue; } // bypass for integration tests String sortKey = ""; if (concept.getLabel() == null || !concept.getLabel().equals("integration-test")) { // get the tree positions for this concept and set the sort key // the first retrieved TreePositionList treePositionsList = contentService.getTreePositions(concept.getTerminologyId(), concept.getTerminology(), concept.getTerminologyVersion()); // if no tree position, throw exception if (treePositionsList.getCount() == 0) { contentService.close(); throw new Exception( "Active concept " + terminologyId + " has no tree positions"); } sortKey = treePositionsList.getTreePositions().get(0).getAncestorPath(); } // create a workflow tracking record for this concept TrackingRecord trackingRecord = new TrackingRecordJpa(); // populate the fields from project and concept trackingRecord.setMapProjectId(mapProject.getId()); trackingRecord.setTerminology(concept.getTerminology()); trackingRecord.setTerminologyId(concept.getTerminologyId()); trackingRecord.setTerminologyVersion(concept.getTerminologyVersion()); trackingRecord.setDefaultPreferredName(concept.getDefaultPreferredName()); trackingRecord.setSortKey(sortKey); // add any existing map records to this tracking record Set<MapRecord> mapRecordsForTrackingRecord = new HashSet<>(); if (unpublishedRecords.containsKey(trackingRecord.getTerminologyId())) { for (final MapRecord mr : unpublishedRecords .get(trackingRecord.getTerminologyId())) { Logger.getLogger(WorkflowServiceJpa.class).info( " Adding existing map record " + mr.getId() + ", owned by " + mr.getOwner().getUserName() + " to tracking record for " + trackingRecord.getTerminologyId()); // Setup tracking record trackingRecord.addMapRecordId(mr.getId()); trackingRecord.addAssignedUserName(mr.getOwner().getUserName()); trackingRecord.addUserAndWorkflowStatusPair( mr.getOwner().getUserName(), mr.getWorkflowStatus().toString()); // add to the local set for workflow calculation mapRecordsForTrackingRecord.add(mr); } } // check against current workflow and universal workflows (currently Fix // Error and QA Paths) boolean isProjectPath = workflowHandler.isTrackingRecordInWorkflow(trackingRecord); boolean isFixErrorPath = (new WorkflowFixErrorPathHandler()) .isTrackingRecordInWorkflow(trackingRecord); boolean isQaPath = (new WorkflowQaPathHandler()) .isTrackingRecordInWorkflow(trackingRecord); // if is project path if (isProjectPath) { // check fix error not detected if (isFixErrorPath == true) { Logger.getLogger(getClass()) .error("Skipping concept -- Workflow combination for concept " + trackingRecord.getTerminologyId() + " matches both " + workflowHandler.getName() + " and FIX_ERROR_PATH: " + trackingRecord.getUserAndWorkflowStatusPairs()); continue; } // check fix error and qa not detected else if (isQaPath == true) { Logger.getLogger(getClass()) .error("Skipping concept -- Workflow combination for concept " + trackingRecord.getTerminologyId() + " matches both " + workflowHandler.getName() + " and QA_PATH: " + trackingRecord.getUserAndWorkflowStatusPairs()); continue; } // otherwise, set workflow type if (mapProject.getWorkflowType().equals(WorkflowType.CONFLICT_PROJECT)) trackingRecord.setWorkflowPath(WorkflowPath.NON_LEGACY_PATH); else if (mapProject.getWorkflowType() .equals(WorkflowType.REVIEW_PROJECT)) trackingRecord.setWorkflowPath(WorkflowPath.REVIEW_PROJECT_PATH); else { trackingRecord.setWorkflowPath( WorkflowPath.valueOf(mapProject.getWorkflowType().toString())); } } // otherwise, if Fix Error Path else if (isFixErrorPath == true) { trackingRecord.setWorkflowPath(WorkflowPath.FIX_ERROR_PATH); } // otherwise, if QA Path else if (isQaPath == true) { trackingRecord.setWorkflowPath(WorkflowPath.QA_PATH); } // otherwise, workflow combination not valid, skip and log else { Logger.getLogger(getClass()) .error("Skipping concept -- Workflow combination for concept " + trackingRecord.getTerminologyId() + " not valid for any of" + workflowHandler.getName() + ", FIX_ERROR_PATH, or QA_PATH: " + trackingRecord.getUserAndWorkflowStatusPairs()); continue; } addTrackingRecord(trackingRecord); if (++trackingRecordCt % commitCt == 0) { Logger.getLogger(WorkflowServiceJpa.class) .info(" " + trackingRecordCt + " tracking records created"); commit(); beginTransaction(); // close and re-instantiate the content service to prevent // memory buildup from Concept and TreePosition objects contentService.close(); contentService = new ContentServiceJpa(); } } // commit any remaining transactions commit(); // instantiate the full text eneity manager and set version FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(manager); fullTextEntityManager.setProperty("Version", Version.LUCENE_36); // create the indexes Logger.getLogger(WorkflowServiceJpa.class) .info(" Creating indexes for TrackingRecordJpa"); fullTextEntityManager.purgeAll(TrackingRecordJpa.class); fullTextEntityManager.flushToIndexes(); fullTextEntityManager.createIndexer(TrackingRecordJpa.class) .batchSizeToLoadObjects(100).cacheMode(CacheMode.NORMAL) .threadsToLoadObjects(4).threadsForSubsequentFetching(8).startAndWait(); Logger.getLogger(WorkflowServiceJpa.class).info("Done."); } /* see superclass */ @Override public void clearWorkflowForMapProject(MapProject mapProject) throws Exception { int commitCt = 0; int commitInterval = 1000; // begin transaction not in transaction-per-operation mode if (!getTransactionPerOperation()) { beginTransaction(); } for (final TrackingRecord tr : getTrackingRecordsForMapProject(mapProject) .getTrackingRecords()) { removeTrackingRecord(tr.getId()); if (++commitCt % commitInterval == 0) { // if not a transaction for every operation, commit at intervals if (!getTransactionPerOperation()) { commit(); beginTransaction(); } Logger.getLogger(WorkflowServiceJpa.class) .info(" Removed " + commitCt + " tracking records"); } } // commit any last deletions if not in transaction-per-operation mode if (!getTransactionPerOperation()) { commit(); } } // Utility functions /* see superclass */ @Override public Set<MapRecord> getMapRecordsForTrackingRecord( TrackingRecord trackingRecord) throws Exception { Set<MapRecord> mapRecords = new HashSet<>(); if (trackingRecord != null && trackingRecord.getMapRecordIds() != null) { for (final Long id : trackingRecord.getMapRecordIds()) { mapRecords.add(getMapRecord(id)); } } return mapRecords; } /* see superclass */ @Override public MapUserList getMapUsersForTrackingRecord(TrackingRecord trackingRecord) throws Exception { return getMapUsersFromMapRecords( getMapRecordsForTrackingRecord(trackingRecord)); } /* see superclass */ @Override public WorkflowStatus getWorkflowStatusForTrackingRecord( TrackingRecord trackingRecord) throws Exception { return getWorkflowStatusFromMapRecords( getMapRecordsForTrackingRecord(trackingRecord)); } /* see superclass */ @Override public WorkflowStatus getLowestWorkflowStatusForTrackingRecord( TrackingRecord trackingRecord) throws Exception { return getLowestWorkflowStatusFromMapRecords( getMapRecordsForTrackingRecord(trackingRecord)); } /* see superclass */ @Override public MapUserList getMapUsersFromMapRecords(Set<MapRecord> mapRecords) { MapUserList mapUserList = new MapUserListJpa(); for (final MapRecord mr : mapRecords) { mapUserList.addMapUser(mr.getOwner()); } return mapUserList; } /* see superclass */ @Override public WorkflowStatus getWorkflowStatusFromMapRecords( Set<MapRecord> mapRecords) { WorkflowStatus workflowStatus = WorkflowStatus.NEW; for (final MapRecord mr : mapRecords) { if (mr.getWorkflowStatus().compareTo(workflowStatus) > 0) workflowStatus = mr.getWorkflowStatus(); } return workflowStatus; } /* see superclass */ @Override public WorkflowStatus getLowestWorkflowStatusFromMapRecords( Set<MapRecord> mapRecords) { WorkflowStatus workflowStatus = WorkflowStatus.REVISION; for (final MapRecord mr : mapRecords) { if (mr.getWorkflowStatus().compareTo(workflowStatus) < 0) workflowStatus = mr.getWorkflowStatus(); } return workflowStatus; } /* see superclass */ @Override public List<String> computeWorkflowStatusErrors(MapProject mapProject) throws Exception { List<String> results = new ArrayList<>(); Logger.getLogger(WorkflowServiceJpa.class) .info("Retrieving tracking records for project " + mapProject.getId() + ", " + mapProject.getName()); // get all the tracking records for this project TrackingRecordList trackingRecords = this.getTrackingRecordsForMapProject(mapProject); // construct a set of terminology ids for which a tracking record exists Set<String> terminologyIdsWithTrackingRecord = new HashSet<>(); WorkflowPathHandler handler = getWorkflowPathHandlerForMapProject(mapProject); WorkflowPathHandler fixErrorHandler = this.getWorkflowPathHandler(WorkflowPath.FIX_ERROR_PATH.toString()); WorkflowPathHandler qaPathHandler = this.getWorkflowPathHandler(WorkflowPath.QA_PATH.toString()); for (final TrackingRecord trackingRecord : trackingRecords .getTrackingRecords()) { terminologyIdsWithTrackingRecord.add(trackingRecord.getTerminologyId()); ValidationResult result = null; // check fix error path if (trackingRecord.getWorkflowPath() .equals(WorkflowPath.FIX_ERROR_PATH)) { result = fixErrorHandler.validateTrackingRecord(trackingRecord); } // check qa path else if (trackingRecord.getWorkflowPath().equals(WorkflowPath.QA_PATH)) { result = qaPathHandler.validateTrackingRecord(trackingRecord); } // otherwise, check against project handler else { result = handler.validateTrackingRecord(trackingRecord); } if (result == null) { result = new ValidationResultJpa(); result.addError("Unexpected error -- validation result came back null"); } if (!result.isValid()) { results.add( constructErrorMessageStringForTrackingRecordAndValidationResult( trackingRecord, result)); } } Logger.getLogger(WorkflowServiceJpa.class) .info(" Checking map records for " + mapProject.getId() + ", " + mapProject.getName()); // second, check all records for non-publication ready content without // tracking record, skip inactive concepts final ContentService contentService = new ContentServiceJpa(); for (final MapRecord mapRecord : getMapRecordsForMapProject( mapProject.getId()).getMapRecords()) { // if eligible for workflow if (handler.isMapRecordInWorkflow(mapRecord)) { final Concept concept = contentService.getConcept( mapRecord.getConceptId(), mapProject.getSourceTerminology(), mapProject.getSourceTerminologyVersion()); // if no tracking record found for this concept // and the concept is active, then report an error if (!terminologyIdsWithTrackingRecord.contains(mapRecord.getConceptId()) && concept != null && concept.isActive()) { results.add("Map Record " + mapRecord.getId() + ": " + mapRecord.getWorkflowStatus() + " but no tracking record exists (Concept " + mapRecord.getConceptId() + " " + mapRecord.getConceptName()); } } } contentService.close(); return results; } /* see superclass */ @Override public void computeUntrackedMapRecords(MapProject mapProject) throws Exception { Logger.getLogger(WorkflowServiceJpa.class) .info("Retrieving map records for project " + mapProject.getId() + ", " + mapProject.getName()); final MapRecordList mapRecordsInProject = getMapRecordsForMapProject(mapProject.getId()); Logger.getLogger(WorkflowServiceJpa.class) .info(" " + mapRecordsInProject.getCount() + " retrieved"); WorkflowPathHandler handler = getWorkflowPathHandler(mapProject.getWorkflowType().toString()); // set the reporting interval based on number of tracking records int nObjects = 0; int nMessageInterval = (int) Math.floor(mapRecordsInProject.getCount() / 10); final Set<MapRecord> recordsUntracked = new HashSet<>(); for (final MapRecord mr : mapRecordsInProject.getIterable()) { final TrackingRecord tr = this.getTrackingRecordForMapProjectAndConcept( mapProject, mr.getConceptId()); // if no tracking record, check that this is a publication ready map // record if (tr == null) { if (handler.isMapRecordInWorkflow(mr)) { recordsUntracked.add(mr); } } if (++nObjects % nMessageInterval == 0) { Logger.getLogger(WorkflowServiceJpa.class) .info(" " + nObjects + " records processed, " + recordsUntracked.size() + " unpublished map records without tracking record"); } } } // FEEDBACK FUNCTIONS /** * Adds the feedback. * * @param feedback the feedback * @return the feedback */ @Override public Feedback addFeedback(Feedback feedback) { if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.persist(feedback); tx.commit(); } else { manager.persist(feedback); } return feedback; } /* see superclass */ @Override @SuppressWarnings("unchecked") public FeedbackList getFeedbacks() { List<Feedback> feedbacks = null; // construct query javax.persistence.Query query = manager.createQuery("select m from FeedbackJpa m"); // Try query feedbacks = query.getResultList(); FeedbackListJpa feedbackList = new FeedbackListJpa(); feedbackList.setFeedbacks(feedbacks); feedbackList.setTotalCount(feedbacks.size()); return feedbackList; } /* see superclass */ @Override public FeedbackConversation addFeedbackConversation( FeedbackConversation conversation) { // set the conversation of all elements of this conversation conversation.assignToChildren(); if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.persist(conversation); tx.commit(); } else { manager.persist(conversation); } return conversation; } /* see superclass */ @Override public void updateFeedbackConversation(FeedbackConversation conversation) { // set the conversation of all elements of this conversation conversation.assignToChildren(); if (getTransactionPerOperation()) { tx = manager.getTransaction(); tx.begin(); manager.merge(conversation); tx.commit(); // manager.close(); } else { manager.merge(conversation); } } /* see superclass */ @Override public FeedbackConversation getFeedbackConversation(Long id) throws Exception { try { // construct query javax.persistence.Query query = manager.createQuery( "select m from FeedbackConversationJpa m where id = :id"); // Try query query.setParameter("id", id); final FeedbackConversation feedbackConversation = (FeedbackConversation) query.getSingleResult(); return feedbackConversation; } catch (NoSuchElementException e) { return null; } } /* see superclass */ @Override public Feedback getFeedback(Long id) throws Exception { try { // construct query javax.persistence.Query query = manager.createQuery( "select m from FeedbackJpa m where id = :id"); // Try query query.setParameter("id", id); final Feedback feedback = (Feedback) query.getSingleResult(); return feedback; } catch (NoSuchElementException e) { return null; } } /** * Handle feedback conversation lazy initialization. * * @param feedbackConversation the feedback conversation */ @SuppressWarnings("static-method") private void handleFeedbackConversationLazyInitialization( FeedbackConversation feedbackConversation) { // handle all lazy initializations for (final Feedback feedback : feedbackConversation.getFeedbacks()) { feedback.getSender().getName(); for (final MapUser recipient : feedback.getRecipients()) recipient.getName(); for (final MapUser viewedBy : feedback.getViewedBy()) viewedBy.getName(); } } /* see superclass */ @SuppressWarnings("unchecked") @Override public FeedbackConversationList getFeedbackConversationsForConcept( Long mapProjectId, String terminologyId) throws Exception { final MapProject mapProject = getMapProject(mapProjectId); final javax.persistence.Query query = manager .createQuery( "select m from FeedbackConversationJpa m where terminology = :terminology and" + " terminologyVersion = :terminologyVersion and terminologyId = :terminologyId") .setParameter("terminology", mapProject.getSourceTerminology()) .setParameter("terminologyVersion", mapProject.getSourceTerminologyVersion()) .setParameter("terminologyId", terminologyId); List<FeedbackConversation> feedbackConversations = query.getResultList(); for (final FeedbackConversation feedbackConversation : feedbackConversations) { handleFeedbackConversationLazyInitialization(feedbackConversation); } // set the total count FeedbackConversationListJpa feedbackConversationList = new FeedbackConversationListJpa(); feedbackConversationList.setTotalCount(feedbackConversations.size()); // extract the required sublist of feedback conversations feedbackConversationList.setFeedbackConversations(feedbackConversations); return feedbackConversationList; } /* see superclass */ @SuppressWarnings({ "unchecked" }) @Override public FeedbackConversationList findFeedbackConversationsForProject( Long mapProjectId, String userName, String query, PfsParameter pfsParameter) throws Exception { MapProject mapProject = null; mapProject = getMapProject(mapProjectId); String modifiedQuery = ""; if (query.contains(" AND viewed:false")) modifiedQuery = query.replace(" AND viewed:false", ""); else if (query.contains(" AND viewed:true")) modifiedQuery = query.replace(" AND viewed:true", ""); else modifiedQuery = query; final StringBuilder sb = new StringBuilder(); sb.append(modifiedQuery).append(" AND "); sb.append("mapProjectId:" + mapProject.getId()); // remove from the query the viewed parameter, if it exists // viewed will be handled later because it is on the Feedback object, // not the FeedbackConversation object sb.append(" AND terminology:" + mapProject.getSourceTerminology() + " AND terminologyVersion:" + mapProject.getSourceTerminologyVersion() + " AND " + "( feedbacks.sender.userName:" + userName + " OR " + "feedbacks.recipients.userName:" + userName + ")"); Logger.getLogger(getClass()).info(" query = " + sb.toString()); final PfsParameter pfs = new PfsParameterJpa(pfsParameter); if (pfs.getSortField() == null || pfs.getSortField().isEmpty()) { pfs.setSortField("lastModified"); } // Get all results if viewed is specified if (query.contains("viewed")) { pfs.setStartIndex(-1); } int[] totalCt = new int[1]; final List<FeedbackConversation> feedbackConversations = (List<FeedbackConversation>) getQueryResults(sb.toString(), FeedbackConversationJpa.class, FeedbackConversationJpa.class, pfs, totalCt); if (pfsParameter != null && query.contains("viewed")) { // Handle viewed flag final List<FeedbackConversation> conversationsToKeep = new ArrayList<>(); for (final FeedbackConversation fc : feedbackConversations) { if (query.contains("viewed:false")) { for (final Feedback feedback : fc.getFeedbacks()) { final Set<MapUser> alreadyViewedBy = feedback.getViewedBy(); boolean found = false; for (final MapUser user : alreadyViewedBy) { if (user.getUserName().equals(userName)) { found = true; break; } } // add if not found if (!found) conversationsToKeep.add(fc); } } if (query.contains("viewed:true")) { boolean found = false; for (final Feedback feedback : fc.getFeedbacks()) { Set<MapUser> alreadyViewedBy = feedback.getViewedBy(); for (final MapUser user : alreadyViewedBy) { if (user.getUserName().equals(userName)) { found = true; break; } } if (!found) break; } if (found) conversationsToKeep.add(fc); } } totalCt[0] = conversationsToKeep.size(); feedbackConversations.clear(); if (pfsParameter.getStartIndex() != -1) { for (int i = pfsParameter.getStartIndex(); i < pfsParameter.getStartIndex() + pfsParameter.getMaxResults() && i < conversationsToKeep.size(); i++) { feedbackConversations.add(conversationsToKeep.get(i)); } } else { feedbackConversations.addAll(conversationsToKeep); } } Logger.getLogger(this.getClass()) .debug(Integer.toString(feedbackConversations.size()) + " feedbackConversations retrieved"); for (final FeedbackConversation feedbackConversation : feedbackConversations) { handleFeedbackConversationLazyInitialization(feedbackConversation); } // set the total count FeedbackConversationListJpa feedbackConversationList = new FeedbackConversationListJpa(); feedbackConversationList.setTotalCount(totalCt[0]); // extract the required sublist of feedback conversations feedbackConversationList.setFeedbackConversations(feedbackConversations); return feedbackConversationList; } /* see superclass */ @SuppressWarnings("unchecked") @Override public FeedbackConversationList getFeedbackConversationsForRecord( Long mapRecordId) throws Exception { javax.persistence.Query query = manager .createQuery( "select m from FeedbackConversationJpa m where mapRecordId=:mapRecordId") .setParameter("mapRecordId", mapRecordId); List<FeedbackConversation> feedbackConversations = query.getResultList(); for (final FeedbackConversation feedbackConversation : feedbackConversations) { handleFeedbackConversationLazyInitialization(feedbackConversation); } // set the total count FeedbackConversationListJpa feedbackConversationList = new FeedbackConversationListJpa(); feedbackConversationList.setTotalCount(feedbackConversations.size()); // extract the required sublist of feedback conversations feedbackConversationList.setFeedbackConversations(feedbackConversations); return feedbackConversationList; } /* see superclass */ @Override public FeedbackList getFeedbackErrorsForRecord(MapRecord mapRecord) throws Exception { List<Feedback> feedbacksWithError = new ArrayList<>(); // find any feedback conersations for this record FeedbackConversationList conversations = this.getFeedbackConversationsForRecord(mapRecord.getId()); // cycle over feedbacks for (final FeedbackConversation conversation : conversations .getIterable()) { for (final Feedback feedback : conversation.getFeedbacks()) { if (feedback.getIsError()) { feedbacksWithError.add(feedback); } } } FeedbackList feedbackList = new FeedbackListJpa(); feedbackList.setFeedbacks(feedbacksWithError); return feedbackList; } /* see superclass */ @Override public void sendFeedbackEmail(String name, String email, String conceptId, String conceptName, String refSetId, String message) throws Exception { // get to address from config.properties Properties config = ConfigUtility.getConfigProperties(); String feedbackUserRecipient = config.getProperty("mail.smtp.to.feedback.user"); String baseUrlWebapp = config.getProperty("base.url"); String conceptUrl = baseUrlWebapp + "/#/record/conceptId/" + conceptId + "/autologin?refSetId=" + refSetId; String from; if (config.containsKey("mail.smtp.from")) { from = config.getProperty("mail.smtp.from"); } else { from = config.getProperty("mail.smtp.user"); } Properties props = new Properties(); props.put("mail.smtp.user", config.getProperty("mail.smtp.user")); props.put("mail.smtp.password", config.getProperty("mail.smtp.password")); props.put("mail.smtp.host", config.getProperty("mail.smtp.host")); props.put("mail.smtp.port", config.getProperty("mail.smtp.port")); props.put("mail.smtp.starttls.enable", config.getProperty("mail.smtp.starttls.enable")); props.put("mail.smtp.auth", config.getProperty("mail.smtp.auth")); ConfigUtility.sendEmail( "Mapping Tool User Feedback: " + conceptId + "-" + conceptName, from, feedbackUserRecipient, "<html>User: " + name + "<br>" + "Email: " + email + "<br>" + "Concept: <a href=" + conceptUrl + ">" + conceptId + "- " + conceptName + "</a><br><br>" + message + "</html>", props, "true".equals(config.getProperty("mail.smtp.auth"))); } /** * Construct error message string for tracking record and validation result. * * @param trackingRecord the tracking record * @param result the result * @return the string * @throws Exception the exception */ private String constructErrorMessageStringForTrackingRecordAndValidationResult( TrackingRecord trackingRecord, ValidationResult result) throws Exception { StringBuffer message = new StringBuffer(); message.append("ERROR for Concept " + trackingRecord.getTerminologyId() + ", Path " + trackingRecord.getWorkflowPath().toString() + "\n"); // record information message.append(" Records involved:\n"); message.append(" " + "id\tUser\tWorkflowStatus\n"); for (final MapRecord mr : getMapRecordsForTrackingRecord(trackingRecord)) { message.append( " " + mr.getId().toString() + "\t" + mr.getOwner().getUserName() + "\t" + mr.getWorkflowStatus().toString() + "\n"); } message.append(" Errors reported:\n"); for (final String error : result.getErrors()) { message.append(" " + error + "\n"); } return message.toString(); } @Override public SearchResultList findAvailableWork(MapProject mapProject, MapUser mapUser, MapUserRole userRole, String query, PfsParameter pfsParameter) throws Exception { WorkflowPathHandler handler = null; switch (mapProject.getWorkflowType()) { case CONFLICT_PROJECT: handler = new WorkflowNonLegacyPathHandler(); break; case REVIEW_PROJECT: handler = new WorkflowReviewProjectPathHandler(); break; default: handler = this .getWorkflowPathHandler(mapProject.getWorkflowType().toString()); break; } if (handler == null) { throw new Exception( "Could not retrieve workflow handler for workflow type " + mapProject.getWorkflowType()); } return handler.findAvailableWork(mapProject, mapUser, userRole, query, pfsParameter, this); } @Override public SearchResultList findAssignedWork(MapProject mapProject, MapUser mapUser, MapUserRole userRole, String query, PfsParameter pfsParameter) throws Exception { WorkflowPathHandler handler = null; // TODO Get rid of switch cases once workflow type and workflow path are // aligned switch (mapProject.getWorkflowType()) { case CONFLICT_PROJECT: handler = new WorkflowNonLegacyPathHandler(); break; case REVIEW_PROJECT: handler = new WorkflowReviewProjectPathHandler(); break; default: handler = this .getWorkflowPathHandler(mapProject.getWorkflowType().toString()); break; } if (handler == null) { throw new Exception( "Could not retrieve workflow handler for workflow type " + mapProject.getWorkflowType()); } return handler.findAssignedWork(mapProject, mapUser, userRole, query, pfsParameter, this); } /* see superclass */ @Override public MapRecord getPreviouslyPublishedVersionOfMapRecord(MapRecord mapRecord) throws Exception { // get the record revisions final List<MapRecord> revisions = getMapRecordRevisions(mapRecord.getId()).getMapRecords(); // ensure revisions are sorted by descending timestamp Collections.sort(revisions, new Comparator<MapRecord>() { @Override public int compare(MapRecord mr1, MapRecord mr2) { return mr2.getLastModified().compareTo(mr1.getLastModified()); } }); // check assumption: last revision exists, at least two records must be // present if (revisions.size() < 2) { throw new Exception( "Attempted to get the previously published version of map record with id " + mapRecord.getId() + ", " + mapRecord.getOwner().getName() + ", and concept id " + mapRecord.getConceptId() + ", but no previous revisions exist."); } // cycle over records until the previously // published/ready-for-publication // state record is found for (final MapRecord revision : revisions) { if (revision.getWorkflowStatus().equals(WorkflowStatus.PUBLISHED) || revision.getWorkflowStatus() .equals(WorkflowStatus.READY_FOR_PUBLICATION)) { return revision; } } throw new Exception( "Could not retrieve previously published state of map record for concept " + mapRecord.getConceptId() + ", " + mapRecord.getConceptName()); } @Override public WorkflowPathHandler getWorkflowPathHandler(String name) throws Exception { String handlerClass = ConfigUtility.getConfigProperties() .getProperty("workflow.path.handler." + name + ".class"); return (WorkflowPathHandler) Class.forName(handlerClass).newInstance(); } @Override public WorkflowPathHandler getWorkflowPathHandlerForMapProject( MapProject mapProject) throws Exception { // TODO Remove the switch statement once conflict/review project types are // normalized with workflow switch (mapProject.getWorkflowType()) { case CONFLICT_PROJECT: return getWorkflowPathHandler("NON_LEGACY_PATH"); case REVIEW_PROJECT: return getWorkflowPathHandler("REVIEW_PROJECT_PATH"); default: return getWorkflowPathHandler(mapProject.getWorkflowType().toString()); } } }
package org.kurento.room.demo; import java.util.SortedMap; import org.kurento.client.Continuation; import org.kurento.client.Filter; import org.kurento.module.markerdetector.ArMarkerdetector; import org.kurento.room.api.UserNotificationService; import org.kurento.room.internal.DefaultNotificationRoomHandler; import org.kurento.room.internal.Participant; import org.kurento.room.internal.ProtocolElements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonObject; public class DemoNotificationRoomHandler extends DefaultNotificationRoomHandler { private static final Logger log = LoggerFactory.getLogger(DemoNotificationRoomHandler.class); private SortedMap<Integer, String> markerUrls; private UserNotificationService notifService; public DemoNotificationRoomHandler(UserNotificationService notifService) { super(notifService); this.notifService = notifService; } @Override public void updateFilter(String roomName, Participant participant, String filterId, String state) { Integer newState = -1; if (state != null) { newState = Integer.parseInt(state); } String url = markerUrls.get(newState); JsonObject notificationParams = new JsonObject(); notificationParams.addProperty("MarkerFilterState", newState); notifService.sendNotification(participant.getId(), ProtocolElements.CUSTOM_NOTIFICATION, notificationParams); ArMarkerdetector newFilter; Filter filter = participant.getFilterElement(filterId); if (filter == null) { newFilter = new ArMarkerdetector.Builder(participant.getPipeline()).build(); log.info("New {} filter for participant {}", filterId, participant.getId()); participant.addFilterElement(filterId, newFilter); } else { log.info("Reusing {} filter in participant {}", filterId, participant.getId()); newFilter = (ArMarkerdetector) filter; } if (url != null) { newFilter.setOverlayImage(url, new Continuation<Void>() { @Override public void onSuccess(Void result) throws Exception { } @Override public void onError(Throwable cause) throws Exception { } }); newFilter.setOverlayScale(1.0F, new Continuation<Void>() { @Override public void onSuccess(Void result) throws Exception { } @Override public void onError(Throwable cause) throws Exception { } }); } else { newFilter.setOverlayScale(0.0001F, new Continuation<Void>() { @Override public void onSuccess(Void result) throws Exception { } @Override public void onError(Throwable cause) throws Exception { } }); } } @Override public String getNextFilterState(String filterId, String oldState) { Integer currentUrlIndex; if (oldState == null) { currentUrlIndex = -1; } else { currentUrlIndex = Integer.parseInt(oldState); } Integer nextIndex = -1; // disable filter if (currentUrlIndex < markerUrls.firstKey()) { nextIndex = markerUrls.firstKey(); // enable filter using first URL } else if (currentUrlIndex < markerUrls.lastKey()) { nextIndex = markerUrls.tailMap(currentUrlIndex + 1).firstKey(); } return nextIndex.toString(); } public void setMarkerUrls(SortedMap<Integer, String> markerUrls) { this.markerUrls = markerUrls; } }
package com.felipecsl.quickreturn.library.widget; import android.database.DataSetObserver; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.ListAdapter; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class QuickReturnAdapter extends DataSetObserver implements ListAdapter { private static final String TAG = "QuickReturnAdapter"; private final ListAdapter wrappedAdapter; private final int heightMeasureSpec; private int[] itemsVerticalOffset; private final int numColumns; private int targetViewHeight; private int verticalSpacing; public QuickReturnAdapter(final ListAdapter wrappedAdapter) { this(wrappedAdapter, 1); } public QuickReturnAdapter(final ListAdapter wrappedAdapter, final int numColumns) { this.wrappedAdapter = wrappedAdapter; this.numColumns = numColumns; heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); itemsVerticalOffset = new int[wrappedAdapter.getCount() + numColumns]; wrappedAdapter.registerDataSetObserver(this); } @Override public boolean areAllItemsEnabled() { return wrappedAdapter.areAllItemsEnabled(); } @Override public boolean isEnabled(final int position) { if (position < numColumns) return true; return wrappedAdapter.isEnabled(position - numColumns); } @Override public void registerDataSetObserver(final DataSetObserver observer) { wrappedAdapter.registerDataSetObserver(observer); } @Override public void unregisterDataSetObserver(final DataSetObserver observer) { wrappedAdapter.unregisterDataSetObserver(observer); } @Override public int getCount() { return wrappedAdapter.getCount() + numColumns; } @Override public Object getItem(final int position) { if (position < numColumns) return null; return wrappedAdapter.getItem(position - numColumns); } @Override public long getItemId(final int position) { if (position < numColumns) return 0; return wrappedAdapter.getItemId(position - numColumns); } @Override public boolean hasStableIds() { return wrappedAdapter.hasStableIds(); } @Override public View getView(final int position, final View convertView, final ViewGroup parent) { View v; int finalHeight; if (position < numColumns) { if (convertView == null) v = new View(parent.getContext()); else v = convertView; v.setLayoutParams(new AbsListView.LayoutParams( AbsListView.LayoutParams.MATCH_PARENT, targetViewHeight)); finalHeight = targetViewHeight; } else { v = wrappedAdapter.getView(position - numColumns, convertView, parent); //fixes NullPointerException when v.measure() is called v.setLayoutParams(new AbsListView.LayoutParams( AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT)); v.measure(View.MeasureSpec.makeMeasureSpec(parent.getWidth() / numColumns, View.MeasureSpec.AT_MOST), heightMeasureSpec); finalHeight = v.getMeasuredHeight(); } if (position + numColumns < itemsVerticalOffset.length) itemsVerticalOffset[position + numColumns] = itemsVerticalOffset[position] + finalHeight + verticalSpacing; return v; } @Override public int getItemViewType(final int position) { if (position < numColumns) return wrappedAdapter.getViewTypeCount(); return wrappedAdapter.getItemViewType(position - numColumns); } @Override public int getViewTypeCount() { return wrappedAdapter.getViewTypeCount() + 1; } @Override public boolean isEmpty() { return wrappedAdapter.isEmpty(); } public int getPositionVerticalOffset(int position) { if (position >= itemsVerticalOffset.length) return 0; return itemsVerticalOffset[position]; } public int getMaxVerticalOffset() { if (isEmpty()) return 0; final List<Integer> items = new ArrayList<>(itemsVerticalOffset.length); for (final int aMItemOffsetY : itemsVerticalOffset) items.add(aMItemOffsetY); return Collections.max(items); } @Override public void onChanged() { super.onChanged(); if (wrappedAdapter.getCount() < itemsVerticalOffset.length) return; int[] newArray = new int[wrappedAdapter.getCount() + numColumns]; System.arraycopy(itemsVerticalOffset, 0, newArray, 0, Math.min(itemsVerticalOffset.length, newArray.length)); itemsVerticalOffset = newArray; } public void setTargetViewHeight(final int targetViewHeight) { this.targetViewHeight = targetViewHeight; } public void setVerticalSpacing(final int verticalSpacing) { this.verticalSpacing = verticalSpacing; } }
package liquibase.sqlgenerator.core; import liquibase.configuration.LiquibaseConfiguration; import liquibase.database.Database; import liquibase.database.core.DB2Database; import liquibase.database.core.MSSQLDatabase; import liquibase.database.core.OracleDatabase; import liquibase.exception.ValidationErrors; import liquibase.parser.ChangeLogParserCofiguration; import liquibase.sql.Sql; import liquibase.sql.UnparsedSql; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.statement.core.CreateProcedureStatement; import liquibase.structure.core.Schema; import liquibase.structure.core.StoredProcedure; import liquibase.util.SqlParser; import liquibase.util.StringClauses; import liquibase.util.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; public class CreateProcedureGenerator extends AbstractSqlGenerator<CreateProcedureStatement> { @Override public ValidationErrors validate(CreateProcedureStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { ValidationErrors validationErrors = new ValidationErrors(); validationErrors.checkRequiredField("procedureText", statement.getProcedureText()); if (statement.getReplaceIfExists() != null) { if (database instanceof MSSQLDatabase) { if (statement.getReplaceIfExists() && statement.getProcedureName() == null) { validationErrors.addError("procedureName is required if replaceIfExists = true"); } } else { validationErrors.checkDisallowedField("replaceIfExists", statement.getReplaceIfExists(), null); } } return validationErrors; } @Override public Sql[] generateSql(CreateProcedureStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { List<Sql> sql = new ArrayList<Sql>(); String schemaName = statement.getSchemaName(); if (schemaName == null) { schemaName = database.getDefaultSchemaName(); } String procedureText = addSchemaToText(statement.getProcedureText(), schemaName, "PROCEDURE", database); if (statement.getReplaceIfExists() != null && statement.getReplaceIfExists()) { String fullyQualifiedName = database.escapeObjectName(statement.getProcedureName(), StoredProcedure.class); if (schemaName != null) { fullyQualifiedName = database.escapeObjectName(schemaName, Schema.class) + "." + fullyQualifiedName; } sql.add(new UnparsedSql("if object_id('" + fullyQualifiedName + "', 'p') is null exec ('create procedure " + fullyQualifiedName + " as select 1 a')")); StringClauses parsedSql = SqlParser.parse(procedureText, true, true); StringClauses.ClauseIterator clauseIterator = parsedSql.getClauseIterator(); Object next = "START"; while (next != null && !(next.toString().equalsIgnoreCase("create") || next.toString().equalsIgnoreCase("alter")) && clauseIterator.hasNext()) { next = clauseIterator.nextNonWhitespace(); } clauseIterator.replace("ALTER"); procedureText = parsedSql.toString(); } procedureText = removeTrailingDelimiter(procedureText, statement.getEndDelimiter()); if (database instanceof MSSQLDatabase && procedureText.toLowerCase().contains("merge") && !procedureText.endsWith(";")) { //mssql "AS MERGE" procedures need a trailing ; (regardless of the end delimiter) StringClauses parsed = SqlParser.parse(procedureText); StringClauses.ClauseIterator clauseIterator = parsed.getClauseIterator(); boolean reallyMerge = false; while (clauseIterator.hasNext()) { Object clause = clauseIterator.nextNonWhitespace(); if (((String) clause).equalsIgnoreCase("merge")) { reallyMerge = true; } } if (reallyMerge) { procedureText = procedureText + ";"; } } sql.add(new UnparsedSql(procedureText, statement.getEndDelimiter())); surroundWithSchemaSets(sql, statement.getSchemaName(), database); return sql.toArray(new Sql[sql.size()]); } public static String removeTrailingDelimiter(String procedureText, String endDelimiter) { if (procedureText == null) { return null; } if (endDelimiter == null) { return procedureText; } String fixedText = procedureText; while (fixedText.length() > 0) { String lastChar = fixedText.substring(fixedText.length() - 1); if (lastChar.equals(" ") || lastChar.equals("\n") || lastChar.equals("\r") || lastChar.equals("\t")) { fixedText = fixedText.substring(0, fixedText.length() - 1); } else { break; } } endDelimiter = endDelimiter.replace("\\r", "\r").replace("\\n", "\n"); if (fixedText.endsWith(endDelimiter)) { return fixedText.substring(0, fixedText.length() - endDelimiter.length()); } else { return procedureText; } } /** * Convenience method for when the schemaName is set but we don't want to parse the body */ public static void surroundWithSchemaSets(List<Sql> sql, String schemaName, Database database) { if ((StringUtils.trimToNull(schemaName) != null) && !LiquibaseConfiguration.getInstance().getProperty(ChangeLogParserCofiguration.class, ChangeLogParserCofiguration.USE_PROCEDURE_SCHEMA).getValue(Boolean.class)) { String defaultSchema = database.getDefaultSchemaName(); if (database instanceof OracleDatabase) { sql.add(0, new UnparsedSql("ALTER SESSION SET CURRENT_SCHEMA=" + database.escapeObjectName(schemaName, Schema.class))); sql.add(new UnparsedSql("ALTER SESSION SET CURRENT_SCHEMA=" + database.escapeObjectName(defaultSchema, Schema.class))); } else if (database instanceof DB2Database) { sql.add(0, new UnparsedSql("SET CURRENT SCHEMA " + schemaName)); sql.add(new UnparsedSql("SET CURRENT SCHEMA " + defaultSchema)); } } } /** * Convenience method for other classes similar to this that want to be able to modify the procedure text to add the schema */ public static String addSchemaToText(String procedureText, String schemaName, String keywordBeforeName, Database database) { if ((StringUtils.trimToNull(schemaName) != null) && LiquibaseConfiguration.getInstance().getProperty(ChangeLogParserCofiguration.class, ChangeLogParserCofiguration.USE_PROCEDURE_SCHEMA).getValue(Boolean.class)) { StringClauses parsedSql = SqlParser.parse(procedureText, true, true); StringClauses.ClauseIterator clauseIterator = parsedSql.getClauseIterator(); Object next = "START"; while (next != null && !next.toString().equalsIgnoreCase(keywordBeforeName) && clauseIterator.hasNext()) { next = clauseIterator.nextNonWhitespace(); } if (next != null && clauseIterator.hasNext()) { Object procNameClause = clauseIterator.nextNonWhitespace(); if (procNameClause instanceof String) { String[] nameParts = ((String) procNameClause).split("\\."); String finalName; if (nameParts.length == 1) { finalName = database.escapeObjectName(schemaName, Schema.class) + "." + nameParts[0]; } else if (nameParts.length == 2) { finalName = database.escapeObjectName(schemaName, Schema.class) + "." + nameParts[1]; } else if (nameParts.length == 3) { finalName = nameParts[0] + "." + database.escapeObjectName(schemaName, Schema.class) + "." + nameParts[2]; } else { finalName = (String) procNameClause; //just go with what was there } clauseIterator.replace(finalName); } procedureText = parsedSql.toString(); } } return procedureText; } }
package com.facebook.litho.specmodels.model; import com.facebook.litho.annotations.ResType; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.TypeName; import java.lang.annotation.Annotation; import java.util.List; import java.util.Objects; import javax.annotation.concurrent.Immutable; /** * Model that is an abstract representation of a {@link com.facebook.litho.annotations.InjectProp}. */ @Immutable public class InjectPropModel implements MethodParamModel { private final MethodParamModel mParamModel; private final boolean mIsLazy; public InjectPropModel(MethodParamModel paramModel, boolean isLazy) { mParamModel = paramModel; mIsLazy = isLazy; } @Override public TypeSpec getTypeSpec() { return mParamModel.getTypeSpec(); } @Override public TypeName getTypeName() { return mParamModel.getTypeName(); } @Override public String getName() { return mParamModel.getName(); } @Override public List<Annotation> getAnnotations() { return mParamModel.getAnnotations(); } @Override public List<AnnotationSpec> getExternalAnnotations() { return mParamModel.getExternalAnnotations(); } @Override public Object getRepresentedObject() { return mParamModel.getRepresentedObject(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InjectPropModel that = (InjectPropModel) o; return mIsLazy == that.mIsLazy && Objects.equals(mParamModel, that.mParamModel); } @Override public int hashCode() { return Objects.hash(mParamModel, mIsLazy); } /** Convert to a regular prop model. */ public PropModel toPropModel() { final String localName = getName(); return new PropModel(mParamModel, false, ResType.NONE, "") { @Override public String getName() { return localName; } }; } public boolean isLazy() { return mIsLazy; } /** @return a new {@link PropModel} instance with the given name overridden. */ public InjectPropModel withName(String name) { return new InjectPropModel(mParamModel, mIsLazy) { @Override public String getName() { return name; } }; } }
package mil.nga.giat.mage.map.preference; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.ListFragment; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.format.Formatter; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseExpandableListAdapter; import android.widget.CheckBox; import android.widget.ExpandableListView; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import mil.nga.geopackage.GeoPackageManager; import mil.nga.geopackage.factory.GeoPackageFactory; import mil.nga.giat.mage.R; import mil.nga.giat.mage.cache.CacheUtils; import mil.nga.giat.mage.map.cache.CacheOverlay; import mil.nga.giat.mage.map.cache.CacheOverlayFilter; import mil.nga.giat.mage.map.cache.CacheProvider; import mil.nga.giat.mage.map.cache.CacheProvider.OnCacheOverlayListener; import mil.nga.giat.mage.map.cache.GeoPackageCacheOverlay; import mil.nga.giat.mage.map.cache.XYZDirectoryCacheOverlay; import mil.nga.giat.mage.map.download.GeoPackageDownloadManager; import mil.nga.giat.mage.sdk.datastore.layer.Layer; import mil.nga.giat.mage.sdk.datastore.layer.LayerHelper; import mil.nga.giat.mage.sdk.datastore.user.Event; import mil.nga.giat.mage.sdk.datastore.user.EventHelper; import mil.nga.giat.mage.sdk.exceptions.LayerException; import mil.nga.giat.mage.sdk.gson.deserializer.LayerDeserializer; import mil.nga.giat.mage.sdk.http.HttpClientManager; import mil.nga.giat.mage.sdk.http.resource.LayerResource; import mil.nga.giat.mage.sdk.utils.StorageUtility; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class TileOverlayPreferenceActivity extends AppCompatActivity { private static final String LOG_NAME = TileOverlayPreferenceActivity.class.getName(); private static final int PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 100; private OverlayListFragment overlayFragment; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.cache_overlay); overlayFragment = (OverlayListFragment) getSupportFragmentManager().findFragmentById(R.id.overlay_fragment); } @Override public void onBackPressed() { Intent intent = new Intent(); intent.putStringArrayListExtra(MapPreferencesActivity.OVERLAY_EXTENDED_DATA_KEY, overlayFragment.getSelectedOverlays()); setResult(Activity.RESULT_OK, intent); finish(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } public static class OverlayListFragment extends ListFragment implements OnCacheOverlayListener { private OverlayAdapter overlayAdapter; private ExpandableListView listView; private View progress; private MenuItem refreshButton; private GeoPackageDownloadManager downloadManager; private Timer downloadRefreshTimer; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); downloadManager = new GeoPackageDownloadManager(getContext(), new GeoPackageDownloadManager.GeoPackageDownloadListener() { @Override public void onGeoPackageDownloaded(Layer layer, CacheOverlay overlay) { overlayAdapter.addOverlay(overlay, layer); overlayAdapter.notifyDataSetChanged(); } }); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_cache_overlay, container, false); listView = (ExpandableListView) view.findViewById(android.R.id.list); listView.setEnabled(true); progress = view.findViewById(R.id.progress); progress.setVisibility(View.VISIBLE); if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) { new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle) .setTitle(R.string.overlay_access_title) .setMessage(R.string.overlay_access_message) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); } }) .create() .show(); } else { requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); } } return view; } @Override public void onResume() { super.onResume(); downloadManager.onResume(); } @Override public void onPause() { super.onPause(); downloadManager.onPause(); if (downloadRefreshTimer != null) { downloadRefreshTimer.cancel(); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.tile_overlay_menu, menu); refreshButton = menu.findItem(R.id.tile_overlay_refresh); refreshButton.setEnabled(false); // This really should be done in the onResume, but I need to have the refreshButton // before I register as the callback will set it to enabled. // The problem is that onResume gets called before this so my menu is // not yet setup and I will not have a handle on this button CacheProvider.getInstance(getActivity()).registerCacheOverlayListener(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.tile_overlay_refresh: refresh(item); return true; default: return super.onOptionsItemSelected(item); } } private void refresh(MenuItem item) { item.setEnabled(false); progress.setVisibility(View.VISIBLE); listView.setEnabled(false); fetchGeopackageLayers(new Callback<Collection<Layer>>() { @Override public void onResponse(Call<Collection<Layer>> call, Response<Collection<Layer>> response) { if (response.isSuccessful()) { saveGeopackageLayers(response.body()); CacheProvider.getInstance(getActivity()).refreshTileOverlays(); } } @Override public void onFailure(Call<Collection<Layer>> call, Throwable t) { Log.e(LOG_NAME, "Error fetching event geopackage layers", t); } }); } private void fetchGeopackageLayers(Callback<Collection<Layer>> callback) { Context context = getContext(); Event event = EventHelper.getInstance(context).getCurrentEvent(); String baseUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(context.getString(mil.nga.giat.mage.sdk.R.string.serverURLKey), context.getString(mil.nga.giat.mage.sdk.R.string.serverURLDefaultValue)); Retrofit retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create(LayerDeserializer.getGsonBuilder(event))) .client(HttpClientManager.getInstance().httpClient()) .build(); Collection<Layer> layers = new ArrayList<>(); LayerResource.LayerService service = retrofit.create(LayerResource.LayerService.class); service.getLayers(event.getRemoteId(), "GeoPackage").enqueue(callback); } private void saveGeopackageLayers(Collection<Layer> layers) { Context context = getContext(); LayerHelper layerHelper = LayerHelper.getInstance(context); try { layerHelper.deleteAll("GeoPackage"); GeoPackageManager manager = GeoPackageFactory.getManager(context); for (Layer layer : layers) { // Check if its loaded File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), String.format("MAGE/geopackages/%s/%s", layer.getRemoteId(), layer.getFileName())); if (file.exists() && manager.existsAtExternalFile(file)) { layer.setLoaded(true); } layerHelper.create(layer); } } catch (LayerException e) { Log.e(LOG_NAME, "Error saving geopackage layers", e); } } @Override public void onDestroy() { super.onDestroy(); CacheProvider.getInstance(getActivity()).unregisterCacheOverlayListener(this); } @Override public void onCacheOverlay(final List<CacheOverlay> cacheOverlays) { List<Layer> geopackages = Collections.EMPTY_LIST; final Event event = EventHelper.getInstance(getContext()).getCurrentEvent(); try { geopackages = LayerHelper.getInstance(getContext()).readByEvent(event,"GeoPackage"); } catch (LayerException e) { } listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { int itemType = ExpandableListView.getPackedPositionType(id); if (itemType == ExpandableListView.PACKED_POSITION_TYPE_CHILD) { int childPosition = ExpandableListView.getPackedPositionChild(id); int groupPosition = ExpandableListView.getPackedPositionGroup(id); // Handle child row long clicks here return true; } else if (itemType == ExpandableListView.PACKED_POSITION_TYPE_GROUP) { int groupPosition = ExpandableListView.getPackedPositionGroup(id); Object group = overlayAdapter.getGroup(groupPosition); if (group instanceof CacheOverlay) { CacheOverlay cacheOverlay = (CacheOverlay) overlayAdapter.getGroup(groupPosition); deleteCacheOverlayConfirm(cacheOverlay); return true; } return false; } return false; } }); downloadManager.reconcileDownloads(geopackages, new GeoPackageDownloadManager.GeoPackageLoadListener() { @Override public void onReady(List<Layer> layers) { overlayAdapter = new OverlayAdapter(getActivity(), event, cacheOverlays, layers, downloadManager); listView.setAdapter(overlayAdapter); refreshButton.setEnabled(true); listView.setEnabled(true); progress.setVisibility(View.GONE); downloadRefreshTimer = new Timer(); downloadRefreshTimer.schedule(new TimerTask() { @Override public void run() { refreshDownloads(); } }, 0, 2000); } }); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: { if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { CacheProvider.getInstance(getActivity()).refreshTileOverlays(); }; break; } } } /** * Get the selected cache overlays and child cache overlays * * @return */ public ArrayList<String> getSelectedOverlays() { ArrayList<String> overlays = new ArrayList<>(); if (overlayAdapter != null) { for (CacheOverlay cacheOverlay : overlayAdapter.getOverlays()) { boolean childAdded = false; for (CacheOverlay childCache : cacheOverlay.getChildren()) { if (childCache.isEnabled()) { overlays.add(childCache.getCacheName()); childAdded = true; } } if (!childAdded && cacheOverlay.isEnabled()) { overlays.add(cacheOverlay.getCacheName()); } } } return overlays; } private void refreshDownloads() { List<Layer> layers = overlayAdapter.getGeopackages(); for (int i = 0; i < layers.size(); i++) { final Layer layer = layers.get(i); if (layer.getDownloadId() != null && !layer.isLoaded()) { // layer is currently downloading, get progress and refresh view final View view = listView.getChildAt(i - listView.getFirstVisiblePosition()); if (view == null) { continue; } Activity activity = getActivity(); if (activity == null) { continue; } activity.runOnUiThread(new Runnable() { @Override public void run() { overlayAdapter.updateDownloadProgress(view, downloadManager.getProgress(layer), layer.getFileSize()); } }); } } } /** * Delete the cache overlay * @param cacheOverlay */ private void deleteCacheOverlayConfirm(final CacheOverlay cacheOverlay) { AlertDialog deleteDialog = new AlertDialog.Builder(getActivity()) .setTitle("Delete Cache") .setMessage("Delete " + cacheOverlay.getName() + " Cache?") .setPositiveButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteCacheOverlay(cacheOverlay); } }) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create(); deleteDialog.show(); } /** * Delete the XYZ cache overlay * @param xyzCacheOverlay */ private void deleteXYZCacheOverlay(XYZDirectoryCacheOverlay xyzCacheOverlay){ File directory = xyzCacheOverlay.getDirectory(); if(directory.canWrite()){ deleteFile(directory); } } /** * Delete the base directory file * @param base directory */ private void deleteFile(File base) { if (base.isDirectory()) { for (File file : base.listFiles()) { deleteFile(file); } } base.delete(); } /** * Delete the cache overlay * @param cacheOverlay */ private void deleteCacheOverlay(CacheOverlay cacheOverlay){ progress.setVisibility(View.VISIBLE); listView.setEnabled(false); switch(cacheOverlay.getType()) { case XYZ_DIRECTORY: deleteXYZCacheOverlay((XYZDirectoryCacheOverlay)cacheOverlay); break; case GEOPACKAGE: deleteGeoPackageCacheOverlay((GeoPackageCacheOverlay)cacheOverlay); break; } CacheProvider.getInstance(getActivity()).refreshTileOverlays(); } /** * Delete the GeoPackage cache overlay * @param geoPackageCacheOverlay */ private void deleteGeoPackageCacheOverlay(GeoPackageCacheOverlay geoPackageCacheOverlay) { String database = geoPackageCacheOverlay.getName(); // Get the GeoPackage file GeoPackageManager manager = GeoPackageFactory.getManager(getActivity()); File path = manager.getFile(database); // Delete the cache from the GeoPackage manager manager.delete(database); // Attempt to delete the cache file if it is in the cache directory File pathDirectory = path.getParentFile(); if(path.canWrite() && pathDirectory != null) { Map<StorageUtility.StorageType, File> storageLocations = StorageUtility.getWritableStorageLocations(); for (File storageLocation : storageLocations.values()) { File root = new File(storageLocation, getString(R.string.overlay_cache_directory)); if (root.equals(pathDirectory)) { path.delete(); break; } } } // Check internal/external application storage File applicationCacheDirectory = CacheUtils.getApplicationCacheDirectory(getActivity()); if (applicationCacheDirectory != null && applicationCacheDirectory.exists()) { for (File cache : applicationCacheDirectory.listFiles()) { if (cache.equals(path)) { path.delete(); break; } } } if (path.getAbsolutePath().startsWith(String.format("%s/MAGE/geopackages", getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)))) { LayerHelper layerHelper = LayerHelper.getInstance(getContext()); try { String relativePath = path.getAbsolutePath().split(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/")[1]; Layer layer = layerHelper.getByRelativePath(relativePath); if (layer != null) { layer.setLoaded(false); layer.setDownloadId(null); layerHelper.update(layer); } } catch (LayerException e) { Log.e(LOG_NAME, "Error setting loaded to false for path " + path, e); } if (!path.delete()) { Log.e(LOG_NAME, "Error deleting geopackage file from filesystem for path " + path); } } } } /** * Cache Overlay Expandable list adapter */ public static class OverlayAdapter extends BaseExpandableListAdapter { /** * Context */ private Activity activity; /** * List of cache overlays */ private List<CacheOverlay> overlays; /** * List of geopackages */ private List<Layer> geopackages = new ArrayList<>(); private GeoPackageDownloadManager downloadManager; /** * Constructor * * @param activity * @param overlays */ public OverlayAdapter(Activity activity, Event event, List<CacheOverlay> overlays, List<Layer> geopackages, GeoPackageDownloadManager downloadManager) { this.activity = activity; this.overlays = new CacheOverlayFilter(activity.getApplicationContext(), event).filter(overlays); this.geopackages = geopackages; this.downloadManager = downloadManager; } public void addOverlay(CacheOverlay overlay, Layer layer) { if (layer.isLoaded()) { geopackages.remove(layer); overlays.add(overlay); } } /** * Get the overlays * * @return */ public List<CacheOverlay> getOverlays() { return overlays; } public List<Layer> getGeopackages() { return geopackages; } public void updateDownloadProgress(View view, int progress, long size) { if (progress <= 0) { return; } ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.layer_progress); if (progressBar == null) { return; } int currentProgress = (int) (progress / (float) size * 100); progressBar.setProgress(currentProgress); TextView layerSize = (TextView) view.findViewById(R.id.layer_size); layerSize.setText(String.format("Downloading: %s of %s", Formatter.formatFileSize(activity.getApplicationContext(), progress), Formatter.formatFileSize(activity.getApplicationContext(), size))); } @Override public int getGroupCount() { return overlays.size() + geopackages.size(); } @Override public int getChildrenCount(int i) { if (i < geopackages.size()) { return 0; } else { int children = overlays.get(i - geopackages.size()).getChildren().size(); for (Layer geopackage : geopackages) { if (geopackage.isLoaded()) { children++; } } return children; } } @Override public Object getGroup(int i) { if (i < geopackages.size()) { return geopackages.get(i); } else { return overlays.get(i - geopackages.size()); } } @Override public Object getChild(int i, int j) { return overlays.get(i - geopackages.size()).getChildren().get(j); } @Override public long getGroupId(int i) { return i; } @Override public long getChildId(int i, int j) { return j; } @Override public boolean hasStableIds() { return false; } @Override public View getGroupView(int i, boolean isExpanded, View view, ViewGroup viewGroup) { if (i < geopackages.size()) { return getLayerView(i, isExpanded, view, viewGroup); } else { return getOverlayView(i, isExpanded, view, viewGroup); } } private View getOverlayView(int i, boolean isExpanded, View view, ViewGroup viewGroup) { LayoutInflater inflater = LayoutInflater.from(activity); view = inflater.inflate(R.layout.cache_overlay_group, viewGroup, false); final CacheOverlay overlay = overlays.get(i - geopackages.size()); view.findViewById(R.id.section_header).setVisibility(i == geopackages.size() ? View.VISIBLE : View.GONE); ImageView imageView = (ImageView) view.findViewById(R.id.cache_overlay_group_image); TextView cacheName = (TextView) view.findViewById(R.id.cache_overlay_group_name); TextView childCount = (TextView) view.findViewById(R.id.cache_overlay_group_count); CheckBox checkBox = (CheckBox) view.findViewById(R.id.cache_overlay_group_checkbox); checkBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean checked = ((CheckBox) v).isChecked(); overlay.setEnabled(checked); boolean modified = false; for (CacheOverlay childCache : overlay.getChildren()) { if (childCache.isEnabled() != checked) { childCache.setEnabled(checked); modified = true; } } if (modified) { notifyDataSetChanged(); } } }); Integer imageResource = overlay.getIconImageResourceId(); if (imageResource != null) { imageView.setImageResource(imageResource); } else { imageView.setImageResource(-1); } Layer layer = null; if (overlay instanceof GeoPackageCacheOverlay) { String filePath = ((GeoPackageCacheOverlay) overlay).getFilePath(); if (filePath.startsWith(String.format("%s/MAGE/geopackages", activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)))) { try { String relativePath = filePath.split(activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/")[1]; layer = LayerHelper.getInstance(activity).getByRelativePath(relativePath); } catch(Exception e) { Log.e(LOG_NAME, "Error getting layer by relative paht", e); } } } cacheName.setText(layer != null ? layer.getName() : overlay.getName()); if (overlay.isSupportsChildren()) { childCount.setText("(" + getChildrenCount(i) + ")"); } else { childCount.setText(""); } checkBox.setChecked(overlay.isEnabled()); return view; } private View getLayerView(int i, boolean isExpanded, View view, ViewGroup viewGroup) { LayoutInflater inflater = LayoutInflater.from(activity); view = inflater.inflate(R.layout.layer_overlay, viewGroup, false); final Layer layer = geopackages.get(i); view.findViewById(R.id.section_header).setVisibility(i == 0 ? View.VISIBLE : View.GONE); TextView cacheName = (TextView) view.findViewById(R.id.layer_name); cacheName.setText(layer.getName()); TextView layerSize = (TextView) view.findViewById(R.id.layer_size); final ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.layer_progress); final View download = view.findViewById(R.id.layer_download); if (downloadManager.isDownloading(layer)) { int progress = downloadManager.getProgress(layer); long fileSize = layer.getFileSize(); progressBar.setVisibility(View.VISIBLE); download.setVisibility(View.GONE); view.setEnabled(false); view.setOnClickListener(null); int currentProgress = (int) (progress / (float) layer.getFileSize() * 100); progressBar.setProgress(currentProgress); layerSize.setVisibility(View.VISIBLE); layerSize.setText(String.format("Downloading: %s of %s", Formatter.formatFileSize(activity.getApplicationContext(), progress), Formatter.formatFileSize(activity.getApplicationContext(), fileSize))); } else { progressBar.setVisibility(View.GONE); download.setVisibility(View.VISIBLE); } download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progressBar.setVisibility(View.VISIBLE ); download.setVisibility(View.GONE); downloadManager.downloadGeoPackage(layer); } }); return view; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = LayoutInflater.from(activity); convertView = inflater.inflate(R.layout.cache_overlay_child, parent, false); } final CacheOverlay overlay = overlays.get(groupPosition - geopackages.size()); final CacheOverlay childCache = overlay.getChildren().get(childPosition); ImageView imageView = (ImageView) convertView.findViewById(R.id.cache_overlay_child_image); TextView tableName = (TextView) convertView.findViewById(R.id.cache_overlay_child_name); TextView info = (TextView) convertView.findViewById(R.id.cache_overlay_child_info); CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.cache_overlay_child_checkbox); convertView.findViewById(R.id.divider).setVisibility(isLastChild ? View.VISIBLE : View.INVISIBLE); checkBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean checked = ((CheckBox) v).isChecked(); childCache.setEnabled(checked); boolean modified = false; if (checked) { if (!overlay.isEnabled()) { overlay.setEnabled(true); modified = true; } } else if (overlay.isEnabled()) { modified = true; for (CacheOverlay childCache : overlay.getChildren()) { if (childCache.isEnabled()) { modified = false; break; } } if (modified) { overlay.setEnabled(false); } } if (modified) { notifyDataSetChanged(); } } }); tableName.setText(childCache.getName()); info.setText(childCache.getInfo()); checkBox.setChecked(childCache.isEnabled()); Integer imageResource = childCache.getIconImageResourceId(); if (imageResource != null){ imageView.setImageResource(imageResource); } else { imageView.setImageResource(-1); } return convertView; } @Override public boolean isChildSelectable(int i, int j) { return true; } } }
package roart.aggregator.impl; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.lang3.ArrayUtils; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import roart.aggregatorindicator.impl.Recommend; import roart.category.AbstractCategory; import roart.common.config.MyConfig; import roart.common.config.MyMyConfig; import roart.common.pipeline.PipelineConstants; import roart.gene.CalcGene; import roart.gene.impl.CalcComplexGene; import roart.gene.impl.CalcDoubleGene; import roart.gene.impl.CalcGeneUtils; import roart.common.constants.CategoryConstants; import roart.common.constants.Constants; import roart.indicator.AbstractIndicator; import roart.indicator.util.IndicatorUtils; import roart.model.StockItem; import roart.pipeline.Pipeline; import roart.result.model.ResultItemTableRow; import roart.model.data.MarketData; import roart.model.data.PeriodData; import roart.talib.util.TaUtil; import roart.pipeline.common.aggregate.Aggregator; public class AggregatorRecommenderIndicator extends Aggregator { Map<String, Double[]> listMap; Map<String, List<Recommend>> usedRecommenders; Map<String, Map<String, Double[]>> resultMap; public List<String> disableList; public AggregatorRecommenderIndicator(MyMyConfig conf, String index, List<StockItem> stocks, Map<String, MarketData> marketdatamap, Map<String, PeriodData> periodDataMap, AbstractCategory[] categories, Pipeline[] datareaders, List<String> disableList) throws Exception { super(conf, index, 0); this.disableList = disableList; AbstractCategory cat = IndicatorUtils.getWantedCategory(categories, marketdatamap.get(conf.getMarket()).meta); if (cat == null) { return; } Map<String, AbstractIndicator> usedIndicatorMap = cat.getIndicatorMap(); Map<String, Map<String, Object>> localResultMap = cat.getIndicatorLocalResultMap(); Map<String, Double[]> list0 = (Map<String, Double[]>) localResultMap.get(localResultMap.keySet().iterator().next()).get(PipelineConstants.LIST); usedRecommenders = Recommend.getUsedRecommenders(conf); Map<String, List<String>[]> recommendKeyMap = Recommend.getRecommenderKeyMap(usedRecommenders, usedIndicatorMap, conf); Map<String, AbstractIndicator> indicatorMap = new HashMap<>(); this.category = cat.getPeriod(); this.title = cat.getTitle(); Set<String> ids = new HashSet<>(); ids.addAll(list0.keySet()); Map<String, AbstractIndicator> newIndicatorMap = new HashMap<>(); for (Entry<String, List<Recommend>> entry : usedRecommenders.entrySet()) { List<Recommend> list = entry.getValue(); for (Recommend recommend : list) { String indicator = recommend.indicator(); if (indicator != null) { AbstractIndicator newIndicator = recommend.getIndicator(marketdatamap, category, newIndicatorMap, usedIndicatorMap, datareaders); if (newIndicator != null) { indicatorMap.put(indicator, newIndicator); } } // fix Map<String, Object[]> aResult = (Map<String, Object[]>) cat.getIndicatorLocalResultMap().get(indicator).get(PipelineConstants.LIST); ids.retainAll(aResult.keySet()); } } Map<String, Double[]> result = new HashMap<>(); TaUtil tu = new TaUtil(); resultMap = new HashMap<>(); if (!isEnabled()) { return; } for (Entry<String, List<Recommend>> entry : usedRecommenders.entrySet()) { String recommender = entry.getKey(); List<String>[] buysell = recommendKeyMap.get(recommender); List<AbstractIndicator> indicators = Recommend.getIndicators(recommender, usedRecommenders, indicatorMap); // We just want the config, any in the list will do Object[] retObj = IndicatorUtils.getDayIndicatorMap(conf, tu, indicators, 0 /*recommend.getFutureDays()*/, 1 /*conf.getTableDays()*/, 1 /*recommend.getIntervalDays()*/, null); Map<Integer, Map<String, Double[]>> dayIndicatorMap = (Map<Integer, Map<String, Double[]>>) retObj[0]; result = dayIndicatorMap.get(0); List<Double>[] macdrsiMinMax = (List<Double>[]) retObj[1]; List<String> buyKeys = buysell[0]; List<String> sellKeys = buysell[1]; CalcGeneUtils.transformToNode(conf, buyKeys, true, macdrsiMinMax, disableList); CalcGeneUtils.transformToNode(conf, sellKeys, false, macdrsiMinMax, disableList); // find recommendations Map<String, Double[]> indicatorResultMap; indicatorResultMap = new HashMap<>(); for (String id : ids) { if (id.equals("KZKAK:IND")) { int jj=0; } Double[] aResult = new Double[2]; System.out.println("ttt " + result.get(id)); Double[] mergedResult = result.get(id); if (mergedResult == null || mergedResult.length == 0) { continue; } double buyRecommendValue = 0; double sellRecommendValue = 0; for (int i = 0; i < buyKeys.size(); i++) { String key = buyKeys.get(i); if (disableList.contains(key)) { continue; } // temp fix Object o = conf.getConfigValueMap().get(key); if (o instanceof Integer) { Integer oint = (Integer) o; buyRecommendValue += mergedResult[i] * oint; continue; } Object tmp = conf.getConfigValueMap().get(key); CalcGene node = (CalcGene) conf.getConfigValueMap().get(key); //node.setDoBuy(useMax); if (mergedResult.length < buyKeys.size()) { int jj = 0; } double value = mergedResult[i]; buyRecommendValue += node.calc(value, 0); } aResult[0] = buyRecommendValue; for (int i = 0; i < sellKeys.size(); i++) { String key = sellKeys.get(i); if (disableList.contains(key)) { continue; } // temp fix Object o = conf.getConfigValueMap().get(key); if (o instanceof Integer) { Integer oint = (Integer) o; sellRecommendValue += mergedResult[i] * oint; continue; } CalcGene node = (CalcGene) conf.getConfigValueMap().get(key); //node.setDoBuy(useMax); double value = mergedResult[i]; sellRecommendValue += node.calc(value, 0); } aResult[1] = sellRecommendValue; indicatorResultMap.put(id, aResult); } resultMap.put(recommender, indicatorResultMap); } } @Override public boolean isEnabled() { return conf.wantIndicatorRecommender(); } @Override public Object[] getResultItem(StockItem stock) { Double[] arrayResult = new Double[0]; if (usedRecommenders == null) { return arrayResult; } for (String recommender : usedRecommenders.keySet()) { Map<String, Double[]> indicatorResultMap = resultMap.get(recommender); Double[] aResult = indicatorResultMap.get(stock.getId()); int size = usedRecommenders.keySet().size(); if (aResult == null || aResult.length < size) { aResult = new Double[size]; } arrayResult = ArrayUtils.addAll(arrayResult, aResult); } return arrayResult; } @Override public void addResultItemTitle(ResultItemTableRow headrow) { if (usedRecommenders == null) { return; } for (String recommender : usedRecommenders.keySet()) { headrow.add("Buy" + Constants.WEBBR + recommender); headrow.add("Sell" + Constants.WEBBR + recommender); } } @Override public void addResultItem(ResultItemTableRow row, StockItem stock) { Object[] arrayResult = getResultItem(stock); row.addarr(arrayResult); } @Override public String getName() { return PipelineConstants.AGGREGATORRECOMMENDERINDICATOR; } @Override public Map<String, Object> getLocalResultMap() { Map<String, Object> map = new HashMap<>(); map.put(PipelineConstants.CATEGORY, category); map.put(PipelineConstants.CATEGORYTITLE, title); map.put(PipelineConstants.RESULT, resultMap); return map; } }
package coffee; import dagger.Component; import javax.inject.Singleton; public class CoffeeApp { @Singleton @Component(modules = { DripCoffeeModule.class }) public interface CoffeeShop { CoffeeMaker maker(); } public static void main(String[] args) { CoffeeShop coffeeShop = DaggerCoffeeApp_CoffeeShop.builder().build(); coffeeShop.maker().brew(); } }
package VASSAL.tools.image; import java.awt.image.BufferedImage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import VASSAL.tools.io.TemporaryFileFactory; import VASSAL.tools.lang.Reference; /** * Convert a {@link BufferedImage} to a different type, falling back to * conversion on disk if convertion in memory fails. * * @since 3.2.0 * @author Joel Uckelman */ public class FallbackImageTypeConverter implements ImageTypeConverter { private static final Logger logger = LoggerFactory.getLogger(FallbackImageTypeConverter.class); protected final TemporaryFileFactory tfactory; protected final ImageTypeConverter memory_converter; protected final ImageTypeConverter file_converter; /** * Create a converter. * * @param tfactory the temporary file factory */ public FallbackImageTypeConverter(TemporaryFileFactory tfactory) { this( tfactory, new MemoryImageTypeConverter(), new FileImageTypeConverter(tfactory) ); } /** * Create a converter. * * @param tfactory the temporary file factory * @param memory_converter the in-memory image converter * @param file_converter the on-disk image converter */ FallbackImageTypeConverter( TemporaryFileFactory tfactory, ImageTypeConverter memory_converter, ImageTypeConverter file_converter) { this.tfactory = tfactory; this.memory_converter = memory_converter; this.file_converter = file_converter; } /** {@inheritDoc} */ public BufferedImage convert(Reference<BufferedImage> ref, int type) throws ImageIOException { try { return memory_converter.convert(ref, type); } catch (OutOfMemoryError e) { // This is ok, we just don't have enough free heap for the conversion. logger.info("Switching to FileImageTypeConverter..."); } // Try converting on disk instead. return file_converter.convert(ref, type); } }
package jolie.net.http; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class HttpMessage { public enum Type { RESPONSE, POST, GET, UNSUPPORTED, ERROR } public enum Version { HTTP_1_0, HTTP_1_1 } static public class Cookie { private final String name, value, domain, path, expirationDate; private final boolean secure; public Cookie( String name, String value, String domain, String path, String expirationDate, boolean secure ) { this.name = name; this.value = value; this.domain = domain; this.path = path; this.expirationDate = expirationDate; this.secure = secure; } @Override public String toString() { return( name + "=" + value + "; " + "expires=" + expirationDate + "; " + "domain=" + domain + "; " + "path=" + path + ( ( secure ) ? ( "; secure" ) : "" ) ); } public String name() { return name; } public String value() { return value; } public String path() { return path; } public String domain() { return domain; } public String expirationDate() { return expirationDate; } public boolean secure() { return secure; } } private Version version; private Type type; private byte[] content = null; final private Map< String, String > propMap = new HashMap< String, String > (); final private List< Cookie > setCookies = new ArrayList< Cookie > (); final private Map< String, String > cookies = new HashMap< String, String >(); private int httpCode; private String requestPath; private String reason; private String userAgent; public boolean isSupported() { return type != Type.UNSUPPORTED; } public boolean isGet() { return type == Type.GET; } public void addCookie( String name, String value ) { cookies.put( name, value); } public Map< String, String > cookies() { return cookies; } public void addSetCookie( Cookie cookie ) { setCookies.add( cookie ); } public List< Cookie > setCookies() { return setCookies; } public HttpMessage( Type type ) { this.type = type; } protected void setVersion( Version version ) { this.version = version; } public Version version() { return version; } public void setContent( byte[] content ) { this.content = content; } public Collection< Entry< String, String > > properties() { return propMap.entrySet(); } public void setRequestPath( String path ) { requestPath = path; } public void setUserAgent( String userAgent ) { this.userAgent = userAgent; } public void setProperty( String name, String value ) { propMap.put( name, value ); } public String getProperty( String name ) { return propMap.get( name.toLowerCase() ); } public String getPropertyOrEmptyString( String name ) { String ret = propMap.get( name ); return ( ret == null ) ? "" : ret; } public String reason() { return reason; } public void setReason( String reason ) { this.reason = reason; } public int size() { if ( content == null ) return 0; return content.length; } public String requestPath() { return requestPath; } public String userAgent() { return userAgent; } /*public Type type() { return type; }*/ public boolean isResponse() { return type == Type.RESPONSE; } public boolean isError() { return type == Type.ERROR; } public int httpCode() { return httpCode; } public void setHttpCode( int code ) { httpCode = code; } public byte[] content() { return content; } }
package agentgui.envModel.p2Dsvg.display; import jade.core.AID; import jade.core.Agent; import jade.core.ServiceException; import jade.core.behaviours.TickerBehaviour; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import org.w3c.dom.Document; import agentgui.core.application.Application; import agentgui.core.application.Language; import agentgui.envModel.p2Dsvg.controller.Physical2DEnvironmentController; import agentgui.envModel.p2Dsvg.controller.Physical2DEnvironmentControllerGUI; import agentgui.envModel.p2Dsvg.ontology.Physical2DEnvironment; import agentgui.envModel.p2Dsvg.ontology.Physical2DObject; import agentgui.envModel.p2Dsvg.ontology.PositionUpdate; import agentgui.envModel.p2Dsvg.provider.EnvironmentProviderHelper; import agentgui.envModel.p2Dsvg.provider.EnvironmentProviderService; import agentgui.simulationService.SimulationServiceHelper; import agentgui.simulationService.environment.EnvironmentModel; import agentgui.simulationService.time.TimeModelDiscrete; /** * This type of agent controls a visualization of a Physical2DEnvironment * * @author Nils Loose - DAWIS - ICB - University of Duisburg - Essen * @author Tim Lewen - DAWIS - ICB - University of Duisburg - Essen */ public class DisplayAgent extends Agent { private static final long serialVersionUID = 8613715346940866246L; private static final int PERIOD = 50; /** * The DisplayAgent's GUI */ private DisplayAgentGUI myGUI = null; private JFrame useFrame = null; private JPanel usePanel = null; private Document svgDoc = null; private Physical2DEnvironment environment = null; private EnvironmentProviderHelper envHelper = null; private int lastMaximumValue = -2; private int lastCurrentValue = -1; private int sameTransactionSizeCounter = 0; private int sameVisualisationCounter = 0; private int counter = 0; private int addValue = 1; private long initialTimeStep = 0; private boolean play = true; public void setup() { int use4Visualization = 0; Object[] startArgs = getArguments(); if (startArgs == null || startArgs.length == 0) { use4Visualization = 1; useFrame = getIndependentFrame(); try { EnvironmentProviderHelper helper = (EnvironmentProviderHelper) getHelper(EnvironmentProviderService.SERVICE_NAME); svgDoc = helper.getSVGDoc(); environment = helper.getEnvironment(); } catch (ServiceException e) { System.err.println(getLocalName() + " - Error: Could not retrieve EnvironmentProviderHelper, shutting down!"); doDelete(); } } else { use4Visualization = 2; usePanel = (JPanel) startArgs[0]; Physical2DEnvironmentControllerGUI envPanel = (Physical2DEnvironmentControllerGUI) startArgs[1]; Physical2DEnvironmentController p2DCont = (Physical2DEnvironmentController) envPanel.getEnvironmentController(); environment = p2DCont.getEnvironmentModelCopy(); svgDoc = p2DCont.getSvgDocCopy(); try { EnvironmentProviderHelper helper = (EnvironmentProviderHelper) getHelper(EnvironmentProviderService.SERVICE_NAME); helper.setEnvironment(environment); helper.setSVGDoc(svgDoc); } catch (ServiceException e) { System.err.println(getLocalName() + " - Error: Could not set EnvironmentProviderHelper, shutting down!"); } } this.myGUI = new DisplayAgentGUI(svgDoc, environment); switch (use4Visualization) { case 1: useFrame.setContentPane(myGUI); useFrame.setSize(800, 600); useFrame.setVisible(true); useFrame.pack(); break; case 2: usePanel.add(myGUI, BorderLayout.CENTER); usePanel.repaint(); break; } try { myGUI.jPanelSimuInfos.setVisible(true); SimulationServiceHelper simHelper = (SimulationServiceHelper) getHelper(SimulationServiceHelper.SERVICE_NAME); EnvironmentModel envModel = simHelper.getEnvironmentModel(); while (envModel == null) { Thread.sleep(100); envModel = simHelper.getEnvironmentModel(); } TimeModelDiscrete model = (TimeModelDiscrete) envModel.getTimeModel(); initialTimeStep = model.getStep(); String unit = Language.translate("Sekunden"); myGUI.jLabelSpeedFactor.setText((initialTimeStep / 1000.0)+ " " + unit); } catch (Exception e) { e.printStackTrace(); } myGUI.jButtonPlay.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { play = !play; envHelper.setRunning(play); String pathImage = Application.RunInfo.PathImageIntern(); Icon icon = null; if (play) { icon = new ImageIcon(getClass().getResource( pathImage + "MBLoadPause.png")); } else { icon = new ImageIcon(getClass().getResource( pathImage + "MBLoadPlay.png")); } myGUI.jButtonPlay.setIcon(icon); sameVisualisationCounter = 0; } }); // the user change the status of the simulation myGUI.jSliderTime.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent e) { counter = myGUI.jSliderTime.getValue(); sameVisualisationCounter = 0; if (counter == -1) { counter = 0; } try { if (envHelper != null) { if (initialTimeStep == 0) { SimulationServiceHelper simHelper = (SimulationServiceHelper) getHelper(SimulationServiceHelper.SERVICE_NAME); TimeModelDiscrete model = (TimeModelDiscrete) simHelper.getEnvironmentModel().getTimeModel(); initialTimeStep = model.getStep(); } String unit = Language.translate("Sekunden"); myGUI.jLabelTimeDisplay.setText((initialTimeStep * myGUI.jSliderTime.getValue())/ 1000.0 + " " + unit); } else { envHelper = (EnvironmentProviderHelper) getHelper(EnvironmentProviderService.SERVICE_NAME); } } catch (Exception ex) { ex.printStackTrace(); } } }); // User adjusted the simulation time steps myGUI.jSliderVisualation.addChangeListener(new javax.swing.event.ChangeListener() { SimulationServiceHelper simHelper = null; public void stateChanged(javax.swing.event.ChangeEvent e) { // Call simu service and tell him that something is // changed! try { if (simHelper == null) { simHelper = (SimulationServiceHelper) getHelper(SimulationServiceHelper.SERVICE_NAME); TimeModelDiscrete model = (TimeModelDiscrete) simHelper.getEnvironmentModel().getTimeModel(); initialTimeStep = model.getStep(); } String unit = Language.translate("Sekunden"); myGUI.jLabelSpeedFactor.setText((((myGUI.jSliderVisualation.getValue() * initialTimeStep)) / 1000.0) + " " + unit); addValue = myGUI.jSliderVisualation.getValue(); } catch (Exception ex) { ex.printStackTrace(); } } }); addBehaviour(new UpdateSVGBehaviour()); } public void takeDown() { if (useFrame != null) { useFrame.dispose(); } if (usePanel != null) { myGUI = null; usePanel.removeAll(); usePanel.repaint(); } } private JFrame getIndependentFrame() { JFrame frame = new JFrame(); frame.setTitle("DisplayAgent " + getLocalName() + " - GUI"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { DisplayAgent.this.doDelete(); } }); return frame; } /** * * @author Nils Loose - DAWIS - ICB - University of Duisburg - Essen */ private class UpdateSVGBehaviour extends TickerBehaviour { private static final long serialVersionUID = -4205541330627054644L; private EnvironmentProviderHelper helper; public UpdateSVGBehaviour() { super(DisplayAgent.this, PERIOD); try { helper = (EnvironmentProviderHelper) getHelper(EnvironmentProviderService.SERVICE_NAME); } catch (ServiceException e) { System.err.println(getLocalName()+ " - EnvironmentProviderHelper not found, shutting down"); doDelete(); } } public HashSet<Physical2DObject> fordwardToVisualation( HashMap<AID, PositionUpdate> pos) { HashSet<Physical2DObject> movingObjects = envHelper .getCurrentlyMovingObjects(); // Clear map movingObjects.clear(); Set<AID> keys = pos.keySet(); Iterator<AID> it = keys.iterator(); while (it.hasNext()) { AID aid = it.next(); Physical2DObject obj = envHelper.getObject(aid.getLocalName()); obj.setPosition(pos.get(aid).getNewPosition()); movingObjects.add(obj); } return movingObjects; } @Override protected void onTick() { try { int size = -1; if (sameTransactionSizeCounter == 20) { size = lastMaximumValue; } else { size = helper.getTransactionSize(); if (lastMaximumValue != size) { sameTransactionSizeCounter = 0; myGUI.setMaximum(size); } else { sameTransactionSizeCounter++; } } if (size > 1) { if (lastCurrentValue == counter) { sameVisualisationCounter++; } else { sameVisualisationCounter = 0; } if (sameVisualisationCounter < 20) { HashSet<Physical2DObject> movingObjects = this.fordwardToVisualation(helper.getModel(counter)); synchronized (movingObjects) { myGUI.updatePositions(movingObjects); } myGUI.setCurrentTimePos(counter); if (play) { if (counter + addValue < size) { counter = counter + addValue; } } lastMaximumValue = size; lastCurrentValue = counter; } } else { } } catch (Exception e) { e.printStackTrace(); } } } }
package it.eonardol.plugins; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import android.content.Intent; import android.net.Uri; import android.util.Log; import android.content.pm.PackageManager; public class CustomUrlLauncher extends CordovaPlugin { private static final String ACTION_LAUNCH_EVENT = "launch"; private static final String ACTION_CAN_LAUNCH_EVENT = "canLaunch"; private static final String LOG_TAG = "CustomUrlLauncher"; @Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { if (ACTION_LAUNCH_EVENT.equals(action)) { final String urlToLaunch = args.getString(0); Log.i(LOG_TAG, "opening " + urlToLaunch); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlToLaunch)); browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.cordova.getActivity().startActivity(browserIntent); callbackContext.success(); return true; } else if (ACTION_CAN_LAUNCH_EVENT.equals(action)) { PackageManager manager = getPackageManager(); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(Uri.parse(urlToLaunch)); List<ResolveInfo> infos = manager.queryIntentActivities (intent, PackageManager.GET_RESOLVED_FILTER); Log.i(LOG_TAG, "result " + infos); Log.i(LOG_TAG, "result " + infos.size()); } else { callbackContext.error("customurllauncher." + action + " is not a supported function. Did you mean '" + ACTION_LAUNCH_EVENT + "'?"); return false; } } }
package be.ibridge.kettle.job.entry; import java.util.ArrayList; import org.eclipse.swt.widgets.Shell; import org.w3c.dom.Node; import be.ibridge.kettle.core.Result; import be.ibridge.kettle.core.database.DatabaseMeta; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleXMLException; import be.ibridge.kettle.job.Job; import be.ibridge.kettle.job.JobMeta; import be.ibridge.kettle.job.entry.createfile.JobEntryCreateFile; import be.ibridge.kettle.job.entry.deletefile.JobEntryDeleteFile; import be.ibridge.kettle.job.entry.eval.JobEntryEval; import be.ibridge.kettle.job.entry.filecompare.JobEntryFileCompare; import be.ibridge.kettle.job.entry.fileexists.JobEntryFileExists; import be.ibridge.kettle.job.entry.ftp.JobEntryFTP; import be.ibridge.kettle.job.entry.http.JobEntryHTTP; import be.ibridge.kettle.job.entry.job.JobEntryJob; import be.ibridge.kettle.job.entry.mail.JobEntryMail; import be.ibridge.kettle.job.entry.mysqlbulkload.JobEntryMysqlBulkLoad; import be.ibridge.kettle.job.entry.msgboxinfo.JobEntryMsgBoxInfo; import be.ibridge.kettle.job.entry.sftp.JobEntrySFTP; import be.ibridge.kettle.job.entry.sftpput.JobEntrySFTPPUT; import be.ibridge.kettle.job.entry.shell.JobEntryShell; import be.ibridge.kettle.job.entry.special.JobEntrySpecial; import be.ibridge.kettle.job.entry.sql.JobEntrySQL; import be.ibridge.kettle.job.entry.tableexists.JobEntryTableExists; import be.ibridge.kettle.job.entry.trans.JobEntryTrans; import be.ibridge.kettle.job.entry.waitforfile.JobEntryWaitForFile; import be.ibridge.kettle.repository.Repository; /** * Interface for the different JobEntry classes. * * @author Matt * @since 18-06-04 * */ public interface JobEntryInterface { public final static int TYPE_JOBENTRY_NONE = 0; public final static int TYPE_JOBENTRY_TRANSFORMATION = 1; public final static int TYPE_JOBENTRY_JOB = 2; public final static int TYPE_JOBENTRY_SHELL = 3; public final static int TYPE_JOBENTRY_MAIL = 4; public final static int TYPE_JOBENTRY_SQL = 5; public final static int TYPE_JOBENTRY_FTP = 6; public final static int TYPE_JOBENTRY_TABLE_EXISTS = 7; public final static int TYPE_JOBENTRY_FILE_EXISTS = 8; public final static int TYPE_JOBENTRY_EVALUATION = 9; public final static int TYPE_JOBENTRY_SPECIAL = 10; public static final int TYPE_JOBENTRY_SFTP = 11; public static final int TYPE_JOBENTRY_HTTP = 12; public static final int TYPE_JOBENTRY_CREATE_FILE = 13; public static final int TYPE_JOBENTRY_DELETE_FILE = 14; public static final int TYPE_JOBENTRY_WAIT_FOR_FILE = 15; public static final int TYPE_JOBENTRY_SFTPPUT = 16; public static final int TYPE_JOBENTRY_FILE_COMPARE = 17; public static final int TYPE_JOBENTRY_MYSQL_BULK_LOAD= 18; public static final int TYPE_JOBENTRY_MSGBOX_INFO= 19; public final static String typeCode[] = { "-", "TRANS", "JOB", "SHELL", "MAIL", "SQL", "FTP", "TABLE_EXISTS", "FILE_EXISTS", "EVAL", "SPECIAL", "SFTP", "HTTP", "CREATE_FILE", "DELETE_FILE", "WAIT_FOR_FILE", "SFTPPUT", "FILE_COMPARE", "MYSQL_BULK_LOAD", "MSGBOX_INFO", }; public final static String typeDesc[] = { "-", Messages.getString("JobEntry.Trans.TypeDesc"), Messages.getString("JobEntry.Job.TypeDesc"), Messages.getString("JobEntry.Shell.TypeDesc"), Messages.getString("JobEntry.Mail.TypeDesc"), Messages.getString("JobEntry.SQL.TypeDesc"), Messages.getString("JobEntry.FTP.TypeDesc"), Messages.getString("JobEntry.TableExists.TypeDesc"), Messages.getString("JobEntry.FileExists.TypeDesc"), Messages.getString("JobEntry.Evaluation.TypeDesc"), Messages.getString("JobEntry.Special.TypeDesc"), Messages.getString("JobEntry.SFTP.TypeDesc"), Messages.getString("JobEntry.HTTP.TypeDesc"), Messages.getString("JobEntry.CreateFile.TypeDesc"), Messages.getString("JobEntry.DeleteFile.TypeDesc"), Messages.getString("JobEntry.WaitForFile.TypeDesc"), Messages.getString("JobEntry.SFTPPut.TypeDesc"), Messages.getString("JobEntry.FileCompare.TypeDesc"), Messages.getString("JobEntry.MysqlBulkLoad.TypeDesc"), Messages.getString("JobEntry.MsgBoxInfo.TypeDesc"), }; public final static String icon_filename[] = { "", "TRN.png", "JOB.png", "SHL.png", "MAIL.png", "SQL.png", "FTP.png", "TEX.png", "FEX.png", "RES.png", "", "SFT.png", "WEB.png", "CFJ.png", "DFJ.png", "WFF.png", "SFP.png", "BFC.png", "MBL.png", "INF.png", }; public final static String type_tooltip_desc[] = { "", Messages.getString("JobEntry.Trans.Tooltip"), Messages.getString("JobEntry.Job.Tooltip"), Messages.getString("JobEntry.Shell.Tooltip"), Messages.getString("JobEntry.Mail.Tooltip"), Messages.getString("JobEntry.SQL.Tooltip"), Messages.getString("JobEntry.FTP.Tooltip"), Messages.getString("JobEntry.TableExists.Tooltip"), Messages.getString("JobEntry.FileExists.Tooltip"), Messages.getString("JobEntry.Evaluation.Tooltip"), Messages.getString("JobEntry.Special.Tooltip"), Messages.getString("JobEntry.SFTP.Tooltip"), Messages.getString("JobEntry.HTTP.Tooltip"), Messages.getString("JobEntry.CreateFile.Tooltip"), Messages.getString("JobEntry.DeleteFile.Tooltip"), Messages.getString("JobEntry.WaitForFile.Tooltip"), Messages.getString("JobEntry.SFTPPut.Tooltip"), Messages.getString("JobEntry.FileCompare.Tooltip"), Messages.getString("JobEntry.MysqlBulkLoad.Tooltip"), Messages.getString("JobEntry.MsgBoxInfo.Tooltip"), }; public final static Class type_classname[] = { null, JobEntryTrans.class, JobEntryJob.class, JobEntryShell.class, JobEntryMail.class, JobEntrySQL.class, JobEntryFTP.class, JobEntryTableExists.class, JobEntryFileExists.class, JobEntryEval.class, JobEntrySpecial.class, JobEntrySFTP.class, JobEntryHTTP.class, JobEntryCreateFile.class, JobEntryDeleteFile.class, JobEntryWaitForFile.class, JobEntrySFTPPUT.class, JobEntryFileCompare.class, JobEntryMysqlBulkLoad.class, JobEntryMsgBoxInfo.class, }; public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) throws KettleException; public void clear(); public long getID(); public void setID(long id); public String getName(); public void setName(String name); public String getDescription(); public void setDescription(String description); public void setChanged(); public void setChanged(boolean ch); public boolean hasChanged(); public void loadXML(Node entrynode, ArrayList databases, Repository rep) throws KettleXMLException; public String getXML(); public void loadRep(Repository rep, long id_jobentry, ArrayList databases) throws KettleException; public void saveRep(Repository rep, long id_job) throws KettleException; public int getType(); public String getTypeCode(); public String getPluginID(); public boolean isStart(); public boolean isDummy(); public Object clone(); public boolean resetErrorsBeforeExecution(); public boolean evaluates(); public boolean isUnconditional(); public boolean isEvaluation(); public boolean isTransformation(); public boolean isJob(); public boolean isShell(); public boolean isMail(); public boolean isSpecial(); public ArrayList getSQLStatements(Repository repository) throws KettleException; public JobEntryDialogInterface getDialog(Shell shell,JobEntryInterface jei,JobMeta jobMeta,String jobName,Repository rep); public String getFilename(); public String getRealFilename(); /** * This method returns all the database connections that are used by the job entry. * @return an array of database connections meta-data. * Return an empty array if no connections are used. */ public DatabaseMeta[] getUsedDatabaseConnections(); public void setPluginID(String id); }
import org.libelektra.*; import org.libelektra.plugin.Echo; /** Simple hello world to see how Elektra can be used in Java. */ public class HelloElektra { public static void main(String[] args) { // Example 1: create a Key and print it System.out.println("Example 1"); final Key key = Key.create("user:/hello_world", "Hello World"); System.out.println(key); // to get name System.out.println(key.getString()); System.out.println(); // Example 2: adding basename for Key System.out.println("Example 2"); Key subKey = Key.create("user:/hello_world", "Sub Key"); subKey.addBaseName("sub_key"); System.out.println(subKey.getName()); System.out.println(subKey.getString()); System.out.println(); // Example 3: create a KeySet and print it System.out.println("Example 3"); final KeySet ks = KeySet.create(10, Key.create("user:/hello_world2", "Hello World2"), key); for (Key k : ks) { System.out.println("iter: " + k.getName() + " " + k.getString()); } System.out.println(ks); System.out.println(); // Example 4: duplicating a KeySet System.out.println("Example 4"); final KeySet ks2 = ks.dup(); ks2.copy(ks); System.out.println(ks2.size()); ks2.append(ks); ks2.append(key); System.out.println(); // Example 5: reading from the KDB System.out.println("Example 5"); try (final KDB kdb = KDB.open(key)) { kdb.get(ks, key); ks.lookup (key).ifPresent (k -> System.out.println (k.getString ())); } catch (KDBException e) { System.out.println(e); } System.out.println(); // Example 6: manually calling a Plugin (normally not needed) System.out.println("Example 6"); final Echo dp = new Echo(); dp.open(ks, key); dp.get(ks, key); dp.close(key); System.out.println(); // Example 7: Keys support different types System.out.println("Example 7"); final Key b = Key.create("user:/boolean", "true"); System.out.println(b.getBoolean()); b.setBoolean(false); System.out.println(b.getBoolean()); System.out.println(); // Example 8: iterating over keyname parts of a Key System.out.println("Example 8"); Key n = Key.create("user:/weird\\/name///\\\\/is/\no/_\\\\problem"); n.keyNameIterator().forEachRemaining(s -> System.out.println("itername: " + s)); System.out.println(); // Example 9: cutting part of a KeySet System.out.println("Example 9"); Key cutpoint = Key.create("user:/cutpoint"), ka = Key.create("user:/cutpoint/hello", "hiback"), kb = Key.create("user:/cutpoint/hello2", "hellotoo"), kc = Key.create("user:/outside/cutpoint/hello", "hellothere"); KeySet whole = KeySet.create(ka, kb, kc); System.out.println("Whole:"); System.out.println(whole); KeySet cut = whole.cut(cutpoint); System.out.println("Cut:"); System.out.println(cut); System.out.println("Rest:"); System.out.println(whole); System.out.println(); exampleSetMetaKeys(); exampleSetArrayMetaKey(); } private static void exampleSetMetaKeys() { // Example 9: Set and get meta keys System.out.println("Example 9"); Key key = Key.create("user:/key/with/meta"); key.setMeta("example", "anExampleValue"); var returnedMeta = key.getMeta("example").orElseThrow(AssertionError::new); System.out.println("Value of meta key 'example': " + returnedMeta.getString()); } private static void exampleSetArrayMetaKey() { // Example 10: Create an array using meta keys System.out.println("Example 10"); Key array = Key.create("user:/array"); // Create an array with length 2 array.setMeta("array", " Key firstEntry = Key.create("user:/array/#0/test"); firstEntry.setString("first"); Key secondEntry = Key.create("user:/array/#1/test"); secondEntry.setString("second"); KeySet ks = KeySet.create(array, firstEntry, secondEntry); ks.forEach( key -> { System.out.print(key + " = " + key.getString()); System.out.print(" | Meta: "); for (ReadableKey metaKey : key) { System.out.print(metaKey + " = " + metaKey.getString()); } System.out.println(); }); } }
package org.commcare.util.screen; import org.commcare.modern.session.SessionWrapper; import org.commcare.modern.util.Pair; import org.commcare.session.CommCareSession; import org.commcare.session.RemoteQuerySessionManager; import org.commcare.suite.model.DisplayUnit; import org.javarosa.core.model.instance.ExternalDataInstance; import org.javarosa.core.util.OrderedHashtable; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.net.URL; import java.util.Hashtable; import java.util.Map; import okhttp3.Credentials; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Screen that displays user configurable entry texts and makes * a case query to the server with these fields. * * @author wspride */ public class QueryScreen extends Screen { private RemoteQuerySessionManager remoteQuerySessionManager; private OrderedHashtable<String, DisplayUnit> userInputDisplays; private SessionWrapper sessionWrapper; private String[] fields; private String mTitle; private String currentMessage; private String domainedUsername; private String password; private PrintStream out; public QueryScreen(String domainedUsername, String password, PrintStream out) { this.domainedUsername = domainedUsername; this.password = password; this.out = out; } @Override public void init(SessionWrapper sessionWrapper) throws CommCareSessionException { this.sessionWrapper = sessionWrapper; remoteQuerySessionManager = RemoteQuerySessionManager.buildQuerySessionManager(sessionWrapper, sessionWrapper.getEvaluationContext()); if (remoteQuerySessionManager == null) { throw new CommCareSessionException(String.format("QueryManager for case " + "claim screen with id %s cannot be null.", sessionWrapper.getNeededData())); } userInputDisplays = remoteQuerySessionManager.getNeededUserInputDisplays(); int count = 0; fields = new String[userInputDisplays.keySet().size()]; for (Map.Entry<String, DisplayUnit> displayEntry : userInputDisplays.entrySet()) { fields[count] = displayEntry.getValue().getText().evaluate(sessionWrapper.getEvaluationContext()); } mTitle = "Case Claim"; } private static String buildUrl(String baseUrl, Hashtable<String, String> queryParams) { HttpUrl.Builder urlBuilder = HttpUrl.parse(baseUrl).newBuilder(); for (String key: queryParams.keySet()) { urlBuilder.addQueryParameter(key, queryParams.get(key)); } return urlBuilder.build().toString(); } private InputStream makeQueryRequestReturnStream() { String url = buildUrl(getBaseUrl().toString(), getQueryParams()); String credential = Credentials.basic(domainedUsername, password); Request request = new Request.Builder() .url(url) .header("Authorization", credential) .build(); try { Response response = new OkHttpClient().newCall(request).execute(); return response.body().byteStream(); } catch (IOException e) { e.printStackTrace(); return null; } } public boolean processResponse(InputStream responseData) { if (responseData == null) { currentMessage = "Query result null."; return false; } Pair<ExternalDataInstance, String> instanceOrError = remoteQuerySessionManager.buildExternalDataInstance(responseData); if (instanceOrError.first == null) { currentMessage = "Query response format error: " + instanceOrError.second; return false; } else if (isResponseEmpty(instanceOrError.first)) { currentMessage = "Query successful but returned no results."; return false; } else { sessionWrapper.setQueryDatum(instanceOrError.first); return true; } } private boolean isResponseEmpty(ExternalDataInstance instance) { return !instance.getRoot().hasChildren(); } public void answerPrompts(Hashtable<String, String> answers) { for(String key: answers.keySet()){ remoteQuerySessionManager.answerUserPrompt(key, answers.get(key)); } } protected URL getBaseUrl(){ return remoteQuerySessionManager.getBaseUrl(); } protected Hashtable<String, String> getQueryParams(){ return remoteQuerySessionManager.getRawQueryParams(); } public String getScreenTitle() { return mTitle; } @Override public void prompt(PrintStream out) { out.println("Enter the search fields as a space separated list."); for (int i=0; i< fields.length; i++) { out.println(i + ") " + fields[i]); } } @Override public String[] getOptions() { return fields; } @Override public boolean handleInputAndUpdateSession(CommCareSession session, String input) { String[] answers = input.split(","); Hashtable<String, String> userAnswers = new Hashtable<>(); int count = 0; for (Map.Entry<String, DisplayUnit> displayEntry : userInputDisplays.entrySet()) { userAnswers.put(displayEntry.getKey(), answers[count]); count ++; } answerPrompts(userAnswers); InputStream response = makeQueryRequestReturnStream(); boolean refresh = processResponse(response); if (currentMessage != null) { out.println(currentMessage); } return refresh; } public OrderedHashtable<String, DisplayUnit> getUserInputDisplays(){ return userInputDisplays; } public String getCurrentMessage(){ return currentMessage; } }
package userInterface; import gameRender.IsoCanvas; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.Border; import javax.swing.border.LineBorder; import com.sun.xml.internal.messaging.saaj.soap.JpegDataContentHandler; /** * * @author Venkata Peesapati * */ public class MainMenuPanel extends JPanel { private static final long serialVersionUID = 1L; JFrame currentFrame; JLabel gameName; JButton newGameButton; JButton loadButton; JButton storyButton; JButton controlsButton; JButton optionsButton; JButton exitButton; public MainMenuPanel(JFrame currentFrame) { this.currentFrame = currentFrame; setLayout(new GridLayout(7, 1)); gameName = new JLabel("Robot Mania"); gameName.setFont(gameName.getFont().deriveFont(40.0f)); gameName.setHorizontalAlignment(JLabel.CENTER); newGameButton = new JButton("New Game"); newGameButton.setOpaque(false); newGameButton.setContentAreaFilled(false); newGameButton.setBorderPainted(false); newGameButton.setFont(new Font("Arial", Font.PLAIN, 35)); newGameButton.setFocusPainted(false); newGameButton.setForeground(Color.black); newGameButton.addMouseListener(new HoverButtonListener()); newGameButton.addActionListener(new NewGameButtonListener()); loadButton = new JButton("Load Game"); loadButton.setOpaque(false); loadButton.setContentAreaFilled(false); loadButton.setBorderPainted(false); loadButton.setFont(new Font("Arial", Font.PLAIN, 35)); loadButton.setFocusPainted(false); loadButton.setForeground(Color.black); loadButton.addMouseListener(new HoverButtonListener()); storyButton = new JButton("Story"); storyButton.setOpaque(false); storyButton.setContentAreaFilled(false); storyButton.setBorderPainted(false); storyButton.setFont(new Font("Arial", Font.PLAIN, 35)); storyButton.setFocusPainted(false); storyButton.setForeground(Color.black); storyButton.addMouseListener(new HoverButtonListener()); controlsButton = new JButton("Controls"); controlsButton.setOpaque(false); controlsButton.setContentAreaFilled(false); controlsButton.setBorderPainted(false); controlsButton.setFont(new Font("Arial", Font.PLAIN, 35)); controlsButton.setFocusPainted(false); controlsButton.setForeground(Color.black); controlsButton.addMouseListener(new HoverButtonListener()); optionsButton = new JButton("Options"); optionsButton.setOpaque(false); optionsButton.setContentAreaFilled(false); optionsButton.setBorderPainted(false); optionsButton.setFont(new Font("Arial", Font.PLAIN, 35)); optionsButton.setFocusPainted(false); optionsButton.setForeground(Color.black); optionsButton.addMouseListener(new HoverButtonListener()); exitButton = new JButton("Exit"); exitButton.setOpaque(false); exitButton.setContentAreaFilled(false); exitButton.setBorderPainted(false); exitButton.setFont(new Font("Arial", Font.PLAIN, 35)); exitButton.setFocusPainted(false); exitButton.setForeground(Color.black); exitButton.addMouseListener(new HoverButtonListener()); exitButton.addActionListener(new ExitButtonListener()); add(gameName); add(newGameButton); add(loadButton); add(storyButton); add(controlsButton); add(optionsButton); add(exitButton); // This helps make the panel transparent. setOpaque(false); } // Action listeners for each of the buttons can go down here. /** * This is the listener class used for the newGameButton. It opens a new * canvas. * * @author Venkata Peesapati * */ class NewGameButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { currentFrame.getContentPane().removeAll(); currentFrame.getContentPane().validate(); currentFrame.getContentPane().repaint(); currentFrame.getContentPane().add(new IsoCanvas(), BorderLayout.CENTER); currentFrame.getContentPane().validate(); currentFrame.getContentPane().repaint(); } } /** * This is the listener class used for the exitButton. It quits the program * and closed the window. * * @author Venkata Peesapati * */ class ExitButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } } /** * This MouseListener class is used to change the color of the text when * hovering over a button. It is used for all the buttons in the main menu. * * @author Venkata Peesapati * */ class HoverButtonListener implements MouseListener { @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { ((JButton) e.getSource()).setForeground(Color.red); } @Override public void mouseExited(MouseEvent e) { ((JButton) e.getSource()).setForeground(Color.black); } } }
package utilities.video; import javafx.application.Platform; import javafx.beans.InvalidationListener; import javafx.beans.Observable; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.Priority; import javafx.scene.media.MediaPlayer; import javafx.scene.media.MediaPlayer.Status; import javafx.scene.media.MediaView; import javafx.util.Duration; class VideoPlayer extends BorderPane { private static final String PLAY_BUTTON_TEXT = "Play"; private static final String PAUSE_BUTTON_TEXT = "Pause"; private static final String SPACE = " "; private static final String TIME_LABEL_TEXT = "Play Time: 308"; private static final String VOLUME_LABEL_TEXT = "Volume: "; private MediaPlayer myMediaPlayer; private MediaView myMediaView; private Slider myTimeSlider; private Label myTimeLabel; private Label myVolumeLabel; private Slider myVolumeSlider; private Duration myDuration; private final boolean replayVideo = true; private boolean stopVideo = false; private boolean cycleComplete = false; private HBox myMediaBar; public VideoPlayer (final MediaPlayer mediaPlayer) { this.myMediaPlayer = mediaPlayer; myMediaView = new MediaView(mediaPlayer); Pane moviePane = new Pane() { }; moviePane.getChildren().add(myMediaView); setCenter(moviePane); myMediaBar = new HBox(); myMediaBar.setAlignment(Pos.CENTER); BorderPane.setAlignment(myMediaBar, Pos.CENTER); setBottom(myMediaBar); final Button playButton = new Button(PLAY_BUTTON_TEXT); definePlayButtonBehavior(mediaPlayer, playButton); myMediaBar.getChildren().add(new Label(SPACE)); myMediaBar.getChildren().add(playButton); myMediaBar.getChildren().add(new Label(SPACE)); myTimeSlider = new Slider(); HBox.setHgrow(myTimeSlider, Priority.ALWAYS); myTimeSlider.setMinWidth(50); myTimeSlider.setMaxWidth(Double.MAX_VALUE); myMediaBar.getChildren().add(myTimeSlider); myTimeLabel = new Label(TIME_LABEL_TEXT); myTimeLabel.setPrefWidth(150); myTimeLabel.setMinWidth(50); // timeSlider.valueProperty().addListener(new InvalidationListener() { // public void invalidated(Observable ov) { // if (timeSlider.isValueChanging()) { // mediaPlayer.seek(myDuration.multiply(timeSlider.getValue() / 100.0)); myMediaBar.getChildren().add(myTimeLabel); myVolumeLabel = new Label(VOLUME_LABEL_TEXT); myMediaBar.getChildren().add(myVolumeLabel); myVolumeSlider = new Slider(); myVolumeSlider.valueProperty().addListener(new InvalidationListener() { public void invalidated (Observable observable) { if (myVolumeSlider.isValueChanging()) { mediaPlayer.setVolume(myVolumeSlider.getValue() / 100.0); } } }); myMediaBar.getChildren().add(myVolumeSlider); mediaPlayer.setCycleCount(replayVideo ? MediaPlayer.INDEFINITE : 1); defineMediaPlayerBehavior(mediaPlayer, playButton); } private void defineMediaPlayerBehavior (final MediaPlayer player, final Button button) { player.setOnPlaying(new Runnable() { public void run () { if (stopVideo) { player.pause(); stopVideo = false; } else { button.setText(PAUSE_BUTTON_TEXT); } } }); player.setOnPaused(new Runnable() { public void run () { button.setText(PLAY_BUTTON_TEXT); } }); player.setOnReady(new Runnable() { public void run () { myDuration = player.getMedia().getDuration(); updateValues(); } }); player.setOnEndOfMedia(new Runnable() { public void run () { if (!replayVideo) { button.setText(PLAY_BUTTON_TEXT); stopVideo = true; cycleComplete = true; } } }); } private void definePlayButtonBehavior (final MediaPlayer player, final Button button) { button.setOnAction(new EventHandler<ActionEvent>() { public void handle (ActionEvent e) { Status status = player.getStatus(); if (status == Status.HALTED || status == Status.UNKNOWN) { return; } if (status == Status.PAUSED || status == Status.READY || status == Status.STOPPED) { if (cycleComplete) { player.seek(player.getStartTime()); cycleComplete = false; } player.play(); } else { player.pause(); } } }); player.currentTimeProperty().addListener(new InvalidationListener() { public void invalidated (Observable observable) { updateValues(); } }); } private void updateValues () { Platform.runLater(new Runnable() { public void run () { if (!myVolumeSlider.isValueChanging()) { myVolumeSlider.setValue((int) Math.round(myMediaPlayer.getVolume() * 100)); } } }); } }
package v2.simulators; import v2.io.reporters.Reporter; import java.io.IOException; /** * Data collector is the class responsible for collecting data during a simulation. Simulators delegate on data * collectors the data collection logic. To collect data from a simulation a data collector must be registered with a * simulation engine. After finishing the data collection the collector should be unregistered. The data * collector can be visited by a reporter to report its data. */ public interface DataCollector { /** * Gives access to the data set storing the collected data. The dataset implementation returned depends on the * collector implementation * * @return a dataset instance with the collected data. */ Dataset getDataset(); /** * Clears all data that has been collected */ void clear(); /** * Reports the current collected data using the given reporter implementation. * * @param reporter reporter implementation to be used. */ void report(Reporter reporter) throws IOException; }
//$HeadURL$ package org.deegree.protocol.wmts.ops; import static org.deegree.commons.ows.exception.OWSException.INVALID_PARAMETER_VALUE; import static org.deegree.commons.ows.exception.OWSException.MISSING_PARAMETER_VALUE; import java.util.Map; import org.deegree.commons.ows.exception.OWSException; public class GetFeatureInfo { private final String layer; private final String style; private String infoFormat; private final String tileMatrixSet; private final String tileMatrix; private long tileRow; private long tileCol; private int i, j; /** * The parameter values correspond to what's described in the spec. * * @param layer * @param style * @param infoFormat * @param tileMatrixSet * @param tileMatrix * @param tileRow * @param tileCol * @param i * @param j */ public GetFeatureInfo( String layer, String style, String infoFormat, String tileMatrixSet, String tileMatrix, long tileRow, long tileCol, int i, int j ) { this.layer = layer; this.style = style; this.infoFormat = infoFormat; this.tileMatrixSet = tileMatrixSet; this.tileMatrix = tileMatrix; this.tileRow = tileRow; this.tileCol = tileCol; this.i = i; this.j = j; } public GetFeatureInfo( Map<String, String> map ) throws OWSException { this.layer = map.get( "LAYER" ); this.style = map.get( "STYLE" ); this.infoFormat = map.get( "INFOFORMAT" ); if ( infoFormat == null ) { // for friends of the WMS... infoFormat = map.get( "INFO_FORMAT" ); } if ( infoFormat == null ) { throw new OWSException( "The INFOFORMAT parameter is missing.", MISSING_PARAMETER_VALUE, "INFOFORMAT" ); } this.tileMatrixSet = map.get( "TILEMATRIXSET" ); this.tileMatrix = map.get( "TILEMATRIX" ); parseTileRowCol( map ); parseIj( map ); } private void parseIj( Map<String, String> map ) throws OWSException { String i = map.get( "I" ); if ( i == null ) { throw new OWSException( "The I parameter is missing.", MISSING_PARAMETER_VALUE, "I" ); } try { this.i = Integer.parseInt( i ); } catch ( NumberFormatException e ) { throw new OWSException( "The I parameter value of '" + i + "' is not valid.", INVALID_PARAMETER_VALUE, "I" ); } String j = map.get( "J" ); if ( j == null ) { throw new OWSException( "The J parameter is missing.", MISSING_PARAMETER_VALUE, "J" ); } try { this.j = Integer.parseInt( j ); } catch ( NumberFormatException e ) { throw new OWSException( "The J parameter value of '" + j + "' is not valid.", INVALID_PARAMETER_VALUE, "J" ); } } private void parseTileRowCol( Map<String, String> map ) throws OWSException { String row = map.get( "TILEROW" ); if ( row == null ) { throw new OWSException( "The TILEROW parameter is missing.", MISSING_PARAMETER_VALUE, "TILEROW" ); } try { this.tileRow = Integer.parseInt( row ); } catch ( NumberFormatException e ) { throw new OWSException( "The TILEROW parameter value of '" + row + "' is not a valid index.", INVALID_PARAMETER_VALUE, "TILEROW" ); } String col = map.get( "TILECOL" ); if ( col == null ) { throw new OWSException( "The TILECOL parameter is missing.", MISSING_PARAMETER_VALUE, "TILECOL" ); } try { this.tileCol = Integer.parseInt( col ); } catch ( NumberFormatException e ) { throw new OWSException( "The TILECOL parameter value of '" + col + "' is not a valid index.", INVALID_PARAMETER_VALUE, "TILECOL" ); } } /** * @return the layer */ public String getLayer() { return layer; } /** * @return the style */ public String getStyle() { return style; } /** * @return the infoFormat */ public String getInfoFormat() { return infoFormat; } /** * @return the tileMatrixSet */ public String getTileMatrixSet() { return tileMatrixSet; } /** * @return the tileMatrix */ public String getTileMatrix() { return tileMatrix; } /** * @return the tileRow */ public long getTileRow() { return tileRow; } /** * @return the tileCol */ public long getTileCol() { return tileCol; } /** * @return the i */ public int getI() { return i; } /** * @return the j */ public int getJ() { return j; } }
package org.estatio.module.capex.dom.invoice.approval; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import com.google.common.collect.ImmutableMap; import org.estatio.module.asset.dom.Property; import org.estatio.module.capex.dom.invoice.IncomingInvoice; import org.estatio.module.capex.dom.invoice.IncomingInvoiceItem; import org.estatio.module.invoice.dom.InvoiceItem; /** * This class contains a bunch of static methods with "hard coded" user data for incoming invoice approval workflow configuration * At least it then lives in a single place .... */ public class IncomingInvoiceApprovalConfigurationUtil { private static List<String> propertyRefsWithMonitoring = Arrays.asList("AZ", "MAC"); // MAC is there for testing public static BigDecimal singleSignatureThresholdNormal = new BigDecimal("100000.00"); public static BigDecimal singleSignatureThresholdHigh = new BigDecimal("150000.00"); private static List<String> buyerRefsWithHighSingleSignatureThreshold = Arrays.asList("IT07"); private static List<String> buyerRefsHavingAllTypesApprovedByAssetManager = Arrays.asList("IT07"); private static List<String> buyerRefsHavingAllTypesCompletedByPropertyInvoiceManager = Arrays.asList("IT04"); private static List<String> buyerRefsHavingRecoverableCompletedByPropertyInvoiceManager = Arrays.asList("IT01"); public static String CHARGE_REF_MARKETING_NR = "MARKETING EXPENSES (NR)"; // ECP-1346 public static final Map<String, String> PROPERTY_REF_EXTERNAL_PROJECT_REF_MAP = ImmutableMap.of( "COL", "ITPR285", "GIG", "ITPR286", "FAB", "ITPR287", "RON", "TESTEXT" // for intergration tests ); // ECP-1208 public static boolean hasMonitoring(final IncomingInvoice incomingInvoice) { if (incomingInvoice.getProperty()!=null && propertyRefsWithMonitoring.contains(incomingInvoice.getProperty().getReference())) return true; return false; } //ECP-1173 public static boolean hasHighSingleSignatureThreshold(final IncomingInvoice incomingInvoice){ return incomingInvoice.getBuyer()!=null && buyerRefsWithHighSingleSignatureThreshold.contains(incomingInvoice.getBuyer().getReference()); } // ECP-1181 public static boolean hasAllTypesApprovedByAssetManager(final IncomingInvoice incomingInvoice){ return incomingInvoice.getBuyer()!=null && buyerRefsHavingAllTypesApprovedByAssetManager .contains(incomingInvoice.getBuyer().getReference()); } public static boolean hasAllTypesCompletedByPropertyInvoiceManager(final IncomingInvoice incomingInvoice){ return incomingInvoice.getBuyer()!=null && buyerRefsHavingAllTypesCompletedByPropertyInvoiceManager .contains(incomingInvoice.getBuyer().getReference()); } public static boolean hasRecoverableCompletedByPropertyInvoiceManager(final IncomingInvoice incomingInvoice){ return incomingInvoice.getBuyer()!=null && buyerRefsHavingRecoverableCompletedByPropertyInvoiceManager .contains(incomingInvoice.getBuyer().getReference()); } // ECP-1346 public static boolean isInvoiceForExternalCenterManager(final IncomingInvoice incomingInvoice){ final Property propertyOnInvoice = incomingInvoice.getProperty(); if (propertyOnInvoice ==null) return false; final List<String> propertyRefsFound = new ArrayList<>(); PROPERTY_REF_EXTERNAL_PROJECT_REF_MAP.forEach((k,v)->{ if (k.equals(propertyOnInvoice.getReference()) && atLeastOneItemHasProjectWithReference(incomingInvoice, v)) propertyRefsFound.add(k); }); return !propertyRefsFound.isEmpty(); } private static boolean atLeastOneItemHasProjectWithReference(final IncomingInvoice invoice, final String projectRefExt) { for (InvoiceItem ii : invoice.getItems()){ IncomingInvoiceItem cii = (IncomingInvoiceItem) ii; if (cii.getProject()!=null && cii.getProject().getReference().equals(projectRefExt)) { return true; } } return false; } public static boolean hasItemWithChargeMarketingNR(final IncomingInvoice incomingInvoice) { for (InvoiceItem ii : incomingInvoice.getItems()){ if (ii.getCharge()!=null && ii.getCharge().getReference().equals(CHARGE_REF_MARKETING_NR)) return true; } return false; } }
package io.quarkus.vertx.http.deployment.devmode.console; import java.io.File; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.eclipse.microprofile.config.ConfigProvider; import org.jboss.logging.Logger; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.handler.codec.http.HttpHeaderNames; import io.quarkus.bootstrap.classloading.QuarkusClassLoader; import io.quarkus.bootstrap.model.AppArtifact; import io.quarkus.builder.item.SimpleBuildItem; import io.quarkus.deployment.IsDevelopment; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.annotations.Consume; import io.quarkus.deployment.annotations.ExecutionTime; import io.quarkus.deployment.annotations.Record; import io.quarkus.deployment.builditem.LaunchModeBuildItem; import io.quarkus.deployment.builditem.LogHandlerBuildItem; import io.quarkus.deployment.builditem.ServiceStartBuildItem; import io.quarkus.deployment.builditem.ShutdownContextBuildItem; import io.quarkus.deployment.ide.EffectiveIdeBuildItem; import io.quarkus.deployment.ide.Ide; import io.quarkus.deployment.logging.LoggingSetupBuildItem; import io.quarkus.deployment.pkg.builditem.BuildSystemTargetBuildItem; import io.quarkus.deployment.pkg.builditem.CurateOutcomeBuildItem; import io.quarkus.deployment.recording.BytecodeRecorderImpl; import io.quarkus.deployment.util.ArtifactInfoUtil; import io.quarkus.deployment.util.WebJarUtil; import io.quarkus.dev.console.DevConsoleManager; import io.quarkus.dev.spi.DevModeType; import io.quarkus.devconsole.spi.DevConsoleRouteBuildItem; import io.quarkus.devconsole.spi.DevConsoleRuntimeTemplateInfoBuildItem; import io.quarkus.devconsole.spi.DevConsoleTemplateInfoBuildItem; import io.quarkus.netty.runtime.virtual.VirtualChannel; import io.quarkus.netty.runtime.virtual.VirtualServerChannel; import io.quarkus.qute.Engine; import io.quarkus.qute.EngineBuilder; import io.quarkus.qute.EvalContext; import io.quarkus.qute.Expression; import io.quarkus.qute.HtmlEscaper; import io.quarkus.qute.NamespaceResolver; import io.quarkus.qute.RawString; import io.quarkus.qute.ReflectionValueResolver; import io.quarkus.qute.ResultMapper; import io.quarkus.qute.Results; import io.quarkus.qute.Results.Result; import io.quarkus.qute.TemplateException; import io.quarkus.qute.TemplateLocator; import io.quarkus.qute.TemplateNode.Origin; import io.quarkus.qute.UserTagSectionHelper; import io.quarkus.qute.ValueResolver; import io.quarkus.qute.ValueResolvers; import io.quarkus.qute.Variant; import io.quarkus.runtime.RuntimeValue; import io.quarkus.runtime.TemplateHtmlBuilder; import io.quarkus.vertx.http.deployment.NonApplicationRootPathBuildItem; import io.quarkus.vertx.http.deployment.RouteBuildItem; import io.quarkus.vertx.http.runtime.devmode.DevConsoleFilter; import io.quarkus.vertx.http.runtime.devmode.DevConsoleRecorder; import io.quarkus.vertx.http.runtime.devmode.RedirectHandler; import io.quarkus.vertx.http.runtime.devmode.RuntimeDevConsoleRoute; import io.quarkus.vertx.http.runtime.logstream.HistoryHandler; import io.quarkus.vertx.http.runtime.logstream.LogStreamRecorder; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpServerOptions; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.http.impl.Http1xServerConnection; import io.vertx.core.impl.ContextInternal; import io.vertx.core.impl.VertxInternal; import io.vertx.core.json.JsonObject; import io.vertx.core.net.impl.VertxHandler; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; public class DevConsoleProcessor { private static final Logger log = Logger.getLogger(DevConsoleProcessor.class); private static final String STATIC_RESOURCES_PATH = "dev-static/"; private static final Object EMPTY = new Object(); // FIXME: config, take from Qute? private static final String[] suffixes = new String[] { "html", "txt" }; protected static volatile ServerBootstrap virtualBootstrap; protected static volatile Vertx devConsoleVertx; protected static volatile Channel channel; static Router router; static Router mainRouter; public static void initializeVirtual() { if (virtualBootstrap != null) { return; } devConsoleVertx = Vertx.vertx(); VertxInternal vertx = (VertxInternal) devConsoleVertx; QuarkusClassLoader ccl = (QuarkusClassLoader) DevConsoleProcessor.class.getClassLoader(); ccl.addCloseTask(new Runnable() { @Override public void run() { virtualBootstrap = null; if (devConsoleVertx != null) { devConsoleVertx.close(); devConsoleVertx = null; } if (channel != null) { try { channel.close().sync(); } catch (InterruptedException e) { throw new RuntimeException("failed to close virtual http"); } } } }); virtualBootstrap = new ServerBootstrap(); virtualBootstrap.group(vertx.getEventLoopGroup()) .channel(VirtualServerChannel.class) .handler(new ChannelInitializer<VirtualServerChannel>() { @Override public void initChannel(VirtualServerChannel ch) throws Exception { //ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO)); } }) .childHandler(new ChannelInitializer<VirtualChannel>() { @Override public void initChannel(VirtualChannel ch) throws Exception { ContextInternal context = (ContextInternal) vertx .createEventLoopContext(null, null, new JsonObject(), Thread.currentThread().getContextClassLoader()); VertxHandler<Http1xServerConnection> handler = VertxHandler.create(context, chctx -> { Http1xServerConnection conn = new Http1xServerConnection( context.owner(), null, new HttpServerOptions(), chctx, context, "localhost", null); conn.handler(new Handler<HttpServerRequest>() { @Override public void handle(HttpServerRequest event) { mainRouter.handle(event); } }); return conn; }); ch.pipeline().addLast("handler", handler); } }); // Start the server. try { ChannelFuture future = virtualBootstrap.bind(DevConsoleHttpHandler.QUARKUS_DEV_CONSOLE); future.sync(); channel = future.channel(); } catch (InterruptedException e) { throw new RuntimeException("failed to bind virtual http"); } } protected static void newRouter(Engine engine, NonApplicationRootPathBuildItem nonApplicationRootPathBuildItem) { // "/" or "/myroot/" String httpRootPath = nonApplicationRootPathBuildItem.getNormalizedHttpRootPath(); // "/" or "/myroot/" or "/q/" or "/myroot/q/" String frameworkRootPath = nonApplicationRootPathBuildItem.getNonApplicationRootPath(); Handler<RoutingContext> errorHandler = new Handler<RoutingContext>() { @Override public void handle(RoutingContext event) { String message = "Dev console request failed"; log.error(message, event.failure()); event.response().headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=utf-8"); event.response().end( new TemplateHtmlBuilder("Internal Server Error", message, message).stack(event.failure()).toString()); } }; router = Router.router(devConsoleVertx); router.errorHandler(500, errorHandler); router.route() .order(Integer.MIN_VALUE) .handler(new FlashScopeHandler()); router.route().method(HttpMethod.GET) .order(Integer.MIN_VALUE + 1) .handler(new DevConsole(engine, httpRootPath, frameworkRootPath)); mainRouter = Router.router(devConsoleVertx); mainRouter.errorHandler(500, errorHandler); /** * Return the most general packages used in the application * * TODO: this likely covers almost all typical use cases, but probably needs some tweaks for extreme corner cases */ private List<String> sourcePackagesForLang(Path srcMainPath, String lang) { Path langPath = srcMainPath.resolve(lang); if (!Files.exists(langPath)) { return Collections.emptyList(); } File[] rootFiles = langPath.toFile().listFiles(); List<Path> rootPackages = new ArrayList<>(1); if (rootFiles != null) { for (File rootFile : rootFiles) { if (rootFile.isDirectory()) { rootPackages.add(rootFile.toPath()); } } } if (rootPackages.isEmpty()) { return Collections.emptyList(); } List<String> result = new ArrayList<>(rootPackages.size()); for (Path rootPackage : rootPackages) { List<String> paths = new ArrayList<>(); SimpleFileVisitor<Path> simpleFileVisitor = new DetectPackageFileVisitor(paths); try { Files.walkFileTree(rootPackage, simpleFileVisitor); if (paths.isEmpty()) { continue; } String commonPath = commonPath(paths); String rootPackageStr = commonPath.replace(langPath.toAbsolutePath().toString(), "") .replace(File.separator, "."); if (rootPackageStr.startsWith(".")) { rootPackageStr = rootPackageStr.substring(1); } if (rootPackageStr.endsWith(".")) { rootPackageStr = rootPackageStr.substring(0, rootPackageStr.length() - 1); } result.add(rootPackageStr); } catch (IOException e) { log.debug("Unable to determine the sources directories", e); // just ignore it as it's not critical for the DevUI functionality } } return result; } private String commonPath(List<String> paths) { String commonPath = ""; List<String[]> dirs = new ArrayList<>(paths.size()); for (int i = 0; i < paths.size(); i++) { dirs.add(i, paths.get(i).split(Pattern.quote(File.separator))); } for (int j = 0; j < dirs.get(0).length; j++) { String thisDir = dirs.get(0)[j]; // grab the next directory name in the first path boolean allMatched = true; for (int i = 1; i < dirs.size() && allMatched; i++) { // look at the other paths if (dirs.get(i).length < j) { //there is no directory allMatched = false; break; } allMatched = dirs.get(i)[j].equals(thisDir); //check if it matched } if (allMatched) { commonPath += thisDir + File.separator; } else { break; } } return commonPath; } } }
package com.opengamma.strata.collect.io; import static com.opengamma.strata.collect.TestHelper.coverImmutableBean; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.net.MalformedURLException; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import org.joda.beans.ser.JodaBeanSer; import org.junit.jupiter.api.Test; import com.google.common.hash.HashCode; import com.google.common.hash.Hashing; import com.google.common.io.BaseEncoding; import com.google.common.io.ByteProcessor; import com.google.common.io.ByteSource; import com.google.common.io.Files; import com.google.common.io.MoreFiles; import com.google.common.io.Resources; import com.opengamma.strata.collect.function.CheckedSupplier; /** * Test {@link ArrayByteSource}. */ public class ArrayByteSourceTest { @Test public void test_EMPTY() { ArrayByteSource test = ArrayByteSource.EMPTY; assertThat(test.isEmpty()).isEqualTo(true); assertThat(test.size()).isEqualTo(0); assertThat(test.getFileName()).isEmpty(); } @Test public void test_copyOf() { byte[] bytes = {1, 2, 3}; ArrayByteSource test = ArrayByteSource.copyOf(bytes); assertThat(test.size()).isEqualTo(3); assertThat(test.getFileName()).isEmpty(); assertThat(test.read()[0]).isEqualTo((byte) 1); assertThat(test.read()[1]).isEqualTo((byte) 2); assertThat(test.read()[2]).isEqualTo((byte) 3); bytes[0] = 4; assertThat(test.read()[0]).isEqualTo((byte) 1); } @Test public void test_copyOf_from() { byte[] bytes = {1, 2, 3}; ArrayByteSource test = ArrayByteSource.copyOf(bytes, 1); assertThat(test.size()).isEqualTo(2); assertThat(test.read()[0]).isEqualTo((byte) 2); assertThat(test.read()[1]).isEqualTo((byte) 3); } @Test public void test_copyOf_fromTo() { byte[] bytes = {1, 2, 3}; ArrayByteSource test = ArrayByteSource.copyOf(bytes, 1, 2); assertThat(test.size()).isEqualTo(1); assertThat(test.read()[0]).isEqualTo((byte) 2); } @Test public void test_copyOf_fromTo_empty() { byte[] bytes = {1, 2, 3}; ArrayByteSource test = ArrayByteSource.copyOf(bytes, 1, 1); assertThat(test.size()).isEqualTo(0); } @Test public void test_copyOf_fromTo_bad() { byte[] bytes = {1, 2, 3}; assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> ArrayByteSource.copyOf(bytes, -1, 2)); assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> ArrayByteSource.copyOf(bytes, 0, 4)); assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> ArrayByteSource.copyOf(bytes, 4, 5)); } @Test public void test_ofUnsafe() { byte[] bytes = {1, 2, 3}; ArrayByteSource test = ArrayByteSource.ofUnsafe(bytes); assertThat(test.size()).isEqualTo(3); assertThat(test.getFileName()).isEmpty(); assertThat(test.read()[0]).isEqualTo((byte) 1); assertThat(test.read()[1]).isEqualTo((byte) 2); assertThat(test.read()[2]).isEqualTo((byte) 3); bytes[0] = 4; // abusing the unsafe factory assertThat(test.read()[0]).isEqualTo((byte) 4); } @Test public void test_ofUtf8() { ArrayByteSource test = ArrayByteSource.ofUtf8("ABC"); assertThat(test.size()).isEqualTo(3); assertThat(test.getFileName()).isEmpty(); assertThat(test.read()[0]).isEqualTo((byte) 'A'); assertThat(test.read()[1]).isEqualTo((byte) 'B'); assertThat(test.read()[2]).isEqualTo((byte) 'C'); } @Test public void test_from_ByteSource() { ByteSource source = ByteSource.wrap(new byte[] {1, 2, 3}); ArrayByteSource test = ArrayByteSource.from(source); assertThat(test.size()).isEqualTo(3); assertThat(test.getFileName()).isEmpty(); assertThat(test.read()[0]).isEqualTo((byte) 1); assertThat(test.read()[1]).isEqualTo((byte) 2); assertThat(test.read()[2]).isEqualTo((byte) 3); } @Test public void test_from_ByteSource_alreadyArrayByteSource() { ArrayByteSource base = ArrayByteSource.copyOf(new byte[] {1, 2, 3}); ArrayByteSource test = ArrayByteSource.from(base); assertThat(test).isSameAs(base); assertThat(test.getFileName()).isEmpty(); } @Test public void test_from_FileByteSource() { ByteSource source = FileByteSource.of(new File("pom.xml")); ArrayByteSource test = ArrayByteSource.from(source); assertThat(test.getFileName()).hasValue("pom.xml"); } @Test public void test_from_UriByteSource() { ByteSource source = UriByteSource.of(new File("pom.xml").toURI()); ArrayByteSource test = ArrayByteSource.from(source); assertThat(test.getFileName()).hasValue("pom.xml"); } @Test public void test_from_GuavaFileByteSource() { ByteSource source = Files.asByteSource(new File("pom.xml")); ArrayByteSource test = ArrayByteSource.from(source); assertThat(test.getFileName()).hasValue("pom.xml"); } @Test public void test_from_GuavaPathByteSource() { ByteSource source = MoreFiles.asByteSource(Paths.get("pom.xml")); ArrayByteSource test = ArrayByteSource.from(source); assertThat(test.getFileName()).hasValue("pom.xml"); } @Test public void test_from_GuavaUrlByteSource() throws MalformedURLException { ByteSource source = Resources.asByteSource(new File("pom.xml").toURI().toURL()); ArrayByteSource test = ArrayByteSource.from(source); assertThat(test.getFileName()).hasValue("pom.xml"); } @Test public void test_from_GuavaSimpleByteSource() { byte[] bytes = new byte[] {1, 2, 3}; ByteSource source = ByteSource.wrap(bytes); ArrayByteSource test = ArrayByteSource.from(source); assertThat(test.readUnsafe()).isSameAs(bytes); } @Test public void test_from_GuavaSimpleByteSourceSliced() { byte[] bytes = new byte[] {1, 2, 3}; ByteSource source = ByteSource.wrap(bytes).slice(1, 1); ArrayByteSource test = ArrayByteSource.from(source); assertThat(test.readUnsafe()).containsExactly(2); } @Test public void test_from_Supplier() { ByteSource source = ByteSource.wrap(new byte[] {1, 2, 3}); ArrayByteSource test = ArrayByteSource.from(() -> source.openStream()); assertThat(test.size()).isEqualTo(3); assertThat(test.getFileName()).isEmpty(); assertThat(test.read()[0]).isEqualTo((byte) 1); assertThat(test.read()[1]).isEqualTo((byte) 2); assertThat(test.read()[2]).isEqualTo((byte) 3); } @Test public void test_from_SupplierExceptionOnCreate() { CheckedSupplier<InputStream> supplier = () -> { throw new IOException(); }; assertThatExceptionOfType(UncheckedIOException.class).isThrownBy(() -> ArrayByteSource.from(supplier)); } @Test public void test_from_SupplierExceptionOnRead() { CheckedSupplier<InputStream> supplier = () -> { return new InputStream() { @Override public int read() throws IOException { throw new IOException(); } }; }; assertThatExceptionOfType(UncheckedIOException.class).isThrownBy(() -> ArrayByteSource.from(supplier)); } @Test public void test_from_InputStream_sizeCorrect() throws IOException { ByteSource source = ByteSource.wrap(new byte[] {1, 2, 3, 4, 5}); ArrayByteSource test = ArrayByteSource.from(source.openStream(), 5); assertThat(test.size()).isEqualTo(5); assertThat(test.getFileName()).isEmpty(); assertThat(test.read()).containsExactly(1, 2, 3, 4, 5); } @Test public void test_from_InputStream_sizeTooSmall() throws IOException { ByteSource source = ByteSource.wrap(new byte[] {1, 2, 3, 4, 5}); ArrayByteSource test = ArrayByteSource.from(source.openStream(), 2); assertThat(test.size()).isEqualTo(5); assertThat(test.getFileName()).isEmpty(); assertThat(test.read()).containsExactly(1, 2, 3, 4, 5); } @Test public void test_from_InputStream_sizeTooBig() throws IOException { ByteSource source = ByteSource.wrap(new byte[] {1, 2, 3, 4, 5}); ArrayByteSource test = ArrayByteSource.from(source.openStream(), 6); assertThat(test.size()).isEqualTo(5); assertThat(test.getFileName()).isEmpty(); assertThat(test.read()).containsExactly(1, 2, 3, 4, 5); } @Test public void test_withFileName() { ArrayByteSource test = ArrayByteSource.copyOf(new byte[] {1, 2, 3}); assertThat(test.getFileName()).isEmpty(); assertThat(test.withFileName("name.txt").getFileName()).hasValue("name.txt"); assertThat(test.withFileName("foo/name.txt").getFileName()).hasValue("name.txt"); assertThat(test.withFileName("").getFileName()).isEmpty(); assertThatIllegalArgumentException().isThrownBy(() -> test.withFileName(null).getFileName()); } @Test public void test_read() { ArrayByteSource test = ArrayByteSource.copyOf(new byte[] {1, 2, 3}); assertThat(test.size()).isEqualTo(3); byte[] safeArray = test.read(); safeArray[0] = 4; assertThat(test.read()[0]).isEqualTo((byte) 1); assertThat(test.read()[1]).isEqualTo((byte) 2); assertThat(test.read()[2]).isEqualTo((byte) 3); } @Test public void test_readUnsafe() { ArrayByteSource test = ArrayByteSource.copyOf(new byte[] {1, 2, 3}); assertThat(test.size()).isEqualTo(3); byte[] unsafeArray = test.readUnsafe(); unsafeArray[0] = 4; // abusing the unsafe array assertThat(test.read()[0]).isEqualTo((byte) 4); assertThat(test.read()[1]).isEqualTo((byte) 2); assertThat(test.read()[2]).isEqualTo((byte) 3); } @Test public void test_read_processor() throws IOException { ArrayByteSource test = ArrayByteSource.copyOf(new byte[] {1, 2, 3}); ByteProcessor<Integer> processor = new ByteProcessor<Integer>() { @Override public boolean processBytes(byte[] buf, int off, int len) throws IOException { assertThat(off).isEqualTo(0); assertThat(len).isEqualTo(3); assertThat(buf[0]).isEqualTo((byte) 1); assertThat(buf[1]).isEqualTo((byte) 2); assertThat(buf[2]).isEqualTo((byte) 3); return false; } @Override public Integer getResult() { return 123; } }; assertThat(test.read(processor)).isEqualTo(123); } @Test public void test_slice() throws IOException { ArrayByteSource test = ArrayByteSource.copyOf(new byte[] {65, 66, 67, 68, 69}); assertThat(test.size()).isEqualTo(5); assertThat(test.slice(0, 3).readUtf8()).isEqualTo("ABC"); assertThat(test.slice(0, 5).readUtf8()).isEqualTo("ABCDE"); assertThat(test.slice(0, Long.MAX_VALUE).readUtf8()).isEqualTo("ABCDE"); assertThat(test.slice(1, 1).readUtf8()).isEqualTo("B"); assertThat(test.slice(1, 2).readUtf8()).isEqualTo("BC"); assertThat(test.slice(1, 3).readUtf8()).isEqualTo("BCD"); assertThat(test.slice(1, 4).readUtf8()).isEqualTo("BCDE"); assertThat(test.slice(2, 1).readUtf8()).isEqualTo("C"); assertThat(test.slice(2, 2).readUtf8()).isEqualTo("CD"); assertThat(test.slice(2, 3).readUtf8()).isEqualTo("CDE"); assertThat(test.slice(2, Long.MAX_VALUE).readUtf8()).isEqualTo("CDE"); assertThat(test.slice(5, 6).readUtf8()).isEqualTo(""); assertThat(test.slice(5, Long.MAX_VALUE).readUtf8()).isEqualTo(""); assertThat(test.slice(Long.MAX_VALUE - 10, Long.MAX_VALUE).readUtf8()).isEmpty(); } @Test public void test_methods() throws IOException { ArrayByteSource test = ArrayByteSource.copyOf(new byte[] {65, 66, 67}); assertThat(test.size()).isEqualTo(3); assertThat(test.isEmpty()).isEqualTo(false); assertThat(test.sizeIfKnown().isPresent()).isEqualTo(true); assertThat(test.sizeIfKnown().get()).isEqualTo((Long) 3L); assertThat(test.readUtf8()).isEqualTo("ABC"); assertThat(test.readUtf8UsingBom()).isEqualTo("ABC"); assertThat(test.asCharSourceUtf8UsingBom().read()).isEqualTo("ABC"); assertThat(test.contentEquals(test)).isTrue(); assertThat(test.toString()).isEqualTo("ArrayByteSource[3 bytes]"); assertThat(test.withFileName("name.txt").toString()).isEqualTo("ArrayByteSource[3 bytes, name.txt]"); } @Test public void test_toHash() { byte[] bytes = new byte[] {65, 66, 67, 99}; HashCode hash = Hashing.crc32().hashBytes(bytes); ArrayByteSource test = ArrayByteSource.copyOf(bytes); assertThat(test.toHash(Hashing.crc32())).isEqualTo(ArrayByteSource.ofUnsafe(hash.asBytes())); assertThat(test.toHashString(Hashing.crc32())).isEqualTo(hash.toString()); } @Test @SuppressWarnings("deprecation") public void test_md5() { byte[] bytes = new byte[] {65, 66, 67, 99}; @SuppressWarnings("deprecation") byte[] hash = Hashing.md5().hashBytes(bytes).asBytes(); ArrayByteSource test = ArrayByteSource.copyOf(bytes); assertThat(test.toMd5()).isEqualTo(ArrayByteSource.ofUnsafe(hash)); } @Test @SuppressWarnings("deprecation") public void test_sha512() { byte[] bytes = new byte[] {65, 66, 67, 99}; byte[] hash = Hashing.sha512().hashBytes(bytes).asBytes(); ArrayByteSource test = ArrayByteSource.copyOf(bytes); assertThat(test.toSha512()).isEqualTo(ArrayByteSource.ofUnsafe(hash)); } @Test public void test_base64() { byte[] bytes = new byte[] {65, 66, 67, 99}; @SuppressWarnings("deprecation") byte[] base64 = BaseEncoding.base64().encode(bytes).getBytes(StandardCharsets.UTF_8); ArrayByteSource test = ArrayByteSource.copyOf(bytes); assertThat(test.toBase64()).isEqualTo(ArrayByteSource.ofUnsafe(base64)); } @Test public void test_base64String() { byte[] bytes = new byte[] {65, 66, 67, 99}; @SuppressWarnings("deprecation") String base64 = BaseEncoding.base64().encode(bytes); ArrayByteSource test = ArrayByteSource.copyOf(bytes); assertThat(test.toBase64String()).isEqualTo(base64); ArrayByteSource roundtrip = ArrayByteSource.fromBase64(base64); assertThat(roundtrip).isEqualTo(test); assertThat(test.toBase64String()).isEqualTo(test.toBase64().readUtf8()); } @Test public void test_hexString() { byte[] bytes = new byte[] {65, 66, 67, 99}; String hex = "41424363"; ArrayByteSource test = ArrayByteSource.copyOf(bytes); assertThat(test.toHexString()).isEqualTo(hex); ArrayByteSource roundtrip = ArrayByteSource.fromHex(hex); assertThat(roundtrip).isEqualTo(test); } @Test public void test_load() { byte[] bytes = new byte[] {65, 66, 67, 99}; ArrayByteSource test = ArrayByteSource.copyOf(bytes); ArrayByteSource loaded = test.load(); assertThat(loaded).isSameAs(test); } @Test public void coverage() { byte[] bytes = new byte[] {65, 66, 67, 99}; ArrayByteSource test = ArrayByteSource.copyOf(bytes); coverImmutableBean(test); test.metaBean().metaProperty("array").metaBean(); test.metaBean().metaProperty("array").propertyGenericType(); test.metaBean().metaProperty("array").annotations(); } @Test public void testSerialize() { byte[] bytes = new byte[] {65, 66, 67, 99}; ArrayByteSource test = ArrayByteSource.copyOf(bytes); String json = JodaBeanSer.PRETTY.jsonWriter().write(test); ArrayByteSource roundTrip = JodaBeanSer.PRETTY.jsonReader().read(json, ArrayByteSource.class); assertThat(roundTrip).isEqualTo(test); assertThat(roundTrip.getFileName()).isNotPresent(); } @Test public void testSerializeNamed() { byte[] bytes = new byte[] {65, 66, 67, 99}; String fileName = "foo.txt"; ArrayByteSource test = ArrayByteSource.copyOf(bytes).withFileName(fileName); String json = JodaBeanSer.PRETTY.jsonWriter().write(test); ArrayByteSource roundTrip = JodaBeanSer.PRETTY.jsonReader().read(json, ArrayByteSource.class); assertThat(roundTrip).isEqualTo(test); // additional checks to ensure filenames are also equal assertThat(roundTrip.getFileName()).hasValue(fileName); } }
package org.eclipse.kura.core.configuration; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.stream.FactoryConfigurationError; import org.eclipse.kura.KuraErrorCode; import org.eclipse.kura.KuraException; import org.eclipse.kura.KuraPartialSuccessException; import org.eclipse.kura.configuration.ComponentConfiguration; import org.eclipse.kura.configuration.ConfigurationService; import org.eclipse.kura.configuration.SelfConfiguringComponent; import org.eclipse.kura.configuration.metatype.AD; import org.eclipse.kura.configuration.metatype.OCD; import org.eclipse.kura.configuration.metatype.Scalar; import org.eclipse.kura.core.configuration.metatype.Tocd; import org.eclipse.kura.core.configuration.util.CollectionsUtil; import org.eclipse.kura.core.configuration.util.ComponentUtil; import org.eclipse.kura.core.configuration.util.StringUtil; import org.eclipse.kura.core.configuration.util.XmlUtil; import org.eclipse.kura.crypto.CryptoService; import org.eclipse.kura.system.SystemService; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.cm.ConfigurationEvent; import org.osgi.service.cm.ConfigurationListener; import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentException; import org.osgi.service.metatype.AttributeDefinition; import org.osgi.service.metatype.MetaTypeService; import org.osgi.service.metatype.ObjectClassDefinition; import org.osgi.util.tracker.BundleTracker; import org.osgi.util.tracker.ServiceTracker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation of ConfigurationService. */ public class ConfigurationServiceImpl implements ConfigurationService, ConfigurationListener { private static final Logger s_logger = LoggerFactory.getLogger(ConfigurationServiceImpl.class); private ComponentContext m_ctx; private CloudConfigurationHandler m_cloudHandler; private ServiceTracker<?,?> m_serviceTracker; private BundleTracker<Bundle> m_bundleTracker; @SuppressWarnings("unused") private MetaTypeService m_metaTypeService; private ConfigurationAdmin m_configurationAdmin; private SystemService m_systemService; @SuppressWarnings("unused") private CryptoService m_cryptoService; // contains all the PIDs - both of regular and self components private Set<String> m_allPids; // contains the self configuring components ONLY! private Set<String> m_selfConfigComponents; // contains the current configuration of regular components ONLY private Map<String,Tocd> m_ocds; // contains all pids which have been configured and for which we have not received the corresponding ConfigurationEvent yet private Set<String> m_pendingConfigurationPids; // Dependencies public void setConfigurationAdmin(ConfigurationAdmin configAdmin) { this.m_configurationAdmin = configAdmin; } public void unsetConfigurationAdmin(ConfigurationAdmin configAdmin) { this.m_configurationAdmin = null; } public void setMetaTypeService(MetaTypeService metaTypeService) { this.m_metaTypeService = metaTypeService; } public void unsetMetaTypeService(MetaTypeService metaTypeService) { this.m_metaTypeService = null; } public void setSystemService(SystemService systemService) { this.m_systemService = systemService; } public void unsetSystemService(SystemService systemService) { this.m_systemService = null; } public void setCryptoService(CryptoService cryptoService) { this.m_cryptoService = cryptoService; } public void unsetCryptoService(CryptoService cryptoService) { this.m_cryptoService = null; } public ConfigurationServiceImpl() { m_allPids = new HashSet<String>(); m_selfConfigComponents = new HashSet<String>(); m_pendingConfigurationPids = new HashSet<String>(); m_ocds = new HashMap<String,Tocd>(); } // Activation APIs protected void activate(ComponentContext componentContext) throws InvalidSyntaxException { s_logger.info("activate..."); // save the bundle context m_ctx = componentContext; // 1. Register the ConfigurationListener to // monitor Configuration updates m_ctx.getBundleContext().registerService(ConfigurationListener.class.getName(), this, null); // 2. Load the latest snapshot and push it to ConfigurationAdmin try { loadLatestSnapshotInConfigAdmin(); } catch (Exception e) { throw new ComponentException("Error loading latest snapshot", e); } // start the trackers s_logger.info("Trackers being opened..."); m_cloudHandler = new CloudConfigurationHandler(m_ctx.getBundleContext(), this, m_systemService); m_cloudHandler.open(); m_serviceTracker = new ConfigurableComponentTracker(m_ctx.getBundleContext(), this); m_serviceTracker.open(true); m_bundleTracker = new ComponentMetaTypeBundleTracker(m_ctx.getBundleContext(),m_configurationAdmin, this); m_bundleTracker.open(); } protected void deactivate(ComponentContext componentContext) { s_logger.info("deactivate..."); // stop the trackers if (m_cloudHandler != null) { m_cloudHandler.close(); } if (m_serviceTracker != null) { m_serviceTracker.close(); } if (m_bundleTracker != null) { m_bundleTracker.close(); } } // ConfigurationListener @Override public synchronized void configurationEvent(ConfigurationEvent event) { // Called every time a new service configuration is invoked // we need to take a new snapshot every time this happens String pid = event.getPid(); if (m_pendingConfigurationPids.contains(pid)) { // ignore the ConfigurationEvent for those PIDs whose // configuration update was by the ConfigurationService itself m_pendingConfigurationPids.remove(pid); return; } try { if (m_allPids.contains(pid)) { // Take a new snapshot s_logger.info("ConfigurationEvent for tracked ConfigurableComponent with pid: {}", pid); snapshot(); } } catch (Exception e) { s_logger.error("Error taking snapshot after ConfigurationEvent", e); } } // Service APIs public boolean hasConfigurableComponent(String pid) { return m_allPids.contains(pid); } @Override public Set<String> getConfigurableComponentPids() { if (m_allPids.isEmpty()) { return Collections.emptySet(); } return Collections.unmodifiableSet(m_allPids); } @Override public List<ComponentConfiguration> getComponentConfigurations() throws KuraException { List<ComponentConfiguration> configs = new ArrayList<ComponentConfiguration>(); // assemble all the configurations we have // clone the list to avoid concurrent modifications List<String> allPids = new ArrayList<String>(m_allPids); ComponentConfiguration cc = null; for (String pid : allPids) { try { cc = null; if (!m_selfConfigComponents.contains(pid)) { cc = getConfigurableComponentConfiguration(pid); } else { cc = getSelfConfiguringComponentConfiguration(pid); } if (cc != null) { configs.add(cc); } } catch (Exception e) { s_logger.error("Error getting configuration for component "+pid, e); throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR, e, "Error getting configuration for component "+pid); } } return configs; } @Override public ComponentConfiguration getComponentConfiguration(String pid) throws KuraException { ComponentConfiguration cc = null; if (!m_selfConfigComponents.contains(pid)) { cc = getConfigurableComponentConfiguration(pid); } else { cc = getSelfConfiguringComponentConfiguration(pid); } return cc; } @Override public synchronized void updateConfiguration(String pidToUpdate, Map<String,Object> propertiesToUpdate) throws KuraException { // Update the component configuration boolean snapshotOnConfirmation = false; updateConfigurationInternal(pidToUpdate, propertiesToUpdate, snapshotOnConfirmation); // Build the current configuration ComponentConfiguration cc = null; ComponentConfigurationImpl cci = null; Map<String,Object> props = null; List<ComponentConfigurationImpl> configs = new ArrayList<ComponentConfigurationImpl>(); // clone the list to avoid concurrent modifications List<String> allPids = new ArrayList<String>(m_allPids); for (String pid : allPids) { if(pid.equals(pidToUpdate)) { cci = new ComponentConfigurationImpl(pid, null, propertiesToUpdate); configs.add((ComponentConfigurationImpl) cci); } else { if (!m_selfConfigComponents.contains(pid)) { cc = getConfigurableComponentConfiguration(pid); } else { cc = getSelfConfiguringComponentConfiguration(pid); } if (cc != null && cc.getPid() != null && cc.getPid().equals(pid)) { props = cc.getConfigurationProperties(); cci = new ComponentConfigurationImpl(pid, null, props); configs.add((ComponentConfigurationImpl) cci); } } } saveSnapshot(configs); } @Override public long snapshot() throws KuraException { s_logger.info("Writing snapshot - Getting component configurations..."); // Build the current configuration ComponentConfiguration cc = null; ComponentConfigurationImpl cci = null; Map<String,Object> props = null; List<ComponentConfigurationImpl> configs = new ArrayList<ComponentConfigurationImpl>(); // clone the list to avoid concurrent modifications List<String> allPids = new ArrayList<String>(m_allPids); for (String pid : allPids) { if (!m_selfConfigComponents.contains(pid)) { cc = getConfigurableComponentConfiguration(pid); } else { cc = getSelfConfiguringComponentConfiguration(pid); } if (cc != null && cc.getPid() != null && cc.getPid().equals(pid)) { props = cc.getConfigurationProperties(); cci = new ComponentConfigurationImpl(pid, null, props); configs.add((ComponentConfigurationImpl) cci); } } return saveSnapshot(configs); } @Override public long rollback() throws KuraException { // get the second-last most recent snapshot // and rollback to that one. Set<Long> ids = getSnapshots(); if (ids.size() < 2) { throw new KuraException(KuraErrorCode.CONFIGURATION_SNAPSHOT_NOT_FOUND, null, "No Snapshot Available"); } // rollback to the second last snapshot Long[] snapshots = ids.toArray( new Long[]{}); Long id = snapshots[ids.size()-2]; rollback(id); return id; } @Override public synchronized void rollback(long id) throws KuraException { // load the snapshot we need to rollback to XmlComponentConfigurations xmlConfigs = loadSnapshot(id); List<ComponentConfigurationImpl> decryptedConfigs = new ArrayList<ComponentConfigurationImpl>(); List<ComponentConfigurationImpl> configsToDecrypt = xmlConfigs.getConfigurations(); for (ComponentConfigurationImpl config : configsToDecrypt) { if (config != null) { try { Map<String,Object> decryptedProperties= decryptPasswords(config); config.setProperties(decryptedProperties); decryptedConfigs.add(config); } catch (Throwable t) { s_logger.warn("Error during snapshot password decryption"); } } } xmlConfigs.setConfigurations(decryptedConfigs); // restore configuration s_logger.info("Rolling back to snapshot {}...", id); Set<String> snapshotPids = new HashSet<String>(); boolean snapshotOnConfirmation = false; List<Throwable> causes = new ArrayList<Throwable>(); List<ComponentConfigurationImpl> configs = xmlConfigs.getConfigurations(); for (ComponentConfigurationImpl config : configs) { if (config != null) { try { updateConfigurationInternal(config.getPid(), config.getConfigurationProperties(), snapshotOnConfirmation); } catch (Throwable t) { s_logger.warn("Error during rollback for component "+config.getPid(), t); causes.add(t); } // Track the pid of the component snapshotPids.add(config.getPid()); } } // rollback to the default configuration for those configurable components // whose configuration is not present in the snapshot Set<String> pids = new HashSet<String>(m_allPids); pids.removeAll(m_selfConfigComponents); pids.removeAll(snapshotPids); for (String pid : pids) { s_logger.info("Rolling back to default configuration for component pid: '{}'", pid); Bundle bundle = m_ctx.getBundleContext().getServiceReference(pid).getBundle(); try { OCD ocd = ComponentUtil.readObjectClassDefinition(bundle, pid); Map<String, Object> defaults = ComponentUtil.getDefaultProperties(ocd); updateConfigurationInternal(pid, defaults, snapshotOnConfirmation); } catch (Throwable t) { s_logger.warn("Error during rollback for component "+pid, t); causes.add(t); } } if (causes.size() > 0) { throw new KuraPartialSuccessException("Rollback", causes); } // Do not call snapshot() here because it gets the configurations of SelfConfiguringComponents // using SelfConfiguringComponent.getConfiguration() and the configuration returned // might be the old one not the one just loaded from the snapshot and updated through // the Configuration Admin. Instead just make a copy of the snapshot. saveSnapshot(configs); } @Override public Set<Long> getSnapshots() throws KuraException { return getSnapshotsInternal(); } public List<ComponentConfiguration> getSnapshot(long sid) throws KuraException { XmlComponentConfigurations xmlConfigs = loadSnapshot(sid); List<ComponentConfigurationImpl> decryptedConfigs = new ArrayList<ComponentConfigurationImpl>(); List<ComponentConfigurationImpl> configs = xmlConfigs.getConfigurations(); for (ComponentConfigurationImpl config : configs) { if (config != null) { try { Map<String,Object> decryptedProperties= decryptPasswords(config); config.setProperties(decryptedProperties); decryptedConfigs.add(config); } catch (Throwable t) { s_logger.warn("Error during snapshot password decryption"); } } } xmlConfigs.setConfigurations(decryptedConfigs); List<ComponentConfiguration> returnConfigs = new ArrayList<ComponentConfiguration>(); if (xmlConfigs != null) { returnConfigs.addAll(xmlConfigs.getConfigurations()); } return returnConfigs; } public synchronized void updateConfigurations(List<ComponentConfiguration> configsToUpdate) throws KuraException { boolean snapshotOnConfirmation = false; List<Throwable> causes = new ArrayList<Throwable>(); for (ComponentConfiguration config : configsToUpdate) { if (config != null) { try { updateConfigurationInternal(config.getPid(), config.getConfigurationProperties(), snapshotOnConfirmation); } catch (KuraException e) { s_logger.warn("Error during updateConfigurations for component "+config.getPid(), e); causes.add(e); } } } // Build the current configuration ComponentConfiguration cc = null; ComponentConfigurationImpl cci = null; Map<String,Object> props = null; List<ComponentConfiguration> configs = new ArrayList<ComponentConfiguration>(); // clone the list to avoid concurrent modifications List<String> allPids = new ArrayList<String>(m_allPids); for (String pid : allPids) { boolean isConfigToUpdate = false; for(ComponentConfiguration configToUpdate : configsToUpdate) { if(configToUpdate.getPid().equals(pid)) { //found a match isConfigToUpdate = true; configs.add(configToUpdate); break; } } if(!isConfigToUpdate) { if (!m_selfConfigComponents.contains(pid)) { cc = getConfigurableComponentConfiguration(pid); } else { cc = getSelfConfiguringComponentConfiguration(pid); } if (cc != null && cc.getPid() != null && cc.getPid().equals(pid)) { props = cc.getConfigurationProperties(); cci = new ComponentConfigurationImpl(pid, null, props); configs.add((ComponentConfigurationImpl) cci); } } } saveSnapshot(configs); if (causes.size() > 0) { throw new KuraPartialSuccessException("updateConfigurations", causes); } } // Package APIs synchronized void registerComponentConfiguration(Bundle bundle, String pid) throws KuraException { if (!m_allPids.contains(pid)) { s_logger.info("Registration of ConfigurableComponent {} by {}...", pid, this); try { // register it m_allPids.add(pid); // Get the ocd Tocd ocd = null; try { ocd = ComponentUtil.readObjectClassDefinition(bundle, pid); if (ocd != null) { s_logger.info("Registering {} with ocd: {} ...", pid, ocd); m_ocds.put(pid, ocd); } } catch (Throwable t) { s_logger.error("Error reading ObjectClassDefinition for "+pid, t); } s_logger.info("Registration Completed for Component {}.", pid); } catch (Exception e) { s_logger.error("Error initializing Component Configuration", e); } } } synchronized void registerSelfConfiguringComponent(String pid) throws KuraException { if (pid == null) { throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR); } m_allPids.add(pid); m_selfConfigComponents.add(pid); } void unregisterComponentConfiguration(String pid) { if (pid == null) { return; } s_logger.debug("Removing component configuration for " + pid); m_allPids.remove(pid); m_ocds.remove(pid); m_selfConfigComponents.remove(pid); } void updateConfigurationInternal(String pid, Map<String,Object> properties, boolean snapshotOnConfirmation) throws KuraException { s_logger.debug("Attempting update configuration for {}", pid); if (!m_allPids.contains(pid)) { s_logger.info("UpdatingConfiguration ignored as ConfigurableComponent {} is NOT tracked.", pid); return; } if (properties == null) { s_logger.info("UpdatingConfiguration ignored as properties for ConfigurableComponent {} are NULL.", pid); return; } Map<String, Object> mergedProperties = new HashMap<String, Object>(properties); // Try to get the OCD from the registered ConfigurableComponents OCD registerdOCD = m_ocds.get(pid); // Otherwise try to get it from the registered SelfConfiguringComponents // (whose OCD is not tracked in the m_ocds map - why?). if (registerdOCD == null) { ComponentConfiguration config = getSelfConfiguringComponentConfiguration(pid); if (config != null) { registerdOCD = config.getDefinition(); } } if (registerdOCD != null) { boolean changed = mergeWithDefaults(registerdOCD, mergedProperties); if (changed) { s_logger.info("mergeWithDefaults returned "+changed); } } try { if (!m_selfConfigComponents.contains(pid)) { // load the ocd to do the validation BundleContext ctx = m_ctx.getBundleContext(); ObjectClassDefinition ocd = null; ocd = ComponentUtil.getObjectClassDefinition(ctx, pid); // Validate the properties to be applied and set them validateProperties(pid, ocd, mergedProperties); } else { // FIXME: validation of properties for self-configuring components } if (!snapshotOnConfirmation) { m_pendingConfigurationPids.add(pid); } else { s_logger.info("Snapshot on EventAdmin configuration will be taken for {}.", pid); } // Update the new properties // use ConfigurationAdmin to do the update Configuration config = m_configurationAdmin.getConfiguration(pid); config.update(CollectionsUtil.mapToDictionary(mergedProperties)); s_logger.info("Updating Configuration of ConfigurableComponent {} ... Done.", pid); } catch (IOException e) { s_logger.error("Error updating Configuration of ConfigurableComponent "+pid, e); throw new KuraException(KuraErrorCode.CONFIGURATION_UPDATE, e, pid); } } XmlComponentConfigurations loadSnapshot(long id) throws KuraException, FactoryConfigurationError { // Get the snapshot file to rollback to File fSnapshot = getSnapshotFile(id); if (!fSnapshot.exists()) { throw new KuraException(KuraErrorCode.CONFIGURATION_SNAPSHOT_NOT_FOUND, fSnapshot.getAbsolutePath()); } // Unmarshall XmlComponentConfigurations xmlConfigs = null; try { FileReader fr = new FileReader(fSnapshot); BufferedReader br = new BufferedReader(fr); String line=""; String entireFile=""; while ((line = br.readLine()) != null) { entireFile+= line; } // end while String decryptedContent= m_cryptoService.decryptAes(entireFile); xmlConfigs = XmlUtil.unmarshal(decryptedContent, XmlComponentConfigurations.class); } catch (Exception e) { s_logger.info("Snapshot not encrypted, trying to load a not encrypted one"); try { FileReader fr = new FileReader(fSnapshot); xmlConfigs = XmlUtil.unmarshal(fr, XmlComponentConfigurations.class); } catch (Exception ex) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, ex); } } return xmlConfigs; } Map<String,Object> decryptPasswords(ComponentConfiguration config){ Map<String,Object> configProperties= config.getConfigurationProperties(); Map<String,Object> decryptedProperties= new HashMap<String, Object>(); Iterator<String> keys = configProperties.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); Object value = configProperties.get(key); if (value instanceof Password) { try { Password decryptedPassword= new Password(m_cryptoService.decryptAes(value.toString())); decryptedProperties.put(key, decryptedPassword); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); decryptedProperties.put(key,value.toString()); } }else{ decryptedProperties.put(key, value); } } return decryptedProperties; } // Private APIs private synchronized long saveSnapshot(List<? extends ComponentConfiguration> configs) throws KuraException { List<ComponentConfigurationImpl> configImpls = new ArrayList<ComponentConfigurationImpl>(); for (ComponentConfiguration config : configs) { if (config instanceof ComponentConfigurationImpl) { Map<String,Object> propertiesToUpdate= config.getConfigurationProperties(); Map<String, Object> encryptedPropertiesToUpdate= new HashMap<String,Object>(); Iterator<String> keys = propertiesToUpdate.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); Object value = propertiesToUpdate.get(key); if (value != null) { if (value instanceof Password) { try { encryptedPropertiesToUpdate.put(key, new Password(m_cryptoService.encryptAes(value.toString()))); } catch (Exception e) { } } else { encryptedPropertiesToUpdate.put(key, value); } } } ((ComponentConfigurationImpl) config).setProperties(encryptedPropertiesToUpdate); configImpls.add((ComponentConfigurationImpl) config); } } // Build the XML structure XmlComponentConfigurations conf = new XmlComponentConfigurations(); conf.setConfigurations(configImpls); // Write it to disk: marshall long sid = (new Date()).getTime(); // Do not save the snapshot in the past Set<Long> snapshotIDs = getSnapshots(); if (snapshotIDs != null && snapshotIDs.size() > 0) { Long[] snapshots = snapshotIDs.toArray( new Long[]{}); Long lastestID = snapshots[snapshotIDs.size()-1]; if (lastestID != null && sid <= lastestID) { s_logger.warn("Snapshot ID: {} is in the past. Adjusting ID to: {} + 1", sid, lastestID); sid = lastestID + 1; } } File fSnapshot = getSnapshotFile(sid); s_logger.info("Writing snapshot - Saving {}...", fSnapshot.getAbsolutePath()); try { FileOutputStream fos = new FileOutputStream(fSnapshot); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); String xmlResult= XmlUtil.marshal(conf); String encryptedXML= m_cryptoService.encryptAes(xmlResult); osw.append(encryptedXML); osw.flush(); fos.flush(); fos.getFD().sync(); osw.close(); fos.close(); } catch (Throwable t) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, t); } s_logger.info("Writing snapshot - Saving {}... Done.", fSnapshot.getAbsolutePath()); // Garbage Collector for number of Snapshots Saved garbageCollectionOldSnapshots(); return sid; } private ComponentConfiguration getConfigurableComponentConfiguration(String pid) { ComponentConfiguration cc = null; try { Tocd ocd = m_ocds.get(pid); Configuration cfg = m_configurationAdmin.getConfiguration(pid); Map<String,Object> props = CollectionsUtil.dictionaryToMap(cfg.getProperties(), ocd); Map<String,Object> decryptedProperties= new HashMap<String, Object>(); Iterator<String> keys = props.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); Object value = props.get(key); if (value != null) { if (value instanceof Password) { try{ Password decryptedPassword= new Password(m_cryptoService.decryptAes(value.toString())); decryptedProperties.put(key, decryptedPassword); }catch(Exception e){ decryptedProperties.put(key, value); } } else { decryptedProperties.put(key, value); } } } cc = new ComponentConfigurationImpl(pid, ocd, decryptedProperties); //props } catch (Exception e) { s_logger.error("Error getting Configuration for component: "+pid+". Ignoring it.", e); } return cc; } private ComponentConfiguration getSelfConfiguringComponentConfiguration(String pid) { ComponentConfiguration cc = null; ServiceReference<?> ref = m_ctx.getBundleContext().getServiceReference(pid); if (ref != null) { Object obj = m_ctx.getBundleContext().getService(ref); try { if (obj instanceof SelfConfiguringComponent) { SelfConfiguringComponent selfConfigComp = null; selfConfigComp = (SelfConfiguringComponent) obj; try { cc = selfConfigComp.getConfiguration(); if (cc.getPid() == null || !cc.getPid().equals(pid)) { s_logger.error("Invalid pid for returned Configuration of SelfConfiguringComponent with pid: "+pid+". Ignoring it."); cc = null; // do not return the invalid configuration return cc; } OCD ocd = cc.getDefinition(); if (ocd != null) { List<AD> ads = ocd.getAD(); if (ads != null) { for (AD ad : ads) { String adId = ad.getId(); String adType = ad.getType().value(); if (adId == null) { s_logger.error("null required id for AD for returned Configuration of SelfConfiguringComponent with pid: {}", pid); cc = null; return cc; // do not return the invalid configuration } if (adType == null) { s_logger.error("null required type for AD id: {} for returned Configuration of SelfConfiguringComponent with pid: {}", adId, pid); cc = null; return cc; // do not return the invalid configuration } Map<String, Object> props = cc.getConfigurationProperties(); if (props != null) { for (String propName : props.keySet()) { if (propName.equals(adId)) { Object value = props.get(propName); if (value != null) { String propType = value.getClass().getSimpleName(); try { s_logger.debug("pid: {}, property name: {}, type: {}, value: {}", new Object[] {pid, propName, propType, value}); Scalar.fromValue(propType); if (!propType.equals(adType)) { s_logger.error("Type: {} for property named: {} does not match the AD type: {} for returned Configuration of SelfConfiguringComponent with pid: {}", new Object[] {propType, propName, adType, pid}); cc = null; return cc; // do not return the invalid configuration } } catch (IllegalArgumentException e) { s_logger.error("Invalid class: {} for property named: {} for returned Configuration of SelfConfiguringComponent with pid: " + pid, propType, propName); cc = null; return cc; // do not return the invalid configuration } } } } } } } } } catch (KuraException e) { s_logger.error("Error getting Configuration for component: "+pid+". Ignoring it.", e); } } else { s_logger.error("Component "+obj+" is not a SelfConfiguringComponent. Ignoring it."); } } finally { m_ctx.getBundleContext().ungetService(ref); } } return cc; } private TreeSet<Long> getSnapshotsInternal() { // keeps the list of snapshots ordered TreeSet<Long> ids = new TreeSet<Long>(); String configDir = getSnapshotsDirectory(); if(configDir != null) { File fConfigDir = new File(configDir); File[] files = fConfigDir.listFiles(); if (files != null) { Pattern p = Pattern.compile("snapshot_([0-9]+)\\.xml"); for (File file : files) { Matcher m = p.matcher(file.getName()); if (m.matches()) { ids.add(Long.parseLong(m.group(1))); } } } } return ids; } String getSnapshotsDirectory() { String configDirs = m_systemService.getKuraSnapshotsDirectory(); return configDirs; } private File getSnapshotFile(long id) { String configDir = getSnapshotsDirectory(); StringBuilder sbSnapshot = new StringBuilder(configDir); sbSnapshot.append(File.separator) .append("snapshot_") .append(id) .append(".xml"); String snapshot = sbSnapshot.toString(); return new File(snapshot); } private void garbageCollectionOldSnapshots() { // get the current snapshots and compared with the maximum number we need to keep TreeSet<Long> sids = getSnapshotsInternal(); int currCount = sids.size(); int maxCount = m_systemService.getKuraSnapshotsCount(); while (currCount > maxCount) { // preserve snapshot ID 0 as this will be considered the seeding one. long sid = sids.pollFirst(); if (sid != 0) { File fSnapshot = getSnapshotFile(sid); if (fSnapshot.exists()) { s_logger.info("Snapshots Garbage Collector. Deleting {}", fSnapshot.getAbsolutePath()); fSnapshot.delete(); currCount } } } } private void loadLatestSnapshotInConfigAdmin() throws KuraException { // Get the latest snapshot file to use as initialization Set<Long> snapshotIDs = getSnapshots(); if (snapshotIDs == null || snapshotIDs.size() == 0) { return; } Long[] snapshots = snapshotIDs.toArray( new Long[]{}); Long lastestID = snapshots[snapshotIDs.size()-1]; String configDir = getSnapshotsDirectory(); StringBuilder sbSnapshot = new StringBuilder(configDir); sbSnapshot.append(File.separator) .append("snapshot_") .append(lastestID) .append(".xml"); String snapshot = sbSnapshot.toString(); File fSnapshot = new File(snapshot); if (!fSnapshot.exists()) { throw new KuraException(KuraErrorCode.CONFIGURATION_SNAPSHOT_NOT_FOUND, snapshot); } // Unmarshall s_logger.info("Loading init configurations from: {}...", snapshot); XmlComponentConfigurations xmlConfigs = null; try { FileReader fr = new FileReader(fSnapshot); BufferedReader br = new BufferedReader(fr); String line=""; String entireFile=""; while ((line = br.readLine()) != null) { entireFile+= line; } // end while String decryptedContent= m_cryptoService.decryptAes(entireFile); xmlConfigs = XmlUtil.unmarshal(decryptedContent, XmlComponentConfigurations.class); } catch (Exception e) { s_logger.info("Snapshot not encrypted, trying to load a not encrypted one"); try { FileReader fr = new FileReader(fSnapshot); xmlConfigs = XmlUtil.unmarshal(fr, XmlComponentConfigurations.class); } catch (Exception ex) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } } // save away initial configuration List<ComponentConfigurationImpl> configs = xmlConfigs.getConfigurations(); for (ComponentConfigurationImpl config : configs) { if (config != null) { Configuration cfg; try { s_logger.debug("Pushing config to config admin: {}", config.getPid()); // push it to the ConfigAdmin cfg = m_configurationAdmin.getConfiguration(config.getPid()); cfg.update(CollectionsUtil.mapToDictionary(config.getConfigurationProperties())); // track it as a pending Configuration // for which we are expecting a confirmation m_pendingConfigurationPids.add(config.getPid()); } catch (IOException e) { s_logger.warn("Error seeding initial properties to ConfigAdmin for service: "+config.getPid(), e); } } } } private void validateProperties(String pid, ObjectClassDefinition ocd, Map<String, Object> updatedProps) throws KuraException { if (ocd != null) { // build a map of all the attribute definitions Map<String,AttributeDefinition> attrDefs = new HashMap<String,AttributeDefinition>(); AttributeDefinition[] defs = ocd.getAttributeDefinitions(ObjectClassDefinition.ALL); for (AttributeDefinition def : defs) { attrDefs.put(def.getID(), def); } // loop over the proposed property values // and validate them against the definition Iterator<String> keys = updatedProps.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); AttributeDefinition attrDef = attrDefs.get(key); // is attribute undefined? if (attrDef == null) { // we do not have an attribute descriptor to the validation against // As OSGI insert attributes at runtime like service.pid, component.name, // for the attribute for which we do not have a definition, // just accept them. continue; } // validate the attribute value Object objectValue = updatedProps.get(key); String stringValue = StringUtil.valueToString(objectValue); if (stringValue != null) { String result = attrDef.validate(stringValue); if (result != null && !result.isEmpty()) { throw new KuraException(KuraErrorCode.CONFIGURATION_ATTRIBUTE_INVALID, attrDef.getID()+": "+result); } } } // make sure all required properties are set OCD ocdFull = m_ocds.get(pid); if (ocdFull != null) { for (AD attrDef : ocdFull.getAD()) { // to the required attributes make sure a value is defined. if (attrDef.isRequired()) { if (updatedProps.get(attrDef.getId()) == null) { // if the default one is not defined, throw exception. throw new KuraException(KuraErrorCode.CONFIGURATION_REQUIRED_ATTRIBUTE_MISSING, attrDef.getId()); } } } } } } boolean mergeWithDefaults(OCD ocd, Map<String,Object> properties) throws KuraException { boolean changed = false; Set<String> keys = properties.keySet(); Map<String, Object> defaults = ComponentUtil.getDefaultProperties(ocd); Set<String> defaultsKeys = defaults.keySet(); defaultsKeys.removeAll(keys); if (!defaultsKeys.isEmpty()) { changed = true; s_logger.info("Merging configuration for pid: {}", ocd.getId()); for (String key : defaultsKeys) { Object value = defaults.get(key); properties.put(key, value); s_logger.debug("Merged configuration properties with property with name: {} and default value {}", key, value); } } return changed; } }
package org.jpos.ee.pm.struts.converter; import java.util.List; import org.jpos.ee.pm.converter.ConverterException; import org.jpos.ee.pm.core.Entity; import org.jpos.ee.pm.core.EntitySupport; import org.jpos.ee.pm.core.Field; import org.jpos.ee.pm.core.ListFilter; import org.jpos.ee.pm.core.PMException; import org.jpos.ee.pm.core.PMLogger; import org.jpos.ee.pm.struts.PMEntitySupport; import org.jpos.ee.pm.struts.PMStrutsContext; /** * * @author jpaoletti */ public abstract class AbstractCollectionConverter extends StrutsEditConverter{ public void saveList(PMStrutsContext ctx, String eid){ try { ctx.getSession().setAttribute(getTmpName(ctx, eid), getList(ctx)); } catch (PMException ex) { PMLogger.error(ex); } } public static List<?> recoverList(PMStrutsContext ctx, String eid, boolean remove){ try { final List<?> r = (List<?>) ctx.getSession().getAttribute(getTmpName(ctx, eid)); if(remove) ctx.getSession().removeAttribute(getTmpName(ctx, eid)); return r; } catch (PMException ex) { PMLogger.error(ex); return null; } } public List<?> getList(PMStrutsContext ctx) throws PMException { final String filter = getConfig("filter"); final String eid = getConfig("entity"); ListFilter lfilter = null; if( filter != null && filter.compareTo("null") != 0 && filter.compareTo("") != 0) { lfilter = (ListFilter) EntitySupport.newObjectOf(filter); } PMEntitySupport es = PMEntitySupport.getInstance(); Entity e = es.getPmservice().getEntity(eid); List<?> list = null; if(e==null) throw new ConverterException("Cannot find entity "+eid); synchronized (e) { ListFilter tmp = e.getListfilter(); e.setListfilter(lfilter); list = e.getList(ctx,null,null,null); e.setListfilter(tmp); } return list; } public static String getTmpName(PMStrutsContext ctx, String eid) throws PMException{ Field field = (Field) ctx.get(PM_FIELD); return "tmp_"+ctx.getEntity().getId()+"_"+field.getId(); } }
package com.mebigfatguy.fbcontrib.detect; import java.util.HashMap; import java.util.Map; import org.apache.bcel.Repository; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.Type; import com.mebigfatguy.fbcontrib.utils.TernaryPatcher; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.OpcodeStack.CustomUserValue; import edu.umd.cs.findbugs.ba.ClassContext; /** * looks for implementation of clone() where a store is made to a member * of the source object. */ @CustomUserValue public class SuspiciousCloneAlgorithm extends BytecodeScanningDetector { private static JavaClass cloneableClass; private static Map<String, Integer> changingMethods; static { try { cloneableClass = Repository.lookupClass("java/lang/Cloneable"); Integer normal = Integer.valueOf(NORMAL_PRIORITY); Integer low = Integer.valueOf(LOW_PRIORITY); changingMethods = new HashMap<String, Integer>(); changingMethods.put("add", normal); changingMethods.put("addAll", normal); changingMethods.put("put", normal); changingMethods.put("putAll", normal); changingMethods.put("insert", low); changingMethods.put("set", low); } catch (ClassNotFoundException cnfe) { cloneableClass = null; } } private BugReporter bugReporter; private OpcodeStack stack; /** * constructs a SCA detector given the reporter to report bugs on * @param bugReporter the sync of bug reports */ public SuspiciousCloneAlgorithm(BugReporter bugReporter) { this.bugReporter = bugReporter; } /** * override the visitor to look for classes that implement Cloneable * * @param classContext the context object of the class to be checked */ @Override public void visitClassContext(ClassContext classContext) { if (cloneableClass == null) return; try { JavaClass cls = classContext.getJavaClass(); if (cls.implementationOf(cloneableClass)) { stack = new OpcodeStack(); super.visitClassContext(classContext); } } catch (ClassNotFoundException cnfe) { bugReporter.reportMissingClass(cnfe); } finally { stack = null; } } /** * override the visitor to only continue for the clone method * * @param obj the context object of the currently parsed method */ @Override public void visitCode(Code obj) { Method m = getMethod(); if (!m.isStatic() && "clone".equals(m.getName()) && "()Ljava/lang/Object;".equals(m.getSignature())) super.visitCode(obj); } /** * override the visitor to look for stores to member fields of the source object on a clone * * @param seen the opcode of the currently parsed instruction */ @Override public void sawOpcode(int seen) { boolean srcField = false; try { stack.precomputation(this); switch (seen) { case ALOAD_0: srcField = true; break; case DUP: if (stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); if (item.getUserValue() != null) srcField = true; } break; case GETFIELD: if (stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); if (item.getRegisterNumber() == 0) { srcField = true; } } break; case PUTFIELD: if (stack.getStackDepth() >= 2) { OpcodeStack.Item item = stack.getStackItem(1); if ((item.getRegisterNumber() == 0) || (item.getUserValue() != null)) { bugReporter.reportBug(new BugInstance(this, "SCA_SUSPICIOUS_CLONE_ALGORITHM", NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this)); } } break; case INVOKEINTERFACE: case INVOKEVIRTUAL: String sig = getSigConstantOperand(); int numArgs = Type.getArgumentTypes(sig).length; if (stack.getStackDepth() > numArgs) { OpcodeStack.Item item = stack.getStackItem(numArgs); if ((item.getRegisterNumber() == 0) || (item.getUserValue() != null)) { String name = getNameConstantOperand(); Integer priority = changingMethods.get(name); if (priority != null) bugReporter.reportBug(new BugInstance(this, "SCA_SUSPICIOUS_CLONE_ALGORITHM", priority.intValue()) .addClass(this) .addMethod(this) .addSourceLine(this)); } } break; } } finally { TernaryPatcher.pre(stack, seen); stack.sawOpcode(this, seen); TernaryPatcher.post(stack, seen); if (srcField && stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); item.setUserValue(Boolean.TRUE); } } } }
package com.redhat.ceylon.compiler.typechecker.context; import java.util.HashSet; import java.util.List; import java.util.Set; import org.antlr.runtime.CommonToken; import com.redhat.ceylon.compiler.typechecker.analyzer.ControlFlowVisitor; import com.redhat.ceylon.compiler.typechecker.analyzer.DeclarationVisitor; import com.redhat.ceylon.compiler.typechecker.analyzer.DependedUponVisitor; import com.redhat.ceylon.compiler.typechecker.analyzer.ExpressionVisitor; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleManager; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleVisitor; import com.redhat.ceylon.compiler.typechecker.analyzer.RefinementVisitor; import com.redhat.ceylon.compiler.typechecker.analyzer.SelfReferenceVisitor; import com.redhat.ceylon.compiler.typechecker.analyzer.SpecificationVisitor; import com.redhat.ceylon.compiler.typechecker.analyzer.TypeArgumentVisitor; import com.redhat.ceylon.compiler.typechecker.analyzer.TypeHierarchyVisitor; import com.redhat.ceylon.compiler.typechecker.analyzer.TypeVisitor; import com.redhat.ceylon.compiler.typechecker.analyzer.ValueVisitor; import com.redhat.ceylon.compiler.typechecker.io.VirtualFile; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Setter; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Validator; import com.redhat.ceylon.compiler.typechecker.util.AssertionVisitor; import com.redhat.ceylon.compiler.typechecker.util.PrintVisitor; import com.redhat.ceylon.compiler.typechecker.util.StatisticsVisitor; /** * Represent a unit and each of the type checking phases * * @author Emmanuel Bernard <emmanuel@hibernate.org> */ public class PhasedUnit { private Tree.CompilationUnit compilationUnit; private Package pkg; private Unit unit; //must be the non qualified file name private String fileName; private final ModuleManager moduleManager; private final String pathRelativeToSrcDir; private VirtualFile unitFile; private final Set<PhasedUnit> dependentsOf = new HashSet<PhasedUnit>(); private List<CommonToken> tokens; private ModuleVisitor moduleVisitor; private VirtualFile srcDir; private boolean declarationsScanned; private boolean typeDeclarationsScanned; private boolean refinementValidated; private boolean flowAnalyzed; private boolean fullyTyped; public VirtualFile getSrcDir() { return srcDir; } public PhasedUnit(VirtualFile unitFile, VirtualFile srcDir, Tree.CompilationUnit cu, Package p, ModuleManager moduleManager, Context context, List<CommonToken> tokenStream) { this.compilationUnit = cu; this.pkg = p; this.unitFile = unitFile; this.srcDir = srcDir; this.fileName = unitFile.getName(); this.pathRelativeToSrcDir = computeRelativePath(unitFile, srcDir); this.moduleManager = moduleManager; this.tokens = tokenStream; } @Deprecated protected PhasedUnit(VirtualFile unitFile, VirtualFile srcDir, Tree.CompilationUnit cu, Package p, ModuleManager moduleManager, Context context) { this(unitFile, srcDir, cu, p, moduleManager, context, null); } private String computeRelativePath(VirtualFile unitFile, VirtualFile srcDir) { final String rawRelativePath = unitFile.getPath().substring( srcDir.getPath().length() ); if ( rawRelativePath.startsWith("/") ) { return rawRelativePath.substring(1); } else if ( rawRelativePath.startsWith("!/") ) { return rawRelativePath.substring(2); } else { return rawRelativePath; } } public Module visitSrcModulePhase() { if ( ModuleManager.MODULE_FILE.equals(fileName) || ModuleManager.PACKAGE_FILE.equals(fileName) ) { moduleVisitor = new ModuleVisitor(moduleManager, pkg); compilationUnit.visit(moduleVisitor); return moduleVisitor.getMainModule(); } return null; } public void visitRemainingModulePhase() { if ( moduleVisitor != null ) { moduleVisitor.setPhase(ModuleVisitor.Phase.REMAINING); compilationUnit.visit(moduleVisitor); } } public boolean isFullyTyped() { return fullyTyped; } public void setFullyTyped(boolean fullyTyped) { this.fullyTyped = fullyTyped; } public boolean isFlowAnalyzed() { return flowAnalyzed; } public void setFlowAnalyzed(boolean flowAnalyzed) { this.flowAnalyzed = flowAnalyzed; } public boolean isDeclarationsScanned() { return declarationsScanned; } public void setDeclarationsScanned(boolean declarationsScanned) { this.declarationsScanned = declarationsScanned; } public boolean isTypeDeclarationsScanned() { return typeDeclarationsScanned; } public void setTypeDeclarationsScanned(boolean typeDeclarationsScanned) { this.typeDeclarationsScanned = typeDeclarationsScanned; } public boolean isRefinementValidated() { return refinementValidated; } public void setRefinementValidated(boolean refinementValidated) { this.refinementValidated = refinementValidated; } public void validateTree() { //System.out.println("Validating tree for " + fileName); compilationUnit.visit(new Validator()); } public void scanDeclarations() { if (!declarationsScanned) { //System.out.println("Scan declarations for " + fileName); DeclarationVisitor dv = new DeclarationVisitor(pkg, fileName); compilationUnit.visit(dv); unit = dv.getCompilationUnit(); declarationsScanned = true; } } public void scanTypeDeclarations() { if (!typeDeclarationsScanned) { //System.out.println("Scan type declarations for " + fileName); compilationUnit.visit( new TypeVisitor() ); typeDeclarationsScanned = true; } } public void analyseTypes() { if (! fullyTyped) { //System.out.println("Run analysis phase for " + fileName); compilationUnit.visit(new ExpressionVisitor()); compilationUnit.visit(new TypeArgumentVisitor()); compilationUnit.visit(new TypeHierarchyVisitor()); fullyTyped = true; } } public void collectUnitDependencies(PhasedUnits phasedUnits, List<PhasedUnits> phasedUnitsOfDependencies) { //System.out.println("Run collecting unit dependencies phase for " + fileName); compilationUnit.visit(new DependedUponVisitor(this, phasedUnits, phasedUnitsOfDependencies)); } public void analyseFlow() { if (! flowAnalyzed) { //System.out.println("Validate control flow for " + fileName); compilationUnit.visit(new ControlFlowVisitor()); //System.out.println("Validate self references for " + fileName); //System.out.println("Validate specification for " + fileName); for (Declaration d: unit.getDeclarations()) { compilationUnit.visit(new SpecificationVisitor(d)); if (d instanceof TypedDeclaration && !(d instanceof Setter)) { compilationUnit.visit(new ValueVisitor((TypedDeclaration) d)); } else if (d instanceof TypeDeclaration) { compilationUnit.visit(new SelfReferenceVisitor((TypeDeclaration) d)); } } flowAnalyzed = true; } } public void validateRefinement() { if (! refinementValidated) { //System.out.println("Validate member refinement for " + fileName); compilationUnit.visit(new RefinementVisitor()); refinementValidated = true; } } public void generateStatistics(StatisticsVisitor statsVisitor) { compilationUnit.visit(statsVisitor); } public void runAssertions(AssertionVisitor av) { //System.out.println("Running assertions for " + fileName); compilationUnit.visit(av); } public void display() { System.out.println("Displaying " + fileName); compilationUnit.visit(new PrintVisitor()); } public Package getPackage() { return pkg; } public Unit getUnit() { return unit; } public String getPathRelativeToSrcDir() { return pathRelativeToSrcDir; } public VirtualFile getUnitFile() { return unitFile; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("PhasedUnit"); sb.append("{filename=").append(fileName); sb.append(", compilationUnit=").append(unit); sb.append(", pkg=").append(pkg); sb.append('}'); return sb.toString(); } public Tree.CompilationUnit getCompilationUnit() { return compilationUnit; } /** * @return the dependentsOf */ public Set<PhasedUnit> getDependentsOf() { return dependentsOf; } public List<CommonToken> getTokens() { return tokens; } }
package com.tisawesomeness.minecord.command.general; import java.awt.Color; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONObject; import com.tisawesomeness.minecord.command.Command; import com.tisawesomeness.minecord.util.MessageUtils; import com.tisawesomeness.minecord.util.RequestUtils; import net.dv8tion.jda.core.entities.MessageEmbed; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; public class StatusCommand extends Command { public CommandInfo getInfo() { return new CommandInfo( "status", "Checks the status of Mojang servers.", null, null, 2000, false, false, true ); } public Result run(String[] args, MessageReceivedEvent e) { //Request information from Mojang String request = RequestUtils.get("https://status.mojang.com/check"); if (request == null) { return new Result(Outcome.ERROR, ":x: The Mojang API could not be reached."); } Color color = Color.GREEN; //Iterate over response sections ArrayList<String> responses = new ArrayList<String>(); JSONArray status = new JSONArray(request); for (int i = 0; i < status.length(); i++) { //Fetch the response JSONObject json = status.getJSONObject(i); String[] names = JSONObject.getNames(json); String response = json.getString(names[0]); //Parse the response String output = ":x:"; if ("green".equals(response)) { output = ":white_check_mark:"; } else if ("yellow".equals(response)) { output = ":warning:"; if (color != Color.RED) color = Color.YELLOW; } else { color = Color.RED; } responses.add(output); } //Build message String m = "**Minecraft:** " + responses.get(0) + "\n" + "**Accounts:** " + responses.get(2) + "\n" + "**Textures:** " + responses.get(6) + "\n" + "**Session:** " + responses.get(1) + "\n" + "**Session Server:** " + responses.get(4) + "\n" + "**Auth Server:** " + responses.get(3) + "\n" + "**Mojang:** " + responses.get(7) + "\n" + "**Mojang API:** " + responses.get(5); MessageEmbed me = MessageUtils.embedMessage("Minecraft Status", null, m, color); return new Result(Outcome.SUCCESS, me); } }
package de.danielweisser.android.ldapsync.syncadapter; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.Context; import android.content.SyncResult; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import de.danielweisser.android.ldapsync.Constants; import de.danielweisser.android.ldapsync.authenticator.LDAPAuthenticatorActivity; import de.danielweisser.android.ldapsync.client.LDAPServerInstance; import de.danielweisser.android.ldapsync.client.LDAPUtilities; import de.danielweisser.android.ldapsync.client.Contact; import de.danielweisser.android.ldapsync.platform.ContactManager; /** * SyncAdapter implementation for synchronizing LDAP contacts to the platform * ContactOperations provider. */ public class SyncAdapter extends AbstractThreadedSyncAdapter { private static final String TAG = "LDAPSyncAdapter"; private final AccountManager mAccountManager; private final Context mContext; private Date mLastUpdated; public SyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); mContext = context; mAccountManager = AccountManager.get(context); } @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { Log.d(TAG, "Start the sync."); List<Contact> users = new ArrayList<Contact>(); String authtoken = null; try { // use the account manager to request the credentials authtoken = mAccountManager .blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true /* notifyAuthFailure */); final String host = mAccountManager.getUserData(account, LDAPAuthenticatorActivity.PARAM_HOST); final String username = mAccountManager.getUserData(account, LDAPAuthenticatorActivity.PARAM_USERNAME); final int port = Integer.parseInt(mAccountManager.getUserData(account, LDAPAuthenticatorActivity.PARAM_PORT)); final String sEnc = mAccountManager.getUserData(account, LDAPAuthenticatorActivity.PARAM_ENCRYPTION); int encryption = 0; if (!TextUtils.isEmpty(sEnc)) { encryption = Integer.parseInt(sEnc); } LDAPServerInstance ldapServer = new LDAPServerInstance(host, port, encryption, username, authtoken); final String searchFilter = mAccountManager.getUserData(account, LDAPAuthenticatorActivity.PARAM_SEARCHFILTER); final String baseDN = mAccountManager.getUserData(account, LDAPAuthenticatorActivity.PARAM_BASEDN); // LDAP name mappings final Bundle mappingBundle = new Bundle(); mappingBundle.putString(Contact.FIRSTNAME, mAccountManager.getUserData(account, LDAPAuthenticatorActivity.PARAM_MAPPING + Contact.FIRSTNAME)); mappingBundle.putString(Contact.LASTNAME, mAccountManager.getUserData(account, LDAPAuthenticatorActivity.PARAM_MAPPING + Contact.LASTNAME)); mappingBundle.putString(Contact.TELEPHONE, mAccountManager.getUserData(account, LDAPAuthenticatorActivity.PARAM_MAPPING + Contact.TELEPHONE)); mappingBundle.putString(Contact.MOBILE, mAccountManager.getUserData(account, LDAPAuthenticatorActivity.PARAM_MAPPING + Contact.MOBILE)); mappingBundle.putString(Contact.MAIL, mAccountManager.getUserData(account, LDAPAuthenticatorActivity.PARAM_MAPPING + Contact.MAIL)); mappingBundle.putString(Contact.PHOTO, mAccountManager.getUserData(account, LDAPAuthenticatorActivity.PARAM_MAPPING + Contact.PHOTO)); users = LDAPUtilities.fetchContacts(ldapServer, baseDN, searchFilter, mappingBundle, mLastUpdated); if (users == null) { syncResult.stats.numIoExceptions++; return; } // update the last synced date. mLastUpdated = new Date(); // update platform contacts. Log.d(TAG, "Calling contactManager's sync contacts"); ContactManager.syncContacts(mContext, account.name, users, syncResult); } catch (final AuthenticatorException e) { syncResult.stats.numParseExceptions++; Log.e(TAG, "AuthenticatorException", e); } catch (final OperationCanceledException e) { Log.e(TAG, "OperationCanceledExcetpion", e); } catch (final IOException e) { Log.e(TAG, "IOException", e); syncResult.stats.numIoExceptions++; } } }
package de.unitrier.st.soposthistory.tests; import de.unitrier.st.soposthistory.blocks.CodeBlockVersion; import de.unitrier.st.soposthistory.blocks.PostBlockVersion; import de.unitrier.st.soposthistory.blocks.TextBlockVersion; import de.unitrier.st.soposthistory.version.PostVersion; import de.unitrier.st.soposthistory.version.PostVersionList; import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import static org.junit.jupiter.api.Assertions.*; class PostVersionHistoryTest { @Test void testReadPostHistoryAnswer1109108() { PostVersionList a_1109108 = new PostVersionList(); a_1109108.readFromCSV("testdata", 1109108, 2); assertEquals(7, a_1109108.size()); PostVersion version_7 = a_1109108.get(6); assertEquals(3, version_7.getPostBlocks().size()); assertEquals(2, version_7.getTextBlocks().size()); assertEquals(1, version_7.getCodeBlocks().size()); CodeBlockVersion codeBlock_1 = version_7.getCodeBlocks().get(0); String[] lines = codeBlock_1.getContent().split("\n"); assertEquals(6, lines.length); for (String line : lines) { assertTrue(line.startsWith(" ")); } TextBlockVersion textBlock_1 = version_7.getTextBlocks().get(0); lines = textBlock_1.getContent().split("\n"); assertEquals(1, lines.length); for (String line : lines) { assertFalse(line.startsWith(" ")); } } @Test void testReadPostHistoryAnswer3145655() { PostVersionList a_3145655 = new PostVersionList(); a_3145655.readFromCSV("testdata", 3145655, 2); assertEquals(7, a_3145655.size()); PostVersion version_7 = a_3145655.get(6); assertEquals(5, version_7.getPostBlocks().size()); assertEquals(3, version_7.getTextBlocks().size()); assertEquals(2, version_7.getCodeBlocks().size()); CodeBlockVersion codeBlock_1 = version_7.getCodeBlocks().get(0); String[] lines = codeBlock_1.getContent().split("\n"); assertEquals(8, lines.length); for (String line : lines) { assertTrue(line.startsWith(" ")); } TextBlockVersion textBlock_1 = version_7.getTextBlocks().get(0); lines = textBlock_1.getContent().split("\n"); assertEquals(7, lines.length); for (String line : lines) { assertFalse(line.startsWith(" ")); } } @Test void testReadPostHistoryAnswer9855338() { PostVersionList a_9855338 = new PostVersionList(); a_9855338.readFromCSV("testdata", 9855338, 2); assertEquals(11, a_9855338.size()); PostVersion version_11 = a_9855338.get(10); assertEquals(3, version_11.getPostBlocks().size()); assertEquals(2, version_11.getTextBlocks().size()); assertEquals(1, version_11.getCodeBlocks().size()); CodeBlockVersion codeBlock_1 = version_11.getCodeBlocks().get(0); String[] lines = codeBlock_1.getContent().split("\n"); assertEquals(10, lines.length); for (String line : lines) { assertTrue(line.startsWith(" ")); } TextBlockVersion textBlock_1 = version_11.getTextBlocks().get(0); lines = textBlock_1.getContent().split("\n"); assertEquals(1, lines.length); for (String line : lines) { assertFalse(line.startsWith(" ")); } } @Test void testReadPostHistoryAnswer2581754() { PostVersionList a_2581754 = new PostVersionList(); a_2581754.readFromCSV("testdata", 2581754, 2); assertEquals(8, a_2581754.size()); PostVersion version_3 = a_2581754.get(2); assertEquals(6, version_3.getPostBlocks().size()); assertEquals(3, version_3.getTextBlocks().size()); assertEquals(3, version_3.getCodeBlocks().size()); CodeBlockVersion codeBlock_1 = version_3.getCodeBlocks().get(0); String[] lines = codeBlock_1.getContent().split("\n"); assertEquals(25, lines.length); for (String line : lines) { assertTrue(line.startsWith(" ")); } TextBlockVersion textBlock_1 = version_3.getTextBlocks().get(0); lines = textBlock_1.getContent().split("\n"); assertEquals(1, lines.length); for (String line : lines) { assertFalse(line.startsWith(" ")); } } @Test void testPostBlockVersionExtraction() { // TODO: add test cases for testing the version history extraction (similarity and diffs between code blocks and text blocks, linking of block versions) //a_1109108.processVersionHistory(); //PostVersion version_7 = a_1109108.get(6); //assertEquals(2, version_7.getCodeBlocks().get(0).getPredDiff().size()); } @Test void testReadPostHistoryAnswer20991163() { PostVersionList a_20991163 = new PostVersionList(); a_20991163.readFromCSV("testdata", 20991163, 2); // this post should only consist of one code block (not an empty text block at the end) assertEquals(1, a_20991163.size()); PostVersion version_1 = a_20991163.get(0); assertEquals(1, version_1.getPostBlocks().size()); assertEquals(0, version_1.getTextBlocks().size()); assertEquals(1, version_1.getCodeBlocks().size()); } @Test void testReadPostHistoryAnswer32012927() { PostVersionList a_32012927 = new PostVersionList(); a_32012927.readFromCSV("testdata", 32012927, 2); assertEquals(4, a_32012927.size()); // the first version of this post should only consist of one text block PostVersion version_1 = a_32012927.get(0); assertEquals(1, version_1.getPostBlocks().size()); assertEquals(1, version_1.getTextBlocks().size()); assertEquals(0, version_1.getCodeBlocks().size()); } @Test void testReadPostHistoryAnswer10734905() { PostVersionList a_10734905 = new PostVersionList(); a_10734905.readFromCSV("testdata", 10734905, 2); assertEquals(1, a_10734905.size()); // the first and only version of this post should consist of three text blocks and two code blocks PostVersion version_1 = a_10734905.get(0); assertEquals(5, version_1.getPostBlocks().size()); assertEquals(3, version_1.getTextBlocks().size()); assertEquals(2, version_1.getCodeBlocks().size()); List<PostBlockVersion> postBlocks = version_1.getPostBlocks(); assertTrue(postBlocks.get(0) instanceof TextBlockVersion); assertTrue(postBlocks.get(1) instanceof CodeBlockVersion); assertTrue(postBlocks.get(2) instanceof TextBlockVersion); assertTrue(postBlocks.get(3) instanceof CodeBlockVersion); assertTrue(postBlocks.get(4) instanceof TextBlockVersion); } @Test void testReadPostHistoryAnswer31965641() { PostVersionList a_31965641 = new PostVersionList(); a_31965641.readFromCSV("testdata", 31965641, 2); assertEquals(1, a_31965641.size()); // the first and only version of this post should consist of two text blocks and two code blocks PostVersion version_1 = a_31965641.get(0); assertEquals(4, version_1.getPostBlocks().size()); assertEquals(2, version_1.getTextBlocks().size()); assertEquals(2, version_1.getCodeBlocks().size()); List<PostBlockVersion> postBlocks = version_1.getPostBlocks(); assertTrue(postBlocks.get(0) instanceof TextBlockVersion); assertTrue(postBlocks.get(1) instanceof CodeBlockVersion); assertTrue(postBlocks.get(2) instanceof TextBlockVersion); assertTrue(postBlocks.get(3) instanceof CodeBlockVersion); } @Test void testRootPostBlockVersionIdAnswer3758880() { PostVersionList a_3758880 = new PostVersionList(); a_3758880.readFromCSV("testdata", 3758880, 2); // there are 11 versions of this post assertEquals(11, a_3758880.size()); PostVersion firstVersion = a_3758880.get(0); assertEquals(6, firstVersion.getPostBlocks().size()); // root post blocks of first version must be null for (PostBlockVersion currentPostBlock : firstVersion.getPostBlocks()) { assertEquals(currentPostBlock.getId(), (int)currentPostBlock.getRootPostBlockId()); } PostVersion secondPostVersion = a_3758880.get(1); assertEquals(4, secondPostVersion.getPostBlocks().size()); // first code block of second version has first code block of first version as root post block assertEquals((int)secondPostVersion.getCodeBlocks().get(0).getRootPostBlockId(), firstVersion.getCodeBlocks().get(0).getId()); // second code block of second version has third code block of first version as root post block assertEquals((int)secondPostVersion.getCodeBlocks().get(1).getRootPostBlockId(), firstVersion.getCodeBlocks().get(2).getId()); // second text block of second version has no predecessor (-> itself as root post block) assertEquals((int)secondPostVersion.getTextBlocks().get(0).getRootPostBlockId(), secondPostVersion.getTextBlocks().get(0).getId()); PostVersion lastPostVersion = a_3758880.get(a_3758880.size()-1); // first code block of last version still has first code block of first version as root post block assertEquals((int)lastPostVersion.getCodeBlocks().get(0).getRootPostBlockId(), firstVersion.getCodeBlocks().get(0).getId()); // first text block of last version has first text block of second version as root post block assertEquals((int)lastPostVersion.getTextBlocks().get(0).getRootPostBlockId(), secondPostVersion.getTextBlocks().get(0).getId()); } @Test void testReadPostHistoryQuestion22360443() { PostVersionList q_22360443 = new PostVersionList(); q_22360443.readFromCSV("testdata", 22360443, 1); assertEquals(2, q_22360443.size()); PostVersion version_1 = q_22360443.get(0); assertEquals(4, version_1.getPostBlocks().size()); assertEquals(2, version_1.getTextBlocks().size()); assertEquals(2, version_1.getCodeBlocks().size()); List<PostBlockVersion> postBlocks = version_1.getPostBlocks(); assertTrue(postBlocks.get(0) instanceof CodeBlockVersion); assertTrue(postBlocks.get(1) instanceof TextBlockVersion); assertTrue(postBlocks.get(2) instanceof CodeBlockVersion); assertTrue(postBlocks.get(3) instanceof TextBlockVersion); PostVersion version_2 = q_22360443.get(1); assertEquals(5, version_2.getPostBlocks().size()); assertEquals(3, version_2.getTextBlocks().size()); assertEquals(2, version_2.getCodeBlocks().size()); postBlocks = version_2.getPostBlocks(); assertTrue(postBlocks.get(0) instanceof TextBlockVersion); assertTrue(postBlocks.get(1) instanceof CodeBlockVersion); assertTrue(postBlocks.get(2) instanceof TextBlockVersion); assertTrue(postBlocks.get(3) instanceof CodeBlockVersion); assertTrue(postBlocks.get(4) instanceof TextBlockVersion); } @Test void testRootPostBlocksQuestion3758880() { PostVersionList q_3758880 = new PostVersionList(); q_3758880.readFromCSV("testdata", 3758880, 1); assertEquals(11, q_3758880.size()); // TODO: Implement way to test root post block assignment without connection to database } @Test void testStackSnippetCodeBlocksAnswer32143330() { PostVersionList a_32143330 = new PostVersionList(); a_32143330.readFromCSV("testdata", 32143330, 2); assertEquals(4, a_32143330.size()); // and snippet language information blocks (see https://stackoverflow.com/editing-help#syntax-highlighting) // are correctly handled (language info splits code blocks). PostVersion version_4 = a_32143330.get(3); assertEquals(6, version_4.getPostBlocks().size()); assertEquals(3, version_4.getTextBlocks().size()); assertEquals(3, version_4.getCodeBlocks().size()); List<PostBlockVersion> postBlocks = version_4.getPostBlocks(); assertTrue(postBlocks.get(0) instanceof TextBlockVersion); assertTrue(postBlocks.get(1) instanceof CodeBlockVersion); assertTrue(postBlocks.get(2) instanceof TextBlockVersion); assertTrue(postBlocks.get(3) instanceof CodeBlockVersion); assertTrue(postBlocks.get(4) instanceof CodeBlockVersion); assertTrue(postBlocks.get(5) instanceof TextBlockVersion); } @Test void testStackSnippetCodeBlocksAnswer26044128() { PostVersionList a_26044128 = new PostVersionList(); a_26044128.readFromCSV("testdata", 26044128, 2); assertEquals(12, a_26044128.size()); PostVersion version_12 = a_26044128.get(11); assertEquals(8, version_12.getPostBlocks().size()); assertEquals(4, version_12.getTextBlocks().size()); assertEquals(4, version_12.getCodeBlocks().size()); List<PostBlockVersion> postBlocks = version_12.getPostBlocks(); assertTrue(postBlocks.get(0) instanceof TextBlockVersion); assertTrue(postBlocks.get(1) instanceof CodeBlockVersion); assertTrue(postBlocks.get(2) instanceof TextBlockVersion); assertTrue(postBlocks.get(3) instanceof CodeBlockVersion); assertTrue(postBlocks.get(4) instanceof CodeBlockVersion); assertTrue(postBlocks.get(5) instanceof TextBlockVersion); assertTrue(postBlocks.get(6) instanceof CodeBlockVersion); assertTrue(postBlocks.get(7) instanceof TextBlockVersion); // Markdown links } @Test void testAlternativeCodeBlockQuestion32342082() { PostVersionList q_32342082 = new PostVersionList(); q_32342082.readFromCSV("testdata", 32342082, 1); assertEquals(8, q_32342082.size()); PostVersion version_5 = q_32342082.get(4); assertEquals(5, version_5.getPostBlocks().size()); assertEquals(3, version_5.getTextBlocks().size()); assertEquals(2, version_5.getCodeBlocks().size()); List<PostBlockVersion> postBlocks = version_5.getPostBlocks(); assertTrue(postBlocks.get(0) instanceof TextBlockVersion); assertTrue(postBlocks.get(1) instanceof CodeBlockVersion); assertTrue(postBlocks.get(2) instanceof TextBlockVersion); assertTrue(postBlocks.get(3) instanceof CodeBlockVersion); assertTrue(postBlocks.get(4) instanceof TextBlockVersion); } @Test void testCodeTagCodeBlockQuestion19175014() { PostVersionList q_19175014 = new PostVersionList(); q_19175014.readFromCSV("testdata", 19175014, 1); assertEquals(2, q_19175014.size()); PostVersion version_2 = q_19175014.get(1); assertEquals(2, version_2.getPostBlocks().size()); assertEquals(1, version_2.getTextBlocks().size()); assertEquals(1, version_2.getCodeBlocks().size()); List<PostBlockVersion> postBlocks = version_2.getPostBlocks(); assertTrue(postBlocks.get(0) instanceof TextBlockVersion); assertTrue(postBlocks.get(1) instanceof CodeBlockVersion); } @Test void testVersionOrderQuestion3381751() { PostVersionList q_3381751 = new PostVersionList(); q_3381751.readFromCSV("testdata", 3381751, 1); PostVersion previousVersion = q_3381751.get(0); for (int i = 1; i < q_3381751.size(); i++) { PostVersion currentVersion = q_3381751.get(i); assertTrue(currentVersion.getPostHistoryId() > previousVersion.getPostHistoryId()); } } @Test void testScriptTagCodeBlockQuestion3381751() { PostVersionList q_3381751 = new PostVersionList(); q_3381751.readFromCSV("testdata", 3381751, 1); assertEquals(15, q_3381751.size()); PostVersion version_1 = q_3381751.get(0); assertEquals(3, version_1.getPostBlocks().size()); assertEquals(2, version_1.getTextBlocks().size()); assertEquals(1, version_1.getCodeBlocks().size()); List<PostBlockVersion> postBlocks = version_1.getPostBlocks(); assertTrue(postBlocks.get(0) instanceof TextBlockVersion); assertTrue(postBlocks.get(1) instanceof CodeBlockVersion); assertTrue(postBlocks.get(2) instanceof TextBlockVersion); } @Test void testScriptTagInIndentedCodeBlockQuestion28598648() { PostVersionList q_28598648 = new PostVersionList(); q_28598648.readFromCSV("testdata", 28598648, 1); assertEquals(2, q_28598648.size()); PostVersion version_2 = q_28598648.get(1); assertEquals(2, version_2.getPostBlocks().size()); assertEquals(1, version_2.getTextBlocks().size()); assertEquals(1, version_2.getCodeBlocks().size()); List<PostBlockVersion> postBlocks = version_2.getPostBlocks(); assertTrue(postBlocks.get(0) instanceof CodeBlockVersion); assertTrue(postBlocks.get(1) instanceof TextBlockVersion); } @Test void testPredecessorAssignmentAnswer3758880(){ // tests if posts blocks are set more than once as predecessor PostVersionList a_3758880 = new PostVersionList(); a_3758880.readFromCSV("testdata", 3758880, 2, false); TextBlockVersion.similarityMetric = de.unitrier.st.stringsimilarity.set.Variants::twoGramDiceVariant; a_3758880.processVersionHistory(PostVersionList.PostBlockTypeFilter.TEXT); // we consider the most recent version here List<Integer> predecessorList = new LinkedList<>(); List<TextBlockVersion> textBlocks = a_3758880.getLast().getTextBlocks(); for (TextBlockVersion currentTextBlock : textBlocks) { if(currentTextBlock.getPred() != null){ predecessorList.add(currentTextBlock.getPred().getLocalId()); } } // if the list and the set do not have equal size, there exist duplicates (i.e., post blocks with multiple predecessors) Set<Integer> predecessorSet = new HashSet<>(predecessorList); assertTrue(predecessorList.size() == predecessorSet.size()); } @Test void testPredecessorAssignmentQuestion37625877(){ // tests predecessor assignment if two versions have two equal text blocks PostVersionList q_37625877 = new PostVersionList(); q_37625877.readFromCSV("testdata", 37625877, 1, false); TextBlockVersion.similarityMetric = de.unitrier.st.stringsimilarity.set.Variants::twoGramDiceVariant; q_37625877.processVersionHistory(PostVersionList.PostBlockTypeFilter.TEXT); PostVersion version_1 = q_37625877.get(0); PostVersion version_2 = q_37625877.get(1); // both versions have two text blocks with value "or:" at position 2 and 3, which should be linked accordingly assertEquals(version_1.getTextBlocks().get(2).getLocalId(), version_2.getTextBlocks().get(2).getPred().getLocalId()); assertEquals(version_1.getTextBlocks().get(3).getLocalId(), version_2.getTextBlocks().get(3).getPred().getLocalId()); } @Test void testPredecessorAssignmentAnswer42070509(){ // tests predecessor assignment if version i has three code blocks that are equal to four code blocks in version i+1 PostVersionList a_42070509 = new PostVersionList(); a_42070509.readFromCSV("testdata", 42070509, 2, false); a_42070509.processVersionHistory(PostVersionList.PostBlockTypeFilter.CODE); PostVersion version_1 = a_42070509.get(0); PostVersion version_2 = a_42070509.get(1); // code blocks with content "var circle = d3.select("circle");..." are present in both versions assertEquals(version_1.getCodeBlocks().get(0).getLocalId(), version_2.getCodeBlocks().get(0).getPred().getLocalId()); assertEquals(version_1.getCodeBlocks().get(2).getLocalId(), version_2.getCodeBlocks().get(2).getPred().getLocalId()); assertEquals(version_1.getCodeBlocks().get(4).getLocalId(), version_2.getCodeBlocks().get(4).getPred().getLocalId()); // this code block is new in version two and should not have a predecessor assertEquals(null, version_2.getCodeBlocks().get(6).getPred()); } @Test void testPredecessorAssignmentQuestion23459881(){ PostVersionList q_23459881 = new PostVersionList(); q_23459881.readFromCSV("testdata", 23459881, 1, true); PostVersion version_2 = q_23459881.get(1); assertEquals(8, version_2.getPostBlocks().size()); assertEquals(4, version_2.getTextBlocks().size()); assertEquals(4, version_2.getCodeBlocks().size()); List<PostBlockVersion> postBlocks = version_2.getPostBlocks(); assertTrue(postBlocks.get(0) instanceof TextBlockVersion); assertTrue(postBlocks.get(1) instanceof CodeBlockVersion); assertTrue(postBlocks.get(2) instanceof TextBlockVersion); assertTrue(postBlocks.get(3) instanceof CodeBlockVersion); assertTrue(postBlocks.get(4) instanceof TextBlockVersion); assertTrue(postBlocks.get(5) instanceof CodeBlockVersion); assertTrue(postBlocks.get(6) instanceof TextBlockVersion); assertTrue(postBlocks.get(7) instanceof CodeBlockVersion); // version 1: text block with localId 3 and content "Code" // version 2: text block with localId 3 and content "Code" + same content in text block with localId 5 // block 5 is "correct" successor assertNull(postBlocks.get(2).getPred()); // localId 3 assertNull(postBlocks.get(3).getPred()); // localId 4 assertNotNull(postBlocks.get(4).getPred()); // localId 5 assertEquals(new Integer(3), postBlocks.get(4).getPred().getLocalId()); // localId 5 assertNotNull(postBlocks.get(5).getPred()); // localId 6 assertEquals(new Integer(4), postBlocks.get(5).getPred().getLocalId()); // localId 6 assertNotNull(postBlocks.get(6).getPred()); // localId 7 assertEquals(new Integer(5), postBlocks.get(6).getPred().getLocalId()); // localId 7 assertNotNull(postBlocks.get(7).getPred()); // localId 8 assertEquals(new Integer(6), postBlocks.get(7).getPred().getLocalId()); // localId 8 } @Test void testPredecessorAssignmentQuestion36082771(){ PostVersionList q_36082771 = new PostVersionList(); q_36082771.readFromCSV("testdata", 36082771, 1, true); PostVersion version_2 = q_36082771.get(1); assertEquals(12, version_2.getPostBlocks().size()); assertEquals(6, version_2.getTextBlocks().size()); assertEquals(6, version_2.getCodeBlocks().size()); List<PostBlockVersion> postBlocks = version_2.getPostBlocks(); assertTrue(postBlocks.get(0) instanceof TextBlockVersion); assertTrue(postBlocks.get(1) instanceof CodeBlockVersion); assertTrue(postBlocks.get(2) instanceof TextBlockVersion); assertTrue(postBlocks.get(3) instanceof CodeBlockVersion); assertTrue(postBlocks.get(4) instanceof TextBlockVersion); assertTrue(postBlocks.get(5) instanceof CodeBlockVersion); assertTrue(postBlocks.get(6) instanceof TextBlockVersion); assertTrue(postBlocks.get(7) instanceof CodeBlockVersion); assertTrue(postBlocks.get(8) instanceof TextBlockVersion); assertTrue(postBlocks.get(9) instanceof CodeBlockVersion); assertTrue(postBlocks.get(10) instanceof TextBlockVersion); assertTrue(postBlocks.get(11) instanceof CodeBlockVersion); // version 1: code block with localId 2 and content "glaucon@polo..." + same content in code block with localId 6 // version 2: code block with localId 2 and content "glaucon@polo..." // block 2 is "correct" predecessor // version 1: text block with localId 3 and content "If I do then run..." + same content in code block with localId 7 // version 2: code block with localId 3 and content "If I do then run..." // block 3 is "correct" predecessor // version 1: text block with localId 4 and content "glaucon@polo..." + same content in code block with localId 8 // version 2: code block with localId 4 and content "glaucon@polo..." // block 4 is "correct" predecessor assertNotNull(postBlocks.get(1).getPred()); // localId 2 assertEquals(new Integer(2), postBlocks.get(1).getPred().getLocalId()); // localId 2 assertNotNull(postBlocks.get(2).getPred()); // localId 3 assertEquals(new Integer(3), postBlocks.get(2).getPred().getLocalId()); // localId 3 assertNotNull(postBlocks.get(3).getPred()); // localId 4 assertEquals(new Integer(4), postBlocks.get(3).getPred().getLocalId()); // localId 4 } @Test void testPredecessorAssignmentQuestion18276636(){ PostVersionList q_18276636 = new PostVersionList(); q_18276636.readFromCSV("testdata", 18276636, 1, true); PostVersion version_2 = q_18276636.get(1); assertEquals(17, version_2.getPostBlocks().size()); assertEquals(9, version_2.getTextBlocks().size()); assertEquals(8, version_2.getCodeBlocks().size()); List<PostBlockVersion> postBlocks = version_2.getPostBlocks(); assertTrue(postBlocks.get(0) instanceof TextBlockVersion); assertTrue(postBlocks.get(1) instanceof CodeBlockVersion); assertTrue(postBlocks.get(2) instanceof TextBlockVersion); assertTrue(postBlocks.get(3) instanceof CodeBlockVersion); assertTrue(postBlocks.get(4) instanceof TextBlockVersion); assertTrue(postBlocks.get(5) instanceof CodeBlockVersion); assertTrue(postBlocks.get(6) instanceof TextBlockVersion); assertTrue(postBlocks.get(7) instanceof CodeBlockVersion); assertTrue(postBlocks.get(8) instanceof TextBlockVersion); assertTrue(postBlocks.get(9) instanceof CodeBlockVersion); assertTrue(postBlocks.get(10) instanceof TextBlockVersion); assertTrue(postBlocks.get(11) instanceof CodeBlockVersion); assertTrue(postBlocks.get(12) instanceof TextBlockVersion); assertTrue(postBlocks.get(13) instanceof CodeBlockVersion); assertTrue(postBlocks.get(14) instanceof TextBlockVersion); assertTrue(postBlocks.get(15) instanceof CodeBlockVersion); assertTrue(postBlocks.get(16) instanceof TextBlockVersion); // version 1: text block with localId 3 and content "to" // version 2: text block with localId 3 and content "to" + same content in text block with localId 7 // block 7 is "correct" successor (same neighbors) assertNull(postBlocks.get(2).getPred()); // localId 3 assertNotNull(postBlocks.get(5).getPred()); // localId 6 assertEquals(new Integer(2), postBlocks.get(5).getPred().getLocalId()); // localId 6 assertNotNull(postBlocks.get(6).getPred()); // localId 7 assertEquals(new Integer(3), postBlocks.get(6).getPred().getLocalId()); // localId 7 assertNotNull(postBlocks.get(7).getPred()); // localId 8 assertEquals(new Integer(4), postBlocks.get(7).getPred().getLocalId()); // localId 8 } @Test void testBrokenTextBlockQuestion15372744() { PostVersionList q_15372744 = new PostVersionList(); q_15372744.readFromCSV("testdata", 15372744, 1); PostVersion version_1 = q_15372744.get(0); assertEquals(1, version_1.getPostBlocks().size()); assertEquals(1, version_1.getTextBlocks().size()); assertEquals(0, version_1.getCodeBlocks().size()); List<PostBlockVersion> postBlocks = version_1.getPostBlocks(); assertTrue(postBlocks.get(0) instanceof TextBlockVersion); } @Test void testNullPointerException3758880(){ PostVersionList q_3758880 = new PostVersionList(); q_3758880.readFromCSV("testdata", 3758880, 1); q_3758880.processVersionHistory(PostVersionList.PostBlockTypeFilter.CODE); // This causes a null pointer exception because a filter is set. } }
package com.opensymphony.workflow.designer; import java.net.URL; import java.util.*; import javax.swing.*; /** * Central repository for all Actions. * On startup, the application is responsible for registering all actions via the {@link #register(java.lang.String, javax.swing.Action)} * method. Once this is done, any action can be retrieved via the {@link #get(java.lang.String)} method. * The action manager will look for an actions.properties file in the same package, and will read all properties * specified in it for a given action. * <p> * The benefit of specifying actions in the external file is that actions themselves need not be aware of their textual or * graphic representation or key bindings. */ public final class ActionManager { private static final String OS_NAME_STRING = System.getProperty("os.name").replace(' ', '_').toLowerCase(); private static final String SMALL_GRAY_ICON = "smallGrayIcon"; private static final String DISPLAYED_MNEMONIC_INDEX = "mnemonicIndex"; private static final ActionManager INSTANCE = new ActionManager(); private final Map actions; private ResourceBundle bundle; private ActionManager() { this.actions = new HashMap(50); bundle = ResourceBundle.getBundle("com.opensymphony.workflow.designer.actions"); } /** * Register an action. * @param id The action id denotes the set of properties that will be read for the action * @param action The action instance to bind to the specified id. * @return The action, once it has been initialised. If the id is not specified in the * properties file, then null is returned. * @throws NullPointerException if the specified action is null */ public static Action register(String id, Action action) { if(action == null) throw new NullPointerException("Registered actions must not be null."); boolean exists = ActionReader.readAndPutValues(action, INSTANCE.bundle, id); if(!exists) return null; Object oldValue = INSTANCE.actions.put(id, action); if(oldValue != null) System.out.println("WARNING: Duplicate action id: " + id); return action; } /** * Remove a registered action * @param id the action id * @return The removed action, if it existed. */ public static Action deregister(String id) { return (Action)INSTANCE.actions.remove(id); } /** * Get a previously registered action * @param id The action id * @return The action bound to the specified id, or null if no action is bound. */ public static Action get(String id) { Action action = (Action)(INSTANCE.actions.get(id)); if(null == action) { System.out.println("ERROR: No action found for id: " + id); return null; } return action; } public static List getAll(String[] allIDs) { List result = new LinkedList(); for(int i = 0; i < allIDs.length; i++) { Action action = get(allIDs[i]); if(action != null) result.add(action); } return result; } /** * Retrieves and answers the small icon for the given <code>id</code>. */ public static Icon getIcon(String id) { Action action = get(id); if(action == null) return null; return (Icon)action.getValue(Action.SMALL_ICON); } /** * Alias a particular id to another one. * This allows one action to be bound to multiple keys. * @param newKey The new alias to bind to. * @param oldKey The old id to bind to. */ public static void alias(String newKey, String oldKey) { Object oldValue = INSTANCE.actions.put(newKey, INSTANCE.actions.get(oldKey)); if(oldValue != null) System.out.println("WARNING: Duplicate action id: " + newKey); } private static class ActionReader { private static final String LABEL = "label"; private static final char MNEMONIC_MARKER = '&'; private static final String DOT_STRING = "..."; private static final String SHORT_DESCRIPTION = "tooltip"; private static final String LONG_DESCRIPTION = "helptext"; private static final String ICON = "icon"; private static final String GRAY_ICON = ICON + ".gray"; private static final String ACCELERATOR = "accelerator"; private static final String COMMAND = "command"; private String id; private String name; private Integer mnemonic; private Integer aMnemonicIndex; private String shortDescription; private String longDescription; private ImageIcon icon; private ImageIcon grayIcon; private KeyStroke accelerator; private String command; private boolean exists = true; /** * Reads properties for <code>id</code> in <code>bundle</code>. */ static void readValues(ResourceBundle bundle, String id) { new ActionReader(bundle, id); } /** * Reads properties for <code>id</code> in <code>bundle</code> and * sets the approriate values in the given <code>action</code>. */ static boolean readAndPutValues(Action action, ResourceBundle bundle, String id) { ActionReader reader = new ActionReader(bundle, id); if(!reader.actionExists()) return false; reader.putValues(action); return true; } private ActionReader(ResourceBundle bundle, String id) { String iconPath = getString(bundle, id + '.' + ICON, null); if(getString(bundle, id + "." + LABEL, null) == null && iconPath == null) { exists = false; return; } this.id = id; String nameWithMnemonic = getString(bundle, id + "." + LABEL, id); int index = mnemonicIndex(nameWithMnemonic); name = stripName(nameWithMnemonic, index); mnemonic = stripMnemonic(nameWithMnemonic, index); aMnemonicIndex = new Integer(index); shortDescription = getString(bundle, id + '.' + SHORT_DESCRIPTION, defaultShortDescription(name)); longDescription = getString(bundle, id + '.' + LONG_DESCRIPTION, name); URL iconURL = iconPath != null ? getClass().getClassLoader().getResource(iconPath) : null; if(iconURL == null && iconPath != null) { System.out.println("WARNING Invalid icon " + iconPath + " specified in actions.properties for action '" + name + "'"); icon = null; } else { icon = (iconPath == null) ? null : new ImageIcon(iconURL); } String grayIconPath = getString(bundle, id + '.' + GRAY_ICON, null); grayIcon = (grayIconPath == null) ? null : new ImageIcon(getClass().getClassLoader().getResource(grayIconPath)); String shortcut = getString(bundle, id + '.' + ACCELERATOR + '.' + OS_NAME_STRING, null); if(shortcut == null) { shortcut = getString(bundle, id + '.' + ACCELERATOR, null); } accelerator = getKeyStroke(shortcut); command = getString(bundle, id + '.' + COMMAND, null); } public boolean actionExists() { return exists; } /** * Put the ActionReader's properties as values in the Action. */ private void putValues(Action action) { action.putValue(Action.NAME, name); action.putValue(Action.SHORT_DESCRIPTION, shortDescription); action.putValue(Action.LONG_DESCRIPTION, longDescription); if(icon != null) action.putValue(Action.SMALL_ICON, icon); if(grayIcon != null) action.putValue(ActionManager.SMALL_GRAY_ICON, grayIcon); if(accelerator != null) action.putValue(Action.ACCELERATOR_KEY, accelerator); if(mnemonic != null) action.putValue(Action.MNEMONIC_KEY, mnemonic); if(command != null) action.putValue(Action.ACTION_COMMAND_KEY, command); action.putValue(ActionManager.DISPLAYED_MNEMONIC_INDEX, aMnemonicIndex); } private int mnemonicIndex(String nameWithMnemonic) { return nameWithMnemonic.indexOf(MNEMONIC_MARKER); } private String stripName(String nameWithMnemonic, int mnemonicIndex) { return mnemonicIndex == -1 ? nameWithMnemonic : nameWithMnemonic.substring(0, mnemonicIndex) + nameWithMnemonic.substring(mnemonicIndex + 1); } private Integer stripMnemonic(String nameWithMnemonic, int mnemonicIndex) { return mnemonicIndex == -1 ? null : new Integer(nameWithMnemonic.charAt(mnemonicIndex + 1)); } private String defaultShortDescription(String nameWithDots) { return nameWithDots.endsWith(DOT_STRING) ? (nameWithDots.substring(0, nameWithDots.length() - DOT_STRING.length())) : nameWithDots; } private KeyStroke getKeyStroke(String accelerator) { if(accelerator == null) { return null; } else { KeyStroke keyStroke = KeyStroke.getKeyStroke(accelerator); if(keyStroke == null) System.out.println("WARNING: Action " + id + " has an invalid accelerator " + accelerator); return keyStroke; } } private String getString(ResourceBundle bundle, String key, String defaultString) { try { return bundle.getString(key); } catch(MissingResourceException e) { return defaultString; } } } }
package com.opensymphony.workflow.designer; import java.util.*; import java.util.List; import java.awt.*; import java.awt.event.MouseEvent; import javax.swing.*; import org.jgraph.JGraph; import org.jgraph.graph.*; import com.opensymphony.workflow.loader.*; import com.opensymphony.workflow.designer.layout.SugiyamaLayoutAlgorithm; import com.opensymphony.workflow.designer.layout.LayoutAlgorithm; import com.opensymphony.workflow.designer.views.*; import com.opensymphony.workflow.designer.actions.CreateInitialAction; public class WorkflowGraph extends JGraph { private Layout layout = new Layout(); private WorkflowDescriptor descriptor; private JPopupMenu menu; public WorkflowGraph(GraphModel model, WorkflowDescriptor descriptor, Layout layout, boolean doAutoLayout) { super(model); ToolTipManager.sharedInstance().registerComponent(this); this.layout = layout; if(descriptor != null) { this.descriptor = descriptor; addInitialActions(); addSteps(); addSplits(); addJoins(); getWorkflowGraphModel().insertResultConnections(); } if(doAutoLayout) { autoLayout(); } setSelectNewCells(true); //setGridEnabled(true); //setGridSize(6); //setTolerance(2); setMarqueeHandler(new WorkflowMarqueeHandler()); setCloneable(false); setPortsVisible(true); menu = new JPopupMenu(); JMenu n = new JMenu("New"); menu.add(n); n.add(new CreateInitialAction(this)); } protected PortView createPortView(Object object, CellMapper mapper) { return new CustomPortView(object, this, mapper); } public class WorkflowMarqueeHandler extends BasicMarqueeHandler { // Holds the Start and the Current Point protected Point start, current; // Holds the First and the Current Port protected PortView port, firstPort; // Override to Gain Control (for PopupMenu and ConnectMode) public boolean isForceMarqueeEvent(MouseEvent e) { // If Right Mouse Button we want to Display the PopupMenu if(SwingUtilities.isRightMouseButton(e)) // Return Immediately return true; // Find and Remember Port port = getSourcePortAt(e.getPoint()); // If Port Found and in ConnectMode (=Ports Visible) if(port != null && isPortsVisible()) return true; // Else Call Superclass return super.isForceMarqueeEvent(e); } // Use Xor-Mode on Graphics to Paint Connector protected void paintConnector(Color fg, Color bg, Graphics g) { // Set Foreground g.setColor(fg); // Set Xor-Mode Color g.setXORMode(bg); // Highlight the Current Port paintPort(getGraphics()); // If Valid First Port, Start and Current Point if(firstPort != null && start != null && current != null) // Then Draw A Line From Start to Current Point g.drawLine(start.x, start.y, current.x, current.y); } // Use the Preview Flag to Draw a Highlighted Port protected void paintPort(Graphics g) { // If Current Port is Valid if(port != null) { // If Not Floating Port... boolean o = (GraphConstants.getOffset(port.getAttributes()) != null); // ...Then use Parent's Bounds Rectangle r = (o) ? port.getBounds() : port.getParentView().getBounds(); // Scale from Model to Screen r = toScreen(new Rectangle(r)); // Add Space For the Highlight Border r.setBounds(r.x - 3, r.y - 3, r.width + 6, r.height + 6); // Paint Port in Preview (=Highlight) Mode getUI().paintCell(g, port, r, true); } } public PortView getSourcePortAt(Point point) { // Scale from Screen to Model Point tmp = fromScreen(new Point(point)); // Find a Port View in Model Coordinates and Remember return getPortViewAt(tmp.x, tmp.y); } // Find a Cell at point and Return its first Port as a PortView protected PortView getTargetPortAt(Point point) { // Find Cell at point (No scaling needed here) Object cell = getFirstCellForLocation(point.x, point.y); // Loop Children to find PortView for(int i = 0; i < getModel().getChildCount(cell); i++) { // Get Child from Model Object tmp = getModel().getChild(cell, i); // Get View for Child using the Graph's View as a Cell Mapper tmp = getGraphLayoutCache().getMapping(tmp, false); // If Child View is a Port View and not equal to First Port if(tmp instanceof PortView && tmp != firstPort) // Return as PortView return (PortView)tmp; } // No Port View found return getSourcePortAt(point); } // Display PopupMenu or Remember Start Location and First Port public void mousePressed(final MouseEvent e) { // If Right Mouse Button if(SwingUtilities.isRightMouseButton(e)) { // Scale From Screen to Model //Point loc = fromScreen(e.getPoint()); // Find Cell in Model Coordinates //Object cell = getFirstCellForLocation(loc.x, loc.y); // Create PopupMenu for the Cell menu.show(WorkflowGraph.this, e.getX(), e.getY()); // JPopupMenu menu = createPopupMenu(e.getPoint(), cell); // menu.show(graph, e.getX(), e.getY()); // Else if in ConnectMode and Remembered Port is Valid } else if(port != null && !e.isConsumed() && isPortsVisible()) { // Remember Start Location start = toScreen(port.getLocation(null)); // Remember First Port firstPort = port; // Consume Event e.consume(); } else // Call Superclass super.mousePressed(e); } // Find Port under Mouse and Repaint Connector public void mouseDragged(MouseEvent e) { // If remembered Start Point is Valid if(start != null && !e.isConsumed()) { // Fetch Graphics from Graph Graphics g = getGraphics(); // Xor-Paint the old Connector (Hide old Connector) paintConnector(Color.black, getBackground(), g); // Reset Remembered Port PortView newPort = getTargetPortAt(e.getPoint()); if(port!=newPort && port!=null) { paintPort(g); } port = newPort; // If Port was found then Point to Port Location if(port != null) current = toScreen(port.getLocation(null)); // Else If no Port was found then Point to Mouse Location else current = snap(e.getPoint()); // Xor-Paint the new Connector paintConnector(getBackground(), Color.black, g); // Consume Event e.consume(); } // Call Superclass super.mouseDragged(e); } // Connect the First Port and the Current Port in the Graph or Repaint public void mouseReleased(MouseEvent e) { // If Valid Event, Current and First Port if(e != null && !e.isConsumed() && port != null && firstPort != null && firstPort != port) { // Then Establish Connection WorkflowCell source = (WorkflowCell)((WorkflowPort)firstPort.getCell()).getParent(); WorkflowCell target = (WorkflowCell)((WorkflowPort)port.getCell()).getParent(); System.out.println("connect " + source + "->" + target); // connect((Port) firstPort.getCell(), (Port) port.getCell()); // Consume Event e.consume(); // Else Repaint the Graph } repaint(); // Reset Global Vars firstPort = port = null; start = current = null; // Call Superclass super.mouseReleased(e); } // Show Special Cursor if Over Port public void mouseMoved(MouseEvent e) { // Check Mode and Find Port if(e != null && getSourcePortAt(e.getPoint()) != null && !e.isConsumed()) { // Set Cusor on Graph (Automatically Reset) setCursor(new Cursor(Cursor.HAND_CURSOR)); // Consume Event e.consume(); } // Call Superclass super.mouseReleased(e); } } public void autoLayout() { if(descriptor.getSteps().size() > 0) { LayoutAlgorithm algo = new SugiyamaLayoutAlgorithm(); Properties p = new Properties(); p.put(SugiyamaLayoutAlgorithm.KEY_HORIZONTAL_SPACING, "110"); p.put(SugiyamaLayoutAlgorithm.KEY_VERTICAL_SPACING, "70"); algo.perform(this, true, p); } } public void addInitialActions() { List initialActionList = descriptor.getInitialActions(); addInitialActionView(initialActionList); } private void addInitialActionView(List initialActionList) { InitialActionCell initialActionCell = new InitialActionCell("Start"); // Create Vertex Attributes if(layout != null) { Rectangle bounds = layout.getBounds(initialActionCell.toString()); if(bounds != null) { GraphConstants.setBounds(initialActionCell.getAttributes(), bounds); } } getWorkflowGraphModel().insertInitialActions(initialActionList, initialActionCell, null, null, null); } public void addSteps() { List stepsList = descriptor.getSteps(); for(int i = 0; i < stepsList.size(); i++) { StepDescriptor step = (StepDescriptor)stepsList.get(i); addStepView(step); } } public void addSplits() { List splitsList = descriptor.getSplits(); for(int i = 0; i < splitsList.size(); i++) { SplitDescriptor split = (SplitDescriptor)splitsList.get(i); addSplitView(split); } } public void addJoins() { List joinsList = descriptor.getJoins(); for(int i = 0; i < joinsList.size(); i++) { JoinDescriptor join = (JoinDescriptor)joinsList.get(i); addJoinView(join); } } private void addJoinView(JoinDescriptor descriptor) { JoinCell join = new JoinCell(descriptor); // Create Vertex Attributes if(layout != null) { Rectangle bounds = layout.getBounds(join.toString()); if(bounds != null) join.getAttributes().put(GraphConstants.BOUNDS, bounds); } getWorkflowGraphModel().insertJoinCell(join, null, null, null); } private void addSplitView(SplitDescriptor descriptor) { SplitCell split = new SplitCell(descriptor); if(layout != null) { Rectangle bounds = layout.getBounds(split.toString()); if(bounds != null) split.getAttributes().put(GraphConstants.BOUNDS, bounds); } getWorkflowGraphModel().insertSplitCell(split, null, null, null); } private void addStepView(StepDescriptor descriptor) { StepCell step = new StepCell(descriptor); if(layout != null) { Rectangle bounds = layout.getBounds(step.toString()); if(bounds != null) step.getAttributes().put(GraphConstants.BOUNDS, bounds); } // Insert into Model getWorkflowGraphModel().insertStepCell(step, null, null, null); } private WorkflowGraphModel getWorkflowGraphModel() { return (WorkflowGraphModel)getModel(); } /** * Overriding method as required by JGraph API, * In order to return right View object corresponding to Cell. */ protected VertexView createVertexView(Object v, CellMapper cm) { if(v instanceof StepCell) return new StepView(v, this, cm); if(v instanceof SplitCell) return new SplitView(v, this, cm); if(v instanceof JoinCell) return new JoinView(v, this, cm); if(v instanceof InitialActionCell) return new InitialActionView(v, this, cm); // Else Call Superclass return super.createVertexView(v, cm); } public void addStepCell(StepCell step) { if(layout != null) { Rectangle bounds = layout.getBounds(step.toString()); if(bounds != null) { step.getAttributes().put(GraphConstants.BOUNDS, bounds); } } getWorkflowGraphModel().insertStep(step, null, null, null); } public void addSplitCell(SplitCell split) { if(layout != null) { Rectangle bounds = layout.getBounds(split.toString()); if(bounds != null) { split.getAttributes().put(GraphConstants.BOUNDS, bounds); } } getWorkflowGraphModel().insertSplit(split, null, null, null); } public void addJoinCell(JoinCell join) { if(layout != null) { Rectangle bounds = layout.getBounds(join.toString()); if(bounds != null) { join.getAttributes().put(GraphConstants.BOUNDS, bounds); } } getWorkflowGraphModel().insertJoin(join, null, null, null); } public void addInitialActionsCell(InitialActionCell initialActionCell) { if(layout != null) { Rectangle bounds = layout.getBounds(initialActionCell.toString()); if(bounds != null) { initialActionCell.getAttributes().put(GraphConstants.BOUNDS, bounds); } } getWorkflowGraphModel().insertInitialActions(null, initialActionCell, null, null, null); } }
package dr.app.beagle.tools.parsers; import dr.app.beagle.evomodel.sitemodel.BranchSubstitutionModel; import dr.app.beagle.evomodel.sitemodel.GammaSiteRateModel; import dr.app.beagle.evomodel.substmodel.FrequencyModel; import dr.app.beagle.tools.BeagleSequenceSimulator; import dr.evolution.alignment.Alignment; import dr.evolution.sequence.Sequence; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.branchratemodel.DefaultBranchRateModel; import dr.evomodel.tree.TreeModel; import dr.xml.AbstractXMLObjectParser; import dr.xml.AttributeRule; import dr.xml.ElementRule; import dr.xml.XMLObject; import dr.xml.XMLParseException; import dr.xml.XMLSyntaxRule; public class BeagleSequenceSimulatorParser extends AbstractXMLObjectParser { public static final String BEAGLE_SEQUENCE_SIMULATOR = "beagleSequenceSimulator"; public static final String SEQUENCE_LENGTH = "sequenceLength"; private XMLSyntaxRule[] rules = new XMLSyntaxRule[] { new ElementRule(TreeModel.class), new ElementRule(BranchSubstitutionModel.class, true), new ElementRule(GammaSiteRateModel.class), new ElementRule(BranchRateModel.class), new ElementRule(FrequencyModel.class), new ElementRule(Sequence.class, true), AttributeRule.newIntegerRule(SEQUENCE_LENGTH) }; @Override public String getParserName() { return BEAGLE_SEQUENCE_SIMULATOR; } @Override public String getParserDescription() { return "Beagle sequence simulator"; } @Override public Class<Alignment> getReturnType() { return Alignment.class; } @Override public XMLSyntaxRule[] getSyntaxRules() { return rules; } @Override public Object parseXMLObject(XMLObject xo) throws XMLParseException { TreeModel tree = (TreeModel) xo.getChild(TreeModel.class); GammaSiteRateModel siteModel = (GammaSiteRateModel) xo.getChild(GammaSiteRateModel.class); BranchRateModel rateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); FrequencyModel freqModel = (FrequencyModel) xo.getChild(FrequencyModel.class); Sequence ancestralSequence = (Sequence) xo.getChild(Sequence.class); int sequenceLength = xo.getIntegerAttribute(SEQUENCE_LENGTH); //TODO from siteModel BranchSubstitutionModel substitutionModel = (BranchSubstitutionModel) xo.getChild(BranchSubstitutionModel.class); if (rateModel == null) { rateModel = new DefaultBranchRateModel(); } BeagleSequenceSimulator s = new BeagleSequenceSimulator(tree, // substitutionModel, // siteModel, rateModel, freqModel, sequenceLength ); if (ancestralSequence != null) { s.setAncestralSequence(ancestralSequence); } return s.simulate(); }// END: parseXMLObject }// END: class
package dr.inference.distribution; import dr.util.Attribute; import java.awt.geom.Point2D; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; /** * A class that returns the log likelihood of a set of data (statistics) * being distributed according to a distribution generated empirically from some data. * * @author Andrew Rambaut * @author Marc Suchard * @version $Id:$ */ public abstract class EmpiricalDistributionLikelihood extends AbstractDistributionLikelihood { public static final String EMPIRICAL_DISTRIBUTION_LIKELIHOOD = "empiricalDistributionLikelihood"; private static final double MIN_DENSITY_PROPORTION = 1E-2; private static final boolean DEBUG = false; private int from = -1; private int to = Integer.MAX_VALUE; private double offset = 0; private double lower = Double.NEGATIVE_INFINITY; private double upper = Double.POSITIVE_INFINITY; public EmpiricalDistributionLikelihood(String fileName, boolean inverse, boolean byColumn) { super(null); this.fileName = fileName; if (byColumn) readFileByColumn(fileName); else readFileByRow(fileName); this.inverse = inverse; } public void setBounds(double lower, double upper) { this.lower = lower; this.upper = upper; } class ComparablePoint2D extends Point2D.Double implements Comparable<ComparablePoint2D> { ComparablePoint2D(double x, double y) { super(x,y); } public int compareTo(ComparablePoint2D pt0) { if (getX() > pt0.getX()) return 1; if (getX() == pt0.getX()) return 0; return -1; } } protected void readFileByRow(String fileName) { try { BufferedReader reader = new BufferedReader(new FileReader(fileName)); List<ComparablePoint2D> ptList = new ArrayList<ComparablePoint2D>(); String line; while ((line = reader.readLine()) != null) { if (line.charAt(0) != ' StringTokenizer st = new StringTokenizer(line); try { double value = Double.valueOf(st.nextToken()); double density = Double.valueOf(st.nextToken()); ptList.add(new ComparablePoint2D(value,density)); } catch (Exception e) { System.err.println("Error parsing line: '"+line+"' in "+fileName); System.exit(-1); } } } Collections.sort(ptList); // Prune off begining and ending zeros while( (ptList.get(0).getY() == 0) && (ptList.get(1).getY() == 0) ) ptList.remove(0); while( (ptList.get(ptList.size()-1).getY() == 0) && (ptList.get(ptList.size()-2).getY() == 0) ) ptList.remove(ptList.size()-1); // Find min density double minDensity = Double.POSITIVE_INFINITY; for(ComparablePoint2D pt : ptList) { if (pt.getY() > 0.0 && pt.getY() < minDensity) minDensity = pt.getY(); } // Set zeros in the middle to 1/100th of minDensity for(ComparablePoint2D pt : ptList) { if (pt.getY() == 0) pt.y = minDensity * MIN_DENSITY_PROPORTION; } values = new double[ptList.size()]; density = new double[ptList.size()]; double total = 0.0; for(int i=0; i<ptList.size(); i++) { ComparablePoint2D pt = ptList.get(i); values[i] = pt.getX(); density[i] = pt.getY(); total += pt.getY(); } for (int i = 0; i < density.length; ++i) { density[i] /= total; } reader.close(); if (DEBUG) { System.err.println("EDL File : "+fileName); System.err.println("Min value: "+values[0]); System.err.println("Max value: "+values[values.length-1]); } } catch (FileNotFoundException e) { System.err.println("File not found: "+fileName); System.exit(-1); } catch (IOException e) { System.err.println("IO exception reading: "+fileName); System.exit(-1); } } protected void readFileByColumn(String fileName) { try { BufferedReader reader = new BufferedReader(new FileReader(fileName)); String line1 = reader.readLine(); StringTokenizer st = new StringTokenizer(line1," "); values = new double[st.countTokens()]; for(int i=0; i<values.length; i++) values[i] = Double.valueOf(st.nextToken()); String line2 = reader.readLine(); st = new StringTokenizer(line2," "); density = new double[st.countTokens()]; for(int i=0; i<density.length; i++) density[i] = Double.valueOf(st.nextToken()); reader.close(); } catch (FileNotFoundException e) { System.err.println("File not found: "+fileName); System.exit(-1); } catch (IOException e) { System.err.println("IO exception reading: "+fileName); System.exit(-1); } } public void setOffset(double offset) { this.offset = offset; } public void setRange(int from, int to) { this.from = from; this.to = to; } // Likelihood IMPLEMENTATION /** * Calculate the log likelihood of the current state. * * @return the log likelihood. */ public double calculateLogLikelihood() { double logL = 0.0; for (Attribute<double[]> data : dataList) { // see comment in DistributionLikelihood final double[] attributeValue = data.getAttributeValue(); for (int j = Math.max(0, from); j < Math.min(attributeValue.length, to); j++) { double value = attributeValue[j] + offset; if (value > lower && value < upper) { logL += logPDF(value); } else { return Double.NEGATIVE_INFINITY; } if (DEBUG) { if (Double.isInfinite(logL)) { System.err.println("Infinite log density in "+ (getId() != null ? getId() : fileName) ); System.err.println("Evaluated at "+value); System.err.println("Min: " + values[0] + " Max: " + values[values.length - 1]); } } } } return logL; } abstract protected double logPDF(double value); protected double[] values; protected double[] density; protected boolean inverse; protected String fileName; }
package edu.wpi.first.wpilibj.templates.subsystems; import com.sun.squawk.util.MathUtils; import edu.wpi.first.wpilibj.Gyro; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.templates.RobotMap; import edu.wpi.first.wpilibj.templates.commands.placment.CalculatePlace; /** * * @author ThinkRedstone */ public class PlacmentSystem extends Subsystem { // Put methods for controlling this subsystem // here. Call these from Commands. private Gyro gyro; private double x, y; private long startingTime; public PlacmentSystem(Gyro gyro) { this.gyro = gyro; reset(); } public PlacmentSystem(int gyroPort) { this(new Gyro(gyroPort)); } public double getAngle() { return gyro.getAngle() - (System.currentTimeMillis() - startingTime) * RobotMap.GYTO_MISTAKE_PER_MILISECOND; } public double getX() { return x; } public void addToX(double x) { this.x += x; } public double getY() { return y; } public void addToY(double y) { this.y += y; } public void reset() { x = 0; y = 0; gyro.reset(); startingTime = System.currentTimeMillis(); } public double getDistanceToCord(double x, double y) { return Math.sqrt(MathUtils.pow((y - getY()), 2) + MathUtils.pow(x - getX(), 2)); } public void initDefaultCommand() { // Set the default command for a subsystem here. setDefaultCommand(new CalculatePlace()); } }
package it.unibz.krdb.obda.protege4.core; import it.unibz.krdb.obda.io.ModelIOManager; import it.unibz.krdb.obda.io.PrefixManager; import it.unibz.krdb.obda.io.QueryIOManager; import it.unibz.krdb.obda.model.OBDADataFactory; import it.unibz.krdb.obda.model.OBDADataSource; import it.unibz.krdb.obda.model.OBDAException; import it.unibz.krdb.obda.model.OBDAMappingAxiom; import it.unibz.krdb.obda.model.OBDAMappingListener; import it.unibz.krdb.obda.model.OBDAModel; import it.unibz.krdb.obda.model.OBDAModelListener; import it.unibz.krdb.obda.model.Predicate; import it.unibz.krdb.obda.model.impl.OBDADataFactoryImpl; import it.unibz.krdb.obda.owlapi3.OBDAModelValidator; import it.unibz.krdb.obda.owlapi3.OWLAPI3Translator; import it.unibz.krdb.obda.owlrefplatform.core.QuestPreferences; import it.unibz.krdb.obda.protege4.utils.DialogUtils; import it.unibz.krdb.obda.querymanager.QueryController; import it.unibz.krdb.obda.querymanager.QueryControllerEntity; import it.unibz.krdb.obda.querymanager.QueryControllerGroup; import it.unibz.krdb.obda.querymanager.QueryControllerListener; import it.unibz.krdb.obda.querymanager.QueryControllerQuery; import it.unibz.krdb.sql.JDBCConnectionManager; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.protege.editor.core.Disposable; import org.protege.editor.core.editorkit.EditorKit; import org.protege.editor.owl.OWLEditorKit; import org.protege.editor.owl.model.OWLModelManager; import org.protege.editor.owl.model.event.EventType; import org.protege.editor.owl.model.event.OWLModelManagerChangeEvent; import org.protege.editor.owl.model.event.OWLModelManagerListener; import org.protege.editor.owl.model.inference.ProtegeOWLReasonerInfo; import org.protege.editor.owl.ui.prefix.PrefixUtilities; import org.semanticweb.owlapi.model.AddAxiom; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLDataProperty; import org.semanticweb.owlapi.model.OWLDeclarationAxiom; import org.semanticweb.owlapi.model.OWLEntity; import org.semanticweb.owlapi.model.OWLException; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyChange; import org.semanticweb.owlapi.model.OWLOntologyChangeListener; import org.semanticweb.owlapi.model.OWLOntologyID; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.model.RemoveAxiom; import org.semanticweb.owlapi.model.SetOntologyID; import org.semanticweb.owlapi.vocab.PrefixOWLOntologyFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OBDAModelManager implements Disposable { private static final String OBDA_EXT = "obda"; // The default OBDA file extension. private static final String QUERY_EXT = "q"; // The default query file extension. private OWLEditorKit owlEditorKit; private OWLOntologyManager mmgr; private QueryController queryController; private Map<URI, OBDAModel> obdamodels; private List<OBDAModelManagerListener> obdaManagerListeners; private JDBCConnectionManager connectionManager = JDBCConnectionManager.getJDBCConnectionManager(); private static OBDADataFactory dfac = OBDADataFactoryImpl.getInstance(); private static Logger log = LoggerFactory.getLogger(OBDAModelManager.class); /*** * This is the instance responsible for listening for Protege ontology * events (loading/saving/changing ontology) */ private final OWLModelManagerListener modelManagerListener = new OBDAPLuginOWLModelManagerListener(); private ProtegeQueryControllerListener qlistener = new ProtegeQueryControllerListener(); private ProtegeMappingControllerListener mlistener = new ProtegeMappingControllerListener(); private ProtegeDatasourcesControllerListener dlistener = new ProtegeDatasourcesControllerListener(); /*** * This flag is used to avoid triggering a "Ontology Changed" event when new * mappings/sources/queries are inserted into the model not by the user, but * by a ontology load call. */ private boolean loadingData; public OBDAModelManager(EditorKit editorKit) { super(); if (!(editorKit instanceof OWLEditorKit)) { throw new IllegalArgumentException("The OBDA PLugin only works with OWLEditorKit instances."); } this.owlEditorKit = (OWLEditorKit) editorKit; mmgr = ((OWLModelManager) owlEditorKit.getModelManager()).getOWLOntologyManager(); OWLModelManager owlmmgr = (OWLModelManager) editorKit.getModelManager(); owlmmgr.addListener(modelManagerListener); obdaManagerListeners = new LinkedList<OBDAModelManagerListener>(); obdamodels = new HashMap<URI, OBDAModel>(); // Adding ontology change listeners to synchronize with the mappings mmgr.addOntologyChangeListener(new OntologyRefactoringListener()); // Initialize the query controller queryController = new QueryController(); // Printing the version information to the console // System.out.println("Using " + VersionInfo.getVersionInfo().toString() + "\n"); } /*** * This ontology change listener has some euristics that determine if the * user is refactoring his ontology. In particular, this listener will try * to determine if some add/remove axioms are in fact a "renaming" * operation. This happens when a list of axioms has a * remove(DeclarationAxiom(x)) immediatly followed by an * add(DeclarationAxiom(y)), in this case, y is a renaming for x. */ public class OntologyRefactoringListener implements OWLOntologyChangeListener { OWLAPI3Translator translator = new OWLAPI3Translator(); @Override public void ontologiesChanged(List<? extends OWLOntologyChange> changes) throws OWLException { Map<OWLEntity, OWLEntity> renamings = new HashMap<OWLEntity, OWLEntity>(); Set<OWLEntity> removals = new HashSet<OWLEntity>(); for (int idx = 0; idx < changes.size(); idx++) { OWLOntologyChange change = changes.get(idx); if (change instanceof SetOntologyID) { IRI newiri = ((SetOntologyID) change).getNewOntologyID().getOntologyIRI(); IRI oldiri = ((SetOntologyID) change).getOriginalOntologyID().getOntologyIRI(); log.debug("Ontology ID changed"); log.debug("Old ID: {}", oldiri); log.debug("New ID: {}", newiri); OBDAModel model = obdamodels.get(oldiri.toURI()); if (model == null) { setupNewOBDAModel(); model = getActiveOBDAModel(); } PrefixManager prefixManager = model.getPrefixManager(); prefixManager.addPrefix(PrefixManager.DEFAULT_PREFIX, newiri.toURI().toString()); obdamodels.remove(oldiri.toURI()); obdamodels.put(newiri.toURI(), model); continue; } else if (change instanceof AddAxiom) { OWLAxiom axiom = change.getAxiom(); if (axiom instanceof OWLDeclarationAxiom) { OWLEntity entity = ((OWLDeclarationAxiom) axiom).getEntity(); OBDAModel activeOBDAModel = getActiveOBDAModel(); if (entity instanceof OWLClass) { OWLClass oc = (OWLClass) entity; Predicate c = dfac.getClassPredicate(oc.getIRI().toString()); activeOBDAModel.declareClass(c); } else if (entity instanceof OWLObjectProperty) { OWLObjectProperty or = (OWLObjectProperty) entity; Predicate r = dfac.getObjectPropertyPredicate(or.getIRI().toString()); activeOBDAModel.declareObjectProperty(r); } else if (entity instanceof OWLDataProperty) { OWLDataProperty op = (OWLDataProperty) entity; Predicate p = dfac.getDataPropertyPredicate(op.getIRI().toString()); activeOBDAModel.declareDataProperty(p); } } } else if (change instanceof RemoveAxiom) { OWLAxiom axiom = change.getAxiom(); if (axiom instanceof OWLDeclarationAxiom) { OWLEntity entity = ((OWLDeclarationAxiom) axiom).getEntity(); OBDAModel activeOBDAModel = getActiveOBDAModel(); if (entity instanceof OWLClass) { OWLClass oc = (OWLClass) entity; Predicate c = dfac.getClassPredicate(oc.getIRI().toString()); activeOBDAModel.unDeclareClass(c); } else if (entity instanceof OWLObjectProperty) { OWLObjectProperty or = (OWLObjectProperty) entity; Predicate r = dfac.getObjectPropertyPredicate(or.getIRI().toString()); activeOBDAModel.unDeclareObjectProperty(r); } else if (entity instanceof OWLDataProperty) { OWLDataProperty op = (OWLDataProperty) entity; Predicate p = dfac.getDataPropertyPredicate(op.getIRI().toString()); activeOBDAModel.unDeclareDataProperty(p); } } } if (idx + 1 >= changes.size()) { continue; } if (change instanceof RemoveAxiom && changes.get(idx + 1) instanceof AddAxiom) { // Found the pattern of a renaming refactoring RemoveAxiom remove = (RemoveAxiom) change; AddAxiom add = (AddAxiom) changes.get(idx + 1); if (!(remove.getAxiom() instanceof OWLDeclarationAxiom && add.getAxiom() instanceof OWLDeclarationAxiom)) { continue; } // Found the patter we are looking for, a remove and add of // declaration axioms OWLEntity olde = ((OWLDeclarationAxiom) remove.getAxiom()).getEntity(); OWLEntity newe = ((OWLDeclarationAxiom) add.getAxiom()).getEntity(); renamings.put(olde, newe); } else if (change instanceof RemoveAxiom && ((RemoveAxiom) change).getAxiom() instanceof OWLDeclarationAxiom) { // Found the pattern of a deletion OWLDeclarationAxiom declaration = (OWLDeclarationAxiom) ((RemoveAxiom) change).getAxiom(); OWLEntity removedEntity = declaration.getEntity(); removals.add(removedEntity); } } // Applying the renaming to the OBDA model OBDAModel obdamodel = getActiveOBDAModel(); for (OWLEntity olde : renamings.keySet()) { OWLEntity removedEntity = olde; OWLEntity newEntity = renamings.get(removedEntity); // This set of changes appears to be a "renaming" operation, // hence we will modify the OBDA model accordingly Predicate removedPredicate = translator.getPredicate(removedEntity); Predicate newPredicate = translator.getPredicate(newEntity); obdamodel.renamePredicate(removedPredicate, newPredicate); } // Applying the deletions to the obda model for (OWLEntity removede : removals) { Predicate removedPredicate = translator.getPredicate(removede); obdamodel.deletePredicate(removedPredicate); } } } public void addListener(OBDAModelManagerListener listener) { obdaManagerListeners.add(listener); } public void removeListener(OBDAModelManagerListener listener) { obdaManagerListeners.remove(listener); } public OBDAModel getActiveOBDAModel() { OWLOntology ontology = owlEditorKit.getOWLModelManager().getActiveOntology(); if (ontology != null) { OWLOntologyID ontologyID = ontology.getOntologyID(); IRI ontologyIRI = ontologyID.getOntologyIRI(); URI uri = null; if (ontologyIRI != null) { uri = ontologyIRI.toURI(); } else { uri = URI.create(ontologyID.toString()); } return obdamodels.get(uri); } return null; } /** * This method makes sure is used to setup a new/fresh OBDA model. This is * done by replacing the instance this.obdacontroller (the OBDA model) with * a new object. On creation listeners for the datasources, mappings and * queries are setup so that changes in these trigger and ontology change. * * Additionally, this method configures all available OBDAOWLReasonerFacotry * objects to have a reference to the newly created OBDA model and to the * global preference object. This is necessary so that the factories are * able to pass the OBDA model to the reasoner instances when they are * created. */ private void setupNewOBDAModel() { OBDAModel activeOBDAModel = getActiveOBDAModel(); if (activeOBDAModel != null) { return; } activeOBDAModel = dfac.getOBDAModel(); activeOBDAModel.addSourcesListener(dlistener); activeOBDAModel.addMappingsListener(mlistener); queryController.addListener(qlistener); OWLModelManager mmgr = owlEditorKit.getOWLWorkspace().getOWLModelManager(); Set<OWLOntology> ontologies = mmgr.getOntologies(); for (OWLOntology ontology : ontologies) { // Setup the entity declarations for (OWLClass c : ontology.getClassesInSignature()) { Predicate pred = dfac.getClassPredicate(c.getIRI().toString()); activeOBDAModel.declareClass(pred); } for (OWLObjectProperty r : ontology.getObjectPropertiesInSignature()) { Predicate pred = dfac.getObjectPropertyPredicate(r.getIRI().toString()); activeOBDAModel.declareObjectProperty(pred); } for (OWLDataProperty p : ontology.getDataPropertiesInSignature()) { Predicate pred = dfac.getDataPropertyPredicate(p.getIRI().toString()); activeOBDAModel.declareDataProperty(pred); } } // Setup the prefixes PrefixOWLOntologyFormat prefixManager = PrefixUtilities.getPrefixOWLOntologyFormat(mmgr.getActiveOntology()); // addOBDACommonPrefixes(prefixManager); PrefixManagerWrapper prefixwrapper = new PrefixManagerWrapper(prefixManager); activeOBDAModel.setPrefixManager(prefixwrapper); OWLOntology activeOntology = mmgr.getActiveOntology(); String defaultPrefix = prefixManager.getDefaultPrefix(); if (defaultPrefix == null) { OWLOntologyID ontologyID = activeOntology.getOntologyID(); defaultPrefix = ontologyID.getOntologyIRI().toURI().toString(); } activeOBDAModel.getPrefixManager().addPrefix(PrefixManager.DEFAULT_PREFIX, defaultPrefix); // Add the model URI modelUri = activeOntology.getOntologyID().getOntologyIRI().toURI(); obdamodels.put(modelUri, activeOBDAModel); } // /** // * Append here all default prefixes used by the system. // */ // private void addOBDACommonPrefixes(PrefixOWLOntologyFormat prefixManager) { // if (!prefixManager.containsPrefixMapping("quest")) { //// sb.append("@PREFIX xsd: <http://www.w3.org/2001/XMLSchema //// sb.append("@PREFIX rdfs: <http: //www.w3.org/2000/01/rdf-schema //// sb.append("@PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns //// sb.append("@PREFIX owl: <http://www.w3.org/2002/07/owl // prefixManager.setPrefix("quest", OBDAVocabulary.QUEST_NS); public QueryController getQueryController() { if (queryController == null) { queryController = new QueryController(); } return queryController; } /** * Internal class responsible for coordinating actions related to updates in * the ontology environment. */ private class OBDAPLuginOWLModelManagerListener implements OWLModelManagerListener { public boolean inititializing = false; @Override public void handleChange(OWLModelManagerChangeEvent event) { // Get the active ontology OWLModelManager source = event.getSource(); OWLOntology activeOntology = source.getActiveOntology(); // Initialize the active OBDA model OBDAModel activeOBDAModel = null; // Perform a proper handling for each type of event final EventType eventType = event.getType(); switch (eventType) { case ABOUT_TO_CLASSIFY: log.debug("ABOUT TO CLASSIFY"); loadingData = true; break; case ENTITY_RENDERER_CHANGED: log.debug("RENDERER CHANGED"); break; case ONTOLOGY_CLASSIFIED: loadingData = false; break; case ACTIVE_ONTOLOGY_CHANGED: log.debug("ACTIVE ONTOLOGY CHANGED"); inititializing = true; // flag on // Setting up a new OBDA model and retrieve the object. setupNewOBDAModel(); activeOBDAModel = getActiveOBDAModel(); OWLModelManager mmgr = owlEditorKit.getOWLWorkspace().getOWLModelManager(); OWLOntology ontology = mmgr.getActiveOntology(); PrefixOWLOntologyFormat prefixManager = PrefixUtilities.getPrefixOWLOntologyFormat(ontology); String defaultPrefix = prefixManager.getDefaultPrefix(); if (defaultPrefix == null) { OWLOntologyID ontologyID = ontology.getOntologyID(); defaultPrefix = ontologyID.getOntologyIRI().toURI().toString(); } activeOBDAModel.getPrefixManager().addPrefix(PrefixManager.DEFAULT_PREFIX, defaultPrefix); ProtegeOWLReasonerInfo factory = owlEditorKit.getOWLModelManager().getOWLReasonerManager().getCurrentReasonerFactory(); if (factory instanceof ProtegeOBDAOWLReformulationPlatformFactory) { ProtegeOBDAOWLReformulationPlatformFactory questfactory = (ProtegeOBDAOWLReformulationPlatformFactory) factory; ProtegeReformulationPlatformPreferences reasonerPreference = (ProtegeReformulationPlatformPreferences) owlEditorKit.get(QuestPreferences.class.getName()); questfactory.setPreferences(reasonerPreference); questfactory.setOBDAModel(getActiveOBDAModel()); } fireActiveOBDAModelChange(); inititializing = false; // flag off break; case ENTITY_RENDERING_CHANGED: break; case ONTOLOGY_CREATED: log.debug("ONTOLOGY CREATED"); break; case ONTOLOGY_LOADED: case ONTOLOGY_RELOADED: log.debug("ONTOLOGY LOADED/RELOADED"); loadingData = true; // flag on try { // Get the active OBDA model activeOBDAModel = getActiveOBDAModel(); String owlDocumentIri = source.getOWLOntologyManager().getOntologyDocumentIRI(activeOntology).toString(); String obdaDocumentIri = owlDocumentIri.substring(0, owlDocumentIri.length() - 3) + OBDA_EXT; String queryDocumentIri = owlDocumentIri.substring(0, owlDocumentIri.length() - 3) + QUERY_EXT; File obdaFile = new File(URI.create(obdaDocumentIri)); File queryFile = new File(URI.create(queryDocumentIri)); IRI ontologyIRI = activeOntology.getOntologyID().getOntologyIRI(); activeOBDAModel.getPrefixManager().addPrefix(PrefixManager.DEFAULT_PREFIX, ontologyIRI.toString()); if (obdaFile.exists()) { try { // Load the OBDA model ModelIOManager modelIO = new ModelIOManager(activeOBDAModel); modelIO.load(obdaFile); } catch (Exception ex) { activeOBDAModel.reset(); throw new Exception("Exception occurred while loading OBDA document: " + obdaFile + "\n\n" + ex.getMessage()); } try { // Load the saved queries QueryIOManager queryIO = new QueryIOManager(queryController); queryIO.load(queryFile); } catch (Exception ex) { queryController.reset(); throw new Exception("Exception occurred while loading Query document: " + queryFile + "\n\n" + ex.getMessage()); } } else { log.warn("OBDA model couldn't be loaded because no .obda file exists in the same location as the .owl file"); } OBDAModelValidator refactorer = new OBDAModelValidator(activeOBDAModel, activeOntology); refactorer.run(); // adding type information to the mapping predicates. } catch (Exception e) { OBDAException ex = new OBDAException("An exception has occurred when loading input file.\nMessage: " + e.getMessage()); DialogUtils.showQuickErrorDialog(null, ex, "Open file error"); log.error(e.getMessage()); } finally { loadingData = false; // flag off } break; case ONTOLOGY_SAVED: log.debug("ACTIVE ONTOLOGY SAVED"); try { // Get the active OBDA model activeOBDAModel = getActiveOBDAModel(); String owlDocumentIri = source.getOWLOntologyManager().getOntologyDocumentIRI(activeOntology).toString(); String obdaDocumentIri = owlDocumentIri.substring(0, owlDocumentIri.length() - 3) + OBDA_EXT; String queryDocumentIri = owlDocumentIri.substring(0, owlDocumentIri.length() - 3) + QUERY_EXT; // Save the OBDA model File obdaFile = new File(URI.create(obdaDocumentIri)); ModelIOManager ModelIO = new ModelIOManager(activeOBDAModel); ModelIO.save(obdaFile); // Save the queries File queryFile = new File(URI.create(queryDocumentIri)); QueryIOManager queryIO = new QueryIOManager(queryController); queryIO.save(queryFile); } catch (IOException e) { log.error(e.getMessage()); Exception newException = new Exception( "Error saving the OBDA file. Closing Protege now can result in losing changes in your data sources or mappings. Please resolve the issue that prevents saving in the current location, or do \"Save as..\" to save in an alternative location. \n\nThe error message was: \n" + e.getMessage()); DialogUtils.showQuickErrorDialog(null, newException, "Error saving OBDA file"); triggerOntologyChanged(); } break; case ONTOLOGY_VISIBILITY_CHANGED: log.debug("VISIBILITY CHANGED"); break; case REASONER_CHANGED: log.info("REASONER CHANGED"); // Get the active OBDA model activeOBDAModel = getActiveOBDAModel(); if ((!inititializing) && (obdamodels != null) && (owlEditorKit != null) && (getActiveOBDAModel() != null)) { ProtegeOWLReasonerInfo fac = owlEditorKit.getOWLModelManager().getOWLReasonerManager().getCurrentReasonerFactory(); if (fac instanceof ProtegeOBDAOWLReformulationPlatformFactory) { ProtegeOBDAOWLReformulationPlatformFactory questfactory = (ProtegeOBDAOWLReformulationPlatformFactory) fac; ProtegeReformulationPlatformPreferences reasonerPreference = (ProtegeReformulationPlatformPreferences) owlEditorKit .get(QuestPreferences.class.getName()); questfactory.setPreferences(reasonerPreference); questfactory.setOBDAModel(getActiveOBDAModel()); } break; } } } } public void fireActiveOBDAModelChange() { for (OBDAModelManagerListener listener : obdaManagerListeners) { try { listener.activeOntologyChanged(); } catch (Exception e) { log.debug("Badly behaved listener: {}", listener.getClass().toString()); log.debug(e.getMessage(), e); } } } /*** * Protege wont trigger a save action unless it detects that the OWLOntology * currently opened has suffered a change. The OBDA plugin requires that * protege triggers a save action also in the case when only the OBDA model * has suffered chagnes. To acomplish this, this method will "fake" an * ontology change by inserting and removing a class into the OWLModel. * */ private void triggerOntologyChanged() { if (loadingData) { return; } OWLModelManager owlmm = owlEditorKit.getOWLModelManager(); OWLOntology ontology = owlmm.getActiveOntology(); if (ontology == null) { return; } OWLClass newClass = owlmm.getOWLDataFactory().getOWLClass(IRI.create("http://www.unibz.it/krdb/obdaplugin#RandomClass6677841155")); OWLAxiom axiom = owlmm.getOWLDataFactory().getOWLDeclarationAxiom(newClass); try { AddAxiom addChange = new AddAxiom(ontology, axiom); owlmm.applyChange(addChange); RemoveAxiom removeChange = new RemoveAxiom(ontology, axiom); owlmm.applyChange(removeChange); } catch (Exception e) { log.warn("Exception forcing an ontology change. Your OWL model might contain a new class that you need to remove manually: {}", newClass.getIRI()); log.warn(e.getMessage()); log.debug(e.getMessage(), e); } } /*** * Called from ModelManager dispose method since this object is setup as the * APIController.class.getName() property with the put method. */ public void dispose() throws Exception { try { owlEditorKit.getModelManager().removeListener(getModelManagerListener()); connectionManager.dispose(); } catch (Exception e) { log.warn(e.getMessage()); } } protected OWLModelManagerListener getModelManagerListener() { return modelManagerListener; } /* * The following are internal helpers that dispatch "needs save" messages to * the OWL ontology model when OBDA model changes. */ private class ProtegeDatasourcesControllerListener implements OBDAModelListener { private static final long serialVersionUID = -1633463551656406417L; public void datasourceUpdated(String oldname, OBDADataSource currendata) { triggerOntologyChanged(); } public void datasourceDeleted(OBDADataSource source) { triggerOntologyChanged(); } public void datasourceAdded(OBDADataSource source) { triggerOntologyChanged(); } public void alldatasourcesDeleted() { triggerOntologyChanged(); } public void datasourcParametersUpdated() { triggerOntologyChanged(); } } private class ProtegeMappingControllerListener implements OBDAMappingListener { private static final long serialVersionUID = -5794145688669702879L; public void allMappingsRemoved() { triggerOntologyChanged(); } public void currentSourceChanged(URI oldsrcuri, URI newsrcuri) { // Do nothing! } public void mappingDeleted(URI srcuri, String mapping_id) { triggerOntologyChanged(); } public void mappingInserted(URI srcuri, String mapping_id) { triggerOntologyChanged(); } public void mappingUpdated(URI srcuri, String mapping_id, OBDAMappingAxiom mapping) { triggerOntologyChanged(); } } private class ProtegeQueryControllerListener implements QueryControllerListener { private static final long serialVersionUID = 4536639410306364312L; public void elementAdded(QueryControllerEntity element) { triggerOntologyChanged(); } public void elementAdded(QueryControllerQuery query, QueryControllerGroup group) { triggerOntologyChanged(); } public void elementRemoved(QueryControllerEntity element) { triggerOntologyChanged(); } public void elementRemoved(QueryControllerQuery query, QueryControllerGroup group) { triggerOntologyChanged(); } public void elementChanged(QueryControllerQuery query) { triggerOntologyChanged(); } public void elementChanged(QueryControllerQuery query, QueryControllerGroup group) { triggerOntologyChanged(); } } }
package org.csstudio.javafx.rtplot.internal; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.geom.IllegalPathStateException; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.csstudio.display.builder.util.undo.UndoableActionManager; import org.csstudio.javafx.rtplot.util.RTPlotUpdateThrottle; import javafx.application.Platform; import javafx.geometry.Point2D; import javafx.scene.image.ImageView; import javafx.scene.image.PixelFormat; import javafx.scene.image.WritableImage; import javafx.scene.input.MouseEvent; import javafx.scene.input.ScrollEvent; /** Base for plots * * <p>Based on an {@link ImageView}. * Container needs to call <code>setSize</code>. * * @author Kay Kasemir */ @SuppressWarnings("nls") abstract class PlotCanvasBase extends ImageView { // Implementation used to be based on JFX Canvas, // drawing the plot's image and then adding cursor mode feedback. // JFX canvas, however, can queue up rendering requests, // including multiple copies of to-be-rendered images, // which quickly exhausts memory for large plots. // Using reflection to check the Canvas.current and its internal // buffer one can warn about this. // Calling canvas.getGraphicsContext2D().clearRect(0, 0, width, height) // will help to shrink the rendering queue IF it's being processed // Overall, however, ImageView avoids memory issues because it // only holds a reference to the current image. protected static final int ARROW_SIZE = 8; protected static final double ZOOM_FACTOR = 1.2; /** When using 'rubberband' to zoom in, need to select a region * at least this wide resp. high. * Smaller regions are likely the result of an accidental * click-with-jerk, which would result into a huge zoom step. */ protected static final int ZOOM_PIXEL_THRESHOLD = 20; /** Strokes used for mouse feedback */ protected static final BasicStroke MOUSE_FEEDBACK_BACK = new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER), MOUSE_FEEDBACK_FRONT = new BasicStroke(1); /** Support for un-do and re-do */ protected final UndoableActionManager undo = new UndoableActionManager(50); /** Area of this plot */ protected volatile Rectangle area = new Rectangle(0, 0, 0, 0); /** Suppress updates triggered by axis changes from layout or autoscale * * Calling updateImageBuffer can trigger axis changes because of layout * or autoscale, which call the plot_part_listener. */ private volatile boolean in_update = false; /** Does layout need to be re-computed? */ protected final AtomicBoolean need_layout = new AtomicBoolean(true); /** Does plot image to be re-created? */ protected final AtomicBoolean need_update = new AtomicBoolean(true); /** Throttle updates, enforcing a 'dormant' period */ private final RTPlotUpdateThrottle update_throttle; /** Buffer for image and color bar * * <p>UpdateThrottle calls updateImageBuffer() to set the image * in its thread, then redrawn in UI thread. */ private volatile BufferedImage plot_image = null; /** Listener to {@link PlotPart}s, triggering refresh of plot */ protected final PlotPartListener plot_part_listener = new PlotPartListener() { @Override public void layoutPlotPart(final PlotPart plotPart) { need_layout.set(true); } @Override public void refreshPlotPart(final PlotPart plotPart) { if (! in_update) requestUpdate(); } }; /** Redraw the plot on UI thread by painting the 'plot_image' */ private final Runnable redraw_runnable = () -> { final BufferedImage copy = plot_image; if (copy != null) { // Create copy of basic plot if (copy.getType() != BufferedImage.TYPE_INT_ARGB) throw new IllegalPathStateException("Need TYPE_INT_ARGB for direct buffer access, not " + copy.getType()); final int width = copy.getWidth(), height = copy.getHeight(); final BufferedImage combined = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); final int[] src = ((DataBufferInt) copy.getRaster().getDataBuffer()).getData(); final int[] dest = ((DataBufferInt) combined.getRaster().getDataBuffer()).getData(); System.arraycopy(src, 0, dest, 0, width * height); // Add mouse mode feedback final Graphics2D gc = combined.createGraphics(); gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); gc.setColor(Color.BLACK); drawMouseModeFeedback(gc); gc.dispose(); // Convert to JFX image and show final WritableImage image = new WritableImage(width, height); // SwingFXUtils.toFXImage(combined, image); image.getPixelWriter().setPixels(0, 0, width, height, PixelFormat.getIntArgbInstance(), dest, 0, width); setImage(image); } }; protected MouseMode mouse_mode = MouseMode.NONE; protected Optional<Point2D> mouse_start = Optional.empty(); protected volatile Optional<Point2D> mouse_current = Optional.empty(); /** Constructor * @param active Active mode where plot reacts to mouse/keyboard? */ protected PlotCanvasBase(final boolean active) { // 50ms = 20Hz default throttle update_throttle = new RTPlotUpdateThrottle(50, TimeUnit.MILLISECONDS, () -> { if (need_update.getAndSet(false)) { in_update = true; final BufferedImage latest = updateImageBuffer(); in_update = false; if (latest == null) // Update failed, request another requestUpdate(); else plot_image = latest; } Platform.runLater(redraw_runnable); }); if (active) { setOnMouseEntered(this::mouseEntered); setOnScroll(this::wheelZoom); } } /** Call to update size of plot * * @param width * @param height */ public void setSize(final double width, final double height) { area = new Rectangle((int)width, (int)height); need_layout.set(true); requestUpdate(); } /** @return {@link UndoableActionManager} for this plot */ public UndoableActionManager getUndoableActionManager() { return undo; } /** Update the dormant time between updates * @param dormant_time How long throttle remains dormant after a trigger * @param unit Units for the dormant period */ public void setUpdateThrottle(final long dormant_time, final TimeUnit unit) { update_throttle.setDormantTime(dormant_time, unit); } /** Request a complete redraw of the plot with new layout */ final public void requestLayout() { need_layout.set(true); need_update.set(true); update_throttle.trigger(); } /** Request a complete update of plot image */ final public void requestUpdate() { need_update.set(true); update_throttle.trigger(); } /** Request redraw of current image and cursors */ final void requestRedraw() { update_throttle.trigger(); } /** Draw all components into image buffer * @return Latest image, must be of type BufferedImage.TYPE_INT_ARGB */ protected abstract BufferedImage updateImageBuffer(); protected abstract void drawMouseModeFeedback(Graphics2D gc); /** Draw the zoom indicator for a horizontal zoom, i.e. on an X axis * * @param gc GC to use * @param plot_bounds Plot area where to draw the zoom indicator * @param start Initial mouse position * @param current Current mouse position */ protected void drawZoomXMouseFeedback(final Graphics2D gc, final Rectangle plot_bounds, final Point2D start, final Point2D current) { final int left = (int) Math.min(start.getX(), current.getX()); final int right = (int) Math.max(start.getX(), current.getX()); final int width = right - left; final int mid_y = plot_bounds.y + plot_bounds.height / 2; for (int i=0; i<2; ++i) { if (i==0) { gc.setColor(java.awt.Color.WHITE); gc.setStroke(MOUSE_FEEDBACK_BACK); } else { gc.setColor(java.awt.Color.BLACK); gc.setStroke(MOUSE_FEEDBACK_FRONT); } // Range on axis gc.drawRect(left, (int)start.getY(), width, 1); // Left, right vertical bar gc.drawLine(left, plot_bounds.y, left, plot_bounds.y + plot_bounds.height); gc.drawLine(right, plot_bounds.y, right, plot_bounds.y + plot_bounds.height); if (width >= 5*ARROW_SIZE) { gc.drawLine(left, mid_y, left + 2*ARROW_SIZE, mid_y); gc.drawLine(left+ARROW_SIZE, mid_y-ARROW_SIZE, left + 2*ARROW_SIZE, mid_y); gc.drawLine(left+ARROW_SIZE, mid_y+ARROW_SIZE, left + 2*ARROW_SIZE, mid_y); gc.drawLine(right, mid_y, right - 2*ARROW_SIZE, mid_y); gc.drawLine(right-ARROW_SIZE, mid_y-ARROW_SIZE, right - 2*ARROW_SIZE, mid_y); gc.drawLine(right-ARROW_SIZE, mid_y+ARROW_SIZE, right - 2*ARROW_SIZE, mid_y); } } } /** Draw the zoom indicator for a vertical zoom, i.e. on a Y axis * * @param gc GC to use * @param plot_bounds Plot area where to draw the zoom indicator * @param start Initial mouse position * @param current Current mouse position */ protected void drawZoomYMouseFeedback(final Graphics2D gc, final Rectangle plot_bounds, final Point2D start, final Point2D current) { final int top = (int) Math.min(start.getY(), current.getY()); final int bottom = (int) Math.max(start.getY(), current.getY()); final int height = bottom - top; final int mid_x = plot_bounds.x + plot_bounds.width / 2; for (int i=0; i<2; ++i) { if (i==0) { gc.setColor(java.awt.Color.WHITE); gc.setStroke(MOUSE_FEEDBACK_BACK); } else { gc.setColor(java.awt.Color.BLACK); gc.setStroke(MOUSE_FEEDBACK_FRONT); } // Range on axis gc.drawRect((int)start.getX(), top, 1, height); // Top, bottom horizontal bar gc.drawLine(plot_bounds.x, top, plot_bounds.x + plot_bounds.width, top); gc.drawLine(plot_bounds.x, bottom, plot_bounds.x + plot_bounds.width, bottom); if (height >= 5 * ARROW_SIZE) { gc.drawLine(mid_x, top, mid_x, top + 2*ARROW_SIZE); gc.drawLine(mid_x-ARROW_SIZE, top+ARROW_SIZE, mid_x, top + 2*ARROW_SIZE); gc.drawLine(mid_x+ARROW_SIZE, top+ARROW_SIZE, mid_x, top + 2*ARROW_SIZE); gc.drawLine(mid_x, bottom - 2*ARROW_SIZE, mid_x, bottom); gc.drawLine(mid_x, bottom - 2*ARROW_SIZE, mid_x-ARROW_SIZE, bottom - ARROW_SIZE); gc.drawLine(mid_x, bottom - 2*ARROW_SIZE, mid_x+ARROW_SIZE, bottom - ARROW_SIZE); } } } /** Draw the zoom indicator for zoom, i.e. a 'rubberband' * * @param gc GC to use * @param plot_bounds Plot area where to draw the zoom indicator * @param start Initial mouse position * @param current Current mouse position */ protected void drawZoomMouseFeedback(final Graphics2D gc, final Rectangle plot_bounds, final Point2D start, final Point2D current) { final int left = (int) Math.min(start.getX(), current.getX()); final int right = (int) Math.max(start.getX(), current.getX()); final int top = (int) Math.min(start.getY(), current.getY()); final int bottom = (int) Math.max(start.getY(), current.getY()); final int width = right - left; final int height = bottom - top; final int mid_x = left + width / 2; final int mid_y = top + height / 2; for (int i=0; i<2; ++i) { if (i==0) { // White 'background' to help rectangle show up on top // of dark images gc.setColor(java.awt.Color.WHITE); gc.setStroke(MOUSE_FEEDBACK_BACK); } else { gc.setColor(java.awt.Color.BLACK); gc.setStroke(MOUSE_FEEDBACK_FRONT); } // Main 'rubberband' rect gc.drawRect(left, top, width, height); if (width >= 5*ARROW_SIZE) { gc.drawLine(left, mid_y, left + 2*ARROW_SIZE, mid_y); gc.drawLine(left+ARROW_SIZE, mid_y-ARROW_SIZE, left + 2*ARROW_SIZE, mid_y); gc.drawLine(left+ARROW_SIZE, mid_y+ARROW_SIZE, left + 2*ARROW_SIZE, mid_y); gc.drawLine(right, mid_y, right - 2*ARROW_SIZE, mid_y); gc.drawLine(right-ARROW_SIZE, mid_y-ARROW_SIZE, right - 2*ARROW_SIZE, mid_y); gc.drawLine(right-ARROW_SIZE, mid_y+ARROW_SIZE, right - 2*ARROW_SIZE, mid_y); } if (height >= 5*ARROW_SIZE) { gc.drawLine(mid_x, top, mid_x, top + 2*ARROW_SIZE); gc.drawLine(mid_x-ARROW_SIZE, top+ARROW_SIZE, mid_x, top + 2*ARROW_SIZE); gc.drawLine(mid_x+ARROW_SIZE, top+ARROW_SIZE, mid_x, top + 2*ARROW_SIZE); gc.drawLine(mid_x, bottom - 2*ARROW_SIZE, mid_x, bottom); gc.drawLine(mid_x, bottom - 2*ARROW_SIZE, mid_x-ARROW_SIZE, bottom - ARROW_SIZE); gc.drawLine(mid_x, bottom - 2*ARROW_SIZE, mid_x+ARROW_SIZE, bottom - ARROW_SIZE); } } } public void setMouseMode(final MouseMode mode) { if (mode.ordinal() >= MouseMode.INTERNAL_MODES.ordinal()) throw new IllegalArgumentException("Not permitted to set " + mode); mouse_mode = mode; PlotCursors.setCursor(this, mouse_mode); } /** onMouseEntered */ protected void mouseEntered(final MouseEvent e) { getScene().setCursor(getCursor()); } /** Zoom in/out triggered by mouse wheel * @param event Scroll event */ protected void wheelZoom(final ScrollEvent event) { // Invoked by mouse scroll wheel. // Only allow zoom (with control), not pan. if (! event.isControlDown()) return; if (event.getDeltaY() > 0) zoomInOut(event.getX(), event.getY(), 1.0/ZOOM_FACTOR); else if (event.getDeltaY() < 0) zoomInOut(event.getX(), event.getY(), ZOOM_FACTOR); else return; event.consume(); } /** Zoom 'in' or 'out' from where the mouse was clicked * @param x Mouse coordinate * @param y Mouse coordinate * @param factor Zoom factor, positive to zoom 'out' */ protected abstract void zoomInOut(final double x, final double y, final double factor); /** Should be invoked when plot no longer used to release resources */ public void dispose() { // Stop updates which could otherwise still use // what's about to be disposed update_throttle.dispose(); } }
package cgeo.geocaching; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.util.Log; /** * provides all the available templates for logging * */ public class LogTemplateProvider { public static abstract class LogTemplate { private String template; private int resourceId; public LogTemplate(String template, int resourceId) { this.template = template; this.resourceId = resourceId; } abstract String getValue(cgBase base); public int getResourceId() { return resourceId; } public int getItemId() { return template.hashCode(); } public String getTemplateString() { return template; } protected String apply(String input, cgBase base) { if (input.contains("[" + template + "]")) { return input.replaceAll("\\[" + template + "\\]", getValue(base)); } return input; } } private static LogTemplate[] templates; public static LogTemplate[] getTemplates() { if (templates == null) { templates = new LogTemplate[] { new LogTemplate("DATE", R.string.init_signature_template_date) { @Override String getValue(final cgBase base) { return base.formatFullDate(System.currentTimeMillis()); } }, new LogTemplate("TIME", R.string.init_signature_template_time) { @Override String getValue(final cgBase base) { return base.formatTime(System.currentTimeMillis()); } }, new LogTemplate("USER", R.string.init_signature_template_user) { @Override String getValue(final cgBase base) { return base.getUserName(); } }, new LogTemplate("NUMBER", R.string.init_signature_template_number) { @Override String getValue(final cgBase base) { String findCount = ""; final HashMap<String, String> params = new HashMap<String, String>(); final String page = base.request(false, "www.geocaching.com", "/email/", "GET", params, false, false, false).getData(); int current = parseFindCount(page); if (current >= 0) { findCount = String.valueOf(current + 1); } return findCount; } } }; } return templates; } public static LogTemplate getTemplate(int itemId) { for (LogTemplate template : getTemplates()) { if (template.getItemId() == itemId) { return template; } } return null; } public static String applyTemplates(String signature, cgBase base) { if (signature == null) { return ""; } String result = signature; for (LogTemplate template : getTemplates()) { result = template.apply(result, base); } return result; } private static int parseFindCount(String page) { if (page == null || page.length() == 0) { return -1; } int findCount = -1; try { final Pattern findPattern = Pattern.compile("<strong><img.+?icon_smile.+?title=\"Caches Found\" /> ([,\\d]+)", Pattern.CASE_INSENSITIVE); final Matcher findMatcher = findPattern.matcher(page); if (findMatcher.find()) { if (findMatcher.groupCount() > 0) { String count = findMatcher.group(1); if (count != null) { if (count.length() == 0) { findCount = 0; } else { findCount = Integer.parseInt(count.replaceAll(",", "")); } } } } } catch (Exception e) { Log.w(cgSettings.tag, "cgBase.parseFindCount: " + e.toString()); } return findCount; } }
package org.nuxeo.ecm.automation.jaxrs.io.documents; import static org.nuxeo.ecm.core.api.security.SecurityConstants.BROWSE; import static org.nuxeo.ecm.core.api.security.SecurityConstants.EVERYONE; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.ws.rs.Produces; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.ext.Provider; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonGenerator; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.security.ACE; import org.nuxeo.ecm.core.api.security.ACL; import org.nuxeo.ecm.core.api.security.ACP; import org.nuxeo.ecm.core.security.SecurityService; import org.nuxeo.ecm.platform.tag.Tag; import org.nuxeo.ecm.platform.tag.TagService; import org.nuxeo.runtime.api.Framework; /** * JSon writer that outputs a format ready to eat by elasticsearch. * * * @since 5.9.3 */ @Provider @Produces({ "application/json+esentity" }) public class JsonESDocumentWriter extends JsonDocumentWriter { public static void writeDoc(JsonGenerator jg, DocumentModel doc, String[] schemas, Map<String, String> contextParameters, HttpHeaders headers) throws Exception { jg.writeStartObject(); jg.writeStringField("repository", doc.getRepositoryName()); jg.writeStringField("ecm:uuid", doc.getId()); jg.writeStringField("ecm:name", doc.getName()); jg.writeStringField("ecm:title", doc.getTitle()); jg.writeStringField("ecm:path", doc.getPathAsString()); jg.writeStringField("ecm:primarytype", doc.getType()); jg.writeStringField("ecm:parentId", doc.getParentRef().toString()); jg.writeStringField("ecm:currentLifeCycleState", doc.getCurrentLifeCycleState()); jg.writeStringField("ecm:versionLabel", doc.getVersionLabel()); jg.writeBooleanField("ecm:isCheckedIn", !doc.isCheckedOut()); jg.writeBooleanField("ecm:isProxy", doc.isProxy()); jg.writeBooleanField("ecm:isVersion", doc.isVersion()); jg.writeArrayFieldStart("ecm:mixinType"); for (String facet : doc.getFacets()) { jg.writeString(facet); } jg.writeEndArray(); TagService tagService = Framework.getService(TagService.class); if (tagService != null) { jg.writeArrayFieldStart("ecm:tag"); for (Tag tag : tagService.getDocumentTags(doc.getCoreSession(), doc.getId(), null)) { jg.writeString(tag.getLabel()); } jg.writeEndArray(); } jg.writeStringField("changeToken", doc.getChangeToken()); // Add a positive ACL only SecurityService securityService = Framework.getService(SecurityService.class); List<String> browsePermissions = new ArrayList<String>( Arrays.asList(securityService.getPermissionsToCheck(BROWSE))); ACP acp = doc.getACP(); ACL acl = acp.getACL(ACL.INHERITED_ACL); jg.writeArrayFieldStart("acl"); for (ACE ace : acl.getACEs()) { if (ace.isGranted() && browsePermissions.contains(ace.getPermission())) { jg.writeString(ace.getUsername()); } if (ace.isDenied()) { if (!EVERYONE.equals(ace.getUsername())) { jg.writeString("UNSUPPORTED_DENIED_ACL"); } break; } } jg.writeEndArray(); // TODO Add fulltext jg.writeStringField("fulltext", doc.getTitle() + " " + doc.getName()); if (schemas == null || (schemas.length == 1 && "*".equals(schemas[0]))) { schemas = doc.getSchemas(); } for (String schema : schemas) { writeProperties(jg, doc, schema); } if (contextParameters != null && !contextParameters.isEmpty()) { for (Map.Entry<String, String> parameter : contextParameters.entrySet()) { jg.writeStringField(parameter.getKey(), parameter.getValue()); } } jg.writeEndObject(); jg.flush(); } @Override public void writeDocument(OutputStream out, DocumentModel doc, String[] schemas, Map<String, String> contextParameters) throws Exception { writeDoc(factory.createJsonGenerator(out, JsonEncoding.UTF8), doc, schemas, contextParameters, headers); } public static void writeESDocument(JsonGenerator jg, DocumentModel doc, String[] schemas, Map<String, String> contextParameters) throws Exception { writeDoc(jg, doc, schemas, contextParameters, null); } }
package info.evanchik.eclipse.karaf.ui.internal; import java.io.File; import org.eclipse.core.expressions.PropertyTester; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; /** * A {@link PropertyTester} implemenation that us suitable for evaluating * several {@link File} properties (file name, directory and, extension). * <p> * Consult the constants declared in {@link Property} for a description in how * the test is performed. * * @author Stephen Evanchik (evanchsa@gmail.com) * */ public final class JavaFilePropertyTester extends PropertyTester { public static enum Property { /** * Matches the name of the file as returned by {@link File#getName()} */ name, /** * Matches the directory of the file as returned by * {@link File#getParent()}. The test does not attempt to match the * directory exactly. Instead it considers a match if the file's * directory ends with the supplied value. */ directory, /** * Matches the extension of the file as returned by * {@link IPath#getFileExtension()}. The {@code File} is converted to an * {@link IPath} using the {@link File#getAbsolutePath()} */ extension } @Override public boolean test(final Object receiver, final String property, final Object[] args, final Object expectedValue) { if (receiver instanceof File) { final File f = (File) receiver; if (property.equals(Property.name.toString())) { return f.getName().equals(expectedValue); } else if (property.equals(Property.directory.toString())) { return f.getParent().endsWith((String) expectedValue); } else if (property.equals(Property.extension.toString())) { return new Path(f.getAbsolutePath()).getFileExtension().equals(expectedValue); } else { return false; } } return false; } }
package cz.seznam.euphoria.flink.streaming; import cz.seznam.euphoria.core.client.dataset.HashPartitioner; import cz.seznam.euphoria.core.client.dataset.windowing.WindowID; import cz.seznam.euphoria.core.client.dataset.windowing.Windowing; import cz.seznam.euphoria.core.client.functional.UnaryFunction; import cz.seznam.euphoria.core.client.operator.CompositeKey; import cz.seznam.euphoria.core.client.operator.ReduceByKey; import cz.seznam.euphoria.core.client.operator.WindowedPair; import cz.seznam.euphoria.core.client.util.Pair; import cz.seznam.euphoria.flink.FlinkOperator; import cz.seznam.euphoria.flink.functions.IteratorIterable; import cz.seznam.euphoria.flink.functions.PartitionerWrapper; import cz.seznam.euphoria.flink.streaming.windowing.FlinkWindow; import cz.seznam.euphoria.flink.streaming.windowing.MultiWindowedElement; import cz.seznam.euphoria.flink.streaming.windowing.MultiWindowedElementWindowFunction; import cz.seznam.euphoria.guava.shaded.com.google.common.collect.Iterables; import cz.seznam.euphoria.guava.shaded.com.google.common.collect.Iterators; import org.apache.flink.api.common.functions.ReduceFunction; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.java.typeutils.ResultTypeQueryable; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.datastream.WindowedStream; import org.apache.flink.streaming.api.functions.windowing.PassThroughWindowFunction; import org.apache.flink.streaming.api.functions.windowing.WindowFunction; import org.apache.flink.streaming.api.windowing.windows.Window; import org.apache.flink.util.Collector; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.Set; class ReduceByKeyTranslator implements StreamingOperatorTranslator<ReduceByKey> { @Override @SuppressWarnings("unchecked") public DataStream<?> translate(FlinkOperator<ReduceByKey> operator, StreamingExecutorContext context) { DataStream<?> input = Iterables.getOnlyElement(context.getInputStreams(operator)); ReduceByKey origOperator = operator.getOriginalOperator(); final UnaryFunction<Iterable, Object> reducer = origOperator.getReducer(); final UnaryFunction keyExtractor; final UnaryFunction valueExtractor; final Windowing windowing = origOperator.getWindowing(); if (origOperator.isGrouped()) { UnaryFunction reduceKeyExtractor = origOperator.getKeyExtractor(); keyExtractor = (UnaryFunction<Pair, CompositeKey>) (Pair p) -> CompositeKey.of( p.getFirst(), reduceKeyExtractor.apply(p.getSecond())); UnaryFunction vfn = origOperator.getValueExtractor(); valueExtractor = (UnaryFunction<Pair, Object>) (Pair p) -> vfn.apply(p.getSecond()); } else { keyExtractor = origOperator.getKeyExtractor(); valueExtractor = origOperator.getValueExtractor(); } // apply windowing first SingleOutputStreamOperator<StreamingWindowedElement<?, ?, WindowedPair>> reduced; if (windowing == null) { WindowedStream windowedPairs = context.attachedWindowStream((DataStream) input, keyExtractor, valueExtractor); if (origOperator.isCombinable()) { // reduce incrementally reduced = windowedPairs.apply( new StreamingWindowedElementIncrementalReducer(reducer), new PassThroughWindowFunction<>()); } else { // reduce all elements at once when the window is fired reduced = windowedPairs.apply( new StreamingWindowedElementWindowedReducer(reducer, new PassThroughWindowFunction<>())); } } else { WindowedStream windowedPairs = context.flinkWindow( (DataStream) input, keyExtractor, valueExtractor, windowing); if (origOperator.isCombinable()) { // reduce incrementally reduced = windowedPairs.apply( new MultiWindowedElementIncrementalReducer(reducer), new MultiWindowedElementWindowFunction()); } else { // reduce all elements at once when the window is fired reduced = windowedPairs.apply( new MultiWindowedElementWindowedReducer(reducer, new MultiWindowedElementWindowFunction())); } } DataStream<StreamingWindowedElement<?, ?, WindowedPair>> out = reduced.name(operator.getName()) .setParallelism(operator.getParallelism()); // FIXME partitioner should be applied during "reduce" to avoid // unnecessary shuffle, but there is no (known) way how to set custom // partitioner to "keyBy" transformation // apply custom partitioner if different from default HashPartitioner if (!(origOperator.getPartitioning().getPartitioner().getClass() == HashPartitioner.class)) { out = out.partitionCustom( new PartitionerWrapper<>(origOperator.getPartitioning().getPartitioner()), p -> p.get().getKey()); } return out; } /** * Performs incremental reduction (in case of combining reduce). */ private static class StreamingWindowedElementIncrementalReducer implements ReduceFunction<StreamingWindowedElement<?, ?, WindowedPair>>, ResultTypeQueryable<StreamingWindowedElement<?, ?, WindowedPair>> { final UnaryFunction<Iterable, Object> reducer; public StreamingWindowedElementIncrementalReducer(UnaryFunction<Iterable, Object> reducer) { this.reducer = reducer; } @Override public StreamingWindowedElement<?, ?, WindowedPair> reduce( StreamingWindowedElement<?, ?, WindowedPair> p1, StreamingWindowedElement<?, ?, WindowedPair> p2) { Object v1 = p1.get().getSecond(); Object v2 = p2.get().getSecond(); WindowID<?, ?> wid = p1.getWindowID(); StreamingWindowedElement<?, ?, WindowedPair> out = new StreamingWindowedElement<>( wid, WindowedPair.of( wid.getLabel(), p1.get().getKey(), reducer.apply(Arrays.asList(v1, v2)))); // ~ forward the emission watermark - if any out.withEmissionWatermark(p1.getEmissionWatermark()); return out; } @Override @SuppressWarnings("unchecked") public TypeInformation<StreamingWindowedElement<?, ?, WindowedPair>> getProducedType() { return TypeInformation.of((Class) StreamingWindowedElement.class); } } // ~ end of StreamingWindowedElementIncrementalReducer /** * Performs non-incremental reduction (in case of non-combining reduce). */ private static class StreamingWindowedElementWindowedReducer implements WindowFunction< StreamingWindowedElement<?, ?, WindowedPair>, StreamingWindowedElement<?, ?, WindowedPair>, Object, Window> { private final UnaryFunction<Iterable, Object> reducer; private final WindowFunction<StreamingWindowedElement<?, ?, WindowedPair>, StreamingWindowedElement<?, ?, WindowedPair>, Object, Window> emissionFunction; @SuppressWarnings("unchecked") public StreamingWindowedElementWindowedReducer(UnaryFunction<Iterable, Object> reducer, WindowFunction emissionFunction) { this.reducer = reducer; this.emissionFunction = emissionFunction; } @Override public void apply(Object key, Window window, Iterable<StreamingWindowedElement<?, ?, WindowedPair>> input, Collector<StreamingWindowedElement<?, ?, WindowedPair>> collector) throws Exception { Iterator<StreamingWindowedElement<?, ?, WindowedPair>> it = input.iterator(); // read the first element to obtain window metadata StreamingWindowedElement<?, ?, WindowedPair> element = it.next(); WindowID<?, ?> wid = element.getWindowID(); long emissionWatermark = element.getEmissionWatermark(); // concat the already read element with rest of the opened iterator Iterator<StreamingWindowedElement<?, ?, WindowedPair>> concatIt = Iterators.concat(Iterators.singletonIterator(element), it); // unwrap all elements to be used in user defined reducer Iterator<Object> unwrapped = Iterators.transform(concatIt, e -> e.get().getValue()); Object reduced = reducer.apply(new IteratorIterable<>(unwrapped)); StreamingWindowedElement<?, ?, WindowedPair> out = new StreamingWindowedElement<>( wid, WindowedPair.of( wid.getLabel(), key, reduced)); out.withEmissionWatermark(emissionWatermark); // decorate resulting item with emission watermark from fired window emissionFunction.apply(key, window, Collections.singletonList(out), collector); } } // ~ end of StreamingWindowedElementWindowedReducer /** * Performs incremental reduction (in case of combining reduce) on * {@link MultiWindowedElement}s. Assumes the result is emitted using * {@link MultiWindowedElementWindowFunction}. */ private static class MultiWindowedElementIncrementalReducer<GROUP, LABEL, KEY, VALUE> implements ReduceFunction<MultiWindowedElement<GROUP, LABEL, Pair<KEY, VALUE>>>, ResultTypeQueryable<MultiWindowedElement<GROUP, LABEL, Pair<KEY, VALUE>>> { final UnaryFunction<Iterable<VALUE>, VALUE> reducer; public MultiWindowedElementIncrementalReducer(UnaryFunction<Iterable<VALUE>, VALUE> reducer) { this.reducer = reducer; } @Override public MultiWindowedElement<GROUP, LABEL, Pair<KEY, VALUE>> reduce( MultiWindowedElement<GROUP, LABEL, Pair<KEY, VALUE>> p1, MultiWindowedElement<GROUP, LABEL, Pair<KEY, VALUE>> p2) { VALUE v1 = p1.get().getSecond(); VALUE v2 = p2.get().getSecond(); Set<WindowID<GROUP, LABEL>> s = Collections.emptySet(); return new MultiWindowedElement<>(s, Pair.of(p1.get().getFirst(), reducer.apply(Arrays.asList(v1, v2)))); } @Override @SuppressWarnings("unchecked") public TypeInformation<MultiWindowedElement<GROUP, LABEL, Pair<KEY, VALUE>>> getProducedType() { return TypeInformation.of((Class) MultiWindowedElement.class); } } // ~ end of MultiWindowedElementIncrementalReducer /** * Performs non-incremental reduction (in case of non-combining reduce). */ private static class MultiWindowedElementWindowedReducer<GROUP, LABEL, KEY, VALUEIN, VALUEOUT> implements WindowFunction< MultiWindowedElement<?, ?, Pair<KEY, VALUEIN>>, StreamingWindowedElement<GROUP, LABEL, WindowedPair<LABEL, KEY, VALUEOUT>>, KEY, FlinkWindow<GROUP, LABEL>> { private final UnaryFunction<Iterable<VALUEIN>, VALUEOUT> reducer; private final MultiWindowedElementWindowFunction<GROUP, LABEL, KEY, VALUEOUT> emissionFunction; public MultiWindowedElementWindowedReducer( UnaryFunction<Iterable<VALUEIN>, VALUEOUT> reducer, MultiWindowedElementWindowFunction<GROUP, LABEL, KEY, VALUEOUT> emissionFunction) { this.reducer = reducer; this.emissionFunction = emissionFunction; } @Override public void apply(KEY key, FlinkWindow<GROUP, LABEL> window, Iterable<MultiWindowedElement<?, ?, Pair<KEY, VALUEIN>>> input, Collector<StreamingWindowedElement<GROUP, LABEL, WindowedPair<LABEL, KEY, VALUEOUT>>> collector) throws Exception { Iterator<MultiWindowedElement<?, ?, Pair<KEY, VALUEIN>>> it = input.iterator(); // read the first element to obtain window metadata MultiWindowedElement<?, ?, Pair<KEY, VALUEIN>> element = it.next(); // concat the already read element with rest of the opened iterator Iterator<MultiWindowedElement<?, ?, Pair<KEY, VALUEIN>>> concatIt = Iterators.concat(Iterators.singletonIterator(element), it); // unwrap all elements to be used in user defined reducer Iterator<VALUEIN> unwrapped = Iterators.transform(concatIt, e -> e.get().getValue()); MultiWindowedElement<Object, Object, Pair<KEY, VALUEOUT>> reduced = new MultiWindowedElement<>( Collections.emptySet(), Pair.of(key, reducer.apply(new IteratorIterable<>(unwrapped)))); this.emissionFunction.apply(key, window, Collections.singletonList(reduced), collector); } } // ~ end of MultiWindowedElementWindowedReducer }
package org.collectionspace.services.client.test; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; //import org.collectionspace.services.client.AbstractServiceClientImpl; import org.collectionspace.services.client.CollectionObjectClient; import org.collectionspace.services.client.CollectionObjectFactory; import org.collectionspace.services.client.CollectionSpaceClient; import org.collectionspace.services.client.PayloadInputPart; import org.collectionspace.services.client.PayloadOutputPart; import org.collectionspace.services.client.PoxPayloadIn; import org.collectionspace.services.client.PoxPayloadOut; import org.collectionspace.services.collectionobject.BriefDescriptionList; import org.collectionspace.services.collectionobject.CollectionobjectsCommon; import org.collectionspace.services.collectionobject.domain.naturalhistory.CollectionobjectsNaturalhistory; import org.collectionspace.services.collectionobject.DimensionSubGroup; import org.collectionspace.services.collectionobject.DimensionSubGroupList; import org.collectionspace.services.collectionobject.MeasuredPartGroup; import org.collectionspace.services.collectionobject.MeasuredPartGroupList; import org.collectionspace.services.collectionobject.ObjectNameGroup; import org.collectionspace.services.collectionobject.ObjectNameList; import org.collectionspace.services.collectionobject.OtherNumber; import org.collectionspace.services.collectionobject.OtherNumberList; import org.collectionspace.services.collectionobject.ResponsibleDepartmentList; import org.collectionspace.services.collectionobject.TitleGroup; import org.collectionspace.services.collectionobject.TitleGroupList; import org.collectionspace.services.collectionobject.TitleTranslationSubGroup; import org.collectionspace.services.collectionobject.TitleTranslationSubGroupList; import org.collectionspace.services.common.AbstractCommonListUtils; import org.collectionspace.services.jaxb.AbstractCommonList; import org.jboss.resteasy.client.ClientResponse; import org.testng.Assert; import org.testng.annotations.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * CollectionObjectServiceTest, carries out tests against a * deployed and running CollectionObject Service. * * $LastChangedRevision$ * $LastChangedDate$ */ public class CollectionObjectServiceTest extends AbstractServiceTestImpl { /** The logger. */ private final String CLASS_NAME = CollectionObjectServiceTest.class.getName(); private final Logger logger = LoggerFactory.getLogger(CLASS_NAME); // Instance variables specific to this test. /** The known resource id. */ private String knownResourceId = null; private final String OBJECT_NAME_VALUE = "an object name"; private final BigInteger AGE_VALUE = new BigInteger("55"); private final String MEASURED_PART = "light box frame"; private final BigDecimal DIMENSION_VALUE_LENGTH = new BigDecimal("0.009"); private final BigDecimal DIMENSION_VALUE_WIDTH = new BigDecimal("3087.56"); private final String UPDATED_MEASUREMENT_UNIT = "Angstroms"; private final String UTF8_DATA_SAMPLE = "Audiorecording album cover signed by Lech " + "Wa" + '\u0142' + '\u0119' + "sa"; // /* (non-Javadoc) // * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent() // */ // @Override // protected String getServicePathComponent() { // return new CollectionObjectClient().getServicePathComponent(); @Override protected String getServiceName() { return CollectionObjectClient.SERVICE_NAME; } /* (non-Javadoc) * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance() */ @Override protected CollectionSpaceClient getClientInstance() { return new CollectionObjectClient(); } /* (non-Javadoc) * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse) */ @Override protected AbstractCommonList getAbstractCommonList( ClientResponse<AbstractCommonList> response) { return response.getEntity(AbstractCommonList.class); } // CRUD tests : CREATE tests // Success outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.ServiceTest#create(java.lang.String) */ @Override @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class) public void create(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup, such as initializing the type of service request // (e.g. CREATE, DELETE), its valid and expected status codes, and // its associated HTTP method name (e.g. POST, DELETE). setupCreate(); // Submit the request to the service and store the response. CollectionObjectClient client = new CollectionObjectClient(); String identifier = createIdentifier(); PoxPayloadOut multipart = createCollectionObjectInstance(client.getCommonPartName(), identifier); ClientResponse<Response> res = client.create(multipart); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? // Specifically: // Does it fall within the set of valid status codes? // Does it exactly match the expected status code? if (logger.isDebugEnabled()) { logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); // Store the ID returned from the first resource created // for additional tests below. if (knownResourceId == null) { knownResourceId = extractId(res); if (logger.isDebugEnabled()) { logger.debug(testName + ": knownResourceId=" + knownResourceId); } } // so they can be deleted after tests have been run. allResourceIdsCreated.add(extractId(res)); } /* * Tests to diagnose and verify the fixed status of CSPACE-1026, * "Whitespace at certain points in payload cause failure" */ /** * Creates the from xml cambridge. * * @param testName the test name * @throws Exception the exception */ @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create", "testSubmitRequest"}) public void createFromXmlCambridge(String testName) throws Exception { String newId = createFromXmlFile(testName, "./test-data/testCambridge.xml", true); testSubmitRequest(newId); } /* * Tests to diagnose and fix CSPACE-2242. * * This is a bug identified in release 0.8 in which value instances of a * repeatable field are not stored when the first value instance of that * field is blank. */ // Verify that record creation occurs successfully when the first value instance // of a single, repeatable String scalar field is non-blank. @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create", "testSubmitRequest"}, groups = {"cspace2242group"}) public void createFromXmlNonBlankFirstValueInstance(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } String newId = createFromXmlFile(testName, "./test-data/cspace-2242-first-value-instance-nonblank.xml", true); CollectionobjectsCommon collectionObject = readCollectionObjectCommonPart(newId); // Verify that at least one value instance of the repeatable field was successfully persisted. BriefDescriptionList descriptionList = collectionObject.getBriefDescriptions(); List<String> descriptions = descriptionList.getBriefDescription(); Assert.assertTrue(descriptions.size() > 0); } // Verify that record creation occurs successfully when the first value instance // of a single, repeatable String scalar field is blank. @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create", "testSubmitRequest"}, groups = {"cspace2242group"}) public void createFromXmlBlankFirstValueInstance(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } String newId = createFromXmlFile(testName, "./test-data/cspace-2242-first-value-instance-blank.xml", true); CollectionobjectsCommon collectionObject = readCollectionObjectCommonPart(newId); // Verify that at least one value instance of the repeatable field was successfully persisted. BriefDescriptionList descriptionList = collectionObject.getBriefDescriptions(); List<String> descriptions = descriptionList.getBriefDescription(); Assert.assertTrue(descriptions.size() > 0); } // Verify that values are preserved when enclosed in double quote marks. @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create", "testSubmitRequest"}, groups = {"cspace3237group"}) public void doubleQuotesEnclosingFieldContents(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } String newId = createFromXmlFile(testName, "./test-data/cspace-3237-double-quotes.xml", true); CollectionobjectsCommon collectionObject = readCollectionObjectCommonPart(newId); Assert.assertTrue(collectionObject.getDistinguishingFeatures().matches("^\\\".+?\\\"$")); BriefDescriptionList descriptionList = collectionObject.getBriefDescriptions(); List<String> descriptions = descriptionList.getBriefDescription(); Assert.assertTrue(descriptions.size() > 0); Assert.assertNotNull(descriptions.get(0)); Assert.assertTrue(descriptions.get(0).matches("^\\\".+?\\\"$")); if (logger.isDebugEnabled()) { logger.debug(objectAsXmlString(collectionObject, CollectionobjectsCommon.class)); } } /** * Creates the from xml rfw s1. * * @param testName the test name * @throws Exception the exception */ @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create", "testSubmitRequest"}) public void createFromXmlRFWS1(String testName) throws Exception { String testDataDir = System.getProperty("test-data.fileName"); String newId = //createFromXmlFile(testName, "./target/test-classes/test-data/repfield_whitesp1.xml", false); createFromXmlFile(testName, testDataDir + "/repfield_whitesp1.xml", false); testSubmitRequest(newId); } /** * Creates the from xml rfw s2. * * @param testName the test name * @throws Exception the exception */ @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create", "testSubmitRequest"}) public void createFromXmlRFWS2(String testName) throws Exception { String testDataDir = System.getProperty("test-data.fileName"); String newId = //createFromXmlFile(testName, "./target/test-classes/test-data/repfield_whitesp2.xml", false); createFromXmlFile(testName, testDataDir + "/repfield_whitesp2.xml", false); testSubmitRequest(newId); } /** * Creates the from xml rfw s3. * * @param testName the test name * @throws Exception the exception */ @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create", "testSubmitRequest"}) public void createFromXmlRFWS3(String testName) throws Exception { String testDataDir = System.getProperty("test-data.fileName"); String newId = //createFromXmlFile(testName, "./target/test-classes/test-data/repfield_whitesp3.xml", false); createFromXmlFile(testName, testDataDir + "/repfield_whitesp3.xml", false); testSubmitRequest(newId); } /** * Creates the from xml rfw s4. * * @param testName the test name * @throws Exception the exception */ @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create", "testSubmitRequest"}) public void createFromXmlRFWS4(String testName) throws Exception { String testDataDir = System.getProperty("test-data.fileName"); String newId = createFromXmlFile(testName, testDataDir + "/repfield_whitesp4.xml", false); testSubmitRequest(newId); } /* * Tests to diagnose and verify the fixed status of CSPACE-1248, * "Wedged records created!" (i.e. records with child repeatable * fields, which contain null values, can be successfully created * but an error occurs on trying to retrieve those records). */ /** * Creates a CollectionObject resource with a null value repeatable field. * * @param testName the test name * @throws Exception the exception */ @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create", "testSubmitRequest"}) public void createWithNullValueRepeatableField(String testName) throws Exception { String testDataDir = System.getProperty("test-data.fileName"); String newId = createFromXmlFile(testName, testDataDir + "/repfield_null1.xml", false); if (logger.isDebugEnabled()) { logger.debug("Successfully created record with null value repeatable field."); logger.debug("Attempting to retrieve just-created record ..."); } testSubmitRequest(newId); } /** * Creates a CollectionObject resource, one of whose fields contains * non-Latin 1 Unicode UTF-8 characters. * * @param testName the test name * @throws Exception the exception */ @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create", "testSubmitRequest"}, groups={"utf8-create"}) public void createWithUTF8Data(String testName) throws Exception { String testDataDir = System.getProperty("test-data.fileName"); String newId = createFromXmlFile(testName, testDataDir + "/cspace-2779-utf-8-create.xml", false); if (logger.isDebugEnabled()) { logger.debug("Created record with UTF-8 chars in payload."); logger.debug("Attempting to retrieve just-created record ..."); } CollectionobjectsCommon collectionObject = readCollectionObjectCommonPart(newId); String distinguishingFeatures = collectionObject.getDistinguishingFeatures(); if (logger.isDebugEnabled()) { logger.debug("Sent distinguishingFeatures: " + UTF8_DATA_SAMPLE); logger.debug("Received distinguishingFeatures: " + distinguishingFeatures); } Assert.assertTrue(distinguishingFeatures.equals(UTF8_DATA_SAMPLE)); } /* (non-Javadoc) * @see org.collectionspace.services.client.test.ServiceTest#createList() */ @Override @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create"}) public void createList(String testName) throws Exception { this.createPaginatedList(testName, DEFAULT_LIST_SIZE); } // Failure outcomes // Placeholders until the three tests below can be uncommented. // See Issue CSPACE-401. /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#createWithEmptyEntityBody(java.lang.String) */ @Override @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class) public void createWithEmptyEntityBody(String testName) throws Exception { //FIXME: Should this test really be empty? } /** * Test how the service handles XML that is not well formed, * when sent in the payload of a Create request. * * @param testName The name of this test method. This name is supplied * automatically, via reflection, by a TestNG 'data provider' in * a base class. */ @Override @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class) public void createWithMalformedXml(String testName) throws Exception { } /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#createWithWrongXmlSchema(java.lang.String) */ @Override @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class) public void createWithWrongXmlSchema(String testName) throws Exception { //FIXME: Should this test really be empty? } /* @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class, dependsOnMethods = {"create", "testSubmitRequest"}) public void createWithEmptyEntityBody(String testName) throwsException { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupCreateWithEmptyEntityBody(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getServiceRootURL(); String mediaType = MediaType.APPLICATION_XML; final String entity = ""; int statusCode = submitRequest(method, url, mediaType, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class, dependsOnMethods = {"create", "testSubmitRequest"}) public void createWithMalformedXml(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupCreateWithMalformedXml(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getServiceRootURL(); String mediaType = MediaType.APPLICATION_XML; final String entity = MALFORMED_XML_DATA; // Constant from base class. int statusCode = submitRequest(method, url, mediaType, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class, dependsOnMethods = {"create", "testSubmitRequest"}) public void createWithWrongXmlSchema(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupCreateWithWrongXmlSchema(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getServiceRootURL(); String mediaType = MediaType.APPLICATION_XML; final String entity = WRONG_XML_SCHEMA_DATA; int statusCode = submitRequest(method, url, mediaType, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } */ /** * Test how the service handles, in a Create request, payloads * containing null values (or, in the case of String fields, * empty String values) in one or more fields which must be * present and are required to contain non-empty values. * * This is a test of code and/or configuration in the service's * validation routine(s). * * @param testName The name of this test method. This name is supplied * automatically, via reflection, by a TestNG 'data provider' in * a base class. * @throws Exception */ @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class) public void createWithRequiredValuesNullOrEmpty(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } setupCreate(); // Build a payload with invalid content, by omitting a // field (objectNumber) which must be present, and in which // a non-empty value is required, as enforced by the service's // validation routine(s). CollectionobjectsCommon collectionObject = new CollectionobjectsCommon(); TitleGroupList titleGroupList = new TitleGroupList(); List<TitleGroup> titleGroups = titleGroupList.getTitleGroup(); TitleGroup titleGroup = new TitleGroup(); titleGroup.setTitle("a title"); titleGroups.add(titleGroup); collectionObject.setTitleGroupList(titleGroupList); ObjectNameList objNameList = new ObjectNameList(); List<ObjectNameGroup> objNameGroups = objNameList.getObjectNameGroup(); ObjectNameGroup objectNameGroup = new ObjectNameGroup(); objectNameGroup.setObjectName("an object name"); objNameGroups.add(objectNameGroup); collectionObject.setObjectNameList(objNameList); // Submit the request to the service and store the response. CollectionObjectClient client = new CollectionObjectClient(); PoxPayloadOut multipart = createCollectionObjectInstance(client.getCommonPartName(), collectionObject, null); ClientResponse<Response> res = client.create(multipart); int statusCode = res.getStatus(); // Read the response and verify that the create attempt failed. if (logger.isDebugEnabled()) { logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, Response.Status.BAD_REQUEST.getStatusCode()); // FIXME: Consider splitting off the following into its own test method. // Build a payload with invalid content, by setting a value to the // empty String, in a field (objectNumber) that requires a non-empty // value, as enforced by the service's validation routine(s). collectionObject = new CollectionobjectsCommon(); collectionObject.setObjectNumber(""); collectionObject.setDistinguishingFeatures("Distinguishing features."); objNameList = new ObjectNameList(); objNameGroups = objNameList.getObjectNameGroup(); objectNameGroup = new ObjectNameGroup(); objectNameGroup.setObjectName(OBJECT_NAME_VALUE); objNameGroups.add(objectNameGroup); collectionObject.setObjectNameList(objNameList); // Submit the request to the service and store the response. multipart = createCollectionObjectInstance(client.getCommonPartName(), collectionObject, null); res = client.create(multipart); statusCode = res.getStatus(); // Read the response and verify that the create attempt failed. if (logger.isDebugEnabled()) { logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, Response.Status.BAD_REQUEST.getStatusCode()); } // CRUD tests : READ tests // Success outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#read(java.lang.String) */ @Override @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create"}) public void read(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupRead(); // Submit the request to the service and store the response. CollectionObjectClient client = new CollectionObjectClient(); ClientResponse<String> res = client.read(knownResourceId); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if (logger.isDebugEnabled()) { logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); // Extract the common part. CollectionobjectsCommon collectionobjectCommon = extractCommonPartValue(testName, res); // Verify the number and contents of values in repeatable fields, // as created in the instance record used for testing. MeasuredPartGroupList measuredPartGroupList = collectionobjectCommon.getMeasuredPartGroupList(); Assert.assertNotNull(measuredPartGroupList, "Measured part group list was null"); List<MeasuredPartGroup> measuredPartGroups = measuredPartGroupList.getMeasuredPartGroup(); Assert.assertNotNull(measuredPartGroups, "Measured part groups were null"); Assert.assertTrue(measuredPartGroups.size() > 0, "No measured part groups were returned"); MeasuredPartGroup mpGroup = measuredPartGroups.get(0); Assert.assertNotNull(mpGroup.getMeasuredPart(), "Measured part was null"); Assert.assertEquals(mpGroup.getMeasuredPart(), MEASURED_PART, "Measured part value returned didn't match expected value"); DimensionSubGroupList dimensionSubGroupList = mpGroup.getDimensionSubGroupList(); Assert.assertNotNull(dimensionSubGroupList, "Dimension subgroup list was null"); List<DimensionSubGroup> dimensionSubGroups = dimensionSubGroupList.getDimensionSubGroup(); Assert.assertNotNull(dimensionSubGroups, "Dimension subgroups were null"); Assert.assertTrue(dimensionSubGroups.size() > 0, "No dimension subgroups were returned"); DimensionSubGroup lengthDimension = dimensionSubGroups.get(0); Assert.assertNotNull(lengthDimension, "Length dimension was null"); Assert.assertEquals(lengthDimension.getValue().setScale(5), DIMENSION_VALUE_LENGTH.setScale(5), "Dimension length value returned didn't match expected value"); /* No longer part of the "default" domain service tests for the CollectionObject record. if (logger.isDebugEnabled()) { logger.debug(testName + ": Reading Natural History part ..."); } // Currently checking only that the natural history part is non-null; // can add specific field-level checks as warranted. Object conh = extractPartValue(testName, res, getNHPartName()); Assert.assertNotNull(conh); */ } // Failure outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#readNonExistent(java.lang.String) */ @Override @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"read"}) public void readNonExistent(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupReadNonExistent(); // Submit the request to the service and store the response. CollectionObjectClient client = new CollectionObjectClient(); ClientResponse<String> res = client.read(NON_EXISTENT_ID); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if (logger.isDebugEnabled()) { logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } // CRUD tests : READ_LIST tests // Success outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#readList(java.lang.String) */ @Override @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"createList", "read"}) public void readList(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupReadList(); // Submit the request to the service and store the response. CollectionObjectClient client = new CollectionObjectClient(); ClientResponse<AbstractCommonList> res = client.readList(); AbstractCommonList list = res.getEntity(); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if (logger.isDebugEnabled()) { logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); // Optionally output additional data about list members for debugging. // the expected response(s)? if(logger.isTraceEnabled()){ AbstractCommonListUtils.ListItemsInAbstractCommonList(list, logger, testName); } } // Failure outcomes // None at present. // CRUD tests : UPDATE tests // Success outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#update(java.lang.String) */ @Override @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"read"}) public void update(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Read an existing resource that will be updated. ClientResponse<String> res = updateRetrieve(testName, knownResourceId); // Extract its common part. CollectionobjectsCommon collectionObjectCommon = extractCommonPartValue(testName, res); // Change the content of one or more fields in the common part. collectionObjectCommon.setObjectNumber("updated-" + collectionObjectCommon.getObjectNumber()); // Change the object name in the first value instance in the // object name repeatable group. ObjectNameList objNameList = collectionObjectCommon.getObjectNameList(); List<ObjectNameGroup> objNameGroups = objNameList.getObjectNameGroup(); Assert.assertNotNull(objNameGroups); Assert.assertTrue(objNameGroups.size() >= 1); String objectName = objNameGroups.get(0).getObjectName(); Assert.assertEquals(objectName, OBJECT_NAME_VALUE); String updatedObjectName = "updated-" + objectName; objNameGroups.get(0).setObjectName(updatedObjectName); collectionObjectCommon.setObjectNameList(objNameList); // Replace the existing value instances in the dimensions repeatable group // with entirely new value instances, also changing the number of such instances. MeasuredPartGroupList measuredPartGroupList = collectionObjectCommon.getMeasuredPartGroupList(); Assert.assertNotNull(measuredPartGroupList); List<MeasuredPartGroup> measuredPartGroups = measuredPartGroupList.getMeasuredPartGroup(); Assert.assertNotNull(measuredPartGroups); Assert.assertTrue(measuredPartGroups.size() > 0); MeasuredPartGroup mpGroup = measuredPartGroups.get(0); Assert.assertNotNull(mpGroup.getMeasuredPart()); DimensionSubGroupList dimensionSubGroupList = mpGroup.getDimensionSubGroupList(); Assert.assertNotNull(dimensionSubGroupList); List<DimensionSubGroup> dimensionSubGroups = dimensionSubGroupList.getDimensionSubGroup(); Assert.assertNotNull(dimensionSubGroups); int originalDimensionSubGroupSize = dimensionSubGroups.size(); Assert.assertTrue(dimensionSubGroups.size() > 0); dimensionSubGroups.clear(); DimensionSubGroup heightDimension = new DimensionSubGroup(); heightDimension.setDimension("height"); heightDimension.setMeasurementUnit(UPDATED_MEASUREMENT_UNIT); dimensionSubGroups.add(heightDimension); int updatedDimensionGroupSize = dimensionSubGroups.size(); Assert.assertTrue(updatedDimensionGroupSize > 0); Assert.assertTrue(updatedDimensionGroupSize != originalDimensionSubGroupSize); collectionObjectCommon.setMeasuredPartGroupList(measuredPartGroupList); if (logger.isDebugEnabled()) { logger.debug("sparse update that will be sent in update request:"); logger.debug(objectAsXmlString(collectionObjectCommon, CollectionobjectsCommon.class)); } // Send the changed resource to be updated and read the updated resource // from the response. res = updateSend(testName, knownResourceId, collectionObjectCommon); // Extract its common part. CollectionobjectsCommon updatedCollectionobjectCommon = extractCommonPartValue(testName, res); // Read the updated common part and verify that the resource was correctly updated. objNameList = updatedCollectionobjectCommon.getObjectNameList(); Assert.assertNotNull(objNameList); objNameGroups = objNameList.getObjectNameGroup(); Assert.assertNotNull(objNameGroups); Assert.assertTrue(objNameGroups.size() >= 1); Assert.assertEquals(updatedObjectName, objNameGroups.get(0).getObjectName(), "Data in updated object did not match submitted data."); measuredPartGroupList = collectionObjectCommon.getMeasuredPartGroupList(); Assert.assertNotNull(measuredPartGroupList); measuredPartGroups = measuredPartGroupList.getMeasuredPartGroup(); Assert.assertNotNull(measuredPartGroups); Assert.assertTrue(measuredPartGroups.size() > 0); mpGroup = measuredPartGroups.get(0); Assert.assertNotNull(mpGroup.getMeasuredPart()); dimensionSubGroupList = mpGroup.getDimensionSubGroupList(); Assert.assertNotNull(dimensionSubGroupList); dimensionSubGroups = dimensionSubGroupList.getDimensionSubGroup(); Assert.assertNotNull(dimensionSubGroups); Assert.assertTrue(dimensionSubGroups.size() > 0); Assert.assertTrue(dimensionSubGroups.size() == updatedDimensionGroupSize); Assert.assertEquals(UPDATED_MEASUREMENT_UNIT, dimensionSubGroups.get(0).getMeasurementUnit(), "Data in updated object did not match submitted data."); } /** * Update retrieve. * * @param testName the test name * @param id the id * @return the client response */ private ClientResponse<String> updateRetrieve(String testName, String id) { setupRead(); CollectionObjectClient client = new CollectionObjectClient(); ClientResponse<String> res = client.read(knownResourceId); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if (logger.isDebugEnabled()) { logger.debug(testName + ": read status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); if(logger.isDebugEnabled()){ logger.debug("got object to update with ID: " + knownResourceId); } return res; } /** * Update send. * * @param testName the test name * @param id the id * @return the client response */ private ClientResponse<String> updateSend(String testName, String id, CollectionobjectsCommon collectionObjectCommon) { setupUpdate(); PoxPayloadOut output = new PoxPayloadOut(CollectionObjectClient.SERVICE_PAYLOAD_NAME); PayloadOutputPart commonPart = output.addPart(collectionObjectCommon, MediaType.APPLICATION_XML_TYPE); CollectionObjectClient client = new CollectionObjectClient(); commonPart.setLabel(client.getCommonPartName()); ClientResponse<String> res = client.update(knownResourceId, output); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if (logger.isDebugEnabled()) { logger.debug(testName + ": read status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); return res; } // Failure outcomes // Placeholders until the three tests below can be uncommented. // See Issue CSPACE-401. /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#updateWithEmptyEntityBody(java.lang.String) */ @Override @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"read"}) public void updateWithEmptyEntityBody(String testName) throws Exception { //FIXME: Should this test really be empty? } /** * Test how the service handles XML that is not well formed, * when sent in the payload of an Update request. * * @param testName The name of this test method. This name is supplied * automatically, via reflection, by a TestNG 'data provider' in * a base class. */ @Override @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"read"}) public void updateWithMalformedXml(String testName) throws Exception { //FIXME: Should this test really be empty? } /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#updateWithWrongXmlSchema(java.lang.String) */ @Override @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"read"}) public void updateWithWrongXmlSchema(String testName) throws Exception { //FIXME: Should this test really be empty? } /* @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class, dependsOnMethods = {"create", "update", "testSubmitRequest"}) public void updateWithEmptyEntityBody(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupUpdateWithEmptyEntityBody(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getResourceURL(knownResourceId); String mediaType = MediaType.APPLICATION_XML; final String entity = ""; int statusCode = submitRequest(method, url, mediaType, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class, dependsOnMethods = {"create", "update", "testSubmitRequest"}) public void updateWithMalformedXml() throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupUpdateWithMalformedXml(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getResourceURL(knownResourceId); final String entity = MALFORMED_XML_DATA; String mediaType = MediaType.APPLICATION_XML; int statusCode = submitRequest(method, url, mediaType, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class, dependsOnMethods = {"create", "update", "testSubmitRequest"}) public void updateWithWrongXmlSchema(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupUpdateWithWrongXmlSchema(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getResourceURL(knownResourceId); String mediaType = MediaType.APPLICATION_XML; final String entity = WRONG_XML_SCHEMA_DATA; int statusCode = submitRequest(method, url, mediaType, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } */ /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#updateNonExistent(java.lang.String) */ @Override @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"update", "testSubmitRequest"}) public void updateNonExistent(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupUpdateNonExistent(); // Submit the request to the service and store the response. // Note: The ID used in this 'create' call may be arbitrary. // The only relevant ID may be the one used in updateCollectionObject(), below. CollectionObjectClient client = new CollectionObjectClient(); PoxPayloadOut multipart = createCollectionObjectInstance(client.getCommonPartName(), NON_EXISTENT_ID); ClientResponse<String> res = client.update(NON_EXISTENT_ID, multipart); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if (logger.isDebugEnabled()) { logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } /** * Test how the service handles, in an Update request, payloads * containing null values (or, in the case of String fields, * empty String values) in one or more fields in which non-empty * values are required. * * This is a test of code and/or configuration in the service's * validation routine(s). * * @param testName The name of this test method. This name is supplied * automatically, via reflection, by a TestNG 'data provider' in * a base class. * @throws Exception */ @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"read"}) public void updateWithRequiredValuesNullOrEmpty(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Read an existing record for updating. ClientResponse<String> res = updateRetrieve(testName, knownResourceId); // Extract its common part. CollectionobjectsCommon collectionObjectCommon = extractCommonPartValue(testName, res); // Update the common part with invalid content, by setting a value to // the empty String, in a field that requires a non-empty value, // as enforced by the service's validation routine(s). collectionObjectCommon.setObjectNumber(""); if (logger.isDebugEnabled()) { logger.debug(testName + " updated object"); logger.debug(objectAsXmlString(collectionObjectCommon, CollectionobjectsCommon.class)); } // Submit the request to the service and store the response. setupUpdate(); PoxPayloadOut output = new PoxPayloadOut(CollectionObjectClient.SERVICE_PAYLOAD_NAME); PayloadOutputPart commonPart = output.addPart(collectionObjectCommon, MediaType.APPLICATION_XML_TYPE); CollectionObjectClient client = new CollectionObjectClient(); commonPart.setLabel(client.getCommonPartName()); res = client.update(knownResourceId, output); int statusCode = res.getStatus(); // Read the response and verify that the update attempt failed. Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, Response.Status.BAD_REQUEST.getStatusCode()); } // CRUD tests : DELETE tests // Success outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#delete(java.lang.String) */ @Override @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create", "readList", "testSubmitRequest", "update"}) public void delete(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupDelete(); // Submit the request to the service and store the response. CollectionObjectClient client = new CollectionObjectClient(); ClientResponse<Response> res = client.delete(knownResourceId); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if (logger.isDebugEnabled()) { logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } // Failure outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#deleteNonExistent(java.lang.String) */ @Override @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"delete"}) public void deleteNonExistent(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupDeleteNonExistent(); // Submit the request to the service and store the response. CollectionObjectClient client = new CollectionObjectClient(); ClientResponse<Response> res = client.delete(NON_EXISTENT_ID); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if (logger.isDebugEnabled()) { logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } // Utility tests : tests of code used in tests above /** * Tests the code for manually submitting data that is used by several * of the methods above. * @throws Exception */ @Test(dependsOnMethods = {"create", "read"}) public void testSubmitRequest() throws Exception { testSubmitRequest(knownResourceId); } /** * Test submit request. * * @param resourceId the resource id * @throws Exception the exception */ private void testSubmitRequest(String resourceId) throws Exception { // Expected status code: 200 OK final int EXPECTED_STATUS = Response.Status.OK.getStatusCode(); // Submit the request to the service and store the response. String method = ServiceRequestType.READ.httpMethodName(); String url = getResourceURL(resourceId); int statusCode = submitRequest(method, url); // Check the status code of the response: does it match // the expected response(s)? if (logger.isDebugEnabled()) { logger.debug("testSubmitRequest: url=" + url + " status=" + statusCode); } Assert.assertEquals(statusCode, EXPECTED_STATUS); } // Utility methods used by tests above /** * Creates the collection object instance. * * @param commonPartName the common part name * @param identifier the identifier * @return the multipart output */ private PoxPayloadOut createCollectionObjectInstance(String commonPartName, String identifier) { return createCollectionObjectInstance(commonPartName, "objectNumber-" + identifier, "objectName-" + identifier); } @Override protected PoxPayloadOut createInstance(String identifier) { String commonPartName = CollectionObjectClient.SERVICE_COMMON_PART_NAME; return createCollectionObjectInstance(commonPartName, identifier); } /** * Creates the collection object instance. * * @param commonPartName the common part name * @param objectNumber the object number * @param objectName the object name * @return the multipart output */ private PoxPayloadOut createCollectionObjectInstance(String commonPartName, String objectNumber, String objectName) { CollectionobjectsCommon collectionObject = new CollectionobjectsCommon(); //REM OtherNumber remNumber = new OtherNumber(); remNumber.setNumberType("remNumber"); remNumber.setNumberValue("2271966-" + System.currentTimeMillis()); collectionObject.setRemNumber(remNumber); // Scalar fields collectionObject.setObjectNumber(objectNumber); collectionObject.setAge(AGE_VALUE); //test for null string // FIXME this can be removed when the repeatable other number list // is supported by the application layers collectionObject.setOtherNumber("urn:org.walkerart.id:123"); // Repeatable structured groups TitleGroupList titleGroupList = new TitleGroupList(); List<TitleGroup> titleGroups = titleGroupList.getTitleGroup(); Assert.assertNotNull(titleGroups); TitleGroup titleGroup = new TitleGroup(); titleGroup.setTitle("a title"); titleGroups.add(titleGroup); collectionObject.setTitleGroupList(titleGroupList); ObjectNameList objNameList = new ObjectNameList(); List<ObjectNameGroup> objNameGroups = objNameList.getObjectNameGroup(); ObjectNameGroup objectNameGroup = new ObjectNameGroup(); objectNameGroup.setObjectName(OBJECT_NAME_VALUE); objNameGroups.add(objectNameGroup); collectionObject.setObjectNameList(objNameList); MeasuredPartGroupList measuredPartGroupList = new MeasuredPartGroupList(); List<MeasuredPartGroup> measuredPartGroups = measuredPartGroupList.getMeasuredPartGroup(); Assert.assertNotNull(measuredPartGroups, "Measured part groups are null"); MeasuredPartGroup measuredPartGroup = new MeasuredPartGroup(); measuredPartGroup.setMeasuredPart(MEASURED_PART); DimensionSubGroupList dimensionSubGroupList = new DimensionSubGroupList(); List<DimensionSubGroup> dimensionSubGroups = dimensionSubGroupList.getDimensionSubGroup(); Assert.assertNotNull(dimensionSubGroups, "Dimension subgroups are null"); DimensionSubGroup lengthDimension = new DimensionSubGroup(); lengthDimension.setDimension("length"); lengthDimension.setValue(DIMENSION_VALUE_LENGTH); lengthDimension.setMeasurementUnit("cm"); dimensionSubGroups.add(lengthDimension); DimensionSubGroup widthDimension = new DimensionSubGroup(); widthDimension.setDimension("width"); widthDimension.setValue(DIMENSION_VALUE_WIDTH); widthDimension.setMeasurementUnit("m"); widthDimension.setValueQualifier(""); // test empty string dimensionSubGroups.add(widthDimension); measuredPartGroup.setDimensionSubGroupList(dimensionSubGroupList); measuredPartGroups.add(measuredPartGroup); collectionObject.setMeasuredPartGroupList(measuredPartGroupList); // Repeatable scalar fields BriefDescriptionList descriptionList = new BriefDescriptionList(); List<String> descriptions = descriptionList.getBriefDescription(); descriptions.add("Papier mache bird cow mask with horns, " + "painted red with black and yellow spots. " + "Puerto Rico. ca. 8&quot; high, 6&quot; wide, projects 10&quot; (with horns)."); descriptions.add("Acrylic rabbit mask with wings, " + "painted red with green and aquamarine spots. " + "Puerto Rico. ca. 8&quot; high, 6&quot; wide, projects 10&quot; (with wings)."); collectionObject.setBriefDescriptions(descriptionList); ResponsibleDepartmentList deptList = new ResponsibleDepartmentList(); List<String> depts = deptList.getResponsibleDepartment(); // @TODO Use properly formatted refNames for representative departments // in this example test record. The following are mere placeholders. depts.add("urn:org.collectionspace.services.department:Registrar"); depts.add("urn:org.walkerart.department:Fine Art"); collectionObject.setResponsibleDepartments(deptList); OtherNumberList otherNumList = new OtherNumberList(); List<OtherNumber> otherNumbers = otherNumList.getOtherNumber(); OtherNumber otherNumber1 = new OtherNumber(); otherNumber1.setNumberValue("101." + objectName); otherNumber1.setNumberType("integer"); otherNumbers.add(otherNumber1); OtherNumber otherNumber2 = new OtherNumber(); otherNumber2.setNumberValue("101.502.23.456." + objectName); otherNumber2.setNumberType("ipaddress"); otherNumbers.add(otherNumber2); collectionObject.setOtherNumberList(otherNumList); // Add instances of fields from an extension schema CollectionobjectsNaturalhistory conh = new CollectionobjectsNaturalhistory(); // Laramie20110524 removed for build: conh.setNhString("test-string"); // Laramie20110524 removed for build: conh.setNhInt(999); // Laramie20110524 removed for build: conh.setNhLong(9999); PoxPayloadOut multipart = createCollectionObjectInstance(commonPartName, collectionObject, conh); return multipart; } /** * Creates the collection object instance. * * @param commonPartName the common part name * @param collectionObject the collection object * @param conh the conh * @return the multipart output */ private PoxPayloadOut createCollectionObjectInstance(String commonPartName, CollectionobjectsCommon collectionObject, CollectionobjectsNaturalhistory conh) { PoxPayloadOut multipart = CollectionObjectFactory.createCollectionObjectInstance( commonPartName, collectionObject, getNHPartName(), conh); if (logger.isDebugEnabled()) { logger.debug("to be created, collectionobject common"); logger.debug(objectAsXmlString(collectionObject, CollectionobjectsCommon.class)); } if (conh != null) { if (logger.isDebugEnabled()) { logger.debug("to be created, collectionobject nhistory"); logger.debug(objectAsXmlString(conh, CollectionobjectsNaturalhistory.class)); } } return multipart; } /** * createCollectionObjectInstanceFromXml uses JAXB unmarshaller to retrieve * collectionobject from given file * @param commonPartName * @param commonPartFileName * @return * @throws Exception */ private PoxPayloadOut createCollectionObjectInstanceFromXml(String testName, String commonPartName, String commonPartFileName) throws Exception { CollectionobjectsCommon collectionObject = (CollectionobjectsCommon) getObjectFromFile(CollectionobjectsCommon.class, commonPartFileName); PoxPayloadOut multipart = new PoxPayloadOut(CollectionObjectClient.SERVICE_PAYLOAD_NAME); PayloadOutputPart commonPart = multipart.addPart(collectionObject, MediaType.APPLICATION_XML_TYPE); CollectionObjectClient client = new CollectionObjectClient(); commonPart.setLabel(client.getCommonPartName()); if (logger.isDebugEnabled()) { logger.debug(testName + " to be created, collectionobject common"); logger.debug(objectAsXmlString(collectionObject, CollectionobjectsCommon.class)); } return multipart; } /** * createCollectionObjectInstanceFromRawXml uses stringified collectionobject * retrieve from given file * @param commonPartName * @param commonPartFileName * @return * @throws Exception */ private PoxPayloadOut createCollectionObjectInstanceFromRawXml(String testName, String commonPartName, String commonPartFileName) throws Exception { PoxPayloadOut multipart = new PoxPayloadOut(CollectionObjectClient.SERVICE_PAYLOAD_NAME); String stringObject = getXmlDocumentAsString(commonPartFileName); if (logger.isDebugEnabled()) { logger.debug(testName + " to be created, collectionobject common " + "\n" + stringObject); } PayloadOutputPart commonPart = multipart.addPart(commonPartName, stringObject); // commonPart.setLabel(commonPartName); return multipart; } /** * Gets the nH part name. * * @return the nH part name */ private String getNHPartName() { return "collectionobjects_naturalhistory"; } /** * Creates the from xml file. * * @param testName the test name * @param fileName the file name * @param useJaxb the use jaxb * @return the string * @throws Exception the exception */ private String createFromXmlFile(String testName, String fileName, boolean useJaxb) throws Exception { // Perform setup. setupCreate(); PoxPayloadOut multipart = null; CollectionObjectClient client = new CollectionObjectClient(); if (useJaxb) { multipart = createCollectionObjectInstanceFromXml(testName, client.getCommonPartName(), fileName); } else { multipart = createCollectionObjectInstanceFromRawXml(testName, client.getCommonPartName(), fileName); } ClientResponse<Response> res = client.create(multipart); int statusCode = res.getStatus(); if (logger.isDebugEnabled()) { logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); String newId = extractId(res); allResourceIdsCreated.add(newId); return newId; } // FIXME: This duplicates code in read(), and should be consolidated. // This is an expedient to support reading and verifying the contents // of resources that have been created from test data XML files. private CollectionobjectsCommon readCollectionObjectCommonPart(String csid) throws Exception { String testName = "readCollectionObjectCommonPart"; setupRead(); // Submit the request to the service and store the response. CollectionObjectClient client = new CollectionObjectClient(); ClientResponse<String> res = client.read(csid); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if (logger.isDebugEnabled()) { logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); // Extract the common part. CollectionobjectsCommon collectionObject = extractCommonPartValue(testName, res); Assert.assertNotNull(collectionObject); return collectionObject; } private CollectionobjectsCommon extractCommonPartValue(String testName, ClientResponse<String> res) throws Exception { CollectionObjectClient client = new CollectionObjectClient(); PayloadInputPart payloadInputPart = extractPart(testName, res, client.getCommonPartName()); Object obj = null; if (payloadInputPart != null) { obj = payloadInputPart.getBody(); } Assert.assertNotNull(obj, testName + ": body of " + client.getCommonPartName() + " part was unexpectedly null."); CollectionobjectsCommon collectionobjectCommon = (CollectionobjectsCommon) obj; Assert.assertNotNull(collectionobjectCommon, testName + ": " + client.getCommonPartName() + " part was unexpectedly null."); return collectionobjectCommon; } private Object extractPartValue(String testName, ClientResponse<String> res, String partLabel) throws Exception { Object obj = null; PayloadInputPart payloadInputPart = extractPart(testName, res, partLabel); if (payloadInputPart != null) { obj = payloadInputPart.getElementBody(); } Assert.assertNotNull(obj, testName + ": value of part " + partLabel + " was unexpectedly null."); return obj; } private PayloadInputPart extractPart(String testName, ClientResponse<String> res, String partLabel) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testName + ": Reading part " + partLabel + " ..."); } PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); PayloadInputPart payloadInputPart = input.getPart(partLabel); Assert.assertNotNull(payloadInputPart, testName + ": part " + partLabel + " was unexpectedly null."); return payloadInputPart; } @Override protected String getServicePathComponent() { // TODO Auto-generated method stub return CollectionObjectClient.SERVICE_PATH_COMPONENT; } }
package org.mechaverse.simulation.ant.core.entity.ant; import java.io.IOException; import java.util.Arrays; import org.apache.commons.math3.random.RandomGenerator; import org.mechaverse.simulation.ant.api.AntSimulationState; import org.mechaverse.simulation.ant.api.model.Ant; import org.mechaverse.simulation.ant.api.model.Direction; import org.mechaverse.simulation.ant.api.model.Entity; import org.mechaverse.simulation.ant.api.model.EntityType; import org.mechaverse.simulation.ant.api.model.Pheromone; import org.mechaverse.simulation.ant.api.util.EntityUtil; import org.mechaverse.simulation.ant.core.ActiveEntity; import org.mechaverse.simulation.ant.core.AntSimulationUtil; import org.mechaverse.simulation.ant.core.Cell; import org.mechaverse.simulation.ant.core.CellEnvironment; import org.mechaverse.simulation.ant.core.EntityManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; /** * An ant that active in the simulation. An active ant receives sensory information about itself and * the environment and is able to perform actions. */ public final class ActiveAnt implements ActiveEntity { public static final String OUTPUT_REPLAY_DATA_KEY = "outputReplayData"; /** * Determines the action an ant should take based on the input. */ public static interface AntBehavior { void setEntity(Ant entity); /** * Sets the current input. */ void setInput(AntInput input, RandomGenerator random); /** * Returns output values based on the current input. */ AntOutput getOutput(RandomGenerator random); void onRemoveEntity(); void setState(AntSimulationState state); void updateState(AntSimulationState state); } private static final EntityType[] CARRIABLE_ENTITY_TYPES = {EntityType.DIRT, EntityType.FOOD,EntityType.ROCK}; private static final Logger logger = LoggerFactory.getLogger(ActiveAnt.class); @Value("#{properties['pheromoneInitialEnergy']}") private int pheromoneInitialEnergy; private final Ant entity; private final AntBehavior behavior; private EntityType carriedEntityType = EntityType.NONE; private final AntInput input = new AntInput(); private AntOutputDataOutputStream outputReplayDataOutputStream = new AntOutputDataOutputStream(); public ActiveAnt(Ant entity, AntBehavior behavior) { this.entity = entity; this.behavior = behavior; behavior.setEntity(entity); if (entity.getCarriedEntity() != null) { this.carriedEntityType = EntityUtil.getType(entity.getCarriedEntity()); } } @Override public void updateInput(CellEnvironment env, RandomGenerator random) { input.resetToDefault(); input.setEnergy(entity.getEnergy(), entity.getMaxEnergy()); input.setDirection(entity.getDirection()); input.setCarriedEntityType(carriedEntityType); // Cell sensor. Cell cell = env.getCell(entity); for (EntityType cellEntityType : EntityUtil.ENTITY_TYPES) { Entity cellEntity = cell.getEntity(cellEntityType); if (cellEntity != null && cellEntity != entity) { input.setCellSensor(cellEntityType); break; } } // Nest direction sensor. input.setNestDirection(env.getNestDirection(cell)); // Front cell sensor. Cell frontCell = env.getCellInDirection(cell, entity.getDirection()); if (frontCell != null) { Entity frontEntity = frontCell.getEntity(); if (frontEntity != null) { input.setFrontSensor( frontCell.getEntityType(), frontEntity.getDirection(), frontEntity.getId()); } } else { input.setFrontSensor(null, null, ""); } // Front left cell sensor. Direction frontLeftDirection = AntSimulationUtil.directionCCW(entity.getDirection()); Cell frontLeftCell = env.getCellInDirection(cell, frontLeftDirection); if (frontLeftCell != null) { Entity frontLeftEntity = frontLeftCell.getEntity(); if (frontLeftEntity != null) { input.setFrontLeftSensor(frontLeftCell.getEntityType(), frontLeftEntity.getDirection()); } } else { input.setFrontLeftSensor(null, null); } // Left cell sensor. Cell leftCell = env.getCellInDirection(cell, AntSimulationUtil.directionCCW(frontLeftDirection)); if (leftCell != null) { Entity leftEntity = leftCell.getEntity(); if (leftEntity != null) { input.setLeftSensor(leftCell.getEntityType(), leftEntity.getDirection()); } } else { input.setLeftSensor(null, null); } // Front right cell sensor. Direction frontRightDirection = AntSimulationUtil.directionCW(entity.getDirection()); Cell frontRightCell = env.getCellInDirection(cell, frontRightDirection); if (frontRightCell != null) { Entity frontRightEntity = frontRightCell.getEntity(); if (frontRightEntity != null) { input.setFrontRightSensor(frontRightCell.getEntityType(), frontRightEntity.getDirection()); } } else { input.setFrontRightSensor(null, null); } // Right cell sensor. Cell rightCell = env.getCellInDirection(cell, AntSimulationUtil.directionCW(frontRightDirection)); if (rightCell != null) { Entity rightEntity = rightCell.getEntity(); if (rightEntity != null) { input.setRightSensor(rightCell.getEntityType(), rightEntity.getDirection()); } } else { input.setRightSensor(null, null); } // Pheromone sensor. Entity pheromoneEntity = cell.getEntity(EntityType.PHEROMONE); if (pheromoneEntity != null && pheromoneEntity instanceof Pheromone) { Pheromone pheromone = (Pheromone) pheromoneEntity; input.setPheromoneType(pheromone.getValue()); } behavior.setInput(input, random); } @Override public void performAction(CellEnvironment env, EntityManager entityManager, RandomGenerator random) { AntOutput output = behavior.getOutput(random); try { outputReplayDataOutputStream.writeAntOutput(output); logger.trace("Recorded output {} for ant {}", Arrays.toString(output.getData()), entity.getId()); } catch (IOException e) {} Cell cell = env.getCell(entity); Cell frontCell = env.getCellInDirection(cell, entity.getDirection()); entity.setAge(entity.getAge() + 1); entity.setEnergy(entity.getEnergy() - 1); if (entity.getEnergy() <= 0) { behavior.onRemoveEntity(); entityManager.removeEntity(this); // Attempt to drop the carried entity. if (entity.getCarriedEntity() != null) { if (!drop(cell)) { if (!drop(frontCell)) { // Unable to drop the carried entity. Remove the entity occupying the cell and drop. entityManager.removeEntity(entity.getCarriedEntity()); } } } return; } // Consume action. if (output.shouldConsume()) { if(carriedEntityType == EntityType.FOOD) { // Consume food that the ant is carrying. if(consumeFood(entity.getCarriedEntity(), entityManager)) { entity.setCarriedEntity(null); carriedEntityType = EntityType.NONE; } } else if (consumeFood(cell.getEntity(EntityType.FOOD), entityManager)) { } else if (consumeFoodFromNest(cell.getEntity(EntityType.NEST))) {} } // Pickup / Drop action. if (carriedEntityType == EntityType.NONE && output.shouldPickUp()) { if (pickup(cell)) { } else if (pickup(frontCell)) {} } else if (carriedEntityType != EntityType.NONE && output.shouldDrop()) { if (carriedEntityType == EntityType.FOOD && drop(cell)) { } else if (drop(frontCell)) {} } // Leave pheromone action. int pheromoneType = output.shouldLeavePheromone(); if (pheromoneType > 0) { leavePheromone(cell, pheromoneType, entityManager); } // Move action. switch (output.getMoveDirection()) { case NONE: break; case FORWARD: moveForward(cell, frontCell, env); break; case BACKWARD: break; } // Turn action. switch (output.getTurnDirection()) { case NONE: break; case CLOCKWISE: AntSimulationUtil.turnCW(entity); case COUNTERCLOCKWISE: AntSimulationUtil.turnCCW(entity); } } @Override public Ant getEntity() { return entity; } @Override public EntityType getType() { return EntityType.ANT; } @Override public void setState(AntSimulationState state) { behavior.setState(state); // Output replay data will contain all outputs since the state was last set. outputReplayDataOutputStream = new AntOutputDataOutputStream(); } @Override public void updateState(AntSimulationState state) { behavior.updateState(state); try { outputReplayDataOutputStream.close(); state.getEntityReplayDataStore(entity).put( OUTPUT_REPLAY_DATA_KEY, outputReplayDataOutputStream.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void onRemoveEntity() { behavior.onRemoveEntity(); } private boolean moveForward(Cell cell, Cell frontCell, CellEnvironment env) { if (frontCell != null && canMoveToCell(frontCell)) { env.moveEntityToCell(EntityType.ANT, cell, frontCell); updateCarriedEntityLocation(); return true; } return false; } private boolean canMoveToCell(Cell cell) { // An an can move to the cell if it does not contain another ant, a barrier, a rock, or dirt. return !cell.hasEntity(EntityType.ANT) && !cell.hasEntity(EntityType.BARRIER) && !cell.hasEntity(EntityType.DIRT) && !cell.hasEntity(EntityType.ROCK); } private boolean pickup(Cell cell) { if(cell != null) { for (EntityType type : CARRIABLE_ENTITY_TYPES) { Entity carriableEntity = cell.getEntity(type); if (carriableEntity != null) { cell.removeEntity(type); entity.setCarriedEntity(carriableEntity); this.carriedEntityType = type; carriableEntity.setX(entity.getX()); carriableEntity.setY(entity.getY()); return true; } } } return false; } private boolean drop(Cell cell) { // The cell must not already have an entity of the given type. if (cell != null && cell.getEntity(carriedEntityType) == null) { Entity carriedEntity = entity.getCarriedEntity(); cell.setEntity(carriedEntity, carriedEntityType); entity.setCarriedEntity(null); carriedEntityType = EntityType.NONE; return true; } return false; } private void leavePheromone(Cell cell, int type, EntityManager entityManager) { Pheromone pheromone = new Pheromone(); pheromone.setValue(type); pheromone.setEnergy(pheromoneInitialEnergy); pheromone.setMaxEnergy(pheromoneInitialEnergy); Entity existingPheromone = cell.getEntity(EntityType.PHEROMONE); if (existingPheromone != null) { entityManager.removeEntity(existingPheromone); } cell.setEntity(pheromone, EntityType.PHEROMONE); entityManager.addEntity(pheromone); } private boolean consumeFood(Entity food, EntityManager entityManager) { if (food != null) { addEnergy(food.getEnergy()); entityManager.removeEntity(food); return true; } return false; } private boolean consumeFoodFromNest(Entity nest) { if(nest != null) { int energyNeeded = entity.getMaxEnergy() - entity.getEnergy(); int energy = energyNeeded <= nest.getEnergy() ? energyNeeded : nest.getEnergy(); addEnergy(energy); nest.setEnergy(nest.getEnergy() - energy); } return false; } private void updateCarriedEntityLocation() { Entity carriedEntity = entity.getCarriedEntity(); if (carriedEntity != null) { carriedEntity.setX(entity.getX()); carriedEntity.setY(entity.getY()); } } private void addEnergy(int amount) { int energy = entity.getEnergy() + amount; entity.setEnergy(energy <= entity.getMaxEnergy() ? energy : entity.getMaxEnergy()); } }
package org.xbill.DNS; import java.io.*; import java.text.*; import java.util.*; import org.xbill.DNS.utils.*; /** * A representation of a domain name. * * @author Brian Wellington */ public class Name { private static final int LABEL_NORMAL = 0; private static final int LABEL_COMPRESSION = 0xC0; private static final int LABEL_EXTENDED = 0x40; private static final int LABEL_MASK = 0xC0; private static final int EXT_LABEL_BITSTRING = 1; private Object [] name; private byte labels; private boolean qualified; /** The root name */ public static final Name root = new Name("."); /** The maximum number of labels in a Name */ static final int MAXLABELS = 128; /* The number of labels initially allocated. */ private static final int STARTLABELS = 4; /* Used for printing non-printable characters */ private static DecimalFormat byteFormat = new DecimalFormat(); static { byteFormat.setMinimumIntegerDigits(3); } private Name() { } private final void grow(int n) { if (n > MAXLABELS) throw new ArrayIndexOutOfBoundsException("name too long"); Object [] newarray = new Object[n]; System.arraycopy(name, 0, newarray, 0, labels); name = newarray; } private final void grow() { grow(labels * 2); } /** * Create a new name from a string and an origin * @param s The string to be converted * @param origin If the name is unqalified, the origin to be appended */ public Name(String s, Name origin) { labels = 0; name = new Object[STARTLABELS]; if (s.equals("@") && origin != null) { append(origin); qualified = true; return; } try { MyStringTokenizer st = new MyStringTokenizer(s, "."); while (st.hasMoreTokens()) { String token = st.nextToken(); if (labels == name.length) grow(); if (token.charAt(0) == '[') name[labels++] = new BitString(token); else name[labels++] = token.getBytes(); } if (st.hasMoreDelimiters()) qualified = true; else { if (origin != null) { append(origin); qualified = true; } else { /* This isn't exactly right, but it's close. * Partially qualified names are evil. */ if (Options.check("pqdn")) qualified = false; else qualified = (labels > 1); } } } catch (Exception e) { StringBuffer sb = new StringBuffer(); sb.append(s); if (origin != null) { sb.append("."); sb.append(origin); } if (e instanceof ArrayIndexOutOfBoundsException) sb.append(" has too many labels"); else if (e instanceof IOException) sb.append(" contains an invalid binary label"); else sb.append(" is invalid"); System.err.println(sb.toString()); name = null; labels = 0; } } /** * Create a new name from a string * @param s The string to be converted */ public Name(String s) { this (s, null); } /** * Create a new name from DNS wire format * @param in A stream containing the input data * @param c The compression context. This should be null unless a full * message is being parsed. */ public Name(DataByteInputStream in, Compression c) throws IOException { int len, start, pos, count = 0; Name name2; labels = 0; name = new Object[STARTLABELS]; start = in.getPos(); loop: while ((len = in.readUnsignedByte()) != 0) { switch(len & LABEL_MASK) { case LABEL_NORMAL: byte [] b = new byte[len]; in.read(b); if (labels == name.length) grow(); name[labels++] = b; count++; break; case LABEL_COMPRESSION: pos = in.readUnsignedByte(); pos += ((len & ~LABEL_MASK) << 8); name2 = (c == null) ? null : c.get(pos); if (Options.check("verbosecompression")) System.err.println("Looking at " + pos + ", found " + name2); if (name2 == null) throw new WireParseException("bad compression"); else { if (labels + name2.labels > name.length) grow(labels + name2.labels); System.arraycopy(name2.name, 0, name, labels, name2.labels); labels += name2.labels; } break loop; case LABEL_EXTENDED: int type = len & ~LABEL_MASK; switch (type) { case EXT_LABEL_BITSTRING: int bits = in.readUnsignedByte(); if (bits == 0) bits = 256; int bytes = (bits + 7) / 8; byte [] data = new byte[bytes]; in.read(data); if (labels == name.length) grow(); name[labels++] = new BitString(bits, data); count++; break; default: throw new WireParseException( "Unknown name format"); } /* switch */ break; } /* switch */ } if (c != null) { pos = start; if (Options.check("verbosecompression")) System.out.println("name = " + this + ", count = " + count); for (int i = 0; i < count; i++) { Name tname = new Name(this, i); c.add(pos, tname); if (Options.check("verbosecompression")) System.err.println("Adding " + tname + " at " + pos); if (name[i] instanceof BitString) pos += (((BitString)name[i]).bytes() + 2); else pos += (((byte [])name[i]).length + 1); } } qualified = true; } /** * Create a new name by removing labels from the beginning of an existing Name * @param d An existing Name * @param n The number of labels to remove from the beginning in the copy */ /* Skips n labels and creates a new name */ public Name(Name d, int n) { name = new Object[d.labels - n]; labels = (byte) (d.labels - n); System.arraycopy(d.name, n, name, 0, labels); qualified = d.qualified; } /** * Generates a new Name with the first n labels replaced by a wildcard * @return The wildcard name */ public Name wild(int n) { Name wild = new Name(this, n - 1); wild.name[0] = new byte[] {(byte)'*'}; return wild; } /** * Generates a new Name to be used when following a DNAME. * @return The new name, or null if the DNAME is invalid. */ public Name fromDNAME(DNAMERecord dname) { Name dnameowner = dname.getName(); Name dnametarget = dname.getTarget(); int nlabels; int saved; if (!subdomain(dnameowner)) return null; saved = labels - dnameowner.labels; nlabels = saved + dnametarget.labels; if (nlabels > MAXLABELS) return null; Name newname = new Name(); newname.labels = (byte)nlabels; newname.name = new Object[labels]; System.arraycopy(this.name, 0, newname.name, 0, saved); System.arraycopy(dnametarget.name, 0, newname.name, saved, dnametarget.labels); newname.qualified = true; return newname; } /** * Is this name a wildcard? */ public boolean isWild() { if (labels == 0 || (name[0] instanceof BitString)) return false; byte [] b = (byte []) name[0]; return (b.length == 1 && b[0] == '*'); } /** * Is this name fully qualified? */ public boolean isQualified() { return qualified; } /** * Appends the specified name to the end of the current Name */ public void append(Name d) { if (labels + d.labels > name.length) grow(labels + d.labels); System.arraycopy(d.name, 0, name, labels, d.labels); labels += d.labels; qualified = d.qualified; } /** * The length */ public short length() { short total = 0; for (int i = 0; i < labels; i++) { if (name[i] instanceof BitString) total += (((BitString)name[i]).bytes() + 2); else total += (((byte [])name[i]).length + 1); } return ++total; } /** * The number of labels */ public byte labels() { return labels; } /** * Is the current Name a subdomain of the specified name? */ public boolean subdomain(Name domain) { if (domain == null || domain.labels > labels) return false; Name tname = new Name(this, labels - domain.labels); return (tname.equals(domain)); } private String byteString(byte [] array) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; i++) { /* Ick. */ short b = (short)(array[i] & 0xFF); if (b <= 0x20 || b >= 0x7f) { sb.append('\\'); sb.append(byteFormat.format(b)); } else if (b == '"' || b == '(' || b == ')' || b == '.' || b == ';' || b == '\\' || b == '@' || b == '$') { sb.append('\\'); sb.append((char)b); } else sb.append((char)b); } return sb.toString(); } /** * Convert Name to a String */ public String toString() { StringBuffer sb = new StringBuffer(); if (labels == 0) sb.append("."); for (int i = 0; i < labels; i++) { if (name[i] instanceof BitString) sb.append(name[i]); else sb.append(byteString((byte [])name[i])); if (qualified || i < labels - 1) sb.append("."); } return sb.toString(); } /** * Convert the nth label in a Name to a String * @param n The label to be converted to a String */ public String getLabelString(int n) { if (name[n] instanceof BitString) return name[n].toString(); else return byteString((byte [])name[n]); } /** * Convert Name to DNS wire format */ public void toWire(DataByteOutputStream out, Compression c) throws IOException { for (int i = 0; i < labels; i++) { Name tname; if (i == 0) tname = this; else tname = new Name(this, i); int pos = -1; if (c != null) { pos = c.get(tname); if (Options.check("verbosecompression")) System.err.println("Looking for " + tname + ", found " + pos); } if (pos >= 0) { pos |= (LABEL_MASK << 8); out.writeShort(pos); return; } else { if (c != null) { c.add(out.getPos(), tname); if (Options.check("verbosecompression")) System.err.println("Adding " + tname + " at " + out.getPos()); } if (name[i] instanceof BitString) { out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING); out.writeByte(((BitString)name[i]).wireBits()); out.write(((BitString)name[i]).data); } else out.writeString((byte []) name[i]); } } out.writeByte(0); } /** * Convert Name to canonical DNS wire format (all lowercase) */ public void toWireCanonical(DataByteOutputStream out) throws IOException { for (int i = 0; i < labels; i++) { if (name[i] instanceof BitString) { out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING); out.writeByte(((BitString)name[i]).wireBits()); out.write(((BitString)name[i]).data); } else out.writeStringCanonical(new String((byte []) name[i])); } out.writeByte(0); } private static final byte toLower(byte b) { if (b < 'A' || b > 'Z') return b; else return (byte)(b - 'A' + 'a'); } /** * Are these two Names equivalent? */ public boolean equals(Object arg) { if (arg == null || !(arg instanceof Name)) return false; if (arg == this) return true; Name d = (Name) arg; if (d.labels != labels) return false; for (int i = 0; i < labels; i++) { if (name[i].getClass() != d.name[i].getClass()) return false; if (name[i] instanceof BitString) { if (!name[i].equals(d.name[i])) return false; } else { byte [] b1 = (byte []) name[i]; byte [] b2 = (byte []) d.name[i]; if (b1.length != b2.length) return false; for (int j = 0; j < b1.length; j++) { if (toLower(b1[j]) != toLower(b2[j])) return false; } } } return true; } /** * Computes a hashcode based on the value */ public int hashCode() { int code = labels; for (int i = 0; i < labels; i++) { if (name[i] instanceof BitString) { BitString b = (BitString) name[i]; for (int j = 0; j < b.bytes(); j++) code += ((code << 3) + b.data[i]); } else { byte [] b = (byte []) name[i]; for (int j = 0; j < b.length; j++) code += ((code << 3) + toLower(b[j])); } } return code; } public int compareTo(Object o) { Name arg = (Name) o; int compares = labels > arg.labels ? arg.labels : labels; for (int i = 1; i <= compares; i++) { Object label = name[labels - i]; Object alabel = arg.name[arg.labels - i]; if (label.getClass() != alabel.getClass()) { if (label instanceof BitString) return (-1); else return (1); } if (label instanceof BitString) { BitString bs = (BitString)label; int n = bs.compareTo(alabel); if (n != 0) return (n); } else { byte [] b = (byte []) label; byte [] ab = (byte []) alabel; for (int j = 0; j < b.length && j < ab.length; j++) { int n = toLower(b[j]) - toLower(ab[j]); if (n != 0) return (n); } if (b.length != ab.length) return (b.length - ab.length); } } return (labels - arg.labels); } }
package gov.nih.nci.calab.ui.administration; /** * This class prepares the form fields in the Create Sample page * * @author pansu */ /* CVS $Id: PreCreateSampleAction.java,v 1.12 2006-05-03 17:40:11 pansu Exp $ */ import gov.nih.nci.calab.dto.administration.ContainerBean; import gov.nih.nci.calab.service.administration.ManageSampleService; import gov.nih.nci.calab.ui.core.AbstractBaseAction; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.validator.DynaValidatorActionForm; public class PreCreateSampleAction extends AbstractBaseAction { public ActionForward executeTask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; DynaValidatorActionForm theForm = (DynaValidatorActionForm) form; String sampleNamePrefix = (String) theForm.get("sampleNamePrefix"); String lotId = (String) theForm.get("lotId"); int numContainers = Integer.parseInt((String) theForm .get("numberOfContainers")); ManageSampleService mangeSampleService = new ManageSampleService(); // set default form values if (sampleNamePrefix.length() == 0) { theForm.set("sampleNamePrefix", mangeSampleService .getDefaultSampleNamePrefix()); } if (lotId.length() == 0) { theForm.set("lotId", mangeSampleService.getDefaultLotId()); } ContainerBean[] origContainers = (ContainerBean[]) theForm .get("containers"); ContainerBean[] containers = new ContainerBean[numContainers]; // reuse containers from the previous request // set other containers to have values from the first container if (origContainers.length < numContainers) { for (int i = 0; i < origContainers.length; i++) { containers[i] = new ContainerBean(origContainers[i]); } for (int i = origContainers.length; i < numContainers; i++) { if (origContainers.length > 0) { containers[i] = new ContainerBean(origContainers[0]); } // if no containers from previous request, set them new else { containers[i] = new ContainerBean(); } } } else { for (int i = 0; i < numContainers; i++) { containers[i] = new ContainerBean(origContainers[i]); } } theForm.set("containers", containers); forward = mapping.findForward("success"); return forward; } public boolean loginRequired() { return true; } }
package org.apache.velocity.runtime.parser.node; import java.io.Writer; import java.io.IOException; import java.util.Map; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import org.apache.velocity.context.Context; import org.apache.velocity.context.InternalContextAdapter; import org.apache.velocity.runtime.Runtime; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.exception.ReferenceException; import org.apache.velocity.runtime.parser.*; import org.apache.velocity.exception.MethodInvocationException; import org.apache.velocity.context.EventCartridge; import org.apache.velocity.context.ReferenceInsertionEventHandler; import org.apache.velocity.context.NullReferenceEventHandler; /** * This class is responsible for handling the references in * VTL ($foo). * * Please look at the Parser.jjt file which is * what controls the generation of this class. * * @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a> * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> * @author <a href="mailto:Christoph.Reck@dlr.de">Christoph Reck</a> * @author <a href="mailto:kjohnson@transparent.com>Kent Johnson</a> * @version $Id: ASTReference.java,v 1.30 2001/05/17 13:04:16 geirm Exp $ */ public class ASTReference extends SimpleNode { /* Reference types */ private static final int NORMAL_REFERENCE = 1; private static final int FORMAL_REFERENCE = 2; private static final int QUIET_REFERENCE = 3; private int referenceType; private String nullString; private String rootString; private boolean escaped = false; private boolean computableReference = true; private String prefix = ""; private String firstTokenPrefix = ""; private String identifier = ""; private int numChildren = 0; public ASTReference(int id) { super(id); } public ASTReference(Parser p, int id) { super(p, id); } /** Accept the visitor. **/ public Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public Object init( InternalContextAdapter context, Object data) throws Exception { /* * init our children */ super.init( context, data ); /* * the only thing we can do in init() is getRoot() * as that is template based, not context based, * so it's thread- and context-safe */ rootString = getRoot(); numChildren = jjtGetNumChildren(); /* * we can glom these together.. both are template immutables... */ String firstToken = NodeUtils.specialText( getFirstToken() ); firstTokenPrefix = firstToken + prefix; /* * and if appropriate... */ if (numChildren > 0 ) { identifier = jjtGetChild(numChildren - 1).getFirstToken().image; } return data; } /** * gets an Object that 'is' the value of the reference * * @param o unused Object parameter * @param context context used to generate value */ public Object execute(Object o, InternalContextAdapter context) throws MethodInvocationException { /* * get the root object from the context */ Object result = getVariableValue(context, rootString); if (result == null) { return null; } /* * Iteratively work 'down' (it's flat...) the reference * to get the value, but check to make sure that * every result along the path is valid. For example: * * $hashtable.Customer.Name * * The $hashtable may be valid, but there is no key * 'Customer' in the hashtable so we want to stop * when we find a null value and return the null * so the error gets logged. */ try { for (int i = 0; i < numChildren; i++) { result = jjtGetChild(i).execute(result,context); if (result == null) { return null; } } return result; } catch( MethodInvocationException mie) { /* * someone tossed their cookies */ Runtime.error("Method " + mie.getMethodName() + " threw exception for reference $" + rootString + " in template " + context.getCurrentTemplateName() + " at " + " [" + this.getLine() + "," + this.getColumn() + "]"); mie.setReferenceName( rootString ); throw mie; } } /** * gets the value of the reference and outputs it to the * writer. * * @param context context of data to use in getting value * @param writer writer to render to */ public boolean render( InternalContextAdapter context, Writer writer) throws IOException, MethodInvocationException { Object value = execute(null, context); /* * if this reference is escaped (\$foo) then we want to do one of two things : * 1) if this is a reference in the context, then we want to print $foo * 2) if not, then \$foo (its considered shmoo, not VTL) */ if ( escaped ) { if ( value == null ) { writer.write( firstTokenPrefix ); writer.write( "\\" ); writer.write( nullString ); } else { writer.write( firstTokenPrefix ); writer.write( nullString ); } return true; } /* * the normal processing * * if we have an event cartridge, get a new value object */ EventCartridge ec = context.getEventCartridge(); if (ec != null) { value = ec.referenceInsert( nullString, value ); } /* * if value is null... */ if (value == null) { /* * write prefix twice, because it's shmoo, so the \ don't escape each other... */ writer.write( firstTokenPrefix ); writer.write( prefix ); writer.write( nullString ); if (referenceType != QUIET_REFERENCE && Runtime.getBoolean( RuntimeConstants.RUNTIME_LOG_REFERENCE_LOG_INVALID, true) ) { Runtime.warn(new ReferenceException("reference : template = " + context.getCurrentTemplateName(), this)); } return true; } else { /* * non-null processing */ writer.write( firstTokenPrefix ); writer.write( value.toString() ); return true; } } /** * Computes boolean value of this reference * Returns the actual value of reference return type * boolean, and 'true' if value is not null * * @param context context to compute value with */ public boolean evaluate( InternalContextAdapter context) throws MethodInvocationException { Object value = execute(null, context); if (value == null) { return false; } else if (value instanceof Boolean) { if (((Boolean) value).booleanValue()) return true; else return false; } else return true; } public Object value( InternalContextAdapter context) throws MethodInvocationException { return ( computableReference ? execute(null, context) : null ); } /** * Sets the value of a complex reference (something like $foo.bar) * Currently used by ASTSetReference() * * @see ASTSetDirective * * @param context context object containing this reference * @param value Object to set as value * @return true if successful, false otherwise */ public boolean setValue( InternalContextAdapter context, Object value) throws MethodInvocationException { /* * The rootOfIntrospection is the object we will * retrieve from the Context. This is the base * object we will apply reflection to. */ Object result = getVariableValue(context, rootString); if (result == null) { Runtime.error(new ReferenceException("reference set : template = " + context.getCurrentTemplateName(), this)); return false; } /* * How many child nodes do we have? */ for (int i = 0; i < numChildren - 1; i++) { result = jjtGetChild(i).execute(result, context); if (result == null) { Runtime.error(new ReferenceException("reference set : template = " + context.getCurrentTemplateName(), this)); return false; } } /* * We support two ways of setting the value in a #set($ref.foo = $value ) : * 1) ref.setFoo( value ) * 2) ref,put("foo", value ) to parallel the get() map introspection */ try { /* * first, we introspect for the set<identifier> setter method */ Class[] params = { value.getClass() }; Class c = result.getClass(); Method m = null; try { m = c.getMethod("set" + identifier, params); } catch( NoSuchMethodException nsme2) { StringBuffer sb = new StringBuffer( "set" ); sb.append( identifier ); if( Character.isLowerCase( sb.charAt(3))) { sb.setCharAt( 3 , Character.toUpperCase( sb.charAt( 3 ) ) ); } else { sb.setCharAt( 3 , Character.toLowerCase( sb.charAt( 3 ) ) ); } m = c.getMethod( sb.toString(), params); } /* * and if we get here, getMethod() didn't chuck an exception... */ Object[] args = { value }; m.invoke(result, args); } catch (NoSuchMethodException nsme) { /* * right now, we only support the Map interface */ if (result instanceof Map) { try { ((Map) result).put(identifier, value); } catch (Exception ex) { Runtime.error("ASTReference Map.put : exception : " + ex + " template = " + context.getCurrentTemplateName() + " [" + this.getLine() + "," + this.getColumn() + "]"); return false; } } else { Runtime.error("ASTReference : cannot find " + identifier + " as settable property or key to Map in" + " template = " + context.getCurrentTemplateName() + " [" + this.getLine() + "," + this.getColumn() + "]"); return false; } } catch( InvocationTargetException ite ) { /* * this is possible */ throw new MethodInvocationException( "ASTReference : Invocation of method '" + identifier + "' in " + result.getClass() + " threw exception " + ite.getTargetException().getClass(), ite.getTargetException(), identifier ); } catch( Exception e ) { /* * maybe a security exception? */ Runtime.error("ASTReference setValue() : exception : " + e + " template = " + context.getCurrentTemplateName() + " [" + this.getLine() + "," + this.getColumn() + "]"); return false; } return true; } private String getRoot() { Token t = getFirstToken(); /* * we have a special case where something like * $(\\)*!, where the user want's to see something * like $!blargh in the output, but the ! prevents it from showing. * I think that at this point, this isn't a reference. */ /* so, see if we have "\\!" */ int slashbang = t.image.indexOf("\\!"); if ( slashbang != -1 ) { /* * lets do all the work here. I would argue that if this occurrs, it's * not a reference at all, so preceeding \ characters in front of the $ * are just schmoo. So we just do the escape processing trick (even | odd) * and move on. This kind of breaks the rule pattern of $ and # but '!' really * tosses a wrench into things. */ /* * count the escapes : even # -> not escaped, odd -> escaped */ int i = 0; int len = t.image.length(); i = t.image.indexOf("$"); if (i == -1) { /* yikes! */ Runtime.error("ASTReference.getRoot() : internal error : no $ found for slashbang."); computableReference = false; nullString = t.image; return nullString; } while( i < len && t.image.charAt(i) != '\\') i++; /* ok, i is the first \ char */ int start = i; int count = 0; while( i < len && t.image.charAt(i++) == '\\' ) count++; /* * now construct the output string. We really don't care about leading * slashes as this is not a reference. It's quasi-schmoo */ nullString = t.image.substring(0,start); // prefix up to the first nullString += t.image.substring(start, start + count-1 ); // get the slashes nullString += t.image.substring(start+count); // and the rest, including the /* * this isn't a valid reference, so lets short circuit the value and set calcs */ computableReference = false; return nullString; } /* * we need to see if this reference is escaped. if so * we will clean off the leading \'s and let the * regular behavior determine if we should output this * as \$foo or $foo later on in render(). Lazyness.. */ escaped = false; if ( t.image.startsWith("\\")) { /* * count the escapes : even # -> not escaped, odd -> escaped */ int i = 0; int len = t.image.length(); while( i < len && t.image.charAt(i) == '\\' ) i++; if ( (i % 2) != 0 ) escaped = true; if (i > 0) prefix = t.image.substring(0, i / 2 ); t.image = t.image.substring(i); } /* * get the literal in case this reference isn't backed by the context at runtime */ nullString = literal(); if (t.image.startsWith("$!")) { referenceType = QUIET_REFERENCE; /* * only if we aren't escaped do we want to null the output */ if (!escaped) nullString = ""; if (t.image.startsWith("$!{")) { /* * ex : $!{provider.Title} */ return t.next.image; } else { /* * ex : $!provider.Title */ return t.image.substring(2); } } else if (t.image.equals("${")) { /* * ex : ${provider.Title} */ referenceType = FORMAL_REFERENCE; return t.next.image; } else { /* * the magic <MORE> can prepend '#' and '$' * on the front of a reference - so lets clean it * and save that info as the prefix */ String img = t.image; int loc = 0; for( loc = 0; loc < img.length(); loc++) { char c = img.charAt(loc); if ( c != ' { break; } } /* * if we have extra stuff, loc > 0 * ex. '#$foo' so attach that to * the prefix. */ if( loc > 0) { prefix = prefix + img.substring(0, loc-1); } referenceType = NORMAL_REFERENCE; // Token tt = first; // while(tt != null) // System.out.println("->" + tt.image); // tt = tt.next; return img.substring(loc); } } public Object getVariableValue(Context context, String variable) { return context.get(variable); } }
package CodeQuizServer; import java.io.Serializable; import java.util.LinkedList; import javax.swing.ImageIcon; import codequiz.Question; public class Game implements Serializable { private LinkedList<Question> questionlist = new LinkedList<Question>(); private LinkedList<QuizScenario> scenariolist = new LinkedList<QuizScenario>(); private Question question1, question2, question3, question4, question5, question6, question7, question8, question9; private QuizScenario scenario, scenario1, scenario2, scenario3, scenario4, scenario5; public Game() { System.out.println("Game: Konstruktor"); createQuestions(); createScenario(); } public void createQuestions() { System.out.println("Game: createQuestions()"); question1 = new Question( "Vilket av följande påståenden är korrekt?", "<html>Ett subsystem är en del av ett system <br> som kan fungera som ett eget system.</html>", "Ett subsystem kan inte bestå av andra subsystem", "Vattenfallsmodellen är en agil modell.", "Man måste använda ett informationssystem i lösningen som byggs medvattenfallsmodellen", "<html>Ett subsystem är en del av ett system <br> som kan fungera som ett eget system.</html>", 1); question2 = new Question( "Vilket av följande påståenden om objekt är korrekt?", "Alla objekt representerar abstraktioner av något konkret.", "Alla objekt har ett tillstånd.", "Alla objekt måste ha någon operation som utför en matematisk beräkning", "Inkapsling betyder att ett attribut inte kan ändra värde efter det att objektet skapats.", "Alla objekt har ett tillstånd.", 2); question3 = new Question("Vilket påstående om Java är felaktigt?", "Java är ett objektorienterat programspråk.", "Java kallades ursprungligen för ”D” och senare ”Oak”.", "Java utvecklades av företaget Sun Microsystems.", "Java konstruerades under 80-talets senare hälft.", "Java konstruerades under 80-talets senare hälft.", 4); question4 = new Question("Vilket påstående är korrekt?", "Ett Font-objekt beskriver färgen på text.", "Man lyssnar efter knapp-klick med en ButtonListener.", "JPanel är ett interface som kan implementeras.", "En JFrame är ett fönster.", "En JFrame är ett fönster.", 4); question5 = new Question( "Vilket påstående är korrekt om modeller?", "En modell kan inte användas för simuleringar.", "En modell måste kunna sammanfattas i ett enda diagram.", "En användbar modell måste erbjuda rätt detaljdjup.", "En modell är inte enklare/snabbare att bygga än det verkliga systemet.", "En användbar modell måste erbjuda rätt detaljdjup.", 3); question6 = new Question( "Vilket påstående nedan är korrekt?", "Man kan inte använda pseudokod för att testa om en algoritm fungerar som man tänkt.", "I pseudokod är det irrelevant att vara konsekvent med hur man skriver.", "Algoritmer går att återanvända mellan olika program.", "En algoritm är unik för just det programspråk som man implementerar algoritmen i.", "Algoritmer går att återanvända mellan olika program.", 3); question7 = new Question( "Vilket påstående är korrekt för Java?", "Programmet javac.exe kan översätta källkodsfiler till bytekodsfiler.", "Kompilatorn kan exekvera class-filer.", "Java Virtual Machine används för att editera källkodsfiler.", "Programmet java.exe används för kontroll av indentering i källkoden.", "Programmet javac.exe kan översätta källkodsfiler till bytekodsfiler.", 1); question8 = new Question( "Vilket av följande påståenden är korrekt?", "Klassen Random kan användas då man behöver slumptal i ett program.", "Ett objekt av typen String måste innehålla minst ett tecken.", "Med metoden Double.parseDouble kan man avrunda ett flyttal till två decimaler.", "Med metoden Math.max kan man erhålla det minsta tänkbara heltalet.", "Klassen Random kan användas då man behöver slumptal i ett program.", 1); question9 = new Question( "Vilket påstående är korrekt?", "Om klasserna A och B är associerade med en aggregation där A är helheten så kan ett objekt av klassen B som mest vara associerat till ett objekt av klassen A.", "En klass kan inte associera till sig själv.", "Det kan endast finnas en associationstyp mellan två klasser.", "Om navigeringsriktning är utsatt så antar man att klasserna bara kan skicka meddelanden i associationens riktning.", "Om navigeringsriktning är utsatt så antar man att klasserna bara kan skicka meddelanden i associationens riktning.", 4); setQuestion(); } public void createScenario() { scenario = new QuizScenario(new ImageIcon("src/media/Story1.jpg"), new ImageIcon("src/media/Correct1.jpg"), new ImageIcon( "src/media/Incorrect1.jpg")); scenario1 = new QuizScenario( new ImageIcon("src/media/dementorer.jpeg"), new ImageIcon( "src/media/Dementorerb.jpeg"), new ImageIcon( "src/media/dementorerv.jpeg")); scenario2 = new QuizScenario(new ImageIcon( "src/media/Scenario2intro.jpg"), new ImageIcon( "src/media/Scenario2correct.jpg"), new ImageIcon( "src/media/Scenario2inCorrect.jpg")); scenario3 = new QuizScenario(new ImageIcon( "src/media/beatrixQuestion.png"), new ImageIcon( "src/media/beatrixCorrect.png"), new ImageIcon( "src/media/beatrixIncorrect.png")); scenario4 = new QuizScenario(new ImageIcon( "src/media/MonsterBookOfMonstersQ.png"), new ImageIcon( "src/media/MonsterBookOfMonstersC.png"), new ImageIcon( "src/media/MonsterBookOfMonstersW.png")); scenario5 = new QuizScenario(new ImageIcon( "src/media/ScenarioDumbledoreIntro.jpg"), new ImageIcon( "src/media/ScenarioDumbledoreCorrect.jpg"), new ImageIcon( "src/media/ScenarioDumbledoreIncorrect.jpg")); setScenario(); } public void setQuestion() { questionlist.add(question1); questionlist.add(question2); questionlist.add(question3); questionlist.add(question4); questionlist.add(question5); questionlist.add(question6); questionlist.add(question7); questionlist.add(question8); questionlist.add(question9); } public Question getQuestion(int index) { return questionlist.get(index); } public void setScenario() { scenariolist.add(scenario); scenariolist.add(scenario1); scenariolist.add(scenario2); scenariolist.add(scenario3); scenariolist.add(scenario4); scenariolist.add(scenario5); } public QuizScenario getScenario(int index) { return scenariolist.get(index); } /** * * @return antal element i scenariolist */ public int getScenarioListSize() { return scenariolist.size(); } }
package sk.henrichg.phoneprofilesplus; import android.annotation.SuppressLint; import android.content.Context; import android.os.DeadSystemException; import android.provider.Settings; import androidx.annotation.NonNull; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.concurrent.TimeoutException; class TopExceptionHandler implements Thread.UncaughtExceptionHandler { private final Thread.UncaughtExceptionHandler defaultUEH; private final Context applicationContext; private final int actualVersionCode; static final String CRASH_FILENAME = "crash.txt"; TopExceptionHandler(Context applicationContext, int actualVersionCode) { this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); this.applicationContext = applicationContext; this.actualVersionCode = actualVersionCode; } @SuppressWarnings("StringConcatenationInLoop") public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) { // PPApplication.logE("TopExceptionHandler.uncaughtException", "defaultUEH="+defaultUEH); try { if (PPApplication.lockDeviceActivity != null) { boolean canWriteSettings;// = true; canWriteSettings = Settings.System.canWrite(applicationContext); if (canWriteSettings) { /*if (PPApplication.deviceIsOppo || PPApplication.deviceIsRealme) { if (PPApplication.screenTimeoutHandler != null) { PPApplication.screenTimeoutHandler.post(() -> { synchronized (PPApplication.rootMutex) { PPApplication.logE("TopExceptionHandler.uncaughtException", "" + PPApplication.screenTimeoutBeforeDeviceLock); String command1 = "settings put system " + Settings.System.SCREEN_OFF_TIMEOUT + " " + PPApplication.screenTimeoutBeforeDeviceLock; //if (PPApplication.isSELinuxEnforcing()) // command1 = PPApplication.getSELinuxEnforceCommand(command1, Shell.ShellContext.SYSTEM_APP); Command command = new Command(0, false, command1); //, command2); try { RootTools.getShell(false, Shell.ShellContext.SYSTEM_APP).add(command); PPApplication.commandWait(command, "TopExceptionHandler.uncaughtException"); } catch (Exception ee) { // com.stericson.rootshell.exceptions.RootDeniedException: Root Access Denied //Log.e("ActivateProfileHelper.setScreenTimeout", Log.getStackTraceString(e)); //PPApplication.recordException(e); } } }); } } else*/ if ((PPApplication.lockDeviceActivity != null) && (PPApplication.screenTimeoutWhenLockDeviceActivityIsDisplayed != 0)) Settings.System.putInt(applicationContext.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, PPApplication.screenTimeoutWhenLockDeviceActivityIsDisplayed); } } } catch (Exception ee) { //Log.e("TopExceptionHandler.uncaughtException", Log.getStackTraceString(ee)); } try { if (PPApplication.crashIntoFile) { StackTraceElement[] arr = e.getStackTrace(); String report = e.toString() + "\n\n"; report += " for (StackTraceElement anArr : arr) { report += " " + anArr.toString() + "\n"; } report += " report += " for (StackTraceElement anArr : arr) { report += " " + anArr.toString() + "\n"; } report += " // If the exception was thrown in a background thread inside // AsyncTask, then the actual exception can be found with getCause report += " Throwable cause = e.getCause(); if (cause != null) { report += cause.toString() + "\n\n"; arr = cause.getStackTrace(); for (StackTraceElement anArr : arr) { report += " " + anArr.toString() + "\n"; } } report += " logIntoFile("E", "TopExceptionHandler", report); } } catch (Exception ee) { //Log.e("TopExceptionHandler.uncaughtException", Log.getStackTraceString(ee)); } if (defaultUEH != null) { boolean ignore = false; //noinspection RedundantIfStatement if (t.getName().equals("FinalizerWatchdogDaemon") && (e instanceof TimeoutException)) { // ignore these exceptions // java.util.concurrent.TimeoutException: com.android.internal.os.BinderInternal$GcWatcher.finalize() timed out after 10 seconds ignore = true; } //if (Build.VERSION.SDK_INT >= 24) { if (e instanceof DeadSystemException) { // ignore these exceptions // these are from dead of system for example: // java.lang.RuntimeException: Unable to create service // androidx.work.impl.background.systemjob.SystemJobService: // java.lang.RuntimeException: android.os.DeadSystemException ignore = true; } // this is only for debuging, how is handled ignored exceptions //if (e instanceof java.lang.RuntimeException) { // if ((e.getMessage() != null) && (e.getMessage().equals("Test Crash"))) { // PPApplication.logE("TopExceptionHandler.uncaughtException", "it is 'Test Crash'"); // ignore = true; if (!ignore) { //Delegates to Android's error handling defaultUEH.uncaughtException(t, e); } else //Prevents the service/app from freezing System.exit(2); } else //Prevents the service/app from freezing System.exit(2); } @SuppressWarnings("SameParameterValue") private void logIntoFile(String type, String tag, String text) { try { /*File sd = Environment.getExternalStorageDirectory(); File exportDir = new File(sd, PPApplication.EXPORT_PATH); if (!(exportDir.exists() && exportDir.isDirectory())) //noinspection ResultOfMethodCallIgnored exportDir.mkdirs(); File logFile = new File(sd, PPApplication.EXPORT_PATH + "/" + CRASH_FILENAME);*/ File path = applicationContext.getExternalFilesDir(null); File logFile = new File(path, CRASH_FILENAME); if (logFile.length() > 1024 * 10000) resetLog(); if (!logFile.exists()) { //noinspection ResultOfMethodCallIgnored logFile.createNewFile(); } //BufferedWriter for performance, true to set append to file flag BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("d.MM.yy HH:mm:ss:S"); String time = sdf.format(Calendar.getInstance().getTimeInMillis()); String log = time + " buf.append(log); buf.newLine(); buf.flush(); buf.close(); } catch (IOException ee) { //Log.e("TopExceptionHandler.logIntoFile", Log.getStackTraceString(ee)); } } private void resetLog() { /*File sd = Environment.getExternalStorageDirectory(); File exportDir = new File(sd, PPApplication.EXPORT_PATH); if (!(exportDir.exists() && exportDir.isDirectory())) //noinspection ResultOfMethodCallIgnored exportDir.mkdirs(); File logFile = new File(sd, PPApplication.EXPORT_PATH + "/" + CRASH_FILENAME);*/ File path = applicationContext.getExternalFilesDir(null); File logFile = new File(path, CRASH_FILENAME); //noinspection ResultOfMethodCallIgnored logFile.delete(); } }
package com.intellij.codeInsight.daemon.impl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Condition; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; public class CollectHighlightsUtil { private static final ExtensionPointName<Condition<PsiElement>> EP_NAME = ExtensionPointName.create("com.intellij.elementsToHighlightFilter"); private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.CollectHighlightsUtil"); private CollectHighlightsUtil() { } @NotNull public static List<PsiElement> getElementsInRange(PsiElement root, final int startOffset, final int endOffset) { return getElementsInRange(root, startOffset, endOffset, false); } @NotNull public static List<PsiElement> getElementsInRange(@NotNull PsiElement root, final int startOffset, final int endOffset, boolean includeAllParents) { PsiElement commonParent = findCommonParent(root, startOffset, endOffset); if (commonParent == null) return new ArrayList<PsiElement>(); final List<PsiElement> list = getElementsToHighlight(commonParent, startOffset, endOffset); PsiElement parent = commonParent; while (parent != null && parent != root) { list.add(parent); parent = includeAllParents ? parent.getParent() : null; } list.add(root); return list; } private static List<PsiElement> getElementsToHighlight(final PsiElement commonParent, final int startOffset, final int endOffset) { final List<PsiElement> result = new ArrayList<PsiElement>(); final int currentOffset = commonParent.getTextRange().getStartOffset(); final Condition<PsiElement>[] filters = Extensions.getExtensions(EP_NAME); final PsiElementVisitor visitor = new PsiRecursiveElementVisitor() { int offset = currentOffset; @Override public void visitElement(PsiElement element) { for (Condition<PsiElement> filter : filters) { if (!filter.value(element)) return; } PsiElement child = element.getFirstChild(); if (child != null) { // composite element while (child != null) { if (offset > endOffset) break; int start = offset; child.accept(this); if (startOffset <= start && offset <= endOffset) result.add(child); child = child.getNextSibling(); } } else { // leaf element offset += element.getTextLength(); } } }; commonParent.accept(visitor); return result; } @Nullable public static PsiElement findCommonParent(final PsiElement root, final int startOffset, final int endOffset) { if (startOffset == endOffset) return null; final PsiElement left = findElementAtInRoot(root, startOffset); PsiElement right = findElementAtInRoot(root, endOffset - 1); if (left == null || right == null) return null; PsiElement commonParent = PsiTreeUtil.findCommonParent(left, right); LOG.assertTrue(commonParent != null); LOG.assertTrue(commonParent.getTextRange() != null); while (commonParent.getParent() != null && commonParent.getTextRange().equals(commonParent.getParent().getTextRange())) { commonParent = commonParent.getParent(); } return commonParent; } @Nullable private static PsiElement findElementAtInRoot(final PsiElement root, final int offset) { if (root instanceof PsiFile) { return ((PsiFile)root).getViewProvider().findElementAt(offset, root.getLanguage()); } return root.findElementAt(offset); } public static boolean isOutsideSourceRootJavaFile(@Nullable PsiFile psiFile) { return psiFile != null && psiFile.getFileType() == StdFileTypes.JAVA && isOutsideSourceRoot(psiFile); } public static boolean isOutsideSourceRoot(@Nullable PsiFile psiFile) { if (psiFile == null) return false; if (psiFile instanceof PsiCodeFragment) return false; final VirtualFile file = psiFile.getVirtualFile(); if (file == null) return false; final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(psiFile.getProject()).getFileIndex(); return !projectFileIndex.isInSource(file) && !projectFileIndex.isInLibraryClasses(file); } }
package net.jenet; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * Holds information about JeNet events. * Events are returned by the {@link net.jenet.Host#service(int) Host.service} method * to indicate that something happened. * @author Dizan Vasquez */ public class Event { public enum TYPE { /** * A peer has connected to this host. */ CONNECTED, /** * A peer has disconnected from this host. */ DISCONNECTED, /** * A packet has been received. */ RECEIVED, /** * Nothing happened. */ NONE, /** * An communication error ocurred. */ ERROR } protected int channelID; protected Packet packet; protected Peer peer; public TYPE type; Event() { type = TYPE.NONE; } /** * Returns the ID of the channel related to this event. * @return channelID. */ public int getChannelID() { return channelID; } /** * Returns the packet related to this event. * This is different from null only for <code>RECEIVED</code> * events. * @return Returns the packet. */ public Packet getPacket() { return packet; } /** * Returns the peer which originated this event. * @return Returns the peer. */ public Peer getPeer() { return peer; } /** * Return the event's type * @return Returns the type. */ public TYPE getType() { return type; } /** * @param channelID * The channelID to set. */ void setChannelID( int channelID ) { this.channelID = channelID; } /** * @param packet * The packet to set. */ void setPacket( Packet packet ) { this.packet = packet; } /** * @param peer * The peer to set. */ void setPeer( Peer peer ) { this.peer = peer; } /** * @param type * The type to set. */ void setType( TYPE type ) { this.type = type; } public String toString() { return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE ); } }
package com.intellij.vcs.log.statistics; import com.intellij.internal.statistic.beans.UsageDescriptor; import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector; import com.intellij.internal.statistic.service.fus.collectors.UsageDescriptorKeyValidator; import com.intellij.internal.statistic.utils.PluginInfoDetectorKt; import com.intellij.internal.statistic.utils.StatisticsUtilKt; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.vcs.log.VcsLogFilterCollection; import com.intellij.vcs.log.impl.*; import com.intellij.vcs.log.ui.VcsLogUiImpl; import com.intellij.vcs.log.ui.highlighters.VcsLogHighlighterFactory; import com.intellij.vcs.log.ui.table.GraphTableModel; import org.jetbrains.annotations.NotNull; import java.util.*; import static com.intellij.vcs.log.impl.MainVcsLogUiProperties.*; import static com.intellij.vcs.log.ui.VcsLogUiImpl.LOG_HIGHLIGHTER_FACTORY_EP; import static java.util.Arrays.asList; public class VcsLogFeaturesCollector extends ProjectUsagesCollector { @NotNull @Override public Set<UsageDescriptor> getUsages(@NotNull Project project) { VcsProjectLog projectLog = VcsProjectLog.getInstance(project); if (projectLog != null) { VcsLogUiImpl ui = projectLog.getMainLogUi(); if (ui != null) { MainVcsLogUiProperties properties = ui.getProperties(); VcsLogUiProperties defaultProperties = createDefaultPropertiesInstance(); Set<UsageDescriptor> usages = ContainerUtil.newHashSet(); addBooleanUsage(properties, defaultProperties, usages, "details", CommonUiProperties.SHOW_DETAILS); addBooleanUsage(properties, defaultProperties, usages, "diffPreview", CommonUiProperties.SHOW_DIFF_PREVIEW); addBooleanUsage(properties, defaultProperties, usages, "parentChanges", SHOW_CHANGES_FROM_PARENTS); addBooleanUsage(properties, defaultProperties, usages, "onlyAffectedChanges", SHOW_ONLY_AFFECTED_CHANGES); addBooleanUsage(properties, defaultProperties, usages, "long.edges", SHOW_LONG_EDGES); addEnumUsage(properties, defaultProperties, usages, "sort", BEK_SORT_TYPE); if (ui.getColorManager().isMultipleRoots()) { addBooleanUsage(properties, defaultProperties, usages, "roots", CommonUiProperties.SHOW_ROOT_NAMES); } addBooleanUsage(properties, defaultProperties, usages, "labels.compact", COMPACT_REFERENCES_VIEW); addBooleanUsage(properties, defaultProperties, usages, "labels.showTagNames", SHOW_TAG_NAMES); addBooleanUsage(properties, defaultProperties, usages, "textFilter.regex", TEXT_FILTER_REGEX); addBooleanUsage(properties, defaultProperties, usages, "textFilter.matchCase", TEXT_FILTER_MATCH_CASE); for (VcsLogHighlighterFactory factory : LOG_HIGHLIGHTER_FACTORY_EP.getExtensions(project)) { if (factory.showMenuItem()) { addBooleanUsage(properties, defaultProperties, usages, "highlighter." + getFactoryIdSafe(factory), VcsLogHighlighterProperty.get(factory.getId())); } } for (VcsLogFilterCollection.FilterKey<?> key : VcsLogFilterCollection.STANDARD_KEYS) { if (properties.getFilterValues(key.getName()) != null) { usages.add(StatisticsUtilKt.getBooleanUsage(key.getName() + "Filter", true)); } } Set<Integer> currentColumns = ContainerUtil.newHashSet(properties.get(CommonUiProperties.COLUMN_ORDER)); Set<Integer> defaultColumns = ContainerUtil.newHashSet(defaultProperties.get(CommonUiProperties.COLUMN_ORDER)); for (int column : GraphTableModel.DYNAMIC_COLUMNS) { if (currentColumns.contains(column) != defaultColumns.contains(column)) { usages.add(StatisticsUtilKt.getBooleanUsage(StringUtil.toLowerCase(GraphTableModel.COLUMN_NAMES[column]) + "Column", currentColumns.contains(column))); } } List<String> tabs = projectLog.getTabsManager().getTabs(); usages.add(StatisticsUtilKt.getCountingUsage("additionalTabs.count", tabs.size(), asList(0, 1, 2, 3, 4, 8))); return usages; } } return Collections.emptySet(); } @NotNull private static String getFactoryIdSafe(@NotNull VcsLogHighlighterFactory factory) { if (PluginInfoDetectorKt.getPluginInfo(factory.getClass()).isDevelopedByJetBrains()) { return UsageDescriptorKeyValidator.ensureProperKey(factory.getId()); } return "THIRD_PARTY"; } private static void addBooleanUsage(@NotNull VcsLogUiProperties properties, @NotNull VcsLogUiProperties defaultProperties, @NotNull Set<? super UsageDescriptor> usages, @NotNull String usageName, @NotNull VcsLogUiProperty<Boolean> property) { addUsageIfNotDefault(properties, defaultProperties, usages, property, value -> StatisticsUtilKt.getBooleanUsage(usageName, value)); } private static void addEnumUsage(@NotNull VcsLogUiProperties properties, @NotNull VcsLogUiProperties defaultProperties, @NotNull Set<? super UsageDescriptor> usages, @NotNull String usageName, @NotNull VcsLogUiProperty<? extends Enum> property) { addUsageIfNotDefault(properties, defaultProperties, usages, property, value -> StatisticsUtilKt.getEnumUsage(usageName, value)); } private static <T> void addUsageIfNotDefault(@NotNull VcsLogUiProperties properties, @NotNull VcsLogUiProperties defaultProperties, @NotNull Set<? super UsageDescriptor> usages, @NotNull VcsLogUiProperty<T> property, @NotNull Function<? super T, ? extends UsageDescriptor> createUsage) { if (!properties.exists(property)) return; T value = properties.get(property); if (!Objects.equals(defaultProperties.get(property), value)) { usages.add(createUsage.fun(value)); } } @NotNull private static VcsLogUiProperties createDefaultPropertiesInstance() { return new VcsLogUiPropertiesImpl(new VcsLogApplicationSettings()) { @NotNull private final State myState = new State(); @NotNull @Override public State getState() { return myState; } @Override public void addRecentlyFilteredGroup(@NotNull String filterName, @NotNull Collection<String> values) { throw new UnsupportedOperationException(); } @NotNull @Override public List<List<String>> getRecentlyFilteredGroups(@NotNull String filterName) { throw new UnsupportedOperationException(); } @Override public void loadState(@NotNull Object state) { throw new UnsupportedOperationException(); } }; } @NotNull @Override public String getGroupId() { return "vcs.log.ui"; } }
package com.akjava.gwt.three.client.js.core; import com.akjava.gwt.three.client.gwt.core.Intersect; import com.akjava.gwt.three.client.js.cameras.Camera; import com.akjava.gwt.three.client.js.math.Ray; import com.akjava.gwt.three.client.js.math.Vector3; import com.akjava.gwt.three.client.js.scenes.Scene; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; /** * Projects points between spaces. */ public class Projector extends JavaScriptObject { protected Projector() { } public final native Ray gwtCreateRay(int mx,int my,int sw,int sh,Camera camera)/*-{ var vector = new $wnd.THREE.Vector3( ( mx / sw ) * 2 - 1, - ( my / sh ) * 2 + 1, 0.5 ); this.unprojectVector( vector, camera ); var ray = new $wnd.THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() ); return ray; }-*/; public final JsArray<Intersect> gwtPickIntersectsByList(int mx,int my,int sw,int sh,Camera camera,Iterable<Object3D> objects){ @SuppressWarnings("unchecked") JsArray<Object3D> array=(JsArray<Object3D>) JsArray.createArray(); for(Object3D obj:objects){ array.push(obj); } return gwtPickIntersects(mx, my, sw, sh, camera, array); } public final native JsArray<Intersect> gwtPickIntersects(int mx,int my,int sw,int sh,Camera camera,JsArray<Object3D> objects)/*-{ var vector = new $wnd.THREE.Vector3( ( mx / sw ) * 2 - 1, - ( my / sh ) * 2 + 1, 0.5 ); this.unprojectVector( vector, camera ); var ray = new $wnd.THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() ); return ray.intersectObjects( objects ); }-*/; public final native JsArray<Intersect> gwtPickIntersectsByObject(int mx,int my,int sw,int sh,Camera camera,Object3D object)/*-{ var vector = new $wnd.THREE.Vector3( ( mx / sw ) * 2 - 1, - ( my / sh ) * 2 + 1, 0.5 ); this.unprojectVector( vector, camera ); var ray = new $wnd.THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() ); return ray.intersectObject( object ); }-*/; /** * Projects a vector with the camera. Caution, this method changes 'vector'. * @param vector * @param camera * @return projected vector */ public final native Vector3 projectVector(Vector3 vector, Camera camera)/*-{ return this.projectVector(vector, camera); }-*/; /** * Unprojects a vector with the camera. Caution, this method changes 'vector'. * @param vector * @param camera * @return unprojected vector */ public final native Vector3 unprojectVector(Vector3 vector, Camera camera)/*-{ return this.unprojectVector(vector, camera); }-*/; /** * Translates a 2D point from NDC (Normalized Device Coordinates) to a Raycaster that can be used for picking. NDC * range from [-1..1] in x (left to right) and [1.0 .. -1.0] in y (top to bottom). * @param vector * @param camera * @return {@link Raycaster} */ public final native Raycaster pickingRay(Vector3 vector, Camera camera)/*-{ return this.pickingRay(vector, camera); }-*/; /** * Transforms a 3D scene object into 2D render data that can be rendered in a screen with your renderer of choice, * projecting and clipping things out according to the used camera. If the scene were a real scene, this method * would be the equivalent of taking a picture with the camera (and developing the film would be the next step, * using a Renderer). * @param scene scene to project. * @param camera camera to use in the projection. * @param sortObjects * @param sortElements select whether to sort elements using the Painter's algorithm. * @return projected scene */ public final native JavaScriptObject projectScene(Scene scene, Camera camera, Object sortObjects, Object sortElements)/*-{ return this.projectScene(scene, camera, sortObjects, sortElements); }-*/; }
package com.biermacht.brews.frontend; import java.util.ArrayList; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.EditText; import android.widget.TextView; import android.widget.Spinner; import com.biermacht.brews.R; import com.biermacht.brews.frontend.adapters.IngredientSpinnerAdapter; import com.biermacht.brews.frontend.adapters.SpinnerAdapter; import com.biermacht.brews.ingredient.Fermentable; import com.biermacht.brews.ingredient.Ingredient; import com.biermacht.brews.recipe.Recipe; import com.biermacht.brews.utils.IngredientHandler; import com.biermacht.brews.utils.Utils; import android.view.*; public class AddGrainActivity extends Activity implements OnClickListener { IngredientHandler ingredientHandler; private Spinner grainTypeSpinner; private EditText grainNameEditText; private EditText grainColorEditText; private EditText grainGravEditText; private EditText grainWeightEditText; private EditText grainTimeEditText; private TextView grainTypeTextView; private TextView boilSteepTextView; private ArrayList<Ingredient> grainArray; private Recipe mRecipe; Fermentable fermentable; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_grain); // Set icon as back button getActionBar().setDisplayHomeAsUpEnabled(true); // Set up Ingredient Handler ingredientHandler = MainActivity.ingredientHandler; // Set list of ingredients to show grainArray = ingredientHandler.getFermentablesList(); // Get recipe from calling activity long id = getIntent().getLongExtra(Utils.INTENT_RECIPE_ID, -1); mRecipe = Utils.getRecipeWithId(id); // Initialize views and such here grainNameEditText = (EditText) findViewById(R.id.grain_name_edit_text); grainColorEditText = (EditText) findViewById(R.id.grain_color_edit_text); grainGravEditText = (EditText) findViewById(R.id.grain_grav_edit_text); grainWeightEditText = (EditText) findViewById(R.id.grain_weight_edit_text); grainTimeEditText = (EditText) findViewById(R.id.time_edit_text); grainTypeTextView = (TextView) findViewById(R.id.fermentable_type_view); boilSteepTextView = (TextView) findViewById(R.id.time_title); // Set up grain type spinner grainTypeSpinner = (Spinner) findViewById(R.id.grain_type_spinner); IngredientSpinnerAdapter adapter = new IngredientSpinnerAdapter(this, grainArray); adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); grainTypeSpinner.setAdapter(adapter); grainTypeSpinner.setSelection(0); // Handle beer type selector here grainTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { fermentable = (Fermentable) grainArray.get(position); // Set whether we want to show name field if (fermentable.getName().equals("Custom Fermentable")) { grainNameEditText.setVisibility(View.VISIBLE); findViewById(R.id.grain_name_title).setVisibility(View.VISIBLE); } else { grainNameEditText.setVisibility(View.GONE); findViewById(R.id.grain_name_title).setVisibility(View.GONE); } // Set weather we show boil or steep if (mRecipe.getType().equals(Recipe.EXTRACT)) { if (fermentable.getFermentableType().equals(Fermentable.EXTRACT)) { boilSteepTextView.setText(R.string.boil_time); grainTimeEditText.setText(mRecipe.getBoilTime() + ""); } else if (fermentable.getFermentableType().equals(Fermentable.GRAIN)) { boilSteepTextView.setText(R.string.steep_time); grainTimeEditText.setText(15 + ""); } else { boilSteepTextView.setText("Time"); } } else { // TODO: Partial Mash / All Grain } grainNameEditText.setText(fermentable.getName()); grainColorEditText.setText(String.format("%2.2f", fermentable.getLovibondColor())); grainGravEditText.setText(String.format("%2.3f", fermentable.getGravity())); grainWeightEditText.setText(1 +""); grainTimeEditText.setText(String.format("%d", mRecipe.getBoilTime())); grainTypeTextView.setText(fermentable.getFermentableType()); } public void onNothingSelected(AdapterView<?> parentView) { // This is never reached? } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_add_ingredient, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } public void onClick(View v) { // if "SUBMIT" button pressed if (v.getId() == R.id.new_grain_submit_button) { String grainName = grainNameEditText.getText().toString(); double color = Double.parseDouble(grainColorEditText.getText().toString()); double grav = Double.parseDouble(grainGravEditText.getText().toString()); double weight = Double.parseDouble(grainWeightEditText.getText().toString()); int cookTime = Integer.parseInt(grainTimeEditText.getText().toString()); int endTime = mRecipe.getBoilTime(); int startTime = endTime - cookTime; String fermType = grainTypeTextView.getText().toString(); if (startTime > mRecipe.getBoilTime()) startTime = mRecipe.getBoilTime(); fermentable.setName(grainName); fermentable.setLovibondColor(color); fermentable.setGravity(grav); fermentable.setDisplayAmount(weight); fermentable.setFermentableType(fermType); fermentable.setStartTime(startTime); fermentable.setEndTime(endTime); mRecipe.addIngredient(fermentable); mRecipe.update(); Utils.updateRecipe(mRecipe); finish(); } // if "CANCEL" button pressed if (v.getId() == R.id.cancel_button) { finish(); } } }
package org.jetbrains.plugins.groovy.lang.psi.util; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.util.PropertyUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod; /** * @author ilyas */ public class GroovyPropertyUtils { private GroovyPropertyUtils() { } @Nullable public static PsiMethod findSetterForField(PsiField field) { final PsiClass containingClass = field.getContainingClass(); final Project project = field.getProject(); final String propertyName = PropertyUtil.suggestPropertyName(project, field); final boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC); return findPropertySetter(containingClass, propertyName, isStatic, true); } @Nullable public static PsiMethod findGetterForField(PsiField field) { final PsiClass containingClass = field.getContainingClass(); final Project project = field.getProject(); final String propertyName = PropertyUtil.suggestPropertyName(project, field); final boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC); return PropertyUtil.findPropertyGetter(containingClass, propertyName, isStatic, true); } @Nullable public static PsiMethod findPropertySetter(PsiClass aClass, String propertyName, boolean isStatic, boolean checkSuperClasses) { if (aClass == null) return null; PsiMethod[] methods; if (checkSuperClasses) { methods = aClass.getAllMethods(); } else { methods = aClass.getMethods(); } for (PsiMethod method : methods) { if (method.hasModifierProperty(PsiModifier.STATIC) != isStatic) continue; if (isSimplePropertySetter(method)) { if (getPropertyNameBySetter(method).equals(propertyName)) { return method; } } } return null; } @Nullable public static PsiMethod findPropertyGetter(PsiClass aClass, String propertyName, boolean isStatic, boolean checkSuperClasses) { if (aClass == null) return null; PsiMethod[] methods; if (checkSuperClasses) { methods = aClass.getAllMethods(); } else { methods = aClass.getMethods(); } for (PsiMethod method : methods) { if (method.hasModifierProperty(PsiModifier.STATIC) != isStatic) continue; if (isSimplePropertyGetter(method)) { if (getPropertyNameByGetter(method).equals(propertyName)) { return method; } } } return null; } public static boolean isSimplePropertyAccessor(PsiMethod method) { return isSimplePropertyGetter(method) || isSimplePropertySetter(method); }//do not check return type public static boolean isSimplePropertyGetter(PsiMethod method) { return isSimplePropertyGetter(method, null); }//do not check return type public static boolean isSimplePropertyGetter(PsiMethod method, String propertyName) { if (method == null || method.isConstructor()) return false; if (method.getParameterList().getParametersCount() != 0) return false; if (!isGetterName(method.getName())) return false; return (propertyName == null || propertyName.equals(getPropertyNameByGetter(method))) && method.getReturnType() != PsiType.VOID; } public static boolean isSimplePropertySetter(PsiMethod method) { return isSimplePropertySetter(method, null); } public static boolean isSimplePropertySetter(PsiMethod method, String propertyName) { if (method == null || method.isConstructor()) return false; if (method.getParameterList().getParametersCount() != 1) return false; if (!isSetterName(method.getName())) return false; return propertyName == null || propertyName.equals(getPropertyNameBySetter(method)); } public static String getPropertyNameByGetter(PsiMethod getterMethod) { if (getterMethod instanceof GrAccessorMethod) { return ((GrAccessorMethod)getterMethod).getProperty().getName(); } @NonNls String methodName = getterMethod.getName(); if (methodName.startsWith("get") && methodName.length() > 3) { return StringUtil.decapitalize(methodName.substring(3)); } else if (methodName.startsWith("is") && methodName.length() > 2 && PsiType.BOOLEAN.equals(getterMethod.getReturnType())) { return StringUtil.decapitalize(methodName.substring(2)); } return methodName; } public static String getPropertyNameBySetter(PsiMethod setterMethod) { if (setterMethod instanceof GrAccessorMethod) { return ((GrAccessorMethod)setterMethod).getProperty().getName(); } @NonNls String methodName = setterMethod.getName(); if (methodName.startsWith("set") && methodName.length() > 3) { return StringUtil.decapitalize(methodName.substring(3)); } else { return methodName; } } public static String getPropertyName(PsiMethod accessor) { if (isSimplePropertyGetter(accessor)) return getPropertyNameByGetter(accessor); if (isSimplePropertySetter(accessor)) return getPropertyNameBySetter(accessor); return accessor.getName(); } public static boolean isGetterName(@NotNull String name) { if (name.startsWith("get") && name.length() > 3 && isUpperCase(name.charAt(3))) return true; if (name.startsWith("is") && name.length() > 2 && isUpperCase(name.charAt(2))) return true; return false; } public static boolean isSetterName(String name) { return name != null && name.startsWith("set") && name.length() > 3 && isUpperCase(name.charAt(3)); } public static boolean isProperty(@Nullable PsiClass aClass, @Nullable String propertyName, boolean isStatic) { if (aClass == null || propertyName == null) return false; final PsiField field = aClass.findFieldByName(propertyName, true); if (field instanceof GrField && ((GrField)field).isProperty() && field.hasModifierProperty(PsiModifier.STATIC) == isStatic) return true; final PsiMethod getter = findPropertyGetter(aClass, propertyName, isStatic, true); if (getter != null && getter.hasModifierProperty(PsiModifier.PUBLIC)) return true; final PsiMethod setter = findPropertySetter(aClass, propertyName, isStatic, true); return setter != null && setter.hasModifierProperty(PsiModifier.PUBLIC); } public static boolean isProperty(GrField field) { final PsiClass clazz = field.getContainingClass(); return isProperty(clazz, field.getName(), field.hasModifierProperty(PsiModifier.STATIC)); } private static boolean isUpperCase(char c) { return Character.toUpperCase(c) == c; } public static boolean canBePropertyName(String name) { return !(name.length() > 1 && Character.isUpperCase(name.charAt(1)) && Character.isLowerCase(name.charAt(0))); } }
package org.apereo.cas.ticket.registry; import com.google.common.collect.ImmutableSet; import com.mongodb.client.ListIndexesIterable; import com.mongodb.client.MongoCollection; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.commons.lang3.StringUtils; import org.apereo.cas.mongo.MongoDbConnectionFactory; import org.apereo.cas.ticket.BaseTicketSerializers; import org.apereo.cas.ticket.Ticket; import org.apereo.cas.ticket.TicketCatalog; import org.apereo.cas.ticket.TicketDefinition; import org.bson.Document; import org.apereo.cas.ticket.TicketState; import org.hjson.JsonValue; import org.hjson.Stringify; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.index.Index; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.stream.Collectors; /** * A Ticket Registry storage backend based on MongoDB. * * @author Misagh Moayyed * @since 5.1.0 */ @Slf4j public class MongoDbTicketRegistry extends AbstractTicketRegistry { private static final Query SELECT_ALL_NAMES_QUERY = new Query(Criteria.where(TicketHolder.FIELD_NAME_ID).regex(".+")); private static final ImmutableSet<String> MONGO_INDEX_KEYS = ImmutableSet.of("v", "key", "name", "ns"); private final TicketCatalog ticketCatalog; private final MongoOperations mongoTemplate; private final boolean dropCollection; public MongoDbTicketRegistry(final TicketCatalog ticketCatalog, final MongoOperations mongoTemplate, final boolean dropCollection) { this.ticketCatalog = ticketCatalog; this.mongoTemplate = mongoTemplate; this.dropCollection = dropCollection; createTicketCollections(); LOGGER.info("Configured MongoDb Ticket Registry instance with available collections: [{}]", mongoTemplate.getCollectionNames()); } private MongoCollection createTicketCollection(final TicketDefinition ticket, final MongoDbConnectionFactory factory) { val collectionName = ticket.getProperties().getStorageName(); LOGGER.debug("Setting up MongoDb Ticket Registry instance [{}]", collectionName); factory.createCollection(mongoTemplate, collectionName, this.dropCollection); LOGGER.debug("Creating indices on collection [{}] to auto-expire documents...", collectionName); val collection = mongoTemplate.getCollection(collectionName); val index = new Index().on(TicketHolder.FIELD_NAME_EXPIRE_AT, Sort.Direction.ASC).expire(ticket.getProperties().getStorageTimeout()); removeDifferingIndexIfAny(collection, index); mongoTemplate.indexOps(TicketHolder.class).ensureIndex(index); return collection; } /** * Remove any index with the same indexKey but differing indexOptions in anticipation of recreating it. * @param collection The collection to check the indexes of * @param index The index to find */ private void removeDifferingIndexIfAny(final MongoCollection collection, final Index index) { final ListIndexesIterable<Document> indexes = collection.listIndexes(); boolean indexExistsWithDifferentOptions = false; for (final var existingIndex : indexes) { final boolean keyMatches = existingIndex.get("key").equals(index.getIndexKeys()); final boolean optionsMatch = index.getIndexOptions().entrySet().stream().allMatch(entry -> entry.getValue().equals(existingIndex.get(entry.getKey()))); final boolean noExtraOptions = existingIndex.keySet().stream().allMatch(key -> MONGO_INDEX_KEYS.contains(key) || index.getIndexOptions().keySet().contains(key)); indexExistsWithDifferentOptions |= keyMatches && !(optionsMatch && noExtraOptions); } if (indexExistsWithDifferentOptions) { LOGGER.debug("Removing MongoDb index [{}] from [{}] because it appears to already exist in a different form", index.getIndexKeys(), collection.getNamespace()); collection.dropIndex(index.getIndexKeys()); } } private void createTicketCollections() { val definitions = ticketCatalog.findAll(); val factory = new MongoDbConnectionFactory(); definitions.forEach(t -> { val c = createTicketCollection(t, factory); LOGGER.debug("Created MongoDb collection configuration for [{}]", c.getNamespace().getFullName()); }); } @Override public Ticket updateTicket(final Ticket ticket) { LOGGER.debug("Updating ticket [{}]", ticket); try { val holder = buildTicketAsDocument(ticket); val metadata = this.ticketCatalog.find(ticket); if (metadata == null) { LOGGER.error("Could not locate ticket definition in the catalog for ticket [{}]", ticket.getId()); return null; } LOGGER.debug("Located ticket definition [{}] in the ticket catalog", metadata); val collectionName = getTicketCollectionInstanceByMetadata(metadata); if (StringUtils.isBlank(collectionName)) { LOGGER.error("Could not locate collection linked to ticket definition for ticket [{}]", ticket.getId()); return null; } val query = new Query(Criteria.where(TicketHolder.FIELD_NAME_ID).is(holder.getTicketId())); val update = Update.update(TicketHolder.FIELD_NAME_JSON, holder.getJson()); this.mongoTemplate.upsert(query, update, collectionName); LOGGER.debug("Updated ticket [{}]", ticket); } catch (final Exception e) { LOGGER.error("Failed updating [{}]: [{}]", ticket, e); } return ticket; } @Override public void addTicket(final Ticket ticket) { try { LOGGER.debug("Adding ticket [{}]", ticket.getId()); val holder = buildTicketAsDocument(ticket); val metadata = this.ticketCatalog.find(ticket); if (metadata == null) { LOGGER.error("Could not locate ticket definition in the catalog for ticket [{}]", ticket.getId()); return; } LOGGER.debug("Located ticket definition [{}] in the ticket catalog", metadata); val collectionName = getTicketCollectionInstanceByMetadata(metadata); if (StringUtils.isBlank(collectionName)) { LOGGER.error("Could not locate collection linked to ticket definition for ticket [{}]", ticket.getId()); return; } LOGGER.debug("Found collection [{}] linked to ticket [{}]", collectionName, metadata); this.mongoTemplate.insert(holder, collectionName); LOGGER.debug("Added ticket [{}]", ticket.getId()); } catch (final Exception e) { LOGGER.error("Failed adding [{}]: [{}]", ticket, e); } } @Override public Ticket getTicket(final String ticketId) { try { LOGGER.debug("Locating ticket ticketId [{}]", ticketId); val encTicketId = encodeTicketId(ticketId); if (encTicketId == null) { LOGGER.debug("Ticket ticketId [{}] could not be found", ticketId); return null; } val metadata = this.ticketCatalog.find(ticketId); if (metadata == null) { LOGGER.debug("Ticket definition [{}] could not be found in the ticket catalog", ticketId); return null; } val collectionName = getTicketCollectionInstanceByMetadata(metadata); val query = new Query(Criteria.where(TicketHolder.FIELD_NAME_ID).is(encTicketId)); val d = this.mongoTemplate.findOne(query, TicketHolder.class, collectionName); if (d != null) { val decoded = deserializeTicketFromMongoDocument(d); val result = decodeTicket(decoded); if (result != null && result.isExpired()) { LOGGER.debug("Ticket [{}] has expired and is now removed from the collection", result.getId()); deleteSingleTicket(result.getId()); return null; } return result; } } catch (final Exception e) { LOGGER.error("Failed fetching [{}]: [{}]", ticketId, e); } return null; } @Override public Collection<Ticket> getTickets() { return this.ticketCatalog.findAll().stream() .map(this::getTicketCollectionInstanceByMetadata) .map(map -> mongoTemplate.findAll(TicketHolder.class, map)) .flatMap(List::stream) .map(ticket -> decodeTicket(deserializeTicketFromMongoDocument(ticket))) .collect(Collectors.toSet()); } @Override public boolean deleteSingleTicket(final String ticketIdToDelete) { val ticketId = encodeTicketId(ticketIdToDelete); LOGGER.debug("Deleting ticket [{}]", ticketId); try { val metadata = this.ticketCatalog.find(ticketIdToDelete); val collectionName = getTicketCollectionInstanceByMetadata(metadata); val query = new Query(Criteria.where(TicketHolder.FIELD_NAME_ID).is(ticketId)); val res = this.mongoTemplate.remove(query, collectionName); LOGGER.debug("Deleted ticket [{}] with result [{}]", ticketIdToDelete, res); return true; } catch (final Exception e) { LOGGER.error("Failed deleting [{}]: [{}]", ticketId, e); } return false; } @Override public long deleteAll() { return this.ticketCatalog.findAll().stream() .map(this::getTicketCollectionInstanceByMetadata) .filter(StringUtils::isNotBlank) .mapToLong(collectionName -> { val countTickets = this.mongoTemplate.count(SELECT_ALL_NAMES_QUERY, collectionName); mongoTemplate.remove(SELECT_ALL_NAMES_QUERY, collectionName); return countTickets; }) .sum(); } /** * Calculate the time at which the ticket is eligible for automated deletion by MongoDb. * Makes the assumption that the CAS server date and the Mongo server date are in sync. */ private static Date getExpireAt(final Ticket ticket) { val ttl = ticket instanceof TicketState ? ticket.getExpirationPolicy().getTimeToLive((TicketState) ticket) : ticket.getExpirationPolicy().getTimeToLive(); if (ttl < 1) { return null; } return new Date(System.currentTimeMillis() + (ttl * 1000)); } private static String serializeTicketForMongoDocument(final Ticket ticket) { try { return BaseTicketSerializers.serializeTicket(ticket); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return null; } private static Ticket deserializeTicketFromMongoDocument(final TicketHolder holder) { return BaseTicketSerializers.deserializeTicket(holder.getJson(), holder.getType()); } private TicketHolder buildTicketAsDocument(final Ticket ticket) { val encTicket = encodeTicket(ticket); val json = serializeTicketForMongoDocument(encTicket); if (StringUtils.isNotBlank(json)) { LOGGER.trace("Serialized ticket into a JSON document as \n [{}]", JsonValue.readJSON(json).toString(Stringify.FORMATTED)); val expireAt = getExpireAt(ticket); return new TicketHolder(json, encTicket.getId(), encTicket.getClass().getName(), expireAt); } throw new IllegalArgumentException("Ticket " + ticket.getId() + " cannot be serialized to JSON"); } private String getTicketCollectionInstanceByMetadata(final TicketDefinition metadata) { val mapName = metadata.getProperties().getStorageName(); LOGGER.debug("Locating collection name [{}] for ticket definition [{}]", mapName, metadata); val c = getTicketCollectionInstance(mapName); if (c != null) { return c.getNamespace().getCollectionName(); } throw new IllegalArgumentException("Could not locate MongoDb collection " + mapName); } private MongoCollection getTicketCollectionInstance(final String mapName) { try { val inst = this.mongoTemplate.getCollection(mapName); LOGGER.debug("Located MongoDb collection instance [{}]", mapName); return inst; } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return null; } }
package com.ceco.gm2.gravitybox.quicksettings; import com.ceco.gm2.gravitybox.R; import de.robv.android.xposed.XposedBridge; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.LocationManager; import android.provider.Settings; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; public class GpsTile extends AQuickSettingsTile { private static final String TAG = "GB:GpsTile"; private static final boolean DEBUG = false; public static final String GPS_ENABLED_CHANGE_ACTION = "android.location.GPS_ENABLED_CHANGE"; public static final String GPS_FIX_CHANGE_ACTION = "android.location.GPS_FIX_CHANGE"; public static final String EXTRA_GPS_ENABLED = "enabled"; private boolean mGpsEnabled; private boolean mGpsFixed; private TextView mTextView; private static void log(String message) { XposedBridge.log(TAG + ": " + message); } private BroadcastReceiver mLocationManagerReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) log("Broadcast received: " + intent.toString()); final String action = intent.getAction(); if (action.equals(LocationManager.PROVIDERS_CHANGED_ACTION)) { mGpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); mGpsFixed = false; } else if (action.equals(GPS_FIX_CHANGE_ACTION)) { mGpsFixed = intent.getBooleanExtra(EXTRA_GPS_ENABLED, false); } else if (action.equals(GPS_ENABLED_CHANGE_ACTION)) { mGpsFixed = false; } if (DEBUG) log("mGpsEnabled = " + mGpsEnabled + "; mGpsFixed = " + mGpsFixed); updateResources(); } }; public GpsTile(Context context, Context gbContext, Object statusBar, Object panelBar) { super(context, gbContext, statusBar, panelBar); mOnClick = new View.OnClickListener() { @Override public void onClick(View v) { Settings.Secure.setLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER, !mGpsEnabled); } }; mOnLongClick = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startActivity(Settings.ACTION_LOCATION_SOURCE_SETTINGS); return false; } }; mGpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); mGpsFixed = false; } @Override protected void onTileCreate() { LayoutInflater inflater = LayoutInflater.from(mGbContext); inflater.inflate(R.layout.quick_settings_tile_gps, mTile); mTextView = (TextView) mTile.findViewById(R.id.gps_tileview); } @Override protected void onTilePostCreate() { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION); intentFilter.addAction(GPS_ENABLED_CHANGE_ACTION); intentFilter.addAction(GPS_FIX_CHANGE_ACTION); mContext.registerReceiver(mLocationManagerReceiver, intentFilter); super.onTilePostCreate(); } @Override protected synchronized void updateTile() { if (mGpsEnabled) { mLabel = mGpsFixed ? mGbContext.getString(R.string.qs_tile_gps_locked) : mGbContext.getString(R.string.qs_tile_gps_enabled); mDrawableId = mGpsFixed ? R.drawable.ic_qs_gps_locked : R.drawable.ic_qs_gps_enable; } else { mLabel = mGbContext.getString(R.string.qs_tile_gps_disabled); mDrawableId = R.drawable.ic_qs_gps_disable; } mTextView.setText(mLabel); mTextView.setCompoundDrawablesWithIntrinsicBounds(0, mDrawableId, 0, 0); } }
package org.jboss.as.test.integration.ejb.log; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static org.junit.Assert.fail; /** * Tests if the WARN message was logged when default transaction attribute was used on SFSB lifecyle method * Test for [ WFLY-9509 ]. * * @author Daniel Cihak */ @RunWith(Arquillian.class) public class InvalidTransactionAttributeTestCase { private static final String ARCHIVE_NAME = "InvalidTransactionAttribute"; @ArquillianResource Deployer deployer; @Deployment(name = "invalidtransactionattribute", testable = false, managed = false) public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(InvalidTransactionAttributeTestCase.class, StatefulBean.class, StatefulInterface.class); jar.addAsManifestResource(InvalidTransactionAttributeTestCase.class.getPackage(), "ejb-jar.xml", "ejb-jar.xml"); return jar; } @Test public void testInvalidTransactionAttributeWarnLogged() { PrintStream oldOut = null; String output = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { oldOut = System.out; System.setOut(new PrintStream(baos)); } catch (Throwable t) { fail(t.getMessage()); } finally { deployer.deploy("invalidtransactionattribute"); System.setOut(oldOut); } try { output = new String(baos.toByteArray()); } catch (Throwable t) { fail(t.getMessage()); } finally { Assert.assertFalse(output, output.contains("WFLYEJB0463")); Assert.assertFalse(output, output.contains("ERROR")); Assert.assertFalse(output, output.contains("WARN")); deployer.undeploy("invalidtransactionattribute"); } } }
package com.dmdirc.ui.swing.dialogs; import com.dmdirc.Config; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.themes.Theme; import com.dmdirc.themes.ThemeManager; import com.dmdirc.ui.interfaces.PreferencesInterface; import com.dmdirc.ui.swing.components.SwingPreferencesPanel; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; /** * Allows the user to modify global client preferences. */ public final class PreferencesDialog implements PreferencesInterface { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 7; /** A previously created instance of PreferencesDialog. */ private static PreferencesDialog me; /** preferences panel. */ private SwingPreferencesPanel preferencesPanel; /** Theme map. */ private Map<String, String> themes; /** * Creates a new instance of PreferencesDialog. */ private PreferencesDialog() { } /** Creates the dialog if one doesn't exist, and displays it. */ public static synchronized void showPreferencesDialog() { if (me == null) { me = new PreferencesDialog(); } me.initComponents(); me.preferencesPanel.requestFocus(); } /** * Initialises GUI components. */ private void initComponents() { preferencesPanel = new SwingPreferencesPanel(this); initGeneralTab(); initConnectionTab(); initMessagesTab(); initNotificationsTab(); initGUITab(); initThemesTab(); initNicklistTab(); initTreeviewTab(); initAdvancedTab(); preferencesPanel.display(); } /** * Initialises the preferences tab. */ private void initGeneralTab() { final String tabName = "General"; preferencesPanel.addCategory(tabName, ""); preferencesPanel.addCheckboxOption(tabName, "channel.splitusermodes", "Split user modes: ", "Show individual mode lines for each mode change that affects a user (e.g. op, devoice)", Config.getOptionBool("channel", "splitusermodes")); preferencesPanel.addCheckboxOption(tabName, "channel.sendwho", "Send channel WHOs: ", "Request information (away state, hostname, etc) on channel users automatically", Config.getOptionBool("channel", "sendwho")); preferencesPanel.addSpinnerOption(tabName, "general.whotime", "Who request interval (ms): ", "How often to send WHO requests for a channel", Config.getOptionInt("general", "whotime", 600000), 10000, Integer.MAX_VALUE, 10000); preferencesPanel.addCheckboxOption(tabName, "channel.showmodeprefix", "Show mode prefix: ", "Prefix users' names with their mode in channels", Config.getOptionBool("channel", "showmodeprefix")); preferencesPanel.addCheckboxOption(tabName, "server.friendlymodes", "Friendly modes: ", "Show friendly mode names", Config.getOptionBool("server", "friendlymodes")); preferencesPanel.addCheckboxOption(tabName, "general.hidequeries", "Hide queries : ", "", Config.getOptionBool("general", "hidequeries")); preferencesPanel.addTextfieldOption(tabName, "general.commandchar", "Command character: ", "Character used to indicate a command", Config.getCommandChar()); preferencesPanel.addTextfieldOption(tabName, "general.silencechar", "Silence character: ", "Character used to indicate a command should be silently executed", Config.getOption("general", "silencechar")); preferencesPanel.addCheckboxOption(tabName, "ui.awayindicator", "Away indicator: ", "Shows an away indicator in the input field.", Config.getOptionBool("ui", "awayindicator")); preferencesPanel.addSpinnerOption(tabName, "ui.pasteProtectionLimit", "Paste protection trigger: ", "Confirm pasting of text that contains more than this many lines", Config.getOptionInt("ui", "pasteProtectionLimit", 1), 0, Integer.MAX_VALUE, 1); } /** * Initialises the Connection tab. */ private void initConnectionTab() { final String tabName = "Connection"; preferencesPanel.addCategory(tabName, ""); preferencesPanel.addCheckboxOption(tabName, "general.closechannelsonquit", "Close channels on quit: ", "Close channel windows when you quit the server", Config.getOptionBool("general", "closechannelsonquit")); preferencesPanel.addCheckboxOption(tabName, "general.closechannelsondisconnect", "Close channels on disconnect: ", "Close channel windows when the server is disconnected", Config.getOptionBool("general", "closechannelsondisconnect")); preferencesPanel.addCheckboxOption(tabName, "general.closequeriesonquit", "Close queries on quit: ", "Close query windows when you quit the server", Config.getOptionBool("general", "closequeriesonquit")); preferencesPanel.addCheckboxOption(tabName, "general.closequeriesondisconnect", "Close queries on disconnect: ", "Close query windows when the server is disconnected", Config.getOptionBool("general", "closequeriesondisconnect")); preferencesPanel.addSpinnerOption(tabName, "server.pingtimeout", "Server timeout (ms): ", "How long to wait for a server to reply to a PING request before disconnecting", Config.getOptionInt("server", "pingtimeout", 60000), 5000, Integer.MAX_VALUE, 5000); preferencesPanel.addCheckboxOption(tabName, "general.reconnectonconnectfailure", "Reconnect on failure: ", "Attempt to reconnect if there's an error when connecting", Config.getOptionBool("general", "reconnectonconnectfailure")); preferencesPanel.addCheckboxOption(tabName, "general.reconnectondisconnect", "Reconnect on disconnect: ", "Reconnect automatically if the server is disconnected", Config.getOptionBool("general", "reconnectondisconnect")); preferencesPanel.addSpinnerOption(tabName, "general.reconnectdelay", "Reconnect delay: ", "How long to wait before attempting to reconnect to a server", Config.getOptionInt("general", "reconnectdelay", 30)); preferencesPanel.addCheckboxOption(tabName, "general.rejoinchannels", "Rejoin open channels: ", "Rejoin open channels when reconnecting to a server", Config.getOptionBool("general", "rejoinchannels")); } /** * Initialises the Messages tab. */ private void initMessagesTab() { final String tabName = "Messages"; preferencesPanel.addCategory(tabName, ""); preferencesPanel.addTextfieldOption(tabName, "general.closemessage", "Close message: ", "Default quit message to use when closing DMDirc", Config.getOption("general", "closemessage")); preferencesPanel.addTextfieldOption(tabName, "general.partmessage", "Part message: ", "Default message to use when parting a channel", Config.getOption("general", "partmessage")); preferencesPanel.addTextfieldOption(tabName, "general.quitmessage", "Quit message: ", "Default message to use when quitting a server", Config.getOption("general", "quitmessage")); preferencesPanel.addTextfieldOption(tabName, "general.cyclemessage", "Cycle message: ", "Default message to use when cycling a channel", Config.getOption("general", "cyclemessage")); preferencesPanel.addTextfieldOption(tabName, "general.kickmessage", "Kick message: ", "Default message to use when kicking a user from a channel", Config.getOption("general", "kickmessage")); preferencesPanel.addTextfieldOption(tabName, "general.reconnectmessage", "Reconnect message: ", "Default message to use when quitting a server to reconnect", Config.getOption("general", "reconnectmessage")); } /** * Initialises the Notifications tab. */ private void initNotificationsTab() { final String tabName = "Notifications"; preferencesPanel.addCategory("Messages", tabName, ""); final String[] windowOptions = new String[] {"all", "active", "server", }; preferencesPanel.addComboboxOption(tabName, "notifications.socketClosed", "Socket closed: ", "Where to display socket closed notifications", windowOptions, Config.getOption("notifications", "socketClosed"), false); preferencesPanel.addComboboxOption(tabName, "notifications.privateNotice", "Private notice: ", "Where to display private notice notifications", windowOptions, Config.getOption("notifications", "privateNotice"), false); preferencesPanel.addComboboxOption(tabName, "notifications.privateCTCP", "CTCP request: ", "Where to display CTCP request notifications", windowOptions, Config.getOption("notifications", "privateCTCP"), false); preferencesPanel.addComboboxOption(tabName, "notifications.privateCTCPreply", "CTCP reply: ", "Where to display CTCP reply notifications", windowOptions, Config.getOption("notifications", "privateCTCPreply"), false); preferencesPanel.addComboboxOption(tabName, "notifications.connectError", "Connect error: ", "Where to display connect error notifications", windowOptions, Config.getOption("notifications", "connectError"), false); preferencesPanel.addComboboxOption(tabName, "notifications.connectRetry", "Connect retry: ", "Where to display connect retry notifications", windowOptions, Config.getOption("notifications", "connectRetry"), false); preferencesPanel.addComboboxOption(tabName, "notifications.stonedServer", "Stoned server: ", "Where to display stone server notifications", windowOptions, Config.getOption("notifications", "stonedServer"), false); } /** * Initialises the GUI tab. */ private void initGUITab() { final LookAndFeelInfo[] plaf = UIManager.getInstalledLookAndFeels(); final String[] lafs = new String[plaf.length]; final String tabName = "GUI"; int i = 0; for (LookAndFeelInfo laf : plaf) { lafs[i++] = laf.getName(); } preferencesPanel.addCategory(tabName, ""); preferencesPanel.addColourOption(tabName, "ui.backgroundcolour", "Window background colour: ", "Default background colour to use", Config.getOption("ui", "backgroundcolour"), true, true); preferencesPanel.addColourOption(tabName, "ui.foregroundcolour", "Window foreground colour: ", "Default foreground colour to use", Config.getOption("ui", "foregroundcolour"), true, true); preferencesPanel.addOptionalColourOption(tabName, "ui.inputbackgroundcolour", "Input background colour: ", "Background colour to use for input fields", Config.getOption("ui", "inputbackgroundcolour", Config.getOption("ui", "backgroundcolour", "")), false, true, true); preferencesPanel.addOptionalColourOption(tabName, "ui.inputforegroundcolour", "Input foreground colour: ", "Foreground colour to use for input fields", Config.getOption("ui", "inputforegroundcolour", Config.getOption("ui", "foregroundcolour", "")), false, true, true); preferencesPanel.addCheckboxOption(tabName, "general.showcolourdialog", "Show colour dialog: ", "Show colour picker dialog when inserting colour control codes", Config.getOptionBool("general", "showcolourdialog")); preferencesPanel.addComboboxOption(tabName, "ui.lookandfeel", "Look and feel: ", "The Java Look and Feel to use", lafs, Config.getOption("ui", "lookandfeel"), false); preferencesPanel.addCheckboxOption(tabName, "ui.antialias", "System anti-alias: ", "Anti-alias all fonts", Config.getOptionBool("ui", "antialias")); preferencesPanel.addCheckboxOption(tabName, "ui.maximisewindows", "Auto-Maximise windows: ", "Automatically maximise newly opened windows", Config.getOptionBool("ui", "maximisewindows")); preferencesPanel.addCheckboxOption(tabName, "ui.showintext", "Show colours in text area: ", "Show nickname colours in text areas", Config.getOptionBool("ui", "shownickcoloursintext")); preferencesPanel.addCheckboxOption(tabName, "ui.showinlist", "Show colours in nick list: ", "Show nickname colours in the nicklist", Config.getOptionBool("ui", "shownickcoloursinnicklist")); preferencesPanel.addComboboxOption(tabName, "ui.framemanager", "Frame manager: ", "Which frame manager should be used", new String[]{"treeview", "buttonbar", }, Config.getOption("ui", "framemanager", "treeview"), false); preferencesPanel.addComboboxOption(tabName, "ui.framemanagerPosition", "Frame manager position: ", "Where should the frame manager be positioned", new String[]{"top", "bottom", "left", "right"}, Config.getOption("ui", "framemanagerPosition", "left"), false); preferencesPanel.addCheckboxOption(tabName, "ui.stylelinks", "Style links: ", "Style links in the textpane", Config.getOptionBool("ui", "stylelinks")); } private void initThemesTab() { final String tabName = "Themes"; final Map<String, Theme> availThemes = new ThemeManager(). getAvailableThemes(); themes = new HashMap<String, String>(); for (Entry<String, Theme> entry : availThemes.entrySet()) { themes.put(entry.getKey().substring(entry.getKey().lastIndexOf('/'), entry.getKey().length()), entry.getKey()); } themes.put("None", ""); preferencesPanel.addCategory("GUI", tabName, ""); preferencesPanel.addComboboxOption(tabName, "general.theme", "Theme: ", "DMDirc theme to user", themes.keySet().toArray(new String[themes.size()]), Config.getOption("general", "theme", ""), false); } /** * Initialises the Nicklist tab. */ private void initNicklistTab() { final String tabName = "Nicklist"; preferencesPanel.addCategory("GUI", tabName, ""); preferencesPanel.addOptionalColourOption(tabName, "nicklist.backgroundcolour", "Nicklist background colour: ", "Background colour to use for the nicklist", Config.getOption("nicklist", "backgroundcolour", Config.getOption("ui", "backgroundcolour", "")), false, true, true); preferencesPanel.addOptionalColourOption(tabName, "nicklist.foregroundcolour", "Nicklist foreground colour: ", "Foreground colour to use for the nicklist", Config.getOption("nicklist", "foregroundcolour", Config.getOption("ui", "foregroundcolour", "")), false, true, true); preferencesPanel.addCheckboxOption(tabName, "nicklist.altBackground", "Alternating nicklist", "Use an alternate background colour for every other entry", Config.getOptionBool("nicklist", "altBackground")); preferencesPanel.addColourOption(tabName, "nicklist.altBackgroundColour", "Alternate nicklist colour: ", "Alternate background colour to use", Config.getOption("nicklist", "altBackgroundColour", "f0f0f0"), false, true); preferencesPanel.addCheckboxOption(tabName, "ui.sortByMode", "Nicklist sort by mode: ", "Sort nicklist by user mode", Config.getOptionBool("ui", "sortByMode")); preferencesPanel.addCheckboxOption(tabName, "ui.sortByCase", "Nicklist sort by case: ", "Sort nicklist by user mode", Config.getOptionBool("ui", "sortByCase")); } /** * Initialises the Treeview tab. */ private void initTreeviewTab() { final String tabName = "Treeview"; preferencesPanel.addCategory("GUI", tabName, ""); preferencesPanel.addOptionalColourOption(tabName, "treeview.backgroundcolour", "Treeview background colour: ", "Background colour to use for the treeview", Config.getOption("treeview", "backgroundcolour", Config.getOption("ui", "backgroundcolour", "")), false, true, true); preferencesPanel.addOptionalColourOption(tabName, "treeview.foregroundcolour", "Treeview foreground colour: ", "Foreground colour to use for the treeview", Config.getOption("treeview", "foregroundcolour", Config.getOption("ui", "foregroundcolour", "")), false, true, true); preferencesPanel.addCheckboxOption(tabName, "ui.treeviewRolloverEnabled", "Rollover enabled: ", "Use a different background colour when cursor is over a treeview node", Config.getOptionBool("ui", "treeviewRolloverEnabled")); preferencesPanel.addColourOption(tabName, "ui.treeviewRolloverColour", "Rollover colour: ", "Rollover colour to use", Config.getOption("ui", "treeviewRolloverColour"), true, true); preferencesPanel.addCheckboxOption(tabName, "treeview.sortwindows", "Sort windows: ", "Sort windows of servers in the treeview", Config.getOptionBool("treeview", "sortwindows")); preferencesPanel.addCheckboxOption(tabName, "treeview.sortservers", "Sort servers: ", "Sort servers in the treeview", Config.getOptionBool("treeview", "sortservers")); preferencesPanel.addCheckboxOption(tabName, "ui.treeviewActiveBold", "Active node bold: ", "Show the active node in bold", Config.getOptionBool("ui", "treeviewActiveBold")); preferencesPanel.addOptionalColourOption(tabName, "ui.treeviewActiveForeground", "Active node foreground: ", "Foreground colour of the active node", Config.getOption("treeview", "treeviewActiveForeground", Config.getOption("treeview", "foregroundcolour", "")), false, true, true); preferencesPanel.addOptionalColourOption(tabName, "ui.treeviewActiveBackground", "Active node background: ", "Background colour of the active node", Config.getOption("treeview", "treeviewActiveBackground", Config.getOption("treeview", "backgroundcolour", "")), false, true, true); } /** * Initialises the advanced tab. */ private void initAdvancedTab() { final String tabName = "Advanced"; preferencesPanel.addCategory(tabName, ""); preferencesPanel.addTextfieldOption(tabName, "general.browser", "Browser: ", "The browser to use for opening URLs (only required when auto detection fails)", Config.getOption("general", "browser")); preferencesPanel.addCheckboxOption(tabName, "browser.uselaunchdelay", "Use browser delay: ", "Enable delay between browser launches (to prevent mistakenly double clicking)", Config.getOptionBool("browser", "uselaunchdelay")); preferencesPanel.addSpinnerOption(tabName, "browser.launchdelay", "Browser launch delay (ms): ", "Minimum time between opening of URLs", Config.getOptionInt("browser", "launchdelay", 500)); preferencesPanel.addCheckboxOption(tabName, "general.autoSubmitErrors", "Automatically submit errors: ", "Automatically submit client errors to the developers", Config.getOptionBool("general", "autoSubmitErrors")); preferencesPanel.addCheckboxOption(tabName, "tabcompletion.casesensitive", "Case-sensitive tab completion: ", "Respect case when tab completing", Config.getOptionBool("tabcompletion", "casesensitive")); preferencesPanel.addCheckboxOption(tabName, "ui.quickCopy", "Quick Copy: ", "Automatically copy text that's selected in windows when the mouse button is released", Config.getOptionBool("ui", "quickCopy")); preferencesPanel.addCheckboxOption(tabName, "ui.showversion", "Show version: ", "Show DMDirc version in the titlebar", Config.getOptionBool("ui", "showversion")); preferencesPanel.addSpinnerOption(tabName, "ui.frameBufferSize", "Frame buffer size: ", "Sets the maximum number of lines in the frame buffer.", Config.getOptionInt("ui", "frameBufferSize", Integer.MAX_VALUE)); } /** {@inheritDoc}. */ public void configClosed(final Properties properties) { for (Map.Entry<Object, Object> entry : properties.entrySet()) { final String[] args = ((String) entry.getKey()).split("\\."); if (args.length == 2) { if ("".equals(entry.getValue()) || entry.getValue() == null) { Config.unsetOption(args[0], args[1]); } else { if ("general".equals(args[0]) && "theme".equals(args[1])) { Config.setOption(args[0], args[1], themes.get(entry.getValue())); } else { Config.setOption(args[0], args[1], (String) entry.getValue()); } } } else { Logger.appError(ErrorLevel.LOW, "Invalid setting value: " + entry.getKey(), new IllegalArgumentException("Invalid setting: " + entry.getKey())); } } preferencesPanel = null; } /** {@inheritDoc} */ public void configCancelled() { //Ignore } }
package pt.uminho.haslab.echo.transform.alloy; import edu.mit.csail.sdg.alloy4.Err; import edu.mit.csail.sdg.alloy4compiler.ast.*; import edu.mit.csail.sdg.alloy4compiler.ast.Sig.Field; import edu.mit.csail.sdg.alloy4compiler.ast.Sig.PrimSig; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.ocl.examples.pivot.*; import org.eclipse.qvtd.pivot.qvtrelation.RelationCallExp; import org.eclipse.qvtd.pivot.qvttemplate.ObjectTemplateExp; import org.eclipse.qvtd.pivot.qvttemplate.PropertyTemplateItem; import pt.uminho.haslab.echo.*; import pt.uminho.haslab.echo.EchoRunner.Task; import pt.uminho.haslab.echo.transform.ConditionTranslator; import pt.uminho.haslab.mde.MDEManager; import pt.uminho.haslab.mde.model.EMetamodel; import pt.uminho.haslab.mde.model.EVariable; import pt.uminho.haslab.mde.transformation.qvt.QVTRelation; import java.util.AbstractMap.SimpleEntry; import java.util.*; import java.util.Map.Entry; public class OCL2Alloy implements ConditionTranslator{ private Map<String,Entry<ExprHasName,String>> varstates; private Map<String,ExprHasName> posvars; private Map<String,ExprHasName> prevars; private Relation2Alloy parentq; private boolean isPre = false; private Map<String,Integer> news = new HashMap<String,Integer>(); public OCL2Alloy(Relation2Alloy q2a, Map<String,Entry<ExprHasName,String>> vardecls, Map<String,ExprHasName> argsvars, Map<String,ExprHasName> prevars) { this (vardecls,argsvars,prevars); this.parentq = q2a; } public OCL2Alloy(Map<String,Entry<ExprHasName,String>> vardecls, Map<String,ExprHasName> argsvars, Map<String,ExprHasName> prevars) { this.varstates = vardecls; this.prevars = prevars; this.posvars = argsvars; } Expr oclExprToAlloy (VariableExp expr) { String varname = expr.toString(); return varstates.get(varname).getKey(); } Expr oclExprToAlloy (BooleanLiteralExp expr){ if (expr.isBooleanSymbol()) return ExprConstant.TRUE; else return ExprConstant.FALSE; } Expr oclExprToAlloy (UnlimitedNaturalLiteralExp expr) throws EchoError { Number n = expr.getUnlimitedNaturalSymbol(); if (n.toString().equals("*")) throw new ErrorTransform ("No support for unlimited integers."); Integer bitwidth = EchoOptionsSetup.getInstance().getBitwidth(); Integer max = (int) (Math.pow(2, bitwidth) / 2); if (n.intValue() >= max || n.intValue() < -max) throw new ErrorTransform("Bitwidth not enough to represent: "+n+"."); return ExprConstant.makeNUMBER(n.intValue()); } Expr oclExprToAlloy (ObjectTemplateExp temp) throws EchoError { Expr result = Sig.NONE.no(); for (PropertyTemplateItem part: temp.getPart()) { // calculates OCL expression OCLExpression value = part.getValue(); Expr ocl = this.oclExprToAlloy(value); // retrieves the Alloy field Property prop = part.getReferredProperty(); // retrieves the Alloy root variable String varname = temp.getBindsTo().getName(); ExprHasName var = varstates.get(varname).getKey(); if (var == null) throw new ErrorTransform ("Variable not declared: "+ temp.getBindsTo()); Expr localfield = propertyToField(prop,var); if (part.isIsOpposite()) { localfield = localfield.transpose(); } // merges the whole thing Expr item; if (ocl.equals(ExprConstant.TRUE)) item = var.in(localfield); else if (ocl.equals(ExprConstant.FALSE)) item = var.in(localfield).not(); else if (value instanceof ObjectTemplateExp) { varname = ((ObjectTemplateExp) value).getBindsTo().getName(); ExprHasName var1 = varstates.get(varname).getKey(); if (var1 == null) throw new ErrorTransform ("Variable not declared: "+((ObjectTemplateExp) value).getBindsTo()); item = var1.in(var.join(localfield)); item = AlloyUtil.cleanAnd(item,ocl); } else { item = ocl.in(var.join(localfield)); } result = AlloyUtil.cleanAnd(result,item); } OCLExpression where = temp.getWhere(); if (where != null) { Expr awhere = oclExprToAlloy(where); result = AlloyUtil.cleanAnd(result,awhere); } return result; } Expr oclExprToAlloy (RelationCallExp expr) throws EchoError { Func func; func = parentq.transformation_translator.callRelation(new QVTRelation(expr.getReferredRelation()), parentq.dependency); if (func == null) { QVTRelation rel = new QVTRelation(expr.getReferredRelation()); new Relation2Alloy (parentq,rel); func = parentq.transformation_translator.callRelation(rel,parentq.dependency); } List<ExprHasName> aux = new ArrayList<ExprHasName>(); for (Entry<String, ExprHasName> x : (isPre?prevars:posvars).entrySet()) aux.add(x.getValue()); Expr res = func.call(aux.toArray(new ExprHasName[aux.size()])); List<OCLExpression> vars = expr.getArgument(); List<Expr> avars = new ArrayList<Expr>(); for (OCLExpression var : vars){ Expr avar = oclExprToAlloy(var); avars.add(avar); } Expr insig = avars.get(avars.size()-1); avars.remove(insig); for (Expr avar : avars) res = avar.join(res); res = insig.in(res); return res; } Expr oclExprToAlloy (IfExp expr) throws EchoError { Expr res = null; Expr eif = oclExprToAlloy(expr.getCondition()); Expr ethen = oclExprToAlloy(expr.getThenExpression()); Expr eelse = oclExprToAlloy(expr.getElseExpression()); res = ExprITE.make(null, eif, ethen, eelse); return res; } Expr oclExprToAlloy (IteratorExp expr) throws EchoError { Expr res = null; List<org.eclipse.ocl.examples.pivot.Variable> variterator = expr.getIterator(); if (variterator.size() != 1) throw new ErrorTransform("Invalid variables on closure: "+variterator); EVariable x = EVariable.getVariable(variterator.get(0)); Decl d = AlloyUtil.variableListToExpr(new HashSet<EVariable>(Arrays.asList(x)),varstates,isPre?prevars:posvars).get(variterator.get(0).getName()); Expr src = oclExprToAlloy(expr.getSource()); varstates.put(d.get().label, new SimpleEntry<ExprHasName,String>(d.get(),null)); for (String s : varstates.keySet()) { ExprVar var = (ExprVar) varstates.get(s).getKey(); if (src.hasVar(var) && varstates.get(s).getValue() != null) varstates.put(d.get().label, new SimpleEntry<ExprHasName,String>(d.get(),varstates.get(s).getValue())); } Expr bdy = oclExprToAlloy(expr.getBody()); if (expr.getReferredIteration().getName().equals("forAll")) { try { res = ((d.get().in(src)).implies(bdy)); res = res.forAll(d); } catch (Err e) { throw new ErrorAlloy(e.getMessage());} } else if (expr.getReferredIteration().getName().equals("exists")) { try { res = ((d.get().in(src)).and(bdy)); res = res.forSome(d); } catch (Err e) { throw new ErrorAlloy(e.getMessage());} } else if (expr.getReferredIteration().getName().equals("one")) { try { res = ((d.get().in(src)).and(bdy)); res = res.forOne(d); } catch (Err e) { throw new ErrorAlloy(e.getMessage());} } else if (expr.getReferredIteration().getName().equals("collect")) { try { res = d.get().in(src); res = src.join(res.comprehensionOver(d,bdy.oneOf("2_"))); } catch (Err e) { throw new ErrorAlloy(e.getMessage());} } else if (expr.getReferredIteration().getName().equals("select")) { try { res = ((d.get().in(src)).and(bdy)); res = res.comprehensionOver(d); } catch (Err e) { throw new ErrorAlloy(e.getMessage());} } else if (expr.getReferredIteration().getName().equals("reject")) { try { res = ((d.get().in(src)).and(bdy.not())); res = res.comprehensionOver(d); } catch (Err e) { throw new ErrorAlloy(e.getMessage());} } else if (expr.getReferredIteration().getName().equals("closure")) { res = Sig.NONE.no(); try { Decl dd = bdy.oneOf("2_"); res = res.comprehensionOver(d,dd); } catch (Err e) { throw new ErrorAlloy(e.getMessage());} res = src.join(res.closure()); } else throw new ErrorUnsupported("OCL iterator not supported: "+expr.getReferredIteration()+"."); varstates.remove(d.get().label); return res; } Expr oclExprToAlloy (TypeExp expr) throws EchoError { String metamodeluri = EcoreUtil.getURI(expr.getReferredType().getPackage().getEPackage()).path(); EMetamodel metamodel = MDEManager.getInstance().getMetamodel(metamodeluri, false); EClassifier eclass = AlloyEchoTranslator.getInstance().getEClassifierFromName(metamodel.ID, expr.getReferredType().getName()); Field field = AlloyEchoTranslator.getInstance().getStateFieldFromClass(metamodel.ID, (EClass) eclass); Expr state = (isPre?prevars:posvars).get(metamodel.ID); return field.join(state); } Expr oclExprToAlloy (PropertyCallExp expr) throws EchoError { Expr res = null; isPre = expr.isPre(); Expr var = oclExprToAlloy(expr.getSource()); Expr aux = propertyToField(expr.getReferredProperty(),var); if(expr.getType().getName().equals("Boolean")) res = var.in(aux); else res = var.join(aux); return res; } Expr oclExprToAlloy (OperationCallExp expr) throws EchoError { Expr res = null; isPre = expr.isPre(); Expr src = oclExprToAlloy(expr.getSource()); if (expr.getReferredOperation().getName().equals("not")) res = src.not(); else if (expr.getReferredOperation().getName().equals("isEmpty")) res = src.no(); else if (expr.getReferredOperation().getName().equals("size")) { EchoReporter.getInstance().warning("Integer operators (size) require suitable bitwidths.", Task.TRANSLATE_OCL); res = src.cardinality(); } else if (expr.getReferredOperation().getName().equals("=")) { Expr aux = oclExprToAlloy(expr.getArgument().get(0)); if (expr.getArgument().get(0).getType().getName().equals("Boolean")) res = src.iff(aux); else res = src.equal(aux); } else if (expr.getReferredOperation().getName().equals("<>")){ Expr aux = oclExprToAlloy(expr.getArgument().get(0)); if (expr.getArgument().get(0).getType().getName().equals("Boolean")) res = src.iff(aux).not(); else res = src.equal(aux).not(); } else if (expr.getReferredOperation().getName().equals("and")) res = src.and(oclExprToAlloy(expr.getArgument().get(0))); else if (expr.getReferredOperation().getName().equals("or")) { try{ res = closure2Reflexive(expr.getArgument().get(0),expr.getSource()); } catch (Error a) { res = src.or(oclExprToAlloy(expr.getArgument().get(0))); } } else if (expr.getReferredOperation().getName().equals("implies")) res = src.implies(oclExprToAlloy(expr.getArgument().get(0))); else if (expr.getReferredOperation().getName().equals("<")) res = src.lt(oclExprToAlloy(expr.getArgument().get(0))); else if (expr.getReferredOperation().getName().equals(">")) res = src.gt(oclExprToAlloy(expr.getArgument().get(0))); else if (expr.getReferredOperation().getName().equals("<=")) res = src.lte(oclExprToAlloy(expr.getArgument().get(0))); else if (expr.getReferredOperation().getName().equals(">=")) res = src.gte(oclExprToAlloy(expr.getArgument().get(0))); else if (expr.getReferredOperation().getName().equals("union")) res = src.plus(oclExprToAlloy(expr.getArgument().get(0))); else if (expr.getReferredOperation().getName().equals("intersection")) res = src.intersect(oclExprToAlloy(expr.getArgument().get(0))); else if (expr.getReferredOperation().getName().equals("includes")) res =(oclExprToAlloy(expr.getArgument().get(0))).in(src); else if (expr.getReferredOperation().getName().equals("oclAsSet") || expr.getReferredOperation().getName().equals("asSet")) res = src; else if (expr.getReferredOperation().getName().equals("+")) res = src.iplus(oclExprToAlloy(expr.getArgument().get(0))); else if (expr.getReferredOperation().getName().equals("-")) res = src.iminus(oclExprToAlloy(expr.getArgument().get(0))); else if (expr.getReferredOperation().getName().equals("allInstances")) res = src; else if (expr.getReferredOperation().getName().equals("oclIsNew")) { EObject container = expr.eContainer(); while (!(container instanceof IteratorExp) && container != null) container = container.eContainer(); if (container == null || !((IteratorExp)container).getReferredIteration().getName().equals("one")) throw new ErrorTransform("oclIsNew may only occur in a \"one\" iteration"); VariableExp var = (VariableExp) expr.getSource(); String cl = var.getType().getName(); String metamodeluri = EcoreUtil.getURI(var.getType().getPackage().getEPackage()).path(); Integer newi = news.get(cl); if (newi == null) news.put(cl,1); else news.put(cl,newi+1); EMetamodel metamodel = MDEManager.getInstance().getMetamodel(metamodeluri, false); EClass ecl = (EClass) AlloyEchoTranslator.getInstance().getEClassifierFromName(metamodel.ID, cl); Field statefield = AlloyEchoTranslator.getInstance().getStateFieldFromClass(metamodel.ID,ecl); Expr pre = Sig.NONE; Expr pos = Sig.NONE; if (varstates.get(var.toString()) != null && varstates.get(var.toString()).getValue() != null) { if (posvars != null) pos = posvars.get(varstates.get(var.toString()).getValue()); if (prevars != null) pre = prevars.get(varstates.get(var.toString()).getValue()); } else { try { for (ExprHasName x : posvars.values()) if (((PrimSig) x.type().toExpr()).label.equals(metamodeluri)) pos = pos.plus(x); for (ExprHasName x : prevars.values()) if (((PrimSig) x.type().toExpr()).label.equals(metamodeluri)) pre = pre.plus(x); } catch (Err a) {} } Expr pree = (src.in(statefield.join(pre))).not(); Expr pose = src.in(statefield.join(pos)); res = pree.and(pose); } else throw new ErrorUnsupported ("OCL operation not supported: "+expr.toString()+"."); return res; } public Expr oclExprToAlloy (OCLExpression expr) throws EchoError { if (expr instanceof ObjectTemplateExp) return oclExprToAlloy((ObjectTemplateExp) expr); else if (expr instanceof BooleanLiteralExp) return oclExprToAlloy((BooleanLiteralExp) expr); else if (expr instanceof VariableExp) return oclExprToAlloy((VariableExp) expr); else if (expr instanceof RelationCallExp) return oclExprToAlloy((RelationCallExp) expr); else if (expr instanceof IteratorExp) return oclExprToAlloy((IteratorExp) expr); else if (expr instanceof OperationCallExp) return oclExprToAlloy((OperationCallExp) expr); else if (expr instanceof PropertyCallExp) return oclExprToAlloy((PropertyCallExp) expr); else if (expr instanceof IfExp) return oclExprToAlloy((IfExp) expr); else if (expr instanceof UnlimitedNaturalLiteralExp) return oclExprToAlloy((UnlimitedNaturalLiteralExp) expr); else if (expr instanceof TypeExp) return oclExprToAlloy((TypeExp) expr); else throw new ErrorUnsupported ("OCL expression not supported: "+expr+"."); } // retrieves the Alloy field corresponding to an OCL property (attribute) Expr propertyToField (Property prop, Expr var) throws EchoError { String metamodeluri = EcoreUtil.getURI(prop.getOwningType().getPackage().getEPackage()).path().replace("/resource", ""); EMetamodel metamodel = MDEManager.getInstance().getMetamodel(metamodeluri, false); Expr exp; Expr statesig = null; if ((isPre?prevars:posvars) != null && var instanceof ExprHasName) statesig = (isPre?prevars:posvars).get(varstates.get(((ExprHasName)var).label).getValue()); if (statesig == null) { statesig = AlloyEchoTranslator.getInstance().getMetamodel(metamodel.ID).sig_metamodel; for (Entry<ExprHasName,String> x : varstates.values()) { try { if(x.getKey().type().toExpr().isSame(statesig)) statesig = x.getKey(); } catch (Err e) { // TODO Auto-generated catch block e.printStackTrace(); } } } EStructuralFeature feature = AlloyEchoTranslator.getInstance().getESFeatureFromName(metamodel.ID, prop.getOwningType().getName(),prop.getName()); Field field = AlloyEchoTranslator.getInstance().getFieldFromFeature(metamodel.ID,feature); if (field == null && prop.getOpposite() != null && EchoOptionsSetup.getInstance().isOptimize()) { feature = AlloyEchoTranslator.getInstance().getESFeatureFromName(metamodel.ID, prop.getOpposite().getOwningType().getName(),prop.getOpposite().getName()); field = AlloyEchoTranslator.getInstance().getFieldFromFeature(metamodel.ID,feature); exp = (field.join(statesig)).transpose(); } else { exp = (field.join(statesig)); } if (exp == null) throw new Error ("Field not found: "+metamodeluri+", "+prop.getName()); return exp; } /** * Tries to convert an OCL transitive closure into an Alloy reflexive closure * @param x * @param y * @return * @throws ErrorTransform * @throws ErrorAlloy * @throws ErrorUnsupported */ private Expr closure2Reflexive (OCLExpression x, OCLExpression y) throws EchoError { Expr res = Sig.NONE.no(); OperationCallExp a = null,b = null; if ((x instanceof OperationCallExp) && ((OperationCallExp)x).getReferredOperation().getName().equals("includes") && ((OperationCallExp)y).getReferredOperation().getName().equals("=")) { a = (OperationCallExp) x; b = (OperationCallExp) y; } else if ((y instanceof OperationCallExp) && ((OperationCallExp)y).getReferredOperation().getName().equals("includes") && ((OperationCallExp)x).getReferredOperation().getName().equals("=")) { a = (OperationCallExp) y; b = (OperationCallExp) x; } else throw new Error(); IteratorExp it = (IteratorExp) a.getSource(); OperationCallExp itsrc = (OperationCallExp) it.getSource(); VariableExp a1 = ((VariableExp) itsrc.getSource()); VariableExp a2 = ((VariableExp) a.getArgument().get(0)); VariableExp b1 = ((VariableExp) b.getSource()); VariableExp b2 = ((VariableExp) b.getArgument().get(0)); if((a2.getReferredVariable().equals(b1.getReferredVariable()) && a1.getReferredVariable().equals(b2.getReferredVariable())) || (a2.getReferredVariable().equals(b2.getReferredVariable()) && a1.getReferredVariable().equals(b1.getReferredVariable()))) { HashSet<EVariable> aux = new HashSet<EVariable>(); for (VariableDeclaration xx : it.getIterator()) aux.add(EVariable.getVariable(xx)); Decl d = AlloyUtil.variableListToExpr(aux, varstates, isPre?prevars:posvars).get(it.getIterator().get(0).getName()); try{ varstates.put(d.get().label,new SimpleEntry<ExprHasName,String>(d.get(),null)); Expr bdy = oclExprToAlloy(it.getBody()); Decl dd = bdy.oneOf("2_"); res = res.comprehensionOver(d,dd); } catch (Err e) {varstates.remove(d.get().label); throw new ErrorAlloy(e.getMessage());} Expr v1 = oclExprToAlloy(a1); Expr v2 = oclExprToAlloy(a2); res = v2.in(v1.join(res.reflexiveClosure())); varstates.remove(d.get().label); } return res; } public Map<String,Integer> getOCLAreNews() { return news; } @Override public Expr translateExpressions(List<Object> lex) throws EchoError{ Expr expr = Sig.NONE.no(); for (Object ex : lex) { expr = AlloyUtil.cleanAnd(expr, this.oclExprToAlloy((OCLExpression) ex)); } return expr; } }
package org.jboss.as.test.integration.management.cli; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.io.FileUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.cli.CommandContext; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.management.util.CLITestUtil; import org.jboss.as.test.integration.management.util.SimpleServlet; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.impl.base.exporter.ExplodedExporterImpl; import org.jboss.shrinkwrap.impl.base.exporter.zip.ZipExporterImpl; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * @author Alexey Loubyansky * */ @RunWith(Arquillian.class) @RunAsClient public class DeploymentOverlayCLITestCase { private static File replacedLibrary; private static File addedLibrary; private static File war1; private static File war1_exploded; private static File war2; private static File war2_exploded; private static File war3; private static File ear1; private static File ear1_exploded; private static File ear2; private static File ear2_exploded; private static File webXml; private static File overrideXml; private static File replacedAjsp; @ArquillianResource URL url; private String baseUrl; private CommandContext ctx; @Deployment public static Archive<?> getDeployment() { JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "dummy.jar"); ja.addClass(DeploymentOverlayCLITestCase.class); return ja; } @BeforeClass public static void before() throws Exception { String tempDir = TestSuiteEnvironment.getTmpDir(); WebArchive war; JavaArchive jar; jar = ShrinkWrap.create(JavaArchive.class, "lib.jar"); jar.addClass(ReplacedLibraryServlet.class); jar.add(new StringAsset("replaced library"),"jar-info.txt"); replacedLibrary = new File(tempDir + File.separator + jar.getName()); new ZipExporterImpl(jar).exportTo(replacedLibrary, true); jar = ShrinkWrap.create(JavaArchive.class, "addedlib.jar"); jar.addClass(AddedLibraryServlet.class); addedLibrary = new File(tempDir + File.separator + jar.getName()); new ZipExporterImpl(jar).exportTo(addedLibrary, true); jar = ShrinkWrap.create(JavaArchive.class, "lib.jar"); jar.addClass(OriginalLibraryServlet.class); // deployment1 war = ShrinkWrap.create(WebArchive.class, "deployment0.war"); war.addClass(SimpleServlet.class); war.addAsWebResource(DeploymentOverlayCLITestCase.class.getPackage(), "a.jsp", "a.jsp"); war.addAsWebInfResource(DeploymentOverlayCLITestCase.class.getPackage(), "web.xml", "web.xml"); war.addAsLibraries(jar); File explodedwars_basedir = new File(tempDir + File.separator + "exploded_deployments"); explodedwars_basedir.mkdirs(); war1 = new File(tempDir + File.separator + war.getName()); new ZipExporterImpl(war).exportTo(war1, true); war1_exploded = new ExplodedExporterImpl(war).exportExploded(explodedwars_basedir); war = ShrinkWrap.create(WebArchive.class, "deployment1.war"); war.addClass(SimpleServlet.class); war.addAsWebInfResource(DeploymentOverlayCLITestCase.class.getPackage(), "web.xml", "web.xml"); war.addAsLibraries(jar); war2 = new File(tempDir + File.separator + war.getName()); new ZipExporterImpl(war).exportTo(war2, true); war2_exploded = new ExplodedExporterImpl(war).exportExploded(explodedwars_basedir); war = ShrinkWrap.create(WebArchive.class, "another.war"); war.addClass(SimpleServlet.class); war.addAsWebInfResource(DeploymentOverlayCLITestCase.class.getPackage(), "web.xml", "web.xml"); war.addAsLibraries(jar); war3 = new File(tempDir + File.separator + war.getName()); new ZipExporterImpl(war).exportTo(war3, true); EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "eardeployment1.ear"); ear.addAsModule(war1); ear1 = new File(tempDir + File.separator + ear.getName()); new ZipExporterImpl(ear).exportTo(ear1, true); ear1_exploded = new ExplodedExporterImpl(ear).exportExploded(explodedwars_basedir); war = ShrinkWrap.create(WebArchive.class, "deployment0.war"); war.addClass(SimpleServlet.class); war.addClass(EarServlet.class); war.addAsWebResource(DeploymentOverlayCLITestCase.class.getPackage(), "a.jsp", "a.jsp"); war.addAsWebInfResource(DeploymentOverlayCLITestCase.class.getPackage(), "web.xml", "web.xml"); jar = ShrinkWrap.create(JavaArchive.class, "lib.jar"); jar.add(new StringAsset("original library"),"jar-info.txt"); ear = ShrinkWrap.create(EnterpriseArchive.class, "eardeployment2.ear"); ear.addAsModule(war); ear.addAsLibraries(jar); ear2 = new File(tempDir + File.separator + ear.getName()); new ZipExporterImpl(ear).exportTo(ear2, true); ear2_exploded = new ExplodedExporterImpl(ear).exportExploded(explodedwars_basedir); final URL overrideXmlUrl = DeploymentOverlayCLITestCase.class.getResource("override.xml"); if(overrideXmlUrl == null) { Assert.fail("Failed to locate override.xml"); } overrideXml = new File(overrideXmlUrl.toURI()); if(!overrideXml.exists()) { Assert.fail("Failed to locate override.xml"); } final URL webXmlUrl = DeploymentOverlayCLITestCase.class.getResource("web.xml"); if(webXmlUrl == null) { Assert.fail("Failed to locateweb.xml"); } webXml = new File(webXmlUrl.toURI()); if(!webXml.exists()) { Assert.fail("Failed to locate web.xml"); } final URL ajsp = DeploymentOverlayCLITestCase.class.getResource("a-replaced.jsp"); if(ajsp == null) { Assert.fail("Failed to locate a-replaced.jsp"); } replacedAjsp = new File(ajsp.toURI()); if(!replacedAjsp.exists()) { Assert.fail("Failed to locate a-replaced.jsp"); } } @AfterClass public static void after() throws Exception { war1.delete(); FileUtils.deleteDirectory(war1_exploded); war2.delete(); FileUtils.deleteDirectory(war2_exploded); war3.delete(); ear1.delete(); FileUtils.deleteDirectory(ear1_exploded); ear2.delete(); FileUtils.deleteDirectory(ear2_exploded); replacedLibrary.delete(); // replacedAjsp.delete(); addedLibrary.delete(); } protected final String getBaseURL(URL url) throws MalformedURLException { return new URL(url.getProtocol(), url.getHost(), url.getPort(), "/").toString(); } @Before public void setUp() throws Exception { ctx = CLITestUtil.getCommandContext(); ctx.connectController(); baseUrl = getBaseURL(url); } @After public void tearDown() throws Exception { if(ctx != null) { ctx.handleSafe("undeploy " + war1.getName()); ctx.handleSafe("undeploy " + war2.getName()); ctx.handleSafe("undeploy " + war3.getName()); ctx.handleSafe("undeploy " + ear1.getName()); ctx.handleSafe("undeploy " + ear2.getName()); ctx.handleSafe("deployment-overlay remove --name=overlay-test"); ctx.handleSafe("deployment-overlay remove --name=overlay1"); ctx.handleSafe("deployment-overlay remove --name=overlay2"); ctx.handleSafe("deployment-overlay remove --name=overlay3"); ctx.terminateSession(); } } @Test public void testSimpleOverride() throws Exception { simpleOverrideTest(false); } @Test public void testSimpleOverrideMultipleDeploymentOverlay() throws Exception { simpleOverrideTest(true); } private void simpleOverrideTest(boolean multipleOverlay) throws Exception { ctx.handle("deploy " + war1.getAbsolutePath()); ctx.handle("deploy " + war2.getAbsolutePath()); if(multipleOverlay){ ctx.handle("deployment-overlay add --name=overlay1 --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + ",a.jsp=" + replacedAjsp.getAbsolutePath() + " --deployments=" + war1.getName()); ctx.handle("deployment-overlay add --name=overlay2 --content=WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=" + war1.getName()); ctx.handle("deployment-overlay add --name=overlay3 --content=WEB-INF/lib/addedlib.jar=" + addedLibrary.getAbsolutePath() + " --deployments=" + war1.getName()); }else{ ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + ",a.jsp=" + replacedAjsp.getAbsolutePath() + ",WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + ",WEB-INF/lib/addedlib.jar=" + addedLibrary.getAbsolutePath() + " --deployments=" + war1.getName()); } String response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); ctx.handle("/deployment=" + war1.getName() + ":redeploy"); ctx.handle("/deployment=" + war2.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); //now test JSP assertEquals("Replaced JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); //now test Libraries assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment0/LibraryServlet", 10, TimeUnit.SECONDS).trim()); assertEquals("Added Library Servlet", HttpRequest.get(baseUrl + "deployment0/AddedLibraryServlet", 10, TimeUnit.SECONDS).trim()); } @Test public void testSimpleOverrideExploded() throws Exception { simpleOverrideExplodedTest(false); } @Test public void testSimpleOverrideExplodedMultipleDeploymentOverlay() throws Exception { simpleOverrideExplodedTest(true); } private void simpleOverrideExplodedTest(boolean multiple) throws Exception { ctx.handle("/deployment="+war1_exploded.getName() +":add(content=[{\"path\"=>\""+war1_exploded.getAbsolutePath().replace("\\", "\\\\")+"\",\"archive\"=>false}], enabled=true)"); ctx.handle("/deployment="+war2_exploded.getName() +":add(content=[{\"path\"=>\""+war2_exploded.getAbsolutePath().replace("\\", "\\\\")+"\",\"archive\"=>false}], enabled=true)"); if(multiple){ ctx.handle("deployment-overlay add --name=overlay1 --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + ",a.jsp=" + replacedAjsp.getAbsolutePath() + " --deployments=" + war1_exploded.getName()); ctx.handle("deployment-overlay add --name=overlay2 --content=WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=" + war1_exploded.getName()); ctx.handle("deployment-overlay add --name=overlay3 --content=WEB-INF/lib/addedlib.jar=" + addedLibrary.getAbsolutePath() + " --deployments=" + war1_exploded.getName()); }else{ ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + ",a.jsp=" + replacedAjsp.getAbsolutePath() + ",WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + ",WEB-INF/lib/addedlib.jar=" + addedLibrary.getAbsolutePath() + " --deployments=" + war1_exploded.getName()); } String response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); ctx.handle("/deployment=" + war1_exploded.getName() + ":redeploy"); ctx.handle("/deployment=" + war2_exploded.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); // replacing JSP files in exploded deployments is not supported - see WFLY-2989 for more details // assertEquals("Replaced JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); //now test Libraries assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment0/LibraryServlet", 10, TimeUnit.SECONDS).trim()); assertEquals("Added Library Servlet", HttpRequest.get(baseUrl + "deployment0/AddedLibraryServlet", 10, TimeUnit.SECONDS).trim()); } @Test public void testSimpleOverrideInEarAtWarLevel() throws Exception { simpleOverrideInEarAtWarLevelTest(false); } @Test public void testSimpleOverrideInEarAtWarLevelMultipleDeploymentOverlay() throws Exception { simpleOverrideInEarAtWarLevelTest(true); } private void simpleOverrideInEarAtWarLevelTest(boolean multiple) throws Exception { ctx.handle("deploy " + ear1.getAbsolutePath()); if(multiple){ ctx.handle("deployment-overlay add --name=overlay1 --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + ",a.jsp=" + replacedAjsp.getAbsolutePath() + " --deployments=" + war1.getName()); ctx.handle("deployment-overlay add --name=overlay2 --content=WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=" + war1.getName()); }else{ ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + ",a.jsp=" + replacedAjsp.getAbsolutePath() + ",WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=" + war1.getName()); } String response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); ctx.handle("/deployment=" + ear1.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); //now test JSP assertEquals("Replaced JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); //now test Libraries assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment0/LibraryServlet", 10, TimeUnit.SECONDS).trim()); } @Test public void testSimpleOverrideInEarAtWarLevelExploded() throws Exception { simpleOverrideInEarAtWarLevelExplodedTest(false); } @Test public void testSimpleOverrideInEarAtWarLevelExplodedMultipleDeploymentOverlay() throws Exception { simpleOverrideInEarAtWarLevelExplodedTest(true); } private void simpleOverrideInEarAtWarLevelExplodedTest(boolean multiple) throws Exception { ctx.handle("/deployment="+ear1_exploded.getName() +":add(content=[{\"path\"=>\""+ear1_exploded.getAbsolutePath().replace("\\", "\\\\")+"\",\"archive\"=>false}], enabled=true)"); if(multiple){ ctx.handle("deployment-overlay add --name=overlay1 --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + ",a.jsp=" + replacedAjsp.getAbsolutePath() + " --deployments=" + war1.getName()); ctx.handle("deployment-overlay add --name=overlay2 --content=WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=" + war1.getName()); }else{ ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + ",a.jsp=" + replacedAjsp.getAbsolutePath() + ",WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=" + war1.getName()); } String response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); ctx.handle("/deployment=" + ear1_exploded.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); //now test JSP (it works here, because only the EAR is exploded, the inner WAR is not) assertEquals("Replaced JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); //now test Libraries assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment0/LibraryServlet", 10, TimeUnit.SECONDS).trim()); } @Test public void testSimpleOverrideInEarAtEarLevel() throws Exception { ctx.handle("deploy " + ear2.getAbsolutePath()); ctx.handle("deployment-overlay add --name=overlay-test --content=lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=" + ear2.getName()); //now test Libraries assertEquals("original library", HttpRequest.get(baseUrl + "deployment0/EarServlet", 10, TimeUnit.SECONDS).trim()); ctx.handle("/deployment=" + ear2.getName() + ":redeploy"); //now test Libraries assertEquals("replaced library", HttpRequest.get(baseUrl + "deployment0/EarServlet", 10, TimeUnit.SECONDS).trim()); } @Test public void testSimpleOverrideInEarAtEarLevelExploded() throws Exception { ctx.handle("/deployment="+ear2_exploded.getName() +":add(content=[{\"path\"=>\""+ear2_exploded.getAbsolutePath().replace("\\", "\\\\")+"\",\"archive\"=>false}], enabled=true)"); ctx.handle("deployment-overlay add --name=overlay-test --content=lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=" + ear2_exploded.getName()); //now test Libraries assertEquals("original library", HttpRequest.get(baseUrl + "deployment0/EarServlet", 10, TimeUnit.SECONDS).trim()); ctx.handle("/deployment=" + ear2_exploded.getName() + ":redeploy"); //now test Libraries assertEquals("replaced library", HttpRequest.get(baseUrl + "deployment0/EarServlet", 10, TimeUnit.SECONDS).trim()); } @Test public void testSimpleOverrideWithRedeployAffected() throws Exception { simpleOverrideWithRedeployAffectedTest(false); } @Test public void testSimpleOverrideWithRedeployAffectedMultipleDeploymentOverlay() throws Exception { simpleOverrideWithRedeployAffectedTest(true); } private void simpleOverrideWithRedeployAffectedTest(boolean multiple) throws Exception { ctx.handle("deploy " + war1.getAbsolutePath()); ctx.handle("deploy " + war2.getAbsolutePath()); String response1 = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response1); if(multiple){ ctx.handle("deployment-overlay add --name=overlay1 --content=a.jsp=" + replacedAjsp.getAbsolutePath() + " --deployments=" + war1.getName()); ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --deployments=" + war1.getName() + " --redeploy-affected"); }else{ ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --deployments=" + war1.getName() + " --redeploy-affected"); } String response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); if(multiple){ //now test JSP assertEquals("Replaced JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); } } @Test public void testWildcardOverride() throws Exception { wildcardOverrideTest(false); } @Test public void testWildcardOverrideMultipleDeploymentOverlay() throws Exception { wildcardOverrideTest(true); } private void wildcardOverrideTest(boolean multiple) throws Exception { if(multiple){ ctx.handle("deployment-overlay add --name=overlay1 --content=WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=deployment*.war"); } ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --deployments=deployment*.war"); ctx.handle("deploy " + war1.getAbsolutePath()); ctx.handle("deploy " + war2.getAbsolutePath()); ctx.handle("deploy " + war3.getAbsolutePath()); String response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("OVERRIDDEN", response); response = readResponse("another"); assertEquals("NON OVERRIDDEN", response); if(multiple){ assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment0/LibraryServlet", 10, TimeUnit.SECONDS).trim()); assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment1/LibraryServlet", 10, TimeUnit.SECONDS).trim()); } } @Test public void testWildcardOverrideWithRedeployAffected() throws Exception { wildcardOverrideWithRedeployAffectedTest(false); } @Test public void testWildcardOverrideWithRedeployAffectedMultipleDeploymentOverlay() throws Exception { wildcardOverrideWithRedeployAffectedTest(true); } private void wildcardOverrideWithRedeployAffectedTest(boolean multiple) throws Exception { ctx.handle("deploy " + war1.getAbsolutePath()); ctx.handle("deploy " + war2.getAbsolutePath()); ctx.handle("deploy " + war3.getAbsolutePath()); if(multiple){ ctx.handle("deployment-overlay add --name=overlay1 --content=WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath() + " --deployments=deployment*.war"); } ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --deployments=deployment*.war --redeploy-affected"); //Thread.sleep(2000); String response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("OVERRIDDEN", response); response = readResponse("another"); assertEquals("NON OVERRIDDEN", response); if(multiple){ assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment0/LibraryServlet", 10, TimeUnit.SECONDS).trim()); assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment1/LibraryServlet", 10, TimeUnit.SECONDS).trim()); } } @Test public void testMultipleLinks() throws Exception { ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --deployments=" + war1.getName()); ctx.handle("deploy " + war1.getAbsolutePath()); ctx.handle("deploy " + war2.getAbsolutePath()); ctx.handle("deploy " + war3.getAbsolutePath()); String response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("NON OVERRIDDEN", response); ctx.handle("deployment-overlay link --name=overlay-test --deployments=a*.war"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("NON OVERRIDDEN", response); ctx.handle("/deployment=" + war1.getName() + ":redeploy"); ctx.handle("/deployment=" + war2.getName() + ":redeploy"); ctx.handle("/deployment=" + war3.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("OVERRIDDEN", response); ctx.handle("deployment-overlay link --name=overlay-test --deployments=" + war2.getName() + " --redeploy-affected"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("OVERRIDDEN", response); response = readResponse("another"); assertEquals("OVERRIDDEN", response); ctx.handle("deployment-overlay remove --name=overlay-test --deployments=" + war2.getName() + " --redeploy-affected"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("OVERRIDDEN", response); ctx.handle("deployment-overlay remove --name=overlay-test --deployments=a*.war"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("OVERRIDDEN", response); ctx.handle("/deployment=" + war1.getName() + ":redeploy"); ctx.handle("/deployment=" + war2.getName() + ":redeploy"); ctx.handle("/deployment=" + war3.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("NON OVERRIDDEN", response); ctx.handle("deployment-overlay remove --name=overlay-test --content=WEB-INF/web.xml --redeploy-affected"); response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("NON OVERRIDDEN", response); ctx.handle("deployment-overlay upload --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath() + " --redeploy-affected"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("NON OVERRIDDEN", response); } @Test public void testRedeployAffected() throws Exception { ctx.handle("deploy " + war1.getAbsolutePath()); ctx.handle("deploy " + war2.getAbsolutePath()); ctx.handle("deploy " + war3.getAbsolutePath()); ctx.handle("deployment-overlay add --name=overlay-test --content=WEB-INF/web.xml=" + overrideXml.getAbsolutePath()); ctx.handle("deployment-overlay link --name=overlay-test --deployments=deployment0.war,a*.war"); String response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("NON OVERRIDDEN", response); ctx.handle("deployment-overlay redeploy-affected --name=overlay-test"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); response = readResponse("another"); assertEquals("OVERRIDDEN", response); } @Test public void testSimpleOverrideRemoveOverlay() throws Exception { ctx.handle("deploy " + war1.getAbsolutePath()); ctx.handle("deploy " + war2.getAbsolutePath()); ctx.handle("deployment-overlay add --name=" + "overlay-test --content=" + "WEB-INF/web.xml=" + overrideXml.getAbsolutePath()+"," + "a.jsp=" + replacedAjsp.getAbsolutePath() + "," + "WEB-INF/lib/lib.jar=" + replacedLibrary.getAbsolutePath()+"," + "WEB-INF/lib/addedlib.jar=" + addedLibrary.getAbsolutePath() + " --deployments=" + war1.getName()); String response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); ctx.handle("/deployment=" + war1.getName() + ":redeploy"); ctx.handle("/deployment=" + war2.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); //now test JSP assertEquals("Replaced JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); //now test Libraries assertEquals("Replaced Library Servlet", HttpRequest.get(baseUrl + "deployment0/LibraryServlet", 10, TimeUnit.SECONDS).trim()); assertEquals("Added Library Servlet", HttpRequest.get(baseUrl + "deployment0/AddedLibraryServlet", 10, TimeUnit.SECONDS).trim()); ctx.handleSafe("deployment-overlay remove --name=overlay-test"); ctx.handle("/deployment=" + war1.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); //now test Libraries assertEquals("Original Library Servlet", HttpRequest.get(baseUrl + "deployment0/LibraryServlet", 10, TimeUnit.SECONDS).trim()); try{ // Assert.assertNotEquals("Added Library Servlet", HttpRequest.get(baseUrl + "deployment0/AddedLibraryServlet", 10, TimeUnit.SECONDS).trim()); HttpRequest.get(baseUrl + "deployment0/AddedLibraryServlet", 10, TimeUnit.SECONDS); Assert.fail(); }catch (IOException e){ } //now test JSP assertEquals("Original JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); } @Test public void testSimpleOverrideRemoveOverlay2() throws Exception { ctx.handle("deploy " + war1.getAbsolutePath()); ctx.handle("deploy " + war2.getAbsolutePath()); ctx.handle("deployment-overlay add --name=" + "overlay-test --content=" + "a.jsp=" + replacedAjsp.getAbsolutePath() + "," + " --deployments=" + war1.getName()); String response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); ctx.handle("/deployment=" + war1.getName() + ":redeploy"); ctx.handle("/deployment=" + war2.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); response = readResponse("deployment1"); assertEquals("NON OVERRIDDEN", response); //now test JSP assertEquals("Replaced JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); ctx.handleSafe("deployment-overlay remove --name=overlay-test"); ctx.handle("/deployment=" + war1.getName() + ":redeploy"); response = readResponse("deployment0"); assertEquals("NON OVERRIDDEN", response); //now test JSP assertEquals("Original JSP File", HttpRequest.get(baseUrl + "deployment0/a.jsp", 10, TimeUnit.SECONDS).trim()); } protected String readResponse(String warName) throws IOException, ExecutionException, TimeoutException, MalformedURLException { return HttpRequest.get(baseUrl + warName + "/SimpleServlet?env-entry=overlay-test", 10, TimeUnit.SECONDS).trim(); } }
package edu.umd.cs.findbugs; import java.io.*; import java.util.*; import java.util.jar.*; import java.util.zip.*; import edu.umd.cs.pugh.io.IO; import edu.umd.cs.pugh.visitclass.Constants2; import org.apache.bcel.classfile.*; import org.apache.bcel.Repository; import org.apache.bcel.util.ClassPath; import org.apache.bcel.util.SyntheticRepository; import edu.umd.cs.daveho.ba.AnalysisContext; import edu.umd.cs.daveho.ba.AnalysisException; import edu.umd.cs.daveho.ba.ClassContext; import edu.umd.cs.daveho.ba.ClassObserver; /** * An instance of this class is used to apply the selected set of * analyses on some collection of Java classes. It also implements the * comand line interface. * * @author Bill Pugh * @author David Hovemeyer */ public class FindBugs implements Constants2, ExitCodes { /** * Interface for an object representing a source of class files to analyze. */ private interface ClassProducer { /** * Get the next class to analyze. * @return the class, or null of there are no more classes for this ClassProducer * @throws IOException if an IOException occurs * @throws InterruptedException if the thread is interrupted */ public JavaClass getNextClass() throws IOException, InterruptedException; /** * Did this class producer scan any Java source files? */ public boolean containsSourceFiles(); /** * Add any aux classpath entries in the resource * to given list. * @param list the list of aux classpath entries */ public void addAuxClasspathEntries(List<String> list); } /** * ClassProducer for single class files. */ private static class SingleClassProducer implements ClassProducer { private String fileName; /** * Constructor. * @param fileName the single class file to be analyzed */ public SingleClassProducer(String fileName) { this.fileName = fileName; } public JavaClass getNextClass() throws IOException, InterruptedException { if (fileName == null) return null; if (Thread.interrupted()) throw new InterruptedException(); String fileNameToParse = fileName; fileName = null; // don't return it next time try { return new ClassParser(fileNameToParse).parse(); } catch (ClassFormatException e) { throw new ClassFormatException("Invalid class file format for " + fileNameToParse + ": " + e.getMessage()); } } public boolean containsSourceFiles() { return false; } public void addAuxClasspathEntries(List<String> list) { } } /** * ClassProducer for .zip and .jar files. * Nested jar and zip files are also scanned for classes; * this is needed for .ear and .war files associated with EJBs. */ private static class ZipClassProducer implements ClassProducer { private String fileName; private boolean isJar; private String nestedFileName; private ZipFile zipFile; private Enumeration entries; private ZipInputStream zipStream; private boolean containsSourceFiles; // a DataInputStream wrapper that cannot be closed private static class DupDataStream extends DataInputStream { public DupDataStream( InputStream in ) { super( in ); } public void close() { }; } /** * Constructor. * @param fileName the name of the zip or jar file */ public ZipClassProducer(String fileName) throws IOException { this.fileName = fileName; this.isJar = fileName.endsWith(".jar"); this.zipFile = isJar ? (ZipFile)new JarFile(fileName) : new ZipFile(fileName); this.entries = zipFile.entries(); this.zipStream = null; this.nestedFileName = null; this.containsSourceFiles = false; } private void setZipStream( ZipInputStream in, String fileName ) { zipStream = in; nestedFileName = fileName; } private void closeZipStream() throws IOException { zipStream.close(); zipStream = null; nestedFileName = null; } private JavaClass getNextNestedClass() throws IOException, InterruptedException { JavaClass parsedClass = null; if ( zipStream != null ) { ZipEntry entry = zipStream.getNextEntry(); while ( entry != null ) { if (Thread.interrupted()) throw new InterruptedException(); if ( entry.getName().endsWith( ".class" ) ) { try { parsedClass = new ClassParser( new DupDataStream(zipStream), entry.getName()).parse(); break; } catch (ClassFormatException e) { throw new ClassFormatException("Invalid class file format for " + fileName + ":" + nestedFileName + ":" + entry.getName() + ": " + e.getMessage()); } } entry = zipStream.getNextEntry(); } if ( parsedClass == null ) { closeZipStream(); } } return parsedClass; } public JavaClass getNextClass() throws IOException, InterruptedException { JavaClass parsedClass = getNextNestedClass(); if ( parsedClass == null ) { while (entries.hasMoreElements()) { if (Thread.interrupted()) throw new InterruptedException(); ZipEntry entry = (ZipEntry) entries.nextElement(); String name = entry.getName(); if (name.endsWith(".class")) { try { parsedClass = new ClassParser(zipFile.getInputStream(entry), name).parse(); break; } catch (ClassFormatException e) { throw new ClassFormatException("Invalid class file format for " + fileName + ":" + name + ": " + e.getMessage()); } } else if ( name.endsWith(".jar") || name.endsWith( ".zip" ) ) { setZipStream(new ZipInputStream(zipFile.getInputStream(entry)), name ); parsedClass = getNextNestedClass(); if ( parsedClass != null ) { break; } } else if (name.endsWith(".java")) containsSourceFiles = true; } } return parsedClass; } public boolean containsSourceFiles() { return containsSourceFiles; } public void addAuxClasspathEntries(List<String> list) { // TODO: get them from the manifest } } /** * ClassProducer for directories. * The directory is scanned recursively for class files. */ private static class DirectoryClassProducer implements ClassProducer { private Iterator<String> rfsIter; private boolean containsSourceFiles; public DirectoryClassProducer(String dirName) throws InterruptedException { FileFilter filter = new FileFilter() { public boolean accept(File file) { String fileName = file.getName(); if (file.isDirectory() || fileName.endsWith(".class")) return true; if (fileName.endsWith(".java")) containsSourceFiles = true; return false; } }; // This will throw InterruptedException if the thread is // interrupted. RecursiveFileSearch rfs = new RecursiveFileSearch(dirName, filter).search(); this.rfsIter = rfs.fileNameIterator(); this.containsSourceFiles = false; } public JavaClass getNextClass() throws IOException, InterruptedException { if (!rfsIter.hasNext()) return null; String fileName = rfsIter.next(); try { return new ClassParser(fileName).parse(); } catch (ClassFormatException e) { throw new ClassFormatException("Invalid class file format for " + fileName + ": " + e.getMessage()); } } public boolean containsSourceFiles() { return containsSourceFiles; } public void addAuxClasspathEntries(List<String> list) { } } /** * A delegating bug reporter which counts reported bug instances, * missing classes, and serious analysis errors. */ private static class ErrorCountingBugReporter extends DelegatingBugReporter { private int bugCount; private int missingClassCount; private int errorCount; private Set<String> missingClassSet = new HashSet<String>(); public ErrorCountingBugReporter(BugReporter realBugReporter) { super(realBugReporter); this.bugCount = 0; this.missingClassCount = 0; this.errorCount = 0; // Add an observer to record when bugs make it through // all priority and filter criteria, so our bug count is // accurate. realBugReporter.addObserver(new BugReporterObserver() { public void reportBug(BugInstance bugInstance) { ++bugCount; } }); } public int getBugCount() { return bugCount; } public int getMissingClassCount() { return missingClassCount; } public int getErrorCount() { return errorCount; } public void logError(String message) { ++errorCount; super.logError(message); } public void reportMissingClass(ClassNotFoundException ex) { String missing = AbstractBugReporter.getMissingClassName(ex); if (missingClassSet.add(missing)) ++missingClassCount; super.reportMissingClass(ex); } } private static final boolean DEBUG = Boolean.getBoolean("findbugs.debug"); /** FindBugs home directory. */ private static String home; private ErrorCountingBugReporter bugReporter; private Project project; private List<ClassObserver> classObserverList; private Detector detectors []; private FindBugsProgress progressCallback; /** * Constructor. * @param bugReporter the BugReporter object that will be used to report * BugInstance objects, analysis errors, class to source mapping, etc. * @param project the Project indicating which files to analyze and * the auxiliary classpath to use */ public FindBugs(BugReporter bugReporter, Project project) { if (bugReporter == null) throw new IllegalArgumentException("null bugReporter"); if (project == null) throw new IllegalArgumentException("null project"); this.bugReporter = new ErrorCountingBugReporter(bugReporter); this.project = project; this.classObserverList = new LinkedList<ClassObserver>(); // Create a no-op progress callback. this.progressCallback = new FindBugsProgress() { public void reportNumberOfArchives(int numArchives) { } public void finishArchive() { } public void startAnalysis(int numClasses) { } public void finishClass() { } public void finishPerClassAnalysis() { } }; addClassObserver(bugReporter); } /** * Set the progress callback that will be used to keep track * of the progress of the analysis. * @param progressCallback the progress callback */ public void setProgressCallback(FindBugsProgress progressCallback) { this.progressCallback = progressCallback; } /** * Set filter of bug instances to include or exclude. * @param filterFileName the name of the filter file * @param include true if the filter specifies bug instances to include, * false if it specifies bug instances to exclude */ public void setFilter(String filterFileName, boolean include) throws IOException, FilterException { Filter filter = new Filter(filterFileName); BugReporter origBugReporter = bugReporter.getRealBugReporter(); BugReporter filterBugReporter = new FilterBugReporter(origBugReporter, filter, include); bugReporter.setRealBugReporter(filterBugReporter); } /** * Add a ClassObserver. * @param classObserver the ClassObserver */ public void addClassObserver(ClassObserver classObserver) { classObserverList.add(classObserver); } /** * Execute FindBugs on the Project. * All bugs found are reported to the BugReporter object which was set * when this object was constructed. * @throws java.io.IOException if an I/O exception occurs analyzing one of the files * @throws InterruptedException if the thread is interrupted while conducting the analysis */ public void execute() throws java.io.IOException, InterruptedException { // Configure the analysis context AnalysisContext analysisContext = AnalysisContext.instance(); analysisContext.setLookupFailureCallback(bugReporter); analysisContext.setSourcePath(project.getSourceDirList()); // Create detectors, if required if (detectors == null) createDetectors(); // Clear repository and analysis context cache of all class files clearRepository(); // Scan all jar files and directories, // making a list of all classes encountered. // We also keep track of all resources referenced by // Class-Path entries in the manifests of scanned jar // files, in order to add them to the auxiliary classpath // when the analysis is performed. String[] argv = project.getJarFileArray(); progressCallback.reportNumberOfArchives(argv.length); List<String> repositoryClassList = new LinkedList<String>(); List<String> manifestClassPathEntryList = new LinkedList<String>(); for (int i = 0; i < argv.length; i++) addFileToRepository(argv[i], repositoryClassList, manifestClassPathEntryList); // Set the classpath to be used for class lookups. setClasspath(manifestClassPathEntryList); // Examine all classes for bugs. // Don't examine the same class more than once. // (The user might specify two jar files that contain // the same class.) progressCallback.startAnalysis(repositoryClassList.size()); Set<String> examinedClassSet = new HashSet<String>(); for (Iterator<String> i = repositoryClassList.iterator(); i.hasNext(); ) { String className = i.next(); if (examinedClassSet.add(className)) examineClass(className); } progressCallback.finishPerClassAnalysis(); this.reportFinal(); // Flush any queued bug reports bugReporter.finish(); // Flush any queued error reports bugReporter.reportQueuedErrors(); } /** * Get the number of bug instances that were reported during analysis. */ public int getBugCount() { return bugReporter.getBugCount(); } /** * Get the number of errors that occurred during analysis. */ public int getErrorCount() { return bugReporter.getErrorCount(); } /** * Get the number of time missing classes were reported during analysis. */ public int getMissingClassCount() { return bugReporter.getMissingClassCount(); } /** * Set the FindBugs home directory. */ public static void setHome(String home) { FindBugs.home = home; } /** * Get the FindBugs home directory. */ public static String getHome() { if (home == null) { home = System.getProperty("findbugs.home"); if (home == null) { System.err.println("Error: The findbugs.home property is not set!"); System.exit(1); } } return home; } /** * Create Detectors for each enabled DetectorFactory. * This will populate the detectors array. */ private void createDetectors() { ArrayList<Detector> result = new ArrayList<Detector>(); Iterator<DetectorFactory> i = DetectorFactoryCollection.instance().factoryIterator(); int count = 0; while (i.hasNext()) { DetectorFactory factory = i.next(); if (factory.isEnabled()) result.add(factory.create(bugReporter)); } detectors = result.toArray(new Detector[0]); } /** * Clear the Repository and AnalysisContext cache. * This will ensure that no stale classfiles are left over * from a previous execution. */ private void clearRepository() { // Purge repository of previous contents Repository.clearCache(); // Clear the cache in the AnalysisContext. AnalysisContext.instance().clearCache(); } /** * Set up the classpath to be used to perform class lookups * during the analysis. This is based on the project, * and also on the Class-Path entries in the manifests of * scanned jar files. * @param manifestClassPathEntryList list of aux classpath entries found * in the manifests of scanned jar files */ private void setClasspath(List<String> manifestClassPathEntryList) { // Create a SyntheticRepository based on the current project, // and make it current. StringBuffer buf = new StringBuffer(); List<String> auxClasspathEntryList = project.getAuxClasspathEntryList(); Iterator i = auxClasspathEntryList.iterator(); while (i.hasNext()) { String entry = (String) i.next(); buf.append(entry); buf.append(File.pathSeparatorChar); } // Add the system classpath entries buf.append(ClassPath.getClassPath()); if (DEBUG) System.out.println("System classpath: " + buf.toString()); // Set up the Repository to use the combined classpath ClassPath classPath = new ClassPath(buf.toString()); SyntheticRepository repository = SyntheticRepository.getInstance(classPath); Repository.setRepository(repository); } /** * Add all classes contained in given file to the BCEL Repository. * @param fileName the file, which may be a jar/zip archive, a single class file, * or a directory to be recursively searched for class files * @param manifestClassPathEntryList list used to store aux classpath entries * found in the manifests of scanned jar files */ private void addFileToRepository(String fileName, List<String> repositoryClassList, List<String> manifestClassPathEntryList) throws IOException, InterruptedException { try { ClassProducer classProducer; // Create the ClassProducer if (fileName.endsWith(".jar") || fileName.endsWith(".zip") || fileName.endsWith(".war") || fileName.endsWith(".ear")) classProducer = new ZipClassProducer(fileName); else if (fileName.endsWith(".class")) classProducer = new SingleClassProducer(fileName); else { File dir = new File(fileName); if (!dir.isDirectory()) throw new IOException("Path " + fileName + " is not an archive, class file, or directory"); classProducer = new DirectoryClassProducer(fileName); } // Load all referenced classes into the Repository for (;;) { if (Thread.interrupted()) throw new InterruptedException(); try { JavaClass jclass = classProducer.getNextClass(); if (jclass == null) break; Repository.addClass(jclass); repositoryClassList.add(jclass.getClassName()); } catch (ClassFormatException e) { e.printStackTrace(); bugReporter.logError(e.getMessage()); } } progressCallback.finishArchive(); // If the archive or directory scanned contained source files, // add it to the end of the source path. if (classProducer.containsSourceFiles()) project.addSourceDir(fileName); // If the archive or directory scanned contained // aux classpath entries, add them to the list. classProducer.addAuxClasspathEntries(manifestClassPathEntryList); } catch (IOException e) { // You'd think that the message for a FileNotFoundException would include // the filename, but you'd be wrong. So, we'll add it explicitly. throw new IOException("Could not analyze " + fileName + ": " + e.getMessage()); } } /** * Examine a single class by invoking all of the Detectors on it. * @param className the fully qualified name of the class to examine */ private void examineClass(String className) throws InterruptedException { if (DEBUG) System.out.println("Examining class " + className); try { JavaClass javaClass = Repository.lookupClass(className); // Notify ClassObservers for (Iterator<ClassObserver> i = classObserverList.iterator(); i.hasNext(); ) { i.next().observeClass(javaClass); } // Create a ClassContext for the class ClassContext classContext = AnalysisContext.instance().getClassContext(javaClass); // Run the Detectors for (int i = 0; i < detectors.length; ++i) { if (Thread.interrupted()) throw new InterruptedException(); try { Detector detector = detectors[i]; if (DEBUG) System.out.println(" running " + detector.getClass().getName()); detector.visitClassContext(classContext); } catch (AnalysisException e) { reportRecoverableException(className, e); } catch (ArrayIndexOutOfBoundsException e) { reportRecoverableException(className, e); } } } catch (ClassNotFoundException e) { // This should never happen unless there are bugs in BCEL. bugReporter.reportMissingClass(e); reportRecoverableException(className, e); } catch (ClassFormatException e) { reportRecoverableException(className, e); } progressCallback.finishClass(); } private void reportRecoverableException(String className, Exception e) { if (DEBUG) { e.printStackTrace(); } bugReporter.logError("Exception analyzing " + className + ": " + e.toString()); } /** * Call report() on all detectors, to give them a chance to * report any accumulated bug reports. */ private void reportFinal() throws InterruptedException { for (int i = 0; i < detectors.length; ++i) { if (Thread.interrupted()) throw new InterruptedException(); detectors[i].report(); } } private static final int PRINTING_REPORTER = 0; private static final int SORTING_REPORTER = 1; private static final int XML_REPORTER = 2; private static final int EMACS_REPORTER = 3; public static void main(String argv[]) throws Exception { int bugReporterType = PRINTING_REPORTER; Project project = new Project(); boolean quiet = false; String filterFile = null; boolean include = false; boolean setExitCode = false; int priorityThreshold = Detector.NORMAL_PRIORITY; PrintStream outputStream = null; // Process command line options int argCount = 0; while (argCount < argv.length) { String option = argv[argCount]; if (!option.startsWith("-")) break; if (option.equals("-home")) { ++argCount; if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument"); String homeDir = argv[argCount]; FindBugs.setHome(homeDir); } else if (option.equals("-pluginList")) { ++argCount; if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument"); String pluginListStr = argv[argCount]; ArrayList<File> pluginList = new ArrayList<File>(); StringTokenizer tok = new StringTokenizer(pluginListStr, File.pathSeparator); while (tok.hasMoreTokens()) { pluginList.add(new File(tok.nextToken())); } DetectorFactoryCollection.setPluginList((File[]) pluginList.toArray(new File[0])); } else if (option.equals("-low")) priorityThreshold = Detector.LOW_PRIORITY; else if (option.equals("-medium")) priorityThreshold = Detector.NORMAL_PRIORITY; else if (option.equals("-high")) priorityThreshold = Detector.HIGH_PRIORITY; else if (option.equals("-sortByClass")) bugReporterType = SORTING_REPORTER; else if (option.equals("-xml")) bugReporterType = XML_REPORTER; else if (option.equals("-emacs")) bugReporterType = EMACS_REPORTER; else if (option.equals("-outputFile")) { ++argCount; if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument"); String outputFile = argv[argCount]; try { outputStream = new PrintStream(new BufferedOutputStream(new FileOutputStream(outputFile))); } catch (IOException e) { System.err.println("Couldn't open " + outputFile + " for output: " + e.toString()); System.exit(1); } } else if (option.equals("-visitors") || option.equals("-omitVisitors")) { ++argCount; if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument"); boolean omit = option.equals("-omitVisitors"); if (!omit) { // Selecting detectors explicitly, so start out by // disabling all of them. The selected ones will // be re-enabled. Iterator<DetectorFactory> factoryIter = DetectorFactoryCollection.instance().factoryIterator(); while (factoryIter.hasNext()) { DetectorFactory factory = factoryIter.next(); factory.setEnabled(false); } } // Explicitly enable or disable the selected detectors. StringTokenizer tok = new StringTokenizer(argv[argCount], ","); while (tok.hasMoreTokens()) { String visitorName = tok.nextToken(); DetectorFactory factory = DetectorFactoryCollection.instance().getFactory(visitorName); if (factory == null) throw new IllegalArgumentException("Unknown detector: " + visitorName); factory.setEnabled(!omit); } } else if (option.equals("-exclude") || option.equals("-include")) { ++argCount; if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument"); filterFile = argv[argCount]; include = option.equals("-include"); } else if (option.equals("-quiet")) { quiet = true; } else if (option.equals("-auxclasspath")) { ++argCount; if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument"); String auxClassPath = argv[argCount]; StringTokenizer tok = new StringTokenizer(auxClassPath, File.pathSeparator); while (tok.hasMoreTokens()) project.addAuxClasspathEntry(tok.nextToken()); } else if (option.equals("-sourcepath")) { ++argCount; if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument"); String sourcePath = argv[argCount]; StringTokenizer tok = new StringTokenizer(sourcePath, File.pathSeparator); while (tok.hasMoreTokens()) { project.addSourceDir(new File(tok.nextToken()).getAbsolutePath()); } } else if (option.equals("-project")) { ++argCount; if (argCount == argv.length) throw new IllegalArgumentException(option + " option requires argument"); String projectFile = argv[argCount]; // Convert project file to be an absolute path projectFile = new File(projectFile).getAbsolutePath(); try { project = new Project(projectFile); project.read(new BufferedInputStream(new FileInputStream(projectFile))); } catch (IOException e) { System.err.println("Error opening " + projectFile); e.printStackTrace(System.err); throw e; } } else if (option.equals("-exitcode")) { setExitCode = true; } else throw new IllegalArgumentException("Unknown option: [" + option + "]"); ++argCount; } if (argCount == argv.length && project.getNumJarFiles() == 0) { InputStream in = FindBugs.class.getClassLoader().getResourceAsStream("USAGE"); if (in == null) { System.out.println("FindBugs tool, version " + Version.RELEASE); System.out.println("usage: java -jar findbugs.jar [options] <classfiles, zip/jar files, or directories>"); System.out.println("Example: java -jar findbugs.jar rt.jar"); System.out.println("Options:"); System.out.println(" -home <home directory> specify FindBugs home directory"); System.out.println(" -pluginList <jar1>" + File.pathSeparatorChar + "<jar2>... " + "specify list of plugin Jar files to load"); System.out.println(" -quiet suppress error messages"); System.out.println(" -low report all bugs"); System.out.println(" -medium report medium and high priority bugs [default]"); System.out.println(" -high report high priority bugs only"); System.out.println(" -sortByClass sort bug reports by class"); System.out.println(" -xml XML output"); System.out.println(" -emacs Use emacs reporting format"); System.out.println(" -outputFile <filename> Save output in named file"); System.out.println(" -visitors <v1>,<v2>,... run only named visitors"); System.out.println(" -omitVisitors <v1>,<v2>,... omit named visitors"); System.out.println(" -exclude <filter file> exclude bugs matching given filter"); System.out.println(" -include <filter file> include only bugs matching given filter"); System.out.println(" -auxclasspath <classpath> set aux classpath for analysis"); System.out.println(" -sourcepath path in which source files are found"); System.out.println(" -project <project> analyze given project"); System.out.println(" -exitcode set exit code of process"); } else IO.copy(in,System.out); return; } TextUIBugReporter bugReporter = null; switch (bugReporterType) { case PRINTING_REPORTER: bugReporter = new PrintingBugReporter(); break; case SORTING_REPORTER: bugReporter = new SortingBugReporter(); break; case XML_REPORTER: bugReporter = new XMLBugReporter(project); break; case EMACS_REPORTER: bugReporter = new EmacsBugReporter(); break; default: throw new IllegalStateException(); } if (quiet) bugReporter.setErrorVerbosity(BugReporter.SILENT); bugReporter.setPriorityThreshold(priorityThreshold); if (outputStream != null) bugReporter.setOutputStream(outputStream); for (int i = argCount; i < argv.length; ++i) project.addJar(argv[i]); FindBugs findBugs = new FindBugs(bugReporter, project); if (filterFile != null) findBugs.setFilter(filterFile, include); findBugs.execute(); int bugCount = findBugs.getBugCount(); int missingClassCount = findBugs.getMissingClassCount(); int errorCount = findBugs.getErrorCount(); if (!quiet || setExitCode) { if (bugCount > 0) System.err.println("Warnings generated: " + bugCount); if (missingClassCount > 0) System.err.println("Missing classes: " + missingClassCount); if (errorCount > 0) System.err.println("Analysis errors: " + errorCount); } if (setExitCode) { int exitCode = 0; if (errorCount > 0) exitCode |= ERROR_FLAG; if (missingClassCount > 0) exitCode |= MISSING_CLASS_FLAG; if (bugCount > 0) exitCode |= BUGS_FOUND_FLAG; System.exit(exitCode); } } }
package org.opendaylight.yangtools.yang.parser.spi.source; import java.net.URI; import java.util.HashMap; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition; public class QNameToStatementDefinitionMap implements QNameToStatementDefinition { private Map<QName, StatementDefinition> qNameToStmtDefMap = new HashMap<>(); private Map<QName, StatementDefinition> qNameWithoutRevisionToStmtDefMap = new HashMap<>(); public void put(QName qName, StatementDefinition stDef) { qNameToStmtDefMap.put(qName, stDef); final QName norev; if (qName.getRevision() != null) { norev = QName.create(qName.getNamespace(), null, qName.getLocalName()).intern(); } else { norev = qName; } qNameWithoutRevisionToStmtDefMap.put(norev, stDef); } @Nullable @Override public StatementDefinition get(@Nonnull QName identifier) { return qNameToStmtDefMap.get(identifier); } @Nullable @Override public StatementDefinition getByNamespaceAndLocalName(final URI namespace, @Nonnull final String localName) { return qNameWithoutRevisionToStmtDefMap.get(QName.create(namespace, null, localName)); } }