id
int64 22
34.9k
| comment_id
int64 0
328
| comment
stringlengths 2
2.55k
| code
stringlengths 31
107k
| classification
stringclasses 6
values | isFinished
bool 1
class | code_context_2
stringlengths 21
27.3k
| code_context_10
stringlengths 29
27.3k
| code_context_20
stringlengths 29
27.3k
|
---|---|---|---|---|---|---|---|---|
26,190 | 4 | // "Id : ", id, | private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
searchText.setText("");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField();
JTextField about = new JTextField();
Object[] input = {
// "Id : ", id,
"Name : ", name,
"About : ", about,
};
int option = JOptionPane.showConfirmDialog(this, input, "Enter Artist details", JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345");
CallableStatement ps = con.prepareCall ("{call addartist(?, ?, ?)}");
ps.setString(1,null);
ps.setString(2, name.getText());
ps.setString(3, about.getText());
ps.executeUpdate();
ps.close();
con.close();
} catch (Exception e) {e.printStackTrace();}
JOptionPane.showMessageDialog(this, "Success!\n");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage());
}
} | NONSATD | true | JTextField about = new JTextField();
Object[] input = {
// "Id : ", id,
"Name : ", name,
"About : ", about, | try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField();
JTextField about = new JTextField();
Object[] input = {
// "Id : ", id,
"Name : ", name,
"About : ", about,
};
int option = JOptionPane.showConfirmDialog(this, input, "Enter Artist details", JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345");
CallableStatement ps = con.prepareCall ("{call addartist(?, ?, ?)}"); | private void addArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
searchText.setText("");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField();
JTextField about = new JTextField();
Object[] input = {
// "Id : ", id,
"Name : ", name,
"About : ", about,
};
int option = JOptionPane.showConfirmDialog(this, input, "Enter Artist details", JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345");
CallableStatement ps = con.prepareCall ("{call addartist(?, ?, ?)}");
ps.setString(1,null);
ps.setString(2, name.getText());
ps.setString(3, about.getText());
ps.executeUpdate();
ps.close();
con.close();
} catch (Exception e) {e.printStackTrace();}
JOptionPane.showMessageDialog(this, "Success!\n");
}
} catch (Exception e) { |
26,191 | 0 | //GEN-FIRST:event_addAlbumActionPerformed | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField();
Object[] input = {
// "Id : ", id,
"Name : ", name,
};
int option = JOptionPane.showConfirmDialog(this, input, "Enter Album details", JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345");
CallableStatement ps = con.prepareCall ("{call addalbum(?, ?)}");
ps.setString(1, null);
ps.setString(2, name.getText());
ps.executeUpdate();
ps.close();
con.close();
} catch (Exception e) {e.printStackTrace();}
JOptionPane.showMessageDialog(this, "Success!\n");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage());
}
} | NONSATD | true | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try { | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField(); | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField();
Object[] input = {
// "Id : ", id,
"Name : ", name,
};
int option = JOptionPane.showConfirmDialog(this, input, "Enter Album details", JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection( |
26,191 | 1 | // TODO add your handling code here: | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField();
Object[] input = {
// "Id : ", id,
"Name : ", name,
};
int option = JOptionPane.showConfirmDialog(this, input, "Enter Album details", JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345");
CallableStatement ps = con.prepareCall ("{call addalbum(?, ?)}");
ps.setString(1, null);
ps.setString(2, name.getText());
ps.executeUpdate();
ps.close();
con.close();
} catch (Exception e) {e.printStackTrace();}
JOptionPane.showMessageDialog(this, "Success!\n");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage());
}
} | IMPLEMENTATION | true | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here: | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField(); | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField();
Object[] input = {
// "Id : ", id,
"Name : ", name,
};
int option = JOptionPane.showConfirmDialog(this, input, "Enter Album details", JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); |
26,191 | 2 | // TODO add your handling code here: | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField();
Object[] input = {
// "Id : ", id,
"Name : ", name,
};
int option = JOptionPane.showConfirmDialog(this, input, "Enter Album details", JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345");
CallableStatement ps = con.prepareCall ("{call addalbum(?, ?)}");
ps.setString(1, null);
ps.setString(2, name.getText());
ps.executeUpdate();
ps.close();
con.close();
} catch (Exception e) {e.printStackTrace();}
JOptionPane.showMessageDialog(this, "Success!\n");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage());
}
} | IMPLEMENTATION | true | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here: | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField(); | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField();
Object[] input = {
// "Id : ", id,
"Name : ", name,
};
int option = JOptionPane.showConfirmDialog(this, input, "Enter Album details", JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345"); |
26,191 | 3 | // TODO add your handling code here:
// JTextField id = new JTextField(); | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField();
Object[] input = {
// "Id : ", id,
"Name : ", name,
};
int option = JOptionPane.showConfirmDialog(this, input, "Enter Album details", JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345");
CallableStatement ps = con.prepareCall ("{call addalbum(?, ?)}");
ps.setString(1, null);
ps.setString(2, name.getText());
ps.executeUpdate();
ps.close();
con.close();
} catch (Exception e) {e.printStackTrace();}
JOptionPane.showMessageDialog(this, "Success!\n");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage());
}
} | IMPLEMENTATION | true | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
try { | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField();
Object[] input = { | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField();
Object[] input = {
// "Id : ", id,
"Name : ", name,
};
int option = JOptionPane.showConfirmDialog(this, input, "Enter Album details", JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345");
CallableStatement ps = con.prepareCall ("{call addalbum(?, ?)}"); |
26,191 | 4 | // "Id : ", id, | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField();
Object[] input = {
// "Id : ", id,
"Name : ", name,
};
int option = JOptionPane.showConfirmDialog(this, input, "Enter Album details", JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345");
CallableStatement ps = con.prepareCall ("{call addalbum(?, ?)}");
ps.setString(1, null);
ps.setString(2, name.getText());
ps.executeUpdate();
ps.close();
con.close();
} catch (Exception e) {e.printStackTrace();}
JOptionPane.showMessageDialog(this, "Success!\n");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage());
}
} | NONSATD | true | JTextField name = new JTextField();
Object[] input = {
// "Id : ", id,
"Name : ", name,
}; | // TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField();
Object[] input = {
// "Id : ", id,
"Name : ", name,
};
int option = JOptionPane.showConfirmDialog(this, input, "Enter Album details", JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345");
CallableStatement ps = con.prepareCall ("{call addalbum(?, ?)}");
ps.setString(1, null); | private void addAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addAlbumActionPerformed
// TODO add your handling code here:
try {
// TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(AdminView.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
// JTextField id = new JTextField();
JTextField name = new JTextField();
Object[] input = {
// "Id : ", id,
"Name : ", name,
};
int option = JOptionPane.showConfirmDialog(this, input, "Enter Album details", JOptionPane.OK_CANCEL_OPTION);
if(option == JOptionPane.OK_OPTION) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:newdatabase","system","not12345");
CallableStatement ps = con.prepareCall ("{call addalbum(?, ?)}");
ps.setString(1, null);
ps.setString(2, name.getText());
ps.executeUpdate();
ps.close();
con.close();
} catch (Exception e) {e.printStackTrace();}
JOptionPane.showMessageDialog(this, "Success!\n");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error!\n"+e.getMessage());
} |
34,400 | 0 | /**
* Gets the line number associated with the given address.
*
* @param pc {@code >= 0;} the address to look up
* @return {@code >= -1;} the associated line number, or {@code -1} if
* none is known
*/ | public int pcToLine(int pc) {
/*
* Line number entries don't have to appear in any particular
* order, so we have to do a linear search. TODO: If
* this turns out to be a bottleneck, consider sorting the
* list prior to use.
*/
int sz = size();
int bestPc = -1;
int bestLine = -1;
for (int i = 0; i < sz; i++) {
Item one = get(i);
int onePc = one.getStartPc();
if ((onePc <= pc) && (onePc > bestPc)) {
bestPc = onePc;
bestLine = one.getLineNumber();
if (bestPc == pc) {
// We can't do better than this
break;
}
}
}
return bestLine;
} | NONSATD | true | public int pcToLine(int pc) {
/*
* Line number entries don't have to appear in any particular
* order, so we have to do a linear search. TODO: If
* this turns out to be a bottleneck, consider sorting the
* list prior to use.
*/
int sz = size();
int bestPc = -1;
int bestLine = -1;
for (int i = 0; i < sz; i++) {
Item one = get(i);
int onePc = one.getStartPc();
if ((onePc <= pc) && (onePc > bestPc)) {
bestPc = onePc;
bestLine = one.getLineNumber();
if (bestPc == pc) {
// We can't do better than this
break;
}
}
}
return bestLine;
} | public int pcToLine(int pc) {
/*
* Line number entries don't have to appear in any particular
* order, so we have to do a linear search. TODO: If
* this turns out to be a bottleneck, consider sorting the
* list prior to use.
*/
int sz = size();
int bestPc = -1;
int bestLine = -1;
for (int i = 0; i < sz; i++) {
Item one = get(i);
int onePc = one.getStartPc();
if ((onePc <= pc) && (onePc > bestPc)) {
bestPc = onePc;
bestLine = one.getLineNumber();
if (bestPc == pc) {
// We can't do better than this
break;
}
}
}
return bestLine;
} | public int pcToLine(int pc) {
/*
* Line number entries don't have to appear in any particular
* order, so we have to do a linear search. TODO: If
* this turns out to be a bottleneck, consider sorting the
* list prior to use.
*/
int sz = size();
int bestPc = -1;
int bestLine = -1;
for (int i = 0; i < sz; i++) {
Item one = get(i);
int onePc = one.getStartPc();
if ((onePc <= pc) && (onePc > bestPc)) {
bestPc = onePc;
bestLine = one.getLineNumber();
if (bestPc == pc) {
// We can't do better than this
break;
}
}
}
return bestLine;
} |
34,400 | 1 | /*
* Line number entries don't have to appear in any particular
* order, so we have to do a linear search. TODO: If
* this turns out to be a bottleneck, consider sorting the
* list prior to use.
*/ | public int pcToLine(int pc) {
/*
* Line number entries don't have to appear in any particular
* order, so we have to do a linear search. TODO: If
* this turns out to be a bottleneck, consider sorting the
* list prior to use.
*/
int sz = size();
int bestPc = -1;
int bestLine = -1;
for (int i = 0; i < sz; i++) {
Item one = get(i);
int onePc = one.getStartPc();
if ((onePc <= pc) && (onePc > bestPc)) {
bestPc = onePc;
bestLine = one.getLineNumber();
if (bestPc == pc) {
// We can't do better than this
break;
}
}
}
return bestLine;
} | DESIGN | true | public int pcToLine(int pc) {
/*
* Line number entries don't have to appear in any particular
* order, so we have to do a linear search. TODO: If
* this turns out to be a bottleneck, consider sorting the
* list prior to use.
*/
int sz = size();
int bestPc = -1; | public int pcToLine(int pc) {
/*
* Line number entries don't have to appear in any particular
* order, so we have to do a linear search. TODO: If
* this turns out to be a bottleneck, consider sorting the
* list prior to use.
*/
int sz = size();
int bestPc = -1;
int bestLine = -1;
for (int i = 0; i < sz; i++) {
Item one = get(i);
int onePc = one.getStartPc();
if ((onePc <= pc) && (onePc > bestPc)) {
bestPc = onePc;
bestLine = one.getLineNumber();
if (bestPc == pc) { | public int pcToLine(int pc) {
/*
* Line number entries don't have to appear in any particular
* order, so we have to do a linear search. TODO: If
* this turns out to be a bottleneck, consider sorting the
* list prior to use.
*/
int sz = size();
int bestPc = -1;
int bestLine = -1;
for (int i = 0; i < sz; i++) {
Item one = get(i);
int onePc = one.getStartPc();
if ((onePc <= pc) && (onePc > bestPc)) {
bestPc = onePc;
bestLine = one.getLineNumber();
if (bestPc == pc) {
// We can't do better than this
break;
}
}
}
return bestLine;
} |
34,400 | 2 | // We can't do better than this | public int pcToLine(int pc) {
/*
* Line number entries don't have to appear in any particular
* order, so we have to do a linear search. TODO: If
* this turns out to be a bottleneck, consider sorting the
* list prior to use.
*/
int sz = size();
int bestPc = -1;
int bestLine = -1;
for (int i = 0; i < sz; i++) {
Item one = get(i);
int onePc = one.getStartPc();
if ((onePc <= pc) && (onePc > bestPc)) {
bestPc = onePc;
bestLine = one.getLineNumber();
if (bestPc == pc) {
// We can't do better than this
break;
}
}
}
return bestLine;
} | DESIGN | true | bestLine = one.getLineNumber();
if (bestPc == pc) {
// We can't do better than this
break;
} | int sz = size();
int bestPc = -1;
int bestLine = -1;
for (int i = 0; i < sz; i++) {
Item one = get(i);
int onePc = one.getStartPc();
if ((onePc <= pc) && (onePc > bestPc)) {
bestPc = onePc;
bestLine = one.getLineNumber();
if (bestPc == pc) {
// We can't do better than this
break;
}
}
}
return bestLine;
} | public int pcToLine(int pc) {
/*
* Line number entries don't have to appear in any particular
* order, so we have to do a linear search. TODO: If
* this turns out to be a bottleneck, consider sorting the
* list prior to use.
*/
int sz = size();
int bestPc = -1;
int bestLine = -1;
for (int i = 0; i < sz; i++) {
Item one = get(i);
int onePc = one.getStartPc();
if ((onePc <= pc) && (onePc > bestPc)) {
bestPc = onePc;
bestLine = one.getLineNumber();
if (bestPc == pc) {
// We can't do better than this
break;
}
}
}
return bestLine;
} |
26,213 | 0 | // FIXME: These record counts are only correct iff if duplicate keys are disregarted.
// This is unfortunate. Keys are currently only considered based their SKSKode.
// They should be a combination of type + kode + startdato based on the register doc. | @Test
public void canImportTheCorrectNumberOfRecords() throws Throwable {
process(shakParser, shakDao, "data/sks/SHAKCOMPLETE.TXT");
// FIXME: These record counts are only correct iff if duplicate keys are disregarted.
// This is unfortunate. Keys are currently only considered based their SKSKode.
// They should be a combination of type + kode + startdato based on the register doc.
assertEquals(1017, jdbc.queryForInt("SELECT COUNT(*) FROM class_shak WHERE Organisationstype = 'Sygehus'"));
assertEquals(18411, jdbc.queryForInt("SELECT COUNT(*) FROM class_shak WHERE Organisationstype = 'Afdeling'"));
process(sksParser, sksDao, "data/sks/SKScomplete.txt");
assertEquals(573, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'und'"));
assertEquals(8990, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'pro'"));
assertEquals(43857, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'dia'"));
assertEquals(19980, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'opr'"));
assertEquals(10461, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'atc'"));
} | DEFECT | true | public void canImportTheCorrectNumberOfRecords() throws Throwable {
process(shakParser, shakDao, "data/sks/SHAKCOMPLETE.TXT");
// FIXME: These record counts are only correct iff if duplicate keys are disregarted.
// This is unfortunate. Keys are currently only considered based their SKSKode.
// They should be a combination of type + kode + startdato based on the register doc.
assertEquals(1017, jdbc.queryForInt("SELECT COUNT(*) FROM class_shak WHERE Organisationstype = 'Sygehus'"));
assertEquals(18411, jdbc.queryForInt("SELECT COUNT(*) FROM class_shak WHERE Organisationstype = 'Afdeling'")); | @Test
public void canImportTheCorrectNumberOfRecords() throws Throwable {
process(shakParser, shakDao, "data/sks/SHAKCOMPLETE.TXT");
// FIXME: These record counts are only correct iff if duplicate keys are disregarted.
// This is unfortunate. Keys are currently only considered based their SKSKode.
// They should be a combination of type + kode + startdato based on the register doc.
assertEquals(1017, jdbc.queryForInt("SELECT COUNT(*) FROM class_shak WHERE Organisationstype = 'Sygehus'"));
assertEquals(18411, jdbc.queryForInt("SELECT COUNT(*) FROM class_shak WHERE Organisationstype = 'Afdeling'"));
process(sksParser, sksDao, "data/sks/SKScomplete.txt");
assertEquals(573, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'und'"));
assertEquals(8990, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'pro'"));
assertEquals(43857, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'dia'"));
assertEquals(19980, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'opr'"));
assertEquals(10461, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'atc'"));
} | @Test
public void canImportTheCorrectNumberOfRecords() throws Throwable {
process(shakParser, shakDao, "data/sks/SHAKCOMPLETE.TXT");
// FIXME: These record counts are only correct iff if duplicate keys are disregarted.
// This is unfortunate. Keys are currently only considered based their SKSKode.
// They should be a combination of type + kode + startdato based on the register doc.
assertEquals(1017, jdbc.queryForInt("SELECT COUNT(*) FROM class_shak WHERE Organisationstype = 'Sygehus'"));
assertEquals(18411, jdbc.queryForInt("SELECT COUNT(*) FROM class_shak WHERE Organisationstype = 'Afdeling'"));
process(sksParser, sksDao, "data/sks/SKScomplete.txt");
assertEquals(573, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'und'"));
assertEquals(8990, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'pro'"));
assertEquals(43857, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'dia'"));
assertEquals(19980, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'opr'"));
assertEquals(10461, jdbc.queryForInt("SELECT COUNT(*) FROM class_sks WHERE Type = 'atc'"));
} |
34,410 | 0 | // TODO unsubscribe from everything? And resubscribe on resume? | @Override
public void suspend() {
// TODO unsubscribe from everything? And resubscribe on resume?
super.suspend();
if (executor != null) executor.shutdownNow();
executorQueued.set(false);
} | DESIGN | true | @Override
public void suspend() {
// TODO unsubscribe from everything? And resubscribe on resume?
super.suspend();
if (executor != null) executor.shutdownNow(); | @Override
public void suspend() {
// TODO unsubscribe from everything? And resubscribe on resume?
super.suspend();
if (executor != null) executor.shutdownNow();
executorQueued.set(false);
} | @Override
public void suspend() {
// TODO unsubscribe from everything? And resubscribe on resume?
super.suspend();
if (executor != null) executor.shutdownNow();
executorQueued.set(false);
} |
1,644 | 0 | /**
* @desc Sets the first timex of type DATE in the document timex list as the
* document creation time TODO: make sure "first" in list is necessarily
* first that appears in document! Should be, unless the relevant string
* is somehow dropped during sentence tokenization.
*/ | public static void setFirstDateAsDCT(SieveDocument doc) {
if (doc.getDocstamp() == null) {
for (Timex nextTimex : doc.getTimexes()) {
if (nextTimex.getType().equals(Timex.Type.DATE)) {
nextTimex.setDocumentFunction(DocumentFunction.CREATION_TIME);
doc.addCreationTime(nextTimex);
break;
}
}
}
} | DESIGN | true | public static void setFirstDateAsDCT(SieveDocument doc) {
if (doc.getDocstamp() == null) {
for (Timex nextTimex : doc.getTimexes()) {
if (nextTimex.getType().equals(Timex.Type.DATE)) {
nextTimex.setDocumentFunction(DocumentFunction.CREATION_TIME);
doc.addCreationTime(nextTimex);
break;
}
}
}
} | public static void setFirstDateAsDCT(SieveDocument doc) {
if (doc.getDocstamp() == null) {
for (Timex nextTimex : doc.getTimexes()) {
if (nextTimex.getType().equals(Timex.Type.DATE)) {
nextTimex.setDocumentFunction(DocumentFunction.CREATION_TIME);
doc.addCreationTime(nextTimex);
break;
}
}
}
} | public static void setFirstDateAsDCT(SieveDocument doc) {
if (doc.getDocstamp() == null) {
for (Timex nextTimex : doc.getTimexes()) {
if (nextTimex.getType().equals(Timex.Type.DATE)) {
nextTimex.setDocumentFunction(DocumentFunction.CREATION_TIME);
doc.addCreationTime(nextTimex);
break;
}
}
}
} |
18,031 | 0 | /**
* @Fix the Illegal group reference issue
*/ | private String replaceParam(String message, Object... parameters) {
int startSize = 0;
int parametersIndex = 0;
int index;
String tmpMessage = message;
while ((index = message.indexOf("{}", startSize)) != -1) {
if (parametersIndex >= parameters.length) {
break;
}
/**
* @Fix the Illegal group reference issue
*/
tmpMessage = tmpMessage.replaceFirst("\\{\\}", Matcher.quoteReplacement(String.valueOf(parameters[parametersIndex++])));
startSize = index + 2;
}
return tmpMessage;
} | DEFECT | true | break;
}
/**
* @Fix the Illegal group reference issue
*/
tmpMessage = tmpMessage.replaceFirst("\\{\\}", Matcher.quoteReplacement(String.valueOf(parameters[parametersIndex++])));
startSize = index + 2; | private String replaceParam(String message, Object... parameters) {
int startSize = 0;
int parametersIndex = 0;
int index;
String tmpMessage = message;
while ((index = message.indexOf("{}", startSize)) != -1) {
if (parametersIndex >= parameters.length) {
break;
}
/**
* @Fix the Illegal group reference issue
*/
tmpMessage = tmpMessage.replaceFirst("\\{\\}", Matcher.quoteReplacement(String.valueOf(parameters[parametersIndex++])));
startSize = index + 2;
}
return tmpMessage;
} | private String replaceParam(String message, Object... parameters) {
int startSize = 0;
int parametersIndex = 0;
int index;
String tmpMessage = message;
while ((index = message.indexOf("{}", startSize)) != -1) {
if (parametersIndex >= parameters.length) {
break;
}
/**
* @Fix the Illegal group reference issue
*/
tmpMessage = tmpMessage.replaceFirst("\\{\\}", Matcher.quoteReplacement(String.valueOf(parameters[parametersIndex++])));
startSize = index + 2;
}
return tmpMessage;
} |
26,228 | 0 | /**
* Import note: "onlyDatatRelatedToMe" relies on filterQueries for providing
* access to Private Data for the correct user
*
* In other words "onlyDatatRelatedToMe", negates other filter Queries
* related to permissions
*
*
* @param user
* @param dataverse
* @param query
* @param filterQueries
* @param sortField
* @param sortOrder
* @param paginationStart
* @param onlyDatatRelatedToMe
* @param numResultsPerPage
* @param retrieveEntities - look up dvobject entities with .find() (potentially expensive!)
* @return
* @throws SearchException
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} |
26,228 | 1 | // SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc)); | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else { | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
} | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label"); |
26,228 | 2 | // } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause); | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | // solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize(); | if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name"); | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/** |
26,228 | 3 | // TODO: Do not hard code "Name" etc as English here. | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DESIGN | true | solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation"); | // }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId")); | }
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card? |
26,228 | 4 | /**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DESIGN | true | solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation"); | solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) { | // solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score"); |
26,228 | 5 | // solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DESIGN | true | * https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag"); | solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey(); | solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*"); |
26,228 | 6 | // String displayName = entry.getValue(); | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
} | solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) { | * this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// ----------------------------------- |
26,228 | 7 | /**
* @todo: do we need facet.query?
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DESIGN | true | solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431 | solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension"); | // solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue(); |
26,228 | 8 | // -----------------------------------
// PERMISSION FILTER QUERY
// ----------------------------------- | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) { | solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY); | for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse |
26,228 | 9 | // -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING); | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
} | solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION); | for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490 |
26,228 | 10 | // solrQuery.addFacetField(SearchFields.AFFILIATION); | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY); | if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490 | * @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable()); |
26,228 | 11 | // solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DESIGN | true | // solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) { | }
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last... | solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart); |
26,228 | 12 | /**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | IMPLEMENTATION | true | solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/ | solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag"); | // solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField); |
26,228 | 13 | /**
* @todo: do sanity checking... throw error if negative
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | IMPLEMENTATION | true | solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431 | solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension"); | // solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue(); |
26,228 | 14 | /**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DESIGN | true | solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/ | solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag"); | // solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField); |
26,228 | 15 | // Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DESIGN | true | * support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/** | solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field | }
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// ----------------------------------- |
26,228 | 16 | /**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DEFECT | true | solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/ | solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag"); | // solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField); |
26,228 | 17 | /**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DESIGN | true | solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/** | solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable(); | // solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select"); |
26,228 | 18 | // solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan); | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | * above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery); | final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage(); | // Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery); |
26,228 | 19 | // -----------------------------------
// Make the solr query
// ----------------------------------- | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) { | solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY); | for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse |
26,228 | 20 | // hide "org.apache.solr..." | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else { | // Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0; | * facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse; |
26,228 | 21 | // we can't show anything because of the search syntax error | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0; | String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList); | logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string |
26,228 | 22 | /**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DESIGN | true | solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject"); | solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById(); | // solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
} |
26,228 | 23 | // ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE); | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID); | Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE); | if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field); |
26,228 | 24 | // logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title); | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE); | String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>(); | }
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the |
26,228 | 25 | /**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DESIGN | true | solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject"); | solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById(); | // solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
} |
26,228 | 26 | /**
* @todo put all this in the constructor?
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DESIGN | true | solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431 | solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension"); | // solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue(); |
26,228 | 27 | // set list of all statuses
// this method also sets booleans for individual statuses | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
} | highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl); | /**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>(); |
26,228 | 28 | // logger.info(id + ": " + description); | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid); | SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort); | */
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason); |
26,228 | 29 | /**
* @todo start using SearchConstants class here
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | IMPLEMENTATION | true | solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431 | solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension"); | // solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue(); |
26,228 | 30 | // Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DESIGN | true | solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) { | String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId); | solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) { |
26,228 | 31 | // solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid); | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | * dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier); | solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){ | solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription); |
26,228 | 32 | //Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) { | //solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml); | }
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors); |
26,228 | 33 | // solrSearchResult.setTitle((String) titles.get(0)); | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else { | if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) { | // We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because |
26,228 | 34 | /**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DESIGN | true | solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/** | solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable(); | // solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select"); |
26,228 | 35 | // solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid); | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | * JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype); | }
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage()); | List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF)); |
26,228 | 36 | /**
* @todo store PARENT_ID as a long instead and cast as such
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DESIGN | true | solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431 | solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension"); | // solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue(); |
26,228 | 37 | /**
* @todo we do want to show the count for each facet
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | IMPLEMENTATION | true | solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431 | solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension"); | // solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue(); |
26,228 | 38 | // logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")"); | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | * @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount()); | boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true; | List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) { |
26,228 | 39 | // quote field facets | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel); | FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
} | }
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName()); |
26,228 | 40 | // hopefully people will never see the raw facetField.getName() because it may well have an _s at the end | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | }
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet | }
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable(); | facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
} |
26,228 | 41 | // try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DESIGN | true | // hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable(); | numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match | if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/ |
26,228 | 42 | // give it the non-friendly name so we remember to update the reference data script for datasets | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) { | /**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
} | }
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject); |
26,228 | 43 | // stop examining available dataset fields. we found a match | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
} | */
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/ | }
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_"); |
26,228 | 44 | /**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/ | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | DESIGN | true | solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject"); | solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById(); | // solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
} |
26,228 | 45 | // logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>"); | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match | }
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory); | * should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory); |
26,228 | 46 | // stop examining the declared/static fields in the SearchFields object. we found a match | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | // logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
} | String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) { | */
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else { |
26,228 | 47 | // the "type" facet is special, these are not | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) { | facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) { | Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory(); |
26,228 | 48 | // for now the only range facet is citation year | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | }
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory(); | }
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1; | if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top |
26,228 | 49 | // to avoid overlapping dates | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) { | }
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList); | facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
} |
26,228 | 50 | // special [12 TO 34] syntax for range facets | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel); | List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) { | facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken); |
26,228 | 51 | // reverse to show the newest citation year range at the top | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size()); | end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
} | // for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries(); |
26,228 | 52 | // null check added because these tests were failing: mvn test -Dtest=SearchIT | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries); | solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse; | ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} |
26,228 | 53 | // how often is this null? | public SolrQueryResponse search(DataverseRequest dataverseRequest, Dataverse dataverse, String query, List<String> filterQueries, String sortField, String sortOrder, int paginationStart, boolean onlyDatatRelatedToMe, int numResultsPerPage, boolean retrieveEntities) throws SearchException {
if (paginationStart < 0) {
throw new IllegalArgumentException("paginationStart must be 0 or greater");
}
if (numResultsPerPage < 1) {
throw new IllegalArgumentException("numResultsPerPage must be 1 or greater");
}
SolrQuery solrQuery = new SolrQuery();
query = SearchUtil.sanitizeQuery(query);
solrQuery.setQuery(query);
// SortClause foo = new SortClause("name", SolrQuery.ORDER.desc);
// if (query.equals("*") || query.equals("*:*")) {
// solrQuery.setSort(new SortClause(SearchFields.NAME_SORT, SolrQuery.ORDER.asc));
solrQuery.setSort(new SortClause(sortField, sortOrder));
// } else {
// solrQuery.setSort(sortClause);
// }
// solrQuery.setSort(sortClause);
solrQuery.setHighlight(true).setHighlightSnippets(1);
Integer fragSize = systemConfig.getSearchHighlightFragmentSize();
if (fragSize != null) {
solrQuery.setHighlightFragsize(fragSize);
}
solrQuery.setHighlightSimplePre("<span class=\"search-term-match\">");
solrQuery.setHighlightSimplePost("</span>");
Map<String, String> solrFieldsToHightlightOnMap = new HashMap<>();
// TODO: Do not hard code "Name" etc as English here.
solrFieldsToHightlightOnMap.put(SearchFields.NAME, "Name");
solrFieldsToHightlightOnMap.put(SearchFields.AFFILIATION, "Affiliation");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_FRIENDLY, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DESCRIPTION, "Description");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_NAME, "Variable Name");
solrFieldsToHightlightOnMap.put(SearchFields.VARIABLE_LABEL, "Variable Label");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TYPE_SEARCHABLE, "File Type");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PUBLICATION_DATE, "Publication Date");
solrFieldsToHightlightOnMap.put(SearchFields.DATASET_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.datasets.persistentId"));
solrFieldsToHightlightOnMap.put(SearchFields.FILE_PERSISTENT_ID, BundleUtil.getStringFromBundle("advanced.search.files.persistentId"));
/**
* @todo Dataverse subject and affiliation should be highlighted but
* this is commented out right now because the "friendly" names are not
* being shown on the dataverse cards. See also
* https://github.com/IQSS/dataverse/issues/1431
*/
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_SUBJECT, "Subject");
// solrFieldsToHightlightOnMap.put(SearchFields.DATAVERSE_AFFILIATION, "Affiliation");
/**
* @todo: show highlight on file card?
* https://redmine.hmdc.harvard.edu/issues/3848
*/
solrFieldsToHightlightOnMap.put(SearchFields.FILENAME_WITHOUT_EXTENSION, "Filename Without Extension");
solrFieldsToHightlightOnMap.put(SearchFields.FILE_TAG_SEARCHABLE, "File Tag");
List<DatasetFieldType> datasetFields = datasetFieldService.findAllOrderedById();
for (DatasetFieldType datasetFieldType : datasetFields) {
String solrField = datasetFieldType.getSolrField().getNameSearchable();
String displayName = datasetFieldType.getDisplayName();
solrFieldsToHightlightOnMap.put(solrField, displayName);
}
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String solrField = entry.getKey();
// String displayName = entry.getValue();
solrQuery.addHighlightField(solrField);
}
solrQuery.setParam("fl", "*,score");
solrQuery.setParam("qt", "/select");
solrQuery.setParam("facet", "true");
/**
* @todo: do we need facet.query?
*/
solrQuery.setParam("facet.query", "*");
for (String filterQuery : filterQueries) {
solrQuery.addFilterQuery(filterQuery);
}
// -----------------------------------
// PERMISSION FILTER QUERY
// -----------------------------------
String permissionFilterQuery = this.getPermissionFilterQuery(dataverseRequest, solrQuery, dataverse, onlyDatatRelatedToMe);
if (permissionFilterQuery != null) {
solrQuery.addFilterQuery(permissionFilterQuery);
}
// -----------------------------------
// Facets to Retrieve
// -----------------------------------
// solrQuery.addFacetField(SearchFields.HOST_DATAVERSE);
// solrQuery.addFacetField(SearchFields.AUTHOR_STRING);
solrQuery.addFacetField(SearchFields.DATAVERSE_CATEGORY);
solrQuery.addFacetField(SearchFields.METADATA_SOURCE);
// solrQuery.addFacetField(SearchFields.AFFILIATION);
solrQuery.addFacetField(SearchFields.PUBLICATION_DATE);
// solrQuery.addFacetField(SearchFields.CATEGORY);
// solrQuery.addFacetField(SearchFields.FILE_TYPE_MIME);
// solrQuery.addFacetField(SearchFields.DISTRIBUTOR);
// solrQuery.addFacetField(SearchFields.KEYWORD);
/**
* @todo when a new method on datasetFieldService is available
* (retrieveFacetsByDataverse?) only show the facets that the dataverse
* in question wants to show (and in the right order):
* https://redmine.hmdc.harvard.edu/issues/3490
*
* also, findAll only returns advancedSearchField = true... we should
* probably introduce the "isFacetable" boolean rather than caring about
* if advancedSearchField is true or false
*
*/
if (dataverse != null) {
for (DataverseFacet dataverseFacet : dataverse.getDataverseFacets()) {
DatasetFieldType datasetField = dataverseFacet.getDatasetFieldType();
solrQuery.addFacetField(datasetField.getSolrField().getNameFacetable());
}
}
solrQuery.addFacetField(SearchFields.FILE_TYPE);
/**
* @todo: hide the extra line this shows in the GUI... at least it's
* last...
*/
solrQuery.addFacetField(SearchFields.TYPE);
solrQuery.addFacetField(SearchFields.FILE_TAG);
if (!systemConfig.isPublicInstall()) {
solrQuery.addFacetField(SearchFields.ACCESS);
}
/**
* @todo: do sanity checking... throw error if negative
*/
solrQuery.setStart(paginationStart);
/**
* @todo: decide if year CITATION_YEAR is good enough or if we should
* support CITATION_DATE
*/
// Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
// calendar.set(2010, 1, 1);
// Date start = calendar.getTime();
// calendar.set(2013, 1, 1);
// Date end = calendar.getTime();
// solrQuery.addDateRangeFacet(SearchFields.CITATION_DATE, start, end, "+1MONTH");
/**
* @todo make this configurable
*/
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
/**
* @todo: odd or even makes a difference. Couldn't find value of 2014
* when this was set to 2000
*/
final int citationYearRangeStart = 1901;
final int citationYearRangeEnd = thisYear;
final int citationYearRangeSpan = 2;
/**
* @todo: these are dates and should be "range facets" not "field
* facets"
*
* right now they are lumped in with the datasetFieldService.findAll()
* above
*/
// solrQuery.addNumericRangeFacet(SearchFields.PRODUCTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
// solrQuery.addNumericRangeFacet(SearchFields.DISTRIBUTION_DATE_YEAR_ONLY, citationYearRangeStart, citationYearRangeEnd, citationYearRangeSpan);
solrQuery.setRows(numResultsPerPage);
logger.fine("Solr query:" + solrQuery);
// -----------------------------------
// Make the solr query
// -----------------------------------
QueryResponse queryResponse = null;
try {
queryResponse = solrServer.query(solrQuery);
} catch (RemoteSolrException ex) {
String messageFromSolr = ex.getLocalizedMessage();
String error = "Search Syntax Error: ";
String stringToHide = "org.apache.solr.search.SyntaxError: ";
if (messageFromSolr.startsWith(stringToHide)) {
// hide "org.apache.solr..."
error += messageFromSolr.substring(stringToHide.length());
} else {
error += messageFromSolr;
}
logger.info(error);
SolrQueryResponse exceptionSolrQueryResponse = new SolrQueryResponse(solrQuery);
exceptionSolrQueryResponse.setError(error);
// we can't show anything because of the search syntax error
long zeroNumResultsFound = 0;
long zeroGetResultsStart = 0;
List<SolrSearchResult> emptySolrSearchResults = new ArrayList<>();
List<FacetCategory> exceptionFacetCategoryList = new ArrayList<>();
Map<String, List<String>> emptySpellingSuggestion = new HashMap<>();
exceptionSolrQueryResponse.setNumResultsFound(zeroNumResultsFound);
exceptionSolrQueryResponse.setResultsStart(zeroGetResultsStart);
exceptionSolrQueryResponse.setSolrSearchResults(emptySolrSearchResults);
exceptionSolrQueryResponse.setFacetCategoryList(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setTypeFacetCategories(exceptionFacetCategoryList);
exceptionSolrQueryResponse.setSpellingSuggestionsByToken(emptySpellingSuggestion);
return exceptionSolrQueryResponse;
} catch (SolrServerException | IOException ex) {
throw new SearchException("Internal Dataverse Search Engine Error", ex);
}
SolrDocumentList docs = queryResponse.getResults();
List<SolrSearchResult> solrSearchResults = new ArrayList<>();
/**
* @todo refactor SearchFields to a hashmap (or something? put in
* database? internationalize?) to avoid the crazy reflection and string
* manipulation below
*/
Object searchFieldsObject = new SearchFields();
Field[] staticSearchFields = searchFieldsObject.getClass().getDeclaredFields();
String titleSolrField = null;
try {
DatasetFieldType titleDatasetField = datasetFieldService.findByName(DatasetFieldConstant.title);
titleSolrField = titleDatasetField.getSolrField().getNameSearchable();
} catch (EJBTransactionRolledbackException ex) {
logger.info("Couldn't find " + DatasetFieldConstant.title);
if (ex.getCause() instanceof TransactionRolledbackLocalException) {
if (ex.getCause().getCause() instanceof NoResultException) {
logger.info("Caught NoResultException");
}
}
}
Map<String, String> datasetfieldFriendlyNamesBySolrField = new HashMap<>();
Map<String, String> staticSolrFieldFriendlyNamesBySolrField = new HashMap<>();
String baseUrl = systemConfig.getDataverseSiteUrl();
for (SolrDocument solrDocument : docs) {
String id = (String) solrDocument.getFieldValue(SearchFields.ID);
Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID);
String type = (String) solrDocument.getFieldValue(SearchFields.TYPE);
float score = (Float) solrDocument.getFieldValue(SearchFields.RELEVANCE);
logger.fine("score for " + id + ": " + score);
String identifier = (String) solrDocument.getFieldValue(SearchFields.IDENTIFIER);
String citation = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION);
String citationPlainHtml = (String) solrDocument.getFieldValue(SearchFields.DATASET_CITATION_HTML);
String persistentUrl = (String) solrDocument.getFieldValue(SearchFields.PERSISTENT_URL);
String name = (String) solrDocument.getFieldValue(SearchFields.NAME);
String nameSort = (String) solrDocument.getFieldValue(SearchFields.NAME_SORT);
// ArrayList titles = (ArrayList) solrDocument.getFieldValues(SearchFields.TITLE);
String title = (String) solrDocument.getFieldValue(titleSolrField);
Long datasetVersionId = (Long) solrDocument.getFieldValue(SearchFields.DATASET_VERSION_ID);
String deaccessionReason = (String) solrDocument.getFieldValue(SearchFields.DATASET_DEACCESSION_REASON);
// logger.info("titleSolrField: " + titleSolrField);
// logger.info("title: " + title);
String filetype = (String) solrDocument.getFieldValue(SearchFields.FILE_TYPE_FRIENDLY);
String fileContentType = (String) solrDocument.getFieldValue(SearchFields.FILE_CONTENT_TYPE);
Date release_or_create_date = (Date) solrDocument.getFieldValue(SearchFields.RELEASE_OR_CREATE_DATE);
String dateToDisplayOnCard = (String) solrDocument.getFirstValue(SearchFields.RELEASE_OR_CREATE_DATE_SEARCHABLE_TEXT);
String dvTree = (String) solrDocument.getFirstValue(SearchFields.SUBTREE);
List<String> matchedFields = new ArrayList<>();
List<Highlight> highlights = new ArrayList<>();
Map<SolrField, Highlight> highlightsMap = new HashMap<>();
Map<SolrField, List<String>> highlightsMap2 = new HashMap<>();
Map<String, Highlight> highlightsMap3 = new HashMap<>();
if (queryResponse.getHighlighting().get(id) != null) {
for (Map.Entry<String, String> entry : solrFieldsToHightlightOnMap.entrySet()) {
String field = entry.getKey();
String displayName = entry.getValue();
List<String> highlightSnippets = queryResponse.getHighlighting().get(id).get(field);
if (highlightSnippets != null) {
matchedFields.add(field);
/**
* @todo only SolrField.SolrType.STRING? that's not
* right... knit the SolrField object more into the
* highlighting stuff
*/
SolrField solrField = new SolrField(field, SolrField.SolrType.STRING, true, true);
Highlight highlight = new Highlight(solrField, highlightSnippets, displayName);
highlights.add(highlight);
highlightsMap.put(solrField, highlight);
highlightsMap2.put(solrField, highlightSnippets);
highlightsMap3.put(field, highlight);
}
}
}
SolrSearchResult solrSearchResult = new SolrSearchResult(query, name);
/**
* @todo put all this in the constructor?
*/
List<String> states = (List<String>) solrDocument.getFieldValue(SearchFields.PUBLICATION_STATUS);
if (states != null) {
// set list of all statuses
// this method also sets booleans for individual statuses
solrSearchResult.setPublicationStatuses(states);
}
// logger.info(id + ": " + description);
solrSearchResult.setId(id);
solrSearchResult.setEntityId(entityid);
if (retrieveEntities) {
solrSearchResult.setEntity(dvObjectService.findDvObject(entityid));
}
solrSearchResult.setIdentifier(identifier);
solrSearchResult.setPersistentUrl(persistentUrl);
solrSearchResult.setType(type);
solrSearchResult.setScore(score);
solrSearchResult.setNameSort(nameSort);
solrSearchResult.setReleaseOrCreateDate(release_or_create_date);
solrSearchResult.setDateToDisplayOnCard(dateToDisplayOnCard);
solrSearchResult.setMatchedFields(matchedFields);
solrSearchResult.setHighlightsAsList(highlights);
solrSearchResult.setHighlightsMap(highlightsMap);
solrSearchResult.setHighlightsAsMap(highlightsMap3);
Map<String, String> parent = new HashMap<>();
String description = (String) solrDocument.getFieldValue(SearchFields.DESCRIPTION);
solrSearchResult.setDescriptionNoSnippet(description);
solrSearchResult.setDeaccessionReason(deaccessionReason);
solrSearchResult.setDvTree(dvTree);
String originSource = (String) solrDocument.getFieldValue(SearchFields.METADATA_SOURCE);
if (IndexServiceBean.HARVESTED.equals(originSource)) {
solrSearchResult.setHarvested(true);
}
/**
* @todo start using SearchConstants class here
*/
if (type.equals("dataverses")) {
solrSearchResult.setName(name);
solrSearchResult.setHtmlUrl(baseUrl + SystemConfig.DATAVERSE_PATH + identifier);
// Do not set the ImageUrl, let the search include fragment fill in
// the thumbnail, similarly to how the dataset and datafile cards
// are handled.
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dvCardImage/" + entityid);
/**
* @todo Expose this API URL after "dvs" is changed to
* "dataverses". Also, is an API token required for published
* dataverses? Michael: url changed.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/dataverses/" + entityid);
} else if (type.equals("datasets")) {
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?globalId=" + identifier);
solrSearchResult.setApiUrl(baseUrl + "/api/datasets/" + entityid);
//Image url now set via thumbnail api
//solrSearchResult.setImageUrl(baseUrl + "/api/access/dsCardImage/" + datasetVersionId);
// No, we don't want to set the base64 thumbnails here.
// We want to do it inside SearchIncludeFragment, AND ONLY once the rest of the
// page has already loaded.
//DatasetVersion datasetVersion = datasetVersionService.find(datasetVersionId);
//if (datasetVersion != null){
// solrSearchResult.setDatasetThumbnail(datasetVersion.getDataset().getDatasetThumbnail(datasetVersion));
//}
/**
* @todo Could use getFieldValues (plural) here.
*/
List<String> datasetDescriptions = (List<String>) solrDocument.getFieldValue(SearchFields.DATASET_DESCRIPTION);
if (datasetDescriptions != null) {
String firstDatasetDescription = datasetDescriptions.get(0);
if (firstDatasetDescription != null) {
solrSearchResult.setDescriptionNoSnippet(firstDatasetDescription);
}
}
solrSearchResult.setDatasetVersionId(datasetVersionId);
solrSearchResult.setCitation(citation);
solrSearchResult.setCitationHtml(citationPlainHtml);
if (title != null) {
// solrSearchResult.setTitle((String) titles.get(0));
solrSearchResult.setTitle(title);
} else {
logger.fine("No title indexed. Setting to empty string to prevent NPE. Dataset id " + entityid + " and version id " + datasetVersionId);
solrSearchResult.setTitle("");
}
List<String> authors = (List) solrDocument.getFieldValues(DatasetFieldConstant.authorName);
if (authors != null) {
solrSearchResult.setDatasetAuthors(authors);
}
} else if (type.equals("files")) {
String parentGlobalId = null;
Object parentGlobalIdObject = solrDocument.getFieldValue(SearchFields.PARENT_IDENTIFIER);
if (parentGlobalIdObject != null) {
parentGlobalId = (String) parentGlobalIdObject;
parent.put(SolrSearchResult.PARENT_IDENTIFIER, parentGlobalId);
}
solrSearchResult.setHtmlUrl(baseUrl + "/dataset.xhtml?persistentId=" + parentGlobalId);
solrSearchResult.setDownloadUrl(baseUrl + "/api/access/datafile/" + entityid);
/**
* @todo We are not yet setting the API URL for files because
* not all files have metadata. Only subsettable files (those
* with a datatable) seem to have metadata. Furthermore, the
* response is in XML whereas the rest of the Search API returns
* JSON.
*/
// solrSearchResult.setApiUrl(baseUrl + "/api/meta/datafile/" + entityid);
//solrSearchResult.setImageUrl(baseUrl + "/api/access/fileCardImage/" + entityid);
solrSearchResult.setName(name);
solrSearchResult.setFiletype(filetype);
solrSearchResult.setFileContentType(fileContentType);
Object fileSizeInBytesObject = solrDocument.getFieldValue(SearchFields.FILE_SIZE_IN_BYTES);
if (fileSizeInBytesObject != null) {
try {
long fileSizeInBytesLong = (long) fileSizeInBytesObject;
solrSearchResult.setFileSizeInBytes(fileSizeInBytesLong);
} catch (ClassCastException ex) {
logger.info("Could not cast file " + entityid + " to long for " + SearchFields.FILE_SIZE_IN_BYTES + ": " + ex.getLocalizedMessage());
}
}
solrSearchResult.setFileMd5((String) solrDocument.getFieldValue(SearchFields.FILE_MD5));
try {
solrSearchResult.setFileChecksumType(DataFile.ChecksumType.fromString((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_TYPE)));
} catch (IllegalArgumentException ex) {
logger.info("Exception setting setFileChecksumType: " + ex);
}
solrSearchResult.setFileChecksumValue((String) solrDocument.getFieldValue(SearchFields.FILE_CHECKSUM_VALUE));
solrSearchResult.setUnf((String) solrDocument.getFieldValue(SearchFields.UNF));
solrSearchResult.setDatasetVersionId(datasetVersionId);
List<String> fileCategories = (List) solrDocument.getFieldValues(SearchFields.FILE_TAG);
if (fileCategories != null) {
solrSearchResult.setFileCategories(fileCategories);
}
List<String> tabularDataTags = (List) solrDocument.getFieldValues(SearchFields.TABDATA_TAG);
if (tabularDataTags != null) {
Collections.sort(tabularDataTags);
solrSearchResult.setTabularDataTags(tabularDataTags);
}
}
/**
* @todo store PARENT_ID as a long instead and cast as such
*/
parent.put("id", (String) solrDocument.getFieldValue(SearchFields.PARENT_ID));
parent.put("name", (String) solrDocument.getFieldValue(SearchFields.PARENT_NAME));
parent.put("citation", (String) solrDocument.getFieldValue(SearchFields.PARENT_CITATION));
solrSearchResult.setParent(parent);
solrSearchResults.add(solrSearchResult);
}
Map<String, List<String>> spellingSuggestionsByToken = new HashMap<>();
SpellCheckResponse spellCheckResponse = queryResponse.getSpellCheckResponse();
if (spellCheckResponse != null) {
List<SpellCheckResponse.Suggestion> suggestions = spellCheckResponse.getSuggestions();
for (SpellCheckResponse.Suggestion suggestion : suggestions) {
spellingSuggestionsByToken.put(suggestion.getToken(), suggestion.getAlternatives());
}
}
List<FacetCategory> facetCategoryList = new ArrayList<>();
List<FacetCategory> typeFacetCategories = new ArrayList<>();
boolean hidePublicationStatusFacet = true;
boolean draftsAvailable = false;
boolean unpublishedAvailable = false;
boolean deaccessionedAvailable = false;
boolean hideMetadataSourceFacet = true;
for (FacetField facetField : queryResponse.getFacetFields()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
int numMetadataSources = 0;
for (FacetField.Count facetFieldCount : facetField.getValues()) {
/**
* @todo we do want to show the count for each facet
*/
// logger.info("field: " + facetField.getName() + " " + facetFieldCount.getName() + " (" + facetFieldCount.getCount() + ")");
if (facetFieldCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(facetFieldCount.getName(), facetFieldCount.getCount());
// quote field facets
facetLabel.setFilterQuery(facetField.getName() + ":\"" + facetFieldCount.getName() + "\"");
facetLabelList.add(facetLabel);
if (facetField.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (facetLabel.getName().equals(IndexServiceBean.getUNPUBLISHED_STRING())) {
unpublishedAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDRAFT_STRING())) {
draftsAvailable = true;
} else if (facetLabel.getName().equals(IndexServiceBean.getDEACCESSIONED_STRING())) {
deaccessionedAvailable = true;
}
}
if (facetField.getName().equals(SearchFields.METADATA_SOURCE)) {
numMetadataSources++;
}
}
}
if (numMetadataSources > 1) {
hideMetadataSourceFacet = false;
}
facetCategory.setName(facetField.getName());
// hopefully people will never see the raw facetField.getName() because it may well have an _s at the end
facetCategory.setFriendlyName(facetField.getName());
// try to find a friendlier name to display as a facet
/**
* @todo hmm, we thought we wanted the datasetFields array to go
* away once we have more granularity than findAll() available per
* the todo above but we need a way to lookup by Solr field, so
* we'll build a hashmap
*/
for (DatasetFieldType datasetField : datasetFields) {
String solrFieldNameForDataset = datasetField.getSolrField().getNameFacetable();
String friendlyName = datasetField.getDisplayName();
if (solrFieldNameForDataset != null && facetField.getName().endsWith(datasetField.getTmpNullFieldTypeIdentifier())) {
// give it the non-friendly name so we remember to update the reference data script for datasets
facetCategory.setName(facetField.getName());
} else if (solrFieldNameForDataset != null && facetField.getName().equals(solrFieldNameForDataset)) {
if (friendlyName != null && !friendlyName.isEmpty()) {
facetCategory.setFriendlyName(friendlyName);
// stop examining available dataset fields. we found a match
break;
}
}
datasetfieldFriendlyNamesBySolrField.put(datasetField.getSolrField().getNameFacetable(), friendlyName);
}
/**
* @todo get rid of this crazy reflection, per todo above... or
* should we... let's put into a hash the friendly names of facet
* categories, indexed by Solr field
*/
for (Field fieldObject : staticSearchFields) {
String name = fieldObject.getName();
String staticSearchField = null;
try {
staticSearchField = (String) fieldObject.get(searchFieldsObject);
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(SearchServiceBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (staticSearchField != null && facetField.getName().equals(staticSearchField)) {
String[] parts = name.split("_");
StringBuilder stringBuilder = new StringBuilder();
for (String part : parts) {
stringBuilder.append(getCapitalizedName(part.toLowerCase()) + " ");
}
String friendlyNameWithTrailingSpace = stringBuilder.toString();
String friendlyName = friendlyNameWithTrailingSpace.replaceAll(" $", "");
facetCategory.setFriendlyName(friendlyName);
// logger.info("adding <<<" + staticSearchField + ":" + friendlyName + ">>>");
staticSolrFieldFriendlyNamesBySolrField.put(staticSearchField, friendlyName);
// stop examining the declared/static fields in the SearchFields object. we found a match
break;
}
}
facetCategory.setFacetLabel(facetLabelList);
if (!facetLabelList.isEmpty()) {
if (facetCategory.getName().equals(SearchFields.TYPE)) {
// the "type" facet is special, these are not
typeFacetCategories.add(facetCategory);
} else if (facetCategory.getName().equals(SearchFields.PUBLICATION_STATUS)) {
if (unpublishedAvailable || draftsAvailable || deaccessionedAvailable) {
hidePublicationStatusFacet = false;
}
if (!hidePublicationStatusFacet) {
facetCategoryList.add(facetCategory);
}
} else if (facetCategory.getName().equals(SearchFields.METADATA_SOURCE)) {
if (!hideMetadataSourceFacet) {
facetCategoryList.add(facetCategory);
}
} else {
facetCategoryList.add(facetCategory);
}
}
}
// for now the only range facet is citation year
for (RangeFacet<String, String> rangeFacet : queryResponse.getFacetRanges()) {
FacetCategory facetCategory = new FacetCategory();
List<FacetLabel> facetLabelList = new ArrayList<>();
for (Object rfObj : rangeFacet.getCounts()) {
RangeFacet.Count rangeFacetCount = (RangeFacet.Count) rfObj;
String valueString = rangeFacetCount.getValue();
Integer start = Integer.parseInt(valueString);
Integer end = start + Integer.parseInt(rangeFacet.getGap().toString());
// to avoid overlapping dates
end = end - 1;
if (rangeFacetCount.getCount() > 0) {
FacetLabel facetLabel = new FacetLabel(start + "-" + end, new Long(rangeFacetCount.getCount()));
// special [12 TO 34] syntax for range facets
facetLabel.setFilterQuery(rangeFacet.getName() + ":" + "[" + start + " TO " + end + "]");
facetLabelList.add(facetLabel);
}
}
facetCategory.setName(rangeFacet.getName());
facetCategory.setFacetLabel(facetLabelList);
// reverse to show the newest citation year range at the top
List<FacetLabel> facetLabelListReversed = new ArrayList<>();
ListIterator<FacetLabel> li = facetLabelList.listIterator(facetLabelList.size());
while (li.hasPrevious()) {
facetLabelListReversed.add(li.previous());
}
facetCategory.setFacetLabel(facetLabelListReversed);
if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | NONSATD | true | solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
} | solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} | if (!facetLabelList.isEmpty()) {
facetCategoryList.add(facetCategory);
}
}
SolrQueryResponse solrQueryResponse = new SolrQueryResponse(solrQuery);
solrQueryResponse.setSolrSearchResults(solrSearchResults);
solrQueryResponse.setSpellingSuggestionsByToken(spellingSuggestionsByToken);
solrQueryResponse.setFacetCategoryList(facetCategoryList);
solrQueryResponse.setTypeFacetCategories(typeFacetCategories);
solrQueryResponse.setNumResultsFound(queryResponse.getResults().getNumFound());
solrQueryResponse.setResultsStart(queryResponse.getResults().getStart());
solrQueryResponse.setDatasetfieldFriendlyNamesBySolrField(datasetfieldFriendlyNamesBySolrField);
solrQueryResponse.setStaticSolrFieldFriendlyNamesBySolrField(staticSolrFieldFriendlyNamesBySolrField);
String[] filterQueriesArray = solrQuery.getFilterQueries();
if (filterQueriesArray != null) {
// null check added because these tests were failing: mvn test -Dtest=SearchIT
List<String> actualFilterQueries = Arrays.asList(filterQueriesArray);
logger.fine("actual filter queries: " + actualFilterQueries);
solrQueryResponse.setFilterQueriesActual(actualFilterQueries);
} else {
// how often is this null?
logger.info("solrQuery.getFilterQueries() was null");
}
solrQueryResponse.setDvObjectCounts(queryResponse.getFacetField("dvObjectType"));
solrQueryResponse.setPublicationStatusCounts(queryResponse.getFacetField("publicationStatus"));
return solrQueryResponse;
} |
9,846 | 0 | // Be sure to clear the active file bit in case MPlayer is waiting for more data
// Be sure we don't close the stdin connection before we send the quit message, but don't
// hang waiting for the quit to be processed
// inactiveFile();
// stop(); | public void free()
{
currState = NO_STATE;
if (Sage.DBG) System.out.println("Closing down mplayer");
if (uiMgr != null)
uiMgr.putFloat("mplayer/last_volume", currVolume);
timeGuessMillis = 0;
guessTimestamp = 0;
currVolume = 1.0f;
if (mpStdin != null && isMPlayerRunning())
{
// Be sure to clear the active file bit in case MPlayer is waiting for more data
// Be sure we don't close the stdin connection before we send the quit message, but don't
// hang waiting for the quit to be processed
// inactiveFile();
// stop();
Thread t = new Thread("PlayerSendCmd")
{
public void run()
{
if (Sage.DBG) System.out.println("Waiting for the cmd queue to clear...");
synchronized (sendCmdQueue)
{
while (!sendCmdQueue.isEmpty())
{
try
{
sendCmdQueue.wait(50);
}
catch (InterruptedException e){}
continue;
}
}
if (Sage.DBG) System.out.println("Sending mplayer command: quit");
if (!fileDeactivated)
{
fileDeactivated = true;
synchronized (mpStdin)
{
mpStdin.println("inactive_file");
}
}
if (currState == PLAY_STATE && !eos)
{
synchronized (mpStdin)
{
mpStdin.println("pause");
}
currState = STOPPED_STATE;
}
else
currState = STOPPED_STATE;
synchronized (mpStdin)
{
mpStdin.println("quit");
}
mpStdin.close();
mpStdin = null;
if (mpStdout != null)
{
try { mpStdout.close(); } catch (java.io.IOException e) {}
mpStdout = null;
}
if (mpStderr != null)
{
try { mpStderr.close(); } catch (java.io.IOException e) {}
mpStderr = null;
}
}
};
t.setPriority(Thread.currentThread().getPriority());
t.setDaemon(true);
t.start();
}
if (mpProc != null)
{
long startWait = Sage.eventTime();
// FIXME: temp crutch, in testing on Mac OS X mplayer either terminates immediately or hangs, there is no in-between...
long killDelay = (Sage.MAC_OS_X ? 2000 : 15000);
while (true)
{
try
{
int exitValue = mpProc.exitValue();
if (Sage.DBG) System.out.println("MPlayer process exit code:" + exitValue);
break;
}
catch (IllegalThreadStateException e)
{
if (Sage.DBG) System.out.println("MPlayer process has not exited yet...");
try{Thread.sleep(100);}catch(Exception e1){}
if (Sage.eventTime() - startWait > killDelay)
{
if (Sage.DBG) System.out.println("Forcibly killing MPlayer process!");
mpProc.destroy();
break;
}
}
}
mpProc = null;
}
if (launchedAsyncRenderThread)
((DirectX9SageRenderer)uiMgr.getRootPanel().getRenderEngine()).asyncVideoRender(null);
if (releaseServerAccessVobSubBase != null)
{
NetworkClient.getSN().requestMediaServerAccess(new java.io.File(releaseServerAccessVobSubBase + ".idx"), false);
NetworkClient.getSN().requestMediaServerAccess(new java.io.File(releaseServerAccessVobSubBase + ".sub"), false);
releaseServerAccessVobSubBase = null;
}
} | NONSATD | true | if (mpStdin != null && isMPlayerRunning())
{
// Be sure to clear the active file bit in case MPlayer is waiting for more data
// Be sure we don't close the stdin connection before we send the quit message, but don't
// hang waiting for the quit to be processed
// inactiveFile();
// stop();
Thread t = new Thread("PlayerSendCmd")
{ | {
currState = NO_STATE;
if (Sage.DBG) System.out.println("Closing down mplayer");
if (uiMgr != null)
uiMgr.putFloat("mplayer/last_volume", currVolume);
timeGuessMillis = 0;
guessTimestamp = 0;
currVolume = 1.0f;
if (mpStdin != null && isMPlayerRunning())
{
// Be sure to clear the active file bit in case MPlayer is waiting for more data
// Be sure we don't close the stdin connection before we send the quit message, but don't
// hang waiting for the quit to be processed
// inactiveFile();
// stop();
Thread t = new Thread("PlayerSendCmd")
{
public void run()
{
if (Sage.DBG) System.out.println("Waiting for the cmd queue to clear...");
synchronized (sendCmdQueue)
{
while (!sendCmdQueue.isEmpty())
{
try | public void free()
{
currState = NO_STATE;
if (Sage.DBG) System.out.println("Closing down mplayer");
if (uiMgr != null)
uiMgr.putFloat("mplayer/last_volume", currVolume);
timeGuessMillis = 0;
guessTimestamp = 0;
currVolume = 1.0f;
if (mpStdin != null && isMPlayerRunning())
{
// Be sure to clear the active file bit in case MPlayer is waiting for more data
// Be sure we don't close the stdin connection before we send the quit message, but don't
// hang waiting for the quit to be processed
// inactiveFile();
// stop();
Thread t = new Thread("PlayerSendCmd")
{
public void run()
{
if (Sage.DBG) System.out.println("Waiting for the cmd queue to clear...");
synchronized (sendCmdQueue)
{
while (!sendCmdQueue.isEmpty())
{
try
{
sendCmdQueue.wait(50);
}
catch (InterruptedException e){}
continue;
}
}
if (Sage.DBG) System.out.println("Sending mplayer command: quit");
if (!fileDeactivated)
{ |
9,846 | 1 | // FIXME: temp crutch, in testing on Mac OS X mplayer either terminates immediately or hangs, there is no in-between... | public void free()
{
currState = NO_STATE;
if (Sage.DBG) System.out.println("Closing down mplayer");
if (uiMgr != null)
uiMgr.putFloat("mplayer/last_volume", currVolume);
timeGuessMillis = 0;
guessTimestamp = 0;
currVolume = 1.0f;
if (mpStdin != null && isMPlayerRunning())
{
// Be sure to clear the active file bit in case MPlayer is waiting for more data
// Be sure we don't close the stdin connection before we send the quit message, but don't
// hang waiting for the quit to be processed
// inactiveFile();
// stop();
Thread t = new Thread("PlayerSendCmd")
{
public void run()
{
if (Sage.DBG) System.out.println("Waiting for the cmd queue to clear...");
synchronized (sendCmdQueue)
{
while (!sendCmdQueue.isEmpty())
{
try
{
sendCmdQueue.wait(50);
}
catch (InterruptedException e){}
continue;
}
}
if (Sage.DBG) System.out.println("Sending mplayer command: quit");
if (!fileDeactivated)
{
fileDeactivated = true;
synchronized (mpStdin)
{
mpStdin.println("inactive_file");
}
}
if (currState == PLAY_STATE && !eos)
{
synchronized (mpStdin)
{
mpStdin.println("pause");
}
currState = STOPPED_STATE;
}
else
currState = STOPPED_STATE;
synchronized (mpStdin)
{
mpStdin.println("quit");
}
mpStdin.close();
mpStdin = null;
if (mpStdout != null)
{
try { mpStdout.close(); } catch (java.io.IOException e) {}
mpStdout = null;
}
if (mpStderr != null)
{
try { mpStderr.close(); } catch (java.io.IOException e) {}
mpStderr = null;
}
}
};
t.setPriority(Thread.currentThread().getPriority());
t.setDaemon(true);
t.start();
}
if (mpProc != null)
{
long startWait = Sage.eventTime();
// FIXME: temp crutch, in testing on Mac OS X mplayer either terminates immediately or hangs, there is no in-between...
long killDelay = (Sage.MAC_OS_X ? 2000 : 15000);
while (true)
{
try
{
int exitValue = mpProc.exitValue();
if (Sage.DBG) System.out.println("MPlayer process exit code:" + exitValue);
break;
}
catch (IllegalThreadStateException e)
{
if (Sage.DBG) System.out.println("MPlayer process has not exited yet...");
try{Thread.sleep(100);}catch(Exception e1){}
if (Sage.eventTime() - startWait > killDelay)
{
if (Sage.DBG) System.out.println("Forcibly killing MPlayer process!");
mpProc.destroy();
break;
}
}
}
mpProc = null;
}
if (launchedAsyncRenderThread)
((DirectX9SageRenderer)uiMgr.getRootPanel().getRenderEngine()).asyncVideoRender(null);
if (releaseServerAccessVobSubBase != null)
{
NetworkClient.getSN().requestMediaServerAccess(new java.io.File(releaseServerAccessVobSubBase + ".idx"), false);
NetworkClient.getSN().requestMediaServerAccess(new java.io.File(releaseServerAccessVobSubBase + ".sub"), false);
releaseServerAccessVobSubBase = null;
}
} | DEFECT | true | {
long startWait = Sage.eventTime();
// FIXME: temp crutch, in testing on Mac OS X mplayer either terminates immediately or hangs, there is no in-between...
long killDelay = (Sage.MAC_OS_X ? 2000 : 15000);
while (true) | }
}
};
t.setPriority(Thread.currentThread().getPriority());
t.setDaemon(true);
t.start();
}
if (mpProc != null)
{
long startWait = Sage.eventTime();
// FIXME: temp crutch, in testing on Mac OS X mplayer either terminates immediately or hangs, there is no in-between...
long killDelay = (Sage.MAC_OS_X ? 2000 : 15000);
while (true)
{
try
{
int exitValue = mpProc.exitValue();
if (Sage.DBG) System.out.println("MPlayer process exit code:" + exitValue);
break;
}
catch (IllegalThreadStateException e) | mpStdin = null;
if (mpStdout != null)
{
try { mpStdout.close(); } catch (java.io.IOException e) {}
mpStdout = null;
}
if (mpStderr != null)
{
try { mpStderr.close(); } catch (java.io.IOException e) {}
mpStderr = null;
}
}
};
t.setPriority(Thread.currentThread().getPriority());
t.setDaemon(true);
t.start();
}
if (mpProc != null)
{
long startWait = Sage.eventTime();
// FIXME: temp crutch, in testing on Mac OS X mplayer either terminates immediately or hangs, there is no in-between...
long killDelay = (Sage.MAC_OS_X ? 2000 : 15000);
while (true)
{
try
{
int exitValue = mpProc.exitValue();
if (Sage.DBG) System.out.println("MPlayer process exit code:" + exitValue);
break;
}
catch (IllegalThreadStateException e)
{
if (Sage.DBG) System.out.println("MPlayer process has not exited yet...");
try{Thread.sleep(100);}catch(Exception e1){}
if (Sage.eventTime() - startWait > killDelay)
{
if (Sage.DBG) System.out.println("Forcibly killing MPlayer process!");
mpProc.destroy();
break;
}
} |
1,656 | 0 | // TODO(qinmin): pass the error code to native. | private void onSessionError(final int sessionId) {
// TODO(qinmin): pass the error code to native.
mHandler.post(new Runnable() {
@Override
public void run() {
nativeOnSessionError(mNativeMediaDrmBridge, sessionId);
}
});
} | IMPLEMENTATION | true | private void onSessionError(final int sessionId) {
// TODO(qinmin): pass the error code to native.
mHandler.post(new Runnable() {
@Override | private void onSessionError(final int sessionId) {
// TODO(qinmin): pass the error code to native.
mHandler.post(new Runnable() {
@Override
public void run() {
nativeOnSessionError(mNativeMediaDrmBridge, sessionId);
}
});
} | private void onSessionError(final int sessionId) {
// TODO(qinmin): pass the error code to native.
mHandler.post(new Runnable() {
@Override
public void run() {
nativeOnSessionError(mNativeMediaDrmBridge, sessionId);
}
});
} |
1,657 | 0 | /**
* replaces all except if a match is immediately preceded by a > sign, in which case this
* match is not replaced
*/ | public static String replaceAllIfNotInsideTag(String origStr, String findThis, String replaceWith) {
if (origStr == null) {
return null;
}
if (findThis == null) {
return origStr;
}
if (replaceWith == null) {
replaceWith = "";
}
StringBuilder result = new StringBuilder();
int index = origStr.indexOf(findThis);
while (index >= 0) {
result.append(origStr.substring(0, index));
if ((index > 0) && origStr.charAt(index - 1) == '>') {
result.append(findThis);
} else {
result.append(replaceWith);
}
// TODO :: improve speed by not calling substring but keeping track of start!
origStr = origStr.substring(index + findThis.length());
index = origStr.indexOf(findThis);
}
result.append(origStr);
return result.toString();
} | NONSATD | true | public static String replaceAllIfNotInsideTag(String origStr, String findThis, String replaceWith) {
if (origStr == null) {
return null;
}
if (findThis == null) {
return origStr;
}
if (replaceWith == null) {
replaceWith = "";
}
StringBuilder result = new StringBuilder();
int index = origStr.indexOf(findThis);
while (index >= 0) {
result.append(origStr.substring(0, index));
if ((index > 0) && origStr.charAt(index - 1) == '>') {
result.append(findThis);
} else {
result.append(replaceWith);
}
// TODO :: improve speed by not calling substring but keeping track of start!
origStr = origStr.substring(index + findThis.length());
index = origStr.indexOf(findThis);
}
result.append(origStr);
return result.toString();
} | public static String replaceAllIfNotInsideTag(String origStr, String findThis, String replaceWith) {
if (origStr == null) {
return null;
}
if (findThis == null) {
return origStr;
}
if (replaceWith == null) {
replaceWith = "";
}
StringBuilder result = new StringBuilder();
int index = origStr.indexOf(findThis);
while (index >= 0) {
result.append(origStr.substring(0, index));
if ((index > 0) && origStr.charAt(index - 1) == '>') {
result.append(findThis);
} else {
result.append(replaceWith);
}
// TODO :: improve speed by not calling substring but keeping track of start!
origStr = origStr.substring(index + findThis.length());
index = origStr.indexOf(findThis);
}
result.append(origStr);
return result.toString();
} | public static String replaceAllIfNotInsideTag(String origStr, String findThis, String replaceWith) {
if (origStr == null) {
return null;
}
if (findThis == null) {
return origStr;
}
if (replaceWith == null) {
replaceWith = "";
}
StringBuilder result = new StringBuilder();
int index = origStr.indexOf(findThis);
while (index >= 0) {
result.append(origStr.substring(0, index));
if ((index > 0) && origStr.charAt(index - 1) == '>') {
result.append(findThis);
} else {
result.append(replaceWith);
}
// TODO :: improve speed by not calling substring but keeping track of start!
origStr = origStr.substring(index + findThis.length());
index = origStr.indexOf(findThis);
}
result.append(origStr);
return result.toString();
} |
1,657 | 1 | // TODO :: improve speed by not calling substring but keeping track of start! | public static String replaceAllIfNotInsideTag(String origStr, String findThis, String replaceWith) {
if (origStr == null) {
return null;
}
if (findThis == null) {
return origStr;
}
if (replaceWith == null) {
replaceWith = "";
}
StringBuilder result = new StringBuilder();
int index = origStr.indexOf(findThis);
while (index >= 0) {
result.append(origStr.substring(0, index));
if ((index > 0) && origStr.charAt(index - 1) == '>') {
result.append(findThis);
} else {
result.append(replaceWith);
}
// TODO :: improve speed by not calling substring but keeping track of start!
origStr = origStr.substring(index + findThis.length());
index = origStr.indexOf(findThis);
}
result.append(origStr);
return result.toString();
} | DESIGN | true | result.append(replaceWith);
}
// TODO :: improve speed by not calling substring but keeping track of start!
origStr = origStr.substring(index + findThis.length());
index = origStr.indexOf(findThis); | }
StringBuilder result = new StringBuilder();
int index = origStr.indexOf(findThis);
while (index >= 0) {
result.append(origStr.substring(0, index));
if ((index > 0) && origStr.charAt(index - 1) == '>') {
result.append(findThis);
} else {
result.append(replaceWith);
}
// TODO :: improve speed by not calling substring but keeping track of start!
origStr = origStr.substring(index + findThis.length());
index = origStr.indexOf(findThis);
}
result.append(origStr);
return result.toString();
} | public static String replaceAllIfNotInsideTag(String origStr, String findThis, String replaceWith) {
if (origStr == null) {
return null;
}
if (findThis == null) {
return origStr;
}
if (replaceWith == null) {
replaceWith = "";
}
StringBuilder result = new StringBuilder();
int index = origStr.indexOf(findThis);
while (index >= 0) {
result.append(origStr.substring(0, index));
if ((index > 0) && origStr.charAt(index - 1) == '>') {
result.append(findThis);
} else {
result.append(replaceWith);
}
// TODO :: improve speed by not calling substring but keeping track of start!
origStr = origStr.substring(index + findThis.length());
index = origStr.indexOf(findThis);
}
result.append(origStr);
return result.toString();
} |
26,234 | 0 | //TODO Replace this with java.util.Collections! | @GET
@PermitAll
@Path("/server/info")
@Produces(MediaType.APPLICATION_JSON)
public Response getServerInformation() throws ApiException {
Map<String, Object> returnMap = new HashMap<String, Object>();
List<Object> configurations = new ArrayList<Object>();
AppConstants appConstants = AppConstants.getInstance();
for (Configuration configuration : getIbisManager().getConfigurations()) {
Map<String, Object> cfg = new HashMap<String, Object>();
cfg.put("name", configuration.getName());
cfg.put("version", configuration.getVersion());
cfg.put("stubbed", configuration.isStubbed());
cfg.put("type", configuration.getClassLoaderType());
if(configuration.getConfigurationException() != null) {
cfg.put("exception", configuration.getConfigurationException().getMessage());
}
ClassLoader classLoader = configuration.getClassLoader();
if(classLoader instanceof DatabaseClassLoader) {
cfg.put("filename", ((DatabaseClassLoader) classLoader).getFileName());
cfg.put("created", ((DatabaseClassLoader) classLoader).getCreationDate());
cfg.put("user", ((DatabaseClassLoader) classLoader).getUser());
}
String parentConfig = AppConstants.getInstance().getString("configurations." + configuration.getName() + ".parentConfig", null);
if(parentConfig != null)
cfg.put("parent", parentConfig);
configurations.add(cfg);
}
//TODO Replace this with java.util.Collections!
Collections.sort(configurations, new Comparator<Map<String, String>>() {
@Override
public int compare(Map<String, String> lhs, Map<String, String> rhs) {
String name1 = lhs.get("name");
String name2 = rhs.get("name");
return name1.startsWith("IAF_") ? -1 : name2.startsWith("IAF_") ? 1 : name1.compareTo(name2);
}
});
returnMap.put("configurations", configurations);
Map<String, Object> framework = new HashMap<String, Object>(2);
framework.put("name", "FF!");
framework.put("version", appConstants.getProperty("application.version"));
returnMap.put("framework", framework);
Map<String, Object> instance = new HashMap<String, Object>(2);
instance.put("version", appConstants.getProperty("instance.version"));
instance.put("name", getIbisContext().getApplicationName());
returnMap.put("instance", instance);
String dtapStage = appConstants.getProperty("dtap.stage");
returnMap.put("dtap.stage", dtapStage);
String dtapSide = appConstants.getProperty("dtap.side");
returnMap.put("dtap.side", dtapSide);
returnMap.put("applicationServer", servletConfig.getServletContext().getServerInfo());
returnMap.put("javaVersion", System.getProperty("java.runtime.name") + " (" + System.getProperty("java.runtime.version") + ")");
Map<String, Object> fileSystem = new HashMap<String, Object>(2);
fileSystem.put("totalSpace", Misc.getFileSystemTotalSpace());
fileSystem.put("freeSpace", Misc.getFileSystemFreeSpace());
returnMap.put("fileSystem", fileSystem);
returnMap.put("processMetrics", ProcessMetrics.toMap());
Date date = new Date();
returnMap.put("serverTime", date.getTime());
returnMap.put("machineName" , Misc.getHostname());
ApplicationMetrics metrics = getIbisContext().getBean("metrics", ApplicationMetrics.class);
returnMap.put("uptime", (metrics != null) ? metrics.getUptimeDate() : "");
return Response.status(Response.Status.OK).entity(returnMap).build();
} | DESIGN | true | configurations.add(cfg);
}
//TODO Replace this with java.util.Collections!
Collections.sort(configurations, new Comparator<Map<String, String>>() {
@Override | if(classLoader instanceof DatabaseClassLoader) {
cfg.put("filename", ((DatabaseClassLoader) classLoader).getFileName());
cfg.put("created", ((DatabaseClassLoader) classLoader).getCreationDate());
cfg.put("user", ((DatabaseClassLoader) classLoader).getUser());
}
String parentConfig = AppConstants.getInstance().getString("configurations." + configuration.getName() + ".parentConfig", null);
if(parentConfig != null)
cfg.put("parent", parentConfig);
configurations.add(cfg);
}
//TODO Replace this with java.util.Collections!
Collections.sort(configurations, new Comparator<Map<String, String>>() {
@Override
public int compare(Map<String, String> lhs, Map<String, String> rhs) {
String name1 = lhs.get("name");
String name2 = rhs.get("name");
return name1.startsWith("IAF_") ? -1 : name2.startsWith("IAF_") ? 1 : name1.compareTo(name2);
}
});
returnMap.put("configurations", configurations);
Map<String, Object> framework = new HashMap<String, Object>(2); | for (Configuration configuration : getIbisManager().getConfigurations()) {
Map<String, Object> cfg = new HashMap<String, Object>();
cfg.put("name", configuration.getName());
cfg.put("version", configuration.getVersion());
cfg.put("stubbed", configuration.isStubbed());
cfg.put("type", configuration.getClassLoaderType());
if(configuration.getConfigurationException() != null) {
cfg.put("exception", configuration.getConfigurationException().getMessage());
}
ClassLoader classLoader = configuration.getClassLoader();
if(classLoader instanceof DatabaseClassLoader) {
cfg.put("filename", ((DatabaseClassLoader) classLoader).getFileName());
cfg.put("created", ((DatabaseClassLoader) classLoader).getCreationDate());
cfg.put("user", ((DatabaseClassLoader) classLoader).getUser());
}
String parentConfig = AppConstants.getInstance().getString("configurations." + configuration.getName() + ".parentConfig", null);
if(parentConfig != null)
cfg.put("parent", parentConfig);
configurations.add(cfg);
}
//TODO Replace this with java.util.Collections!
Collections.sort(configurations, new Comparator<Map<String, String>>() {
@Override
public int compare(Map<String, String> lhs, Map<String, String> rhs) {
String name1 = lhs.get("name");
String name2 = rhs.get("name");
return name1.startsWith("IAF_") ? -1 : name2.startsWith("IAF_") ? 1 : name1.compareTo(name2);
}
});
returnMap.put("configurations", configurations);
Map<String, Object> framework = new HashMap<String, Object>(2);
framework.put("name", "FF!");
framework.put("version", appConstants.getProperty("application.version"));
returnMap.put("framework", framework);
Map<String, Object> instance = new HashMap<String, Object>(2);
instance.put("version", appConstants.getProperty("instance.version"));
instance.put("name", getIbisContext().getApplicationName());
returnMap.put("instance", instance);
String dtapStage = appConstants.getProperty("dtap.stage");
returnMap.put("dtap.stage", dtapStage);
String dtapSide = appConstants.getProperty("dtap.side"); |
1,659 | 0 | // TODO :: improve speed by not calling substring but keeping track of start! | private static String addAfterLinesContainingEx(String origStr, String findThis, String addThat,
String eolMarker, boolean notInsideTag) {
if (origStr == null) {
return null;
}
if (findThis == null) {
return origStr;
}
if ((addThat == null) || "".equals(addThat)) {
return origStr;
}
if ((eolMarker == null) || "".equals(eolMarker)) {
return origStr;
}
if ("".equals(findThis)) {
return replaceAll(origStr, "\n", "\n" + addThat) + "\n" + addThat;
}
StringBuilder result = new StringBuilder();
int index = origStr.indexOf(findThis);
while (index >= 0) {
if (notInsideTag) {
if ((index > 0) && origStr.charAt(index - 1) == '>') {
index = origStr.indexOf(findThis, index + 1);
continue;
}
}
int eol = origStr.indexOf(eolMarker, index);
if (eol < 0) {
result.append(origStr);
result.append(eolMarker);
origStr = "";
} else {
result.append(origStr.substring(0, eol + eolMarker.length()));
// TODO :: improve speed by not calling substring but keeping track of start!
origStr = origStr.substring(eol + eolMarker.length());
}
result.append(addThat);
index = origStr.indexOf(findThis);
}
result.append(origStr);
return result.toString();
} | DESIGN | true | } else {
result.append(origStr.substring(0, eol + eolMarker.length()));
// TODO :: improve speed by not calling substring but keeping track of start!
origStr = origStr.substring(eol + eolMarker.length());
} | continue;
}
}
int eol = origStr.indexOf(eolMarker, index);
if (eol < 0) {
result.append(origStr);
result.append(eolMarker);
origStr = "";
} else {
result.append(origStr.substring(0, eol + eolMarker.length()));
// TODO :: improve speed by not calling substring but keeping track of start!
origStr = origStr.substring(eol + eolMarker.length());
}
result.append(addThat);
index = origStr.indexOf(findThis);
}
result.append(origStr);
return result.toString();
} | }
if ("".equals(findThis)) {
return replaceAll(origStr, "\n", "\n" + addThat) + "\n" + addThat;
}
StringBuilder result = new StringBuilder();
int index = origStr.indexOf(findThis);
while (index >= 0) {
if (notInsideTag) {
if ((index > 0) && origStr.charAt(index - 1) == '>') {
index = origStr.indexOf(findThis, index + 1);
continue;
}
}
int eol = origStr.indexOf(eolMarker, index);
if (eol < 0) {
result.append(origStr);
result.append(eolMarker);
origStr = "";
} else {
result.append(origStr.substring(0, eol + eolMarker.length()));
// TODO :: improve speed by not calling substring but keeping track of start!
origStr = origStr.substring(eol + eolMarker.length());
}
result.append(addThat);
index = origStr.indexOf(findThis);
}
result.append(origStr);
return result.toString();
} |
26,236 | 0 | // TODO: the null value is not allowed per OAS document.
// The deserialization should fail. | @Test
public void testNullValueDisallowed() throws Exception {
{
String str = "{ \"id\": 123, \"petId\": 345, \"quantity\": 100, \"status\": \"placed\" }";
org.openapitools.client.model.Order o = json.getContext(null).readValue(str, org.openapitools.client.model.Order.class);
assertEquals(100L, (long)o.getQuantity());
assertEquals(org.openapitools.client.model.Order.StatusEnum.PLACED, o.getStatus());
}
{
String str = "{ \"id\": 123, \"petId\": 345, \"quantity\": null }";
org.openapitools.client.model.Order o = json.getContext(null).readValue(str, org.openapitools.client.model.Order.class);
// TODO: the null value is not allowed per OAS document.
// The deserialization should fail.
assertNull(o.getQuantity());
}
} | DEFECT | true | String str = "{ \"id\": 123, \"petId\": 345, \"quantity\": null }";
org.openapitools.client.model.Order o = json.getContext(null).readValue(str, org.openapitools.client.model.Order.class);
// TODO: the null value is not allowed per OAS document.
// The deserialization should fail.
assertNull(o.getQuantity());
} | public void testNullValueDisallowed() throws Exception {
{
String str = "{ \"id\": 123, \"petId\": 345, \"quantity\": 100, \"status\": \"placed\" }";
org.openapitools.client.model.Order o = json.getContext(null).readValue(str, org.openapitools.client.model.Order.class);
assertEquals(100L, (long)o.getQuantity());
assertEquals(org.openapitools.client.model.Order.StatusEnum.PLACED, o.getStatus());
}
{
String str = "{ \"id\": 123, \"petId\": 345, \"quantity\": null }";
org.openapitools.client.model.Order o = json.getContext(null).readValue(str, org.openapitools.client.model.Order.class);
// TODO: the null value is not allowed per OAS document.
// The deserialization should fail.
assertNull(o.getQuantity());
}
} | @Test
public void testNullValueDisallowed() throws Exception {
{
String str = "{ \"id\": 123, \"petId\": 345, \"quantity\": 100, \"status\": \"placed\" }";
org.openapitools.client.model.Order o = json.getContext(null).readValue(str, org.openapitools.client.model.Order.class);
assertEquals(100L, (long)o.getQuantity());
assertEquals(org.openapitools.client.model.Order.StatusEnum.PLACED, o.getStatus());
}
{
String str = "{ \"id\": 123, \"petId\": 345, \"quantity\": null }";
org.openapitools.client.model.Order o = json.getContext(null).readValue(str, org.openapitools.client.model.Order.class);
// TODO: the null value is not allowed per OAS document.
// The deserialization should fail.
assertNull(o.getQuantity());
}
} |
34,429 | 0 | // todo dk: think about specific method versions for each allowed type | public void setValue(Object newValue) {
Object checkedValue = checkValue(newValue);
setDirty(isDifferent(baseValue, checkedValue));
if (isDifferent(value, checkedValue)){ // firePropertyChange doesn't do this check sufficiently
firePropertyChange(VALUE, value, value = checkedValue); // set inline to avoid recursion
}
} | DESIGN | true | public void setValue(Object newValue) {
Object checkedValue = checkValue(newValue);
setDirty(isDifferent(baseValue, checkedValue));
if (isDifferent(value, checkedValue)){ // firePropertyChange doesn't do this check sufficiently
firePropertyChange(VALUE, value, value = checkedValue); // set inline to avoid recursion
}
} | public void setValue(Object newValue) {
Object checkedValue = checkValue(newValue);
setDirty(isDifferent(baseValue, checkedValue));
if (isDifferent(value, checkedValue)){ // firePropertyChange doesn't do this check sufficiently
firePropertyChange(VALUE, value, value = checkedValue); // set inline to avoid recursion
}
} | public void setValue(Object newValue) {
Object checkedValue = checkValue(newValue);
setDirty(isDifferent(baseValue, checkedValue));
if (isDifferent(value, checkedValue)){ // firePropertyChange doesn't do this check sufficiently
firePropertyChange(VALUE, value, value = checkedValue); // set inline to avoid recursion
}
} |
34,429 | 1 | // firePropertyChange doesn't do this check sufficiently | public void setValue(Object newValue) {
Object checkedValue = checkValue(newValue);
setDirty(isDifferent(baseValue, checkedValue));
if (isDifferent(value, checkedValue)){ // firePropertyChange doesn't do this check sufficiently
firePropertyChange(VALUE, value, value = checkedValue); // set inline to avoid recursion
}
} | NONSATD | true | Object checkedValue = checkValue(newValue);
setDirty(isDifferent(baseValue, checkedValue));
if (isDifferent(value, checkedValue)){ // firePropertyChange doesn't do this check sufficiently
firePropertyChange(VALUE, value, value = checkedValue); // set inline to avoid recursion
} | public void setValue(Object newValue) {
Object checkedValue = checkValue(newValue);
setDirty(isDifferent(baseValue, checkedValue));
if (isDifferent(value, checkedValue)){ // firePropertyChange doesn't do this check sufficiently
firePropertyChange(VALUE, value, value = checkedValue); // set inline to avoid recursion
}
} | public void setValue(Object newValue) {
Object checkedValue = checkValue(newValue);
setDirty(isDifferent(baseValue, checkedValue));
if (isDifferent(value, checkedValue)){ // firePropertyChange doesn't do this check sufficiently
firePropertyChange(VALUE, value, value = checkedValue); // set inline to avoid recursion
}
} |
34,429 | 2 | // set inline to avoid recursion | public void setValue(Object newValue) {
Object checkedValue = checkValue(newValue);
setDirty(isDifferent(baseValue, checkedValue));
if (isDifferent(value, checkedValue)){ // firePropertyChange doesn't do this check sufficiently
firePropertyChange(VALUE, value, value = checkedValue); // set inline to avoid recursion
}
} | NONSATD | true | setDirty(isDifferent(baseValue, checkedValue));
if (isDifferent(value, checkedValue)){ // firePropertyChange doesn't do this check sufficiently
firePropertyChange(VALUE, value, value = checkedValue); // set inline to avoid recursion
}
} | public void setValue(Object newValue) {
Object checkedValue = checkValue(newValue);
setDirty(isDifferent(baseValue, checkedValue));
if (isDifferent(value, checkedValue)){ // firePropertyChange doesn't do this check sufficiently
firePropertyChange(VALUE, value, value = checkedValue); // set inline to avoid recursion
}
} | public void setValue(Object newValue) {
Object checkedValue = checkValue(newValue);
setDirty(isDifferent(baseValue, checkedValue));
if (isDifferent(value, checkedValue)){ // firePropertyChange doesn't do this check sufficiently
firePropertyChange(VALUE, value, value = checkedValue); // set inline to avoid recursion
}
} |
1,664 | 0 | /**
* Returns an accumulator to use for this animation. All animations with the same tag and target share the same accumulator.
* The lookup is rather slow, so try to store the returned object somewhere you can access it directly.
*/ | public AccumulatedAnimationValue getAccumulatedAnimationValue(AdditiveAnimation animation) {
// TODO: is there any way to make this `get()` faster?
AccumulatedAnimationValue accumulatedAnimationValue = accumulatedAnimationValues.get(animation);
if(accumulatedAnimationValue != null) {
return accumulatedAnimationValue;
}
accumulatedAnimationValue = new AccumulatedAnimationValue(animation);
accumulatedAnimationValues.put(animation, accumulatedAnimationValue);
return accumulatedAnimationValue;
} | NONSATD | true | public AccumulatedAnimationValue getAccumulatedAnimationValue(AdditiveAnimation animation) {
// TODO: is there any way to make this `get()` faster?
AccumulatedAnimationValue accumulatedAnimationValue = accumulatedAnimationValues.get(animation);
if(accumulatedAnimationValue != null) {
return accumulatedAnimationValue;
}
accumulatedAnimationValue = new AccumulatedAnimationValue(animation);
accumulatedAnimationValues.put(animation, accumulatedAnimationValue);
return accumulatedAnimationValue;
} | public AccumulatedAnimationValue getAccumulatedAnimationValue(AdditiveAnimation animation) {
// TODO: is there any way to make this `get()` faster?
AccumulatedAnimationValue accumulatedAnimationValue = accumulatedAnimationValues.get(animation);
if(accumulatedAnimationValue != null) {
return accumulatedAnimationValue;
}
accumulatedAnimationValue = new AccumulatedAnimationValue(animation);
accumulatedAnimationValues.put(animation, accumulatedAnimationValue);
return accumulatedAnimationValue;
} | public AccumulatedAnimationValue getAccumulatedAnimationValue(AdditiveAnimation animation) {
// TODO: is there any way to make this `get()` faster?
AccumulatedAnimationValue accumulatedAnimationValue = accumulatedAnimationValues.get(animation);
if(accumulatedAnimationValue != null) {
return accumulatedAnimationValue;
}
accumulatedAnimationValue = new AccumulatedAnimationValue(animation);
accumulatedAnimationValues.put(animation, accumulatedAnimationValue);
return accumulatedAnimationValue;
} |
1,664 | 1 | // TODO: is there any way to make this `get()` faster? | public AccumulatedAnimationValue getAccumulatedAnimationValue(AdditiveAnimation animation) {
// TODO: is there any way to make this `get()` faster?
AccumulatedAnimationValue accumulatedAnimationValue = accumulatedAnimationValues.get(animation);
if(accumulatedAnimationValue != null) {
return accumulatedAnimationValue;
}
accumulatedAnimationValue = new AccumulatedAnimationValue(animation);
accumulatedAnimationValues.put(animation, accumulatedAnimationValue);
return accumulatedAnimationValue;
} | DESIGN | true | public AccumulatedAnimationValue getAccumulatedAnimationValue(AdditiveAnimation animation) {
// TODO: is there any way to make this `get()` faster?
AccumulatedAnimationValue accumulatedAnimationValue = accumulatedAnimationValues.get(animation);
if(accumulatedAnimationValue != null) { | public AccumulatedAnimationValue getAccumulatedAnimationValue(AdditiveAnimation animation) {
// TODO: is there any way to make this `get()` faster?
AccumulatedAnimationValue accumulatedAnimationValue = accumulatedAnimationValues.get(animation);
if(accumulatedAnimationValue != null) {
return accumulatedAnimationValue;
}
accumulatedAnimationValue = new AccumulatedAnimationValue(animation);
accumulatedAnimationValues.put(animation, accumulatedAnimationValue);
return accumulatedAnimationValue;
} | public AccumulatedAnimationValue getAccumulatedAnimationValue(AdditiveAnimation animation) {
// TODO: is there any way to make this `get()` faster?
AccumulatedAnimationValue accumulatedAnimationValue = accumulatedAnimationValues.get(animation);
if(accumulatedAnimationValue != null) {
return accumulatedAnimationValue;
}
accumulatedAnimationValue = new AccumulatedAnimationValue(animation);
accumulatedAnimationValues.put(animation, accumulatedAnimationValue);
return accumulatedAnimationValue;
} |
26,242 | 0 | /**
* Returns the [position]th call found in the call map with the specified state. TODO: Improve
* this logic to sort by call time.
*/ | public DialerCall getCallWithState(int state, int positionToFind) {
DialerCall retval = null;
int position = 0;
for (DialerCall call : callById.values()) {
if (call.getState() == state) {
if (position >= positionToFind) {
retval = call;
break;
} else {
position++;
}
}
}
return retval;
} | DESIGN | true | public DialerCall getCallWithState(int state, int positionToFind) {
DialerCall retval = null;
int position = 0;
for (DialerCall call : callById.values()) {
if (call.getState() == state) {
if (position >= positionToFind) {
retval = call;
break;
} else {
position++;
}
}
}
return retval;
} | public DialerCall getCallWithState(int state, int positionToFind) {
DialerCall retval = null;
int position = 0;
for (DialerCall call : callById.values()) {
if (call.getState() == state) {
if (position >= positionToFind) {
retval = call;
break;
} else {
position++;
}
}
}
return retval;
} | public DialerCall getCallWithState(int state, int positionToFind) {
DialerCall retval = null;
int position = 0;
for (DialerCall call : callById.values()) {
if (call.getState() == state) {
if (position >= positionToFind) {
retval = call;
break;
} else {
position++;
}
}
}
return retval;
} |
26,243 | 0 | //TODO: Better way for run manager to get dependencies so he can be tested. (And better ways of creating his objects) | public RunResult run(RunDecision runDecision) throws DetectUserFriendlyException, InterruptedException, IntegrationException {
//TODO: Better way for run manager to get dependencies so he can be tested. (And better ways of creating his objects)
final DetectConfiguration detectConfiguration = detectContext.getBean(DetectConfiguration.class);
final DetectConfigurationFactory detectConfigurationFactory = detectContext.getBean(DetectConfigurationFactory.class);
final DirectoryManager directoryManager = detectContext.getBean(DirectoryManager.class);
final EventSystem eventSystem = detectContext.getBean(EventSystem.class);
final CodeLocationNameManager codeLocationNameManager = detectContext.getBean(CodeLocationNameManager.class);
final BdioCodeLocationCreator bdioCodeLocationCreator = detectContext.getBean(BdioCodeLocationCreator.class);
final ConnectionManager connectionManager = detectContext.getBean(ConnectionManager.class);
final DetectInfo detectInfo = detectContext.getBean(DetectInfo.class);
final RunResult runResult = new RunResult();
final RunOptions runOptions = detectConfigurationFactory.createRunOptions();
final DetectToolFilter detectToolFilter = runOptions.getDetectToolFilter();
if (runDecision.willRunBlackduck()) {
logger.info("Black Duck tools will run.");
final ConnectivityManager connectivityManager = detectContext.getBean(ConnectivityManager.class);
if (connectivityManager.getPhoneHomeManager().isPresent()) {
connectivityManager.getPhoneHomeManager().get().startPhoneHome();
}
DetectorEnvironment detectorEnvironment = new DetectorEnvironment(directoryManager.getSourceDirectory(), Collections.emptySet(), 0, null, false);
DetectorFactory detectorFactory = detectContext.getBean(DetectorFactory.class);
logger.info(ReportConstants.RUN_SEPARATOR);
if (detectToolFilter.shouldInclude(DetectTool.DOCKER)) {
logger.info("Will include the docker tool.");
ToolRunner toolRunner = new ToolRunner(eventSystem, detectorFactory.createDockerDetector(detectorEnvironment));
toolRunner.run(runResult);
logger.info("Docker actions finished.");
} else {
logger.info("Docker tool will not be run.");
}
logger.info(ReportConstants.RUN_SEPARATOR);
if (detectToolFilter.shouldInclude(DetectTool.BAZEL)) {
logger.info("Will include the bazel tool.");
ToolRunner toolRunner = new ToolRunner(eventSystem, detectorFactory.createBazelDetector(detectorEnvironment));
toolRunner.run(runResult);
logger.info("Bazel actions finished.");
} else {
logger.info("Bazel tool will not be run.");
}
logger.info(ReportConstants.RUN_SEPARATOR);
if (detectToolFilter.shouldInclude(DetectTool.DETECTOR)) {
logger.info("Will include the detector tool.");
final String projectBomTool = detectConfiguration.getProperty(DetectProperty.DETECT_PROJECT_DETECTOR, PropertyAuthority.None);
final SearchOptions searchOptions = detectConfigurationFactory.createSearchOptions(directoryManager.getSourceDirectory());
final DetectorTool detectorTool = new DetectorTool(detectContext);
final DetectorToolResult detectorToolResult = detectorTool.performDetectors(searchOptions, projectBomTool);
runResult.addToolNameVersionIfPresent(DetectTool.DETECTOR, detectorToolResult.bomToolProjectNameVersion);
runResult.addDetectCodeLocations(detectorToolResult.bomToolCodeLocations);
runResult.addApplicableDetectors(detectorToolResult.applicableDetectorTypes);
if (detectorToolResult.failedDetectorTypes.size() > 0) {
eventSystem.publishEvent(Event.ExitCode, new ExitCodeRequest(ExitCodeType.FAILURE_DETECTOR, "A detector failed."));
}
logger.info("Detector actions finished.");
} else {
logger.info("Detector tool will not be run.");
}
logger.info(ReportConstants.RUN_SEPARATOR);
logger.info("Completed code location tools.");
logger.info("Determining project info.");
final ProjectNameVersionOptions projectNameVersionOptions = detectConfigurationFactory.createProjectNameVersionOptions(directoryManager.getSourceDirectory().getName());
final ProjectNameVersionDecider projectNameVersionDecider = new ProjectNameVersionDecider(projectNameVersionOptions);
final NameVersion projectNameVersion = projectNameVersionDecider.decideProjectNameVersion(runOptions.getPreferredTools(), runResult.getDetectToolProjectInfo());
logger.info("Project name: " + projectNameVersion.getName());
logger.info("Project version: " + projectNameVersion.getVersion());
Optional<ProjectVersionWrapper> projectVersionWrapper = Optional.empty();
if (connectivityManager.isDetectOnline() && connectivityManager.getBlackDuckServicesFactory().isPresent()) {
final BlackDuckServicesFactory blackDuckServicesFactory = connectivityManager.getBlackDuckServicesFactory().get();
logger.info("Getting or creating project.");
final DetectProjectServiceOptions options = detectConfigurationFactory.createDetectProjectServiceOptions();
final DetectProjectMappingService detectProjectMappingService = new DetectProjectMappingService(blackDuckServicesFactory.createBlackDuckService());
final DetectProjectService detectProjectService = new DetectProjectService(blackDuckServicesFactory, options, detectProjectMappingService);
projectVersionWrapper = Optional.of(detectProjectService.createOrUpdateHubProject(projectNameVersion, options.getApplicationId()));
if (projectVersionWrapper.isPresent() && runOptions.shouldUnmapCodeLocations()) {
logger.info("Unmapping code locations.");
final DetectCodeLocationUnmapService detectCodeLocationUnmapService = new DetectCodeLocationUnmapService(blackDuckServicesFactory.createBlackDuckService(), blackDuckServicesFactory.createCodeLocationService());
detectCodeLocationUnmapService.unmapCodeLocations(projectVersionWrapper.get().getProjectVersionView());
} else {
logger.debug("Will not unmap code locations: Project view was not present, or should not unmap code locations.");
}
} else {
logger.debug("Detect is not online, and will not create the project.");
}
logger.info("Completed project and version actions.");
logger.info("Processing Detect Code Locations.");
final CodeLocationWaitData codeLocationWaitData = new CodeLocationWaitData();
final BdioManager bdioManager = new BdioManager(detectInfo, new SimpleBdioFactory(), new IntegrationEscapeUtil(), codeLocationNameManager, detectConfiguration, bdioCodeLocationCreator, directoryManager, eventSystem);
final BdioResult bdioResult = bdioManager.createBdioFiles(runOptions.getAggregateName(), projectNameVersion, runResult.getDetectCodeLocations());
if (bdioResult.getUploadTargets().size() > 0) {
logger.info("Created " + bdioResult.getUploadTargets().size() + " BDIO files.");
bdioResult.getUploadTargets().forEach(it -> eventSystem.publishEvent(Event.OutputFileOfInterest, it.getUploadFile()));
if (connectivityManager.isDetectOnline() && connectivityManager.getBlackDuckServicesFactory().isPresent()) {
logger.info("Uploading BDIO files.");
final BlackDuckServicesFactory blackDuckServicesFactory = connectivityManager.getBlackDuckServicesFactory().get();
final DetectBdioUploadService detectBdioUploadService = new DetectBdioUploadService(detectConfiguration, blackDuckServicesFactory.createBdioUploadService(), eventSystem);
final CodeLocationCreationData<UploadBatchOutput> uploadBatchOutputCodeLocationCreationData = detectBdioUploadService.uploadBdioFiles(bdioResult.getUploadTargets());
codeLocationWaitData.setFromBdioCodeLocationCreationData(uploadBatchOutputCodeLocationCreationData);
}
} else {
logger.debug("Did not create any BDIO files.");
}
logger.info("Completed Detect Code Location processing.");
logger.info(ReportConstants.RUN_SEPARATOR);
if (detectToolFilter.shouldInclude(DetectTool.SIGNATURE_SCAN)) {
logger.info("Will include the signature scanner tool.");
final BlackDuckSignatureScannerOptions blackDuckSignatureScannerOptions = detectConfigurationFactory.createBlackDuckSignatureScannerOptions();
final BlackDuckSignatureScannerTool blackDuckSignatureScannerTool = new BlackDuckSignatureScannerTool(blackDuckSignatureScannerOptions, detectContext);
final SignatureScannerToolResult signatureScannerToolResult = blackDuckSignatureScannerTool.runScanTool(projectNameVersion, runResult.getDockerTar());
if (signatureScannerToolResult.getResult() == Result.SUCCESS && signatureScannerToolResult.getCreationData().isPresent()) {
codeLocationWaitData.setFromSignatureScannerCodeLocationCreationData(signatureScannerToolResult.getCreationData().get());
}
logger.info("Signature scanner actions finished.");
} else {
logger.info("Signature scan tool will not be run.");
}
logger.info(ReportConstants.RUN_SEPARATOR);
if (detectToolFilter.shouldInclude(DetectTool.BINARY_SCAN)) {
logger.info("Will include the binary scanner tool.");
if (connectivityManager.isDetectOnline() && connectivityManager.getBlackDuckServicesFactory().isPresent()) {
final BlackDuckServicesFactory blackDuckServicesFactory = connectivityManager.getBlackDuckServicesFactory().get();
final BlackDuckBinaryScannerTool blackDuckBinaryScanner = new BlackDuckBinaryScannerTool(eventSystem, codeLocationNameManager, detectConfiguration, blackDuckServicesFactory);
BinaryScanToolResult result = blackDuckBinaryScanner.performBinaryScanActions(projectNameVersion);
if (result.isSuccessful()) {
codeLocationWaitData.setFromBinaryScan(result.getNotificationTaskRange(), result.getCodeLocationNames());
}
}
logger.info("Binary scanner actions finished.");
} else {
logger.info("Binary scan tool will not be run.");
}
logger.info(ReportConstants.RUN_SEPARATOR);
if (projectVersionWrapper.isPresent() && connectivityManager.isDetectOnline() && connectivityManager.getBlackDuckServicesFactory().isPresent()) {
final BlackDuckServicesFactory blackDuckServicesFactory = connectivityManager.getBlackDuckServicesFactory().get();
logger.info("Will perform Black Duck post actions.");
final BlackduckReportOptions blackduckReportOptions = detectConfigurationFactory.createReportOptions();
final PolicyCheckOptions policyCheckOptions = detectConfigurationFactory.createPolicyCheckOptions();
final long timeoutInSeconds = detectConfigurationFactory.getTimeoutInSeconds();
final BlackduckPostActions blackduckPostActions = new BlackduckPostActions(blackDuckServicesFactory, eventSystem);
blackduckPostActions.perform(blackduckReportOptions, policyCheckOptions, codeLocationWaitData, projectVersionWrapper.get(), timeoutInSeconds);
final boolean hasAtLeastOneBdio = !bdioResult.getUploadTargets().isEmpty();
final boolean shouldHaveScanned = detectToolFilter.shouldInclude(DetectTool.SIGNATURE_SCAN);
if (hasAtLeastOneBdio || shouldHaveScanned) {
final Optional<String> componentsLink = projectVersionWrapper.get().getProjectVersionView().getFirstLink(ProjectVersionView.COMPONENTS_LINK);
if (componentsLink.isPresent()) {
logger.info(String.format("To see your results, follow the URL: %s", componentsLink.get()));
}
}
logger.info("Black Duck actions have finished.");
} else {
logger.debug("Will not perform post actions: Detect is not online.");
}
} else {
logger.info("Black Duck tools will NOT be run.");
}
if (runDecision.willRunPolaris()) {
logger.info(ReportConstants.RUN_SEPARATOR);
if (detectToolFilter.shouldInclude(DetectTool.POLARIS)) {
logger.info("Will include the Polaris tool.");
final PolarisTool polarisTool = new PolarisTool(eventSystem, directoryManager, new ExecutableRunner(), connectionManager, detectConfiguration);
polarisTool.runPolaris(new Slf4jIntLogger(logger), directoryManager.getSourceDirectory());
logger.info("Polaris actions finished.");
} else {
logger.info("Polaris CLI tool will not be run.");
}
} else {
logger.info("Polaris tools will NOT be run.");
}
logger.info("All tools have finished.");
logger.info(ReportConstants.RUN_SEPARATOR);
return runResult;
} | DESIGN | true | public RunResult run(RunDecision runDecision) throws DetectUserFriendlyException, InterruptedException, IntegrationException {
//TODO: Better way for run manager to get dependencies so he can be tested. (And better ways of creating his objects)
final DetectConfiguration detectConfiguration = detectContext.getBean(DetectConfiguration.class);
final DetectConfigurationFactory detectConfigurationFactory = detectContext.getBean(DetectConfigurationFactory.class); | public RunResult run(RunDecision runDecision) throws DetectUserFriendlyException, InterruptedException, IntegrationException {
//TODO: Better way for run manager to get dependencies so he can be tested. (And better ways of creating his objects)
final DetectConfiguration detectConfiguration = detectContext.getBean(DetectConfiguration.class);
final DetectConfigurationFactory detectConfigurationFactory = detectContext.getBean(DetectConfigurationFactory.class);
final DirectoryManager directoryManager = detectContext.getBean(DirectoryManager.class);
final EventSystem eventSystem = detectContext.getBean(EventSystem.class);
final CodeLocationNameManager codeLocationNameManager = detectContext.getBean(CodeLocationNameManager.class);
final BdioCodeLocationCreator bdioCodeLocationCreator = detectContext.getBean(BdioCodeLocationCreator.class);
final ConnectionManager connectionManager = detectContext.getBean(ConnectionManager.class);
final DetectInfo detectInfo = detectContext.getBean(DetectInfo.class);
final RunResult runResult = new RunResult();
final RunOptions runOptions = detectConfigurationFactory.createRunOptions(); | public RunResult run(RunDecision runDecision) throws DetectUserFriendlyException, InterruptedException, IntegrationException {
//TODO: Better way for run manager to get dependencies so he can be tested. (And better ways of creating his objects)
final DetectConfiguration detectConfiguration = detectContext.getBean(DetectConfiguration.class);
final DetectConfigurationFactory detectConfigurationFactory = detectContext.getBean(DetectConfigurationFactory.class);
final DirectoryManager directoryManager = detectContext.getBean(DirectoryManager.class);
final EventSystem eventSystem = detectContext.getBean(EventSystem.class);
final CodeLocationNameManager codeLocationNameManager = detectContext.getBean(CodeLocationNameManager.class);
final BdioCodeLocationCreator bdioCodeLocationCreator = detectContext.getBean(BdioCodeLocationCreator.class);
final ConnectionManager connectionManager = detectContext.getBean(ConnectionManager.class);
final DetectInfo detectInfo = detectContext.getBean(DetectInfo.class);
final RunResult runResult = new RunResult();
final RunOptions runOptions = detectConfigurationFactory.createRunOptions();
final DetectToolFilter detectToolFilter = runOptions.getDetectToolFilter();
if (runDecision.willRunBlackduck()) {
logger.info("Black Duck tools will run.");
final ConnectivityManager connectivityManager = detectContext.getBean(ConnectivityManager.class);
if (connectivityManager.getPhoneHomeManager().isPresent()) {
connectivityManager.getPhoneHomeManager().get().startPhoneHome();
}
DetectorEnvironment detectorEnvironment = new DetectorEnvironment(directoryManager.getSourceDirectory(), Collections.emptySet(), 0, null, false);
DetectorFactory detectorFactory = detectContext.getBean(DetectorFactory.class);
logger.info(ReportConstants.RUN_SEPARATOR); |
26,251 | 0 | /**
* A SetterWriter expression is one of the following
*
* // set:
* // setf:
* // setb:
*
* @param expression
* @return
*/ | public SetterType determineSetterType(String expression) {
// TODO: if (expression.contains("setb")) return SetterType.BUILDER;
if(expression.contains("setf"))
return SetterType.FIELD;
return SetterType.METHOD;
} | NONSATD | true | public SetterType determineSetterType(String expression) {
// TODO: if (expression.contains("setb")) return SetterType.BUILDER;
if(expression.contains("setf"))
return SetterType.FIELD;
return SetterType.METHOD;
} | public SetterType determineSetterType(String expression) {
// TODO: if (expression.contains("setb")) return SetterType.BUILDER;
if(expression.contains("setf"))
return SetterType.FIELD;
return SetterType.METHOD;
} | public SetterType determineSetterType(String expression) {
// TODO: if (expression.contains("setb")) return SetterType.BUILDER;
if(expression.contains("setf"))
return SetterType.FIELD;
return SetterType.METHOD;
} |
26,251 | 1 | // TODO: if (expression.contains("setb")) return SetterType.BUILDER; | public SetterType determineSetterType(String expression) {
// TODO: if (expression.contains("setb")) return SetterType.BUILDER;
if(expression.contains("setf"))
return SetterType.FIELD;
return SetterType.METHOD;
} | IMPLEMENTATION | true | public SetterType determineSetterType(String expression) {
// TODO: if (expression.contains("setb")) return SetterType.BUILDER;
if(expression.contains("setf"))
return SetterType.FIELD; | public SetterType determineSetterType(String expression) {
// TODO: if (expression.contains("setb")) return SetterType.BUILDER;
if(expression.contains("setf"))
return SetterType.FIELD;
return SetterType.METHOD;
} | public SetterType determineSetterType(String expression) {
// TODO: if (expression.contains("setb")) return SetterType.BUILDER;
if(expression.contains("setf"))
return SetterType.FIELD;
return SetterType.METHOD;
} |
26,262 | 0 | // TODO Should be split into different tests for mean, variance, covariance, covariancematrix | @Override
public TestThread<ResourcePoolT, ProtocolBuilderNumeric> next() {
// TODO Should be split into different tests for mean, variance, covariance, covariancematrix
return new TestThread<ResourcePoolT, ProtocolBuilderNumeric>() {
private final List<Integer> data1 = Arrays.asList(543, 520, 532, 497, 450, 432);
private final List<Integer> data2 = Arrays.asList(432, 620, 232, 337, 250, 433);
private final List<Integer> data3 = Arrays.asList(80, 90, 123, 432, 145, 606);
private final List<Integer> dataMean = Arrays.asList(496, 384);
private DRes<BigInteger> outputMean1;
private DRes<BigInteger> outputMean2;
private DRes<BigInteger> outputVariance;
private DRes<BigInteger> outputCovariance;
private List<List<DRes<BigInteger>>> outputCovarianceMatix;
@Override
public void test() throws Exception {
Application<Void, ProtocolBuilderNumeric> app = builder -> {
Numeric NumericBuilder = builder.numeric();
List<DRes<SInt>> input1 = data1.stream().map(BigInteger::valueOf)
.map(NumericBuilder::known).collect(Collectors.toList());
List<DRes<SInt>> input2 = data2.stream().map(BigInteger::valueOf)
.map(NumericBuilder::known).collect(Collectors.toList());
List<DRes<SInt>> input3 = data3.stream().map(BigInteger::valueOf)
.map(NumericBuilder::known).collect(Collectors.toList());
List<DRes<SInt>> means = dataMean.stream().map(BigInteger::valueOf)
.map(NumericBuilder::known).collect(Collectors.toList());
DRes<SInt> mean1 = builder.seq(new Mean(input1));
DRes<SInt> mean2 = builder.seq(new Mean(input2));
DRes<SInt> variance = builder.seq(new Variance(input1, mean1));
DRes<SInt> covariance = builder.seq(new Covariance(input1, input2, mean1, mean2));
DRes<List<List<DRes<SInt>>>> covarianceMatrix =
builder.seq(new CovarianceMatrix(Arrays.asList(input1, input2, input3), means));
return builder.par((par) -> {
Numeric open = par.numeric();
outputMean1 = open.open(mean1);
outputMean2 = open.open(mean2);
outputVariance = open.open(variance);
outputCovariance = open.open(covariance);
List<List<DRes<SInt>>> covarianceMatrixOut = covarianceMatrix.out();
List<List<DRes<BigInteger>>> openCovarianceMatrix =
new ArrayList<>(covarianceMatrixOut.size());
for (List<DRes<SInt>> computations : covarianceMatrixOut) {
List<DRes<BigInteger>> computationList = new ArrayList<>(computations.size());
openCovarianceMatrix.add(computationList);
for (DRes<SInt> computation : computations) {
computationList.add(open.open(computation));
}
}
outputCovarianceMatix = openCovarianceMatrix;
return null;
});
};
runApplication(app);
BigInteger mean1 = outputMean1.out();
BigInteger mean2 = outputMean2.out();
BigInteger variance = outputVariance.out();
BigInteger covariance = outputCovariance.out();
double sum = 0.0;
for (int entry : data1) {
sum += entry;
}
double mean1Exact = sum / data1.size();
sum = 0.0;
for (int entry : data2) {
sum += entry;
}
double mean2Exact = sum / data2.size();
double ssd = 0.0;
for (int entry : data1) {
ssd += (entry - mean1Exact) * (entry - mean1Exact);
}
double varianceExact = ssd / (data1.size() - 1);
double covarianceExact = 0.0;
for (int i = 0; i < data1.size(); i++) {
covarianceExact += (data1.get(i) - mean1Exact) * (data2.get(i) - mean2Exact);
}
covarianceExact /= (data1.size() - 1);
double tolerance = 1.0;
Assert.assertTrue(isInInterval(mean1, mean1Exact, tolerance));
Assert.assertTrue(isInInterval(mean2, mean2Exact, tolerance));
Assert.assertTrue(isInInterval(variance, varianceExact, tolerance));
System.out.println(covariance + " " + covarianceExact + " - " + tolerance);
Assert.assertTrue(isInInterval(covariance, covarianceExact, tolerance));
Assert.assertTrue(
isInInterval(outputCovarianceMatix.get(0).get(0).out(), varianceExact, tolerance));
Assert.assertTrue(
isInInterval(outputCovarianceMatix.get(1).get(0).out(), covarianceExact, tolerance));
}
};
} | TEST | true | @Override
public TestThread<ResourcePoolT, ProtocolBuilderNumeric> next() {
// TODO Should be split into different tests for mean, variance, covariance, covariancematrix
return new TestThread<ResourcePoolT, ProtocolBuilderNumeric>() {
private final List<Integer> data1 = Arrays.asList(543, 520, 532, 497, 450, 432); | @Override
public TestThread<ResourcePoolT, ProtocolBuilderNumeric> next() {
// TODO Should be split into different tests for mean, variance, covariance, covariancematrix
return new TestThread<ResourcePoolT, ProtocolBuilderNumeric>() {
private final List<Integer> data1 = Arrays.asList(543, 520, 532, 497, 450, 432);
private final List<Integer> data2 = Arrays.asList(432, 620, 232, 337, 250, 433);
private final List<Integer> data3 = Arrays.asList(80, 90, 123, 432, 145, 606);
private final List<Integer> dataMean = Arrays.asList(496, 384);
private DRes<BigInteger> outputMean1;
private DRes<BigInteger> outputMean2;
private DRes<BigInteger> outputVariance;
private DRes<BigInteger> outputCovariance;
private List<List<DRes<BigInteger>>> outputCovarianceMatix; | @Override
public TestThread<ResourcePoolT, ProtocolBuilderNumeric> next() {
// TODO Should be split into different tests for mean, variance, covariance, covariancematrix
return new TestThread<ResourcePoolT, ProtocolBuilderNumeric>() {
private final List<Integer> data1 = Arrays.asList(543, 520, 532, 497, 450, 432);
private final List<Integer> data2 = Arrays.asList(432, 620, 232, 337, 250, 433);
private final List<Integer> data3 = Arrays.asList(80, 90, 123, 432, 145, 606);
private final List<Integer> dataMean = Arrays.asList(496, 384);
private DRes<BigInteger> outputMean1;
private DRes<BigInteger> outputMean2;
private DRes<BigInteger> outputVariance;
private DRes<BigInteger> outputCovariance;
private List<List<DRes<BigInteger>>> outputCovarianceMatix;
@Override
public void test() throws Exception {
Application<Void, ProtocolBuilderNumeric> app = builder -> {
Numeric NumericBuilder = builder.numeric();
List<DRes<SInt>> input1 = data1.stream().map(BigInteger::valueOf)
.map(NumericBuilder::known).collect(Collectors.toList());
List<DRes<SInt>> input2 = data2.stream().map(BigInteger::valueOf)
.map(NumericBuilder::known).collect(Collectors.toList());
List<DRes<SInt>> input3 = data3.stream().map(BigInteger::valueOf)
.map(NumericBuilder::known).collect(Collectors.toList()); |
18,082 | 0 | // TODO: translate url? | @Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
String scheme = requestUrl.getScheme();
if (isAlreadyRouted(exchange) || !"forward".equals(scheme)) {
return chain.filter(exchange);
}
// TODO: translate url?
if (log.isTraceEnabled()) {
log.trace("Forwarding to URI: " + requestUrl);
}
/**
* 匹配并转发到当前网关实例本地接口。
* 注意:需要通过 PrefixPathGatewayFilterFactory 将请求重写路径,以匹配本地 API ,否则 DispatcherHandler 转发会失败。
*/
return this.getDispatcherHandler().handle(exchange);
} | IMPLEMENTATION | true | return chain.filter(exchange);
}
// TODO: translate url?
if (log.isTraceEnabled()) {
log.trace("Forwarding to URI: " + requestUrl); | @Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
String scheme = requestUrl.getScheme();
if (isAlreadyRouted(exchange) || !"forward".equals(scheme)) {
return chain.filter(exchange);
}
// TODO: translate url?
if (log.isTraceEnabled()) {
log.trace("Forwarding to URI: " + requestUrl);
}
/**
* 匹配并转发到当前网关实例本地接口。
* 注意:需要通过 PrefixPathGatewayFilterFactory 将请求重写路径,以匹配本地 API ,否则 DispatcherHandler 转发会失败。
*/
return this.getDispatcherHandler().handle(exchange);
} | @Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
String scheme = requestUrl.getScheme();
if (isAlreadyRouted(exchange) || !"forward".equals(scheme)) {
return chain.filter(exchange);
}
// TODO: translate url?
if (log.isTraceEnabled()) {
log.trace("Forwarding to URI: " + requestUrl);
}
/**
* 匹配并转发到当前网关实例本地接口。
* 注意:需要通过 PrefixPathGatewayFilterFactory 将请求重写路径,以匹配本地 API ,否则 DispatcherHandler 转发会失败。
*/
return this.getDispatcherHandler().handle(exchange);
} |
18,082 | 1 | /**
* 匹配并转发到当前网关实例本地接口。
* 注意:需要通过 PrefixPathGatewayFilterFactory 将请求重写路径,以匹配本地 API ,否则 DispatcherHandler 转发会失败。
*/ | @Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
String scheme = requestUrl.getScheme();
if (isAlreadyRouted(exchange) || !"forward".equals(scheme)) {
return chain.filter(exchange);
}
// TODO: translate url?
if (log.isTraceEnabled()) {
log.trace("Forwarding to URI: " + requestUrl);
}
/**
* 匹配并转发到当前网关实例本地接口。
* 注意:需要通过 PrefixPathGatewayFilterFactory 将请求重写路径,以匹配本地 API ,否则 DispatcherHandler 转发会失败。
*/
return this.getDispatcherHandler().handle(exchange);
} | NONSATD | true | log.trace("Forwarding to URI: " + requestUrl);
}
/**
* 匹配并转发到当前网关实例本地接口。
* 注意:需要通过 PrefixPathGatewayFilterFactory 将请求重写路径,以匹配本地 API ,否则 DispatcherHandler 转发会失败。
*/
return this.getDispatcherHandler().handle(exchange);
} | public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
String scheme = requestUrl.getScheme();
if (isAlreadyRouted(exchange) || !"forward".equals(scheme)) {
return chain.filter(exchange);
}
// TODO: translate url?
if (log.isTraceEnabled()) {
log.trace("Forwarding to URI: " + requestUrl);
}
/**
* 匹配并转发到当前网关实例本地接口。
* 注意:需要通过 PrefixPathGatewayFilterFactory 将请求重写路径,以匹配本地 API ,否则 DispatcherHandler 转发会失败。
*/
return this.getDispatcherHandler().handle(exchange);
} | @Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
String scheme = requestUrl.getScheme();
if (isAlreadyRouted(exchange) || !"forward".equals(scheme)) {
return chain.filter(exchange);
}
// TODO: translate url?
if (log.isTraceEnabled()) {
log.trace("Forwarding to URI: " + requestUrl);
}
/**
* 匹配并转发到当前网关实例本地接口。
* 注意:需要通过 PrefixPathGatewayFilterFactory 将请求重写路径,以匹配本地 API ,否则 DispatcherHandler 转发会失败。
*/
return this.getDispatcherHandler().handle(exchange);
} |
18,084 | 0 | /**
* Continuously attempts to connect for at least the indicated amount of time; or indefinitely if -1. This method
* is useful when you are not sure if the system you are trying to connect to already is up and running.
*
* This method doesn't throw an Exception, but returns true on success, false otherwise.
*
* TODO: What happens if already connected?
*
* @param timeoutMs
* @return
*/ | public boolean connect(long timeoutMs) {
if (LOG.isDebugEnabled()) LOG.debug("Connecting to JMX URL: {} ({})", url, ((timeoutMs == -1) ? "indefinitely" : timeoutMs+"ms timeout"));
long startMs = System.currentTimeMillis();
long endMs = (timeoutMs == -1) ? Long.MAX_VALUE : (startMs + timeoutMs);
long currentTime = startMs;
Throwable lastError = null;
int attempt = 0;
while (currentTime <= endMs) {
currentTime = System.currentTimeMillis();
if (attempt != 0) sleep(100); //sleep 100 to prevent thrashing and facilitate interruption
if (LOG.isTraceEnabled()) LOG.trace("trying connection to {} at time {}", url, currentTime);
try {
connect();
return true;
} catch (Exception e) {
Exceptions.propagateIfFatal(e);
if (!terminated.get() && shouldRetryOn(e)) {
if (LOG.isDebugEnabled()) LOG.debug("Attempt {} failed connecting to {} ({})", new Object[] {attempt + 1, url, e.getMessage()});
lastError = e;
} else {
throw Exceptions.propagate(e);
}
}
attempt++;
}
LOG.warn("unable to connect to JMX url: "+url, lastError);
return false;
} | DESIGN | true | public boolean connect(long timeoutMs) {
if (LOG.isDebugEnabled()) LOG.debug("Connecting to JMX URL: {} ({})", url, ((timeoutMs == -1) ? "indefinitely" : timeoutMs+"ms timeout"));
long startMs = System.currentTimeMillis();
long endMs = (timeoutMs == -1) ? Long.MAX_VALUE : (startMs + timeoutMs);
long currentTime = startMs;
Throwable lastError = null;
int attempt = 0;
while (currentTime <= endMs) {
currentTime = System.currentTimeMillis();
if (attempt != 0) sleep(100); //sleep 100 to prevent thrashing and facilitate interruption
if (LOG.isTraceEnabled()) LOG.trace("trying connection to {} at time {}", url, currentTime);
try {
connect();
return true;
} catch (Exception e) {
Exceptions.propagateIfFatal(e);
if (!terminated.get() && shouldRetryOn(e)) {
if (LOG.isDebugEnabled()) LOG.debug("Attempt {} failed connecting to {} ({})", new Object[] {attempt + 1, url, e.getMessage()});
lastError = e;
} else {
throw Exceptions.propagate(e);
}
}
attempt++;
}
LOG.warn("unable to connect to JMX url: "+url, lastError);
return false;
} | public boolean connect(long timeoutMs) {
if (LOG.isDebugEnabled()) LOG.debug("Connecting to JMX URL: {} ({})", url, ((timeoutMs == -1) ? "indefinitely" : timeoutMs+"ms timeout"));
long startMs = System.currentTimeMillis();
long endMs = (timeoutMs == -1) ? Long.MAX_VALUE : (startMs + timeoutMs);
long currentTime = startMs;
Throwable lastError = null;
int attempt = 0;
while (currentTime <= endMs) {
currentTime = System.currentTimeMillis();
if (attempt != 0) sleep(100); //sleep 100 to prevent thrashing and facilitate interruption
if (LOG.isTraceEnabled()) LOG.trace("trying connection to {} at time {}", url, currentTime);
try {
connect();
return true;
} catch (Exception e) {
Exceptions.propagateIfFatal(e);
if (!terminated.get() && shouldRetryOn(e)) {
if (LOG.isDebugEnabled()) LOG.debug("Attempt {} failed connecting to {} ({})", new Object[] {attempt + 1, url, e.getMessage()});
lastError = e;
} else {
throw Exceptions.propagate(e);
}
}
attempt++;
}
LOG.warn("unable to connect to JMX url: "+url, lastError);
return false;
} | public boolean connect(long timeoutMs) {
if (LOG.isDebugEnabled()) LOG.debug("Connecting to JMX URL: {} ({})", url, ((timeoutMs == -1) ? "indefinitely" : timeoutMs+"ms timeout"));
long startMs = System.currentTimeMillis();
long endMs = (timeoutMs == -1) ? Long.MAX_VALUE : (startMs + timeoutMs);
long currentTime = startMs;
Throwable lastError = null;
int attempt = 0;
while (currentTime <= endMs) {
currentTime = System.currentTimeMillis();
if (attempt != 0) sleep(100); //sleep 100 to prevent thrashing and facilitate interruption
if (LOG.isTraceEnabled()) LOG.trace("trying connection to {} at time {}", url, currentTime);
try {
connect();
return true;
} catch (Exception e) {
Exceptions.propagateIfFatal(e);
if (!terminated.get() && shouldRetryOn(e)) {
if (LOG.isDebugEnabled()) LOG.debug("Attempt {} failed connecting to {} ({})", new Object[] {attempt + 1, url, e.getMessage()});
lastError = e;
} else {
throw Exceptions.propagate(e);
}
}
attempt++;
}
LOG.warn("unable to connect to JMX url: "+url, lastError);
return false;
} |
18,084 | 1 | //sleep 100 to prevent thrashing and facilitate interruption | public boolean connect(long timeoutMs) {
if (LOG.isDebugEnabled()) LOG.debug("Connecting to JMX URL: {} ({})", url, ((timeoutMs == -1) ? "indefinitely" : timeoutMs+"ms timeout"));
long startMs = System.currentTimeMillis();
long endMs = (timeoutMs == -1) ? Long.MAX_VALUE : (startMs + timeoutMs);
long currentTime = startMs;
Throwable lastError = null;
int attempt = 0;
while (currentTime <= endMs) {
currentTime = System.currentTimeMillis();
if (attempt != 0) sleep(100); //sleep 100 to prevent thrashing and facilitate interruption
if (LOG.isTraceEnabled()) LOG.trace("trying connection to {} at time {}", url, currentTime);
try {
connect();
return true;
} catch (Exception e) {
Exceptions.propagateIfFatal(e);
if (!terminated.get() && shouldRetryOn(e)) {
if (LOG.isDebugEnabled()) LOG.debug("Attempt {} failed connecting to {} ({})", new Object[] {attempt + 1, url, e.getMessage()});
lastError = e;
} else {
throw Exceptions.propagate(e);
}
}
attempt++;
}
LOG.warn("unable to connect to JMX url: "+url, lastError);
return false;
} | NONSATD | true | while (currentTime <= endMs) {
currentTime = System.currentTimeMillis();
if (attempt != 0) sleep(100); //sleep 100 to prevent thrashing and facilitate interruption
if (LOG.isTraceEnabled()) LOG.trace("trying connection to {} at time {}", url, currentTime);
try { | public boolean connect(long timeoutMs) {
if (LOG.isDebugEnabled()) LOG.debug("Connecting to JMX URL: {} ({})", url, ((timeoutMs == -1) ? "indefinitely" : timeoutMs+"ms timeout"));
long startMs = System.currentTimeMillis();
long endMs = (timeoutMs == -1) ? Long.MAX_VALUE : (startMs + timeoutMs);
long currentTime = startMs;
Throwable lastError = null;
int attempt = 0;
while (currentTime <= endMs) {
currentTime = System.currentTimeMillis();
if (attempt != 0) sleep(100); //sleep 100 to prevent thrashing and facilitate interruption
if (LOG.isTraceEnabled()) LOG.trace("trying connection to {} at time {}", url, currentTime);
try {
connect();
return true;
} catch (Exception e) {
Exceptions.propagateIfFatal(e);
if (!terminated.get() && shouldRetryOn(e)) {
if (LOG.isDebugEnabled()) LOG.debug("Attempt {} failed connecting to {} ({})", new Object[] {attempt + 1, url, e.getMessage()});
lastError = e;
} else { | public boolean connect(long timeoutMs) {
if (LOG.isDebugEnabled()) LOG.debug("Connecting to JMX URL: {} ({})", url, ((timeoutMs == -1) ? "indefinitely" : timeoutMs+"ms timeout"));
long startMs = System.currentTimeMillis();
long endMs = (timeoutMs == -1) ? Long.MAX_VALUE : (startMs + timeoutMs);
long currentTime = startMs;
Throwable lastError = null;
int attempt = 0;
while (currentTime <= endMs) {
currentTime = System.currentTimeMillis();
if (attempt != 0) sleep(100); //sleep 100 to prevent thrashing and facilitate interruption
if (LOG.isTraceEnabled()) LOG.trace("trying connection to {} at time {}", url, currentTime);
try {
connect();
return true;
} catch (Exception e) {
Exceptions.propagateIfFatal(e);
if (!terminated.get() && shouldRetryOn(e)) {
if (LOG.isDebugEnabled()) LOG.debug("Attempt {} failed connecting to {} ({})", new Object[] {attempt + 1, url, e.getMessage()});
lastError = e;
} else {
throw Exceptions.propagate(e);
}
}
attempt++;
}
LOG.warn("unable to connect to JMX url: "+url, lastError);
return false;
} |
1,701 | 0 | //TODO: Replace this with your own logic | public static boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
} | DESIGN | true | public static boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
} | public static boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
} | public static boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
} |
18,096 | 0 | // TODO: See if we are going to use this. | @SuppressWarnings("unchecked")
public static void SetPageFacet(int facetType, String facetName, long delay) {
FacesContext context = FacesContext.getCurrentInstance();
Map viewScope = context.getViewRoot().getViewMap();
String previousFacet = "";
String selectedFacet = "";
try {
switch (facetType) {
case 1:// Login
previousFacet = "previousLoginFacet";
selectedFacet = "selectedLoginFacet";
break;
case 2:// Home
previousFacet = "previousHomeFacet";
selectedFacet = "selectedHomeFacet";
break;
case 3:// FormPlaceholderFacet
previousFacet = "previousFormPlaceholderFacet";
selectedFacet = "selectedFormPlaceholderFacet";
break;
}
if (facetName.equals("Previous")) {
SetPageFacet(facetType, viewScope.get(previousFacet).toString(), delay);
} else if (!facetName.equals(viewScope.get(selectedFacet))) {
if (delay > 0) {
Thread.currentThread();
Thread.sleep(delay);
}
viewScope.put(previousFacet, viewScope.get(selectedFacet));
viewScope.put(selectedFacet, facetName);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} | DESIGN | true | @SuppressWarnings("unchecked")
public static void SetPageFacet(int facetType, String facetName, long delay) {
FacesContext context = FacesContext.getCurrentInstance();
Map viewScope = context.getViewRoot().getViewMap();
String previousFacet = "";
String selectedFacet = "";
try {
switch (facetType) {
case 1:// Login
previousFacet = "previousLoginFacet";
selectedFacet = "selectedLoginFacet";
break;
case 2:// Home
previousFacet = "previousHomeFacet";
selectedFacet = "selectedHomeFacet";
break;
case 3:// FormPlaceholderFacet
previousFacet = "previousFormPlaceholderFacet";
selectedFacet = "selectedFormPlaceholderFacet";
break;
}
if (facetName.equals("Previous")) {
SetPageFacet(facetType, viewScope.get(previousFacet).toString(), delay);
} else if (!facetName.equals(viewScope.get(selectedFacet))) {
if (delay > 0) {
Thread.currentThread();
Thread.sleep(delay);
}
viewScope.put(previousFacet, viewScope.get(selectedFacet));
viewScope.put(selectedFacet, facetName);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} | @SuppressWarnings("unchecked")
public static void SetPageFacet(int facetType, String facetName, long delay) {
FacesContext context = FacesContext.getCurrentInstance();
Map viewScope = context.getViewRoot().getViewMap();
String previousFacet = "";
String selectedFacet = "";
try {
switch (facetType) {
case 1:// Login
previousFacet = "previousLoginFacet";
selectedFacet = "selectedLoginFacet";
break;
case 2:// Home
previousFacet = "previousHomeFacet";
selectedFacet = "selectedHomeFacet";
break;
case 3:// FormPlaceholderFacet
previousFacet = "previousFormPlaceholderFacet";
selectedFacet = "selectedFormPlaceholderFacet";
break;
}
if (facetName.equals("Previous")) {
SetPageFacet(facetType, viewScope.get(previousFacet).toString(), delay);
} else if (!facetName.equals(viewScope.get(selectedFacet))) {
if (delay > 0) {
Thread.currentThread();
Thread.sleep(delay);
}
viewScope.put(previousFacet, viewScope.get(selectedFacet));
viewScope.put(selectedFacet, facetName);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} | @SuppressWarnings("unchecked")
public static void SetPageFacet(int facetType, String facetName, long delay) {
FacesContext context = FacesContext.getCurrentInstance();
Map viewScope = context.getViewRoot().getViewMap();
String previousFacet = "";
String selectedFacet = "";
try {
switch (facetType) {
case 1:// Login
previousFacet = "previousLoginFacet";
selectedFacet = "selectedLoginFacet";
break;
case 2:// Home
previousFacet = "previousHomeFacet";
selectedFacet = "selectedHomeFacet";
break;
case 3:// FormPlaceholderFacet
previousFacet = "previousFormPlaceholderFacet";
selectedFacet = "selectedFormPlaceholderFacet";
break;
}
if (facetName.equals("Previous")) {
SetPageFacet(facetType, viewScope.get(previousFacet).toString(), delay);
} else if (!facetName.equals(viewScope.get(selectedFacet))) {
if (delay > 0) {
Thread.currentThread();
Thread.sleep(delay);
}
viewScope.put(previousFacet, viewScope.get(selectedFacet));
viewScope.put(selectedFacet, facetName);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} |
18,096 | 1 | // Login | @SuppressWarnings("unchecked")
public static void SetPageFacet(int facetType, String facetName, long delay) {
FacesContext context = FacesContext.getCurrentInstance();
Map viewScope = context.getViewRoot().getViewMap();
String previousFacet = "";
String selectedFacet = "";
try {
switch (facetType) {
case 1:// Login
previousFacet = "previousLoginFacet";
selectedFacet = "selectedLoginFacet";
break;
case 2:// Home
previousFacet = "previousHomeFacet";
selectedFacet = "selectedHomeFacet";
break;
case 3:// FormPlaceholderFacet
previousFacet = "previousFormPlaceholderFacet";
selectedFacet = "selectedFormPlaceholderFacet";
break;
}
if (facetName.equals("Previous")) {
SetPageFacet(facetType, viewScope.get(previousFacet).toString(), delay);
} else if (!facetName.equals(viewScope.get(selectedFacet))) {
if (delay > 0) {
Thread.currentThread();
Thread.sleep(delay);
}
viewScope.put(previousFacet, viewScope.get(selectedFacet));
viewScope.put(selectedFacet, facetName);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} | NONSATD | true | try {
switch (facetType) {
case 1:// Login
previousFacet = "previousLoginFacet";
selectedFacet = "selectedLoginFacet"; | @SuppressWarnings("unchecked")
public static void SetPageFacet(int facetType, String facetName, long delay) {
FacesContext context = FacesContext.getCurrentInstance();
Map viewScope = context.getViewRoot().getViewMap();
String previousFacet = "";
String selectedFacet = "";
try {
switch (facetType) {
case 1:// Login
previousFacet = "previousLoginFacet";
selectedFacet = "selectedLoginFacet";
break;
case 2:// Home
previousFacet = "previousHomeFacet";
selectedFacet = "selectedHomeFacet";
break;
case 3:// FormPlaceholderFacet
previousFacet = "previousFormPlaceholderFacet";
selectedFacet = "selectedFormPlaceholderFacet"; | @SuppressWarnings("unchecked")
public static void SetPageFacet(int facetType, String facetName, long delay) {
FacesContext context = FacesContext.getCurrentInstance();
Map viewScope = context.getViewRoot().getViewMap();
String previousFacet = "";
String selectedFacet = "";
try {
switch (facetType) {
case 1:// Login
previousFacet = "previousLoginFacet";
selectedFacet = "selectedLoginFacet";
break;
case 2:// Home
previousFacet = "previousHomeFacet";
selectedFacet = "selectedHomeFacet";
break;
case 3:// FormPlaceholderFacet
previousFacet = "previousFormPlaceholderFacet";
selectedFacet = "selectedFormPlaceholderFacet";
break;
}
if (facetName.equals("Previous")) {
SetPageFacet(facetType, viewScope.get(previousFacet).toString(), delay);
} else if (!facetName.equals(viewScope.get(selectedFacet))) {
if (delay > 0) {
Thread.currentThread();
Thread.sleep(delay);
}
viewScope.put(previousFacet, viewScope.get(selectedFacet)); |
18,096 | 2 | // Home | @SuppressWarnings("unchecked")
public static void SetPageFacet(int facetType, String facetName, long delay) {
FacesContext context = FacesContext.getCurrentInstance();
Map viewScope = context.getViewRoot().getViewMap();
String previousFacet = "";
String selectedFacet = "";
try {
switch (facetType) {
case 1:// Login
previousFacet = "previousLoginFacet";
selectedFacet = "selectedLoginFacet";
break;
case 2:// Home
previousFacet = "previousHomeFacet";
selectedFacet = "selectedHomeFacet";
break;
case 3:// FormPlaceholderFacet
previousFacet = "previousFormPlaceholderFacet";
selectedFacet = "selectedFormPlaceholderFacet";
break;
}
if (facetName.equals("Previous")) {
SetPageFacet(facetType, viewScope.get(previousFacet).toString(), delay);
} else if (!facetName.equals(viewScope.get(selectedFacet))) {
if (delay > 0) {
Thread.currentThread();
Thread.sleep(delay);
}
viewScope.put(previousFacet, viewScope.get(selectedFacet));
viewScope.put(selectedFacet, facetName);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} | NONSATD | true | selectedFacet = "selectedLoginFacet";
break;
case 2:// Home
previousFacet = "previousHomeFacet";
selectedFacet = "selectedHomeFacet"; | FacesContext context = FacesContext.getCurrentInstance();
Map viewScope = context.getViewRoot().getViewMap();
String previousFacet = "";
String selectedFacet = "";
try {
switch (facetType) {
case 1:// Login
previousFacet = "previousLoginFacet";
selectedFacet = "selectedLoginFacet";
break;
case 2:// Home
previousFacet = "previousHomeFacet";
selectedFacet = "selectedHomeFacet";
break;
case 3:// FormPlaceholderFacet
previousFacet = "previousFormPlaceholderFacet";
selectedFacet = "selectedFormPlaceholderFacet";
break;
}
if (facetName.equals("Previous")) {
SetPageFacet(facetType, viewScope.get(previousFacet).toString(), delay); | @SuppressWarnings("unchecked")
public static void SetPageFacet(int facetType, String facetName, long delay) {
FacesContext context = FacesContext.getCurrentInstance();
Map viewScope = context.getViewRoot().getViewMap();
String previousFacet = "";
String selectedFacet = "";
try {
switch (facetType) {
case 1:// Login
previousFacet = "previousLoginFacet";
selectedFacet = "selectedLoginFacet";
break;
case 2:// Home
previousFacet = "previousHomeFacet";
selectedFacet = "selectedHomeFacet";
break;
case 3:// FormPlaceholderFacet
previousFacet = "previousFormPlaceholderFacet";
selectedFacet = "selectedFormPlaceholderFacet";
break;
}
if (facetName.equals("Previous")) {
SetPageFacet(facetType, viewScope.get(previousFacet).toString(), delay);
} else if (!facetName.equals(viewScope.get(selectedFacet))) {
if (delay > 0) {
Thread.currentThread();
Thread.sleep(delay);
}
viewScope.put(previousFacet, viewScope.get(selectedFacet));
viewScope.put(selectedFacet, facetName);
}
} catch (InterruptedException e) {
e.printStackTrace(); |
18,096 | 3 | // FormPlaceholderFacet | @SuppressWarnings("unchecked")
public static void SetPageFacet(int facetType, String facetName, long delay) {
FacesContext context = FacesContext.getCurrentInstance();
Map viewScope = context.getViewRoot().getViewMap();
String previousFacet = "";
String selectedFacet = "";
try {
switch (facetType) {
case 1:// Login
previousFacet = "previousLoginFacet";
selectedFacet = "selectedLoginFacet";
break;
case 2:// Home
previousFacet = "previousHomeFacet";
selectedFacet = "selectedHomeFacet";
break;
case 3:// FormPlaceholderFacet
previousFacet = "previousFormPlaceholderFacet";
selectedFacet = "selectedFormPlaceholderFacet";
break;
}
if (facetName.equals("Previous")) {
SetPageFacet(facetType, viewScope.get(previousFacet).toString(), delay);
} else if (!facetName.equals(viewScope.get(selectedFacet))) {
if (delay > 0) {
Thread.currentThread();
Thread.sleep(delay);
}
viewScope.put(previousFacet, viewScope.get(selectedFacet));
viewScope.put(selectedFacet, facetName);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} | NONSATD | true | selectedFacet = "selectedHomeFacet";
break;
case 3:// FormPlaceholderFacet
previousFacet = "previousFormPlaceholderFacet";
selectedFacet = "selectedFormPlaceholderFacet"; | try {
switch (facetType) {
case 1:// Login
previousFacet = "previousLoginFacet";
selectedFacet = "selectedLoginFacet";
break;
case 2:// Home
previousFacet = "previousHomeFacet";
selectedFacet = "selectedHomeFacet";
break;
case 3:// FormPlaceholderFacet
previousFacet = "previousFormPlaceholderFacet";
selectedFacet = "selectedFormPlaceholderFacet";
break;
}
if (facetName.equals("Previous")) {
SetPageFacet(facetType, viewScope.get(previousFacet).toString(), delay);
} else if (!facetName.equals(viewScope.get(selectedFacet))) {
if (delay > 0) {
Thread.currentThread();
Thread.sleep(delay); | @SuppressWarnings("unchecked")
public static void SetPageFacet(int facetType, String facetName, long delay) {
FacesContext context = FacesContext.getCurrentInstance();
Map viewScope = context.getViewRoot().getViewMap();
String previousFacet = "";
String selectedFacet = "";
try {
switch (facetType) {
case 1:// Login
previousFacet = "previousLoginFacet";
selectedFacet = "selectedLoginFacet";
break;
case 2:// Home
previousFacet = "previousHomeFacet";
selectedFacet = "selectedHomeFacet";
break;
case 3:// FormPlaceholderFacet
previousFacet = "previousFormPlaceholderFacet";
selectedFacet = "selectedFormPlaceholderFacet";
break;
}
if (facetName.equals("Previous")) {
SetPageFacet(facetType, viewScope.get(previousFacet).toString(), delay);
} else if (!facetName.equals(viewScope.get(selectedFacet))) {
if (delay > 0) {
Thread.currentThread();
Thread.sleep(delay);
}
viewScope.put(previousFacet, viewScope.get(selectedFacet));
viewScope.put(selectedFacet, facetName);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} |
9,907 | 0 | // Quicktime: | public static List<String> contentPrefixList(int flags)
{
final List<String> contentPrefixList = new ArrayList<String>();
if ((flags & JMF) != 0) {
contentPrefixList.add("javax");
contentPrefixList.add("com.sun");
contentPrefixList.add("com.ibm");
}
if ((flags & FMJ_NATIVE) != 0) {
if (OSUtils.isMacOSX() || OSUtils.isWindows()) {
// Quicktime:
contentPrefixList.add("net.sf.fmj.qt");
}
if (OSUtils.isWindows()) {
// DirectShow:
contentPrefixList.add("net.sf.fmj.ds");
}
if (ENABLE_GSTREAMER && OSUtils.isLinux()) {
// TODO: we could add these for other OS's, as gstreamer is cross-platform.
// DirectShow:
contentPrefixList.add("net.sf.fmj.gst");
}
}
if ((flags & FMJ) != 0) {
contentPrefixList.add("net.sf.fmj");
}
if ((flags & THIRD_PARTY) != 0) {
// none to add
}
return contentPrefixList;
} | NONSATD | true | if ((flags & FMJ_NATIVE) != 0) {
if (OSUtils.isMacOSX() || OSUtils.isWindows()) {
// Quicktime:
contentPrefixList.add("net.sf.fmj.qt");
} | public static List<String> contentPrefixList(int flags)
{
final List<String> contentPrefixList = new ArrayList<String>();
if ((flags & JMF) != 0) {
contentPrefixList.add("javax");
contentPrefixList.add("com.sun");
contentPrefixList.add("com.ibm");
}
if ((flags & FMJ_NATIVE) != 0) {
if (OSUtils.isMacOSX() || OSUtils.isWindows()) {
// Quicktime:
contentPrefixList.add("net.sf.fmj.qt");
}
if (OSUtils.isWindows()) {
// DirectShow:
contentPrefixList.add("net.sf.fmj.ds");
}
if (ENABLE_GSTREAMER && OSUtils.isLinux()) {
// TODO: we could add these for other OS's, as gstreamer is cross-platform.
// DirectShow:
contentPrefixList.add("net.sf.fmj.gst"); | public static List<String> contentPrefixList(int flags)
{
final List<String> contentPrefixList = new ArrayList<String>();
if ((flags & JMF) != 0) {
contentPrefixList.add("javax");
contentPrefixList.add("com.sun");
contentPrefixList.add("com.ibm");
}
if ((flags & FMJ_NATIVE) != 0) {
if (OSUtils.isMacOSX() || OSUtils.isWindows()) {
// Quicktime:
contentPrefixList.add("net.sf.fmj.qt");
}
if (OSUtils.isWindows()) {
// DirectShow:
contentPrefixList.add("net.sf.fmj.ds");
}
if (ENABLE_GSTREAMER && OSUtils.isLinux()) {
// TODO: we could add these for other OS's, as gstreamer is cross-platform.
// DirectShow:
contentPrefixList.add("net.sf.fmj.gst");
}
}
if ((flags & FMJ) != 0) {
contentPrefixList.add("net.sf.fmj");
}
if ((flags & THIRD_PARTY) != 0) {
// none to add
}
return contentPrefixList;
} |
9,907 | 1 | // DirectShow: | public static List<String> contentPrefixList(int flags)
{
final List<String> contentPrefixList = new ArrayList<String>();
if ((flags & JMF) != 0) {
contentPrefixList.add("javax");
contentPrefixList.add("com.sun");
contentPrefixList.add("com.ibm");
}
if ((flags & FMJ_NATIVE) != 0) {
if (OSUtils.isMacOSX() || OSUtils.isWindows()) {
// Quicktime:
contentPrefixList.add("net.sf.fmj.qt");
}
if (OSUtils.isWindows()) {
// DirectShow:
contentPrefixList.add("net.sf.fmj.ds");
}
if (ENABLE_GSTREAMER && OSUtils.isLinux()) {
// TODO: we could add these for other OS's, as gstreamer is cross-platform.
// DirectShow:
contentPrefixList.add("net.sf.fmj.gst");
}
}
if ((flags & FMJ) != 0) {
contentPrefixList.add("net.sf.fmj");
}
if ((flags & THIRD_PARTY) != 0) {
// none to add
}
return contentPrefixList;
} | NONSATD | true | }
if (OSUtils.isWindows()) {
// DirectShow:
contentPrefixList.add("net.sf.fmj.ds");
} | contentPrefixList.add("javax");
contentPrefixList.add("com.sun");
contentPrefixList.add("com.ibm");
}
if ((flags & FMJ_NATIVE) != 0) {
if (OSUtils.isMacOSX() || OSUtils.isWindows()) {
// Quicktime:
contentPrefixList.add("net.sf.fmj.qt");
}
if (OSUtils.isWindows()) {
// DirectShow:
contentPrefixList.add("net.sf.fmj.ds");
}
if (ENABLE_GSTREAMER && OSUtils.isLinux()) {
// TODO: we could add these for other OS's, as gstreamer is cross-platform.
// DirectShow:
contentPrefixList.add("net.sf.fmj.gst");
}
}
if ((flags & FMJ) != 0) {
contentPrefixList.add("net.sf.fmj"); | public static List<String> contentPrefixList(int flags)
{
final List<String> contentPrefixList = new ArrayList<String>();
if ((flags & JMF) != 0) {
contentPrefixList.add("javax");
contentPrefixList.add("com.sun");
contentPrefixList.add("com.ibm");
}
if ((flags & FMJ_NATIVE) != 0) {
if (OSUtils.isMacOSX() || OSUtils.isWindows()) {
// Quicktime:
contentPrefixList.add("net.sf.fmj.qt");
}
if (OSUtils.isWindows()) {
// DirectShow:
contentPrefixList.add("net.sf.fmj.ds");
}
if (ENABLE_GSTREAMER && OSUtils.isLinux()) {
// TODO: we could add these for other OS's, as gstreamer is cross-platform.
// DirectShow:
contentPrefixList.add("net.sf.fmj.gst");
}
}
if ((flags & FMJ) != 0) {
contentPrefixList.add("net.sf.fmj");
}
if ((flags & THIRD_PARTY) != 0) {
// none to add
}
return contentPrefixList;
} |
9,907 | 2 | // TODO: we could add these for other OS's, as gstreamer is cross-platform.
// DirectShow: | public static List<String> contentPrefixList(int flags)
{
final List<String> contentPrefixList = new ArrayList<String>();
if ((flags & JMF) != 0) {
contentPrefixList.add("javax");
contentPrefixList.add("com.sun");
contentPrefixList.add("com.ibm");
}
if ((flags & FMJ_NATIVE) != 0) {
if (OSUtils.isMacOSX() || OSUtils.isWindows()) {
// Quicktime:
contentPrefixList.add("net.sf.fmj.qt");
}
if (OSUtils.isWindows()) {
// DirectShow:
contentPrefixList.add("net.sf.fmj.ds");
}
if (ENABLE_GSTREAMER && OSUtils.isLinux()) {
// TODO: we could add these for other OS's, as gstreamer is cross-platform.
// DirectShow:
contentPrefixList.add("net.sf.fmj.gst");
}
}
if ((flags & FMJ) != 0) {
contentPrefixList.add("net.sf.fmj");
}
if ((flags & THIRD_PARTY) != 0) {
// none to add
}
return contentPrefixList;
} | IMPLEMENTATION | true | }
if (ENABLE_GSTREAMER && OSUtils.isLinux()) {
// TODO: we could add these for other OS's, as gstreamer is cross-platform.
// DirectShow:
contentPrefixList.add("net.sf.fmj.gst");
} | if ((flags & FMJ_NATIVE) != 0) {
if (OSUtils.isMacOSX() || OSUtils.isWindows()) {
// Quicktime:
contentPrefixList.add("net.sf.fmj.qt");
}
if (OSUtils.isWindows()) {
// DirectShow:
contentPrefixList.add("net.sf.fmj.ds");
}
if (ENABLE_GSTREAMER && OSUtils.isLinux()) {
// TODO: we could add these for other OS's, as gstreamer is cross-platform.
// DirectShow:
contentPrefixList.add("net.sf.fmj.gst");
}
}
if ((flags & FMJ) != 0) {
contentPrefixList.add("net.sf.fmj");
}
if ((flags & THIRD_PARTY) != 0) {
// none to add
}
return contentPrefixList; | public static List<String> contentPrefixList(int flags)
{
final List<String> contentPrefixList = new ArrayList<String>();
if ((flags & JMF) != 0) {
contentPrefixList.add("javax");
contentPrefixList.add("com.sun");
contentPrefixList.add("com.ibm");
}
if ((flags & FMJ_NATIVE) != 0) {
if (OSUtils.isMacOSX() || OSUtils.isWindows()) {
// Quicktime:
contentPrefixList.add("net.sf.fmj.qt");
}
if (OSUtils.isWindows()) {
// DirectShow:
contentPrefixList.add("net.sf.fmj.ds");
}
if (ENABLE_GSTREAMER && OSUtils.isLinux()) {
// TODO: we could add these for other OS's, as gstreamer is cross-platform.
// DirectShow:
contentPrefixList.add("net.sf.fmj.gst");
}
}
if ((flags & FMJ) != 0) {
contentPrefixList.add("net.sf.fmj");
}
if ((flags & THIRD_PARTY) != 0) {
// none to add
}
return contentPrefixList;
} |
9,907 | 3 | // none to add | public static List<String> contentPrefixList(int flags)
{
final List<String> contentPrefixList = new ArrayList<String>();
if ((flags & JMF) != 0) {
contentPrefixList.add("javax");
contentPrefixList.add("com.sun");
contentPrefixList.add("com.ibm");
}
if ((flags & FMJ_NATIVE) != 0) {
if (OSUtils.isMacOSX() || OSUtils.isWindows()) {
// Quicktime:
contentPrefixList.add("net.sf.fmj.qt");
}
if (OSUtils.isWindows()) {
// DirectShow:
contentPrefixList.add("net.sf.fmj.ds");
}
if (ENABLE_GSTREAMER && OSUtils.isLinux()) {
// TODO: we could add these for other OS's, as gstreamer is cross-platform.
// DirectShow:
contentPrefixList.add("net.sf.fmj.gst");
}
}
if ((flags & FMJ) != 0) {
contentPrefixList.add("net.sf.fmj");
}
if ((flags & THIRD_PARTY) != 0) {
// none to add
}
return contentPrefixList;
} | NONSATD | true | }
if ((flags & THIRD_PARTY) != 0) {
// none to add
}
return contentPrefixList; | if (ENABLE_GSTREAMER && OSUtils.isLinux()) {
// TODO: we could add these for other OS's, as gstreamer is cross-platform.
// DirectShow:
contentPrefixList.add("net.sf.fmj.gst");
}
}
if ((flags & FMJ) != 0) {
contentPrefixList.add("net.sf.fmj");
}
if ((flags & THIRD_PARTY) != 0) {
// none to add
}
return contentPrefixList;
} | }
if ((flags & FMJ_NATIVE) != 0) {
if (OSUtils.isMacOSX() || OSUtils.isWindows()) {
// Quicktime:
contentPrefixList.add("net.sf.fmj.qt");
}
if (OSUtils.isWindows()) {
// DirectShow:
contentPrefixList.add("net.sf.fmj.ds");
}
if (ENABLE_GSTREAMER && OSUtils.isLinux()) {
// TODO: we could add these for other OS's, as gstreamer is cross-platform.
// DirectShow:
contentPrefixList.add("net.sf.fmj.gst");
}
}
if ((flags & FMJ) != 0) {
contentPrefixList.add("net.sf.fmj");
}
if ((flags & THIRD_PARTY) != 0) {
// none to add
}
return contentPrefixList;
} |
18,099 | 0 | /************************************************** <pre>
Process a Vnmrbg "SQ" command.
SQ commands are sent from the VNMR background engine to the SQ
through the vnmrj-Vnmrbg socket interface. Usually, they are generated by
the EM in response to a change in the status of the experiment queue
but (for testing purposes) may also be entered from the command line.
General syntax:
vnmrjcmd('SQ <command> <arg> .. <arg> [<macro>]')
If <macro> is specified, the SQ sends a command to the Background engine
to execute the macro after other actions specified by the command are
carried out.
refer to studyQueueAPI.spec for additional details
<pre>**************************************************/ | private void process(String str) {
QuotedStringTokenizer tok = new QuotedStringTokenizer(str);
String cmd = tok.nextToken().trim();
String retstr = "";
if (cmd.equals("no-op")) {
// Does nothing
}
// syntax: vnmrjcmd('SQ start [<macro>]')
else if (cmd.equals(START)) {
mgr.setExecuting(true);
mgr.setPaused(false);
}
// syntax: vnmrjcmd('SQ pause [<macro>]')
else if (cmd.equals(PAUSE)) {
mgr.setExecuting(false);
mgr.setPaused(true);
}
// syntax: vnmrjcmd('SQ stop [<macro>]')
else if (cmd.equals(STOP)) {
mgr.setExecuting(false);
mgr.setPaused(false);
}
// syntax: vnmrjcmd('SQ NormalMode [<macro>]')
else if (cmd.equalsIgnoreCase(NORMAL_MODE)) {
mgr.setMode(NORMAL_MODE);
}
// syntax: vnmrjcmd('SQ SubmitMode [<macro>]')
else if (cmd.equalsIgnoreCase(SUBMIT_MODE)) {
mgr.setMode(SUBMIT_MODE);
}
// syntax: vnmrjcmd('SQ read filename.xml [<macro>]')
else if (cmd.equals(READ)) {
String fn = tok.nextToken().trim();
if (mgr.isExecuting()) {
postWarning("cannot load a new study while queue is executing");
return;
} else {
String path = FileUtil.openPath(fn);
if (path == null) {
postError("cannot load study file " + fn);
return;
}
mgr.newTree(path);
// set sqdirs[jviewport]=path
sendSQpath(path);
}
}
// syntax: vnmrjcmd('SQ write filename.xml [<macro>]')
else if (cmd.equals(WRITE)) {
String fn = tok.nextToken().trim();
String path = FileUtil.savePath(fn);
if (path == null) {
postError("could not write study file " + fn);
return;
}
mgr.save(path);
// set sqdirs[jviewport]=path
sendSQpath(path);
}
// syntax: vnmrjcmd('SQ nwrite filename.xml [<macro>]')
else if (cmd.equals(NWRITE)) {
String id;
String path;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
if (tok.hasMoreTokens())
path = FileUtil.savePath(tok.nextToken().trim());
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
return;
}
mgr.writeElement(dst, path);
}
// syntax: vnmrjcmd('SQ setids')
else if (cmd.equals(SETIDS)) {
mgr.setIds();
}
// syntax: vnmrjcmd('SQ nesting = {true,false}")
else if (cmd.equals(NESTING)) {
String token;
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (!token.equals("=")) {
postError("syntax error " + "SQ " + str);
return;
}
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (token.equals("no") || token.equals("false"))
mgr.setAllowNesting(false);
else if (token.equals("yes") || token.equals("true"))
mgr.setAllowNesting(true);
}
// syntax: vnmrjcmd('SQ validate {move,copy,all,none}")
else if (cmd.equals(VALIDATE)) {
String token;
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
mgr.setValidateMove(false);
mgr.setValidateCopy(false);
if (token.equals("all")) {
mgr.setValidateMove(true);
mgr.setValidateCopy(true);
return;
} else if (token.equals("move")) {
mgr.setValidateMove(true);
return;
} else if (token.equals("copy")) {
mgr.setValidateCopy(true);
return;
} else if (token.equals("none")) {
mgr.setValidateMove(false);
mgr.setValidateCopy(false);
return;
} else {
postError("syntax error " + "SQ " + str);
return;
}
}
// syntax: vnmrjcmd('SQ delete <id>")
else if (cmd.equals(DELETE)) {
String id;
if (tok.hasMoreTokens())
id = tok.nextToken();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (getCondition(id) == ProtocolBuilder.ALL) {
mgr.clearTree();
// set sqdirs[jviewport]=''
sendSQpath("");
} else {
VElement obj = mgr.getElement(id);
if (obj == null) {
if ( ! id.equals("tmpstudy")) {
postError("node " + id + " not found " + "SQ " + cmd);
}
return;
}
mgr.deleteElement(obj);
}
}
else if (cmd.equals(ADD_QUEUE)) {
String queueDir = tok.nextToken();
mgr.addQueue(queueDir);
}
// syntax: vnmrjcmd('SQ add <file> [<cond>] [<dst>] [<macro>]')
// vnmrjcmd('SQ add new <type> [<cond>] [<dst>] [<macro>]')
else if (cmd.equals(ADD)) {
String id = tok.nextToken().trim();
String fn = null;
String type = "protocol";
if (id.equals("new")) {
type = tok.nextToken();
Messages.postDebug("SQ", "--- SQ ADD: type=" + type);
if (type.equals("action"))
fn = new_action_file;
else
fn = new_protocol_file;
} else
fn = id;
String path = FileUtil.openPath(fn);
if (path == null) {
postError("cannot read protocol file " + fn);
return;
}
id = null;
if (tok.hasMoreTokens()) {
id = tok.nextToken();
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
id = tok.nextToken().trim();
}
}
VElement dst;
if (id == null)
dst = mgr.lastElement();
else
dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
mgr.insertProtocol(dst, path);
mgr.setInsertMode(0);
new_elem = mgr.getSelected();
}
// syntax: vnmrjcmd('SQ move <src> [<cond>] <dst> [true,false] [<macro>]')
else if (cmd.equals(MOVE)) {
String id;
boolean ignorelock = false;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
// postError("insufficient command arguments SQ " + cmd);
return;
}
VElement src = mgr.getElement(id);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
// postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
if (tok.hasMoreTokens()) {
String s = tok.nextToken().trim();
if (s.equals("false"))
ignorelock = true;
else if (s.equals("true"))
ignorelock = false;
else
retstr = s;
}
mgr.moveElement(src, dst, ignorelock);
mgr.setInsertMode(0);
}
// syntax: vnmrjcmd('SQ {lmove,pmove} <src> [<cond>] <dst> [<macro>]')
else if (cmd.equals(PMOVE) || cmd.equals(LMOVE)) {
String id;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
VElement src = mgr.getElement(id);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
id = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
boolean bpmove = false;
if (cmd.equals(PMOVE))
bpmove = true;
boolean ballownesting = mgr.allowNesting();
if (bpmove && !ballownesting)
mgr.setAllowNesting(true);
ArrayList alist = (ArrayList) mgr.getHiddenNodes().clone();
if (!bpmove)
mgr.showElementAll("true");
mgr.moveElement(src, dst, true);
mgr.setHiddenNodes(alist);
if (bpmove)
mgr.setAllowNesting(ballownesting);
else
mgr.hideElements();
mgr.setInsertMode(0);
}
// syntax: vnmrjcmd('SQ show <attr> <id> [<macro>]')
else if (cmd.equals(SHOW)) {
String value;
if (tok.hasMoreTokens())
value = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
ArrayList aListElem = new ArrayList();
while (tok.hasMoreTokens()) {
String id = tok.nextToken().trim();
VElement src = mgr.getElement(id);
if (src == null)
{
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
}
else
{
aListElem.add(src);
}
}
mgr.showElement(aListElem, value);
}
// syntax: vnmrjcmd('SQ copy <id> <cond> <dst> [<macro>]')
else if (cmd.equals(COPY)) {
String id_src;
String id_dst;
if (tok.hasMoreTokens())
id_src = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
if (tok.hasMoreTokens())
id_dst = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id_dst);
if (cond != 0) {
mgr.setInsertMode(cond);
id_dst = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id_dst);
if (dst == null) {
if ( ! id_dst.equals("tmpstudy"))
postError("invalid node id " + id_dst);
return;
}
VElement src = mgr.getElement(id_src);
if (src == null) {
src = mgr.readElement(id_src, dst);
if (src == null) {
if ( ! id_src.equals("tmpstudy"))
postError("invalid node id " + id_src);
return;
}
} else
mgr.copyElement(src, dst);
}
// syntax: vnmrjcmd('SQ {get,set} <type> [<cond> <id>] <attr> <val> [<macro>]')
else if (cmd.equals(SET) || cmd.equals(GET)) {
String arg;
// first token
if (tok.hasMoreTokens())
arg = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
// second token
if (!tok.hasMoreTokens()) {
postError("insufficient command arguments SQ " + cmd);
return;
}
int type = 0;
int scope = 0;
int cond = getCondition(arg);
String apar = null;
String vpar = null;
String id = null;
VElement obj = null;
switch (cond) {
case ProtocolBuilder.FIRST:
case ProtocolBuilder.ALL:
arg = tok.nextToken();
type = getType(arg);
scope = getScope(arg);
apar = tok.nextToken();
vpar = tok.nextToken();
break;
default:
type = getType(arg);
if (type == 0 || type == ProtocolBuilder.NEW) {
if (type == ProtocolBuilder.NEW) {
if (new_elem == null) {
postError("must call SQ add before using new");
return;
}
obj = new_elem;
} else {
// e.g. set p2.a2 Lock on
obj = mgr.getElement(arg);
if (obj == null) {
// NB: This can happen when chempack adds protocols
// Ugly but harmless error
Messages.postDebug("SQ",
"unknown identifier SQ " + str);
return;
}
}
cond = ProtocolBuilder.ONE;
type = ProtocolBuilder.ANY;
scope = SINGLE;
} else {
// e.g. set actions > p2.a2 Lock on
scope = getScope(arg);
arg = tok.nextToken().trim();
cond = getCondition(arg);
if (scope == SINGLE) {
// e.g. set actions after p2.a2 Lock on
if (cond == ProtocolBuilder.GT)
cond = ProtocolBuilder.AFTER;
else if (cond == ProtocolBuilder.LT)
cond = ProtocolBuilder.BEFORE;
}
if (cond == 0) {
id = arg;
cond = ProtocolBuilder.ONE;
} else
id = tok.nextToken();
obj = mgr.getElement(id);
}
apar = tok.nextToken();
vpar = tok.nextToken();
if (vpar.startsWith("\"")) {
try {
vpar = vpar.substring(1) + tok.nextToken("\"");
} catch (NoSuchElementException e) {
vpar = vpar.substring(1, vpar.length() - 1);
}
}
break;
} // switch
if (apar == null || vpar == null) {
postError("syntax error " + "SQ " + str);
return;
}
ArrayList list;
// looking for nodes in id will return a null list if id does not exist
if ((obj == null) && (cond == ProtocolBuilder.EQ) )
list = new ArrayList();
else
list = mgr.getElements(obj, cond, type);
if (cmd.equals(SET)) {
for (int i = 0; i < list.size(); i++) {
obj = (VElement) list.get(i);
mgr.setAttribute(obj, apar, vpar);
}
//mgr.invalidateTree();
} else { // get
if (scope == SINGLE) {
if (list.size() > 1) {
postError("syntax error " + "SQ " + str);
return;
}
String alist = apar + "=`";
String vlist = vpar + "=`";
if (list.size() == 1) {
obj = (VElement) list.get(0);
list = mgr.getAttributes(obj);
for (int i = 0; i < list.size(); i += 2) {
String name = (String) list.get(i);
String value = (String) list.get(i + 1);
alist += name;
vlist += value;
if (i < list.size() - 2) {
alist += "`,`";
vlist += "`,`";
}
}
}
alist += "`";
vlist += "`";
retstr = alist + " " + vlist;
} else {
retstr = vpar + "=`";
for (int i = 0; i < list.size(); i++) {
obj = (VElement) list.get(i);
String value = obj.getAttribute(apar);
retstr += value;
if (i < list.size() - 1)
retstr += "`,`";
}
retstr += "`";
}
}
} else if (cmd.equals(WATCH)) {
// E.g.: vnmrjcmd('SQ watch auto ', cursqexp, autodir, svfdir)
ArrayList<String> args = new ArrayList<String>();
while (tok.hasMoreTokens()) {
args.add(tok.nextToken());
}
if (!SQUpdater.processCommand(this, args.toArray(new String[0]))) {
Messages.postDebug("Bad format for 'watch' cmd: " + str);
}
// if (tok.countTokens() != 3) {
// Messages.postDebug("Bad format for 'watch' cmd: " + str);
// } else {
// String studydir = tok.nextToken();
// String autodir = tok.nextToken();
// String datadir = tok.nextToken();
// SQUpdater.startUpdates(this, studydir, autodir, datadir);
// }
} else {
postError("command not recognized " + "SQ " + cmd);
return;
}
while (tok.hasMoreTokens())
retstr += " " + tok.nextToken().trim();
if (retstr.length() > 0) {
setDebug(retstr);
Util.sendToVnmr(retstr);
}
} | NONSATD | true | private void process(String str) {
QuotedStringTokenizer tok = new QuotedStringTokenizer(str);
String cmd = tok.nextToken().trim();
String retstr = "";
if (cmd.equals("no-op")) {
// Does nothing
}
// syntax: vnmrjcmd('SQ start [<macro>]')
else if (cmd.equals(START)) {
mgr.setExecuting(true);
mgr.setPaused(false);
}
// syntax: vnmrjcmd('SQ pause [<macro>]')
else if (cmd.equals(PAUSE)) {
mgr.setExecuting(false);
mgr.setPaused(true);
}
// syntax: vnmrjcmd('SQ stop [<macro>]')
else if (cmd.equals(STOP)) {
mgr.setExecuting(false);
mgr.setPaused(false);
}
// syntax: vnmrjcmd('SQ NormalMode [<macro>]')
else if (cmd.equalsIgnoreCase(NORMAL_MODE)) {
mgr.setMode(NORMAL_MODE);
}
// syntax: vnmrjcmd('SQ SubmitMode [<macro>]')
else if (cmd.equalsIgnoreCase(SUBMIT_MODE)) {
mgr.setMode(SUBMIT_MODE);
}
// syntax: vnmrjcmd('SQ read filename.xml [<macro>]')
else if (cmd.equals(READ)) {
String fn = tok.nextToken().trim();
if (mgr.isExecuting()) {
postWarning("cannot load a new study while queue is executing");
return;
} else {
String path = FileUtil.openPath(fn);
if (path == null) {
postError("cannot load study file " + fn);
return;
}
mgr.newTree(path);
// set sqdirs[jviewport]=path
sendSQpath(path);
}
}
// syntax: vnmrjcmd('SQ write filename.xml [<macro>]')
else if (cmd.equals(WRITE)) {
String fn = tok.nextToken().trim();
String path = FileUtil.savePath(fn);
if (path == null) {
postError("could not write study file " + fn);
return;
}
mgr.save(path);
// set sqdirs[jviewport]=path
sendSQpath(path);
}
// syntax: vnmrjcmd('SQ nwrite filename.xml [<macro>]')
else if (cmd.equals(NWRITE)) {
String id;
String path;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
if (tok.hasMoreTokens())
path = FileUtil.savePath(tok.nextToken().trim());
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
return;
}
mgr.writeElement(dst, path);
}
// syntax: vnmrjcmd('SQ setids')
else if (cmd.equals(SETIDS)) {
mgr.setIds();
}
// syntax: vnmrjcmd('SQ nesting = {true,false}")
else if (cmd.equals(NESTING)) {
String token;
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (!token.equals("=")) {
postError("syntax error " + "SQ " + str);
return;
}
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (token.equals("no") || token.equals("false"))
mgr.setAllowNesting(false);
else if (token.equals("yes") || token.equals("true"))
mgr.setAllowNesting(true);
}
// syntax: vnmrjcmd('SQ validate {move,copy,all,none}")
else if (cmd.equals(VALIDATE)) {
String token;
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
mgr.setValidateMove(false);
mgr.setValidateCopy(false);
if (token.equals("all")) {
mgr.setValidateMove(true);
mgr.setValidateCopy(true);
return;
} else if (token.equals("move")) {
mgr.setValidateMove(true);
return;
} else if (token.equals("copy")) {
mgr.setValidateCopy(true);
return;
} else if (token.equals("none")) {
mgr.setValidateMove(false);
mgr.setValidateCopy(false);
return;
} else {
postError("syntax error " + "SQ " + str);
return;
}
}
// syntax: vnmrjcmd('SQ delete <id>")
else if (cmd.equals(DELETE)) {
String id;
if (tok.hasMoreTokens())
id = tok.nextToken();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (getCondition(id) == ProtocolBuilder.ALL) {
mgr.clearTree();
// set sqdirs[jviewport]=''
sendSQpath("");
} else {
VElement obj = mgr.getElement(id);
if (obj == null) {
if ( ! id.equals("tmpstudy")) {
postError("node " + id + " not found " + "SQ " + cmd);
}
return;
}
mgr.deleteElement(obj);
}
}
else if (cmd.equals(ADD_QUEUE)) {
String queueDir = tok.nextToken();
mgr.addQueue(queueDir);
}
// syntax: vnmrjcmd('SQ add <file> [<cond>] [<dst>] [<macro>]')
// vnmrjcmd('SQ add new <type> [<cond>] [<dst>] [<macro>]')
else if (cmd.equals(ADD)) {
String id = tok.nextToken().trim();
String fn = null;
String type = "protocol";
if (id.equals("new")) {
type = tok.nextToken();
Messages.postDebug("SQ", "--- SQ ADD: type=" + type);
if (type.equals("action"))
fn = new_action_file;
else
fn = new_protocol_file;
} else
fn = id;
String path = FileUtil.openPath(fn);
if (path == null) {
postError("cannot read protocol file " + fn);
return;
}
id = null;
if (tok.hasMoreTokens()) {
id = tok.nextToken();
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
id = tok.nextToken().trim();
}
}
VElement dst;
if (id == null)
dst = mgr.lastElement();
else
dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
mgr.insertProtocol(dst, path);
mgr.setInsertMode(0);
new_elem = mgr.getSelected();
}
// syntax: vnmrjcmd('SQ move <src> [<cond>] <dst> [true,false] [<macro>]')
else if (cmd.equals(MOVE)) {
String id;
boolean ignorelock = false;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
// postError("insufficient command arguments SQ " + cmd);
return;
}
VElement src = mgr.getElement(id);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
// postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
if (tok.hasMoreTokens()) {
String s = tok.nextToken().trim();
if (s.equals("false"))
ignorelock = true;
else if (s.equals("true"))
ignorelock = false;
else
retstr = s;
}
mgr.moveElement(src, dst, ignorelock);
mgr.setInsertMode(0);
}
// syntax: vnmrjcmd('SQ {lmove,pmove} <src> [<cond>] <dst> [<macro>]')
else if (cmd.equals(PMOVE) || cmd.equals(LMOVE)) {
String id;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
VElement src = mgr.getElement(id);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
id = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
boolean bpmove = false;
if (cmd.equals(PMOVE))
bpmove = true;
boolean ballownesting = mgr.allowNesting();
if (bpmove && !ballownesting)
mgr.setAllowNesting(true);
ArrayList alist = (ArrayList) mgr.getHiddenNodes().clone();
if (!bpmove)
mgr.showElementAll("true");
mgr.moveElement(src, dst, true);
mgr.setHiddenNodes(alist);
if (bpmove)
mgr.setAllowNesting(ballownesting);
else
mgr.hideElements();
mgr.setInsertMode(0);
}
// syntax: vnmrjcmd('SQ show <attr> <id> [<macro>]')
else if (cmd.equals(SHOW)) {
String value;
if (tok.hasMoreTokens())
value = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
ArrayList aListElem = new ArrayList();
while (tok.hasMoreTokens()) {
String id = tok.nextToken().trim();
VElement src = mgr.getElement(id);
if (src == null)
{
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
}
else
{
aListElem.add(src);
}
}
mgr.showElement(aListElem, value);
}
// syntax: vnmrjcmd('SQ copy <id> <cond> <dst> [<macro>]')
else if (cmd.equals(COPY)) {
String id_src;
String id_dst;
if (tok.hasMoreTokens())
id_src = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
if (tok.hasMoreTokens())
id_dst = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id_dst);
if (cond != 0) {
mgr.setInsertMode(cond);
id_dst = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id_dst);
if (dst == null) {
if ( ! id_dst.equals("tmpstudy"))
postError("invalid node id " + id_dst);
return;
}
VElement src = mgr.getElement(id_src);
if (src == null) {
src = mgr.readElement(id_src, dst);
if (src == null) {
if ( ! id_src.equals("tmpstudy"))
postError("invalid node id " + id_src);
return;
}
} else
mgr.copyElement(src, dst);
}
// syntax: vnmrjcmd('SQ {get,set} <type> [<cond> <id>] <attr> <val> [<macro>]')
else if (cmd.equals(SET) || cmd.equals(GET)) {
String arg;
// first token
if (tok.hasMoreTokens())
arg = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
// second token
if (!tok.hasMoreTokens()) {
postError("insufficient command arguments SQ " + cmd);
return;
}
int type = 0;
int scope = 0;
int cond = getCondition(arg);
String apar = null;
String vpar = null;
String id = null;
VElement obj = null;
switch (cond) {
case ProtocolBuilder.FIRST:
case ProtocolBuilder.ALL:
arg = tok.nextToken();
type = getType(arg);
scope = getScope(arg);
apar = tok.nextToken();
vpar = tok.nextToken();
break;
default:
type = getType(arg);
if (type == 0 || type == ProtocolBuilder.NEW) {
if (type == ProtocolBuilder.NEW) {
if (new_elem == null) {
postError("must call SQ add before using new");
return;
}
obj = new_elem;
} else {
// e.g. set p2.a2 Lock on
obj = mgr.getElement(arg);
if (obj == null) {
// NB: This can happen when chempack adds protocols
// Ugly but harmless error
Messages.postDebug("SQ",
"unknown identifier SQ " + str);
return;
}
}
cond = ProtocolBuilder.ONE;
type = ProtocolBuilder.ANY;
scope = SINGLE;
} else {
// e.g. set actions > p2.a2 Lock on
scope = getScope(arg);
arg = tok.nextToken().trim();
cond = getCondition(arg);
if (scope == SINGLE) {
// e.g. set actions after p2.a2 Lock on
if (cond == ProtocolBuilder.GT)
cond = ProtocolBuilder.AFTER;
else if (cond == ProtocolBuilder.LT)
cond = ProtocolBuilder.BEFORE;
}
if (cond == 0) {
id = arg;
cond = ProtocolBuilder.ONE;
} else
id = tok.nextToken();
obj = mgr.getElement(id);
}
apar = tok.nextToken();
vpar = tok.nextToken();
if (vpar.startsWith("\"")) {
try {
vpar = vpar.substring(1) + tok.nextToken("\"");
} catch (NoSuchElementException e) {
vpar = vpar.substring(1, vpar.length() - 1);
}
}
break;
} // switch
if (apar == null || vpar == null) {
postError("syntax error " + "SQ " + str);
return;
}
ArrayList list;
// looking for nodes in id will return a null list if id does not exist
if ((obj == null) && (cond == ProtocolBuilder.EQ) )
list = new ArrayList();
else
list = mgr.getElements(obj, cond, type);
if (cmd.equals(SET)) {
for (int i = 0; i < list.size(); i++) {
obj = (VElement) list.get(i);
mgr.setAttribute(obj, apar, vpar);
}
//mgr.invalidateTree();
} else { // get
if (scope == SINGLE) {
if (list.size() > 1) {
postError("syntax error " + "SQ " + str);
return;
}
String alist = apar + "=`";
String vlist = vpar + "=`";
if (list.size() == 1) {
obj = (VElement) list.get(0);
list = mgr.getAttributes(obj);
for (int i = 0; i < list.size(); i += 2) {
String name = (String) list.get(i);
String value = (String) list.get(i + 1);
alist += name;
vlist += value;
if (i < list.size() - 2) {
alist += "`,`";
vlist += "`,`";
}
}
}
alist += "`";
vlist += "`";
retstr = alist + " " + vlist;
} else {
retstr = vpar + "=`";
for (int i = 0; i < list.size(); i++) {
obj = (VElement) list.get(i);
String value = obj.getAttribute(apar);
retstr += value;
if (i < list.size() - 1)
retstr += "`,`";
}
retstr += "`";
}
}
} else if (cmd.equals(WATCH)) {
// E.g.: vnmrjcmd('SQ watch auto ', cursqexp, autodir, svfdir)
ArrayList<String> args = new ArrayList<String>();
while (tok.hasMoreTokens()) {
args.add(tok.nextToken());
}
if (!SQUpdater.processCommand(this, args.toArray(new String[0]))) {
Messages.postDebug("Bad format for 'watch' cmd: " + str);
}
// if (tok.countTokens() != 3) {
// Messages.postDebug("Bad format for 'watch' cmd: " + str);
// } else {
// String studydir = tok.nextToken();
// String autodir = tok.nextToken();
// String datadir = tok.nextToken();
// SQUpdater.startUpdates(this, studydir, autodir, datadir);
// }
} else {
postError("command not recognized " + "SQ " + cmd);
return;
}
while (tok.hasMoreTokens())
retstr += " " + tok.nextToken().trim();
if (retstr.length() > 0) {
setDebug(retstr);
Util.sendToVnmr(retstr);
}
} | private void process(String str) {
QuotedStringTokenizer tok = new QuotedStringTokenizer(str);
String cmd = tok.nextToken().trim();
String retstr = "";
if (cmd.equals("no-op")) {
// Does nothing
}
// syntax: vnmrjcmd('SQ start [<macro>]')
else if (cmd.equals(START)) {
mgr.setExecuting(true);
mgr.setPaused(false);
}
// syntax: vnmrjcmd('SQ pause [<macro>]')
else if (cmd.equals(PAUSE)) {
mgr.setExecuting(false);
mgr.setPaused(true);
}
// syntax: vnmrjcmd('SQ stop [<macro>]')
else if (cmd.equals(STOP)) {
mgr.setExecuting(false);
mgr.setPaused(false);
}
// syntax: vnmrjcmd('SQ NormalMode [<macro>]')
else if (cmd.equalsIgnoreCase(NORMAL_MODE)) {
mgr.setMode(NORMAL_MODE);
}
// syntax: vnmrjcmd('SQ SubmitMode [<macro>]')
else if (cmd.equalsIgnoreCase(SUBMIT_MODE)) {
mgr.setMode(SUBMIT_MODE);
}
// syntax: vnmrjcmd('SQ read filename.xml [<macro>]')
else if (cmd.equals(READ)) {
String fn = tok.nextToken().trim();
if (mgr.isExecuting()) {
postWarning("cannot load a new study while queue is executing");
return;
} else {
String path = FileUtil.openPath(fn);
if (path == null) {
postError("cannot load study file " + fn);
return;
}
mgr.newTree(path);
// set sqdirs[jviewport]=path
sendSQpath(path);
}
}
// syntax: vnmrjcmd('SQ write filename.xml [<macro>]')
else if (cmd.equals(WRITE)) {
String fn = tok.nextToken().trim();
String path = FileUtil.savePath(fn);
if (path == null) {
postError("could not write study file " + fn);
return;
}
mgr.save(path);
// set sqdirs[jviewport]=path
sendSQpath(path);
}
// syntax: vnmrjcmd('SQ nwrite filename.xml [<macro>]')
else if (cmd.equals(NWRITE)) {
String id;
String path;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
if (tok.hasMoreTokens())
path = FileUtil.savePath(tok.nextToken().trim());
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
return;
}
mgr.writeElement(dst, path);
}
// syntax: vnmrjcmd('SQ setids')
else if (cmd.equals(SETIDS)) {
mgr.setIds();
}
// syntax: vnmrjcmd('SQ nesting = {true,false}")
else if (cmd.equals(NESTING)) {
String token;
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (!token.equals("=")) {
postError("syntax error " + "SQ " + str);
return;
}
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (token.equals("no") || token.equals("false"))
mgr.setAllowNesting(false);
else if (token.equals("yes") || token.equals("true"))
mgr.setAllowNesting(true);
}
// syntax: vnmrjcmd('SQ validate {move,copy,all,none}")
else if (cmd.equals(VALIDATE)) {
String token;
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
mgr.setValidateMove(false);
mgr.setValidateCopy(false);
if (token.equals("all")) {
mgr.setValidateMove(true);
mgr.setValidateCopy(true);
return;
} else if (token.equals("move")) {
mgr.setValidateMove(true);
return;
} else if (token.equals("copy")) {
mgr.setValidateCopy(true);
return;
} else if (token.equals("none")) {
mgr.setValidateMove(false);
mgr.setValidateCopy(false);
return;
} else {
postError("syntax error " + "SQ " + str);
return;
}
}
// syntax: vnmrjcmd('SQ delete <id>")
else if (cmd.equals(DELETE)) {
String id;
if (tok.hasMoreTokens())
id = tok.nextToken();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (getCondition(id) == ProtocolBuilder.ALL) {
mgr.clearTree();
// set sqdirs[jviewport]=''
sendSQpath("");
} else {
VElement obj = mgr.getElement(id);
if (obj == null) {
if ( ! id.equals("tmpstudy")) {
postError("node " + id + " not found " + "SQ " + cmd);
}
return;
}
mgr.deleteElement(obj);
}
}
else if (cmd.equals(ADD_QUEUE)) {
String queueDir = tok.nextToken();
mgr.addQueue(queueDir);
}
// syntax: vnmrjcmd('SQ add <file> [<cond>] [<dst>] [<macro>]')
// vnmrjcmd('SQ add new <type> [<cond>] [<dst>] [<macro>]')
else if (cmd.equals(ADD)) {
String id = tok.nextToken().trim();
String fn = null;
String type = "protocol";
if (id.equals("new")) {
type = tok.nextToken();
Messages.postDebug("SQ", "--- SQ ADD: type=" + type);
if (type.equals("action"))
fn = new_action_file;
else
fn = new_protocol_file;
} else
fn = id;
String path = FileUtil.openPath(fn);
if (path == null) {
postError("cannot read protocol file " + fn);
return;
}
id = null;
if (tok.hasMoreTokens()) {
id = tok.nextToken();
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
id = tok.nextToken().trim();
}
}
VElement dst;
if (id == null)
dst = mgr.lastElement();
else
dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
mgr.insertProtocol(dst, path);
mgr.setInsertMode(0);
new_elem = mgr.getSelected();
}
// syntax: vnmrjcmd('SQ move <src> [<cond>] <dst> [true,false] [<macro>]')
else if (cmd.equals(MOVE)) {
String id;
boolean ignorelock = false;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
// postError("insufficient command arguments SQ " + cmd);
return;
}
VElement src = mgr.getElement(id);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
// postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
if (tok.hasMoreTokens()) {
String s = tok.nextToken().trim();
if (s.equals("false"))
ignorelock = true;
else if (s.equals("true"))
ignorelock = false;
else
retstr = s;
}
mgr.moveElement(src, dst, ignorelock);
mgr.setInsertMode(0);
}
// syntax: vnmrjcmd('SQ {lmove,pmove} <src> [<cond>] <dst> [<macro>]')
else if (cmd.equals(PMOVE) || cmd.equals(LMOVE)) {
String id;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
VElement src = mgr.getElement(id);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
id = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
boolean bpmove = false;
if (cmd.equals(PMOVE))
bpmove = true;
boolean ballownesting = mgr.allowNesting();
if (bpmove && !ballownesting)
mgr.setAllowNesting(true);
ArrayList alist = (ArrayList) mgr.getHiddenNodes().clone();
if (!bpmove)
mgr.showElementAll("true");
mgr.moveElement(src, dst, true);
mgr.setHiddenNodes(alist);
if (bpmove)
mgr.setAllowNesting(ballownesting);
else
mgr.hideElements();
mgr.setInsertMode(0);
}
// syntax: vnmrjcmd('SQ show <attr> <id> [<macro>]')
else if (cmd.equals(SHOW)) {
String value;
if (tok.hasMoreTokens())
value = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
ArrayList aListElem = new ArrayList();
while (tok.hasMoreTokens()) {
String id = tok.nextToken().trim();
VElement src = mgr.getElement(id);
if (src == null)
{
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
}
else
{
aListElem.add(src);
}
}
mgr.showElement(aListElem, value);
}
// syntax: vnmrjcmd('SQ copy <id> <cond> <dst> [<macro>]')
else if (cmd.equals(COPY)) {
String id_src;
String id_dst;
if (tok.hasMoreTokens())
id_src = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
if (tok.hasMoreTokens())
id_dst = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id_dst);
if (cond != 0) {
mgr.setInsertMode(cond);
id_dst = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id_dst);
if (dst == null) {
if ( ! id_dst.equals("tmpstudy"))
postError("invalid node id " + id_dst);
return;
}
VElement src = mgr.getElement(id_src);
if (src == null) {
src = mgr.readElement(id_src, dst);
if (src == null) {
if ( ! id_src.equals("tmpstudy"))
postError("invalid node id " + id_src);
return;
}
} else
mgr.copyElement(src, dst);
}
// syntax: vnmrjcmd('SQ {get,set} <type> [<cond> <id>] <attr> <val> [<macro>]')
else if (cmd.equals(SET) || cmd.equals(GET)) {
String arg;
// first token
if (tok.hasMoreTokens())
arg = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
// second token
if (!tok.hasMoreTokens()) {
postError("insufficient command arguments SQ " + cmd);
return;
}
int type = 0;
int scope = 0;
int cond = getCondition(arg);
String apar = null;
String vpar = null;
String id = null;
VElement obj = null;
switch (cond) {
case ProtocolBuilder.FIRST:
case ProtocolBuilder.ALL:
arg = tok.nextToken();
type = getType(arg);
scope = getScope(arg);
apar = tok.nextToken();
vpar = tok.nextToken();
break;
default:
type = getType(arg);
if (type == 0 || type == ProtocolBuilder.NEW) {
if (type == ProtocolBuilder.NEW) {
if (new_elem == null) {
postError("must call SQ add before using new");
return;
}
obj = new_elem;
} else {
// e.g. set p2.a2 Lock on
obj = mgr.getElement(arg);
if (obj == null) {
// NB: This can happen when chempack adds protocols
// Ugly but harmless error
Messages.postDebug("SQ",
"unknown identifier SQ " + str);
return;
}
}
cond = ProtocolBuilder.ONE;
type = ProtocolBuilder.ANY;
scope = SINGLE;
} else {
// e.g. set actions > p2.a2 Lock on
scope = getScope(arg);
arg = tok.nextToken().trim();
cond = getCondition(arg);
if (scope == SINGLE) {
// e.g. set actions after p2.a2 Lock on
if (cond == ProtocolBuilder.GT)
cond = ProtocolBuilder.AFTER;
else if (cond == ProtocolBuilder.LT)
cond = ProtocolBuilder.BEFORE;
}
if (cond == 0) {
id = arg;
cond = ProtocolBuilder.ONE;
} else
id = tok.nextToken();
obj = mgr.getElement(id);
}
apar = tok.nextToken();
vpar = tok.nextToken();
if (vpar.startsWith("\"")) {
try {
vpar = vpar.substring(1) + tok.nextToken("\"");
} catch (NoSuchElementException e) {
vpar = vpar.substring(1, vpar.length() - 1);
}
}
break;
} // switch
if (apar == null || vpar == null) {
postError("syntax error " + "SQ " + str);
return;
}
ArrayList list;
// looking for nodes in id will return a null list if id does not exist
if ((obj == null) && (cond == ProtocolBuilder.EQ) )
list = new ArrayList();
else
list = mgr.getElements(obj, cond, type);
if (cmd.equals(SET)) {
for (int i = 0; i < list.size(); i++) {
obj = (VElement) list.get(i);
mgr.setAttribute(obj, apar, vpar);
}
//mgr.invalidateTree();
} else { // get
if (scope == SINGLE) {
if (list.size() > 1) {
postError("syntax error " + "SQ " + str);
return;
}
String alist = apar + "=`";
String vlist = vpar + "=`";
if (list.size() == 1) {
obj = (VElement) list.get(0);
list = mgr.getAttributes(obj);
for (int i = 0; i < list.size(); i += 2) {
String name = (String) list.get(i);
String value = (String) list.get(i + 1);
alist += name;
vlist += value;
if (i < list.size() - 2) {
alist += "`,`";
vlist += "`,`";
}
}
}
alist += "`";
vlist += "`";
retstr = alist + " " + vlist;
} else {
retstr = vpar + "=`";
for (int i = 0; i < list.size(); i++) {
obj = (VElement) list.get(i);
String value = obj.getAttribute(apar);
retstr += value;
if (i < list.size() - 1)
retstr += "`,`";
}
retstr += "`";
}
}
} else if (cmd.equals(WATCH)) {
// E.g.: vnmrjcmd('SQ watch auto ', cursqexp, autodir, svfdir)
ArrayList<String> args = new ArrayList<String>();
while (tok.hasMoreTokens()) {
args.add(tok.nextToken());
}
if (!SQUpdater.processCommand(this, args.toArray(new String[0]))) {
Messages.postDebug("Bad format for 'watch' cmd: " + str);
}
// if (tok.countTokens() != 3) {
// Messages.postDebug("Bad format for 'watch' cmd: " + str);
// } else {
// String studydir = tok.nextToken();
// String autodir = tok.nextToken();
// String datadir = tok.nextToken();
// SQUpdater.startUpdates(this, studydir, autodir, datadir);
// }
} else {
postError("command not recognized " + "SQ " + cmd);
return;
}
while (tok.hasMoreTokens())
retstr += " " + tok.nextToken().trim();
if (retstr.length() > 0) {
setDebug(retstr);
Util.sendToVnmr(retstr);
}
} | private void process(String str) {
QuotedStringTokenizer tok = new QuotedStringTokenizer(str);
String cmd = tok.nextToken().trim();
String retstr = "";
if (cmd.equals("no-op")) {
// Does nothing
}
// syntax: vnmrjcmd('SQ start [<macro>]')
else if (cmd.equals(START)) {
mgr.setExecuting(true);
mgr.setPaused(false);
}
// syntax: vnmrjcmd('SQ pause [<macro>]')
else if (cmd.equals(PAUSE)) {
mgr.setExecuting(false);
mgr.setPaused(true);
}
// syntax: vnmrjcmd('SQ stop [<macro>]')
else if (cmd.equals(STOP)) {
mgr.setExecuting(false);
mgr.setPaused(false);
}
// syntax: vnmrjcmd('SQ NormalMode [<macro>]')
else if (cmd.equalsIgnoreCase(NORMAL_MODE)) {
mgr.setMode(NORMAL_MODE);
}
// syntax: vnmrjcmd('SQ SubmitMode [<macro>]')
else if (cmd.equalsIgnoreCase(SUBMIT_MODE)) {
mgr.setMode(SUBMIT_MODE);
}
// syntax: vnmrjcmd('SQ read filename.xml [<macro>]')
else if (cmd.equals(READ)) {
String fn = tok.nextToken().trim();
if (mgr.isExecuting()) {
postWarning("cannot load a new study while queue is executing");
return;
} else {
String path = FileUtil.openPath(fn);
if (path == null) {
postError("cannot load study file " + fn);
return;
}
mgr.newTree(path);
// set sqdirs[jviewport]=path
sendSQpath(path);
}
}
// syntax: vnmrjcmd('SQ write filename.xml [<macro>]')
else if (cmd.equals(WRITE)) {
String fn = tok.nextToken().trim();
String path = FileUtil.savePath(fn);
if (path == null) {
postError("could not write study file " + fn);
return;
}
mgr.save(path);
// set sqdirs[jviewport]=path
sendSQpath(path);
}
// syntax: vnmrjcmd('SQ nwrite filename.xml [<macro>]')
else if (cmd.equals(NWRITE)) {
String id;
String path;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
if (tok.hasMoreTokens())
path = FileUtil.savePath(tok.nextToken().trim());
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
return;
}
mgr.writeElement(dst, path);
}
// syntax: vnmrjcmd('SQ setids')
else if (cmd.equals(SETIDS)) {
mgr.setIds();
}
// syntax: vnmrjcmd('SQ nesting = {true,false}")
else if (cmd.equals(NESTING)) {
String token;
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (!token.equals("=")) {
postError("syntax error " + "SQ " + str);
return;
}
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (token.equals("no") || token.equals("false"))
mgr.setAllowNesting(false);
else if (token.equals("yes") || token.equals("true"))
mgr.setAllowNesting(true);
}
// syntax: vnmrjcmd('SQ validate {move,copy,all,none}")
else if (cmd.equals(VALIDATE)) {
String token;
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
mgr.setValidateMove(false);
mgr.setValidateCopy(false);
if (token.equals("all")) {
mgr.setValidateMove(true);
mgr.setValidateCopy(true);
return;
} else if (token.equals("move")) {
mgr.setValidateMove(true);
return;
} else if (token.equals("copy")) {
mgr.setValidateCopy(true);
return;
} else if (token.equals("none")) {
mgr.setValidateMove(false);
mgr.setValidateCopy(false);
return;
} else {
postError("syntax error " + "SQ " + str);
return;
}
}
// syntax: vnmrjcmd('SQ delete <id>")
else if (cmd.equals(DELETE)) {
String id;
if (tok.hasMoreTokens())
id = tok.nextToken();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (getCondition(id) == ProtocolBuilder.ALL) {
mgr.clearTree();
// set sqdirs[jviewport]=''
sendSQpath("");
} else {
VElement obj = mgr.getElement(id);
if (obj == null) {
if ( ! id.equals("tmpstudy")) {
postError("node " + id + " not found " + "SQ " + cmd);
}
return;
}
mgr.deleteElement(obj);
}
}
else if (cmd.equals(ADD_QUEUE)) {
String queueDir = tok.nextToken();
mgr.addQueue(queueDir);
}
// syntax: vnmrjcmd('SQ add <file> [<cond>] [<dst>] [<macro>]')
// vnmrjcmd('SQ add new <type> [<cond>] [<dst>] [<macro>]')
else if (cmd.equals(ADD)) {
String id = tok.nextToken().trim();
String fn = null;
String type = "protocol";
if (id.equals("new")) {
type = tok.nextToken();
Messages.postDebug("SQ", "--- SQ ADD: type=" + type);
if (type.equals("action"))
fn = new_action_file;
else
fn = new_protocol_file;
} else
fn = id;
String path = FileUtil.openPath(fn);
if (path == null) {
postError("cannot read protocol file " + fn);
return;
}
id = null;
if (tok.hasMoreTokens()) {
id = tok.nextToken();
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
id = tok.nextToken().trim();
}
}
VElement dst;
if (id == null)
dst = mgr.lastElement();
else
dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
mgr.insertProtocol(dst, path);
mgr.setInsertMode(0);
new_elem = mgr.getSelected();
}
// syntax: vnmrjcmd('SQ move <src> [<cond>] <dst> [true,false] [<macro>]')
else if (cmd.equals(MOVE)) {
String id;
boolean ignorelock = false;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
// postError("insufficient command arguments SQ " + cmd);
return;
}
VElement src = mgr.getElement(id);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
// postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
if (tok.hasMoreTokens()) {
String s = tok.nextToken().trim();
if (s.equals("false"))
ignorelock = true;
else if (s.equals("true"))
ignorelock = false;
else
retstr = s;
}
mgr.moveElement(src, dst, ignorelock);
mgr.setInsertMode(0);
}
// syntax: vnmrjcmd('SQ {lmove,pmove} <src> [<cond>] <dst> [<macro>]')
else if (cmd.equals(PMOVE) || cmd.equals(LMOVE)) {
String id;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
VElement src = mgr.getElement(id);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
id = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
boolean bpmove = false;
if (cmd.equals(PMOVE))
bpmove = true;
boolean ballownesting = mgr.allowNesting();
if (bpmove && !ballownesting)
mgr.setAllowNesting(true);
ArrayList alist = (ArrayList) mgr.getHiddenNodes().clone();
if (!bpmove)
mgr.showElementAll("true");
mgr.moveElement(src, dst, true);
mgr.setHiddenNodes(alist);
if (bpmove)
mgr.setAllowNesting(ballownesting);
else
mgr.hideElements();
mgr.setInsertMode(0);
}
// syntax: vnmrjcmd('SQ show <attr> <id> [<macro>]')
else if (cmd.equals(SHOW)) {
String value;
if (tok.hasMoreTokens())
value = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
ArrayList aListElem = new ArrayList();
while (tok.hasMoreTokens()) {
String id = tok.nextToken().trim();
VElement src = mgr.getElement(id);
if (src == null)
{
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
}
else
{
aListElem.add(src);
}
}
mgr.showElement(aListElem, value);
}
// syntax: vnmrjcmd('SQ copy <id> <cond> <dst> [<macro>]')
else if (cmd.equals(COPY)) {
String id_src;
String id_dst;
if (tok.hasMoreTokens())
id_src = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
if (tok.hasMoreTokens())
id_dst = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id_dst);
if (cond != 0) {
mgr.setInsertMode(cond);
id_dst = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id_dst);
if (dst == null) {
if ( ! id_dst.equals("tmpstudy"))
postError("invalid node id " + id_dst);
return;
}
VElement src = mgr.getElement(id_src);
if (src == null) {
src = mgr.readElement(id_src, dst);
if (src == null) {
if ( ! id_src.equals("tmpstudy"))
postError("invalid node id " + id_src);
return;
}
} else
mgr.copyElement(src, dst);
}
// syntax: vnmrjcmd('SQ {get,set} <type> [<cond> <id>] <attr> <val> [<macro>]')
else if (cmd.equals(SET) || cmd.equals(GET)) {
String arg;
// first token
if (tok.hasMoreTokens())
arg = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
// second token
if (!tok.hasMoreTokens()) {
postError("insufficient command arguments SQ " + cmd);
return;
}
int type = 0;
int scope = 0;
int cond = getCondition(arg);
String apar = null;
String vpar = null;
String id = null;
VElement obj = null;
switch (cond) {
case ProtocolBuilder.FIRST:
case ProtocolBuilder.ALL:
arg = tok.nextToken();
type = getType(arg);
scope = getScope(arg);
apar = tok.nextToken();
vpar = tok.nextToken();
break;
default:
type = getType(arg);
if (type == 0 || type == ProtocolBuilder.NEW) {
if (type == ProtocolBuilder.NEW) {
if (new_elem == null) {
postError("must call SQ add before using new");
return;
}
obj = new_elem;
} else {
// e.g. set p2.a2 Lock on
obj = mgr.getElement(arg);
if (obj == null) {
// NB: This can happen when chempack adds protocols
// Ugly but harmless error
Messages.postDebug("SQ",
"unknown identifier SQ " + str);
return;
}
}
cond = ProtocolBuilder.ONE;
type = ProtocolBuilder.ANY;
scope = SINGLE;
} else {
// e.g. set actions > p2.a2 Lock on
scope = getScope(arg);
arg = tok.nextToken().trim();
cond = getCondition(arg);
if (scope == SINGLE) {
// e.g. set actions after p2.a2 Lock on
if (cond == ProtocolBuilder.GT)
cond = ProtocolBuilder.AFTER;
else if (cond == ProtocolBuilder.LT)
cond = ProtocolBuilder.BEFORE;
}
if (cond == 0) {
id = arg;
cond = ProtocolBuilder.ONE;
} else
id = tok.nextToken();
obj = mgr.getElement(id);
}
apar = tok.nextToken();
vpar = tok.nextToken();
if (vpar.startsWith("\"")) {
try {
vpar = vpar.substring(1) + tok.nextToken("\"");
} catch (NoSuchElementException e) {
vpar = vpar.substring(1, vpar.length() - 1);
}
}
break;
} // switch
if (apar == null || vpar == null) {
postError("syntax error " + "SQ " + str);
return;
}
ArrayList list;
// looking for nodes in id will return a null list if id does not exist
if ((obj == null) && (cond == ProtocolBuilder.EQ) )
list = new ArrayList();
else
list = mgr.getElements(obj, cond, type);
if (cmd.equals(SET)) {
for (int i = 0; i < list.size(); i++) {
obj = (VElement) list.get(i);
mgr.setAttribute(obj, apar, vpar);
}
//mgr.invalidateTree();
} else { // get
if (scope == SINGLE) {
if (list.size() > 1) {
postError("syntax error " + "SQ " + str);
return;
}
String alist = apar + "=`";
String vlist = vpar + "=`";
if (list.size() == 1) {
obj = (VElement) list.get(0);
list = mgr.getAttributes(obj);
for (int i = 0; i < list.size(); i += 2) {
String name = (String) list.get(i);
String value = (String) list.get(i + 1);
alist += name;
vlist += value;
if (i < list.size() - 2) {
alist += "`,`";
vlist += "`,`";
}
}
}
alist += "`";
vlist += "`";
retstr = alist + " " + vlist;
} else {
retstr = vpar + "=`";
for (int i = 0; i < list.size(); i++) {
obj = (VElement) list.get(i);
String value = obj.getAttribute(apar);
retstr += value;
if (i < list.size() - 1)
retstr += "`,`";
}
retstr += "`";
}
}
} else if (cmd.equals(WATCH)) {
// E.g.: vnmrjcmd('SQ watch auto ', cursqexp, autodir, svfdir)
ArrayList<String> args = new ArrayList<String>();
while (tok.hasMoreTokens()) {
args.add(tok.nextToken());
}
if (!SQUpdater.processCommand(this, args.toArray(new String[0]))) {
Messages.postDebug("Bad format for 'watch' cmd: " + str);
}
// if (tok.countTokens() != 3) {
// Messages.postDebug("Bad format for 'watch' cmd: " + str);
// } else {
// String studydir = tok.nextToken();
// String autodir = tok.nextToken();
// String datadir = tok.nextToken();
// SQUpdater.startUpdates(this, studydir, autodir, datadir);
// }
} else {
postError("command not recognized " + "SQ " + cmd);
return;
}
while (tok.hasMoreTokens())
retstr += " " + tok.nextToken().trim();
if (retstr.length() > 0) {
setDebug(retstr);
Util.sendToVnmr(retstr);
}
} |
18,099 | 1 | // Does nothing | private void process(String str) {
QuotedStringTokenizer tok = new QuotedStringTokenizer(str);
String cmd = tok.nextToken().trim();
String retstr = "";
if (cmd.equals("no-op")) {
// Does nothing
}
// syntax: vnmrjcmd('SQ start [<macro>]')
else if (cmd.equals(START)) {
mgr.setExecuting(true);
mgr.setPaused(false);
}
// syntax: vnmrjcmd('SQ pause [<macro>]')
else if (cmd.equals(PAUSE)) {
mgr.setExecuting(false);
mgr.setPaused(true);
}
// syntax: vnmrjcmd('SQ stop [<macro>]')
else if (cmd.equals(STOP)) {
mgr.setExecuting(false);
mgr.setPaused(false);
}
// syntax: vnmrjcmd('SQ NormalMode [<macro>]')
else if (cmd.equalsIgnoreCase(NORMAL_MODE)) {
mgr.setMode(NORMAL_MODE);
}
// syntax: vnmrjcmd('SQ SubmitMode [<macro>]')
else if (cmd.equalsIgnoreCase(SUBMIT_MODE)) {
mgr.setMode(SUBMIT_MODE);
}
// syntax: vnmrjcmd('SQ read filename.xml [<macro>]')
else if (cmd.equals(READ)) {
String fn = tok.nextToken().trim();
if (mgr.isExecuting()) {
postWarning("cannot load a new study while queue is executing");
return;
} else {
String path = FileUtil.openPath(fn);
if (path == null) {
postError("cannot load study file " + fn);
return;
}
mgr.newTree(path);
// set sqdirs[jviewport]=path
sendSQpath(path);
}
}
// syntax: vnmrjcmd('SQ write filename.xml [<macro>]')
else if (cmd.equals(WRITE)) {
String fn = tok.nextToken().trim();
String path = FileUtil.savePath(fn);
if (path == null) {
postError("could not write study file " + fn);
return;
}
mgr.save(path);
// set sqdirs[jviewport]=path
sendSQpath(path);
}
// syntax: vnmrjcmd('SQ nwrite filename.xml [<macro>]')
else if (cmd.equals(NWRITE)) {
String id;
String path;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
if (tok.hasMoreTokens())
path = FileUtil.savePath(tok.nextToken().trim());
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
return;
}
mgr.writeElement(dst, path);
}
// syntax: vnmrjcmd('SQ setids')
else if (cmd.equals(SETIDS)) {
mgr.setIds();
}
// syntax: vnmrjcmd('SQ nesting = {true,false}")
else if (cmd.equals(NESTING)) {
String token;
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (!token.equals("=")) {
postError("syntax error " + "SQ " + str);
return;
}
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (token.equals("no") || token.equals("false"))
mgr.setAllowNesting(false);
else if (token.equals("yes") || token.equals("true"))
mgr.setAllowNesting(true);
}
// syntax: vnmrjcmd('SQ validate {move,copy,all,none}")
else if (cmd.equals(VALIDATE)) {
String token;
if (tok.hasMoreTokens())
token = tok.nextToken().trim();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
mgr.setValidateMove(false);
mgr.setValidateCopy(false);
if (token.equals("all")) {
mgr.setValidateMove(true);
mgr.setValidateCopy(true);
return;
} else if (token.equals("move")) {
mgr.setValidateMove(true);
return;
} else if (token.equals("copy")) {
mgr.setValidateCopy(true);
return;
} else if (token.equals("none")) {
mgr.setValidateMove(false);
mgr.setValidateCopy(false);
return;
} else {
postError("syntax error " + "SQ " + str);
return;
}
}
// syntax: vnmrjcmd('SQ delete <id>")
else if (cmd.equals(DELETE)) {
String id;
if (tok.hasMoreTokens())
id = tok.nextToken();
else {
postError("insufficient command arguments " + "SQ " + cmd);
return;
}
if (getCondition(id) == ProtocolBuilder.ALL) {
mgr.clearTree();
// set sqdirs[jviewport]=''
sendSQpath("");
} else {
VElement obj = mgr.getElement(id);
if (obj == null) {
if ( ! id.equals("tmpstudy")) {
postError("node " + id + " not found " + "SQ " + cmd);
}
return;
}
mgr.deleteElement(obj);
}
}
else if (cmd.equals(ADD_QUEUE)) {
String queueDir = tok.nextToken();
mgr.addQueue(queueDir);
}
// syntax: vnmrjcmd('SQ add <file> [<cond>] [<dst>] [<macro>]')
// vnmrjcmd('SQ add new <type> [<cond>] [<dst>] [<macro>]')
else if (cmd.equals(ADD)) {
String id = tok.nextToken().trim();
String fn = null;
String type = "protocol";
if (id.equals("new")) {
type = tok.nextToken();
Messages.postDebug("SQ", "--- SQ ADD: type=" + type);
if (type.equals("action"))
fn = new_action_file;
else
fn = new_protocol_file;
} else
fn = id;
String path = FileUtil.openPath(fn);
if (path == null) {
postError("cannot read protocol file " + fn);
return;
}
id = null;
if (tok.hasMoreTokens()) {
id = tok.nextToken();
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
id = tok.nextToken().trim();
}
}
VElement dst;
if (id == null)
dst = mgr.lastElement();
else
dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
mgr.insertProtocol(dst, path);
mgr.setInsertMode(0);
new_elem = mgr.getSelected();
}
// syntax: vnmrjcmd('SQ move <src> [<cond>] <dst> [true,false] [<macro>]')
else if (cmd.equals(MOVE)) {
String id;
boolean ignorelock = false;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
// postError("insufficient command arguments SQ " + cmd);
return;
}
VElement src = mgr.getElement(id);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
// postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
if (tok.hasMoreTokens()) {
String s = tok.nextToken().trim();
if (s.equals("false"))
ignorelock = true;
else if (s.equals("true"))
ignorelock = false;
else
retstr = s;
}
mgr.moveElement(src, dst, ignorelock);
mgr.setInsertMode(0);
}
// syntax: vnmrjcmd('SQ {lmove,pmove} <src> [<cond>] <dst> [<macro>]')
else if (cmd.equals(PMOVE) || cmd.equals(LMOVE)) {
String id;
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
VElement src = mgr.getElement(id);
if (tok.hasMoreTokens())
id = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id);
if (cond != 0) {
mgr.setInsertMode(cond);
id = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id);
if (dst == null) {
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
mgr.setInsertMode(0);
return;
}
boolean bpmove = false;
if (cmd.equals(PMOVE))
bpmove = true;
boolean ballownesting = mgr.allowNesting();
if (bpmove && !ballownesting)
mgr.setAllowNesting(true);
ArrayList alist = (ArrayList) mgr.getHiddenNodes().clone();
if (!bpmove)
mgr.showElementAll("true");
mgr.moveElement(src, dst, true);
mgr.setHiddenNodes(alist);
if (bpmove)
mgr.setAllowNesting(ballownesting);
else
mgr.hideElements();
mgr.setInsertMode(0);
}
// syntax: vnmrjcmd('SQ show <attr> <id> [<macro>]')
else if (cmd.equals(SHOW)) {
String value;
if (tok.hasMoreTokens())
value = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
ArrayList aListElem = new ArrayList();
while (tok.hasMoreTokens()) {
String id = tok.nextToken().trim();
VElement src = mgr.getElement(id);
if (src == null)
{
if ( ! id.equals("tmpstudy"))
postError("invalid node id " + id);
}
else
{
aListElem.add(src);
}
}
mgr.showElement(aListElem, value);
}
// syntax: vnmrjcmd('SQ copy <id> <cond> <dst> [<macro>]')
else if (cmd.equals(COPY)) {
String id_src;
String id_dst;
if (tok.hasMoreTokens())
id_src = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
if (tok.hasMoreTokens())
id_dst = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
int cond = getCondition(id_dst);
if (cond != 0) {
mgr.setInsertMode(cond);
id_dst = tok.nextToken().trim();
}
VElement dst = mgr.getElement(id_dst);
if (dst == null) {
if ( ! id_dst.equals("tmpstudy"))
postError("invalid node id " + id_dst);
return;
}
VElement src = mgr.getElement(id_src);
if (src == null) {
src = mgr.readElement(id_src, dst);
if (src == null) {
if ( ! id_src.equals("tmpstudy"))
postError("invalid node id " + id_src);
return;
}
} else
mgr.copyElement(src, dst);
}
// syntax: vnmrjcmd('SQ {get,set} <type> [<cond> <id>] <attr> <val> [<macro>]')
else if (cmd.equals(SET) || cmd.equals(GET)) {
String arg;
// first token
if (tok.hasMoreTokens())
arg = tok.nextToken().trim();
else {
postError("insufficient command arguments SQ " + cmd);
return;
}
// second token
if (!tok.hasMoreTokens()) {
postError("insufficient command arguments SQ " + cmd);
return;
}
int type = 0;
int scope = 0;
int cond = getCondition(arg);
String apar = null;
String vpar = null;
String id = null;
VElement obj = null;
switch (cond) {
case ProtocolBuilder.FIRST:
case ProtocolBuilder.ALL:
arg = tok.nextToken();
type = getType(arg);
scope = getScope(arg);
apar = tok.nextToken();
vpar = tok.nextToken();
break;
default:
type = getType(arg);
if (type == 0 || type == ProtocolBuilder.NEW) {
if (type == ProtocolBuilder.NEW) {
if (new_elem == null) {
postError("must call SQ add before using new");
return;
}
obj = new_elem;
} else {
// e.g. set p2.a2 Lock on
obj = mgr.getElement(arg);
if (obj == null) {
// NB: This can happen when chempack adds protocols
// Ugly but harmless error
Messages.postDebug("SQ",
"unknown identifier SQ " + str);
return;
}
}
cond = ProtocolBuilder.ONE;
type = ProtocolBuilder.ANY;
scope = SINGLE;
} else {
// e.g. set actions > p2.a2 Lock on
scope = getScope(arg);
arg = tok.nextToken().trim();
cond = getCondition(arg);
if (scope == SINGLE) {
// e.g. set actions after p2.a2 Lock on
if (cond == ProtocolBuilder.GT)
cond = ProtocolBuilder.AFTER;
else if (cond == ProtocolBuilder.LT)
cond = ProtocolBuilder.BEFORE;
}
if (cond == 0) {
id = arg;
cond = ProtocolBuilder.ONE;
} else
id = tok.nextToken();
obj = mgr.getElement(id);
}
apar = tok.nextToken();
vpar = tok.nextToken();
if (vpar.startsWith("\"")) {
try {
vpar = vpar.substring(1) + tok.nextToken("\"");
} catch (NoSuchElementException e) {
vpar = vpar.substring(1, vpar.length() - 1);
}
}
break;
} // switch
if (apar == null || vpar == null) {
postError("syntax error " + "SQ " + str);
return;
}
ArrayList list;
// looking for nodes in id will return a null list if id does not exist
if ((obj == null) && (cond == ProtocolBuilder.EQ) )
list = new ArrayList();
else
list = mgr.getElements(obj, cond, type);
if (cmd.equals(SET)) {
for (int i = 0; i < list.size(); i++) {
obj = (VElement) list.get(i);
mgr.setAttribute(obj, apar, vpar);
}
//mgr.invalidateTree();
} else { // get
if (scope == SINGLE) {
if (list.size() > 1) {
postError("syntax error " + "SQ " + str);
return;
}
String alist = apar + "=`";
String vlist = vpar + "=`";
if (list.size() == 1) {
obj = (VElement) list.get(0);
list = mgr.getAttributes(obj);
for (int i = 0; i < list.size(); i += 2) {
String name = (String) list.get(i);
String value = (String) list.get(i + 1);
alist += name;
vlist += value;
if (i < list.size() - 2) {
alist += "`,`";
vlist += "`,`";
}
}
}
alist += "`";
vlist += "`";
retstr = alist + " " + vlist;
} else {
retstr = vpar + "=`";
for (int i = 0; i < list.size(); i++) {
obj = (VElement) list.get(i);
String value = obj.getAttribute(apar);
retstr += value;
if (i < list.size() - 1)
retstr += "`,`";
}
retstr += "`";
}
}
} else if (cmd.equals(WATCH)) {
// E.g.: vnmrjcmd('SQ watch auto ', cursqexp, autodir, svfdir)
ArrayList<String> args = new ArrayList<String>();
while (tok.hasMoreTokens()) {
args.add(tok.nextToken());
}
if (!SQUpdater.processCommand(this, args.toArray(new String[0]))) {
Messages.postDebug("Bad format for 'watch' cmd: " + str);
}
// if (tok.countTokens() != 3) {
// Messages.postDebug("Bad format for 'watch' cmd: " + str);
// } else {
// String studydir = tok.nextToken();
// String autodir = tok.nextToken();
// String datadir = tok.nextToken();
// SQUpdater.startUpdates(this, studydir, autodir, datadir);
// }
} else {
postError("command not recognized " + "SQ " + cmd);
return;
}
while (tok.hasMoreTokens())
retstr += " " + tok.nextToken().trim();
if (retstr.length() > 0) {
setDebug(retstr);
Util.sendToVnmr(retstr);
}
} | NONSATD | true | String retstr = "";
if (cmd.equals("no-op")) {
// Does nothing
}
// syntax: vnmrjcmd('SQ start [<macro>]') | private void process(String str) {
QuotedStringTokenizer tok = new QuotedStringTokenizer(str);
String cmd = tok.nextToken().trim();
String retstr = "";
if (cmd.equals("no-op")) {
// Does nothing
}
// syntax: vnmrjcmd('SQ start [<macro>]')
else if (cmd.equals(START)) {
mgr.setExecuting(true);
mgr.setPaused(false);
}
// syntax: vnmrjcmd('SQ pause [<macro>]')
else if (cmd.equals(PAUSE)) {
mgr.setExecuting(false);
mgr.setPaused(true); | private void process(String str) {
QuotedStringTokenizer tok = new QuotedStringTokenizer(str);
String cmd = tok.nextToken().trim();
String retstr = "";
if (cmd.equals("no-op")) {
// Does nothing
}
// syntax: vnmrjcmd('SQ start [<macro>]')
else if (cmd.equals(START)) {
mgr.setExecuting(true);
mgr.setPaused(false);
}
// syntax: vnmrjcmd('SQ pause [<macro>]')
else if (cmd.equals(PAUSE)) {
mgr.setExecuting(false);
mgr.setPaused(true);
}
// syntax: vnmrjcmd('SQ stop [<macro>]')
else if (cmd.equals(STOP)) {
mgr.setExecuting(false);
mgr.setPaused(false);
}
// syntax: vnmrjcmd('SQ NormalMode [<macro>]')
else if (cmd.equalsIgnoreCase(NORMAL_MODE)) {
mgr.setMode(NORMAL_MODE);
} |