updating the vitro branch dev-search_relevance(r8030) with changes from the trunk(r8031).

This commit is contained in:
deepakkoni 2011-05-18 18:30:20 +00:00
commit 4a209a12ce
190 changed files with 9698 additions and 6075 deletions

Binary file not shown.

BIN
solr/apache-solr-3.1.0.war Normal file

Binary file not shown.

View file

@ -12,7 +12,7 @@
<property name="solr.build.dir" location="."/> <property name="solr.build.dir" location="."/>
<property name="solr.example.dir" location="${solr.build.dir}/exampleSolr" /> <property name="solr.example.dir" location="${solr.build.dir}/exampleSolr" />
<property name="solr.context.config.example" location="${solr.build.dir}/exampleSolrContext.xml"/> <property name="solr.context.config.example" location="${solr.build.dir}/exampleSolrContext.xml"/>
<property name="solr.war" location="${solr.build.dir}/apache-solr-1.4.1.war"/> <property name="solr.war" location="${solr.build.dir}/apache-solr-3.1.0.war"/>
<!-- ================================= <!-- =================================
target: describe target: describe

View file

@ -1,54 +1,54 @@
# Licensed to the Apache Software Foundation (ASF) under one or more # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with # contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership. # this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0 # The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with # (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at # the License. You may obtain a copy of the License at
# #
# http://www.apache.org/licenses/LICENSE-2.0 # http://www.apache.org/licenses/LICENSE-2.0
# #
# Unless required by applicable law or agreed to in writing, software # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
Example "Solr Home" Directory Example "Solr Home" Directory
============================= =============================
This directory is provided as an example of what a "Solr Home" directory This directory is provided as an example of what a "Solr Home" directory
should look like. should look like.
It's not strictly necessary that you copy all of the files in this It's not strictly necessary that you copy all of the files in this
directory when setting up a new instance of Solr, but it is recommended. directory when setting up a new instance of Solr, but it is recommended.
Basic Directory Structure Basic Directory Structure
------------------------- -------------------------
The Solr Home directory typically contains the following subdirectories... The Solr Home directory typically contains the following subdirectories...
conf/ conf/
This directory is mandatory and must contain your solrconfig.xml This directory is mandatory and must contain your solrconfig.xml
and schema.xml. Any other optional configuration files would also and schema.xml. Any other optional configuration files would also
be kept here. be kept here.
data/ data/
This directory is the default location where Solr will keep your This directory is the default location where Solr will keep your
index, and is used by the replication scripts for dealing with index, and is used by the replication scripts for dealing with
snapshots. You can override this location in the solrconfig.xml snapshots. You can override this location in the solrconfig.xml
and scripts.conf files. Solr will create this directory if it and scripts.conf files. Solr will create this directory if it
does not already exist. does not already exist.
lib/ lib/
This directory is optional. If it exists, Solr will load any Jars This directory is optional. If it exists, Solr will load any Jars
found in this directory and use them to resolve any "plugins" found in this directory and use them to resolve any "plugins"
specified in your solrconfig.xml or schema.xml (ie: Analyzers, specified in your solrconfig.xml or schema.xml (ie: Analyzers,
Request Handlers, etc...). Alternatively you can use the <lib> Request Handlers, etc...). Alternatively you can use the <lib>
syntax in solrconfig.xml to direct Solr to your plugins. See the syntax in solrconfig.xml to direct Solr to your plugins. See the
example solrconfig.xml file for details. example solrconfig.xml file for details.
bin/ bin/
This directory is optional. It is the default location used for This directory is optional. It is the default location used for
keeping the replication scripts. keeping the replication scripts.

View file

@ -1,31 +1,31 @@
<!-- <!--
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
--> -->
<!-- The content of this page will be statically included into the top <!-- The content of this page will be statically included into the top
of the admin page. Uncomment this as an example to see there the content of the admin page. Uncomment this as an example to see there the content
will show up. will show up.
<hr> <hr>
<i>This line will appear before the first table</i> <i>This line will appear before the first table</i>
<tr> <tr>
<td colspan="2"> <td colspan="2">
This row will be appended to the end of the first table This row will be appended to the end of the first table
</td> </td>
</tr> </tr>
<hr> <hr>
--> -->

View file

@ -1,36 +1,36 @@
<?xml version="1.0" encoding="UTF-8" ?> <?xml version="1.0" encoding="UTF-8" ?>
<!-- <!--
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
--> -->
<!-- If this file is found in the config directory, it will only be <!-- If this file is found in the config directory, it will only be
loaded once at startup. If it is found in Solr's data loaded once at startup. If it is found in Solr's data
directory, it will be re-loaded every commit. directory, it will be re-loaded every commit.
--> -->
<elevate> <elevate>
<query text="foo bar"> <query text="foo bar">
<doc id="1" /> <doc id="1" />
<doc id="2" /> <doc id="2" />
<doc id="3" /> <doc id="3" />
</query> </query>
<query text="ipod"> <query text="ipod">
<doc id="MA147LL/A" /> <!-- put the actual ipod at the top --> <doc id="MA147LL/A" /> <!-- put the actual ipod at the top -->
<doc id="IW-02" exclude="true" /> <!-- exclude this cable --> <doc id="IW-02" exclude="true" /> <!-- exclude this cable -->
</query> </query>
</elevate> </elevate>

File diff suppressed because it is too large Load diff

View file

@ -1,246 +1,246 @@
# The ASF licenses this file to You under the Apache License, Version 2.0 # The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with # (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at # the License. You may obtain a copy of the License at
# #
# http://www.apache.org/licenses/LICENSE-2.0 # http://www.apache.org/licenses/LICENSE-2.0
# #
# Unless required by applicable law or agreed to in writing, software # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# Syntax: # Syntax:
# "source" => "target" # "source" => "target"
# "source".length() > 0 (source cannot be empty.) # "source".length() > 0 (source cannot be empty.)
# "target".length() >= 0 (target can be empty.) # "target".length() >= 0 (target can be empty.)
# example: # example:
# "À" => "A" # "À" => "A"
# "\u00C0" => "A" # "\u00C0" => "A"
# "\u00C0" => "\u0041" # "\u00C0" => "\u0041"
# "ß" => "ss" # "ß" => "ss"
# "\t" => " " # "\t" => " "
# "\n" => "" # "\n" => ""
# À => A # À => A
"\u00C0" => "A" "\u00C0" => "A"
# Á => A # Á => A
"\u00C1" => "A" "\u00C1" => "A"
# Â => A # Â => A
"\u00C2" => "A" "\u00C2" => "A"
# Ã => A # Ã => A
"\u00C3" => "A" "\u00C3" => "A"
# Ä => A # Ä => A
"\u00C4" => "A" "\u00C4" => "A"
# Å => A # Å => A
"\u00C5" => "A" "\u00C5" => "A"
# Æ => AE # Æ => AE
"\u00C6" => "AE" "\u00C6" => "AE"
# Ç => C # Ç => C
"\u00C7" => "C" "\u00C7" => "C"
# È => E # È => E
"\u00C8" => "E" "\u00C8" => "E"
# É => E # É => E
"\u00C9" => "E" "\u00C9" => "E"
# Ê => E # Ê => E
"\u00CA" => "E" "\u00CA" => "E"
# Ë => E # Ë => E
"\u00CB" => "E" "\u00CB" => "E"
# Ì => I # Ì => I
"\u00CC" => "I" "\u00CC" => "I"
# Í => I # Í => I
"\u00CD" => "I" "\u00CD" => "I"
# Î => I # Î => I
"\u00CE" => "I" "\u00CE" => "I"
# Ï => I # Ï => I
"\u00CF" => "I" "\u00CF" => "I"
# IJ => IJ # IJ => IJ
"\u0132" => "IJ" "\u0132" => "IJ"
# Ð => D # Ð => D
"\u00D0" => "D" "\u00D0" => "D"
# Ñ => N # Ñ => N
"\u00D1" => "N" "\u00D1" => "N"
# Ò => O # Ò => O
"\u00D2" => "O" "\u00D2" => "O"
# Ó => O # Ó => O
"\u00D3" => "O" "\u00D3" => "O"
# Ô => O # Ô => O
"\u00D4" => "O" "\u00D4" => "O"
# Õ => O # Õ => O
"\u00D5" => "O" "\u00D5" => "O"
# Ö => O # Ö => O
"\u00D6" => "O" "\u00D6" => "O"
# Ø => O # Ø => O
"\u00D8" => "O" "\u00D8" => "O"
# Œ => OE # Œ => OE
"\u0152" => "OE" "\u0152" => "OE"
# Þ # Þ
"\u00DE" => "TH" "\u00DE" => "TH"
# Ù => U # Ù => U
"\u00D9" => "U" "\u00D9" => "U"
# Ú => U # Ú => U
"\u00DA" => "U" "\u00DA" => "U"
# Û => U # Û => U
"\u00DB" => "U" "\u00DB" => "U"
# Ü => U # Ü => U
"\u00DC" => "U" "\u00DC" => "U"
# Ý => Y # Ý => Y
"\u00DD" => "Y" "\u00DD" => "Y"
# Ÿ => Y # Ÿ => Y
"\u0178" => "Y" "\u0178" => "Y"
# à => a # à => a
"\u00E0" => "a" "\u00E0" => "a"
# á => a # á => a
"\u00E1" => "a" "\u00E1" => "a"
# â => a # â => a
"\u00E2" => "a" "\u00E2" => "a"
# ã => a # ã => a
"\u00E3" => "a" "\u00E3" => "a"
# ä => a # ä => a
"\u00E4" => "a" "\u00E4" => "a"
# å => a # å => a
"\u00E5" => "a" "\u00E5" => "a"
# æ => ae # æ => ae
"\u00E6" => "ae" "\u00E6" => "ae"
# ç => c # ç => c
"\u00E7" => "c" "\u00E7" => "c"
# è => e # è => e
"\u00E8" => "e" "\u00E8" => "e"
# é => e # é => e
"\u00E9" => "e" "\u00E9" => "e"
# ê => e # ê => e
"\u00EA" => "e" "\u00EA" => "e"
# ë => e # ë => e
"\u00EB" => "e" "\u00EB" => "e"
# ì => i # ì => i
"\u00EC" => "i" "\u00EC" => "i"
# í => i # í => i
"\u00ED" => "i" "\u00ED" => "i"
# î => i # î => i
"\u00EE" => "i" "\u00EE" => "i"
# ï => i # ï => i
"\u00EF" => "i" "\u00EF" => "i"
# ij => ij # ij => ij
"\u0133" => "ij" "\u0133" => "ij"
# ð => d # ð => d
"\u00F0" => "d" "\u00F0" => "d"
# ñ => n # ñ => n
"\u00F1" => "n" "\u00F1" => "n"
# ò => o # ò => o
"\u00F2" => "o" "\u00F2" => "o"
# ó => o # ó => o
"\u00F3" => "o" "\u00F3" => "o"
# ô => o # ô => o
"\u00F4" => "o" "\u00F4" => "o"
# õ => o # õ => o
"\u00F5" => "o" "\u00F5" => "o"
# ö => o # ö => o
"\u00F6" => "o" "\u00F6" => "o"
# ø => o # ø => o
"\u00F8" => "o" "\u00F8" => "o"
# œ => oe # œ => oe
"\u0153" => "oe" "\u0153" => "oe"
# ß => ss # ß => ss
"\u00DF" => "ss" "\u00DF" => "ss"
# þ => th # þ => th
"\u00FE" => "th" "\u00FE" => "th"
# ù => u # ù => u
"\u00F9" => "u" "\u00F9" => "u"
# ú => u # ú => u
"\u00FA" => "u" "\u00FA" => "u"
# û => u # û => u
"\u00FB" => "u" "\u00FB" => "u"
# ü => u # ü => u
"\u00FC" => "u" "\u00FC" => "u"
# ý => y # ý => y
"\u00FD" => "y" "\u00FD" => "y"
# ÿ => y # ÿ => y
"\u00FF" => "y" "\u00FF" => "y"
# ff => ff # ff => ff
"\uFB00" => "ff" "\uFB00" => "ff"
# fi => fi # fi => fi
"\uFB01" => "fi" "\uFB01" => "fi"
# fl => fl # fl => fl
"\uFB02" => "fl" "\uFB02" => "fl"
# ffi => ffi # ffi => ffi
"\uFB03" => "ffi" "\uFB03" => "ffi"
# ffl => ffl # ffl => ffl
"\uFB04" => "ffl" "\uFB04" => "ffl"
# ſt => ft # ſt => ft
"\uFB05" => "ft" "\uFB05" => "ft"
# st => st # st => st
"\uFB06" => "st" "\uFB06" => "st"

View file

@ -1,21 +1,21 @@
# The ASF licenses this file to You under the Apache License, Version 2.0 # The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with # (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at # the License. You may obtain a copy of the License at
# #
# http://www.apache.org/licenses/LICENSE-2.0 # http://www.apache.org/licenses/LICENSE-2.0
# #
# Unless required by applicable law or agreed to in writing, software # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
#----------------------------------------------------------------------- #-----------------------------------------------------------------------
# Use a protected word file to protect against the stemmer reducing two # Use a protected word file to protect against the stemmer reducing two
# unrelated words to the same base word. # unrelated words to the same base word.
# Some non-words that normally won't be encountered, # Some non-words that normally won't be encountered,
# just to test that they won't be stemmed. # just to test that they won't be stemmed.
dontstems dontstems
zwhacky zwhacky

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,2 +1,2 @@
pizza pizza
history history

View file

@ -1,58 +1,58 @@
# Licensed to the Apache Software Foundation (ASF) under one or more # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with # contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership. # this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0 # The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with # (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at # the License. You may obtain a copy of the License at
# #
# http://www.apache.org/licenses/LICENSE-2.0 # http://www.apache.org/licenses/LICENSE-2.0
# #
# Unless required by applicable law or agreed to in writing, software # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
#----------------------------------------------------------------------- #-----------------------------------------------------------------------
# a couple of test stopwords to test that the words are really being # a couple of test stopwords to test that the words are really being
# configured from this file: # configured from this file:
stopworda stopworda
stopwordb stopwordb
#Standard english stop words taken from Lucene's StopAnalyzer #Standard english stop words taken from Lucene's StopAnalyzer
a a
an an
and and
are are
as as
at at
be be
but but
by by
for for
if if
in in
into into
is is
it it
no no
not not
of of
on on
or or
s s
such such
t t
that that
the the
their their
then then
there there
these these
they they
this this
to to
was was
will will
with with

View file

@ -1,31 +1,29 @@
# The ASF licenses this file to You under the Apache License, Version 2.0 # The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with # (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at # the License. You may obtain a copy of the License at
# #
# http://www.apache.org/licenses/LICENSE-2.0 # http://www.apache.org/licenses/LICENSE-2.0
# #
# Unless required by applicable law or agreed to in writing, software # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
#----------------------------------------------------------------------- #-----------------------------------------------------------------------
#some test synonym mappings unlikely to appear in real input text #some test synonym mappings unlikely to appear in real input text
aaa => aaaa aaafoo => aaabar
bbb => bbbb1 bbbb2 bbbfoo => bbbfoo bbbbar
ccc => cccc1,cccc2 cccfoo => cccbar cccbaz
a\=>a => b\=>b fooaaa,baraaa,bazaaa
a\,a => b\,b
fooaaa,baraaa,bazaaa # Some synonym groups specific to this example
GB,gib,gigabyte,gigabytes
# Some synonym groups specific to this example MB,mib,megabyte,megabytes
GB,gib,gigabyte,gigabytes Television, Televisions, TV, TVs
MB,mib,megabyte,megabytes #notice we use "gib" instead of "GiB" so any WordDelimiterFilter coming
Television, Televisions, TV, TVs #after us won't split it into two words.
#notice we use "gib" instead of "GiB" so any WordDelimiterFilter coming
#after us won't split it into two words. # Synonym mappings can be used for spelling correction too
pixima => pixma
# Synonym mappings can be used for spelling correction too
pixima => pixma

View file

@ -1,132 +1,132 @@
<?xml version='1.0' encoding='UTF-8'?> <?xml version='1.0' encoding='UTF-8'?>
<!-- <!--
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
--> -->
<!-- <!--
Simple transform of Solr query results to HTML Simple transform of Solr query results to HTML
--> -->
<xsl:stylesheet version='1.0' <xsl:stylesheet version='1.0'
xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
> >
<xsl:output media-type="text/html; charset=UTF-8" encoding="UTF-8"/> <xsl:output media-type="text/html" encoding="UTF-8"/>
<xsl:variable name="title" select="concat('Solr search results (',response/result/@numFound,' documents)')"/> <xsl:variable name="title" select="concat('Solr search results (',response/result/@numFound,' documents)')"/>
<xsl:template match='/'> <xsl:template match='/'>
<html> <html>
<head> <head>
<title><xsl:value-of select="$title"/></title> <title><xsl:value-of select="$title"/></title>
<xsl:call-template name="css"/> <xsl:call-template name="css"/>
</head> </head>
<body> <body>
<h1><xsl:value-of select="$title"/></h1> <h1><xsl:value-of select="$title"/></h1>
<div class="note"> <div class="note">
This has been formatted by the sample "example.xsl" transform - This has been formatted by the sample "example.xsl" transform -
use your own XSLT to get a nicer page use your own XSLT to get a nicer page
</div> </div>
<xsl:apply-templates select="response/result/doc"/> <xsl:apply-templates select="response/result/doc"/>
</body> </body>
</html> </html>
</xsl:template> </xsl:template>
<xsl:template match="doc"> <xsl:template match="doc">
<xsl:variable name="pos" select="position()"/> <xsl:variable name="pos" select="position()"/>
<div class="doc"> <div class="doc">
<table width="100%"> <table width="100%">
<xsl:apply-templates> <xsl:apply-templates>
<xsl:with-param name="pos"><xsl:value-of select="$pos"/></xsl:with-param> <xsl:with-param name="pos"><xsl:value-of select="$pos"/></xsl:with-param>
</xsl:apply-templates> </xsl:apply-templates>
</table> </table>
</div> </div>
</xsl:template> </xsl:template>
<xsl:template match="doc/*[@name='score']" priority="100"> <xsl:template match="doc/*[@name='score']" priority="100">
<xsl:param name="pos"></xsl:param> <xsl:param name="pos"></xsl:param>
<tr> <tr>
<td class="name"> <td class="name">
<xsl:value-of select="@name"/> <xsl:value-of select="@name"/>
</td> </td>
<td class="value"> <td class="value">
<xsl:value-of select="."/> <xsl:value-of select="."/>
<xsl:if test="boolean(//lst[@name='explain'])"> <xsl:if test="boolean(//lst[@name='explain'])">
<xsl:element name="a"> <xsl:element name="a">
<!-- can't allow whitespace here --> <!-- can't allow whitespace here -->
<xsl:attribute name="href">javascript:toggle("<xsl:value-of select="concat('exp-',$pos)" />");</xsl:attribute>?</xsl:element> <xsl:attribute name="href">javascript:toggle("<xsl:value-of select="concat('exp-',$pos)" />");</xsl:attribute>?</xsl:element>
<br/> <br/>
<xsl:element name="div"> <xsl:element name="div">
<xsl:attribute name="class">exp</xsl:attribute> <xsl:attribute name="class">exp</xsl:attribute>
<xsl:attribute name="id"> <xsl:attribute name="id">
<xsl:value-of select="concat('exp-',$pos)" /> <xsl:value-of select="concat('exp-',$pos)" />
</xsl:attribute> </xsl:attribute>
<xsl:value-of select="//lst[@name='explain']/str[position()=$pos]"/> <xsl:value-of select="//lst[@name='explain']/str[position()=$pos]"/>
</xsl:element> </xsl:element>
</xsl:if> </xsl:if>
</td> </td>
</tr> </tr>
</xsl:template> </xsl:template>
<xsl:template match="doc/arr" priority="100"> <xsl:template match="doc/arr" priority="100">
<tr> <tr>
<td class="name"> <td class="name">
<xsl:value-of select="@name"/> <xsl:value-of select="@name"/>
</td> </td>
<td class="value"> <td class="value">
<ul> <ul>
<xsl:for-each select="*"> <xsl:for-each select="*">
<li><xsl:value-of select="."/></li> <li><xsl:value-of select="."/></li>
</xsl:for-each> </xsl:for-each>
</ul> </ul>
</td> </td>
</tr> </tr>
</xsl:template> </xsl:template>
<xsl:template match="doc/*"> <xsl:template match="doc/*">
<tr> <tr>
<td class="name"> <td class="name">
<xsl:value-of select="@name"/> <xsl:value-of select="@name"/>
</td> </td>
<td class="value"> <td class="value">
<xsl:value-of select="."/> <xsl:value-of select="."/>
</td> </td>
</tr> </tr>
</xsl:template> </xsl:template>
<xsl:template match="*"/> <xsl:template match="*"/>
<xsl:template name="css"> <xsl:template name="css">
<script> <script>
function toggle(id) { function toggle(id) {
var obj = document.getElementById(id); var obj = document.getElementById(id);
obj.style.display = (obj.style.display != 'block') ? 'block' : 'none'; obj.style.display = (obj.style.display != 'block') ? 'block' : 'none';
} }
</script> </script>
<style type="text/css"> <style type="text/css">
body { font-family: "Lucida Grande", sans-serif } body { font-family: "Lucida Grande", sans-serif }
td.name { font-style: italic; font-size:80%; } td.name { font-style: italic; font-size:80%; }
td { vertical-align: top; } td { vertical-align: top; }
ul { margin: 0px; margin-left: 1em; padding: 0px; } ul { margin: 0px; margin-left: 1em; padding: 0px; }
.note { font-size:80%; } .note { font-size:80%; }
.doc { margin-top: 1em; border-top: solid grey 1px; } .doc { margin-top: 1em; border-top: solid grey 1px; }
.exp { display: none; font-family: monospace; white-space: pre; } .exp { display: none; font-family: monospace; white-space: pre; }
</style> </style>
</xsl:template> </xsl:template>
</xsl:stylesheet> </xsl:stylesheet>

View file

@ -1,67 +1,67 @@
<?xml version='1.0' encoding='UTF-8'?> <?xml version='1.0' encoding='UTF-8'?>
<!-- <!--
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
--> -->
<!-- <!--
Simple transform of Solr query results to Atom Simple transform of Solr query results to Atom
--> -->
<xsl:stylesheet version='1.0' <xsl:stylesheet version='1.0'
xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:output <xsl:output
method="xml" method="xml"
encoding="utf-8" encoding="utf-8"
media-type="text/xml; charset=UTF-8" media-type="application/xml"
/> />
<xsl:template match='/'> <xsl:template match='/'>
<xsl:variable name="query" select="response/lst[@name='responseHeader']/lst[@name='params']/str[@name='q']"/> <xsl:variable name="query" select="response/lst[@name='responseHeader']/lst[@name='params']/str[@name='q']"/>
<feed xmlns="http://www.w3.org/2005/Atom"> <feed xmlns="http://www.w3.org/2005/Atom">
<title>Example Solr Atom 1.0 Feed</title> <title>Example Solr Atom 1.0 Feed</title>
<subtitle> <subtitle>
This has been formatted by the sample "example_atom.xsl" transform - This has been formatted by the sample "example_atom.xsl" transform -
use your own XSLT to get a nicer Atom feed. use your own XSLT to get a nicer Atom feed.
</subtitle> </subtitle>
<author> <author>
<name>Apache Solr</name> <name>Apache Solr</name>
<email>solr-user@lucene.apache.org</email> <email>solr-user@lucene.apache.org</email>
</author> </author>
<link rel="self" type="application/atom+xml" <link rel="self" type="application/atom+xml"
href="http://localhost:8983/solr/q={$query}&amp;wt=xslt&amp;tr=atom.xsl"/> href="http://localhost:8983/solr/q={$query}&amp;wt=xslt&amp;tr=atom.xsl"/>
<updated> <updated>
<xsl:value-of select="response/result/doc[position()=1]/date[@name='timestamp']"/> <xsl:value-of select="response/result/doc[position()=1]/date[@name='timestamp']"/>
</updated> </updated>
<id>tag:localhost,2007:example</id> <id>tag:localhost,2007:example</id>
<xsl:apply-templates select="response/result/doc"/> <xsl:apply-templates select="response/result/doc"/>
</feed> </feed>
</xsl:template> </xsl:template>
<!-- search results xslt --> <!-- search results xslt -->
<xsl:template match="doc"> <xsl:template match="doc">
<xsl:variable name="id" select="str[@name='id']"/> <xsl:variable name="id" select="str[@name='id']"/>
<entry> <entry>
<title><xsl:value-of select="str[@name='name']"/></title> <title><xsl:value-of select="str[@name='name']"/></title>
<link href="http://localhost:8983/solr/select?q={$id}"/> <link href="http://localhost:8983/solr/select?q={$id}"/>
<id>tag:localhost,2007:<xsl:value-of select="$id"/></id> <id>tag:localhost,2007:<xsl:value-of select="$id"/></id>
<summary><xsl:value-of select="arr[@name='features']"/></summary> <summary><xsl:value-of select="arr[@name='features']"/></summary>
<updated><xsl:value-of select="date[@name='timestamp']"/></updated> <updated><xsl:value-of select="date[@name='timestamp']"/></updated>
</entry> </entry>
</xsl:template> </xsl:template>
</xsl:stylesheet> </xsl:stylesheet>

View file

@ -1,66 +1,66 @@
<?xml version='1.0' encoding='UTF-8'?> <?xml version='1.0' encoding='UTF-8'?>
<!-- <!--
* Licensed to the Apache Software Foundation (ASF) under one or more * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
--> -->
<!-- <!--
Simple transform of Solr query results to RSS Simple transform of Solr query results to RSS
--> -->
<xsl:stylesheet version='1.0' <xsl:stylesheet version='1.0'
xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:output <xsl:output
method="xml" method="xml"
encoding="utf-8" encoding="utf-8"
media-type="text/xml; charset=UTF-8" media-type="application/xml"
/> />
<xsl:template match='/'> <xsl:template match='/'>
<rss version="2.0"> <rss version="2.0">
<channel> <channel>
<title>Example Solr RSS 2.0 Feed</title> <title>Example Solr RSS 2.0 Feed</title>
<link>http://localhost:8983/solr</link> <link>http://localhost:8983/solr</link>
<description> <description>
This has been formatted by the sample "example_rss.xsl" transform - This has been formatted by the sample "example_rss.xsl" transform -
use your own XSLT to get a nicer RSS feed. use your own XSLT to get a nicer RSS feed.
</description> </description>
<language>en-us</language> <language>en-us</language>
<docs>http://localhost:8983/solr</docs> <docs>http://localhost:8983/solr</docs>
<xsl:apply-templates select="response/result/doc"/> <xsl:apply-templates select="response/result/doc"/>
</channel> </channel>
</rss> </rss>
</xsl:template> </xsl:template>
<!-- search results xslt --> <!-- search results xslt -->
<xsl:template match="doc"> <xsl:template match="doc">
<xsl:variable name="id" select="str[@name='id']"/> <xsl:variable name="id" select="str[@name='id']"/>
<xsl:variable name="timestamp" select="date[@name='timestamp']"/> <xsl:variable name="timestamp" select="date[@name='timestamp']"/>
<item> <item>
<title><xsl:value-of select="str[@name='name']"/></title> <title><xsl:value-of select="str[@name='name']"/></title>
<link> <link>
http://localhost:8983/solr/select?q=id:<xsl:value-of select="$id"/> http://localhost:8983/solr/select?q=id:<xsl:value-of select="$id"/>
</link> </link>
<description> <description>
<xsl:value-of select="arr[@name='features']"/> <xsl:value-of select="arr[@name='features']"/>
</description> </description>
<pubDate><xsl:value-of select="$timestamp"/></pubDate> <pubDate><xsl:value-of select="$timestamp"/></pubDate>
<guid> <guid>
http://localhost:8983/solr/select?q=id:<xsl:value-of select="$id"/> http://localhost:8983/solr/select?q=id:<xsl:value-of select="$id"/>
</guid> </guid>
</item> </item>
</xsl:template> </xsl:template>
</xsl:stylesheet> </xsl:stylesheet>

View file

@ -1,337 +1,337 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!-- <!--
Licensed to the Apache Software Foundation (ASF) under one or more Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership. this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0 The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
--> -->
<!-- <!--
Display the luke request handler with graphs Display the luke request handler with graphs
--> -->
<xsl:stylesheet <xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml"
version="1.0" version="1.0"
> >
<xsl:output <xsl:output
method="html" method="html"
encoding="UTF-8" encoding="UTF-8"
media-type="text/html; charset=UTF-8" media-type="text/html"
doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
/> />
<xsl:variable name="title">Solr Luke Request Handler Response</xsl:variable> <xsl:variable name="title">Solr Luke Request Handler Response</xsl:variable>
<xsl:template match="/"> <xsl:template match="/">
<html xmlns="http://www.w3.org/1999/xhtml"> <html xmlns="http://www.w3.org/1999/xhtml">
<head> <head>
<link rel="stylesheet" type="text/css" href="solr-admin.css"/> <link rel="stylesheet" type="text/css" href="solr-admin.css"/>
<link rel="icon" href="favicon.ico" type="image/ico"/> <link rel="icon" href="favicon.ico" type="image/ico"/>
<link rel="shortcut icon" href="favicon.ico" type="image/ico"/> <link rel="shortcut icon" href="favicon.ico" type="image/ico"/>
<title> <title>
<xsl:value-of select="$title"/> <xsl:value-of select="$title"/>
</title> </title>
<xsl:call-template name="css"/> <xsl:call-template name="css"/>
</head> </head>
<body> <body>
<h1> <h1>
<xsl:value-of select="$title"/> <xsl:value-of select="$title"/>
</h1> </h1>
<div class="doc"> <div class="doc">
<ul> <ul>
<xsl:if test="response/lst[@name='index']"> <xsl:if test="response/lst[@name='index']">
<li> <li>
<a href="#index">Index Statistics</a> <a href="#index">Index Statistics</a>
</li> </li>
</xsl:if> </xsl:if>
<xsl:if test="response/lst[@name='fields']"> <xsl:if test="response/lst[@name='fields']">
<li> <li>
<a href="#fields">Field Statistics</a> <a href="#fields">Field Statistics</a>
<ul> <ul>
<xsl:for-each select="response/lst[@name='fields']/lst"> <xsl:for-each select="response/lst[@name='fields']/lst">
<li> <li>
<a href="#{@name}"> <a href="#{@name}">
<xsl:value-of select="@name"/> <xsl:value-of select="@name"/>
</a> </a>
</li> </li>
</xsl:for-each> </xsl:for-each>
</ul> </ul>
</li> </li>
</xsl:if> </xsl:if>
<xsl:if test="response/lst[@name='doc']"> <xsl:if test="response/lst[@name='doc']">
<li> <li>
<a href="#doc">Document statistics</a> <a href="#doc">Document statistics</a>
</li> </li>
</xsl:if> </xsl:if>
</ul> </ul>
</div> </div>
<xsl:if test="response/lst[@name='index']"> <xsl:if test="response/lst[@name='index']">
<h2><a name="index"/>Index Statistics</h2> <h2><a name="index"/>Index Statistics</h2>
<xsl:apply-templates select="response/lst[@name='index']"/> <xsl:apply-templates select="response/lst[@name='index']"/>
</xsl:if> </xsl:if>
<xsl:if test="response/lst[@name='fields']"> <xsl:if test="response/lst[@name='fields']">
<h2><a name="fields"/>Field Statistics</h2> <h2><a name="fields"/>Field Statistics</h2>
<xsl:apply-templates select="response/lst[@name='fields']"/> <xsl:apply-templates select="response/lst[@name='fields']"/>
</xsl:if> </xsl:if>
<xsl:if test="response/lst[@name='doc']"> <xsl:if test="response/lst[@name='doc']">
<h2><a name="doc"/>Document statistics</h2> <h2><a name="doc"/>Document statistics</h2>
<xsl:apply-templates select="response/lst[@name='doc']"/> <xsl:apply-templates select="response/lst[@name='doc']"/>
</xsl:if> </xsl:if>
</body> </body>
</html> </html>
</xsl:template> </xsl:template>
<xsl:template match="lst"> <xsl:template match="lst">
<xsl:if test="parent::lst"> <xsl:if test="parent::lst">
<tr> <tr>
<td colspan="2"> <td colspan="2">
<div class="doc"> <div class="doc">
<xsl:call-template name="list"/> <xsl:call-template name="list"/>
</div> </div>
</td> </td>
</tr> </tr>
</xsl:if> </xsl:if>
<xsl:if test="not(parent::lst)"> <xsl:if test="not(parent::lst)">
<div class="doc"> <div class="doc">
<xsl:call-template name="list"/> <xsl:call-template name="list"/>
</div> </div>
</xsl:if> </xsl:if>
</xsl:template> </xsl:template>
<xsl:template name="list"> <xsl:template name="list">
<xsl:if test="count(child::*)>0"> <xsl:if test="count(child::*)>0">
<table> <table>
<thead> <thead>
<tr> <tr>
<th colspan="2"> <th colspan="2">
<p> <p>
<a name="{@name}"/> <a name="{@name}"/>
</p> </p>
<xsl:value-of select="@name"/> <xsl:value-of select="@name"/>
</th> </th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<xsl:choose> <xsl:choose>
<xsl:when <xsl:when
test="@name='histogram'"> test="@name='histogram'">
<tr> <tr>
<td colspan="2"> <td colspan="2">
<xsl:call-template name="histogram"/> <xsl:call-template name="histogram"/>
</td> </td>
</tr> </tr>
</xsl:when> </xsl:when>
<xsl:otherwise> <xsl:otherwise>
<xsl:apply-templates/> <xsl:apply-templates/>
</xsl:otherwise> </xsl:otherwise>
</xsl:choose> </xsl:choose>
</tbody> </tbody>
</table> </table>
</xsl:if> </xsl:if>
</xsl:template> </xsl:template>
<xsl:template name="histogram"> <xsl:template name="histogram">
<div class="doc"> <div class="doc">
<xsl:call-template name="barchart"> <xsl:call-template name="barchart">
<xsl:with-param name="max_bar_width">50</xsl:with-param> <xsl:with-param name="max_bar_width">50</xsl:with-param>
<xsl:with-param name="iwidth">800</xsl:with-param> <xsl:with-param name="iwidth">800</xsl:with-param>
<xsl:with-param name="iheight">160</xsl:with-param> <xsl:with-param name="iheight">160</xsl:with-param>
<xsl:with-param name="fill">blue</xsl:with-param> <xsl:with-param name="fill">blue</xsl:with-param>
</xsl:call-template> </xsl:call-template>
</div> </div>
</xsl:template> </xsl:template>
<xsl:template name="barchart"> <xsl:template name="barchart">
<xsl:param name="max_bar_width"/> <xsl:param name="max_bar_width"/>
<xsl:param name="iwidth"/> <xsl:param name="iwidth"/>
<xsl:param name="iheight"/> <xsl:param name="iheight"/>
<xsl:param name="fill"/> <xsl:param name="fill"/>
<xsl:variable name="max"> <xsl:variable name="max">
<xsl:for-each select="int"> <xsl:for-each select="int">
<xsl:sort data-type="number" order="descending"/> <xsl:sort data-type="number" order="descending"/>
<xsl:if test="position()=1"> <xsl:if test="position()=1">
<xsl:value-of select="."/> <xsl:value-of select="."/>
</xsl:if> </xsl:if>
</xsl:for-each> </xsl:for-each>
</xsl:variable> </xsl:variable>
<xsl:variable name="bars"> <xsl:variable name="bars">
<xsl:value-of select="count(int)"/> <xsl:value-of select="count(int)"/>
</xsl:variable> </xsl:variable>
<xsl:variable name="bar_width"> <xsl:variable name="bar_width">
<xsl:choose> <xsl:choose>
<xsl:when test="$max_bar_width &lt; ($iwidth div $bars)"> <xsl:when test="$max_bar_width &lt; ($iwidth div $bars)">
<xsl:value-of select="$max_bar_width"/> <xsl:value-of select="$max_bar_width"/>
</xsl:when> </xsl:when>
<xsl:otherwise> <xsl:otherwise>
<xsl:value-of select="$iwidth div $bars"/> <xsl:value-of select="$iwidth div $bars"/>
</xsl:otherwise> </xsl:otherwise>
</xsl:choose> </xsl:choose>
</xsl:variable> </xsl:variable>
<table class="histogram"> <table class="histogram">
<tbody> <tbody>
<tr> <tr>
<xsl:for-each select="int"> <xsl:for-each select="int">
<td> <td>
<xsl:value-of select="."/> <xsl:value-of select="."/>
<div class="histogram"> <div class="histogram">
<xsl:attribute name="style">background-color: <xsl:value-of select="$fill"/>; width: <xsl:value-of select="$bar_width"/>px; height: <xsl:value-of select="($iheight*number(.)) div $max"/>px;</xsl:attribute> <xsl:attribute name="style">background-color: <xsl:value-of select="$fill"/>; width: <xsl:value-of select="$bar_width"/>px; height: <xsl:value-of select="($iheight*number(.)) div $max"/>px;</xsl:attribute>
</div> </div>
</td> </td>
</xsl:for-each> </xsl:for-each>
</tr> </tr>
<tr> <tr>
<xsl:for-each select="int"> <xsl:for-each select="int">
<td> <td>
<xsl:value-of select="@name"/> <xsl:value-of select="@name"/>
</td> </td>
</xsl:for-each> </xsl:for-each>
</tr> </tr>
</tbody> </tbody>
</table> </table>
</xsl:template> </xsl:template>
<xsl:template name="keyvalue"> <xsl:template name="keyvalue">
<xsl:choose> <xsl:choose>
<xsl:when test="@name"> <xsl:when test="@name">
<tr> <tr>
<td class="name"> <td class="name">
<xsl:value-of select="@name"/> <xsl:value-of select="@name"/>
</td> </td>
<td class="value"> <td class="value">
<xsl:value-of select="."/> <xsl:value-of select="."/>
</td> </td>
</tr> </tr>
</xsl:when> </xsl:when>
<xsl:otherwise> <xsl:otherwise>
<xsl:value-of select="."/> <xsl:value-of select="."/>
</xsl:otherwise> </xsl:otherwise>
</xsl:choose> </xsl:choose>
</xsl:template> </xsl:template>
<xsl:template match="int|bool|long|float|double|uuid|date"> <xsl:template match="int|bool|long|float|double|uuid|date">
<xsl:call-template name="keyvalue"/> <xsl:call-template name="keyvalue"/>
</xsl:template> </xsl:template>
<xsl:template match="arr"> <xsl:template match="arr">
<tr> <tr>
<td class="name"> <td class="name">
<xsl:value-of select="@name"/> <xsl:value-of select="@name"/>
</td> </td>
<td class="value"> <td class="value">
<ul> <ul>
<xsl:for-each select="child::*"> <xsl:for-each select="child::*">
<li> <li>
<xsl:apply-templates/> <xsl:apply-templates/>
</li> </li>
</xsl:for-each> </xsl:for-each>
</ul> </ul>
</td> </td>
</tr> </tr>
</xsl:template> </xsl:template>
<xsl:template match="str"> <xsl:template match="str">
<xsl:choose> <xsl:choose>
<xsl:when test="@name='schema' or @name='index' or @name='flags'"> <xsl:when test="@name='schema' or @name='index' or @name='flags'">
<xsl:call-template name="schema"/> <xsl:call-template name="schema"/>
</xsl:when> </xsl:when>
<xsl:otherwise> <xsl:otherwise>
<xsl:call-template name="keyvalue"/> <xsl:call-template name="keyvalue"/>
</xsl:otherwise> </xsl:otherwise>
</xsl:choose> </xsl:choose>
</xsl:template> </xsl:template>
<xsl:template name="schema"> <xsl:template name="schema">
<tr> <tr>
<td class="name"> <td class="name">
<xsl:value-of select="@name"/> <xsl:value-of select="@name"/>
</td> </td>
<td class="value"> <td class="value">
<xsl:if test="contains(.,'unstored')"> <xsl:if test="contains(.,'unstored')">
<xsl:value-of select="."/> <xsl:value-of select="."/>
</xsl:if> </xsl:if>
<xsl:if test="not(contains(.,'unstored'))"> <xsl:if test="not(contains(.,'unstored'))">
<xsl:call-template name="infochar2string"> <xsl:call-template name="infochar2string">
<xsl:with-param name="charList"> <xsl:with-param name="charList">
<xsl:value-of select="."/> <xsl:value-of select="."/>
</xsl:with-param> </xsl:with-param>
</xsl:call-template> </xsl:call-template>
</xsl:if> </xsl:if>
</td> </td>
</tr> </tr>
</xsl:template> </xsl:template>
<xsl:template name="infochar2string"> <xsl:template name="infochar2string">
<xsl:param name="i">1</xsl:param> <xsl:param name="i">1</xsl:param>
<xsl:param name="charList"/> <xsl:param name="charList"/>
<xsl:variable name="char"> <xsl:variable name="char">
<xsl:value-of select="substring($charList,$i,1)"/> <xsl:value-of select="substring($charList,$i,1)"/>
</xsl:variable> </xsl:variable>
<xsl:choose> <xsl:choose>
<xsl:when test="$char='I'"> <xsl:when test="$char='I'">
<xsl:value-of select="/response/lst[@name='info']/lst/str[@name='I']"/> - </xsl:when> <xsl:value-of select="/response/lst[@name='info']/lst/str[@name='I']"/> - </xsl:when>
<xsl:when test="$char='T'"> <xsl:when test="$char='T'">
<xsl:value-of select="/response/lst[@name='info']/lst/str[@name='T']"/> - </xsl:when> <xsl:value-of select="/response/lst[@name='info']/lst/str[@name='T']"/> - </xsl:when>
<xsl:when test="$char='S'"> <xsl:when test="$char='S'">
<xsl:value-of select="/response/lst[@name='info']/lst/str[@name='S']"/> - </xsl:when> <xsl:value-of select="/response/lst[@name='info']/lst/str[@name='S']"/> - </xsl:when>
<xsl:when test="$char='M'"> <xsl:when test="$char='M'">
<xsl:value-of select="/response/lst[@name='info']/lst/str[@name='M']"/> - </xsl:when> <xsl:value-of select="/response/lst[@name='info']/lst/str[@name='M']"/> - </xsl:when>
<xsl:when test="$char='V'"> <xsl:when test="$char='V'">
<xsl:value-of select="/response/lst[@name='info']/lst/str[@name='V']"/> - </xsl:when> <xsl:value-of select="/response/lst[@name='info']/lst/str[@name='V']"/> - </xsl:when>
<xsl:when test="$char='o'"> <xsl:when test="$char='o'">
<xsl:value-of select="/response/lst[@name='info']/lst/str[@name='o']"/> - </xsl:when> <xsl:value-of select="/response/lst[@name='info']/lst/str[@name='o']"/> - </xsl:when>
<xsl:when test="$char='p'"> <xsl:when test="$char='p'">
<xsl:value-of select="/response/lst[@name='info']/lst/str[@name='p']"/> - </xsl:when> <xsl:value-of select="/response/lst[@name='info']/lst/str[@name='p']"/> - </xsl:when>
<xsl:when test="$char='O'"> <xsl:when test="$char='O'">
<xsl:value-of select="/response/lst[@name='info']/lst/str[@name='O']"/> - </xsl:when> <xsl:value-of select="/response/lst[@name='info']/lst/str[@name='O']"/> - </xsl:when>
<xsl:when test="$char='L'"> <xsl:when test="$char='L'">
<xsl:value-of select="/response/lst[@name='info']/lst/str[@name='L']"/> - </xsl:when> <xsl:value-of select="/response/lst[@name='info']/lst/str[@name='L']"/> - </xsl:when>
<xsl:when test="$char='B'"> <xsl:when test="$char='B'">
<xsl:value-of select="/response/lst[@name='info']/lst/str[@name='B']"/> - </xsl:when> <xsl:value-of select="/response/lst[@name='info']/lst/str[@name='B']"/> - </xsl:when>
<xsl:when test="$char='C'"> <xsl:when test="$char='C'">
<xsl:value-of select="/response/lst[@name='info']/lst/str[@name='C']"/> - </xsl:when> <xsl:value-of select="/response/lst[@name='info']/lst/str[@name='C']"/> - </xsl:when>
<xsl:when test="$char='f'"> <xsl:when test="$char='f'">
<xsl:value-of select="/response/lst[@name='info']/lst/str[@name='f']"/> - </xsl:when> <xsl:value-of select="/response/lst[@name='info']/lst/str[@name='f']"/> - </xsl:when>
<xsl:when test="$char='l'"> <xsl:when test="$char='l'">
<xsl:value-of select="/response/lst[@name='info']/lst/str[@name='l']"/> - <xsl:value-of select="/response/lst[@name='info']/lst/str[@name='l']"/> -
</xsl:when> </xsl:when>
</xsl:choose> </xsl:choose>
<xsl:if test="not($i>=string-length($charList))"> <xsl:if test="not($i>=string-length($charList))">
<xsl:call-template name="infochar2string"> <xsl:call-template name="infochar2string">
<xsl:with-param name="i"> <xsl:with-param name="i">
<xsl:value-of select="$i+1"/> <xsl:value-of select="$i+1"/>
</xsl:with-param> </xsl:with-param>
<xsl:with-param name="charList"> <xsl:with-param name="charList">
<xsl:value-of select="$charList"/> <xsl:value-of select="$charList"/>
</xsl:with-param> </xsl:with-param>
</xsl:call-template> </xsl:call-template>
</xsl:if> </xsl:if>
</xsl:template> </xsl:template>
<xsl:template name="css"> <xsl:template name="css">
<style type="text/css"> <style type="text/css">
<![CDATA[ <![CDATA[
td.name {font-style: italic; font-size:80%; } td.name {font-style: italic; font-size:80%; }
.doc { margin: 0.5em; border: solid grey 1px; } .doc { margin: 0.5em; border: solid grey 1px; }
.exp { display: none; font-family: monospace; white-space: pre; } .exp { display: none; font-family: monospace; white-space: pre; }
div.histogram { background: none repeat scroll 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;} div.histogram { background: none repeat scroll 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;}
table.histogram { width: auto; vertical-align: bottom; } table.histogram { width: auto; vertical-align: bottom; }
table.histogram td, table.histogram th { text-align: center; vertical-align: bottom; border-bottom: 1px solid #ff9933; width: auto; } table.histogram td, table.histogram th { text-align: center; vertical-align: bottom; border-bottom: 1px solid #ff9933; width: auto; }
]]> ]]>
</style> </style>
</xsl:template> </xsl:template>
</xsl:stylesheet> </xsl:stylesheet>

34
solr/exampleSolr/solr.xml Normal file
View file

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!--
All (relative) paths are relative to the installation path
persistent: Save changes made via the API to this file
sharedLib: path to a lib directory that will be shared across all cores
-->
<solr persistent="false">
<!--
adminPath: RequestHandler path to manage cores.
If 'null' (or absent), cores will not be manageable via request handler
-->
<cores adminPath="/admin/cores" defaultCoreName="collection1">
<core name="collection1" instanceDir="." />
</cores>
</solr>

View file

@ -143,18 +143,20 @@
<listener-class> edu.cornell.mannlib.vitro.webapp.search.lucene.LuceneSetup </listener-class> <listener-class> edu.cornell.mannlib.vitro.webapp.search.lucene.LuceneSetup </listener-class>
</listener> </listener>
<!--<listener> <!--
<listener-class> <listener>
edu.cornell.mannlib.vitro.webapp.auth.policy.setup.SelfEditingPolicySetup <listener-class>
</listener-class> edu.cornell.mannlib.vitro.webapp.search.solr.SolrSetup
</listener> --> </listener-class>
</listener>
<listener> -->
<listener-class>
edu.cornell.mannlib.vitro.webapp.auth.identifier.UserToIndIdentifierFactorySetup <!--<listener>
</listener-class> <listener-class>
</listener> edu.cornell.mannlib.vitro.webapp.auth.policy.setup.SelfEditingPolicySetup
</listener-class>
</listener> -->
<listener> <listener>
<listener-class> edu.cornell.mannlib.vitro.webapp.auth.policy.setup.EditorEditingPolicySetup <listener-class> edu.cornell.mannlib.vitro.webapp.auth.policy.setup.EditorEditingPolicySetup
</listener-class> </listener-class>
@ -890,7 +892,13 @@
<servlet> <servlet>
<servlet-name>SearchController</servlet-name> <servlet-name>SearchController</servlet-name>
<servlet-class>edu.cornell.mannlib.vitro.webapp.search.controller.PagedSearchController</servlet-class> <servlet-class>edu.cornell.mannlib.vitro.webapp.search.controller.PagedSearchController</servlet-class>
</servlet>
<!--
<servlet>
<servlet-name>SearchController</servlet-name>
<servlet-class>edu.cornell.mannlib.vitro.webapp.search.controller.SolrPagedSearchController</servlet-class>
</servlet> </servlet>
-->
<servlet-mapping> <servlet-mapping>
<servlet-name>SearchController</servlet-name> <servlet-name>SearchController</servlet-name>
<url-pattern>/search</url-pattern> <url-pattern>/search</url-pattern>
@ -913,6 +921,12 @@
<servlet-name>AutocompleteController</servlet-name> <servlet-name>AutocompleteController</servlet-name>
<servlet-class>edu.cornell.mannlib.vitro.webapp.search.controller.AutocompleteController</servlet-class> <servlet-class>edu.cornell.mannlib.vitro.webapp.search.controller.AutocompleteController</servlet-class>
</servlet> </servlet>
<!--
<servlet>
<servlet-name>AutocompleteController</servlet-name>
<servlet-class>edu.cornell.mannlib.vitro.webapp.search.controller.SolrAutocompleteController</servlet-class>
</servlet>
-->
<servlet-mapping> <servlet-mapping>
<servlet-name>AutocompleteController</servlet-name> <servlet-name>AutocompleteController</servlet-name>
<url-pattern>/autocomplete</url-pattern> <url-pattern>/autocomplete</url-pattern>
@ -962,6 +976,12 @@
<servlet-name>JSON Service</servlet-name> <servlet-name>JSON Service</servlet-name>
<servlet-class>edu.cornell.mannlib.vitro.webapp.controller.JSONServlet</servlet-class> <servlet-class>edu.cornell.mannlib.vitro.webapp.controller.JSONServlet</servlet-class>
</servlet> </servlet>
<!--
<servlet>
<servlet-name>JSON Service</servlet-name>
<servlet-class>edu.cornell.mannlib.vitro.webapp.controller.SolrJsonServlet</servlet-class>
</servlet>
-->
<servlet-mapping> <servlet-mapping>
<servlet-name>JSON Service</servlet-name> <servlet-name>JSON Service</servlet-name>
<url-pattern>/dataservice</url-pattern> <url-pattern>/dataservice</url-pattern>

Binary file not shown.

Binary file not shown.

View file

@ -1,25 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.identifier;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
/**
* The current user has this RoleLevel.
*/
public class HasRoleLevel implements Identifier {
private final RoleLevel roleLevel;
public HasRoleLevel(RoleLevel roleLevel) {
this.roleLevel = roleLevel;
}
public RoleLevel getRoleLevel() {
return roleLevel;
}
@Override
public String toString() {
return "HasRoleLevel[" + roleLevel + "]";
}
}

View file

@ -1,58 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.identifier;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import edu.cornell.mannlib.vitro.webapp.auth.policy.RoleBasedPolicy.AuthRole;
import edu.cornell.mannlib.vitro.webapp.beans.User;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
/**
* Checks to see if the Individual associated with a SelfEditingIdentifier
* has Admin, Curator or Editor rights. This ignores black listing.
*
* This should be added to the IdentifierFactory list after the
* SelfEditingIdentiferFactory.
*
* SelfEditing2RoleIdentifierSetup can be used in web.xml to add this class
* to the IdentifierFactory list of a servlet context.
*
* @author bdc34
*
*/
public class SelfEditing2RoleIdentifierFactory implements
IdentifierBundleFactory {
@Override
public IdentifierBundle getIdentifierBundle(ServletRequest request,
HttpSession session, ServletContext context) {
IdentifierBundle whoToAuth = RequestIdentifiers.getIdBundleForRequest(request);
WebappDaoFactory wdf = (WebappDaoFactory)context.getAttribute("webappDaoFactory");
if( wdf == null )
return whoToAuth;
SelfEditingIdentifierFactory.SelfEditing selfEditing =
SelfEditingIdentifierFactory.getSelfEditingIdentifier(whoToAuth);
if( selfEditing != null ){
User user = wdf.getUserDao().getUserByURI(selfEditing.getIndividual().getURI());
if( user != null){
String role = user.getRoleURI();
if("role/:50".equals(role)){
whoToAuth.add( AuthRole.DBA );
}
if("role/:4".equals(role)){
whoToAuth.add( AuthRole.CURATOR);
}
if("role/:3".equals(role)){
whoToAuth.add( AuthRole.EDITOR);
}
if("role/:2".equals(role)){
whoToAuth.add( AuthRole.USER );
}
}
}
return whoToAuth;
}
}

View file

@ -16,7 +16,6 @@ import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QueryExecutionFactory;
@ -31,7 +30,6 @@ import com.hp.hpl.jena.rdf.model.Resource;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean; import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.SelfEditingConfiguration; import edu.cornell.mannlib.vitro.webapp.beans.SelfEditingConfiguration;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao; import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
@ -44,6 +42,7 @@ public class SelfEditingIdentifierFactory implements IdentifierBundleFactory {
private static final int MAXIMUM_USERNAME_LENGTH = 100; private static final int MAXIMUM_USERNAME_LENGTH = 100;
@Override
public IdentifierBundle getIdentifierBundle(ServletRequest request, public IdentifierBundle getIdentifierBundle(ServletRequest request,
HttpSession session, ServletContext context) { HttpSession session, ServletContext context) {
if (!(request instanceof HttpServletRequest)) { if (!(request instanceof HttpServletRequest)) {
@ -202,7 +201,8 @@ public class SelfEditingIdentifierFactory implements IdentifierBundleFactory {
log.debug("checking directlry " + realPath + " for blacklisting sparql query files"); log.debug("checking directlry " + realPath + " for blacklisting sparql query files");
File[] files = blacklistDir.listFiles(new FileFilter(){ File[] files = blacklistDir.listFiles(new FileFilter(){
public boolean accept(File pathname) { @Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".sparql"); return pathname.getName().endsWith(".sparql");
}} }}
); );

View file

@ -1,96 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.identifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
/**
* Check to see if the User is logged in, find Individuals that the User mayEditAs,
* and and those Individuals as identifiers.
*
* @author bdc34
*
*/
public class UserToIndIdentifierFactory implements IdentifierBundleFactory {
public IdentifierBundle getIdentifierBundle(
ServletRequest request,
HttpSession session,
ServletContext context) {
// is the request logged in as a User?
LoginStatusBean loginBean = LoginStatusBean.getBean(session);
if (loginBean.isLoggedIn()) {
String userURI = loginBean.getUserURI();
WebappDaoFactory wdf = (WebappDaoFactory)context.getAttribute("webappDaoFactory");
// get Individuals that the User mayEditAs
List<String> mayEditAsUris =
wdf.getUserDao().getIndividualsUserMayEditAs(userURI);
// make self editing Identifiers for those Individuals
IdentifierBundle idb = new ArrayIdentifierBundle();
idb.add( new UserIdentifier(userURI,mayEditAsUris) );
//Also make a self-editing identifier.
//There is not need for SelfEditingIdentifierFactory because SelfEditing
//identifiers are created here.
for( String personUri : mayEditAsUris){
if( personUri != null ){
Individual person = wdf.getIndividualDao().getIndividualByURI(personUri);
if( person != null ){
idb.add( new SelfEditingIdentifierFactory.SelfEditing(person,null) );
}
}
}
return idb;
}
return null;
}
public static List<String> getIndividualsForUser(IdentifierBundle ids) {
if( ids == null )
return Collections.emptyList();
//find the user id
List<String> uris = new ArrayList<String>();
for( Identifier id : ids ){
if( id instanceof UserIdentifier){
uris.addAll( ((UserIdentifier)id).getMayEditAsURIs() );
}
}
return uris;
}
public class UserIdentifier implements Identifier {
private final String userURI;
private final List<String> mayEditAsURIs;
public UserIdentifier(String userURI, List<String> mayEditAsURIs) {
super();
this.userURI = userURI;
this.mayEditAsURIs = Collections.unmodifiableList(mayEditAsURIs);
}
public String getUserURI() {
return userURI;
}
public List<String> getMayEditAsURIs() {
return mayEditAsURIs;
}
@Override
public String toString() {
return "UserIdentifier: " + userURI;
}
}
}

View file

@ -1,40 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.identifier;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.servlet.setup.AbortStartup;
/**
* Setups context so that Identifiers for Individuals associated with Users are
* added to requests.
*
* This only adds identifiers. A self-editing policy is also needed.
*
* @author bdc34
*
*/
public class UserToIndIdentifierFactorySetup implements ServletContextListener{
private static final Log log = LogFactory.getLog(UserToIndIdentifierFactorySetup.class.getName());
@Override
public void contextInitialized(ServletContextEvent sce) {
if (AbortStartup.isStartupAborted(sce.getServletContext())) {
return;
}
ActiveIdentifierBundleFactories.addFactory(sce, new UserToIndIdentifierFactory());
log.info("Set up Identifier Factory UserToIndIdentifierFactory.");
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// Nothing to do.
}
}

View file

@ -0,0 +1,27 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.identifier.common;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
/**
* A base class for the Identifiers created by the
* CommonIdentifierBundleFactory.
*/
public abstract class AbstractCommonIdentifier {
protected static <T> Collection<T> getIdentifiersForClass(
IdentifierBundle ids, Class<T> clazz) {
Set<T> set = new HashSet<T>();
for (Identifier id : ids) {
if (clazz.isAssignableFrom(id.getClass())) {
set.add(clazz.cast(id));
}
}
return set;
}
}

View file

@ -1,6 +1,6 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.identifier; package edu.cornell.mannlib.vitro.webapp.auth.identifier.common;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -16,6 +16,10 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean; import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.ArrayIdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundleFactory;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel; import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.SelfEditingConfiguration; import edu.cornell.mannlib.vitro.webapp.beans.SelfEditingConfiguration;
@ -29,26 +33,46 @@ public class CommonIdentifierBundleFactory implements IdentifierBundleFactory {
private static final Log log = LogFactory private static final Log log = LogFactory
.getLog(CommonIdentifierBundleFactory.class); .getLog(CommonIdentifierBundleFactory.class);
private final ServletContext context;
public CommonIdentifierBundleFactory(ServletContext context) {
this.context = context;
}
@Override @Override
public IdentifierBundle getIdentifierBundle(ServletRequest request, public IdentifierBundle getIdentifierBundle(ServletRequest request,
HttpSession session, ServletContext context) { HttpSession session, ServletContext unusedContext) {
// If this is not an HttpServletRequest, we might as well fail now. // If this is not an HttpServletRequest, we might as well fail now.
HttpServletRequest req = (HttpServletRequest) request; HttpServletRequest req = (HttpServletRequest) request;
ArrayIdentifierBundle bundle = new ArrayIdentifierBundle(); ArrayIdentifierBundle bundle = new ArrayIdentifierBundle();
bundle.addAll(determineRoleLevelIdentifiers(req)); bundle.addAll(createUserIdentifiers(req));
bundle.addAll(determineAssociatedIndividualIdentifiers(req)); bundle.addAll(createRoleLevelIdentifiers(req));
bundle.addAll(createBlacklistOrAssociatedIndividualIdentifiers(req));
return bundle; return bundle;
} }
/**
* If the user is logged in, create an identifier that shows his URI.
*/
private Collection<? extends Identifier> createUserIdentifiers(
HttpServletRequest req) {
LoginStatusBean bean = LoginStatusBean.getBean(req);
if (bean.isLoggedIn()) {
return Collections.singleton(new IsUser(bean.getUserURI()));
} else {
return Collections.emptySet();
}
}
/** /**
* Create an identifier that shows the role level of the current user, or * Create an identifier that shows the role level of the current user, or
* PUBLIC if the user is not logged in. * PUBLIC if the user is not logged in.
*/ */
private Collection<? extends Identifier> determineRoleLevelIdentifiers( private Collection<? extends Identifier> createRoleLevelIdentifiers(
HttpServletRequest req) { HttpServletRequest req) {
RoleLevel roleLevel = RoleLevel.getRoleFromLoginStatus(req); RoleLevel roleLevel = RoleLevel.getRoleFromLoginStatus(req);
return Collections.singleton(new HasRoleLevel(roleLevel)); return Collections.singleton(new HasRoleLevel(roleLevel));
@ -56,37 +80,48 @@ public class CommonIdentifierBundleFactory implements IdentifierBundleFactory {
/** /**
* Find all of the individuals that are associated with the current user, * Find all of the individuals that are associated with the current user,
* and create an Identifier for each one. * and create either an IsBlacklisted or HasAssociatedIndividual for each
* one.
*/ */
private Collection<? extends Identifier> determineAssociatedIndividualIdentifiers( private Collection<? extends Identifier> createBlacklistOrAssociatedIndividualIdentifiers(
HttpServletRequest req) { HttpServletRequest req) {
Collection<Identifier> ids = new ArrayList<Identifier>(); Collection<Identifier> ids = new ArrayList<Identifier>();
for (Individual ind : getAssociatedIndividuals(req)) {
// If they are blacklisted, this factory will return an identifier
Identifier id = IsBlacklisted.getInstance(ind, context);
if (id != null) {
ids.add(id);
} else {
ids.add(new HasAssociatedIndividual(ind.getURI()));
}
}
return ids;
}
private Collection<Individual> getAssociatedIndividuals(
HttpServletRequest req) {
Collection<Individual> individuals = new ArrayList<Individual>();
LoginStatusBean bean = LoginStatusBean.getBean(req); LoginStatusBean bean = LoginStatusBean.getBean(req);
String username = bean.getUsername(); String username = bean.getUsername();
if (!bean.isLoggedIn()) { if (!bean.isLoggedIn()) {
log.debug("No SelfEditing: not logged in."); log.debug("No Associated Individuals: not logged in.");
return ids; return individuals;
} }
if (StringUtils.isEmpty(username)) { if (StringUtils.isEmpty(username)) {
log.debug("No SelfEditing: username is empty."); log.debug("No Associated Individuals: username is empty.");
return ids; return individuals;
} }
HttpSession session = req.getSession(false);
if (session == null) {
log.debug("No SelfEditing: session is null.");
return ids;
}
ServletContext context = session.getServletContext();
WebappDaoFactory wdf = (WebappDaoFactory) context WebappDaoFactory wdf = (WebappDaoFactory) context
.getAttribute("webappDaoFactory"); .getAttribute("webappDaoFactory");
if (wdf == null) { if (wdf == null) {
log.error("Could not get a WebappDaoFactory from the ServletContext"); log.error("Could not get a WebappDaoFactory from the ServletContext");
return ids; return individuals;
} }
IndividualDao indDao = wdf.getIndividualDao(); IndividualDao indDao = wdf.getIndividualDao();
@ -96,22 +131,18 @@ public class CommonIdentifierBundleFactory implements IdentifierBundleFactory {
if (uri == null) { if (uri == null) {
log.debug("Could not find an Individual with a netId of " log.debug("Could not find an Individual with a netId of "
+ username); + username);
return ids; return individuals;
} }
Individual ind = indDao.getIndividualByURI(uri); Individual ind = indDao.getIndividualByURI(uri);
if (ind == null) { if (ind == null) {
log.warn("Found a URI for the netId " + username log.warn("Found a URI for the netId " + username
+ " but could not build Individual"); + " but could not build Individual");
return ids; return individuals;
} }
log.debug("Found an Individual for netId " + username + " URI: " + uri); log.debug("Found an Individual for netId " + username + " URI: " + uri);
// Use the factory method to fill in the Blacklisting reason, if there individuals.add(ind);
// is one. return individuals;
ids.add(HasAssociatedIndividual.getInstance(ind, context));
return ids;
} }
} }

View file

@ -0,0 +1,48 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.identifier.common;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
/**
* The current user is associated with this Individual.
*
* This includes a thick factory method that will look through a directory of
* files to determine whether the associated individual is blacklisted.
*/
public class HasAssociatedIndividual extends AbstractCommonIdentifier implements
Identifier {
public static Collection<HasAssociatedIndividual> getIdentifiers(
IdentifierBundle ids) {
return getIdentifiersForClass(ids, HasAssociatedIndividual.class);
}
public static Collection<String> getIndividualUris(IdentifierBundle ids) {
Set<String> set = new HashSet<String>();
for (HasAssociatedIndividual id : getIdentifiers(ids)) {
set.add(id.getAssociatedIndividualUri());
}
return set;
}
private final String associatedIndividualUri;
public HasAssociatedIndividual(String associatedIndividualUri) {
this.associatedIndividualUri = associatedIndividualUri;
}
public String getAssociatedIndividualUri() {
return associatedIndividualUri;
}
@Override
public String toString() {
return "HasAssociatedIndividual['" + associatedIndividualUri + "']";
}
}

View file

@ -0,0 +1,52 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.identifier.common;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
/**
* The current user has this RoleLevel.
*/
public class HasRoleLevel extends AbstractCommonIdentifier implements Identifier {
public static Collection<HasRoleLevel> getIdentifiers(IdentifierBundle ids) {
return getIdentifiersForClass(ids, HasRoleLevel.class);
}
public static Collection<String> getRoleLevelUris(IdentifierBundle ids) {
Set<String> set = new HashSet<String>();
for (HasRoleLevel id : getIdentifiers(ids)) {
set.add(id.getRoleLevel().getURI());
}
return set;
}
public static RoleLevel getUsersRoleLevel(IdentifierBundle whoToAuth) {
Collection<HasRoleLevel> roleIds = getIdentifiers(whoToAuth);
if (roleIds.isEmpty()) {
return RoleLevel.PUBLIC;
} else {
return roleIds.iterator().next().getRoleLevel();
}
}
private final RoleLevel roleLevel;
public HasRoleLevel(RoleLevel roleLevel) {
this.roleLevel = roleLevel;
}
public RoleLevel getRoleLevel() {
return roleLevel;
}
@Override
public String toString() {
return "HasRoleLevel[" + roleLevel + "]";
}
}

View file

@ -1,11 +1,14 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.identifier; package edu.cornell.mannlib.vitro.webapp.auth.identifier.common;
import java.io.File; import java.io.File;
import java.io.FileFilter; import java.io.FileFilter;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
@ -22,17 +25,16 @@ import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.RDFNode;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.Individual;
/** /**
* The current user is associated with this Individual. * The current user is blacklisted for this reason.
*
* This includes a thick factory method that will look through a directory of
* files to determine whether the associated individual is blacklisted.
*/ */
public class HasAssociatedIndividual implements Identifier { public class IsBlacklisted extends AbstractCommonIdentifier implements
private static final Log log = LogFactory Identifier {
.getLog(HasAssociatedIndividual.class); private static final Log log = LogFactory.getLog(IsBlacklisted.class);
private final static String BLACKLIST_SPARQL_DIR = "/admin/selfEditBlacklist"; private final static String BLACKLIST_SPARQL_DIR = "/admin/selfEditBlacklist";
private static final String NOT_BLACKLISTED = null; private static final String NOT_BLACKLISTED = null;
@ -41,7 +43,11 @@ public class HasAssociatedIndividual implements Identifier {
// static methods // static methods
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
public static HasAssociatedIndividual getInstance(Individual individual, /**
* If this individual is blacklisted, return an appropriate Identifier.
* Otherwise, return null.
*/
public static IsBlacklisted getInstance(Individual individual,
ServletContext context) { ServletContext context) {
if (individual == null) { if (individual == null) {
throw new NullPointerException("individual may not be null."); throw new NullPointerException("individual may not be null.");
@ -51,8 +57,13 @@ public class HasAssociatedIndividual implements Identifier {
} }
String reasonForBlacklisting = checkForBlacklisted(individual, context); String reasonForBlacklisting = checkForBlacklisted(individual, context);
return new HasAssociatedIndividual(individual.getURI(), IsBlacklisted id = new IsBlacklisted(individual.getURI(),
reasonForBlacklisting); reasonForBlacklisting);
if (id.isBlacklisted()) {
return id;
} else {
return null;
}
} }
/** /**
@ -172,6 +183,20 @@ public class HasAssociatedIndividual implements Identifier {
return NOT_BLACKLISTED; return NOT_BLACKLISTED;
} }
public static Collection<IsBlacklisted> getIdentifiers(IdentifierBundle ids) {
return getIdentifiersForClass(ids, IsBlacklisted.class);
}
public static Collection<String> getBlacklistReasons(IdentifierBundle ids) {
Set<String> set = new HashSet<String>();
for (IsBlacklisted id : getIdentifiers(ids)) {
if (id.isBlacklisted()) {
set.add(id.getReasonForBlacklisting());
}
}
return set;
}
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
// the Identifier // the Identifier
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
@ -179,7 +204,7 @@ public class HasAssociatedIndividual implements Identifier {
private final String associatedIndividualUri; private final String associatedIndividualUri;
private final String reasonForBlacklisting; private final String reasonForBlacklisting;
public HasAssociatedIndividual(String associatedIndividualUri, public IsBlacklisted(String associatedIndividualUri,
String reasonForBlacklisting) { String reasonForBlacklisting) {
this.associatedIndividualUri = associatedIndividualUri; this.associatedIndividualUri = associatedIndividualUri;
this.reasonForBlacklisting = reasonForBlacklisting; this.reasonForBlacklisting = reasonForBlacklisting;
@ -193,9 +218,13 @@ public class HasAssociatedIndividual implements Identifier {
return reasonForBlacklisting != NOT_BLACKLISTED; return reasonForBlacklisting != NOT_BLACKLISTED;
} }
public String getReasonForBlacklisting() {
return reasonForBlacklisting;
}
@Override @Override
public String toString() { public String toString() {
return "HasAssociatedIndividual['" + associatedIndividualUri return "IsBlacklisted['" + reasonForBlacklisting + "']";
+ "', blacklist='" + reasonForBlacklisting + "']";
} }
} }

View file

@ -0,0 +1,42 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.identifier.common;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
/**
* The current user has this URI.
*/
public class IsUser extends AbstractCommonIdentifier implements Identifier {
public static Collection<IsUser> getIdentifiers(IdentifierBundle ids) {
return getIdentifiersForClass(ids, IsUser.class);
}
public static Collection<String> getUserUris(IdentifierBundle ids) {
Set<String> set = new HashSet<String>();
for (IsUser id : getIdentifiers(ids)) {
set.add(id.getUri());
}
return set;
}
private final String uri;
public IsUser(String uri) {
this.uri = uri;
}
public String getUri() {
return uri;
}
@Override
public String toString() {
return "IsUser[" + uri + "]";
}
}

View file

@ -2,14 +2,8 @@
package edu.cornell.mannlib.vitro.webapp.auth.policy; package edu.cornell.mannlib.vitro.webapp.auth.policy;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.SelfEditingIdentifierFactory.SelfEditing;
import edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionPolicyHelper; import edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionPolicyHelper;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization; import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision; import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision;
@ -37,21 +31,6 @@ public abstract class BaseSelfEditingPolicy {
uri, roleLevel); uri, roleLevel);
} }
protected List<String> getUrisOfSelfEditor(IdentifierBundle ids) {
List<String> uris = new ArrayList<String>();
if (ids != null) {
for (Identifier id : ids) {
if (id instanceof SelfEditing) {
SelfEditing selfEditId = (SelfEditing) id;
if (selfEditId.getBlacklisted() == null) {
uris.add(selfEditId.getValue());
}
}
}
}
return uris;
}
protected PolicyDecision cantModifyResource(String uri) { protected PolicyDecision cantModifyResource(String uri) {
return inconclusiveDecision("No access to admin resources; cannot modify " return inconclusiveDecision("No access to admin resources; cannot modify "
+ uri); + uri);

View file

@ -7,9 +7,8 @@ import javax.servlet.ServletContext;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.HasRoleLevel;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle; import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.common.HasRoleLevel;
import edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionPolicyHelper; import edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionPolicyHelper;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization; import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision; import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision;
@ -51,7 +50,7 @@ public class DisplayRestrictedDataByRoleLevelPolicy implements PolicyIface {
return defaultDecision("whatToAuth was null"); return defaultDecision("whatToAuth was null");
} }
RoleLevel userRole = getUsersRoleLevel(whoToAuth); RoleLevel userRole = HasRoleLevel.getUsersRoleLevel(whoToAuth);
PolicyDecision result; PolicyDecision result;
if (whatToAuth instanceof DisplayDataProperty) { if (whatToAuth instanceof DisplayDataProperty) {
@ -164,17 +163,4 @@ public class DisplayRestrictedDataByRoleLevelPolicy implements PolicyIface {
.canDisplayPredicate(uri, userRole); .canDisplayPredicate(uri, userRole);
} }
/**
* The user is nobody unless they have a HasRoleLevel identifier.
*/
private RoleLevel getUsersRoleLevel(IdentifierBundle whoToAuth) {
RoleLevel userRole = RoleLevel.PUBLIC;
for (Identifier id : whoToAuth) {
if (id instanceof HasRoleLevel) {
userRole = ((HasRoleLevel) id).getRoleLevel();
}
}
return userRole;
}
} }

View file

@ -2,19 +2,16 @@
package edu.cornell.mannlib.vitro.webapp.auth.policy; package edu.cornell.mannlib.vitro.webapp.auth.policy;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.HasAssociatedIndividual;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.HasRoleLevel;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle; import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.common.HasAssociatedIndividual;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.common.HasRoleLevel;
import edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionPolicyHelper; import edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionPolicyHelper;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization; import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision; import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision;
@ -24,9 +21,9 @@ import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayData
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayObjectProperty; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayObjectProperty;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayObjectPropertyStatement; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.display.DisplayObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement; import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement; import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
/** /**
* Permit display of various data if it relates to the user's associated * Permit display of various data if it relates to the user's associated
@ -60,12 +57,13 @@ public class DisplayRestrictedDataToSelfPolicy implements PolicyIface {
return defaultDecision("whatToAuth was null"); return defaultDecision("whatToAuth was null");
} }
RoleLevel userRole = getUsersRoleLevel(whoToAuth); RoleLevel userRole = HasRoleLevel.getUsersRoleLevel(whoToAuth);
if (userRole != RoleLevel.SELF) { if (userRole != RoleLevel.SELF) {
return defaultDecision("not a self-editor"); return defaultDecision("not a self-editor");
} }
Collection<String> associated = getAssociatedIndividualUris(whoToAuth); Collection<String> associated = HasAssociatedIndividual
.getIndividualUris(whoToAuth);
if (associated.isEmpty()) { if (associated.isEmpty()) {
return defaultDecision("not self-editing for anyone"); return defaultDecision("not self-editing for anyone");
} }
@ -177,35 +175,4 @@ public class DisplayRestrictedDataToSelfPolicy implements PolicyIface {
return false; return false;
} }
/**
* The user is nobody unless they have a HasRoleLevel identifier.
*/
private RoleLevel getUsersRoleLevel(IdentifierBundle whoToAuth) {
RoleLevel userRole = RoleLevel.PUBLIC;
for (Identifier id : whoToAuth) {
if (id instanceof HasRoleLevel) {
userRole = ((HasRoleLevel) id).getRoleLevel();
}
}
return userRole;
}
/**
* Find out who the user has self-editing rights for. We only include the
* ones that are not blacklisted.
*/
private Collection<String> getAssociatedIndividualUris(
IdentifierBundle whoToAuth) {
List<String> list = new ArrayList<String>();
for (Identifier id : whoToAuth) {
if (id instanceof HasAssociatedIndividual) {
HasAssociatedIndividual haiId = (HasAssociatedIndividual) id;
if (!haiId.isBlacklisted()) {
list.add(haiId.getAssociatedIndividualUri());
}
}
}
return list;
}
} }

View file

@ -1,428 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.policy;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolutionMap;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.ActiveIdentifierBundleFactories;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.SelfEditingIdentifierFactory;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.SelfEditingIdentifierFactory.NetId;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.DefaultInconclusivePolicy;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyIface;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AddDataPropStmt;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AddObjectPropStmt;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.DropDataPropStmt;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.DropObjectPropStmt;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.resource.AddResource;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.resource.DropResource;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
/**
* This policy looks for a netid in the IdentifierBundle and will use that netid
* as a anchor in SPARQL queries. These queries are intended to specify the relations
* that allow authorization.
*
* We could use things other than SPARQL. Other possibilities:
* Some java driven code that worked with the the jena Model
* Fresnel Selector Language (FSL)
* SWRL?
*
* example of how to set up the xml:
*
* <code>
<edu.cornell.mannlib.vitro.webapp.auth.policy.JenaNetidPolicy>
<name>Example Policy</name>
<prefixes>PREFIX rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt;
PREFIX rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt;
PREFIX vivoa: &lt;http://vivo.library.cornell.edu/abox#&gt;
PREFIX vivo: &lt;http://vivo.library.cornell.edu/ns/0.1#&gt;
PREFIX vitro: &lt;http://lowe.mannlib.cornell.edu/ns/vitro/0.1/vitro.owl#&gt;
</prefixes>
<actionToQueryStr>
<entry>
<string>edu.cornell.mannlib.vitro.webapp.auth.requestedAction.DropDataPropStmt</string>
<list>
<string>ASK WHERE { ?subject vitro:netid ?netid }</string>
<string>ASK WHERE { ?object vitro:netid ?netid }</string>
</list>
</entry>
<entry>
<string>edu.cornell.mannlib.vitro.webapp.auth.requestedAction.DropObjectPropStmt</string>
<list>
<string>ASK WHERE { ?subject vitro:netid ?netid }</string>
<string>ASK WHERE { ?object vitro:netid ?netid }</string>
</list>
</entry>
<entry>
<string>edu.cornell.mannlib.vitro.webapp.auth.requestedAction.AddObjectPropStmt</string>
<list>
<string>ASK WHERE { ?subject vitro:netid ?netid }</string>
<string>ASK WHERE { ?object vitro:netid ?netid }</string>
</list>
</entry>
<entry>
<string>edu.cornell.mannlib.vitro.webapp.auth.requestedAction.AddDataPropStmt</string>
<list>
<string>ASK WHERE { ?subject vitro:netid ?netid }</string>
<string>ASK WHERE { ?object vitro:netid ?netid }</string>
</list>
</entry>
</actionToQueryStr>
</edu.cornell.mannlib.vitro.webapp.auth.policy.JenaNetidPolicy>
</code>
* @author bdc34
*
*/
public class JenaNetidPolicy extends DefaultInconclusivePolicy implements PolicyIface {
protected transient Model model = ModelFactory.createDefaultModel();
private transient HashMap<String,Query> queryStrToQuery = new HashMap<String,Query>();
/** human readable name for this policy */
protected String name="Unnamed Policy";
/** prefixes for SPARQL queries. */
protected String prefixes = DEFAULT_PREFIXES;
/** Specifies the type of Authorization returned when the SPARQL query succeeds. This allows us to
* create a JenaNetidPolicy that returns UNAUTHORIZED when the some set of conditions are meet. */
protected Authorization authForSuccessfulQuery = Authorization.AUTHORIZED;
/** The SPARQL queries. They should all be of the type ASK and
* they should all have the variable ?netid */
protected HashMap<String,List<String>> actionToQueryStr = new HashMap<String,List<String>>();
/* *************************** Constructors ******************************* */
/**
* See JenaNetidPolicy.setupDefault() for the sparql queries that will
* be used by the default JenaNetidPolicy.
*/
public JenaNetidPolicy(Model model){
if( model == null ){
this.model = ModelFactory.createDefaultModel();
}else{
this.model = model;
}
setupDefault();
}
/**
* Loads sparql statements for policy from a JSON text file.
*
* @param model
* @param sparqlStmts
*/
public JenaNetidPolicy(Model model, InputStream policySpec){
this(model, policySpec, Authorization.AUTHORIZED);
}
/*
* Load xml policy files with this.getClass().getResourceAsStream()
* Notice that / is the path seperator and strings that lack
* a leading slash are relative to the package of the this.getClass().
*/
public JenaNetidPolicy(Model model, String resource){
this(model, JenaNetidPolicy.class.getResourceAsStream(resource));
}
public JenaNetidPolicy(Model model, InputStream policySpec, Authorization authForSuccessfulQuery){
this.authForSuccessfulQuery = authForSuccessfulQuery;
XStream x = new XStream(new DomDriver());
//XStream x = new XStream();
JenaNetidPolicy jnip =(JenaNetidPolicy) x.fromXML( policySpec );
this.actionToQueryStr = jnip.actionToQueryStr;
this.prefixes = jnip.prefixes;
this.name = jnip.name;
this.model = model;
}
/* *********************** Methods ************************************ */
@Override
public PolicyDecision isAuthorized(IdentifierBundle whoToAuth,
RequestedAction whatToAuth) {
BasicPolicyDecision pd = new BasicPolicyDecision(Authorization.INCONCLUSIVE,"not yet set");
if( whoToAuth == null )
return pd.setMessage("whoToAuth was null");
if(whatToAuth == null)
return pd.setMessage("whatToAuth was null");
String netid = getNetid(whoToAuth);
if (netid == null)
return pd.setMessage("Unable to get netid from IdBundle");
if (whatToAuth instanceof AddResource) {
return visit(whoToAuth, (AddResource) whatToAuth);
} else if (whatToAuth instanceof DropResource) {
return visit(whoToAuth, (DropResource) whatToAuth);
} else if (whatToAuth instanceof AddObjectPropStmt) {
return visit(whoToAuth, (AddObjectPropStmt) whatToAuth);
} else if (whatToAuth instanceof DropObjectPropStmt) {
return visit(whoToAuth, (DropObjectPropStmt) whatToAuth);
} else if (whatToAuth instanceof AddDataPropStmt) {
return visit(whoToAuth, (AddDataPropStmt) whatToAuth);
} else if (whatToAuth instanceof DropDataPropStmt) {
return visit(whoToAuth, (DropDataPropStmt) whatToAuth);
} else {
return UNAUTH;
}
}
/* ************************* visit methods ************************** */
private PolicyDecision visit(IdentifierBundle ids, AddResource action) {
log.debug("doing AddResource");
List<String> queryStrs = actionToQueryStr.get(action.getClass().getName());
if( queryStrs == null || queryStrs.size() ==0 )
return new BasicPolicyDecision(Authorization.INCONCLUSIVE,
"no queryies found for action" + action.getClass().getName());
QuerySolutionMap parameters = new QuerySolutionMap();
parameters.add("netid", model.createLiteral( getNetid(ids) ));
parameters.add("subject",model.createResource( action.getSubjectUri() ));
return doQueries(queryStrs,parameters,action);
}
private PolicyDecision visit(IdentifierBundle ids, DropResource action) {
log.debug("doing DropResource");
List<String> queryStrs = actionToQueryStr.get(action.getClass().getName());
if( queryStrs == null || queryStrs.size() ==0 )
return new BasicPolicyDecision(Authorization.INCONCLUSIVE,
"no queryies found for action" + action.getClass().getName());
QuerySolutionMap parameters = new QuerySolutionMap();
parameters.add("netid", model.createLiteral( getNetid(ids) ));
parameters.add("subject",model.createResource( action.getSubjectUri() ));
return doQueries(queryStrs,parameters,action);
}
private PolicyDecision visit(IdentifierBundle ids, AddObjectPropStmt action) {
log.debug("doing AddObjectPropStmt in visit()");
List<String> queryStrs = actionToQueryStr.get(action.getClass().getName());
if( queryStrs == null || queryStrs.size() ==0 )
return new BasicPolicyDecision(Authorization.INCONCLUSIVE,
"no queryies found for action" + action.getClass().getName());
QuerySolutionMap parameters = new QuerySolutionMap();
parameters.add("netid", model.createLiteral( getNetid(ids) ));
parameters.add("subject",model.createResource( action.getUriOfSubject() )) ;
parameters.add("object", model.createResource( action.getUriOfObject() )) ;
parameters.add("predicate", model.createResource( action.getUriOfPredicate() )) ;
return doQueries(queryStrs,parameters,action);
}
private PolicyDecision visit(IdentifierBundle ids, DropObjectPropStmt action) {
log.debug("doing DropObjectPropStmt");
List<String> queryStrs = actionToQueryStr.get(action.getClass().getName());
if( queryStrs == null || queryStrs.size() ==0 )
return new BasicPolicyDecision(Authorization.INCONCLUSIVE,
"no queryies found for action" + action.getClass().getName());
QuerySolutionMap parameters = new QuerySolutionMap();
parameters.add("netid", model.createLiteral( getNetid(ids) ));
parameters.add("subject",model.createResource( action.getUriOfSubject() )) ;
parameters.add("object", model.createResource( action.getUriOfObject() )) ;
parameters.add("predicate", model.createResource( action.getUriOfPredicate() )) ;
return doQueries(queryStrs,parameters,action);
}
private PolicyDecision visit(IdentifierBundle ids, AddDataPropStmt action) {
log.debug("doing AddDataPropStmt");
List<String> queryStrs = actionToQueryStr.get(action.getClass().getName());
if( queryStrs == null || queryStrs.size() ==0 )
return new BasicPolicyDecision(Authorization.INCONCLUSIVE,
"no queryies found for action" + action.getClass().getName());
QuerySolutionMap parameters = new QuerySolutionMap();
parameters.add("netid", model.createLiteral( getNetid(ids) ));
parameters.add("subject",model.createResource( action.getSubjectUri() )) ;
parameters.add("predicate", model.createResource( action.getPredicateUri() )) ;
parameters.add("literalValue", model.createLiteral(action.getData() ));
return doQueries(queryStrs,parameters,action);
}
private PolicyDecision visit(IdentifierBundle ids, DropDataPropStmt action) {
log.debug("doing DropDataPropStmt");
List<String> queryStrs = actionToQueryStr.get(action.getClass().getName());
if( queryStrs == null || queryStrs.size() ==0 )
return new BasicPolicyDecision(Authorization.INCONCLUSIVE,
"no queries found for action" + action.getClass().getName());
QuerySolutionMap parameters = new QuerySolutionMap();
parameters.add("netid", model.createLiteral( getNetid(ids) ));
parameters.add("subject",model.createResource( action.getSubjectUri() )) ;
parameters.add("predicate", model.createResource( action.getPredicateUri() )) ;
parameters.add("literalValue", model.createLiteral(action.data() )); // caution: will always do untyped things
return doQueries(queryStrs,parameters,action);
}
/* ******************************** utilities ****************************** */
private PolicyDecision doQueries(List<String>queryStrs, QuerySolutionMap parameters, RequestedAction action){
SparqlPolicyDecision pd = new SparqlPolicyDecision(Authorization.INCONCLUSIVE,"");
for(String quStr : queryStrs){
Query query = getQueryForQueryStr(quStr);
pd.setQuery(query);
QueryExecution qexec = QueryExecutionFactory.create(query, model, parameters);
pd.setQexec(qexec);
boolean pathFound = qexec.execAsk();
if( pathFound ){
pd.setAuthorized(authForSuccessfulQuery);
pd.setMessage(action.getClass().getName() + " permited by " + quStr);
if( log.isDebugEnabled()){
log.debug(action.getClass().getName() + " permited by " + quStr);
log.debug(query);
}
break;
} else {
if( log.isDebugEnabled()){
log.debug(action.getClass().getName() + " no results for " + query);
log.debug(query);
}
}
}
return pd;
}
private Query getQueryForQueryStr(String queryStr){
Query q = queryStrToQuery.get(queryStr);
if( q == null ){
q = QueryFactory.create(prefixes + queryStr);
queryStrToQuery.put(queryStr, q);
}
return q;
}
private String getNetid(IdentifierBundle whoToAuth) {
String netidStr = null;
for(Identifier id : whoToAuth){
if (id instanceof NetId) {
NetId netid = (NetId) id;
netidStr = netid.getValue();
break;
}
}
if( log.isDebugEnabled() )
log.debug("netid was " + (netidStr!=null?netidStr:"null") );
return netidStr;
}
/**
* An inner class used to setup everything that's needed for
* a JenaNetidPolicy. This setups the JenaNetidPolicy and a
* SelfEditingIdentifierFactory.
*
* @author bdc34
*
*/
public static class ContextSetup implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
try{
log.trace("Setting up JenaNetidPolicy");
Model model = (Model) sce.getServletContext().getAttribute("jenaOntModel");
if( model == null ){
log.error("could not get jenaOntModel from JenaBaseDao, JenaNetidPolicy will not work");
}
ServletPolicyList.addPolicy(sce.getServletContext(), new JenaNetidPolicy(model));
ActiveIdentifierBundleFactories.addFactory(sce, new SelfEditingIdentifierFactory());
}catch(Exception e){
log.error("could not create AuthorizationFactory: " + e);
e.printStackTrace();
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) { /*nothing*/ }
}
private void setupDefault(){
// --- AddObjectPropStmt ---
// may have 4 parameters: netid, object, predicate, and subject.
ArrayList <String> queries = new ArrayList<String>();
queries.add( "ASK WHERE { ?subject vitro:netid ?netid }");
queries.add( "ASK WHERE { ?object vitro:netid ?netid }");
actionToQueryStr.put( AddObjectPropStmt.class.getName(), queries);
// --- DropObjectPropStmt ---
queries = new ArrayList<String>();
queries.add( "ASK WHERE { ?subject vitro:netid ?netid }");
queries.add( "ASK WHERE { ?object vitro:netid ?netid }");
actionToQueryStr.put( DropObjectPropStmt.class.getName(), queries);
// --- DropDataPropStmt ---
queries = new ArrayList<String>();
queries.add( "ASK WHERE { ?subject vitro:netid ?netid }");
queries.add( "ASK WHERE { ?object vitro:netid ?netid }");
actionToQueryStr.put( DropDataPropStmt.class.getName(), queries);
// --- AddDataPropStmt ---
queries = new ArrayList<String>();
queries.add( "ASK WHERE { ?subject vitro:netid ?netid }");
queries.add( "ASK WHERE { ?object vitro:netid ?netid }");
actionToQueryStr.put( AddDataPropStmt.class.getName(), queries);
// --- DropResource ---
queries = new ArrayList<String>();
queries.add( "ASK WHERE { ?subject vitro:netid ?netid }");
queries.add( "ASK WHERE { ?object vitro:netid ?netid }");
actionToQueryStr.put( DropObjectPropStmt.class.getName(), queries);
// --- AddResource ---
queries = new ArrayList<String>();
queries.add( "ASK WHERE { ?subject vitro:netid ?netid }");
queries.add( "ASK WHERE { ?object vitro:netid ?netid }");
actionToQueryStr.put( DropObjectPropStmt.class.getName(), queries);
}
public final static String netIdPropUri = VitroVocabulary.vitroURI+ "netid";
private static final Log log = LogFactory.getLog(JenaNetidPolicy.class.getName());
public final static String DEFAULT_PREFIXES =
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"+
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"+
"PREFIX vivoa: <http://vivo.library.cornell.edu/abox#>\n"+
"PREFIX vivo: <http://vivo.library.cornell.edu/ns/0.1#>\n"+
"PREFIX vitro: <"+ VitroVocabulary.vitroURI+">\n";
private final PolicyDecision UNAUTH = new BasicPolicyDecision(
Authorization.UNAUTHORIZED,
"JenaNetidPolicy doesn't authorize admin or onto editing actions");
}

View file

@ -2,11 +2,13 @@
package edu.cornell.mannlib.vitro.webapp.auth.policy; package edu.cornell.mannlib.vitro.webapp.auth.policy;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle; import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.common.HasAssociatedIndividual;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision; import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyIface; import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyIface;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
@ -35,7 +37,8 @@ public class SelfEditingPolicy extends BaseSelfEditingPolicy implements
return inconclusiveDecision("whatToAuth was null"); return inconclusiveDecision("whatToAuth was null");
} }
List<String> userUris = getUrisOfSelfEditor(whoToAuth); List<String> userUris = new ArrayList<String>(
HasAssociatedIndividual.getIndividualUris(whoToAuth));
if (userUris.isEmpty()) { if (userUris.isEmpty()) {
return inconclusiveDecision("Not self-editing."); return inconclusiveDecision("Not self-editing.");

View file

@ -1,264 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.policy;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolutionMap;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.DefaultInconclusivePolicy;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyIface;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.admin.UploadFile;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AddDataPropStmt;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AddObjectPropStmt;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.DropDataPropStmt;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.DropObjectPropStmt;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.EditDataPropStmt;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.EditObjPropStmt;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.resource.AddResource;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.resource.DropResource;
/**
* This policy maps strings in the IdentifierBundle to a QuerySolutioinMap in order
* to bind identifiers with unbound variables in SPARQL queries.
* These queries are intended to specify the relations that allow authorization.
* If the query return no rows will be interpreted as unauthorized and a
* query returning one or more rows will be interpreted as authorized.
*
* @author bdc34
*
*/
public class SparqlPolicy extends DefaultInconclusivePolicy implements PolicyIface{
protected Model model = ModelFactory.createDefaultModel();
private HashMap<String,Query> queryStrToQuery = new HashMap<String,Query>();
/** human readable name for this policy */
protected String name="Unnamed Policy";
/** prefixes for SPARQL queries. */
protected String prefixes = "";
/** The SPARQL queries. They should all be of the type ASK */
protected HashMap<String,List<String>> actionToQueryStr = new HashMap<String,List<String>>();
/** Function to transform identifiers into a QuerySolutionMap */
private Ids2QueryBindings binder;
private String resource = null;
/**
* Load XML policy files with this.getClass().getResourceAsStream()
* Notice that / is the path separator and strings that lack
* a leading slash are relative to the package of the this.getClass().
*/
public SparqlPolicy(Model model, Ids2QueryBindings binder, String resource){
if( model == null )
throw new IllegalArgumentException("model must not be null.");
if( binder == null )
throw new IllegalArgumentException("binder must not be null.");
if( resource == null )
throw new IllegalArgumentException("resource must not be null.");
this.model = model;
this.binder = binder;
this.resource = resource;
loadPolicy();
}
public void loadPolicy(){
InputStream policySpec = SparqlPolicy.class.getResourceAsStream(resource);
XStream x = new XStream(new DomDriver());
SparqlPolicy jnip =(SparqlPolicy) x.fromXML( policySpec );
this.actionToQueryStr = jnip.actionToQueryStr;
this.prefixes = jnip.prefixes;
this.name = jnip.name;
try{
policySpec.close();
}catch(Throwable th){/*ignore it?*/}
}
/* *********************** Methods ************************************ */
@Override
public PolicyDecision isAuthorized(IdentifierBundle whoToAuth,
RequestedAction whatToAuth) {
if( whoToAuth == null )
return new BasicPolicyDecision(Authorization.INCONCLUSIVE,"whoToAuth was null");
if(whatToAuth == null)
return new BasicPolicyDecision(Authorization.INCONCLUSIVE,"whatToAuth was null");
List<String> queryStrs = actionToQueryStr.get(whatToAuth.getClass().getName());
if( queryStrs == null || queryStrs.size() ==0 )
return new BasicPolicyDecision(Authorization.INCONCLUSIVE,
"no queryies found for action" + whatToAuth.getClass().getName());
if (whatToAuth instanceof AddObjectPropStmt) {
return visit(whoToAuth, (AddObjectPropStmt) whatToAuth);
} else if (whatToAuth instanceof DropResource) {
return visit(whoToAuth, (DropResource) whatToAuth);
} else if (whatToAuth instanceof DropDataPropStmt) {
return visit(whoToAuth, (DropDataPropStmt) whatToAuth);
} else if (whatToAuth instanceof DropObjectPropStmt) {
return visit(whoToAuth, (DropObjectPropStmt) whatToAuth);
} else if (whatToAuth instanceof AddResource) {
return visit(whoToAuth, (AddResource) whatToAuth);
} else if (whatToAuth instanceof AddDataPropStmt) {
return visit(whoToAuth, (AddDataPropStmt) whatToAuth);
} else if (whatToAuth instanceof UploadFile) {
return visit(whoToAuth, (UploadFile) whatToAuth);
} else if (whatToAuth instanceof EditDataPropStmt) {
return visit(whoToAuth, (EditDataPropStmt) whatToAuth);
} else if (whatToAuth instanceof EditObjPropStmt) {
return visit(whoToAuth, (EditObjPropStmt) whatToAuth);
} else {
return UNAUTH;
}
}
private PolicyDecision doQueries(List<String>queryStrs, IdentifierBundle ids, RequestedAction action){
SparqlPolicyDecision pd = new SparqlPolicyDecision(Authorization.INCONCLUSIVE,"");
List<QuerySolutionMap> bindings = binder.makeScopeBinding(ids, action);
for( QuerySolutionMap scope: bindings ){
for(String quStr : queryStrs){
Query query = getQueryForQueryStr(quStr);
pd.setQuery(query);
QueryExecution qexec = QueryExecutionFactory.create(query, model, scope);
pd.setQexec(qexec);
boolean pathFound = qexec.execAsk();
if( pathFound ){
pd.setAuthorized(Authorization.AUTHORIZED);
pd.setMessage(action.getClass().getName() + " permited by " + quStr);
if( log.isDebugEnabled()){
log.debug(action.getClass().getName() + " permited by " + quStr);
log.debug(query);
}
return pd;
} else {
if( log.isDebugEnabled()){
log.debug(action.getClass().getName() + " no results for " + query);
log.debug(query);
}
}
}
}
return pd;
}
private Query getQueryForQueryStr(String queryStr){
//memoize queries
Query q = queryStrToQuery.get(queryStr);
if( q == null ){
q = QueryFactory.create(prefixes + queryStr);
queryStrToQuery.put(queryStr, q);
}
return q;
}
/* ***************** Visit methods ********************** */
private final String pkg = "edu.cornell.mannlib.vitro.webapp.auth.requestedAction.";
private PolicyDecision visit(IdentifierBundle ids, AddObjectPropStmt action) {
return doQueries(actionToQueryStr.get(pkg +"AddObjectPropStmt"),ids,action);
}
private PolicyDecision visit(IdentifierBundle ids, DropResource action) {
return doQueries(actionToQueryStr.get(pkg +"DropResource"),ids,action);
}
private PolicyDecision visit(IdentifierBundle ids, DropDataPropStmt action) {
return doQueries(actionToQueryStr.get(pkg +"DropDataPropStmt"),ids,action);
}
private PolicyDecision visit(IdentifierBundle ids, DropObjectPropStmt action) {
return doQueries(actionToQueryStr.get(pkg +"DropObjectPropStmt"),ids,action);
}
private PolicyDecision visit(IdentifierBundle ids, AddResource action) {
return doQueries(actionToQueryStr.get(pkg +"AddResource"),ids,action);
}
private PolicyDecision visit(IdentifierBundle ids, AddDataPropStmt action) {
return doQueries(actionToQueryStr.get(pkg +"AddDataPropStmt"),ids,action);
}
private PolicyDecision visit(IdentifierBundle ids, UploadFile action) {
return doQueries(actionToQueryStr.get(pkg +"UploadFile"),ids,action);
}
private PolicyDecision visit(IdentifierBundle ids, EditDataPropStmt action) {
return doQueries(actionToQueryStr.get(pkg +"EditDataPropStmt"),ids,action);
}
private PolicyDecision visit(IdentifierBundle ids, EditObjPropStmt action) {
return doQueries(actionToQueryStr.get(pkg +"EditObjPropStmt"),ids,action);
}
private static final Log log = LogFactory.getLog(SparqlPolicy.class.getName());
private final PolicyDecision UNAUTH = new BasicPolicyDecision(
Authorization.UNAUTHORIZED,
name + " SparqlPolicy doesn't authorize admin or onto editing actions");
/*
* example of how to set up the xml:
*
* <code>
<edu.cornell.mannlib.vitro.webapp.auth.policy.JenaNetidPolicy>
<name>Example Policy</name>
<prefixes>PREFIX rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt;
PREFIX rdfs: &lt;http://www.w3.org/2000/01/rdf-schema#&gt;
PREFIX vivoa: &lt;http://vivo.library.cornell.edu/abox#&gt;
PREFIX vivo: &lt;http://vivo.library.cornell.edu/ns/0.1#&gt;
PREFIX vitro: &lt;http://lowe.mannlib.cornell.edu/ns/vitro/0.1/vitro.owl#&gt;
</prefixes>
<actionToQueryStr>
<entry>
<string>edu.cornell.mannlib.vitro.webapp.auth.requestedAction.DropDataPropStmt</string>
<list>
<string>ASK WHERE { ?subject vitro:netid ?netid }</string>
<string>ASK WHERE { ?object vitro:netid ?netid }</string>
</list>
</entry>
<entry>
<string>edu.cornell.mannlib.vitro.webapp.auth.requestedAction.DropObjectPropStmt</string>
<list>
<string>ASK WHERE { ?subject vitro:netid ?netid }</string>
<string>ASK WHERE { ?object vitro:netid ?netid }</string>
</list>
</entry>
<entry>
<string>edu.cornell.mannlib.vitro.webapp.auth.requestedAction.AddObjectPropStmt</string>
<list>
<string>ASK WHERE { ?subject vitro:netid ?netid }</string>
<string>ASK WHERE { ?object vitro:netid ?netid }</string>
</list>
</entry>
<entry>
<string>edu.cornell.mannlib.vitro.webapp.auth.requestedAction.AddDataPropStmt</string>
<list>
<string>ASK WHERE { ?subject vitro:netid ?netid }</string>
<string>ASK WHERE { ?object vitro:netid ?netid }</string>
</list>
</entry>
</actionToQueryStr>
</edu.cornell.mannlib.vitro.webapp.auth.policy.JenaNetidPolicy>
</code>
*/
}

View file

@ -1,61 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.policy;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
/**
* Extends the BasicPolicyDecision with additional debugging information about the
* sparql queries that were run to create the decision.
*
* @author bdc34
*
*/
public class SparqlPolicyDecision extends BasicPolicyDecision {
Query query = null;
QueryExecution qexec = null;
public SparqlPolicyDecision(Authorization authorized, String message) {
super(authorized, message);
}
public QueryExecution getQexec() {
return qexec;
}
public void setQexec(QueryExecution qexec) {
this.qexec = qexec;
}
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
@Override
public String getDebuggingInfo() {
String msg = "";
if( super.getDebuggingInfo() != null && super.getDebuggingInfo().length() > 0)
msg = super.getDebuggingInfo() + '\n';
if( query != null )
msg= msg + "query: \n" + query.toString() + '\n';
else
msg = msg + " query was null \n";
if( qexec != null )
msg = msg + "query exec: \n" + qexec.toString();
else
msg = msg + " query exec was null \n";
return msg;
}
}

View file

@ -5,9 +5,8 @@ package edu.cornell.mannlib.vitro.webapp.auth.policy;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.HasRoleLevel;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle; import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.common.HasRoleLevel;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization; import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision; import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyIface; import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyIface;
@ -27,6 +26,7 @@ import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.usepages.UseAdvance
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.usepages.UseBasicAjaxControllers; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.usepages.UseBasicAjaxControllers;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.usepages.UseMiscellaneousAdminPages; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.usepages.UseMiscellaneousAdminPages;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.usepages.UseMiscellaneousCuratorPages; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.usepages.UseMiscellaneousCuratorPages;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.usepages.UseMiscellaneousEditorPages;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.usepages.UseMiscellaneousPages; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.usepages.UseMiscellaneousPages;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel; import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel;
@ -48,7 +48,7 @@ public class UseRestrictedPagesByRoleLevelPolicy implements PolicyIface {
return defaultDecision("whatToAuth was null"); return defaultDecision("whatToAuth was null");
} }
RoleLevel userRole = getUsersRoleLevel(whoToAuth); RoleLevel userRole = HasRoleLevel.getUsersRoleLevel(whoToAuth);
PolicyDecision result; PolicyDecision result;
if (whatToAuth instanceof UseAdvancedDataToolsPages) { if (whatToAuth instanceof UseAdvancedDataToolsPages) {
@ -93,6 +93,9 @@ public class UseRestrictedPagesByRoleLevelPolicy implements PolicyIface {
} else if (whatToAuth instanceof SeeIndividualEditingPanel) { } else if (whatToAuth instanceof SeeIndividualEditingPanel) {
result = isAuthorized(whatToAuth, RoleLevel.EDITOR, userRole); result = isAuthorized(whatToAuth, RoleLevel.EDITOR, userRole);
} else if (whatToAuth instanceof UseMiscellaneousEditorPages) {
result = isAuthorized(whatToAuth, RoleLevel.EDITOR, userRole);
} else if (whatToAuth instanceof UseBasicAjaxControllers) { } else if (whatToAuth instanceof UseBasicAjaxControllers) {
result = isAuthorized(whatToAuth, RoleLevel.SELF, userRole); result = isAuthorized(whatToAuth, RoleLevel.SELF, userRole);
@ -137,16 +140,4 @@ public class UseRestrictedPagesByRoleLevelPolicy implements PolicyIface {
return new BasicPolicyDecision(Authorization.INCONCLUSIVE, message); return new BasicPolicyDecision(Authorization.INCONCLUSIVE, message);
} }
/**
* The user is nobody unless they have a HasRoleLevel identifier.
*/
private RoleLevel getUsersRoleLevel(IdentifierBundle whoToAuth) {
RoleLevel userRole = RoleLevel.PUBLIC;
for (Identifier id : whoToAuth) {
if (id instanceof HasRoleLevel) {
userRole = ((HasRoleLevel) id).getRoleLevel();
}
}
return userRole;
}
} }

View file

@ -10,7 +10,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.ActiveIdentifierBundleFactories; import edu.cornell.mannlib.vitro.webapp.auth.identifier.ActiveIdentifierBundleFactories;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.CommonIdentifierBundleFactory; import edu.cornell.mannlib.vitro.webapp.auth.identifier.common.CommonIdentifierBundleFactory;
import edu.cornell.mannlib.vitro.webapp.auth.policy.DisplayRestrictedDataByRoleLevelPolicy; import edu.cornell.mannlib.vitro.webapp.auth.policy.DisplayRestrictedDataByRoleLevelPolicy;
import edu.cornell.mannlib.vitro.webapp.auth.policy.DisplayRestrictedDataToSelfPolicy; import edu.cornell.mannlib.vitro.webapp.auth.policy.DisplayRestrictedDataToSelfPolicy;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ServletPolicyList; import edu.cornell.mannlib.vitro.webapp.auth.policy.ServletPolicyList;
@ -41,7 +41,7 @@ public class CommonPolicyFamilySetup implements ServletContextListener {
new UseRestrictedPagesByRoleLevelPolicy()); new UseRestrictedPagesByRoleLevelPolicy());
// This factory creates Identifiers for all of the above policies. // This factory creates Identifiers for all of the above policies.
CommonIdentifierBundleFactory factory = new CommonIdentifierBundleFactory(); CommonIdentifierBundleFactory factory = new CommonIdentifierBundleFactory(ctx);
ActiveIdentifierBundleFactories.addFactory(sce, factory); ActiveIdentifierBundleFactories.addFactory(sce, factory);
} catch (Exception e) { } catch (Exception e) {

View file

@ -1,55 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.policy.setup;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.ontology.OntModel;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.ActiveIdentifierBundleFactories;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.SelfEditingIdentifierFactory;
import edu.cornell.mannlib.vitro.webapp.auth.policy.JenaNetidPolicy;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ServletPolicyList;
/**
* Class used to setup a JenaNetidPolicy using the default.
* This setups the JenaNetidPolicy and a SelfEditingIdentifierFactory.
*
* See JenaNetidPolicy.setupDefault() for the sparql queries that will
* be used by the default JenaNetidPolicy.
*
* @author bdc34
*
*/
public class JenaNetidPolicySetup implements ServletContextListener {
private static final Log log = LogFactory.getLog(JenaNetidPolicySetup.class.getName());
@Override
public void contextInitialized(ServletContextEvent sce) {
try{
log.debug("Setting up JenaNetidPolicy");
JenaNetidPolicy jnip = new JenaNetidPolicy((OntModel) sce.getServletContext().getAttribute("jenaOntModel"));
ServletPolicyList.addPolicy(sce.getServletContext(), jnip);
SelfEditingIdentifierFactory niif =new SelfEditingIdentifierFactory();
ActiveIdentifierBundleFactories.addFactory(sce, niif);
}catch(Exception e){
log.error("could not create AuthorizationFactory: " + e);
e.printStackTrace();
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
/*nothing*/
}
}

View file

@ -1,49 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.policy.setup;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.ActiveIdentifierBundleFactories;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.SelfEditing2RoleIdentifierFactory;
/**
* Add the SelfEditing2RoleIdentifier factory to the IdentifierFactory list
* in the servlet context.
*
* This should be added to the IdentifierFactory list after the
* SelfEditingIdentiferFactory.
*
* This only sets up a IdentifierFactoy that maps SelfEditing identifiers to
* roles associated with the Individual that represents the self editor. This
* does not set up a policy or the SelfEditingIdentifierFactory.
*
* @author bdc34
*
*/
public class SelfEditing2RoleIdentifierSetup implements ServletContextListener{
private static final Log log = LogFactory.getLog(SelfEditing2RoleIdentifierSetup.class.getName());
@Override
public void contextDestroyed(ServletContextEvent sce) {
//do nothing
}
@Override
public void contextInitialized(ServletContextEvent sce) {
try{
log.debug("Setting up SelfEditing2RoleIdentifier");
ActiveIdentifierBundleFactories.addFactory(sce, new SelfEditing2RoleIdentifierFactory());
log.debug( "SelfEditing2RoleIdentifier has been setup. " );
}catch(Exception e){
log.error("could not run SelfEditing2RoleIdentifier: " + e);
e.printStackTrace();
}
}
}

View file

@ -19,9 +19,6 @@ import com.hp.hpl.jena.rdf.model.SimpleSelector;
import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.shared.Lock; import com.hp.hpl.jena.shared.Lock;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.HasAssociatedIndividual;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.Identifier;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.policy.BasicPolicyDecision; import edu.cornell.mannlib.vitro.webapp.auth.policy.BasicPolicyDecision;
import edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionPolicyHelper; import edu.cornell.mannlib.vitro.webapp.auth.policy.bean.PropertyRestrictionPolicyHelper;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization; import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.Authorization;
@ -47,24 +44,6 @@ public abstract class AbstractRelationshipPolicy implements PolicyIface {
this.model = model; this.model = model;
} }
/**
* Check to see whether we are self-editing, and for which Individuals.
*/
protected List<String> getUrisOfSelfEditor(IdentifierBundle ids) {
List<String> uris = new ArrayList<String>();
if (ids != null) {
for (Identifier id : ids) {
if (id instanceof HasAssociatedIndividual) {
HasAssociatedIndividual selfEditId = (HasAssociatedIndividual) id;
if (!selfEditId.isBlacklisted()) {
uris.add(selfEditId.getAssociatedIndividualUri());
}
}
}
}
return uris;
}
protected boolean canModifyResource(String uri) { protected boolean canModifyResource(String uri) {
return PropertyRestrictionPolicyHelper.getBean(ctx).canModifyResource( return PropertyRestrictionPolicyHelper.getBean(ctx).canModifyResource(
uri, RoleLevel.SELF); uri, RoleLevel.SELF);

View file

@ -2,6 +2,7 @@
package edu.cornell.mannlib.vitro.webapp.auth.policy.specialrelationships; package edu.cornell.mannlib.vitro.webapp.auth.policy.specialrelationships;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
@ -14,6 +15,7 @@ import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModel;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle; import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.common.HasAssociatedIndividual;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ServletPolicyList; import edu.cornell.mannlib.vitro.webapp.auth.policy.ServletPolicyList;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision; import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyDecision;
import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyIface; import edu.cornell.mannlib.vitro.webapp.auth.policy.ifaces.PolicyIface;
@ -128,7 +130,8 @@ public class SelfEditorRelationshipPolicy extends AbstractRelationshipPolicy
private PolicyDecision isAuthorized(IdentifierBundle ids, private PolicyDecision isAuthorized(IdentifierBundle ids,
DistilledAction action) { DistilledAction action) {
List<String> userUris = getUrisOfSelfEditor(ids); List<String> userUris = new ArrayList<String>(
HasAssociatedIndividual.getIndividualUris(ids));
if (userUris.isEmpty()) { if (userUris.isEmpty()) {
return inconclusiveDecision("Not self-editing."); return inconclusiveDecision("Not self-editing.");

View file

@ -31,12 +31,12 @@ import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAct
public class Actions { public class Actions {
private static final Log log = LogFactory.getLog(Actions.class); private static final Log log = LogFactory.getLog(Actions.class);
public static final Actions EMPTY = new Actions(); public static final Actions AUTHORIZED = new Actions();
public static final Actions UNAUTHORIZED = new Actions( public static final Actions UNAUTHORIZED = new Actions(
new UnauthorizedAction()); new UnauthorizedAction());
public static Actions notNull(Actions actions) { public static Actions notNull(Actions actions) {
return (actions == null) ? EMPTY : actions; return (actions == null) ? AUTHORIZED : actions;
} }
private final List<Set<RequestedAction>> clauseList; private final List<Set<RequestedAction>> clauseList;

View file

@ -0,0 +1,11 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.auth.requestedAction.usepages;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
/** Should we allow the user to use the odd-lots pages that were designed for Editors, Curators or DBAs? */
public class UseMiscellaneousEditorPages extends RequestedAction implements
UsePagesRequestedAction {
// no fields
}

View file

@ -11,6 +11,10 @@ import java.util.Set;
* Information about the account of a user. URI, email, password, etc. * Information about the account of a user. URI, email, password, etc.
*/ */
public class UserAccount { public class UserAccount {
public final static int MIN_PASSWORD_LENGTH = 6;
public final static int MAX_PASSWORD_LENGTH = 12;
public enum Status { public enum Status {
ACTIVE, INACTIVE; ACTIVE, INACTIVE;
@ -30,36 +34,20 @@ public class UserAccount {
} }
/** Should never be null. */ private String uri = ""; // Never null.
private String uri = "";
private String emailAddress = ""; // Never null.
private String firstName = ""; // Never null.
private String lastName = ""; // Never null.
/** Should never be null. */ private String md5Password = ""; // Never null.
private String emailAddress = ""; private String oldPassword = ""; // Never null.
private long passwordLinkExpires = 0L; // Never negative.
/** Should never be null. */
private String firstName = "";
/** Should never be null. */
private String lastName = "";
/** Should never be null. */
private String md5Password = "";
/** Should never be null. */
private String oldPassword = "";
/** Should never be negative. */
private long passwordLinkExpires = 0L;
private boolean passwordChangeRequired = false; private boolean passwordChangeRequired = false;
/** Should never be negative. */ private int loginCount = 0; // Never negative.
private int loginCount = 0; private Status status = Status.INACTIVE; // Might be null.
private String externalAuthId = ""; // Never null.
/** Might be null. */
private Status status = Status.INACTIVE;
/** This may be empty, but should never be null. */ /** This may be empty, but should never be null. */
private Set<String> permissionSetUris = Collections.emptySet(); private Set<String> permissionSetUris = Collections.emptySet();
@ -128,7 +116,8 @@ public class UserAccount {
} }
public void setPasswordChangeRequired(Boolean passwordChangeRequired) { public void setPasswordChangeRequired(Boolean passwordChangeRequired) {
this.passwordChangeRequired = nonNull(passwordChangeRequired, Boolean.FALSE); this.passwordChangeRequired = nonNull(passwordChangeRequired,
Boolean.FALSE);
} }
public int getLoginCount() { public int getLoginCount() {
@ -151,6 +140,14 @@ public class UserAccount {
this.status = Status.fromString(statusString); this.status = Status.fromString(statusString);
} }
public String getExternalAuthId() {
return externalAuthId;
}
public void setExternalAuthId(String externalAuthId) {
this.externalAuthId = nonNull(externalAuthId, "");
}
public Set<String> getPermissionSetUris() { public Set<String> getPermissionSetUris() {
return new HashSet<String>(permissionSetUris); return new HashSet<String>(permissionSetUris);
} }
@ -161,19 +158,21 @@ public class UserAccount {
} }
this.permissionSetUris = new HashSet<String>(permissionSetUris); this.permissionSetUris = new HashSet<String>(permissionSetUris);
} }
private <T> T nonNull(T value, T defaultValue) { private <T> T nonNull(T value, T defaultValue) {
return (value == null) ? defaultValue : value; return (value == null) ? defaultValue : value;
} }
@Override @Override
public String toString() { public String toString() {
return "UserAccount[uri=" + uri + ", emailAddress=" + emailAddress return "UserAccount[uri=" + uri + (", emailAddress=" + emailAddress)
+ ", firstName=" + firstName + ", lastName=" + lastName + (", firstName=" + firstName) + (", lastName=" + lastName)
+ ", md5password=" + md5Password + ", passwordChangeExpires=" + (", md5password=" + md5Password)
+ passwordLinkExpires + ", loginCount=" + loginCount + (", oldPassword=" + oldPassword)
+ ", status=" + status + ", permissionSetUris=" + (", passwordLinkExpires=" + passwordLinkExpires)
+ permissionSetUris + "]"; + (", passwordChangeRequired=" + passwordChangeRequired)
+ (", loginCount=" + loginCount) + (", status=" + status)
+ (", externalAuthId=" + externalAuthId)
+ (", permissionSetUris=" + permissionSetUris) + "]";
} }
} }

View file

@ -1,34 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CuwalRedirector extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//forward to /edit/login.jsp to work around CUWebAuth bug
RequestDispatcher rd = getServletContext().getRequestDispatcher("/edit/login.jsp");
rd.forward(req, resp);
return;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//forward to /edit/login.jsp to work around CUWebAuth bug
RequestDispatcher rd = getServletContext().getRequestDispatcher("/edit/login.jsp");
rd.forward(req, resp);
return;
}
}

View file

@ -29,6 +29,7 @@ import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDF;
import edu.cornell.mannlib.vitro.webapp.search.lucene.Entity2LuceneDoc; import edu.cornell.mannlib.vitro.webapp.search.lucene.Entity2LuceneDoc;
import edu.cornell.mannlib.vitro.webapp.search.lucene.Entity2LuceneDoc.VitroLuceneTermNames;
import edu.cornell.mannlib.vitro.webapp.search.lucene.LuceneIndexFactory; import edu.cornell.mannlib.vitro.webapp.search.lucene.LuceneIndexFactory;
import edu.cornell.mannlib.vitro.webapp.web.ContentType; import edu.cornell.mannlib.vitro.webapp.web.ContentType;
@ -74,13 +75,13 @@ public void doGet (HttpServletRequest req, HttpServletResponse res) throws IOExc
String classUri = (String) getServletContext().getAttribute("classuri"); String classUri = (String) getServletContext().getAttribute("classuri");
BooleanQuery query = new BooleanQuery(); BooleanQuery query = new BooleanQuery();
query.add( query.add(
new TermQuery( new Term(Entity2LuceneDoc.term.RDFTYPE, classUri)), new TermQuery( new Term(VitroLuceneTermNames.RDFTYPE, classUri)),
BooleanClause.Occur.MUST ); BooleanClause.Occur.MUST );
IndexSearcher index = LuceneIndexFactory.getIndexSearcher(getServletContext()); IndexSearcher index = LuceneIndexFactory.getIndexSearcher(getServletContext());
TopDocs docs = index.search(query, null, TopDocs docs = index.search(query, null,
ENTITY_LIST_CONTROLLER_MAX_RESULTS, ENTITY_LIST_CONTROLLER_MAX_RESULTS,
new Sort(Entity2LuceneDoc.term.NAMELOWERCASE)); new Sort(VitroLuceneTermNames.NAME_LOWERCASE));
if( docs == null ){ if( docs == null ){
log.error("Search of lucene index returned null"); log.error("Search of lucene index returned null");
@ -97,7 +98,7 @@ public void doGet (HttpServletRequest req, HttpServletResponse res) throws IOExc
if (hit != null) { if (hit != null) {
Document doc = index.doc(hit.doc); Document doc = index.doc(hit.doc);
if (doc != null) { if (doc != null) {
String uri = doc.getField(Entity2LuceneDoc.term.URI).stringValue(); String uri = doc.getField(VitroLuceneTermNames.URI).stringValue();
resource = ResourceFactory.createResource(uri); resource = ResourceFactory.createResource(uri);
node = (RDFNode) ResourceFactory.createResource(classUri); node = (RDFNode) ResourceFactory.createResource(classUri);
model.add(resource, RDF.type, node); model.add(resource, RDF.type, node);

View file

@ -231,7 +231,7 @@ public class FedoraDatastreamController extends VitroHttpServlet implements Cons
} }
//check if fedora is on line //check if fedora is on line
OntModel sessionOntModel = (OntModel)req.getSession().getAttribute("jenaOntModel"); OntModel sessionOntModel = (OntModel)rawRequest.getSession().getAttribute("jenaOntModel");
synchronized (FedoraDatastreamController.class) { synchronized (FedoraDatastreamController.class) {
if( fedoraUrl == null ){ if( fedoraUrl == null ){
setup( sessionOntModel, getServletContext() ); setup( sessionOntModel, getServletContext() );
@ -280,7 +280,7 @@ public class FedoraDatastreamController extends VitroHttpServlet implements Cons
"enough information to complete your request.(Missing fileRes)"); "enough information to complete your request.(Missing fileRes)");
//check if file individual has a fedora:PID for a data stream //check if file individual has a fedora:PID for a data stream
VitroRequest vreq = new VitroRequest(req); VitroRequest vreq = new VitroRequest(rawRequest);
IndividualDao iwDao = vreq.getWebappDaoFactory().getIndividualDao(); IndividualDao iwDao = vreq.getWebappDaoFactory().getIndividualDao();
Individual fileEntity = iwDao.getIndividualByURI(fileUri); Individual fileEntity = iwDao.getIndividualByURI(fileUri);

View file

@ -377,7 +377,7 @@ public class JSONReconcileServlet extends VitroHttpServlet {
String stemParam = (String) request.getParameter("stem"); String stemParam = (String) request.getParameter("stem");
boolean stem = "true".equals(stemParam); boolean stem = "true".equals(stemParam);
String termName = stem ? VitroLuceneTermNames.NAME : VitroLuceneTermNames.NAMEUNSTEMMED; String termName = stem ? VitroLuceneTermNames.AC_NAME_STEMMED : VitroLuceneTermNames.AC_NAME_UNSTEMMED;
BooleanQuery boolQuery = new BooleanQuery(); BooleanQuery boolQuery = new BooleanQuery();
@ -415,7 +415,7 @@ public class JSONReconcileServlet extends VitroHttpServlet {
private Query makeUntokenizedNameQuery(String querystr) { private Query makeUntokenizedNameQuery(String querystr) {
querystr = querystr.toLowerCase(); querystr = querystr.toLowerCase();
String termName = VitroLuceneTermNames.NAMELOWERCASE; String termName = VitroLuceneTermNames.NAME_LOWERCASE;
BooleanQuery query = new BooleanQuery(); BooleanQuery query = new BooleanQuery();
log.debug("Adding wildcard query on unanalyzed name"); log.debug("Adding wildcard query on unanalyzed name");
query.add( query.add(

View file

@ -40,8 +40,8 @@ import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.VClassGroupCache; import edu.cornell.mannlib.vitro.webapp.dao.jena.VClassGroupCache;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.SelectListGenerator; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.SelectListGenerator;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch; import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.IndividualTemplateModel; import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.IndividualTemplateModel;

View file

@ -0,0 +1,566 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.IndividualListController;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.IndividualListController.PageRecord;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.dao.jena.VClassGroupCache;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.SelectListGenerator;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.IndividualTemplateModel;
/**
* This servlet is for servicing requests for JSON objects/data.
* It could be generalized to get other types of data ex. XML, HTML etc
* @author bdc34
*
*/
// RY Rename to JsonServlet once the transition to Solr is complete.
public class SolrJsonServlet extends VitroHttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
VitroRequest vreq = new VitroRequest(req);
try{
if(vreq.getParameter("getEntitiesByVClass") != null ){
if( vreq.getParameter("resultKey") == null) {
getEntitiesByVClass(req, resp);
return;
} else {
getEntitiesByVClassContinuation( req, resp);
return;
}
}else if( vreq.getParameter("getN3EditOptionList") != null ){
doN3EditOptionList(req,resp);
return;
}else if( vreq.getParameter("getLuceneIndividualsByVClass") != null ){
getLuceneIndividualsByVClass(req,resp);
return;
}else if( vreq.getParameter("getVClassesForVClassGroup") != null ){
getVClassesForVClassGroup(req,resp);
return;
}
}catch(Exception ex){
log.warn(ex,ex);
}
}
private void getVClassesForVClassGroup(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException {
JSONObject map = new JSONObject();
VitroRequest vreq = new VitroRequest(req);
String vcgUri = vreq.getParameter("classgroupUri");
if( vcgUri == null ){
log.debug("no URI passed for classgroupUri");
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
VClassGroupCache vcgc = VClassGroupCache.getVClassGroupCache(getServletContext());
VClassGroup vcg = vcgc.getGroup(vcgUri);
if( vcg == null ){
log.debug("Could not find vclassgroup: " + vcgUri);
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
ArrayList<JSONObject> classes = new ArrayList<JSONObject>(vcg.size());
for( VClass vc : vcg){
JSONObject vcObj = new JSONObject();
vcObj.put("name", vc.getName());
vcObj.put("URI", vc.getURI());
vcObj.put("entityCount", vc.getEntityCount());
classes.add(vcObj);
}
map.put("classes", classes);
map.put("classGroupName", vcg.getPublicName());
map.put("classGroupUri", vcg.getURI());
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json;charset=UTF-8");
Writer writer = resp.getWriter();
writer.write(map.toString());
}
private void getLuceneIndividualsByVClass( HttpServletRequest req, HttpServletResponse resp ){
String errorMessage = null;
JSONObject rObj = null;
try{
VitroRequest vreq = new VitroRequest(req);
VClass vclass=null;
String vitroClassIdStr = vreq.getParameter("vclassId");
if ( vitroClassIdStr != null && !vitroClassIdStr.isEmpty()){
vclass = vreq.getWebappDaoFactory().getVClassDao().getVClassByURI(vitroClassIdStr);
if (vclass == null) {
log.debug("Couldn't retrieve vclass ");
throw new Exception (errorMessage = "Class " + vitroClassIdStr + " not found");
}
}else{
log.debug("parameter vclassId URI parameter expected ");
throw new Exception("parameter vclassId URI parameter expected ");
}
rObj = getLuceneIndividualsByVClass(vclass.getURI(),req, getServletContext());
}catch(Exception ex){
errorMessage = ex.toString();
log.error(ex,ex);
}
if( rObj == null )
rObj = new JSONObject();
try{
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json;charset=UTF-8");
if( errorMessage != null ){
rObj.put("errorMessage", errorMessage);
resp.setStatus(500 /*HttpURLConnection.HTTP_SERVER_ERROR*/);
}else{
rObj.put("errorMessage", "");
}
Writer writer = resp.getWriter();
writer.write(rObj.toString());
}catch(JSONException jse){
log.error(jse,jse);
} catch (IOException e) {
log.error(e,e);
}
}
public static JSONObject getLuceneIndividualsByVClass(String vclassURI, HttpServletRequest req, ServletContext context) throws Exception {
VitroRequest vreq = new VitroRequest(req);
VClass vclass=null;
JSONObject rObj = new JSONObject();
DataProperty fNameDp = (new DataProperty());
fNameDp.setURI("http://xmlns.com/foaf/0.1/firstName");
DataProperty lNameDp = (new DataProperty());
lNameDp.setURI("http://xmlns.com/foaf/0.1/lastName");
DataProperty monikerDp = (new DataProperty());
monikerDp.setURI( VitroVocabulary.MONIKER);
//this property is vivo specific
DataProperty preferredTitleDp = (new DataProperty());
preferredTitleDp.setURI("http://vivoweb.org/ontology/core#preferredTitle");
if( log.isDebugEnabled() ){
Enumeration<String> e = vreq.getParameterNames();
while(e.hasMoreElements()){
String name = (String)e.nextElement();
log.debug("parameter: " + name);
for( String value : vreq.getParameterValues(name) ){
log.debug("value for " + name + ": '" + value + "'");
}
}
}
//need an unfiltered dao to get firstnames and lastnames
WebappDaoFactory fullWdf = vreq.getFullWebappDaoFactory();
String vitroClassIdStr = vreq.getParameter("vclassId");
if ( vitroClassIdStr != null && !vitroClassIdStr.isEmpty()){
vclass = vreq.getWebappDaoFactory().getVClassDao().getVClassByURI(vitroClassIdStr);
if (vclass == null) {
log.debug("Couldn't retrieve vclass ");
throw new Exception ("Class " + vitroClassIdStr + " not found");
}
}else{
log.debug("parameter vclassId URI parameter expected ");
throw new Exception("parameter vclassId URI parameter expected ");
}
rObj.put("vclass",
new JSONObject().put("URI",vclass.getURI())
.put("name",vclass.getName()));
if (vclass != null) {
String alpha = IndividualListController.getAlphaParameter(vreq);
int page = IndividualListController.getPageParameter(vreq);
Map<String,Object> map = IndividualListController.getResultsForVClass(
vclass.getURI(),
page,
alpha,
vreq.getWebappDaoFactory().getIndividualDao(),
context);
rObj.put("totalCount", map.get("totalCount"));
rObj.put("alpha", map.get("alpha"));
List<Individual> inds = (List<Individual>)map.get("entities");
List<IndividualTemplateModel> indsTm = new ArrayList<IndividualTemplateModel>();
JSONArray jInds = new JSONArray();
for(Individual ind : inds ){
JSONObject jo = new JSONObject();
jo.put("URI", ind.getURI());
jo.put("label",ind.getRdfsLabel());
jo.put("name",ind.getName());
jo.put("thumbUrl", ind.getThumbUrl());
jo.put("imageUrl", ind.getImageUrl());
jo.put("profileUrl", UrlBuilder.getIndividualProfileUrl(ind, vreq.getWebappDaoFactory()));
String moniker = getDataPropertyValue(ind, monikerDp, fullWdf);
jo.put("moniker", moniker);
jo.put("vclassName", getVClassName(ind,moniker,fullWdf));
jo.put("preferredTitle", getDataPropertyValue(ind, preferredTitleDp, fullWdf));
jo.put("firstName", getDataPropertyValue(ind, fNameDp, fullWdf));
jo.put("lastName", getDataPropertyValue(ind, lNameDp, fullWdf));
jInds.put(jo);
}
rObj.put("individuals", jInds);
JSONArray wpages = new JSONArray();
List<PageRecord> pages = (List<PageRecord>)map.get("pages");
for( PageRecord pr: pages ){
JSONObject p = new JSONObject();
p.put("text", pr.text);
p.put("param", pr.param);
p.put("index", pr.index);
wpages.put( p );
}
rObj.put("pages",wpages);
JSONArray jletters = new JSONArray();
List<String> letters = Controllers.getLetters();
for( String s : letters){
JSONObject jo = new JSONObject();
jo.put("text", s);
jo.put("param", "alpha=" + URLEncoder.encode(s, "UTF-8"));
jletters.put( jo );
}
rObj.put("letters", jletters);
}
return rObj;
}
private static String getVClassName(Individual ind, String moniker,
WebappDaoFactory fullWdf) {
/* so the moniker frequently has a vclass name in it. Try to return
* the vclass name that is the same as the moniker so that the templates
* can detect this. */
if( (moniker == null || moniker.isEmpty()) ){
if( ind.getVClass() != null && ind.getVClass().getName() != null )
return ind.getVClass().getName();
else
return "";
}
List<VClass> vcList = ind.getVClasses();
for( VClass vc : vcList){
if( vc != null && moniker.equals( vc.getName() ))
return moniker;
}
// if we get here, then we didn't find a moniker that matched a vclass,
// so just return any vclass.name
if( ind.getVClass() != null && ind.getVClass().getName() != null )
return ind.getVClass().getName();
else
return "";
}
static String getDataPropertyValue(Individual ind, DataProperty dp, WebappDaoFactory wdf){
List<Literal> values = wdf.getDataPropertyStatementDao()
.getDataPropertyValuesForIndividualByProperty(ind, dp);
if( values == null || values.isEmpty() )
return "";
else{
if( values.get(0) != null )
return values.get(0).getLexicalForm();
else
return "";
}
}
/**
* Gets an option list for a given EditConfiguration and Field.
* Requires following HTTP query parameters:
* editKey
* field
*/
private void doN3EditOptionList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
log.debug("in doN3EditOptionList()");
String field = req.getParameter("field");
if( field == null ){
log.debug("could not find query parameter 'field' for doN3EditOptionList");
throw new IllegalArgumentException(" getN3EditOptionList requires parameter 'field'");
}
HttpSession sess = req.getSession(false);
EditConfiguration editConfig = EditConfiguration.getConfigFromSession(sess, req);
if( editConfig == null ) {
log.debug("could not find query parameter 'editKey' for doN3EditOptionList");
throw new IllegalArgumentException(" getN3EditOptionList requires parameter 'editKey'");
}
if( log.isDebugEnabled() )
log.debug(" attempting to get option list for field '" + field + "'");
// set ProhibitedFromSearch object so picklist doesn't show
// individuals from classes that should be hidden from list views
OntModel displayOntModel =
(OntModel) getServletConfig().getServletContext()
.getAttribute("displayOntModel");
if (displayOntModel != null) {
ProhibitedFromSearch pfs = new ProhibitedFromSearch(
DisplayVocabulary.PRIMARY_LUCENE_INDEX_URI, displayOntModel);
editConfig.setProhibitedFromSearch(pfs);
}
Map<String,String> options = SelectListGenerator.getOptions(editConfig, field, (new VitroRequest(req)).getFullWebappDaoFactory());
resp.setContentType("application/json");
ServletOutputStream out = resp.getOutputStream();
out.println("[");
for(String key : options.keySet()){
JSONArray jsonObj = new JSONArray();
jsonObj.put( options.get(key));
jsonObj.put( key);
out.println(" " + jsonObj.toString() + ",");
}
out.println("]");
}
private void getEntitiesByVClassContinuation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
log.debug("in getEntitiesByVClassContinuation()");
VitroRequest vreq = new VitroRequest(req);
String resKey = vreq.getParameter("resultKey");
if( resKey == null )
throw new ServletException("Could not get resultKey");
HttpSession session = vreq.getSession();
if( session == null )
throw new ServletException("there is no session to get the pervious results from");
List<Individual> entsInVClass = (List<Individual>) session.getAttribute(resKey);
if( entsInVClass == null )
throw new ServletException("Could not find List<Individual> for resultKey " + resKey);
List<Individual> entsToReturn = new ArrayList<Individual>(REPLY_SIZE);
boolean more = false;
int count = 0;
int size = REPLY_SIZE;
/* we have a large number of items to send back so we need to stash the list in the session scope */
if( entsInVClass.size() > REPLY_SIZE){
more = true;
ListIterator<Individual> entsFromVclass = entsInVClass.listIterator();
while ( entsFromVclass.hasNext() && count <= REPLY_SIZE ){
entsToReturn.add( entsFromVclass.next());
entsFromVclass.remove();
count++;
}
if( log.isDebugEnabled() ) log.debug("getEntitiesByVClassContinuation(): Creating reply with continue token," +
" sending in this reply: " + count +", remaing to send: " + entsInVClass.size() );
} else {
//send out reply with no continuation
entsToReturn = entsInVClass;
count = entsToReturn.size();
session.removeAttribute(resKey);
if( log.isDebugEnabled()) log.debug("getEntitiesByVClassContinuation(): sending " + count + " Ind without continue token");
}
//put all the entities on the JSON array
JSONArray ja = individualsToJson( entsToReturn );
//put the responseGroup number on the end of the JSON array
if( more ){
try{
JSONObject obj = new JSONObject();
obj.put("resultGroup", "true");
obj.put("size", count);
StringBuffer nextUrlStr = req.getRequestURL();
nextUrlStr.append("?")
.append("getEntitiesByVClass").append( "=1&" )
.append("resultKey=").append( resKey );
obj.put("nextUrl", nextUrlStr.toString());
ja.put(obj);
}catch(JSONException je ){
throw new ServletException(je.getMessage());
}
}
resp.setContentType("application/json");
ServletOutputStream out = resp.getOutputStream();
out.print( ja.toString() );
log.debug("done with getEntitiesByVClassContinuation()");
}
/**
* Gets a list of entities that are members of the indicated vClass.
*
* If the list is large then we will pass some token indicating that there is more
* to come. The results are sent back in 250 entity blocks. To get all of the
* entities for a VClass just keep requesting lists until there are not more
* continue tokens.
*
* If there are more entities the last item on the returned array will be an object
* with no id property. It will look like this:
*
* {"resultGroup":0,
* "resultKey":"2WEK2306",
* "nextUrl":"http://caruso.mannlib.cornell.edu:8080/vitro/dataservice?getEntitiesByVClass=1&resultKey=2WEK2306&resultGroup=1&vclassId=null",
* "entsInVClass":1752,
* "nextResultGroup":1,
* "standardReplySize":256}
*
*/
private void getEntitiesByVClass(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
log.debug("in getEntitiesByVClass()");
VitroRequest vreq = new VitroRequest(req);
String vclassURI = vreq.getParameter("vclassURI");
WebappDaoFactory daos = (new VitroRequest(req)).getFullWebappDaoFactory();
resp.setCharacterEncoding("UTF-8");
// ServletOutputStream doesn't support UTF-8
PrintWriter out = resp.getWriter();
resp.getWriter();
if( vclassURI == null ){
log.debug("getEntitiesByVClass(): no value for 'vclassURI' found in the HTTP request");
out.print( (new JSONArray()).toString() ); return;
}
VClass vclass = daos.getVClassDao().getVClassByURI( vclassURI );
if( vclass == null ){
log.debug("getEntitiesByVClass(): could not find vclass for uri '"+ vclassURI + "'");
out.print( (new JSONArray()).toString() ); return;
}
List<Individual> entsInVClass = daos.getIndividualDao().getIndividualsByVClass( vclass );
if( entsInVClass == null ){
log.debug("getEntitiesByVClass(): null List<Individual> retruned by getIndividualsByVClass() for "+vclassURI);
out.print( (new JSONArray().toString() )); return ;
}
int numberOfEntsInVClass = entsInVClass.size();
List<Individual> entsToReturn = new ArrayList<Individual>( REPLY_SIZE );
String requestHash = null;
int count = 0;
boolean more = false;
/* we have a large number of items to send back so we need to stash the list in the session scope */
if( entsInVClass.size() > REPLY_SIZE){
more = true;
HttpSession session = vreq.getSession(true);
requestHash = Integer.toString((vclassURI + System.currentTimeMillis()).hashCode());
session.setAttribute(requestHash, entsInVClass );
ListIterator<Individual> entsFromVclass = entsInVClass.listIterator();
while ( entsFromVclass.hasNext() && count < REPLY_SIZE ){
entsToReturn.add( entsFromVclass.next());
entsFromVclass.remove();
count++;
}
if( log.isDebugEnabled() ){ log.debug("getEntitiesByVClass(): Creating reply with continue token, found " + numberOfEntsInVClass + " Individuals"); }
}else{
if( log.isDebugEnabled() ) log.debug("getEntitiesByVClass(): sending " + numberOfEntsInVClass +" Individuals without continue token");
entsToReturn = entsInVClass;
count = entsToReturn.size();
}
//put all the entities on the JSON array
JSONArray ja = individualsToJson( entsToReturn );
//put the responseGroup number on the end of the JSON array
if( more ){
try{
JSONObject obj = new JSONObject();
obj.put("resultGroup", "true");
obj.put("size", count);
obj.put("total", numberOfEntsInVClass);
StringBuffer nextUrlStr = req.getRequestURL();
nextUrlStr.append("?")
.append("getEntitiesByVClass").append( "=1&" )
.append("resultKey=").append( requestHash );
obj.put("nextUrl", nextUrlStr.toString());
ja.put(obj);
}catch(JSONException je ){
throw new ServletException("unable to create continuation as JSON: " + je.getMessage());
}
}
resp.setContentType("application/json");
out.print( ja.toString() );
log.debug("done with getEntitiesByVClass()");
}
private JSONArray individualsToJson(List<Individual> individuals) throws ServletException {
JSONArray ja = new JSONArray();
Iterator it = individuals.iterator();
try{
while(it.hasNext()){
Individual ent = (Individual) it.next();
JSONObject entJ = new JSONObject();
entJ.put("name", ent.getName());
entJ.put("URI", ent.getURI());
ja.put( entJ );
}
}catch(JSONException ex){
throw new ServletException("could not convert list of Individuals into JSON: " + ex);
}
return ja;
}
private static final int REPLY_SIZE = 256;
private static final Log log = LogFactory.getLog(JSONServlet.class.getName());
}

View file

@ -26,6 +26,7 @@ import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean; import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
import edu.cornell.mannlib.vitro.webapp.auth.policy.PolicyHelper; import edu.cornell.mannlib.vitro.webapp.auth.policy.PolicyHelper;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.Actions; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.Actions;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.ifaces.RequestedAction;
import edu.cornell.mannlib.vitro.webapp.beans.DisplayMessage; import edu.cornell.mannlib.vitro.webapp.beans.DisplayMessage;
import edu.cornell.mannlib.vitro.webapp.controller.authenticate.LogoutRedirector; import edu.cornell.mannlib.vitro.webapp.controller.authenticate.LogoutRedirector;
@ -98,7 +99,19 @@ public class VitroHttpServlet extends HttpServlet {
* Don't display a page that the user isn't authorized to see. * Don't display a page that the user isn't authorized to see.
* *
* @param actions * @param actions
* the RequestedActions that need to be authorized. * the RequestedActions that must be authorized.
*/
protected boolean isAuthorizedToDisplayPage(HttpServletRequest request,
HttpServletResponse response, RequestedAction... actions) {
return isAuthorizedToDisplayPage(request, response,
new Actions(Arrays.asList(actions)));
}
/**
* Don't display a page that the user isn't authorized to see.
*
* @param actions
* the combination of RequestedActions that must be authorized.
*/ */
protected boolean isAuthorizedToDisplayPage(HttpServletRequest request, protected boolean isAuthorizedToDisplayPage(HttpServletRequest request,
HttpServletResponse response, Actions actions) { HttpServletResponse response, Actions actions) {
@ -112,7 +125,7 @@ public class VitroHttpServlet extends HttpServlet {
+ "' is authorized for actions: " + actions); + "' is authorized for actions: " + actions);
return true; return true;
} }
log.debug("Servlet '" + this.getClass().getSimpleName() log.debug("Servlet '" + this.getClass().getSimpleName()
+ "' is not authorized for actions: " + actions); + "' is not authorized for actions: " + actions);

View file

@ -67,7 +67,7 @@ public abstract class VitroAjaxController extends HttpServlet {
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
protected Actions requiredActions(VitroRequest vreq) { protected Actions requiredActions(VitroRequest vreq) {
return Actions.EMPTY; return Actions.AUTHORIZED;
} }
/** /**

View file

@ -7,7 +7,11 @@ import static edu.cornell.mannlib.vedit.beans.LoginStatusBean.AuthenticationSour
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.Actions; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.Actions;
import edu.cornell.mannlib.vitro.webapp.beans.User;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
@ -23,9 +27,13 @@ import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.Tem
* URL can come here, but they need to pass Internal Authentication to proceed. * URL can come here, but they need to pass Internal Authentication to proceed.
*/ */
public class AdminLoginController extends FreemarkerHttpServlet { public class AdminLoginController extends FreemarkerHttpServlet {
private static final Log log = LogFactory
.getLog(AdminLoginController.class);
public static final String PARAMETER_USERNAME = "username"; public static final String PARAMETER_USERNAME = "username";
public static final String PARAMETER_PASSWORD = "password"; public static final String PARAMETER_PASSWORD = "password";
public static final String PARAMETER_NEW_PASSWORD = "newPassword"; public static final String PARAMETER_NEW_PASSWORD = "newPassword";
public static final String PARAMETER_CONFIRM_PASSWORD = "confirmPassword";
public static final String URL_THIS = "/admin/login"; public static final String URL_THIS = "/admin/login";
public static final String URL_HOME_PAGE = "/"; public static final String URL_HOME_PAGE = "/";
@ -36,10 +44,13 @@ public class AdminLoginController extends FreemarkerHttpServlet {
private static final String MESSAGE_NO_PASSWORD = "errorNoPassword"; private static final String MESSAGE_NO_PASSWORD = "errorNoPassword";
private static final String MESSAGE_LOGIN_FAILED = "errorLoginFailed"; private static final String MESSAGE_LOGIN_FAILED = "errorLoginFailed";
private static final String MESSAGE_NEW_PASSWORD_REQUIRED = "newPasswordRequired"; private static final String MESSAGE_NEW_PASSWORD_REQUIRED = "newPasswordRequired";
private static final String MESSAGE_NEW_PASSWORD_WRONG_LENGTH = "errorNewPasswordWrongLength";
private static final String MESSAGE_NEW_PASSWORDS_DONT_MATCH = "errorNewPasswordsDontMatch";
private static final String MESSAGE_NEW_PASSWORD_MATCHES_OLD = "errorNewPasswordMatchesOld";
@Override @Override
protected Actions requiredActions(VitroRequest vreq) { protected Actions requiredActions(VitroRequest vreq) {
return Actions.EMPTY; // No requirements to use this page. return Actions.AUTHORIZED; // No requirements to use this page.
} }
@Override @Override
@ -56,6 +67,7 @@ public class AdminLoginController extends FreemarkerHttpServlet {
private final String username; private final String username;
private final String password; private final String password;
private final String newPassword; private final String newPassword;
private final String confirmPassword;
public Core(VitroRequest vreq) { public Core(VitroRequest vreq) {
this.auth = Authenticator.getInstance(vreq); this.auth = Authenticator.getInstance(vreq);
@ -64,20 +76,40 @@ public class AdminLoginController extends FreemarkerHttpServlet {
this.password = nonNull(vreq.getParameter(PARAMETER_PASSWORD)); this.password = nonNull(vreq.getParameter(PARAMETER_PASSWORD));
this.newPassword = nonNull(vreq this.newPassword = nonNull(vreq
.getParameter(PARAMETER_NEW_PASSWORD)); .getParameter(PARAMETER_NEW_PASSWORD));
this.confirmPassword = nonNull(vreq
.getParameter(PARAMETER_CONFIRM_PASSWORD));
log.debug("Parameters: username='" + username + "', password='"
+ password + "', newPassword='" + newPassword
+ "', confirmPassword='" + confirmPassword + "'");
} }
public ResponseValues process() { public ResponseValues process() {
if (username.isEmpty() && password.isEmpty()) { if (username.isEmpty() && password.isEmpty()) {
return showInitialForm(); return showForm();
} }
if (username.isEmpty()) { if (username.isEmpty()) {
return showFormWithMessage(MESSAGE_NO_USERNAME); return showForm(MESSAGE_NO_USERNAME);
} }
if (password.isEmpty()) { if (password.isEmpty()) {
return showFormWithMessage(MESSAGE_NO_PASSWORD); return showForm(MESSAGE_NO_PASSWORD);
} }
if (newPasswordRequired() && newPassword.isEmpty()) { if (newPasswordRequired()) {
return showFormWithMessage(MESSAGE_NEW_PASSWORD_REQUIRED); if (newPassword.isEmpty()) {
return showForm(MESSAGE_NEW_PASSWORD_REQUIRED);
}
if (!isPasswordValidLength(newPassword)) {
return showForm(MESSAGE_NEW_PASSWORD_REQUIRED,
MESSAGE_NEW_PASSWORD_WRONG_LENGTH);
}
if (newPassword.equals(password)) {
return showForm(MESSAGE_NEW_PASSWORD_REQUIRED,
MESSAGE_NEW_PASSWORD_MATCHES_OLD);
}
if (!newPassword.equals(confirmPassword)) {
return showForm(MESSAGE_NEW_PASSWORD_REQUIRED,
MESSAGE_NEW_PASSWORDS_DONT_MATCH);
}
} }
boolean loggedIn = tryToLogin(); boolean loggedIn = tryToLogin();
@ -85,7 +117,7 @@ public class AdminLoginController extends FreemarkerHttpServlet {
return goToHomePage(); return goToHomePage();
} }
return showFormWithMessage(MESSAGE_LOGIN_FAILED); return showForm(MESSAGE_LOGIN_FAILED);
} }
private boolean newPasswordRequired() { private boolean newPasswordRequired() {
@ -93,11 +125,16 @@ public class AdminLoginController extends FreemarkerHttpServlet {
&& auth.isPasswordChangeRequired(username); && auth.isPasswordChangeRequired(username);
} }
private boolean isPasswordValidLength(String pw) {
return (pw.length() >= User.MIN_PASSWORD_LENGTH)
&& (pw.length() <= User.MAX_PASSWORD_LENGTH);
}
private boolean tryToLogin() { private boolean tryToLogin() {
if (auth.isCurrentPassword(username, password)) { if (auth.isCurrentPassword(username, password)) {
auth.recordLoginAgainstUserAccount(username, INTERNAL); auth.recordLoginAgainstUserAccount(username, INTERNAL);
if (auth.isPasswordChangeRequired(username)) { if (!newPassword.isEmpty()) {
auth.recordNewPassword(username, newPassword); auth.recordNewPassword(username, newPassword);
} }
@ -107,18 +144,20 @@ public class AdminLoginController extends FreemarkerHttpServlet {
} }
} }
private ResponseValues showInitialForm() { private ResponseValues showForm(String... codes) {
Map<String, Object> body = new HashMap<String, Object>();
body.put("controllerUrl", UrlBuilder.getUrl(URL_THIS));
body.put("username", "");
return new TemplateResponseValues(TEMPLATE_NAME, body);
}
private ResponseValues showFormWithMessage(String messageCode) {
Map<String, Object> body = new HashMap<String, Object>(); Map<String, Object> body = new HashMap<String, Object>();
body.put("controllerUrl", UrlBuilder.getUrl(URL_THIS)); body.put("controllerUrl", UrlBuilder.getUrl(URL_THIS));
body.put("username", username); body.put("username", username);
body.put(messageCode, Boolean.TRUE); body.put("password", password);
body.put("newPassword", newPassword);
body.put("confirmPassword", confirmPassword);
for (String code : codes) {
body.put(code, Boolean.TRUE);
}
log.debug("showing form with values: " + body);
return new TemplateResponseValues(TEMPLATE_NAME, body); return new TemplateResponseValues(TEMPLATE_NAME, body);
} }

View file

@ -2,10 +2,14 @@
package edu.cornell.mannlib.vitro.webapp.controller.authenticate; package edu.cornell.mannlib.vitro.webapp.controller.authenticate;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List; import java.util.List;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.binary.Hex;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean.AuthenticationSource; import edu.cornell.mannlib.vedit.beans.LoginStatusBean.AuthenticationSource;
import edu.cornell.mannlib.vitro.webapp.beans.User; import edu.cornell.mannlib.vitro.webapp.beans.User;
@ -115,4 +119,25 @@ public abstract class Authenticator {
*/ */
public abstract void recordUserIsLoggedOut(); public abstract void recordUserIsLoggedOut();
// ----------------------------------------------------------------------
// Public utility methods.
// ----------------------------------------------------------------------
/**
* Apply MD5 to this string, and encode as a string of hex digits. Just
* right for storing passwords in the database, or hashing the password
* link.
*/
public static String applyMd5Encoding(String raw) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(raw.getBytes());
char[] hexChars = Hex.encodeHex(digest);
return new String(hexChars).toUpperCase();
} catch (NoSuchAlgorithmException e) {
// This can't happen with a normal Java runtime.
throw new RuntimeException(e);
}
}
} }

View file

@ -66,8 +66,7 @@ public class BasicAuthenticator extends Authenticator {
return false; return false;
} }
String md5NewPassword = Authenticate String md5NewPassword = applyMd5Encoding(clearTextPassword);
.applyMd5Encoding(clearTextPassword);
return md5NewPassword.equals(user.getMd5password()); return md5NewPassword.equals(user.getMd5password());
} }
@ -90,7 +89,7 @@ public class BasicAuthenticator extends Authenticator {
return; return;
} }
user.setOldPassword(user.getMd5password()); user.setOldPassword(user.getMd5password());
user.setMd5password(Authenticate.applyMd5Encoding(newClearTextPassword)); user.setMd5password(applyMd5Encoding(newClearTextPassword));
getUserDao().updateUser(user); getUserDao().updateUser(user);
} }
@ -226,7 +225,7 @@ public class BasicAuthenticator extends Authenticator {
if (iDao == null) { if (iDao == null) {
return Collections.emptyList(); return Collections.emptyList();
} }
String selfEditorUri = SelfEditingConfiguration.getBean(request) String selfEditorUri = SelfEditingConfiguration.getBean(request)
.getIndividualUriFromUsername(iDao, username); .getIndividualUriFromUsername(iDao, username);
if (selfEditorUri == null) { if (selfEditorUri == null) {
@ -313,15 +312,15 @@ public class BasicAuthenticator extends Authenticator {
if (wadf == null) { if (wadf == null) {
return null; return null;
} }
IndividualDao individualDao = wadf.getIndividualDao(); IndividualDao individualDao = wadf.getIndividualDao();
if (individualDao == null) { if (individualDao == null) {
log.error("getIndividualDao: no IndividualDao"); log.error("getIndividualDao: no IndividualDao");
} }
return individualDao; return individualDao;
} }
/** /**
* Get a reference to the WebappDaoFactory, or null. * Get a reference to the WebappDaoFactory, or null.
*/ */

View file

@ -43,7 +43,7 @@ public class ApplicationBeanRetryController extends BaseEditController {
try { try {
super.doGet(request,response); super.doGet(request,response);
} catch (Exception e) { } catch (Exception e) {
log.error("PortalRetryController encountered exception calling super.doGet()"); log.error(e,e);
} }
//create an EditProcessObject for this and put it in the session //create an EditProcessObject for this and put it in the session
@ -88,7 +88,7 @@ public class ApplicationBeanRetryController extends BaseEditController {
RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP); RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
request.setAttribute("bodyJsp","/templates/edit/formBasic.jsp"); request.setAttribute("bodyJsp","/templates/edit/formBasic.jsp");
request.setAttribute("formJsp","/templates/edit/specific/portal_retry.jsp"); request.setAttribute("formJsp","/templates/edit/specific/applicationBean_retry.jsp");
request.setAttribute("scripts","/templates/edit/formBasic.js"); request.setAttribute("scripts","/templates/edit/formBasic.js");
request.setAttribute("title","Site Information Editing Form"); request.setAttribute("title","Site Information Editing Form");
request.setAttribute("_action",action); request.setAttribute("_action",action);

View file

@ -493,22 +493,6 @@ public class Authenticate extends VitroHttpServlet {
// Public utility methods. // Public utility methods.
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
/**
* Encode this password for storage in the database. Apply an MD5 encoding,
* and store the result as a string of hex digits.
*/
public static String applyMd5Encoding(String password) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(password.getBytes());
char[] hexChars = Hex.encodeHex(digest);
return new String(hexChars).toUpperCase();
} catch (NoSuchAlgorithmException e) {
// This can't happen with a normal Java runtime.
throw new RuntimeException(e);
}
}
/** /**
* The servlet context should contain a map from User URIs to * The servlet context should contain a map from User URIs to
* {@link HttpSession}s. Get a reference to it, creating it if necessary. * {@link HttpSession}s. Get a reference to it, creating it if necessary.

View file

@ -38,11 +38,11 @@ import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.UserDao; import edu.cornell.mannlib.vitro.webapp.dao.UserDao;
import edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent; import edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditN3Generator; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditN3Utils; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Generator;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditSubmission; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Utils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.Field; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
import edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest; import edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.FileUploadServletRequest;
import edu.cornell.mannlib.vitro.webapp.utils.MailUtil; import edu.cornell.mannlib.vitro.webapp.utils.MailUtil;

View file

@ -26,7 +26,7 @@ import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.ajax.VitroAjaxController; import edu.cornell.mannlib.vitro.webapp.controller.ajax.VitroAjaxController;
import edu.cornell.mannlib.vitro.webapp.dao.jena.DependentResourceDeleteJena; import edu.cornell.mannlib.vitro.webapp.dao.jena.DependentResourceDeleteJena;
import edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent; import edu.cornell.mannlib.vitro.webapp.dao.jena.event.EditEvent;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditN3Utils; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Utils;
public class PrimitiveRdfEdit extends VitroAjaxController { public class PrimitiveRdfEdit extends VitroAjaxController {

View file

@ -33,6 +33,7 @@ import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.usepages.ManageUser
import edu.cornell.mannlib.vitro.webapp.beans.User; import edu.cornell.mannlib.vitro.webapp.beans.User;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers; import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.authenticate.Authenticator;
import edu.cornell.mannlib.vitro.webapp.dao.UserDao; import edu.cornell.mannlib.vitro.webapp.dao.UserDao;
public class UserRetryController extends BaseEditController { public class UserRetryController extends BaseEditController {
@ -355,7 +356,7 @@ public class UserRetryController extends BaseEditController {
log.error("Can't encode a null password"); log.error("Can't encode a null password");
} }
String encodedPassword = Authenticate.applyMd5Encoding(rawPassword); String encodedPassword = Authenticator.applyMd5Encoding(rawPassword);
log.trace(action + ": Raw password '" + rawPassword log.trace(action + ": Raw password '" + rawPassword
+ "', encoded '" + encodedPassword + "'"); + "', encoded '" + encodedPassword + "'");

View file

@ -121,7 +121,7 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
protected Actions requiredActions(VitroRequest vreq) { protected Actions requiredActions(VitroRequest vreq) {
return Actions.EMPTY; return Actions.AUTHORIZED;
} }
// Subclasses will override // Subclasses will override

View file

@ -48,8 +48,6 @@ import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyDao; import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao; import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditSubmission;
import edu.cornell.mannlib.vitro.webapp.filestorage.model.FileInfo; import edu.cornell.mannlib.vitro.webapp.filestorage.model.FileInfo;
import edu.cornell.mannlib.vitro.webapp.reasoner.SimpleReasoner; import edu.cornell.mannlib.vitro.webapp.reasoner.SimpleReasoner;
import edu.cornell.mannlib.vitro.webapp.utils.NamespaceMapper; import edu.cornell.mannlib.vitro.webapp.utils.NamespaceMapper;
@ -144,11 +142,8 @@ public class IndividualController extends FreemarkerHttpServlet {
} }
private void cleanUpSession(VitroRequest vreq) { private void cleanUpSession(VitroRequest vreq) {
// Session cleanup: any time we are at an entity page we shouldn't have an editing config or submission // We should not remove edit configurations from the session because the user
HttpSession session = vreq.getSession(); // may resubmit the forms via the back button and the system is setup to handle this.
session.removeAttribute("editjson");
EditConfiguration.clearAllConfigsInSession(session);
EditSubmission.clearAllEditSubmissionsInSession(session);
} }
private Map<String, Object> getVerbosePropertyValues(VitroRequest vreq) { private Map<String, Object> getVerbosePropertyValues(VitroRequest vreq) {

View file

@ -188,7 +188,7 @@ public class IndividualListController extends FreemarkerHttpServlet {
try{ try{
docs = index.search(query, null, docs = index.search(query, null,
ENTITY_LIST_CONTROLLER_MAX_RESULTS, ENTITY_LIST_CONTROLLER_MAX_RESULTS,
new Sort(Entity2LuceneDoc.term.NAMELOWERCASE)); new Sort(Entity2LuceneDoc.term.NAME_LOWERCASE));
}catch(Throwable th){ }catch(Throwable th){
log.error("Could not run search. " + th.getMessage()); log.error("Could not run search. " + th.getMessage());
docs = null; docs = null;
@ -258,7 +258,7 @@ public class IndividualListController extends FreemarkerHttpServlet {
Query alphaQuery = null; Query alphaQuery = null;
if( alpha != null && !"".equals(alpha) && alpha.length() == 1){ if( alpha != null && !"".equals(alpha) && alpha.length() == 1){
alphaQuery = alphaQuery =
new PrefixQuery(new Term(Entity2LuceneDoc.term.NAMELOWERCASE, alpha.toLowerCase())); new PrefixQuery(new Term(Entity2LuceneDoc.term.NAME_LOWERCASE, alpha.toLowerCase()));
query.add(alphaQuery,BooleanClause.Occur.MUST); query.add(alphaQuery,BooleanClause.Occur.MUST);
} }

View file

@ -11,8 +11,8 @@ import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ExceptionResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ExceptionResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditSubmission; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
import freemarker.template.ObjectWrapper; import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateModelException; import freemarker.template.TemplateModelException;

View file

@ -13,7 +13,6 @@ import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.TemplateResponseValues;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration;
/** /**
* Freemarker controller and template samples. * Freemarker controller and template samples.

View file

@ -2,11 +2,10 @@
package edu.cornell.mannlib.vitro.webapp.dao; package edu.cornell.mannlib.vitro.webapp.dao;
import edu.cornell.mannlib.vitro.webapp.beans.BaseResourceBean.RoleLevel; import java.util.List;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup; import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import java.util.List;
public interface VClassDao { public interface VClassDao {

View file

@ -193,6 +193,7 @@ public class VitroVocabulary {
public static final String USERACCOUNT_STATUS = VITRO_AUTH + "status"; public static final String USERACCOUNT_STATUS = VITRO_AUTH + "status";
public static final String USERACCOUNT_PASSWORD_LINK_EXPIRES = VITRO_AUTH + "passwordLinkExpires"; public static final String USERACCOUNT_PASSWORD_LINK_EXPIRES = VITRO_AUTH + "passwordLinkExpires";
public static final String USERACCOUNT_PASSWORD_CHANGE_REQUIRED = VITRO_AUTH + "passwordChangeRequired"; public static final String USERACCOUNT_PASSWORD_CHANGE_REQUIRED = VITRO_AUTH + "passwordChangeRequired";
public static final String USERACCOUNT_EXTERNAL_AUTH_ID = VITRO_AUTH + "externalAuthId";
public static final String USERACCOUNT_HAS_PERMISSION_SET = VITRO_AUTH + "hasPermissionSet"; public static final String USERACCOUNT_HAS_PERMISSION_SET = VITRO_AUTH + "hasPermissionSet";
public static final String PERMISSIONSET = VITRO_AUTH + "PermissionSet"; public static final String PERMISSIONSET = VITRO_AUTH + "PermissionSet";

View file

@ -118,8 +118,6 @@ public interface WebappDaoFactory {
public LinksDao getLinksDao(); public LinksDao getLinksDao();
public LinktypeDao getLinktypeDao(); public LinktypeDao getLinktypeDao();
public FlagDao getFlagDao();
// TODO This goes away when the UserAccounts stuff is fully implemented - jblake. // TODO This goes away when the UserAccounts stuff is fully implemented - jblake.
public UserDao getUserDao(); public UserDao getUserDao();

View file

@ -179,10 +179,6 @@ public class WebappDaoFactoryFiltering implements WebappDaoFactory {
return innerWebappDaoFactory.getUserURI(); return innerWebappDaoFactory.getUserURI();
} }
public FlagDao getFlagDao() {
return innerWebappDaoFactory.getFlagDao();
}
public KeywordIndividualRelationDao getKeys2EntsDao() { public KeywordIndividualRelationDao getKeys2EntsDao() {
return innerWebappDaoFactory.getKeys2EntsDao(); return innerWebappDaoFactory.getKeys2EntsDao();
} }

View file

@ -29,12 +29,12 @@ public class ApplicationDaoJena extends JenaBaseDao implements ApplicationDao {
Integer portalCount = null; Integer portalCount = null;
List<String> externallyLinkedNamespaces = null; List<String> externallyLinkedNamespaces = null;
ModelChangedListener modelChangedListener = null; ModelChangedListener externalNamespaceChangeListener = null;
public ApplicationDaoJena(WebappDaoFactoryJena wadf) { public ApplicationDaoJena(WebappDaoFactoryJena wadf) {
super(wadf); super(wadf);
modelChangedListener = new ExternalNamespacesChangeListener(); externalNamespaceChangeListener = new ExternalNamespacesChangeListener();
getOntModelSelector().getDisplayModel().register(modelChangedListener); getOntModelSelector().getDisplayModel().register(externalNamespaceChangeListener);
} }
private String getApplicationResourceURI() { private String getApplicationResourceURI() {
@ -117,18 +117,19 @@ public class ApplicationDaoJena extends JenaBaseDao implements ApplicationDao {
} }
public void close() { public void close() {
if (modelChangedListener != null) { if (externalNamespaceChangeListener != null) {
getOntModelSelector().getDisplayModel().unregister(modelChangedListener); getOntModelSelector().getDisplayModel().unregister(externalNamespaceChangeListener);
} }
} }
private static final boolean CLEAR_CACHE = true; private static final boolean CLEAR_CACHE = true;
@Override
public synchronized List<String> getExternallyLinkedNamespaces() { public synchronized List<String> getExternallyLinkedNamespaces() {
return getExternallyLinkedNamespaces(!CLEAR_CACHE); return getExternallyLinkedNamespaces(!CLEAR_CACHE);
} }
public synchronized List<String> getExternallyLinkedNamespaces(boolean clearCache) { private synchronized List<String> getExternallyLinkedNamespaces(boolean clearCache) {
if (clearCache || externallyLinkedNamespaces == null) { if (clearCache || externallyLinkedNamespaces == null) {
externallyLinkedNamespaces = new ArrayList<String>(); externallyLinkedNamespaces = new ArrayList<String>();
OntModel ontModel = getOntModelSelector().getDisplayModel(); OntModel ontModel = getOntModelSelector().getDisplayModel();

View file

@ -1,13 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import com.hp.hpl.jena.rdf.model.Statement;
public interface ExternalTripleStoreInterface {
public abstract void addToExternalStore(Statement stmt) throws TripleStoreUnavailableException;
public abstract void removeFromExternalStore(Statement stmt) throws TripleStoreUnavailableException;
}

View file

@ -1,36 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import java.util.HashSet;
import java.util.List;
import com.hp.hpl.jena.ontology.OntModel;
import edu.cornell.mannlib.vitro.webapp.dao.FlagDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
public class FlagDaoJena extends JenaBaseDao implements FlagDao {
public FlagDaoJena(WebappDaoFactoryJena wadf) {
super(wadf);
}
public String convertNumericFlagToInsertString(int numeric, String column,
String table) {
// TODO Auto-generated method stub
return null;
}
public String convertNumericFlagToInsertString(int numeric,
String flagColumns) {
// TODO Auto-generated method stub
return null;
}
public String getFlagNames(String table, String field) {
// TODO Auto-generated method stub
return null;
}
}

View file

@ -167,6 +167,7 @@ public class JenaBaseDaoCon {
protected DatatypeProperty USERACCOUNT_STATUS = _constModel.createDatatypeProperty(VitroVocabulary.USERACCOUNT_STATUS); protected DatatypeProperty USERACCOUNT_STATUS = _constModel.createDatatypeProperty(VitroVocabulary.USERACCOUNT_STATUS);
protected DatatypeProperty USERACCOUNT_PASSWORD_LINK_EXPIRES = _constModel.createDatatypeProperty(VitroVocabulary.USERACCOUNT_PASSWORD_LINK_EXPIRES); protected DatatypeProperty USERACCOUNT_PASSWORD_LINK_EXPIRES = _constModel.createDatatypeProperty(VitroVocabulary.USERACCOUNT_PASSWORD_LINK_EXPIRES);
protected DatatypeProperty USERACCOUNT_PASSWORD_CHANGE_REQUIRED = _constModel.createDatatypeProperty(VitroVocabulary.USERACCOUNT_PASSWORD_CHANGE_REQUIRED); protected DatatypeProperty USERACCOUNT_PASSWORD_CHANGE_REQUIRED = _constModel.createDatatypeProperty(VitroVocabulary.USERACCOUNT_PASSWORD_CHANGE_REQUIRED);
protected DatatypeProperty USERACCOUNT_EXTERNAL_AUTH_ID = _constModel.createDatatypeProperty(VitroVocabulary.USERACCOUNT_EXTERNAL_AUTH_ID);
protected ObjectProperty USERACCOUNT_HAS_PERMISSION_SET = _constModel.createObjectProperty(VitroVocabulary.USERACCOUNT_HAS_PERMISSION_SET); protected ObjectProperty USERACCOUNT_HAS_PERMISSION_SET = _constModel.createObjectProperty(VitroVocabulary.USERACCOUNT_HAS_PERMISSION_SET);
protected OntClass PERMISSIONSET = _constModel.createClass(VitroVocabulary.PERMISSIONSET); protected OntClass PERMISSIONSET = _constModel.createClass(VitroVocabulary.PERMISSIONSET);

View file

@ -1,108 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
//import org.openrdf.repository.Repository;
//import org.openrdf.repository.RepositoryConnection;
//import org.openrdf.repository.RepositoryResult;
//import org.openrdf.repository.http.HTTPRepository;
//import org.openrdf.repository.sail.SailRepository;
//import org.openrdf.rio.RDFFormat;
//import org.openrdf.sail.memory.MemoryStore;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.listeners.StatementListener;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
public class JenaToExternalTripleStoreSynchronizer extends StatementListener implements ServletContextListener {
private ExternalTripleStoreInterface extStore;
public JenaToExternalTripleStoreSynchronizer(ExternalTripleStoreInterface extStore, Model additionsQueue, Model retractionsQueue) {
this.extStore = extStore;
}
private Model additionsQueue = ModelFactory.createDefaultModel();
private Model retractionsQueue = ModelFactory.createDefaultModel();
// TODO: add a statement filter to filter out password props
@Override
public void addedStatement(Statement stmt) {
if (!retractionsQueue.contains(stmt)) {
additionsQueue.add(stmt);
} else {
retractionsQueue.remove(stmt);
}
// try {
StmtIterator sit = retractionsQueue.listStatements();
while (sit.hasNext()) {
Statement s = sit.nextStatement();
}
// } catch (TripleStoreUnavailableException e) {
// // log something?
// }
}
@Override
public void removedStatement(Statement stmt) {
processUpdate(stmt, REMOVE);
}
public void processUpdate(Statement stmt, boolean mode) {
// Repository myRepository = new HTTPRepository(sesameServer, repositoryID);
// myRepository.initialize();
// RepositoryConnection myConn = myRepository.getConnection();
// System.out.println(myConn.size()+" statements in remote Sesame");
//
// Repository tempRepository = new SailRepository(new MemoryStore());
// tempRepository.initialize();
// tempRepository.getConnection().add(retractionsFile, null, RDFFormat.N3);
// System.out.println(tempRepository.getConnection().size()+" statements to retract");
// RepositoryResult<Statement> retractStmts = tempRepository.getConnection().getStatements(null, null, null, false);
// System.out.println("Retracting statements from repository...");
// //myConn.remove(retractStmts);
// while (retractStmts.hasNext()) {
// Statement stmt = retractStmts.next();
// myConn.remove(stmt.getSubject(), stmt.getPredicate(), null);
// }
}
public static final boolean ADD = true;
public static final boolean REMOVE = false;
public static final int SESAME_SERVER_URI = 0;
public static final int SESAME_REPOSITORY_NAME = 1;
public List<String[]> getSesameRepositories() {
List<String[]> sesameRepositoryList = new ArrayList<String[]>();
String[] testRepository = new String[2];
testRepository[SESAME_SERVER_URI] = "http://vivosesame.mannlib.cornell.edu:8080/openrdf-sesame";
testRepository[SESAME_REPOSITORY_NAME] = "syncTest";
sesameRepositoryList.add(testRepository);
return sesameRepositoryList;
}
public void contextInitialized(ServletContextEvent sce) {
OntModel jenaOntModel = (OntModel) sce.getServletContext().getAttribute(JenaBaseDao.JENA_ONT_MODEL_ATTRIBUTE_NAME);
jenaOntModel.getBaseModel().register(this);
}
public void contextDestroyed(ServletContextEvent sce) {
}
}

View file

@ -61,6 +61,8 @@ public class UserAccountsDaoJena extends JenaBaseDao implements UserAccountsDao
USERACCOUNT_PASSWORD_CHANGE_REQUIRED)); USERACCOUNT_PASSWORD_CHANGE_REQUIRED));
u.setLoginCount(getPropertyIntValue(r, USERACCOUNT_LOGIN_COUNT)); u.setLoginCount(getPropertyIntValue(r, USERACCOUNT_LOGIN_COUNT));
u.setStatusFromString(getPropertyStringValue(r, USERACCOUNT_STATUS)); u.setStatusFromString(getPropertyStringValue(r, USERACCOUNT_STATUS));
u.setExternalAuthId(getPropertyStringValue(r,
USERACCOUNT_EXTERNAL_AUTH_ID));
u.setPermissionSetUris(getPropertyResourceURIValues(r, u.setPermissionSetUris(getPropertyResourceURIValues(r,
USERACCOUNT_HAS_PERMISSION_SET)); USERACCOUNT_HAS_PERMISSION_SET));
return u; return u;
@ -105,6 +107,8 @@ public class UserAccountsDaoJena extends JenaBaseDao implements UserAccountsDao
addPropertyStringValue(res, USERACCOUNT_STATUS, userAccount addPropertyStringValue(res, USERACCOUNT_STATUS, userAccount
.getStatus().toString(), model); .getStatus().toString(), model);
} }
addPropertyStringValue(res, USERACCOUNT_EXTERNAL_AUTH_ID,
userAccount.getExternalAuthId(), model);
updatePropertyResourceURIValues(res, updatePropertyResourceURIValues(res,
USERACCOUNT_HAS_PERMISSION_SET, USERACCOUNT_HAS_PERMISSION_SET,
userAccount.getPermissionSetUris(), model); userAccount.getPermissionSetUris(), model);
@ -158,6 +162,8 @@ public class UserAccountsDaoJena extends JenaBaseDao implements UserAccountsDao
updatePropertyStringValue(res, USERACCOUNT_STATUS, userAccount updatePropertyStringValue(res, USERACCOUNT_STATUS, userAccount
.getStatus().toString(), model); .getStatus().toString(), model);
} }
updatePropertyStringValue(res, USERACCOUNT_EXTERNAL_AUTH_ID,
userAccount.getExternalAuthId(), model);
updatePropertyResourceURIValues(res, updatePropertyResourceURIValues(res,
USERACCOUNT_HAS_PERMISSION_SET, USERACCOUNT_HAS_PERMISSION_SET,
userAccount.getPermissionSetUris(), model); userAccount.getPermissionSetUris(), model);

View file

@ -444,13 +444,6 @@ public class WebappDaoFactoryJena implements WebappDaoFactory {
return entityWebappDao = new IndividualDaoJena(this); return entityWebappDao = new IndividualDaoJena(this);
} }
public FlagDao getFlagDao() {
if (flagDao != null)
return flagDao;
else
return flagDao = new FlagDaoJena(this);
}
public KeywordIndividualRelationDao getKeys2EntsDao() { public KeywordIndividualRelationDao getKeys2EntsDao() {
if (keys2EntsDao != null) if (keys2EntsDao != null)
return keys2EntsDao; return keys2EntsDao;

View file

@ -9,7 +9,7 @@ import java.util.Map;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.Field; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import freemarker.template.Configuration; import freemarker.template.Configuration;
import freemarker.template.Template; import freemarker.template.Template;
import freemarker.template.TemplateException; import freemarker.template.TemplateException;

View file

@ -25,9 +25,9 @@ import com.hp.hpl.jena.rdf.model.ResourceFactory;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerHttpServlet;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditSubmission; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.Field; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
import freemarker.template.Configuration; import freemarker.template.Configuration;
/** /**

View file

@ -6,8 +6,8 @@ import java.util.Map;
import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditSubmission; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
import freemarker.template.Configuration; import freemarker.template.Configuration;
/** /**
* All classes that implement this interface must have a public constructor that * All classes that implement this interface must have a public constructor that

View file

@ -19,7 +19,7 @@ import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatementImpl;
import edu.cornell.mannlib.vitro.webapp.beans.Individual; import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao; import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyStatementDao; import edu.cornell.mannlib.vitro.webapp.dao.DataPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.BasicValidation; import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.BasicValidation;
public class IndividualDataPropertyStatementProcessor implements ChangeListener { public class IndividualDataPropertyStatementProcessor implements ChangeListener {

View file

@ -1,9 +0,0 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing;
import java.util.Map;
public interface N3Validator {
public Map<String,String> validate(EditConfiguration editConfig, EditSubmission editSub);
}

View file

@ -1,6 +1,6 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing; package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
@ -28,11 +28,15 @@ import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.rdf.model.ResourceFactory;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.IdentifierBundle;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.RequestIdentifiers;
import edu.cornell.mannlib.vitro.webapp.auth.identifier.UserToIndIdentifierFactory;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement; import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral; import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.EditSubmissionPreprocessor;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.ModelChangePreprocessor;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.N3Validator;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Generator;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditN3Utils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.SparqlEvaluate;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch; import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
/** /**
@ -256,22 +260,9 @@ public class EditConfiguration {
throw new Error("EditConfiguration.addSystemValues() needs a session"); throw new Error("EditConfiguration.addSystemValues() needs a session");
/* ********** Get URI of a logged in user ************** */ /* ********** Get URI of a logged in user ************** */
IdentifierBundle ids = RequestIdentifiers.getIdBundleForRequest(request); String userUri = EditN3Utils.getEditorUri(request);
List<String> userUris = log.debug("EditConfiguration.java - checking system value for User URI " + userUri);
UserToIndIdentifierFactory.getIndividualsForUser(ids); getUrisInScope().put("editingUser", userUri);
if( userUris == null || userUris.size() == 0 ){
log.debug("Cound not find user ur for edit request");
log.error("Could not find a userUri for edit request, make " +
"sure that there is an IdentifierBundleFactory that " +
"produces userUri identifiers in the context.");
} else if( userUris.size() > 1 ){
log.error("Found multiple userUris, using the first in list.");
log.debug("Found multiple user uris");
}else {
log.debug("EditConfiguration.java - checking system value for User URI " + userUris.get(0));
getUrisInScope().put("editingUser",userUris.get(0));
}
} }
} }

View file

@ -1,6 +1,6 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing; package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;

View file

@ -1,6 +1,6 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing; package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;

View file

@ -1,6 +1,6 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing; package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@ -187,8 +187,8 @@ public class SelectListGenerator {
for( Individual ind : individuals ){ for( Individual ind : individuals ){
String uri = ind.getURI(); String uri = ind.getURI();
if( uri != null ){ if( uri != null ){
optionsMap.put(uri,ind.getName().trim()); optionsMap.put(uri,ind.getName().trim());
++optionsCount; ++optionsCount;
} }
} }
@ -212,13 +212,13 @@ public class SelectListGenerator {
// individuals asserted in subclasses // individuals asserted in subclasses
boolean inferenceAvailable = false; boolean inferenceAvailable = false;
if (wDaoFact instanceof WebappDaoFactoryJena) { if (wDaoFact instanceof WebappDaoFactoryJena) {
PelletListener pl = ((WebappDaoFactoryJena) wDaoFact) PelletListener pl = ((WebappDaoFactoryJena) wDaoFact)
.getPelletListener(); .getPelletListener();
if (pl != null && pl.isConsistent() if (pl != null && pl.isConsistent()
&& !pl.isInErrorState() && !pl.isInErrorState()
&& !pl.isReasoning()) { && !pl.isReasoning()) {
inferenceAvailable = true; inferenceAvailable = true;
} }
} }
VClass vclass = wDaoFact.getVClassDao().getVClassByURI( vclassUri ); VClass vclass = wDaoFact.getVClassDao().getVClassByURI( vclassUri );
@ -227,41 +227,41 @@ public class SelectListGenerator {
optionsMap.put("", "Could not find class " + vclassUri); optionsMap.put("", "Could not find class " + vclassUri);
}else{ }else{
Map<String, Individual> individualMap = new HashMap<String, Individual>(); Map<String, Individual> individualMap = new HashMap<String, Individual>();
for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(vclass.getURI(),-1,-1)) { for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(vclass.getURI(),-1,-1)) {
if (ind.getURI() != null) { if (ind.getURI() != null) {
individualMap.put(ind.getURI(), ind); individualMap.put(ind.getURI(), ind);
} }
} }
if (!inferenceAvailable) { if (!inferenceAvailable) {
for (String subclassURI : wDaoFact.getVClassDao().getAllSubClassURIs(vclass.getURI())) { for (String subclassURI : wDaoFact.getVClassDao().getAllSubClassURIs(vclass.getURI())) {
for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(subclassURI,-1,-1)) { for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(subclassURI,-1,-1)) {
if (ind.getURI() != null) { if (ind.getURI() != null) {
individualMap.put(ind.getURI(), ind); individualMap.put(ind.getURI(), ind);
} }
} }
} }
} }
List<Individual> individuals = new ArrayList<Individual>(); List<Individual> individuals = new ArrayList<Individual>();
individuals.addAll(individualMap.values()); individuals.addAll(individualMap.values());
Collections.sort(individuals); Collections.sort(individuals);
for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(vclass.getURI(),-1,-1)) { for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(vclass.getURI(),-1,-1)) {
if (ind.getURI() != null) { if (ind.getURI() != null) {
individualMap.put(ind.getURI(), ind); individualMap.put(ind.getURI(), ind);
} }
} }
if (!inferenceAvailable) { if (!inferenceAvailable) {
for (String subclassURI : wDaoFact.getVClassDao().getAllSubClassURIs(vclass.getURI())) { for (String subclassURI : wDaoFact.getVClassDao().getAllSubClassURIs(vclass.getURI())) {
for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(subclassURI,-1,-1)) { for (Individual ind : wDaoFact.getIndividualDao().getIndividualsByVClassURI(subclassURI,-1,-1)) {
if (ind.getURI() != null) { if (ind.getURI() != null) {
individualMap.put(ind.getURI(), ind); individualMap.put(ind.getURI(), ind);
} }
} }
} }
} }
individuals.addAll(individualMap.values()); individuals.addAll(individualMap.values());
@ -274,8 +274,8 @@ public class SelectListGenerator {
for( Individual ind : individuals ) { for( Individual ind : individuals ) {
String uri = ind.getURI(); String uri = ind.getURI();
if( uri != null ) { if( uri != null ) {
optionsMap.put(uri,ind.getName().trim()); optionsMap.put(uri,ind.getName().trim());
++optionsCount; ++optionsCount;
} }
} }
} }

View file

@ -1,6 +1,6 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing; package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;

View file

@ -1,6 +1,6 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing; package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;

View file

@ -1,6 +1,6 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing; package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;

View file

@ -0,0 +1,23 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import javax.servlet.http.HttpSession;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
/**
* Generates the edit configuration for a default property form.
*
*/
public class DefaultPropertyFormGenerator implements EditConfigurationGenerator {
@Override
public EditConfiguration getEditConfiguration(VitroRequest vreq,
HttpSession session) {
// TODO Generate a edit conf for the default object property form and return it.
return null;
}
}

View file

@ -0,0 +1,12 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import javax.servlet.http.HttpSession;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
public interface EditConfigurationGenerator {
public EditConfiguration getEditConfiguration( VitroRequest vreq, HttpSession session );
}

View file

@ -1,6 +1,9 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing; package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
public abstract class BaseEditSubmissionPreprocessor implements public abstract class BaseEditSubmissionPreprocessor implements
EditSubmissionPreprocessor { EditSubmissionPreprocessor {

View file

@ -1,6 +1,6 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing; package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors;
import java.util.Map; import java.util.Map;
@ -11,6 +11,10 @@ import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.vocabulary.XSD; import com.hp.hpl.jena.vocabulary.XSD;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.Field;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.processEdit.EditSubmission;
public class CreateLabelFromNameFields extends BaseEditSubmissionPreprocessor { public class CreateLabelFromNameFields extends BaseEditSubmissionPreprocessor {
private static final Log log = LogFactory.getLog(CreateLabelFromNameFields.class.getName()); private static final Log log = LogFactory.getLog(CreateLabelFromNameFields.class.getName());

View file

@ -1,9 +1,12 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ /* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing; package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors;
import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.rdf.model.ResourceFactory;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
/** /**

Some files were not shown because too many files have changed in this diff Show more